coze-bridge 0.1.86 → 0.1.88

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 +46 -42
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,17 +5,17 @@ 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 $p=Object.create;var go=Object.defineProperty;var Gp=Object.getOwnPropertyDescriptor;var Hp=Object.getOwnPropertyNames;var jp=Object.getPrototypeOf,Wp=Object.prototype.hasOwnProperty;var $=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ie=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),gi=(t,e)=>{for(var r in e)go(t,r,{get:e[r],enumerable:!0})},qp=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Hp(e))!Wp.call(t,i)&&i!==r&&go(t,i,{get:()=>e[i],enumerable:!(n=Gp(e,i))||n.enumerable});return t};var ct=(t,e,r)=>(r=t!=null?$p(jp(t)):{},qp(e||!t||!t.__esModule?go(r,"default",{value:t,enumerable:!0}):r,t));function nl(t){mo=t}function il(t){return wi[mo]<=wi[t]}function _i(t){rl={...t}}function Zp(t){let e=(a,c=2)=>String(a).padStart(c,"0"),r=-t.getTimezoneOffset(),n=r>=0?"+":"-",i=Math.abs(r),s=e(Math.floor(i/60)),o=e(i%60);return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${n}${s}:${o}`}function mi(t,e,r,n){if(wi[t]<wi[mo])return;let i=JSON.stringify({ts:Zp(new Date),level:t,module:e,msg:r,...rl,...n});t==="error"||t==="warn"?Vp.write(`${i}
9
- `):Jp.write(`${i}
10
- `)}function O(t){return{debug:(e,r)=>mi("debug",t,e,r),info:(e,r)=>mi("info",t,e,r),warn:(e,r)=>mi("warn",t,e,r),error:(e,r)=>mi("error",t,e,r),child:e=>O(`${t}.${e}`)}}var wi,mo,Jp,Vp,rl,F=Ie(()=>{"use strict";wi={debug:10,info:20,warn:30,error:40},mo=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Jp=process.stdout,Vp=process.stderr,rl={}});import{execFile as Kp,spawn as Xp,spawnSync as lv}from"node:child_process";import{promisify as Qp}from"node:util";function eg(t){if(process.platform!=="win32")return!1;if(sl.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(sl,"").toLowerCase();return Yp.has(r)}function ol(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return eg(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function It(t,e=[],r={}){return Xp(t,e,ol(t,r))}function yi(t,e=[],r={}){return tg(t,e,ol(t,r))}var Yp,sl,tg,mr=Ie(()=>{"use strict";Yp=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp"]),sl=/\.(cmd|bat|ps1)$/i;tg=Qp(Kp)});var y,ye=Ie(()=>{"use strict";y=class extends Error{code;retriable;cause;constructor(e,r,n){super(r),this.name="BridgeError",this.code=e,this.retriable=n?.retriable??!1,n?.cause!==void 0&&(this.cause=n.cause)}}});var fl={};gi(fl,{_resetAcpInstallerForTests:()=>hg,_resetInstallTimeoutsForTests:()=>lg,_setBinaryPathCacheForTests:()=>ug,_setInFlightForTests:()=>fg,_setInstallTimeoutsForTests:()=>cg,buildInstallFailureMessage:()=>hl,ensureAcpInstalled:()=>yr,formatExecError:()=>ll,getAcpBinaryPath:()=>ln,getAcpPackageSpec:()=>og,getInFlightInstall:()=>yo,npmInstallGlobal:()=>dl,pickWhichLine:()=>Ii,probeAcpVersion:()=>dg,resolveAcpCommand:()=>dn});import{readFile as rg,realpath as ng,stat as ig}from"node:fs/promises";import{dirname as wo,join as sg}from"node:path";function og(t){let e=_o[t];if(e)return`${e.npmPackage}@${e.versionSpec}`}function cg(t,e){Ei=t,Si=e}function lg(){Ei=5e4,Si=5e3}function ll(t){if(t==null||typeof t!="object")return String(t);let e=t,r=[];e.message&&r.push(e.message),e.code!==void 0&&e.code!==null&&r.push(`code=${e.code}`),e.signal&&r.push(`signal=${e.signal}`);let n=e.stderr?.toString().trim();n&&r.push(`stderr=${n.slice(0,2e3)}`);let i=e.stdout?.toString().trim();return i&&r.push(`stdout=${i.slice(0,2e3)}`),r.length>0?r.join(" | "):String(t)}async function al(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await yi(e,[t],{timeout:ag});return Ii(r)}catch{return}}function Ii(t){let e=t.split(/\r?\n/).map(n=>n.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=n=>e.find(i=>i.toLowerCase().endsWith(n));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}async function dg(t){let e=_o[t];if(!e)return;let r=ln(t);if(!r){me.warn("acp wrapper probe: binary path cache empty",{framework:t,binary:e.binary,hint:"ensureAcpInstalled \u6CA1\u8DD1\u8FC7 / \u88C5\u5931\u8D25 / \u4E4B\u524D negative cache 5min \u5185"});return}let n;try{n=await ng(r)}catch(s){me.warn("acp wrapper probe: realpath failed (symlink target \u4E0D\u5B58\u5728?)",{framework:t,binaryPath:r,err:String(s)});return}let i=wo(n);for(let s=0;s<cl;s++){let o=sg(i,"package.json");try{if(!(await ig(o)).isFile()){i=wo(i);continue}let l=await rg(o,"utf8"),d=JSON.parse(l);if(d.name===e.npmPackage){if(typeof d.version=="string"&&d.version.length>0)return d.version;me.warn("acp wrapper probe: package.json \u627E\u5230\u4F46 version \u5B57\u6BB5\u7F3A",{framework:t,packageJsonPath:o});return}}catch(c){let l=c;l.code!=="ENOENT"&&me.warn("acp wrapper probe: package.json \u8BFB\u53D6\u5F02\u5E38",{framework:t,candidate:o,errCode:l?.code,err:String(c)})}let a=wo(i);if(a===i)break;i=a}me.warn("acp wrapper probe: \u627E\u4E0D\u5230\u5339\u914D name \u7684 package.json (\u4E0A\u6EAF\u5230 max depth)",{framework:t,binaryPath:r,realBinary:n,expectedName:e.npmPackage,maxDepth:cl})}async function dl(t,e,r){let n=`${t}@${e}`;me.info("npm install -g start",{npmPackage:t,versionSpec:e});let i=Date.now(),s=process.platform==="win32";return new Promise((o,a)=>{let c=It("npm",["install","-g",n],{stdio:["ignore","pipe","pipe"],...s?{}:{detached:!0}});if(!c.pid){a(new Error(`failed to spawn npm: no pid (npmPackage=${t})`));return}let l=c.pid,d=10*1024*1024,p=[],m=[],f=0,u=0;c.stdout?.on("data",_=>{f+=_.length,f<d&&p.push(_)}),c.stderr?.on("data",_=>{u+=_.length,u<d&&m.push(_)});let g="running",w,E=_=>{try{return s?c.kill(_):process.kill(-l,_),!0}catch(S){return me.warn("npm install: kill failed (process already dead?)",{npmPackage:t,pid:l,sig:_,err:String(S)}),!1}},v=setTimeout(()=>{g="terminating",me.warn("npm install timeout, sending SIGTERM to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,timeoutMs:Ei,graceMs:Si,stdoutBytes:f,stderrBytes:u}),E("SIGTERM"),w=setTimeout(()=>{g="killing",me.warn("npm install SIGTERM grace expired, escalating to SIGKILL",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,stdoutBytes:f,stderrBytes:u}),E("SIGKILL")},Si)},Ei),h=()=>{g="aborted",me.warn("npm install externally aborted, sending SIGKILL to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i}),E("SIGKILL")};r&&(r.aborted?h():r.addEventListener("abort",h,{once:!0})),c.on("error",_=>{clearTimeout(v),w&&clearTimeout(w),r?.removeEventListener("abort",h),me.warn("npm install spawn error",{npmPackage:t,versionSpec:e,pid:l,err:String(_)}),a(new Error(`spawn npm failed: ${String(_)}`))}),c.on("close",(_,S)=>{clearTimeout(v),w&&clearTimeout(w),r?.removeEventListener("abort",h);let k=Buffer.concat(p).toString("utf8"),R=Buffer.concat(m).toString("utf8"),I=Date.now()-i;if(_===0&&g==="running"){me.info("npm install -g done",{npmPackage:t,versionSpec:e,elapsedMs:I}),o();return}me.warn("npm install -g exited non-success",{npmPackage:t,versionSpec:e,pid:l,phase:g,exitCode:_,signal:S,elapsedMs:I,stdoutBytes:f,stderrBytes:u});let T=Object.assign(new Error(`Command failed: npm install -g ${n}`+(S?` (killed by ${S})`:"")+(_!==null?` (exit ${_})`:"")+(g!=="running"?` (phase=${g})`:"")),{code:_,signal:S,stderr:R,stdout:k});a(T)})})}function hl(t){let{framework:e,npmPackage:r,versionSpec:n,command:i,reason:s,elapsedMs:o}=t;return["ACP wrapper \u5B89\u88C5\u5931\u8D25",`Framework: ${e}`,`Package: ${r}@${n}`,`\u6267\u884C\u547D\u4EE4: ${i}`,`\u5931\u8D25\u539F\u56E0: ${s}`,`\u8017\u65F6: ${o}ms`,"","\u6392\u67E5\u5EFA\u8BAE:"," 1. \u68C0\u67E5\u7F51\u7EDC: curl -v https://registry.npmjs.org"," 2. \u67E5\u770B\u5F53\u524D npm \u6E90: npm config get registry"," 3. \u56FD\u5185\u7F51\u7EDC\u5EFA\u8BAE\u5207\u955C\u50CF\u6E90:"," npm config set registry https://registry.npmmirror.com/"].join(`
11
- `)}async function yr(t,e){let r=_o[t];if(!r)throw new y("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let n=wr.get(t);if(n)return n;let i=_r.get(t);if(i)return i;let s=`npm install -g ${r.npmPackage}@${r.versionSpec}`,o=(c,l,d)=>new y("AGENT_DEPENDENCY_INSTALL_FAILED",hl({framework:t,npmPackage:r.npmPackage,versionSpec:r.versionSpec,command:s,reason:c,elapsedMs:l}),d!==void 0?{cause:d}:{}),a=(async()=>{let c=await al(r.binary);if(c)return wr.set(t,c),me.info("acp wrapper found on PATH",{binary:r.binary,path:c}),c;let l=Date.now();try{await dl(r.npmPackage,r.versionSpec,e)}catch(p){let m=ll(p);throw me.warn("acp wrapper install failed",{framework:t,npmPackage:r.npmPackage,versionSpec:r.versionSpec,binary:r.binary,err:m}),o(m,Date.now()-l,p)}let d=await al(r.binary);if(!d)throw me.warn("acp wrapper installed but binary not found on PATH",{framework:t,npmPackage:r.npmPackage,versionSpec:r.versionSpec,binary:r.binary}),o(`npm install \u6210\u529F\u4F46 \`${process.platform==="win32"?"where":"which"} ${r.binary}\` \u627E\u4E0D\u5230 binary (npm prefix \u53EF\u80FD\u672A\u52A0\u5165 PATH, \u6216\u88AB\u88C5\u5230\u4E86 nvm/asdf \u522B\u7684\u7248\u672C\u4E0B)`,Date.now()-l);return wr.set(t,d),d})().finally(()=>{_r.delete(t)});return _r.set(t,a),a}function ln(t){return wr.get(t)}function dn(t,e){if(e)return e;let r=ln(t);if(!r)throw new y("BRIDGE_INTERNAL",`${t} ACP wrapper binary path cache miss (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function yo(t){return _r.get(t)}function hg(){wr.clear(),_r.clear()}function fg(t,e){_r.set(t,e)}function ug(t,e){wr.set(t,e)}var me,_o,Ei,Si,ag,wr,_r,cl,Wt=Ie(()=>{"use strict";mr();ye();F();me=O("agents.acp-installer"),_o={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp",versionSpec:"^0.37"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp",versionSpec:"^0.15"}};Ei=5e4,Si=5e3,ag=5e3;wr=new Map,_r=new Map;cl=6});import{chmod as gg,mkdir as mg,readFile as wg,rename as gl,writeFile as ml}from"node:fs/promises";import{dirname as _g}from"node:path";async function Er(t){try{let e=await wg(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function vi(t,e,r){await mg(_g(t),{recursive:!0});let n=`${JSON.stringify(e,null,2)}
12
- `,i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{r?.mode!==void 0?await ml(i,n,{encoding:"utf8",mode:r.mode}):await ml(i,n,"utf8"),await gl(i,t),r?.mode!==void 0&&await gg(t,r.mode)}catch(s){await gl(i,i).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(i,{force:!0}).catch(()=>{}),s}}var Ti=Ie(()=>{"use strict"});import{promises as wl}from"node:fs";import{homedir as yg}from"node:os";import{sep as Eg,join as le,resolve as _l}from"node:path";function M(t){let e=t??yg(),r=le(e,".coze"),n=le(r,"bridge"),i=le(n,"lib");return{cozeRoot:r,bridgeRoot:n,libDir:i,libEntry:le(i,"index.js"),binDir:le(n,"bin"),pidFile:le(n,"bridge.pid"),portFile:le(n,"bridge.port"),tokenFile:le(n,"bridge.token"),patTokenFile:le(n,"pat-token"),logFile:le(n,"bridge.log"),installLock:le(n,"install.lock"),configFile:le(n,"config.json"),agentsRoot:le(r,"agents")}}function lt(t,e=M()){let r=le(e.agentsRoot,t);return{root:r,config:le(r,"config.json"),workspace:le(r,"workspace"),logs:le(r,"logs")}}async function hn(t,e){let r=await wl.realpath(_l(t)).catch(()=>null);if(!r)return!1;let n=await wl.realpath(_l(e)).catch(()=>null);if(!n)return!1;let i=process.platform==="win32"?r.toLowerCase():r,s=process.platform==="win32"?n.toLowerCase():n;return i===s||i.startsWith(s+Eg)}var de=Ie(()=>{"use strict"});var bi={};gi(bi,{AGENT_CONFIG_FILE_MODE:()=>Ri,enforceAgentConfigMode:()=>vg,loadAgentConfig:()=>he,persistAgentSessions:()=>fn,persistAgentSkills:()=>ki,saveAgentConfig:()=>ve});import{chmod as Sg,stat as Ig}from"node:fs/promises";function he(t,e){return Er(lt(t,e).config)}function ve(t,e){return vi(lt(t.agentId,e).config,t,{mode:Ri})}async function vg(t,e){if(process.platform==="win32")return;let r=lt(t,e).config;try{let n=await Ig(r);if(!n.isFile())return;let i=n.mode&511;i!==Ri&&(await Sg(r,Ri),yl.warn("agent config mode auto-corrected to 0600",{path:r,from:i.toString(8)}))}catch(n){if(n.code==="ENOENT")return;yl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(n)})}}async function fn(t,e,r){let n=await he(t,r);n&&(n.sessions=Object.fromEntries(e),await ve(n,r))}async function ki(t,e,r){let n=await he(t,r);n&&(n.skills=e,await ve(n,r))}var yl,Ri,vt=Ie(()=>{"use strict";Ti();F();de();yl=O("agent-config"),Ri=384});var So=z((zv,vl)=>{vl.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 Oi=z(Rl=>{var Tl={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 Ag(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Tl))Rl[t]=Ag(Tl[t])});var xl=z((Gv,Ol)=>{var Og=$("fs"),ee=$("path"),kl=So(),xg=Oi(),Pg=typeof process=="object"&&process.platform==="win32",bl=t=>typeof t=="object"&&t!==null,Al=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Z(t){this.sep=ee.sep,this.fs=Og,bl(t)&&bl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}Ol.exports=Z;Z.prototype.makeDir=function(t){let e=this;function r(n){let i=n.split(e.sep)[0];n.split(e.sep).forEach(function(s){if(!(!s||s.substr(-1,1)===":")){i+=e.sep+s;var o;try{o=e.fs.statSync(i)}catch(a){if(a.message&&a.message.startsWith("ENOENT"))e.fs.mkdirSync(i);else throw a}if(o&&o.isFile())throw xg.FILE_IN_THE_WAY(`"${i}"`)}})}r(t)};Z.prototype.writeFileTo=function(t,e,r,n){let i=this;if(i.fs.existsSync(t)){if(!r)return!1;var s=i.fs.statSync(t);if(s.isDirectory())return!1}var o=ee.dirname(t);i.fs.existsSync(o)||i.makeDir(o);var a;try{a=i.fs.openSync(t,"w",438)}catch{i.fs.chmodSync(t,438),a=i.fs.openSync(t,"w",438)}if(a)try{i.fs.writeSync(a,e,0,e.length,0)}finally{i.fs.closeSync(a)}return i.fs.chmodSync(t,n||438),!0};Z.prototype.writeFileToAsync=function(t,e,r,n,i){typeof n=="function"&&(i=n,n=void 0);let s=this;s.fs.exists(t,function(o){if(o&&!r)return i(!1);s.fs.stat(t,function(a,c){if(o&&c.isDirectory())return i(!1);var l=ee.dirname(t);s.fs.exists(l,function(d){d||s.makeDir(l),s.fs.open(t,"w",438,function(p,m){p?s.fs.chmod(t,438,function(){s.fs.open(t,"w",438,function(f,u){s.fs.write(u,e,0,e.length,0,function(){s.fs.close(u,function(){s.fs.chmod(t,n||438,function(){i(!0)})})})})}):m?s.fs.write(m,e,0,e.length,0,function(){s.fs.close(m,function(){s.fs.chmod(t,n||438,function(){i(!0)})})}):s.fs.chmod(t,n||438,function(){i(!0)})})})})})};Z.prototype.findFiles=function(t){let e=this;function r(n,i,s){typeof i=="boolean"&&(s=i,i=void 0);let o=[];return e.fs.readdirSync(n).forEach(function(a){let c=ee.join(n,a),l=e.fs.statSync(c);(!i||i.test(c))&&o.push(ee.normalize(c)+(l.isDirectory()?e.sep:"")),l.isDirectory()&&s&&(o=o.concat(r(c,i,s)))}),o}return r(t,void 0,!0)};Z.prototype.findFilesAsync=function(t,e){let r=this,n=[];r.fs.readdir(t,function(i,s){if(i)return e(i);let o=s.length;if(!o)return e(null,n);s.forEach(function(a){a=ee.join(t,a),r.fs.stat(a,function(c,l){if(c)return e(c);l&&(n.push(ee.normalize(a)+(l.isDirectory()?r.sep:"")),l.isDirectory()?r.findFilesAsync(a,function(d,p){if(d)return e(d);n=n.concat(p),--o||e(null,n)}):--o||e(null,n))})})})};Z.prototype.getAttributes=function(){};Z.prototype.setAttributes=function(){};Z.crc32update=function(t,e){return Al[(t^e)&255]^t>>>8};Z.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=Z.crc32update(r,t[n++]);return~r>>>0};Z.methodToString=function(t){switch(t){case kl.STORED:return"STORED ("+t+")";case kl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Z.canonical=function(t){if(!t)return"";let e=ee.posix.normalize("/"+t.split("\\").join("/"));return ee.join(".",e)};Z.zipnamefix=function(t){if(!t)return"";let e=ee.posix.normalize("/"+t.split("\\").join("/"));return ee.posix.join(".",e)};Z.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};Z.sanitize=function(t,e){t=ee.resolve(ee.normalize(t));for(var r=e.split("/"),n=0,i=r.length;n<i;n++){var s=ee.normalize(ee.join(t,r.slice(n,i).join(ee.sep)));if(s.indexOf(t)===0)return s}return ee.normalize(ee.join(t,ee.basename(e)))};Z.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Z.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Z.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)};Z.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Z.isWin=Pg;Z.crcTable=Al});var Cl=z((Hv,Pl)=>{var Cg=$("path");Pl.exports=function(t,{fs:e}){var r=t||"",n=s(),i=null;function s(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(i=e.statSync(r),n.directory=i.isDirectory(),n.mtime=i.mtime,n.atime=i.atime,n.executable=(73&i.mode)!==0,n.readonly=(128&i.mode)===0,n.hidden=Cg.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Nl=z((jv,Dl)=>{Dl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var vr=z((Wv,Ir)=>{Ir.exports=xl();Ir.exports.Constants=So();Ir.exports.Errors=Oi();Ir.exports.FileAttr=Cl();Ir.exports.decoder=Nl()});var Fl=z((qv,Ll)=>{var Tt=vr(),b=Tt.Constants;Ll.exports=function(){var t=20,e=10,r=0,n=0,i=0,s=0,o=0,a=0,c=0,l=0,d=0,p=0,m=0,f=0,u=0;t|=Tt.isWin?2560:768,r|=b.FLG_EFS;let g={extraLen:0},w=h=>Math.max(0,h)>>>0,E=h=>Math.max(0,h)&65535,v=h=>Math.max(0,h)&255;return i=Tt.fromDate2DOS(new Date),{get made(){return t},set made(h){t=h},get version(){return e},set version(h){e=h},get flags(){return r},set flags(h){r=h},get flags_efs(){return(r&b.FLG_EFS)>0},set flags_efs(h){h?r|=b.FLG_EFS:r&=~b.FLG_EFS},get flags_desc(){return(r&b.FLG_DESC)>0},set flags_desc(h){h?r|=b.FLG_DESC:r&=~b.FLG_DESC},get method(){return n},set method(h){switch(h){case b.STORED:this.version=10;case b.DEFLATED:default:this.version=20}n=h},get time(){return Tt.fromDOS2Date(this.timeval)},set time(h){h=new Date(h),this.timeval=Tt.fromDate2DOS(h)},get timeval(){return i},set timeval(h){i=w(h)},get timeHighByte(){return v(i>>>8)},get crc(){return s},set crc(h){s=w(h)},get compressedSize(){return o},set compressedSize(h){o=w(h)},get size(){return a},set size(h){a=w(h)},get fileNameLength(){return c},set fileNameLength(h){c=h},get extraLength(){return l},set extraLength(h){l=h},get extraLocalLength(){return g.extraLen},set extraLocalLength(h){g.extraLen=h},get commentLength(){return d},set commentLength(h){d=h},get diskNumStart(){return p},set diskNumStart(h){p=w(h)},get inAttr(){return m},set inAttr(h){m=w(h)},get attr(){return f},set attr(h){f=w(h)},get fileAttr(){return(f||0)>>16&4095},get offset(){return u},set offset(h){u=w(h)},get encrypted(){return(r&b.FLG_ENC)===b.FLG_ENC},get centralHeaderSize(){return b.CENHDR+c+l+d},get realDataOffset(){return u+b.LOCHDR+g.fnameLen+g.extraLen},get localHeader(){return g},loadLocalHeaderFromBinary:function(h){var _=h.slice(u,u+b.LOCHDR);if(_.readUInt32LE(0)!==b.LOCSIG)throw Tt.Errors.INVALID_LOC();g.version=_.readUInt16LE(b.LOCVER),g.flags=_.readUInt16LE(b.LOCFLG),g.flags_desc=(g.flags&b.FLG_DESC)>0,g.method=_.readUInt16LE(b.LOCHOW),g.time=_.readUInt32LE(b.LOCTIM),g.crc=_.readUInt32LE(b.LOCCRC),g.compressedSize=_.readUInt32LE(b.LOCSIZ),g.size=_.readUInt32LE(b.LOCLEN),g.fnameLen=_.readUInt16LE(b.LOCNAM),g.extraLen=_.readUInt16LE(b.LOCEXT);let S=u+b.LOCHDR+g.fnameLen,k=S+g.extraLen;return h.slice(S,k)},loadFromBinary:function(h){if(h.length!==b.CENHDR||h.readUInt32LE(0)!==b.CENSIG)throw Tt.Errors.INVALID_CEN();t=h.readUInt16LE(b.CENVEM),e=h.readUInt16LE(b.CENVER),r=h.readUInt16LE(b.CENFLG),n=h.readUInt16LE(b.CENHOW),i=h.readUInt32LE(b.CENTIM),s=h.readUInt32LE(b.CENCRC),o=h.readUInt32LE(b.CENSIZ),a=h.readUInt32LE(b.CENLEN),c=h.readUInt16LE(b.CENNAM),l=h.readUInt16LE(b.CENEXT),d=h.readUInt16LE(b.CENCOM),p=h.readUInt16LE(b.CENDSK),m=h.readUInt16LE(b.CENATT),f=h.readUInt32LE(b.CENATX),u=h.readUInt32LE(b.CENOFF)},localHeaderToBinary:function(){var h=Buffer.alloc(b.LOCHDR);return h.writeUInt32LE(b.LOCSIG,0),h.writeUInt16LE(e,b.LOCVER),h.writeUInt16LE(r,b.LOCFLG),h.writeUInt16LE(n,b.LOCHOW),h.writeUInt32LE(i,b.LOCTIM),h.writeUInt32LE(s,b.LOCCRC),h.writeUInt32LE(o,b.LOCSIZ),h.writeUInt32LE(a,b.LOCLEN),h.writeUInt16LE(c,b.LOCNAM),h.writeUInt16LE(g.extraLen,b.LOCEXT),h},centralHeaderToBinary:function(){var h=Buffer.alloc(b.CENHDR+c+l+d);return h.writeUInt32LE(b.CENSIG,0),h.writeUInt16LE(t,b.CENVEM),h.writeUInt16LE(e,b.CENVER),h.writeUInt16LE(r,b.CENFLG),h.writeUInt16LE(n,b.CENHOW),h.writeUInt32LE(i,b.CENTIM),h.writeUInt32LE(s,b.CENCRC),h.writeUInt32LE(o,b.CENSIZ),h.writeUInt32LE(a,b.CENLEN),h.writeUInt16LE(c,b.CENNAM),h.writeUInt16LE(l,b.CENEXT),h.writeUInt16LE(d,b.CENCOM),h.writeUInt16LE(p,b.CENDSK),h.writeUInt16LE(m,b.CENATT),h.writeUInt32LE(f,b.CENATX),h.writeUInt32LE(u,b.CENOFF),h},toJSON:function(){let h=function(_){return _+" bytes"};return{made:t,version:e,flags:r,method:Tt.methodToString(n),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:h(o),size:h(a),fileNameLength:h(c),extraLength:h(l),commentLength:h(d),diskNumStart:p,inAttr:m,attr:f,offset:u,centralHeaderSize:h(b.CENHDR+c+l+d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Bl=z((Jv,Ml)=>{var Tr=vr(),W=Tr.Constants;Ml.exports=function(){var t=0,e=0,r=0,n=0,i=0;return{get diskEntries(){return t},set diskEntries(s){t=e=s},get totalEntries(){return e},set totalEntries(s){e=t=s},get size(){return r},set size(s){r=s},get offset(){return n},set offset(s){n=s},get commentLength(){return i},set commentLength(s){i=s},get mainHeaderSize(){return W.ENDHDR+i},loadFromBinary:function(s){if((s.length!==W.ENDHDR||s.readUInt32LE(0)!==W.ENDSIG)&&(s.length<W.ZIP64HDR||s.readUInt32LE(0)!==W.ZIP64SIG))throw Tr.Errors.INVALID_END();s.readUInt32LE(0)===W.ENDSIG?(t=s.readUInt16LE(W.ENDSUB),e=s.readUInt16LE(W.ENDTOT),r=s.readUInt32LE(W.ENDSIZ),n=s.readUInt32LE(W.ENDOFF),i=s.readUInt16LE(W.ENDCOM)):(t=Tr.readBigUInt64LE(s,W.ZIP64SUB),e=Tr.readBigUInt64LE(s,W.ZIP64TOT),r=Tr.readBigUInt64LE(s,W.ZIP64SIZE),n=Tr.readBigUInt64LE(s,W.ZIP64OFF),i=0)},toBinary:function(){var s=Buffer.alloc(W.ENDHDR+i);return s.writeUInt32LE(W.ENDSIG,0),s.writeUInt32LE(0,4),s.writeUInt16LE(t,W.ENDSUB),s.writeUInt16LE(e,W.ENDTOT),s.writeUInt32LE(r,W.ENDSIZ),s.writeUInt32LE(n,W.ENDOFF),s.writeUInt16LE(i,W.ENDCOM),s.fill(" ",W.ENDHDR),s},toJSON:function(){let s=function(o,a){let c=o.toString(16).toUpperCase();for(;c.length<a;)c="0"+c;return"0x"+c};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:s(n,4),commentLength:i}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var vo=z(Io=>{Io.EntryHeader=Fl();Io.MainHeader=Bl()});var zl=z((Zv,Ul)=>{Ul.exports=function(t){var e=$("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(n){var i=e.createDeflateRaw(r),s=[],o=0;i.on("data",function(a){s.push(a),o+=a.length}),i.on("end",function(){var a=Buffer.alloc(o),c=0;a.fill(0);for(var l=0;l<s.length;l++){var d=s[l];d.copy(a,c),c+=d.length}n&&n(a)}),i.end(t)}}}});var Gl=z((Kv,$l)=>{var Dg=+(process.versions?process.versions.node:"").split(".")[0]||0;$l.exports=function(t,e){var r=$("zlib");let n=Dg>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,n)},inflateAsync:function(i){var s=r.createInflateRaw(n),o=[],a=0;s.on("data",function(c){o.push(c),a+=c.length}),s.on("end",function(){var c=Buffer.alloc(a),l=0;c.fill(0);for(var d=0;d<o.length;d++){var p=o[d];p.copy(c,l),l+=p.length}i&&i(c)}),s.end(t)}}}});var Jl=z((Xv,ql)=>{"use strict";var{randomFillSync:Hl}=$("crypto"),Ng=Oi(),Lg=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Wl=(t,e)=>Math.imul(t,e)>>>0,jl=(t,e)=>Lg[(t^e)&255]^t>>>8,un=()=>typeof Hl=="function"?Hl(Buffer.alloc(12)):un.node();un.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var xi={genSalt:un};function Pi(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}Pi.prototype.updateKeys=function(t){let e=this.keys;return e[0]=jl(e[0],t),e[1]+=e[0]&255,e[1]=Wl(e[1],134775813)+1,e[2]=jl(e[2],e[1]>>>24),t};Pi.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Wl(t,t^1)>>8&255};function Fg(t){let e=new Pi(t);return function(r){let n=Buffer.alloc(r.length),i=0;for(let s of r)n[i++]=e.updateKeys(s^e.next());return n}}function Mg(t){let e=new Pi(t);return function(r,n,i=0){n||(n=Buffer.alloc(r.length));for(let s of r){let o=e.next();n[i++]=s^o,e.updateKeys(s)}return n}}function Bg(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=Fg(r),i=n(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw Ng.WRONG_PASSWORD();return n(t.slice(12))}function Ug(t){Buffer.isBuffer(t)&&t.length>=12?xi.genSalt=function(){return t.slice(0,12)}:t==="node"?xi.genSalt=un.node:xi.genSalt=un}function zg(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=Mg(r),s=xi.genSalt();s[11]=e.crc>>>24&255,n&&(s[10]=e.crc>>>16&255);let o=Buffer.alloc(t.length+12);return i(s,o),i(t,o,12)}ql.exports={decrypt:Bg,encrypt:zg,_salter:Ug}});var Vl=z(Ci=>{Ci.Deflater=zl();Ci.Inflater=Gl();Ci.ZipCrypto=Jl()});var Ro=z((Yv,Zl)=>{var B=vr(),$g=vo(),K=B.Constants,To=Vl();Zl.exports=function(t,e){var r=new $g.EntryHeader,n=Buffer.alloc(0),i=Buffer.alloc(0),s=!1,o=null,a=Buffer.alloc(0),c=Buffer.alloc(0),l=!0;let d=t,p=typeof d.decoder=="object"?d.decoder:B.decoder;l=p.hasOwnProperty("efs")?p.efs:!1;function m(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(c=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function f(h){if(!r.flags_desc&&!r.localHeader.flags_desc){if(B.crc32(h)!==r.localHeader.crc)return!1}else{let _={},S=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(S)==K.LOCSIG||e.readUInt32LE(S)==K.CENSIG)throw B.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(S)==K.EXTSIG)_.crc=e.readUInt32LE(S+K.EXTCRC),_.compressedSize=e.readUInt32LE(S+K.EXTSIZ),_.size=e.readUInt32LE(S+K.EXTLEN);else if(e.readUInt16LE(S+12)===19280)_.crc=e.readUInt32LE(S+K.EXTCRC-4),_.compressedSize=e.readUInt32LE(S+K.EXTSIZ-4),_.size=e.readUInt32LE(S+K.EXTLEN-4);else throw B.Errors.DESCRIPTOR_UNKNOWN();if(_.compressedSize!==r.compressedSize||_.size!==r.size||_.crc!==r.crc)throw B.Errors.DESCRIPTOR_FAULTY();if(B.crc32(h)!==_.crc)return!1}return!0}function u(h,_,S){if(typeof _>"u"&&typeof h=="string"&&(S=h,h=void 0),s)return h&&_&&_(Buffer.alloc(0),B.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var k=m();if(k.length===0)return h&&_&&_(k),k;if(r.encrypted){if(typeof S!="string"&&!Buffer.isBuffer(S))throw B.Errors.INVALID_PASS_PARAM();k=To.ZipCrypto.decrypt(k,r,S)}var R=Buffer.alloc(r.size);switch(r.method){case B.Constants.STORED:if(k.copy(R),f(R))return h&&_&&_(R),R;throw h&&_&&_(R,B.Errors.BAD_CRC()),B.Errors.BAD_CRC();case B.Constants.DEFLATED:var I=new To.Inflater(k,r.size);if(h)I.inflateAsync(function(T){T.copy(T,0),_&&(f(T)?_(T):_(T,B.Errors.BAD_CRC()))});else{if(I.inflate(R).copy(R,0),!f(R))throw B.Errors.BAD_CRC(`"${p.decode(n)}"`);return R}break;default:throw h&&_&&_(Buffer.alloc(0),B.Errors.UNKNOWN_METHOD()),B.Errors.UNKNOWN_METHOD()}}function g(h,_){if((!o||!o.length)&&Buffer.isBuffer(e))return h&&_&&_(m()),m();if(o.length&&!s){var S;switch(r.method){case B.Constants.STORED:return r.compressedSize=r.size,S=Buffer.alloc(o.length),o.copy(S),h&&_&&_(S),S;default:case B.Constants.DEFLATED:var k=new To.Deflater(o);if(h)k.deflateAsync(function(I){S=Buffer.alloc(I.length),r.compressedSize=I.length,I.copy(S),_&&_(S)});else{var R=k.deflate();return r.compressedSize=R.length,R}k=null;break}}else if(h&&_)_(Buffer.alloc(0));else return Buffer.alloc(0)}function w(h,_){return B.readBigUInt64LE(h,_)}function E(h){try{for(var _=0,S,k,R;_+4<h.length;)S=h.readUInt16LE(_),_+=2,k=h.readUInt16LE(_),_+=2,R=h.slice(_,_+k),_+=k,K.ID_ZIP64===S&&v(R)}catch{throw B.Errors.EXTRA_FIELD_PARSE_ERROR()}}function v(h){var _,S,k,R;h.length>=K.EF_ZIP64_SCOMP&&(_=w(h,K.EF_ZIP64_SUNCOMP),r.size===K.EF_ZIP64_OR_32&&(r.size=_)),h.length>=K.EF_ZIP64_RHO&&(S=w(h,K.EF_ZIP64_SCOMP),r.compressedSize===K.EF_ZIP64_OR_32&&(r.compressedSize=S)),h.length>=K.EF_ZIP64_DSN&&(k=w(h,K.EF_ZIP64_RHO),r.offset===K.EF_ZIP64_OR_32&&(r.offset=k)),h.length>=K.EF_ZIP64_DSN+4&&(R=h.readUInt32LE(K.EF_ZIP64_DSN),r.diskNumStart===K.EF_ZIP64_OR_16&&(r.diskNumStart=R))}return{get entryName(){return p.decode(n)},get rawEntryName(){return n},set entryName(h){n=B.toBuffer(h,p.encode);var _=n[n.length-1];s=_===47||_===92,r.fileNameLength=n.length},get efs(){return typeof l=="function"?l(this.entryName):l},get extra(){return a},set extra(h){a=h,r.extraLength=h.length,E(h)},get comment(){return p.decode(i)},set comment(h){if(i=B.toBuffer(h,p.encode),r.commentLength=i.length,i.length>65535)throw B.Errors.COMMENT_TOO_LONG()},get name(){var h=p.decode(n);return s?h.substr(h.length-1).split("/").pop():h.split("/").pop()},get isDirectory(){return s},getCompressedData:function(){return g(!1,null)},getCompressedDataAsync:function(h){g(!0,h)},setData:function(h){o=B.toBuffer(h,B.decoder.encode),!s&&o.length?(r.size=o.length,r.method=B.Constants.DEFLATED,r.crc=B.crc32(h),r.changed=!0):r.method=B.Constants.STORED},getData:function(h){return r.changed?o:u(!1,null,h)},getDataAsync:function(h,_){r.changed?h(o):u(!0,h,_)},set attr(h){r.attr=h},get attr(){return r.attr},set header(h){r.loadFromBinary(h)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=a.length;var h=r.centralHeaderToBinary(),_=B.Constants.CENHDR;return n.copy(h,_),_+=n.length,a.copy(h,_),_+=r.extraLength,i.copy(h,_),h},packLocalHeader:function(){let h=0;r.flags_efs=this.efs,r.extraLocalLength=c.length;let _=r.localHeaderToBinary(),S=Buffer.alloc(_.length+n.length+r.extraLocalLength);return _.copy(S,h),h+=_.length,n.copy(S,h),h+=n.length,c.copy(S,h),h+=c.length,S},toJSON:function(){let h=function(_){return"<"+(_&&_.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:h(e),data:h(o)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ql=z((eT,Xl)=>{var Kl=Ro(),Gg=vo(),fe=vr();Xl.exports=function(t,e){var r=[],n={},i=Buffer.alloc(0),s=new Gg.MainHeader,o=!1,a=null;let c=new Set,l=e,{noSort:d,decoder:p}=l;t?u(l.readEntries):o=!0;function m(){let w=new Set;for(let E of Object.keys(n)){let v=E.split("/");if(v.pop(),!!v.length)for(let h=0;h<v.length;h++){let _=v.slice(0,h+1).join("/")+"/";w.add(_)}}for(let E of w)if(!(E in n)){let v=new Kl(l);v.entryName=E,v.attr=16,v.temporary=!0,r.push(v),n[v.entryName]=v,c.add(v)}}function f(){if(o=!0,n={},s.diskEntries>(t.length-s.offset)/fe.Constants.CENHDR)throw fe.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(s.diskEntries);for(var w=s.offset,E=0;E<r.length;E++){var v=w,h=new Kl(l,t);h.header=t.slice(v,v+=fe.Constants.CENHDR),h.entryName=t.slice(v,v+=h.header.fileNameLength),h.header.extraLength&&(h.extra=t.slice(v,v+=h.header.extraLength)),h.header.commentLength&&(h.comment=t.slice(v,v+h.header.commentLength)),w+=h.header.centralHeaderSize,r[E]=h,n[h.entryName]=h}c.clear(),m()}function u(w){var E=t.length-fe.Constants.ENDHDR,v=Math.max(0,E-65535),h=v,_=t.length,S=-1,k=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(v=0),E;E>=h;E--)if(t[E]===80){if(t.readUInt32LE(E)===fe.Constants.ENDSIG){S=E,k=E,_=E+fe.Constants.ENDHDR,h=E-fe.Constants.END64HDR;continue}if(t.readUInt32LE(E)===fe.Constants.END64SIG){h=v;continue}if(t.readUInt32LE(E)===fe.Constants.ZIP64SIG){S=E,_=E+fe.readBigUInt64LE(t,E+fe.Constants.ZIP64SIZE)+fe.Constants.ZIP64LEAD;break}}if(S==-1)throw fe.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(S,_)),s.commentLength&&(i=t.slice(k+fe.Constants.ENDHDR)),w&&f()}function g(){r.length>1&&!d&&r.sort((w,E)=>w.entryName.toLowerCase().localeCompare(E.entryName.toLowerCase()))}return{get entries(){return o||f(),r.filter(w=>!c.has(w))},get comment(){return p.decode(i)},set comment(w){i=fe.toBuffer(w,p.encode),s.commentLength=i.length},getEntryCount:function(){return o?r.length:s.diskEntries},forEach:function(w){this.entries.forEach(w)},getEntry:function(w){return o||f(),n[w]||null},setEntry:function(w){o||f(),r.push(w),n[w.entryName]=w,s.totalEntries=r.length},deleteFile:function(w,E=!0){o||f();let v=n[w];this.getEntryChildren(v,E).map(_=>_.entryName).forEach(this.deleteEntry)},deleteEntry:function(w){o||f();let E=n[w],v=r.indexOf(E);v>=0&&(r.splice(v,1),delete n[w],s.totalEntries=r.length)},getEntryChildren:function(w,E=!0){if(o||f(),typeof w=="object")if(w.isDirectory&&E){let v=[],h=w.entryName;for(let _ of r)_.entryName.startsWith(h)&&v.push(_);return v}else return[w];return[]},getChildCount:function(w){if(w&&w.isDirectory){let E=this.getEntryChildren(w);return E.includes(w)?E.length-1:E.length}return 0},compressToBuffer:function(){o||f(),g();let w=[],E=[],v=0,h=0;s.size=0,s.offset=0;let _=0;for(let R of this.entries){let I=R.getCompressedData();R.header.offset=h;let T=R.packLocalHeader(),A=T.length+I.length;h+=A,w.push(T),w.push(I);let P=R.packCentralHeader();E.push(P),s.size+=P.length,v+=A+P.length,_++}v+=s.mainHeaderSize,s.offset=h,s.totalEntries=_,h=0;let S=Buffer.alloc(v);for(let R of w)R.copy(S,h),h+=R.length;for(let R of E)R.copy(S,h),h+=R.length;let k=s.toBinary();return i&&i.copy(k,fe.Constants.ENDHDR),k.copy(S,h),t=S,o=!1,S},toAsyncBuffer:function(w,E,v,h){try{o||f(),g();let _=[],S=[],k=0,R=0,I=0;s.size=0,s.offset=0;let T=function(A){if(A.length>0){let P=A.shift(),G=P.entryName+P.extra.toString();v&&v(G),P.getCompressedDataAsync(function(X){h&&h(G),P.header.offset=R;let Pe=P.packLocalHeader(),ot=Pe.length+X.length;R+=ot,_.push(Pe),_.push(X);let at=P.packCentralHeader();S.push(at),s.size+=at.length,k+=ot+at.length,I++,T(A)})}else{k+=s.mainHeaderSize,s.offset=R,s.totalEntries=I,R=0;let P=Buffer.alloc(k);_.forEach(function(X){X.copy(P,R),R+=X.length}),S.forEach(function(X){X.copy(P,R),R+=X.length});let G=s.toBinary();i&&i.copy(G,fe.Constants.ENDHDR),G.copy(P,R),t=P,o=!1,w(P)}};T(Array.from(this.entries))}catch(_){E(_)}}}}});var td=z((tT,ed)=>{var J=vr(),q=$("path"),Hg=Ro(),jg=Ql(),qt=(...t)=>J.findLast(t,e=>typeof e=="boolean"),Yl=(...t)=>J.findLast(t,e=>typeof e=="string"),Wg=(...t)=>J.findLast(t,e=>typeof e=="function"),qg={noSort:!1,readEntries:!1,method:J.Constants.NONE,fs:null};ed.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),qg);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=J.Constants.BUFFER,t=void 0)),Object.assign(n,e);let i=new J(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=J.decoder),t&&typeof t=="string")if(i.fs.existsSync(t))n.method=J.Constants.FILE,n.filename=t,r=i.fs.readFileSync(t);else throw J.Errors.INVALID_FILENAME();let s=new jg(r,n),{canonical:o,sanitize:a,zipnamefix:c}=J;function l(f){if(f&&s){var u;if(typeof f=="string"&&(u=s.getEntry(q.posix.normalize(f))),typeof f=="object"&&typeof f.entryName<"u"&&typeof f.header<"u"&&(u=s.getEntry(f.entryName)),u)return u}return null}function d(f){let{join:u,normalize:g,sep:w}=q.posix;return u(q.isAbsolute(f)?"/":".",g(w+f.split("\\").join(w)+w))}function p(f){return f instanceof RegExp?(function(u){return function(g){return u.test(g)}})(f):typeof f!="function"?()=>!0:f}let m=(f,u)=>{let g=u.slice(-1);return g=g===i.sep?i.sep:"",q.relative(f,u)+g};return{readFile:function(f,u){var g=l(f);return g&&g.getData(u)||null},childCount:function(f){let u=l(f);if(u)return s.getChildCount(u)},readFileAsync:function(f,u){var g=l(f);g?g.getDataAsync(u):u(null,"getEntry failed for:"+f)},readAsText:function(f,u){var g=l(f);if(g){var w=g.getData();if(w&&w.length)return w.toString(u||"utf8")}return""},readAsTextAsync:function(f,u,g){var w=l(f);w?w.getDataAsync(function(E,v){if(v){u(E,v);return}E&&E.length?u(E.toString(g||"utf8")):u("")}):u("")},deleteFile:function(f,u=!0){var g=l(f);g&&s.deleteFile(g.entryName,u)},deleteEntry:function(f){var u=l(f);u&&s.deleteEntry(u.entryName)},addZipComment:function(f){s.comment=f},getZipComment:function(){return s.comment||""},addZipEntryComment:function(f,u){var g=l(f);g&&(g.comment=u)},getZipEntryComment:function(f){var u=l(f);return u&&u.comment||""},updateFile:function(f,u){var g=l(f);g&&g.setData(u)},addLocalFile:function(f,u,g,w){if(i.fs.existsSync(f)){u=u?d(u):"";let E=q.win32.basename(q.win32.normalize(f));u+=g||E;let v=i.fs.statSync(f),h=v.isFile()?i.fs.readFileSync(f):Buffer.alloc(0);v.isDirectory()&&(u+=i.sep),this.addFile(u,h,w,v)}else throw J.Errors.FILE_NOT_FOUND(f)},addLocalFileAsync:function(f,u){f=typeof f=="object"?f:{localPath:f};let g=q.resolve(f.localPath),{comment:w}=f,{zipPath:E,zipName:v}=f,h=this;i.fs.stat(g,function(_,S){if(_)return u(_,!1);E=E?d(E):"";let k=q.win32.basename(q.win32.normalize(g));if(E+=v||k,S.isFile())i.fs.readFile(g,function(R,I){return R?u(R,!1):(h.addFile(E,I,w,S),setImmediate(u,void 0,!0))});else if(S.isDirectory())return E+=i.sep,h.addFile(E,Buffer.alloc(0),w,S),setImmediate(u,void 0,!0)})},addLocalFolder:function(f,u,g){if(g=p(g),u=u?d(u):"",f=q.normalize(f),i.fs.existsSync(f)){let w=i.findFiles(f),E=this;if(w.length)for(let v of w){let h=q.join(u,m(f,v));g(h)&&E.addLocalFile(v,q.dirname(h))}}else throw J.Errors.FILE_NOT_FOUND(f)},addLocalFolderAsync:function(f,u,g,w){w=p(w),g=g?d(g):"",f=q.normalize(f);var E=this;i.fs.open(f,"r",function(v){if(v&&v.code==="ENOENT")u(void 0,J.Errors.FILE_NOT_FOUND(f));else if(v)u(void 0,v);else{var h=i.findFiles(f),_=-1,S=function(){if(_+=1,_<h.length){var k=h[_],R=m(f,k).split("\\").join("/");R=R.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),w(R)?i.fs.stat(k,function(I,T){I&&u(void 0,I),T.isFile()?i.fs.readFile(k,function(A,P){A?u(void 0,A):(E.addFile(g+R,P,"",T),S())}):(E.addFile(g+R+"/",Buffer.alloc(0),"",T),S())}):process.nextTick(()=>{S()})}else u(!0,void 0)};S()}})},addLocalFolderAsync2:function(f,u){let g=this;f=typeof f=="object"?f:{localPath:f},localPath=q.resolve(d(f.localPath));let{zipPath:w,filter:E,namefix:v}=f;E instanceof RegExp?E=(function(S){return function(k){return S.test(k)}})(E):typeof E!="function"&&(E=function(){return!0}),w=w?d(w):"",v=="latin1"&&(v=S=>S.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof v!="function"&&(v=S=>S);let h=S=>q.join(w,v(m(localPath,S))),_=S=>q.win32.basename(q.win32.normalize(v(S)));i.fs.open(localPath,"r",function(S){S&&S.code==="ENOENT"?u(void 0,J.Errors.FILE_NOT_FOUND(localPath)):S?u(void 0,S):i.findFilesAsync(localPath,function(k,R){if(k)return u(k);R=R.filter(I=>E(h(I))),R.length||u(void 0,!1),setImmediate(R.reverse().reduce(function(I,T){return function(A,P){if(A||P===!1)return setImmediate(I,A,!1);g.addLocalFileAsync({localPath:T,zipPath:q.dirname(h(T)),zipName:_(T)},I)}},u))})})},addLocalFolderPromise:function(f,u){return new Promise((g,w)=>{this.addLocalFolderAsync2(Object.assign({localPath:f},u),(E,v)=>{E&&w(E),v&&g(this)})})},addFile:function(f,u,g,w){f=c(f);let E=l(f),v=E!=null;v||(E=new Hg(n),E.entryName=f),E.comment=g||"";let h=typeof w=="object"&&w instanceof i.fs.Stats;h&&(E.header.time=w.mtime);var _=E.isDirectory?16:0;let S=E.isDirectory?16384:32768;return h?S|=4095&w.mode:typeof w=="number"?S|=4095&w:S|=E.isDirectory?493:420,_=(_|S<<16)>>>0,E.attr=_,E.setData(u),v||s.setEntry(E),E},getEntries:function(f){return s.password=f,s?s.entries:[]},getEntry:function(f){return l(f)},getEntryCount:function(){return s.getEntryCount()},forEach:function(f){return s.forEach(f)},extractEntryTo:function(f,u,g,w,E,v){w=qt(!1,w),E=qt(!1,E),g=qt(!0,g),v=Yl(E,v);var h=l(f);if(!h)throw J.Errors.NO_ENTRY();var _=o(h.entryName),S=a(u,v&&!h.isDirectory?v:g?_:q.basename(_));if(h.isDirectory){var k=s.getEntryChildren(h);return k.forEach(function(T){if(T.isDirectory)return;var A=T.getData();if(!A)throw J.Errors.CANT_EXTRACT_FILE();var P=o(T.entryName),G=a(u,g?P:q.basename(P));let X=E?T.header.fileAttr:void 0;i.writeFileTo(G,A,w,X)}),!0}var R=h.getData(s.password);if(!R)throw J.Errors.CANT_EXTRACT_FILE();if(i.fs.existsSync(S)&&!w)throw J.Errors.CANT_OVERRIDE();let I=E?f.header.fileAttr:void 0;return i.writeFileTo(S,R,w,I),!0},test:function(f){if(!s)return!1;for(var u in s.entries)try{if(u.isDirectory)continue;var g=s.entries[u].getData(f);if(!g)return!1}catch{return!1}return!0},extractAllTo:function(f,u,g,w){if(g=qt(!1,g),w=Yl(g,w),u=qt(!1,u),!s)throw J.Errors.NO_ZIP();s.entries.forEach(function(E){var v=a(f,o(E.entryName));if(E.isDirectory){i.makeDir(v);return}var h=E.getData(w);if(!h)throw J.Errors.CANT_EXTRACT_FILE();let _=g?E.header.fileAttr:void 0;i.writeFileTo(v,h,u,_);try{i.fs.utimesSync(v,E.header.time,E.header.time)}catch{throw J.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(f,u,g,w){if(w=Wg(u,g,w),g=qt(!1,g),u=qt(!1,u),!w)return new Promise((S,k)=>{this.extractAllToAsync(f,u,g,function(R){R?k(R):S(this)})});if(!s){w(J.Errors.NO_ZIP());return}f=q.resolve(f);let E=S=>a(f,q.normalize(o(S.entryName))),v=(S,k)=>new Error(S+': "'+k+'"'),h=[],_=[];s.entries.forEach(S=>{S.isDirectory?h.push(S):_.push(S)});for(let S of h){let k=E(S),R=g?S.header.fileAttr:void 0;try{i.makeDir(k),R&&i.fs.chmodSync(k,R),i.fs.utimesSync(k,S.header.time,S.header.time)}catch{w(v("Unable to create folder",k))}}_.reverse().reduce(function(S,k){return function(R){if(R)S(R);else{let I=q.normalize(o(k.entryName)),T=a(f,I);k.getDataAsync(function(A,P){if(P)S(P);else if(!A)S(J.Errors.CANT_EXTRACT_FILE());else{let G=g?k.header.fileAttr:void 0;i.writeFileToAsync(T,A,u,G,function(X){X||S(v("Unable to write file",T)),i.fs.utimes(T,k.header.time,k.header.time,function(Pe){Pe?S(v("Unable to set times",T)):S()})})}})}}},w)()},writeZip:function(f,u){if(arguments.length===1&&typeof f=="function"&&(u=f,f=""),!f&&n.filename&&(f=n.filename),!!f){var g=s.compressToBuffer();if(g){var w=i.writeFileTo(f,g,!0);typeof u=="function"&&u(w?null:new Error("failed"),"")}}},writeZipPromise:function(f,u){let{overwrite:g,perm:w}=Object.assign({overwrite:!0},u);return new Promise((E,v)=>{!f&&n.filename&&(f=n.filename),f||v("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(h=>{let _=S=>S?E(S):v("ADM-ZIP: Wasn't able to write zip file");i.writeFileToAsync(f,h,g,w,_)},v)})},toBufferPromise:function(){return new Promise((f,u)=>{s.toAsyncBuffer(f,u)})},toBuffer:function(f,u,g,w){return typeof f=="function"?(s.toAsyncBuffer(f,u,g,w),null):s.compressToBuffer()}}}});function oE(){return Of||(Of=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function aE(){return xf||(xf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function cE(t){let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{r(Ne(t.result)),i()},o=()=>{n(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(r=>{r instanceof IDBCursor&&Pf.set(r,t)}).catch(()=>{}),Za.set(e,t),e}function lE(t){if(Ja.has(t))return;let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o)},s=()=>{r(),i()},o=()=>{n(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o)});Ja.set(t,e)}function Df(t){Va=t(Va)}function dE(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(Qn(this),e,...r);return Cf.set(n,e.sort?e.sort():[e]),Ne(n)}:aE().includes(t)?function(...e){return t.apply(Qn(this),e),Ne(Pf.get(this))}:function(...e){return Ne(t.apply(Qn(this),e))}}function hE(t){return typeof t=="function"?dE(t):(t instanceof IDBTransaction&&lE(t),sE(t,oE())?new Proxy(t,Va):t)}function Ne(t){if(t instanceof IDBRequest)return cE(t);if(qa.has(t))return qa.get(t);let e=hE(t);return e!==t&&(qa.set(t,e),Za.set(e,t)),e}var sE,Of,xf,Pf,Ja,Cf,qa,Za,Va,Qn,Ka=Ie(()=>{sE=(t,e)=>e.some(r=>t instanceof r);Pf=new WeakMap,Ja=new WeakMap,Cf=new WeakMap,qa=new WeakMap,Za=new WeakMap;Va={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return Ja.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Cf.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Ne(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};Qn=t=>Za.get(t)});var Lf={};gi(Lf,{deleteDB:()=>uE,openDB:()=>fE,unwrap:()=>Qn,wrap:()=>Ne});function fE(t,e,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=Ne(o);return n&&o.addEventListener("upgradeneeded",c=>{n(Ne(o.result),c.oldVersion,c.newVersion,Ne(o.transaction))}),r&&o.addEventListener("blocked",()=>r()),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",()=>i())}).catch(()=>{}),a}function uE(t,{blocked:e}={}){let r=indexedDB.deleteDatabase(t);return e&&r.addEventListener("blocked",()=>e()),Ne(r).then(()=>{})}function Nf(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Xa.get(e))return Xa.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,i=gE.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||pE.includes(r)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),i&&c.done]))[0]};return Xa.set(e,s),s}var pE,gE,Xa,Ff=Ie(()=>{Ka();Ka();pE=["get","getKey","getAll","getAllKeys","count"],gE=["put","add","delete","clear"],Xa=new Map;Df(t=>({...t,get:(e,r,n)=>Nf(e,r)||t.get(e,r,n),has:(e,r)=>!!Nf(e,r)||t.has(e,r)}))});var wt=z((AA,cu)=>{"use strict";var ou=["nodebuffer","arraybuffer","fragments"],au=typeof Blob<"u";au&&ou.push("blob");cu.exports={BINARY_TYPES:ou,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:au,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ii=z((OA,Us)=>{"use strict";var{EMPTY_BUFFER:_0}=wt(),Ec=Buffer[Symbol.species];function y0(t,e){if(t.length===0)return _0;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let i=0;i<t.length;i++){let s=t[i];r.set(s,n),n+=s.length}return n<e?new Ec(r.buffer,r.byteOffset,n):r}function lu(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}function du(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function E0(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Sc(t){if(Sc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Ec(t):ArrayBuffer.isView(t)?e=new Ec(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Sc.readOnly=!1),e}Us.exports={concat:y0,mask:lu,toArrayBuffer:E0,toBuffer:Sc,unmask:du};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=$("bufferutil");Us.exports.mask=function(e,r,n,i,s){s<48?lu(e,r,n,i,s):t.mask(e,r,n,i,s)},Us.exports.unmask=function(e,r){e.length<32?du(e,r):t.unmask(e,r)}}catch{}});var uu=z((xA,fu)=>{"use strict";var hu=Symbol("kDone"),Ic=Symbol("kRun"),vc=class{constructor(e){this[hu]=()=>{this.pending--,this[Ic]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ic]()}[Ic](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[hu])}}};fu.exports=vc});var Yr=z((PA,wu)=>{"use strict";var si=$("zlib"),pu=ii(),S0=uu(),{kStatusCode:gu}=wt(),I0=Buffer[Symbol.species],v0=Buffer.from([0,0,255,255]),$s=Symbol("permessage-deflate"),_t=Symbol("total-length"),Xr=Symbol("callback"),Ht=Symbol("buffers"),Qr=Symbol("error"),zs,Tc=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,!zs){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zs=new S0(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Xr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),e}decompress(e,r,n){zs.add(i=>{this._decompress(e,r,(s,o)=>{i(),n(s,o)})})}compress(e,r,n){zs.add(i=>{this._compress(e,r,(s,o)=>{i(),n(s,o)})})}_decompress(e,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?si.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=si.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[$s]=this,this._inflate[_t]=0,this._inflate[Ht]=[],this._inflate.on("error",R0),this._inflate.on("data",mu)}this._inflate[Xr]=n,this._inflate.write(e),r&&this._inflate.write(v0),this._inflate.flush(()=>{let s=this._inflate[Qr];if(s){this._inflate.close(),this._inflate=null,n(s);return}let o=pu.concat(this._inflate[Ht],this._inflate[_t]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[_t]=0,this._inflate[Ht]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?si.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=si.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[_t]=0,this._deflate[Ht]=[],this._deflate.on("data",T0)}this._deflate[Xr]=n,this._deflate.write(e),this._deflate.flush(si.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=pu.concat(this._deflate[Ht],this._deflate[_t]);r&&(s=new I0(s.buffer,s.byteOffset,s.length-4)),this._deflate[Xr]=null,this._deflate[_t]=0,this._deflate[Ht]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};wu.exports=Tc;function T0(t){this[Ht].push(t),this[_t]+=t.length}function mu(t){if(this[_t]+=t.length,this[$s]._maxPayload<1||this[_t]<=this[$s]._maxPayload){this[Ht].push(t);return}this[Qr]=new RangeError("Max payload size exceeded"),this[Qr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Qr][gu]=1009,this.removeListener("data",mu),this.reset()}function R0(t){if(this[$s]._inflate=null,this[Qr]){this[Xr](this[Qr]);return}t[gu]=1007,this[Xr](t)}});var en=z((CA,Gs)=>{"use strict";var{isUtf8:_u}=$("buffer"),{hasBlob:k0}=wt(),b0=[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 A0(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Rc(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function O0(t){return k0&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Gs.exports={isBlob:O0,isValidStatusCode:A0,isValidUTF8:Rc,tokenChars:b0};if(_u)Gs.exports.isValidUTF8=function(t){return t.length<24?Rc(t):_u(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=$("utf-8-validate");Gs.exports.isValidUTF8=function(e){return e.length<32?Rc(e):t(e)}}catch{}});var xc=z((DA,Ru)=>{"use strict";var{Writable:x0}=$("stream"),yu=Yr(),{BINARY_TYPES:P0,EMPTY_BUFFER:Eu,kStatusCode:C0,kWebSocket:D0}=wt(),{concat:kc,toArrayBuffer:N0,unmask:L0}=ii(),{isValidStatusCode:F0,isValidUTF8:Su}=en(),Hs=Buffer[Symbol.species],Fe=0,Iu=1,vu=2,Tu=3,bc=4,Ac=5,js=6,Oc=class extends x0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||P0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[D0]=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=Fe}_write(e,r,n){if(this._opcode===8&&this._state==Fe)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Hs(n.buffer,n.byteOffset+e,n.length-e),new Hs(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=r.length-e;e>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new Hs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case Fe:this.getInfo(e);break;case Iu:this.getPayloadLength16(e);break;case vu:this.getPayloadLength64(e);break;case Tu:this.getMask();break;case bc:this.getData(e);break;case Ac:case js:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[yu.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=Iu:this._payloadLength===127?this._state=vu:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=Tu:this._state=bc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=bc}getData(e){let r=Eu;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&L0(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Ac,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[yu.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return r(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}this._fragments.push(s)}this.dataMessage(r),this._state===Fe&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=Fe;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=kc(n,r):this._binaryType==="arraybuffer"?i=N0(kc(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Fe):(this._state=js,setImmediate(()=>{this.emit("message",i,!0),this._state=Fe,this.startLoop(e)}))}else{let i=kc(n,r);if(!this._skipUTF8Validation&&!Su(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Ac||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Fe):(this._state=js,setImmediate(()=>{this.emit("message",i,!1),this._state=Fe,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Eu),this.end();else{let n=e.readUInt16BE(0);if(!F0(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new Hs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Su(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Fe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Fe):(this._state=js,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Fe,this.startLoop(r)}))}createError(e,r,n,i,s){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=s,o[C0]=i,o}};Ru.exports=Oc});var Dc=z((LA,Au)=>{"use strict";var{Duplex:NA}=$("stream"),{randomFillSync:M0}=$("crypto"),ku=Yr(),{EMPTY_BUFFER:B0,kWebSocket:U0,NOOP:z0}=wt(),{isBlob:tn,isValidStatusCode:$0}=en(),{mask:bu,toBuffer:hr}=ii(),Me=Symbol("kByteLength"),G0=Buffer.alloc(4),Ws=8*1024,fr,rn=Ws,We=0,H0=1,j0=2,Pc=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=We,this.onerror=z0,this[U0]=void 0}static frame(e,r){let n,i=!1,s=2,o=!1;r.mask&&(n=r.maskBuffer||G0,r.generateMask?r.generateMask(n):(rn===Ws&&(fr===void 0&&(fr=Buffer.alloc(Ws)),M0(fr,0,Ws),rn=0),n[0]=fr[rn++],n[1]=fr[rn++],n[2]=fr[rn++],n[3]=fr[rn++]),o=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||o)&&r[Me]!==void 0?a=r[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,i=r.mask&&r.readOnly&&!o);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(i?a+s:s);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[s-4]=n[0],l[s-3]=n[1],l[s-2]=n[2],l[s-1]=n[3],o?[l,e]:i?(bu(e,n,l,s,a),[l]):(bu(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,i){let s;if(e===void 0)s=B0;else{if(typeof e!="number"||!$0(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let o={[Me]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==We?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):tn(e)?(i=e.size,s=!1):(e=hr(e),i=e.length,s=hr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};tn(e)?this._state!==We?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==We?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}pong(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):tn(e)?(i=e.size,s=!1):(e=hr(e),i=e.length,s=hr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};tn(e)?this._state!==We?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==We?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let i=this._extensions[ku.extensionName],s=r.binary?2:1,o=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):tn(e)?(a=e.size,c=!1):(e=hr(e),a=e.length,c=hr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,s=0),r.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};tn(e)?this._state!==We?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==We?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[Me],this._state=j0,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Cc,this,a,i);return}this._bufferedBytes-=n[Me];let o=hr(s);r?this.dispatch(o,r,n,i):(this._state=We,this.sendFrame(t.frame(o,n),i),this.dequeue())}).catch(s=>{process.nextTick(W0,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[ku.extensionName];this._bufferedBytes+=n[Me],this._state=H0,s.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Cc(this,c,i);return}this._bufferedBytes-=n[Me],this._state=We,n.readOnly=!1,this.sendFrame(t.frame(a,n),i),this.dequeue()})}dequeue(){for(;this._state===We&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};Au.exports=Pc;function Cc(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let i=t._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function W0(t,e,r){Cc(t,e,r),t.onerror(e)}});var Mu=z((FA,Fu)=>{"use strict";var{kForOnEventAttribute:oi,kListener:Nc}=wt(),Ou=Symbol("kCode"),xu=Symbol("kData"),Pu=Symbol("kError"),Cu=Symbol("kMessage"),Du=Symbol("kReason"),nn=Symbol("kTarget"),Nu=Symbol("kType"),Lu=Symbol("kWasClean"),yt=class{constructor(e){this[nn]=null,this[Nu]=e}get target(){return this[nn]}get type(){return this[Nu]}};Object.defineProperty(yt.prototype,"target",{enumerable:!0});Object.defineProperty(yt.prototype,"type",{enumerable:!0});var ur=class extends yt{constructor(e,r={}){super(e),this[Ou]=r.code===void 0?0:r.code,this[Du]=r.reason===void 0?"":r.reason,this[Lu]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Ou]}get reason(){return this[Du]}get wasClean(){return this[Lu]}};Object.defineProperty(ur.prototype,"code",{enumerable:!0});Object.defineProperty(ur.prototype,"reason",{enumerable:!0});Object.defineProperty(ur.prototype,"wasClean",{enumerable:!0});var sn=class extends yt{constructor(e,r={}){super(e),this[Pu]=r.error===void 0?null:r.error,this[Cu]=r.message===void 0?"":r.message}get error(){return this[Pu]}get message(){return this[Cu]}};Object.defineProperty(sn.prototype,"error",{enumerable:!0});Object.defineProperty(sn.prototype,"message",{enumerable:!0});var ai=class extends yt{constructor(e,r={}){super(e),this[xu]=r.data===void 0?null:r.data}get data(){return this[xu]}};Object.defineProperty(ai.prototype,"data",{enumerable:!0});var q0={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[oi]&&i[Nc]===e&&!i[oi])return;let n;if(t==="message")n=function(s,o){let a=new ai("message",{data:o?s:s.toString()});a[nn]=this,qs(e,this,a)};else if(t==="close")n=function(s,o){let a=new ur("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[nn]=this,qs(e,this,a)};else if(t==="error")n=function(s){let o=new sn("error",{error:s,message:s.message});o[nn]=this,qs(e,this,o)};else if(t==="open")n=function(){let s=new yt("open");s[nn]=this,qs(e,this,s)};else return;n[oi]=!!r[oi],n[Nc]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Nc]===e&&!r[oi]){this.removeListener(t,r);break}}};Fu.exports={CloseEvent:ur,ErrorEvent:sn,Event:yt,EventTarget:q0,MessageEvent:ai};function qs(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Js=z((MA,Bu)=>{"use strict";var{tokenChars:ci}=en();function st(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function J0(t){let e=Object.create(null),r=Object.create(null),n=!1,i=!1,s=!1,o,a,c=-1,l=-1,d=-1,p=0;for(;p<t.length;p++)if(l=t.charCodeAt(p),o===void 0)if(d===-1&&ci[l]===1)c===-1&&(c=p);else if(p!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(c,d);l===44?(st(e,f,r),r=Object.create(null)):o=f,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&ci[l]===1)c===-1&&(c=p);else if(l===32||l===9)d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),st(r,t.slice(c,d),!0),l===44&&(st(e,o,r),r=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=t.slice(c,p),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(i){if(ci[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),i=!1}else if(s)if(ci[l]===1)c===-1&&(c=p);else if(l===34&&c!==-1)s=!1,d=p;else if(l===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&t.charCodeAt(p-1)===61)s=!0;else if(d===-1&&ci[l]===1)c===-1&&(c=p);else if(c!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(c,d);n&&(f=f.replace(/\\/g,""),n=!1),st(r,a,f),l===44&&(st(e,o,r),r=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let m=t.slice(c,d);return o===void 0?st(e,m,r):(a===void 0?st(r,m,!0):n?st(r,a,m.replace(/\\/g,"")):st(r,a,m),st(e,o,r)),e}function V0(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Bu.exports={format:V0,parse:J0}});var Xs=z((zA,Ku)=>{"use strict";var Z0=$("events"),K0=$("https"),X0=$("http"),$u=$("net"),Q0=$("tls"),{randomBytes:Y0,createHash:eS}=$("crypto"),{Duplex:BA,Readable:UA}=$("stream"),{URL:Lc}=$("url"),jt=Yr(),tS=xc(),rS=Dc(),{isBlob:nS}=en(),{BINARY_TYPES:Uu,CLOSE_TIMEOUT:iS,EMPTY_BUFFER:Vs,GUID:sS,kForOnEventAttribute:Fc,kListener:oS,kStatusCode:aS,kWebSocket:ce,NOOP:Gu}=wt(),{EventTarget:{addEventListener:cS,removeEventListener:lS}}=Mu(),{format:dS,parse:hS}=Js(),{toBuffer:fS}=ii(),Hu=Symbol("kAborted"),Mc=[8,13],Et=["CONNECTING","OPEN","CLOSING","CLOSED"],uS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,j=class t extends Z0{constructor(e,r,n){super(),this._binaryType=Uu[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Vs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),ju(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Uu.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let i=new tS({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new rS(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[ce]=this,s[ce]=this,e[ce]=this,i.on("conclude",mS),i.on("drain",wS),i.on("error",_S),i.on("message",yS),i.on("ping",ES),i.on("pong",SS),s.onerror=IS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Ju),e.on("data",Ks),e.on("end",Vu),e.on("error",Zu),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[jt.extensionName]&&this._extensions[jt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),qu(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Vs,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Vs,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bc(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[jt.extensionName]||(i.compress=!1),this._sender.send(e||Vs,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){xe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(j,"CONNECTING",{enumerable:!0,value:Et.indexOf("CONNECTING")});Object.defineProperty(j.prototype,"CONNECTING",{enumerable:!0,value:Et.indexOf("CONNECTING")});Object.defineProperty(j,"OPEN",{enumerable:!0,value:Et.indexOf("OPEN")});Object.defineProperty(j.prototype,"OPEN",{enumerable:!0,value:Et.indexOf("OPEN")});Object.defineProperty(j,"CLOSING",{enumerable:!0,value:Et.indexOf("CLOSING")});Object.defineProperty(j.prototype,"CLOSING",{enumerable:!0,value:Et.indexOf("CLOSING")});Object.defineProperty(j,"CLOSED",{enumerable:!0,value:Et.indexOf("CLOSED")});Object.defineProperty(j.prototype,"CLOSED",{enumerable:!0,value:Et.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(j.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(j.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Fc])return e[oS];return null},set(e){for(let r of this.listeners(t))if(r[Fc]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Fc]:!0})}})});j.prototype.addEventListener=cS;j.prototype.removeEventListener=lS;Ku.exports=j;function ju(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:iS,protocolVersion:Mc[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,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=i.autoPong,t._closeTimeout=i.closeTimeout,!Mc.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Mc.join(", ")})`);let s;if(e instanceof Lc)s=e;else try{s=new Lc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(t._redirects===0)throw g;Zs(t,g);return}let l=o?443:80,d=Y0(16).toString("base64"),p=o?K0.request:X0.request,m=new Set,f;if(i.createConnection=i.createConnection||(o?gS:pS),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new jt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=dS({[jt.extensionName]:f.offer()})),r.length){for(let g of r){if(typeof g!="string"||!uS.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){let g=i.path.split(":");i.socketPath=g[0],i.path=g[1]}let u;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[w,E]of Object.entries(g))n.headers[w.toLowerCase()]=E}else if(t.listenerCount("redirect")===0){let g=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,g||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),u=t._req=p(i),t._redirects&&t.emit("redirect",t.url,u)}else u=t._req=p(i);i.timeout&&u.on("timeout",()=>{xe(t,u,"Opening handshake has timed out")}),u.on("error",g=>{u===null||u[Hu]||(u=t._req=null,Zs(t,g))}),u.on("response",g=>{let w=g.headers.location,E=g.statusCode;if(w&&i.followRedirects&&E>=300&&E<400){if(++t._redirects>i.maxRedirects){xe(t,u,"Maximum redirects exceeded");return}u.abort();let v;try{v=new Lc(w,e)}catch{let _=new SyntaxError(`Invalid URL: ${w}`);Zs(t,_);return}ju(t,v,r,n)}else t.emit("unexpected-response",u,g)||xe(t,u,`Unexpected server response: ${g.statusCode}`)}),u.on("upgrade",(g,w,E)=>{if(t.emit("upgrade",g),t.readyState!==j.CONNECTING)return;u=t._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){xe(t,w,"Invalid Upgrade header");return}let h=eS("sha1").update(d+sS).digest("base64");if(g.headers["sec-websocket-accept"]!==h){xe(t,w,"Invalid Sec-WebSocket-Accept header");return}let _=g.headers["sec-websocket-protocol"],S;if(_!==void 0?m.size?m.has(_)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":m.size&&(S="Server sent no subprotocol"),S){xe(t,w,S);return}_&&(t._protocol=_);let k=g.headers["sec-websocket-extensions"];if(k!==void 0){if(!f){xe(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=hS(k)}catch{xe(t,w,"Invalid Sec-WebSocket-Extensions header");return}let I=Object.keys(R);if(I.length!==1||I[0]!==jt.extensionName){xe(t,w,"Server indicated an extension that was not requested");return}try{f.accept(R[jt.extensionName])}catch{xe(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[jt.extensionName]=f}t.setSocket(w,E,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(u,t):u.end()}function Zs(t,e){t._readyState=j.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function pS(t){return t.path=t.socketPath,$u.connect(t)}function gS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=$u.isIP(t.host)?"":t.host),Q0.connect(t)}function xe(t,e,r){t._readyState=j.CLOSING;let n=new Error(r);Error.captureStackTrace(n,xe),e.setHeader?(e[Hu]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zs,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Bc(t,e,r){if(e){let n=nS(e)?e.size:fS(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${Et[t.readyState]})`);process.nextTick(r,n)}}function mS(t,e){let r=this[ce];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[ce]!==void 0&&(r._socket.removeListener("data",Ks),process.nextTick(Wu,r._socket),t===1005?r.close():r.close(t,e))}function wS(){let t=this[ce];t.isPaused||t._socket.resume()}function _S(t){let e=this[ce];e._socket[ce]!==void 0&&(e._socket.removeListener("data",Ks),process.nextTick(Wu,e._socket),e.close(t[aS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function zu(){this[ce].emitClose()}function yS(t,e){this[ce].emit("message",t,e)}function ES(t){let e=this[ce];e._autoPong&&e.pong(t,!this._isServer,Gu),e.emit("ping",t)}function SS(t){this[ce].emit("pong",t)}function Wu(t){t.resume()}function IS(t){let e=this[ce];e.readyState!==j.CLOSED&&(e.readyState===j.OPEN&&(e._readyState=j.CLOSING,qu(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function qu(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Ju(){let t=this[ce];if(this.removeListener("close",Ju),this.removeListener("data",Ks),this.removeListener("end",Vu),t._readyState=j.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[ce]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",zu),t._receiver.on("finish",zu))}function Ks(t){this[ce]._receiver.write(t)||this.pause()}function Vu(){let t=this[ce];t._readyState=j.CLOSING,t._receiver.end(),this.end()}function Zu(){let t=this[ce];this.removeListener("error",Zu),this.on("error",Gu),t&&(t._readyState=j.CLOSING,this.destroy())}});var ep=z((GA,Yu)=>{"use strict";var $A=Xs(),{Duplex:vS}=$("stream");function Xu(t){t.emit("close")}function TS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Qu(t){this.removeListener("error",Qu),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function RS(t,e){let r=!0,n=new vS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&n._readableState.objectMode?s.toString():s;n.push(a)||t.pause()}),t.once("error",function(s){n.destroyed||(r=!1,n.destroy(s))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(Xu,n);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(Xu,n)}),r&&t.terminate()},n._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(i,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(i,s,o)});return}t.send(i,o)},n.on("end",TS),n.on("error",Qu),n}Yu.exports=RS});var Uc=z((HA,tp)=>{"use strict";var{tokenChars:kS}=en();function bS(t){let e=new Set,r=-1,n=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(n===-1&&kS[o]===1)r===-1&&(r=i);else if(i!==0&&(o===32||o===9))n===-1&&r!==-1&&(n=i);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}tp.exports={parse:bS}});var cp=z((WA,ap)=>{"use strict";var AS=$("events"),Qs=$("http"),{Duplex:jA}=$("stream"),{createHash:OS}=$("crypto"),rp=Js(),pr=Yr(),xS=Uc(),PS=Xs(),{CLOSE_TIMEOUT:CS,GUID:DS,kWebSocket:NS}=wt(),LS=/^[+/0-9A-Za-z]{22}==$/,np=0,ip=1,op=2,zc=class extends AS{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:PS,...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=Qs.createServer((n,i)=>{let s=Qs.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=FS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=np}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===op){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(li,this);return}if(e&&this.once("close",e),this._state!==ip)if(this._state=ip,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(li,this):process.nextTick(li,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{li(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,i){r.on("error",sp);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){gr(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){gr(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!LS.test(s)){gr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){gr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){di(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=xS.parse(c)}catch{gr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let m=new pr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=rp.parse(d);f[pr.extensionName]&&(m.accept(f[pr.extensionName]),p[pr.extensionName]=m)}catch{gr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,u,g,w)=>{if(!f)return di(r,u||401,g,w);this.completeUpgrade(p,s,l,e,r,n,i)});return}if(!this.options.verifyClient(m))return di(r,401)}this.completeUpgrade(p,s,l,e,r,n,i)}completeUpgrade(e,r,n,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[NS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>np)return di(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${OS("sha1").update(r+DS).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[pr.extensionName]){let p=e[pr.extensionName].params,m=rp.format({[pr.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
8
+ var Hp=Object.create;var go=Object.defineProperty;var jp=Object.getOwnPropertyDescriptor;var Wp=Object.getOwnPropertyNames;var qp=Object.getPrototypeOf,Jp=Object.prototype.hasOwnProperty;var $=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var Ie=(t,e)=>()=>(t&&(e=t(t=0)),e);var z=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),gi=(t,e)=>{for(var r in e)go(t,r,{get:e[r],enumerable:!0})},Vp=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Wp(e))!Jp.call(t,i)&&i!==r&&go(t,i,{get:()=>e[i],enumerable:!(n=jp(e,i))||n.enumerable});return t};var lt=(t,e,r)=>(r=t!=null?Hp(qp(t)):{},Vp(e||!t||!t.__esModule?go(r,"default",{value:t,enumerable:!0}):r,t));function nl(t){mo=t}function il(t){return wi[mo]<=wi[t]}function yi(t){rl={...t}}function Xp(t){let e=(a,c=2)=>String(a).padStart(c,"0"),r=-t.getTimezoneOffset(),n=r>=0?"+":"-",i=Math.abs(r),s=e(Math.floor(i/60)),o=e(i%60);return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${n}${s}:${o}`}function mi(t,e,r,n){if(wi[t]<wi[mo])return;let i=JSON.stringify({ts:Xp(new Date),level:t,module:e,msg:r,...rl,...n});t==="error"||t==="warn"?Kp.write(`${i}
9
+ `):Zp.write(`${i}
10
+ `)}function x(t){return{debug:(e,r)=>mi("debug",t,e,r),info:(e,r)=>mi("info",t,e,r),warn:(e,r)=>mi("warn",t,e,r),error:(e,r)=>mi("error",t,e,r),child:e=>x(`${t}.${e}`)}}var wi,mo,Zp,Kp,rl,F=Ie(()=>{"use strict";wi={debug:10,info:20,warn:30,error:40},mo=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Zp=process.stdout,Kp=process.stderr,rl={}});import{execFile as Qp,spawn as Yp,spawnSync as hv}from"node:child_process";import{promisify as eg}from"node:util";function rg(t){if(process.platform!=="win32")return!1;if(sl.test(t))return!0;let r=(t.split(/[/\\]/).pop()??t).replace(sl,"").toLowerCase();return tg.has(r)}function ol(t,e){if(process.platform!=="win32")return e??{};let r={...e??{}};return rg(t)&&r.shell===void 0&&(r.shell=!0),r.windowsHide===void 0&&(r.windowsHide=!0),r}function Je(t,e=[],r={}){return Yp(t,e,ol(t,r))}function _i(t,e=[],r={}){return ng(t,e,ol(t,r))}var tg,sl,ng,Wt=Ie(()=>{"use strict";tg=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp"]),sl=/\.(cmd|bat|ps1)$/i;ng=eg(Qp)});var _,_e=Ie(()=>{"use strict";_=class extends Error{code;retriable;cause;constructor(e,r,n){super(r),this.name="BridgeError",this.code=e,this.retriable=n?.retriable??!1,n?.cause!==void 0&&(this.cause=n.cause)}}});var fl={};gi(fl,{_resetAcpInstallerForTests:()=>ug,_resetInstallTimeoutsForTests:()=>hg,_setBinaryPathCacheForTests:()=>gg,_setInFlightForTests:()=>pg,_setInstallTimeoutsForTests:()=>dg,buildInstallFailureMessage:()=>hl,ensureAcpInstalled:()=>_r,formatExecError:()=>ll,getAcpBinaryPath:()=>ln,getAcpPackageSpec:()=>cg,getInFlightInstall:()=>_o,npmInstallGlobal:()=>dl,pickWhichLine:()=>Ii,probeAcpVersion:()=>fg,resolveAcpCommand:()=>dn});import{readFile as ig,realpath as sg,stat as og}from"node:fs/promises";import{dirname as wo,join as ag}from"node:path";function cg(t){let e=yo[t];if(e)return`${e.npmPackage}@${e.versionSpec}`}function dg(t,e){Ei=t,Si=e}function hg(){Ei=5e4,Si=5e3}function ll(t){if(t==null||typeof t!="object")return String(t);let e=t,r=[];e.message&&r.push(e.message),e.code!==void 0&&e.code!==null&&r.push(`code=${e.code}`),e.signal&&r.push(`signal=${e.signal}`);let n=e.stderr?.toString().trim();n&&r.push(`stderr=${n.slice(0,2e3)}`);let i=e.stdout?.toString().trim();return i&&r.push(`stdout=${i.slice(0,2e3)}`),r.length>0?r.join(" | "):String(t)}async function al(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:r}=await _i(e,[t],{timeout:lg});return Ii(r)}catch{return}}function Ii(t){let e=t.split(/\r?\n/).map(n=>n.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let r=n=>e.find(i=>i.toLowerCase().endsWith(n));return r(".cmd")??r(".exe")??r(".bat")??r(".ps1")??e[0]}async function fg(t){let e=yo[t];if(!e)return;let r=ln(t);if(!r){me.warn("acp wrapper probe: binary path cache empty",{framework:t,binary:e.binary,hint:"ensureAcpInstalled \u6CA1\u8DD1\u8FC7 / \u88C5\u5931\u8D25 / \u4E4B\u524D negative cache 5min \u5185"});return}let n;try{n=await sg(r)}catch(s){me.warn("acp wrapper probe: realpath failed (symlink target \u4E0D\u5B58\u5728?)",{framework:t,binaryPath:r,err:String(s)});return}let i=wo(n);for(let s=0;s<cl;s++){let o=ag(i,"package.json");try{if(!(await og(o)).isFile()){i=wo(i);continue}let l=await ig(o,"utf8"),d=JSON.parse(l);if(d.name===e.npmPackage){if(typeof d.version=="string"&&d.version.length>0)return d.version;me.warn("acp wrapper probe: package.json \u627E\u5230\u4F46 version \u5B57\u6BB5\u7F3A",{framework:t,packageJsonPath:o});return}}catch(c){let l=c;l.code!=="ENOENT"&&me.warn("acp wrapper probe: package.json \u8BFB\u53D6\u5F02\u5E38",{framework:t,candidate:o,errCode:l?.code,err:String(c)})}let a=wo(i);if(a===i)break;i=a}me.warn("acp wrapper probe: \u627E\u4E0D\u5230\u5339\u914D name \u7684 package.json (\u4E0A\u6EAF\u5230 max depth)",{framework:t,binaryPath:r,realBinary:n,expectedName:e.npmPackage,maxDepth:cl})}async function dl(t,e,r){let n=`${t}@${e}`;me.info("npm install -g start",{npmPackage:t,versionSpec:e});let i=Date.now(),s=process.platform==="win32";return new Promise((o,a)=>{let c=Je("npm",["install","-g",n],{stdio:["ignore","pipe","pipe"],...s?{}:{detached:!0}});if(!c.pid){a(new Error(`failed to spawn npm: no pid (npmPackage=${t})`));return}let l=c.pid,d=10*1024*1024,p=[],m=[],f=0,u=0;c.stdout?.on("data",y=>{f+=y.length,f<d&&p.push(y)}),c.stderr?.on("data",y=>{u+=y.length,u<d&&m.push(y)});let g="running",w,E=y=>{try{return s?c.kill(y):process.kill(-l,y),!0}catch(S){return me.warn("npm install: kill failed (process already dead?)",{npmPackage:t,pid:l,sig:y,err:String(S)}),!1}},v=setTimeout(()=>{g="terminating",me.warn("npm install timeout, sending SIGTERM to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,timeoutMs:Ei,graceMs:Si,stdoutBytes:f,stderrBytes:u}),E("SIGTERM"),w=setTimeout(()=>{g="killing",me.warn("npm install SIGTERM grace expired, escalating to SIGKILL",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,stdoutBytes:f,stderrBytes:u}),E("SIGKILL")},Si)},Ei),h=()=>{g="aborted",me.warn("npm install externally aborted, sending SIGKILL to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i}),E("SIGKILL")};r&&(r.aborted?h():r.addEventListener("abort",h,{once:!0})),c.on("error",y=>{clearTimeout(v),w&&clearTimeout(w),r?.removeEventListener("abort",h),me.warn("npm install spawn error",{npmPackage:t,versionSpec:e,pid:l,err:String(y)}),a(new Error(`spawn npm failed: ${String(y)}`))}),c.on("close",(y,S)=>{clearTimeout(v),w&&clearTimeout(w),r?.removeEventListener("abort",h);let k=Buffer.concat(p).toString("utf8"),R=Buffer.concat(m).toString("utf8"),I=Date.now()-i;if(y===0&&g==="running"){me.info("npm install -g done",{npmPackage:t,versionSpec:e,elapsedMs:I}),o();return}me.warn("npm install -g exited non-success",{npmPackage:t,versionSpec:e,pid:l,phase:g,exitCode:y,signal:S,elapsedMs:I,stdoutBytes:f,stderrBytes:u});let T=Object.assign(new Error(`Command failed: npm install -g ${n}`+(S?` (killed by ${S})`:"")+(y!==null?` (exit ${y})`:"")+(g!=="running"?` (phase=${g})`:"")),{code:y,signal:S,stderr:R,stdout:k});a(T)})})}function hl(t){let{framework:e,npmPackage:r,versionSpec:n,command:i,reason:s,elapsedMs:o}=t;return["ACP wrapper \u5B89\u88C5\u5931\u8D25",`Framework: ${e}`,`Package: ${r}@${n}`,`\u6267\u884C\u547D\u4EE4: ${i}`,`\u5931\u8D25\u539F\u56E0: ${s}`,`\u8017\u65F6: ${o}ms`,"","\u6392\u67E5\u5EFA\u8BAE:"," 1. \u68C0\u67E5\u7F51\u7EDC: curl -v https://registry.npmjs.org"," 2. \u67E5\u770B\u5F53\u524D npm \u6E90: npm config get registry"," 3. \u56FD\u5185\u7F51\u7EDC\u5EFA\u8BAE\u5207\u955C\u50CF\u6E90:"," npm config set registry https://registry.npmmirror.com/"].join(`
11
+ `)}async function _r(t,e){let r=yo[t];if(!r)throw new _("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let n=wr.get(t);if(n)return n;let i=yr.get(t);if(i)return i;let s=`npm install -g ${r.npmPackage}@${r.versionSpec}`,o=(c,l,d)=>new _("AGENT_DEPENDENCY_INSTALL_FAILED",hl({framework:t,npmPackage:r.npmPackage,versionSpec:r.versionSpec,command:s,reason:c,elapsedMs:l}),d!==void 0?{cause:d}:{}),a=(async()=>{let c=await al(r.binary);if(c)return wr.set(t,c),me.info("acp wrapper found on PATH",{binary:r.binary,path:c}),c;let l=Date.now();try{await dl(r.npmPackage,r.versionSpec,e)}catch(p){let m=ll(p);throw me.warn("acp wrapper install failed",{framework:t,npmPackage:r.npmPackage,versionSpec:r.versionSpec,binary:r.binary,err:m}),o(m,Date.now()-l,p)}let d=await al(r.binary);if(!d)throw me.warn("acp wrapper installed but binary not found on PATH",{framework:t,npmPackage:r.npmPackage,versionSpec:r.versionSpec,binary:r.binary}),o(`npm install \u6210\u529F\u4F46 \`${process.platform==="win32"?"where":"which"} ${r.binary}\` \u627E\u4E0D\u5230 binary (npm prefix \u53EF\u80FD\u672A\u52A0\u5165 PATH, \u6216\u88AB\u88C5\u5230\u4E86 nvm/asdf \u522B\u7684\u7248\u672C\u4E0B)`,Date.now()-l);return wr.set(t,d),d})().finally(()=>{yr.delete(t)});return yr.set(t,a),a}function ln(t){return wr.get(t)}function dn(t,e){if(e)return e;let r=ln(t);if(!r)throw new _("BRIDGE_INTERNAL",`${t} ACP wrapper binary path cache miss (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return r}function _o(t){return yr.get(t)}function ug(){wr.clear(),yr.clear()}function pg(t,e){yr.set(t,e)}function gg(t,e){wr.set(t,e)}var me,yo,Ei,Si,lg,wr,yr,cl,qt=Ie(()=>{"use strict";Wt();_e();F();me=x("agents.acp-installer"),yo={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp",versionSpec:"^0.37"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp",versionSpec:"^0.15"}};Ei=5e4,Si=5e3,lg=5e3;wr=new Map,yr=new Map;cl=6});import{chmod as wg,mkdir as yg,readFile as _g,rename as gl,writeFile as ml}from"node:fs/promises";import{dirname as Eg}from"node:path";async function Er(t){try{let e=await _g(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function vi(t,e,r){await yg(Eg(t),{recursive:!0});let n=`${JSON.stringify(e,null,2)}
12
+ `,i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{r?.mode!==void 0?await ml(i,n,{encoding:"utf8",mode:r.mode}):await ml(i,n,"utf8"),await gl(i,t),r?.mode!==void 0&&await wg(t,r.mode)}catch(s){await gl(i,i).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(i,{force:!0}).catch(()=>{}),s}}var Ti=Ie(()=>{"use strict"});import{promises as wl}from"node:fs";import{homedir as Sg}from"node:os";import{sep as Ig,join as le,resolve as yl}from"node:path";function M(t){let e=t??Sg(),r=le(e,".coze"),n=le(r,"bridge"),i=le(n,"lib");return{cozeRoot:r,bridgeRoot:n,libDir:i,libEntry:le(i,"index.js"),binDir:le(n,"bin"),pidFile:le(n,"bridge.pid"),portFile:le(n,"bridge.port"),tokenFile:le(n,"bridge.token"),patTokenFile:le(n,"pat-token"),logFile:le(n,"bridge.log"),installLock:le(n,"install.lock"),configFile:le(n,"config.json"),agentsRoot:le(r,"agents")}}function dt(t,e=M()){let r=le(e.agentsRoot,t);return{root:r,config:le(r,"config.json"),workspace:le(r,"workspace"),logs:le(r,"logs")}}async function hn(t,e){let r=await wl.realpath(yl(t)).catch(()=>null);if(!r)return!1;let n=await wl.realpath(yl(e)).catch(()=>null);if(!n)return!1;let i=process.platform==="win32"?r.toLowerCase():r,s=process.platform==="win32"?n.toLowerCase():n;return i===s||i.startsWith(s+Ig)}var de=Ie(()=>{"use strict"});var bi={};gi(bi,{AGENT_CONFIG_FILE_MODE:()=>Ri,enforceAgentConfigMode:()=>Rg,loadAgentConfig:()=>he,persistAgentSessions:()=>fn,persistAgentSkills:()=>ki,saveAgentConfig:()=>ve});import{chmod as vg,stat as Tg}from"node:fs/promises";function he(t,e){return Er(dt(t,e).config)}function ve(t,e){return vi(dt(t.agentId,e).config,t,{mode:Ri})}async function Rg(t,e){if(process.platform==="win32")return;let r=dt(t,e).config;try{let n=await Tg(r);if(!n.isFile())return;let i=n.mode&511;i!==Ri&&(await vg(r,Ri),_l.warn("agent config mode auto-corrected to 0600",{path:r,from:i.toString(8)}))}catch(n){if(n.code==="ENOENT")return;_l.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(n)})}}async function fn(t,e,r){let n=await he(t,r);n&&(n.sessions=Object.fromEntries(e),await ve(n,r))}async function ki(t,e,r){let n=await he(t,r);n&&(n.skills=e,await ve(n,r))}var _l,Ri,vt=Ie(()=>{"use strict";Ti();F();de();_l=x("agent-config"),Ri=384});var So=z((Gv,vl)=>{vl.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 xi=z(Rl=>{var Tl={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 Og(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Tl))Rl[t]=Og(Tl[t])});var Ol=z((jv,xl)=>{var Pg=$("fs"),ee=$("path"),kl=So(),Cg=xi(),Dg=typeof process=="object"&&process.platform==="win32",bl=t=>typeof t=="object"&&t!==null,Al=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function Z(t){this.sep=ee.sep,this.fs=Pg,bl(t)&&bl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}xl.exports=Z;Z.prototype.makeDir=function(t){let e=this;function r(n){let i=n.split(e.sep)[0];n.split(e.sep).forEach(function(s){if(!(!s||s.substr(-1,1)===":")){i+=e.sep+s;var o;try{o=e.fs.statSync(i)}catch(a){if(a.message&&a.message.startsWith("ENOENT"))e.fs.mkdirSync(i);else throw a}if(o&&o.isFile())throw Cg.FILE_IN_THE_WAY(`"${i}"`)}})}r(t)};Z.prototype.writeFileTo=function(t,e,r,n){let i=this;if(i.fs.existsSync(t)){if(!r)return!1;var s=i.fs.statSync(t);if(s.isDirectory())return!1}var o=ee.dirname(t);i.fs.existsSync(o)||i.makeDir(o);var a;try{a=i.fs.openSync(t,"w",438)}catch{i.fs.chmodSync(t,438),a=i.fs.openSync(t,"w",438)}if(a)try{i.fs.writeSync(a,e,0,e.length,0)}finally{i.fs.closeSync(a)}return i.fs.chmodSync(t,n||438),!0};Z.prototype.writeFileToAsync=function(t,e,r,n,i){typeof n=="function"&&(i=n,n=void 0);let s=this;s.fs.exists(t,function(o){if(o&&!r)return i(!1);s.fs.stat(t,function(a,c){if(o&&c.isDirectory())return i(!1);var l=ee.dirname(t);s.fs.exists(l,function(d){d||s.makeDir(l),s.fs.open(t,"w",438,function(p,m){p?s.fs.chmod(t,438,function(){s.fs.open(t,"w",438,function(f,u){s.fs.write(u,e,0,e.length,0,function(){s.fs.close(u,function(){s.fs.chmod(t,n||438,function(){i(!0)})})})})}):m?s.fs.write(m,e,0,e.length,0,function(){s.fs.close(m,function(){s.fs.chmod(t,n||438,function(){i(!0)})})}):s.fs.chmod(t,n||438,function(){i(!0)})})})})})};Z.prototype.findFiles=function(t){let e=this;function r(n,i,s){typeof i=="boolean"&&(s=i,i=void 0);let o=[];return e.fs.readdirSync(n).forEach(function(a){let c=ee.join(n,a),l=e.fs.statSync(c);(!i||i.test(c))&&o.push(ee.normalize(c)+(l.isDirectory()?e.sep:"")),l.isDirectory()&&s&&(o=o.concat(r(c,i,s)))}),o}return r(t,void 0,!0)};Z.prototype.findFilesAsync=function(t,e){let r=this,n=[];r.fs.readdir(t,function(i,s){if(i)return e(i);let o=s.length;if(!o)return e(null,n);s.forEach(function(a){a=ee.join(t,a),r.fs.stat(a,function(c,l){if(c)return e(c);l&&(n.push(ee.normalize(a)+(l.isDirectory()?r.sep:"")),l.isDirectory()?r.findFilesAsync(a,function(d,p){if(d)return e(d);n=n.concat(p),--o||e(null,n)}):--o||e(null,n))})})})};Z.prototype.getAttributes=function(){};Z.prototype.setAttributes=function(){};Z.crc32update=function(t,e){return Al[(t^e)&255]^t>>>8};Z.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=Z.crc32update(r,t[n++]);return~r>>>0};Z.methodToString=function(t){switch(t){case kl.STORED:return"STORED ("+t+")";case kl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Z.canonical=function(t){if(!t)return"";let e=ee.posix.normalize("/"+t.split("\\").join("/"));return ee.join(".",e)};Z.zipnamefix=function(t){if(!t)return"";let e=ee.posix.normalize("/"+t.split("\\").join("/"));return ee.posix.join(".",e)};Z.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};Z.sanitize=function(t,e){t=ee.resolve(ee.normalize(t));for(var r=e.split("/"),n=0,i=r.length;n<i;n++){var s=ee.normalize(ee.join(t,r.slice(n,i).join(ee.sep)));if(s.indexOf(t)===0)return s}return ee.normalize(ee.join(t,ee.basename(e)))};Z.toBuffer=function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)};Z.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};Z.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)};Z.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};Z.isWin=Dg;Z.crcTable=Al});var Cl=z((Wv,Pl)=>{var Ng=$("path");Pl.exports=function(t,{fs:e}){var r=t||"",n=s(),i=null;function s(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return r&&e.existsSync(r)?(i=e.statSync(r),n.directory=i.isDirectory(),n.mtime=i.mtime,n.atime=i.atime,n.executable=(73&i.mode)!==0,n.readonly=(128&i.mode)===0,n.hidden=Ng.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Nl=z((qv,Dl)=>{Dl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var vr=z((Jv,Ir)=>{Ir.exports=Ol();Ir.exports.Constants=So();Ir.exports.Errors=xi();Ir.exports.FileAttr=Cl();Ir.exports.decoder=Nl()});var Fl=z((Vv,Ll)=>{var Tt=vr(),b=Tt.Constants;Ll.exports=function(){var t=20,e=10,r=0,n=0,i=0,s=0,o=0,a=0,c=0,l=0,d=0,p=0,m=0,f=0,u=0;t|=Tt.isWin?2560:768,r|=b.FLG_EFS;let g={extraLen:0},w=h=>Math.max(0,h)>>>0,E=h=>Math.max(0,h)&65535,v=h=>Math.max(0,h)&255;return i=Tt.fromDate2DOS(new Date),{get made(){return t},set made(h){t=h},get version(){return e},set version(h){e=h},get flags(){return r},set flags(h){r=h},get flags_efs(){return(r&b.FLG_EFS)>0},set flags_efs(h){h?r|=b.FLG_EFS:r&=~b.FLG_EFS},get flags_desc(){return(r&b.FLG_DESC)>0},set flags_desc(h){h?r|=b.FLG_DESC:r&=~b.FLG_DESC},get method(){return n},set method(h){switch(h){case b.STORED:this.version=10;case b.DEFLATED:default:this.version=20}n=h},get time(){return Tt.fromDOS2Date(this.timeval)},set time(h){h=new Date(h),this.timeval=Tt.fromDate2DOS(h)},get timeval(){return i},set timeval(h){i=w(h)},get timeHighByte(){return v(i>>>8)},get crc(){return s},set crc(h){s=w(h)},get compressedSize(){return o},set compressedSize(h){o=w(h)},get size(){return a},set size(h){a=w(h)},get fileNameLength(){return c},set fileNameLength(h){c=h},get extraLength(){return l},set extraLength(h){l=h},get extraLocalLength(){return g.extraLen},set extraLocalLength(h){g.extraLen=h},get commentLength(){return d},set commentLength(h){d=h},get diskNumStart(){return p},set diskNumStart(h){p=w(h)},get inAttr(){return m},set inAttr(h){m=w(h)},get attr(){return f},set attr(h){f=w(h)},get fileAttr(){return(f||0)>>16&4095},get offset(){return u},set offset(h){u=w(h)},get encrypted(){return(r&b.FLG_ENC)===b.FLG_ENC},get centralHeaderSize(){return b.CENHDR+c+l+d},get realDataOffset(){return u+b.LOCHDR+g.fnameLen+g.extraLen},get localHeader(){return g},loadLocalHeaderFromBinary:function(h){var y=h.slice(u,u+b.LOCHDR);if(y.readUInt32LE(0)!==b.LOCSIG)throw Tt.Errors.INVALID_LOC();g.version=y.readUInt16LE(b.LOCVER),g.flags=y.readUInt16LE(b.LOCFLG),g.flags_desc=(g.flags&b.FLG_DESC)>0,g.method=y.readUInt16LE(b.LOCHOW),g.time=y.readUInt32LE(b.LOCTIM),g.crc=y.readUInt32LE(b.LOCCRC),g.compressedSize=y.readUInt32LE(b.LOCSIZ),g.size=y.readUInt32LE(b.LOCLEN),g.fnameLen=y.readUInt16LE(b.LOCNAM),g.extraLen=y.readUInt16LE(b.LOCEXT);let S=u+b.LOCHDR+g.fnameLen,k=S+g.extraLen;return h.slice(S,k)},loadFromBinary:function(h){if(h.length!==b.CENHDR||h.readUInt32LE(0)!==b.CENSIG)throw Tt.Errors.INVALID_CEN();t=h.readUInt16LE(b.CENVEM),e=h.readUInt16LE(b.CENVER),r=h.readUInt16LE(b.CENFLG),n=h.readUInt16LE(b.CENHOW),i=h.readUInt32LE(b.CENTIM),s=h.readUInt32LE(b.CENCRC),o=h.readUInt32LE(b.CENSIZ),a=h.readUInt32LE(b.CENLEN),c=h.readUInt16LE(b.CENNAM),l=h.readUInt16LE(b.CENEXT),d=h.readUInt16LE(b.CENCOM),p=h.readUInt16LE(b.CENDSK),m=h.readUInt16LE(b.CENATT),f=h.readUInt32LE(b.CENATX),u=h.readUInt32LE(b.CENOFF)},localHeaderToBinary:function(){var h=Buffer.alloc(b.LOCHDR);return h.writeUInt32LE(b.LOCSIG,0),h.writeUInt16LE(e,b.LOCVER),h.writeUInt16LE(r,b.LOCFLG),h.writeUInt16LE(n,b.LOCHOW),h.writeUInt32LE(i,b.LOCTIM),h.writeUInt32LE(s,b.LOCCRC),h.writeUInt32LE(o,b.LOCSIZ),h.writeUInt32LE(a,b.LOCLEN),h.writeUInt16LE(c,b.LOCNAM),h.writeUInt16LE(g.extraLen,b.LOCEXT),h},centralHeaderToBinary:function(){var h=Buffer.alloc(b.CENHDR+c+l+d);return h.writeUInt32LE(b.CENSIG,0),h.writeUInt16LE(t,b.CENVEM),h.writeUInt16LE(e,b.CENVER),h.writeUInt16LE(r,b.CENFLG),h.writeUInt16LE(n,b.CENHOW),h.writeUInt32LE(i,b.CENTIM),h.writeUInt32LE(s,b.CENCRC),h.writeUInt32LE(o,b.CENSIZ),h.writeUInt32LE(a,b.CENLEN),h.writeUInt16LE(c,b.CENNAM),h.writeUInt16LE(l,b.CENEXT),h.writeUInt16LE(d,b.CENCOM),h.writeUInt16LE(p,b.CENDSK),h.writeUInt16LE(m,b.CENATT),h.writeUInt32LE(f,b.CENATX),h.writeUInt32LE(u,b.CENOFF),h},toJSON:function(){let h=function(y){return y+" bytes"};return{made:t,version:e,flags:r,method:Tt.methodToString(n),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:h(o),size:h(a),fileNameLength:h(c),extraLength:h(l),commentLength:h(d),diskNumStart:p,inAttr:m,attr:f,offset:u,centralHeaderSize:h(b.CENHDR+c+l+d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Bl=z((Zv,Ml)=>{var Tr=vr(),W=Tr.Constants;Ml.exports=function(){var t=0,e=0,r=0,n=0,i=0;return{get diskEntries(){return t},set diskEntries(s){t=e=s},get totalEntries(){return e},set totalEntries(s){e=t=s},get size(){return r},set size(s){r=s},get offset(){return n},set offset(s){n=s},get commentLength(){return i},set commentLength(s){i=s},get mainHeaderSize(){return W.ENDHDR+i},loadFromBinary:function(s){if((s.length!==W.ENDHDR||s.readUInt32LE(0)!==W.ENDSIG)&&(s.length<W.ZIP64HDR||s.readUInt32LE(0)!==W.ZIP64SIG))throw Tr.Errors.INVALID_END();s.readUInt32LE(0)===W.ENDSIG?(t=s.readUInt16LE(W.ENDSUB),e=s.readUInt16LE(W.ENDTOT),r=s.readUInt32LE(W.ENDSIZ),n=s.readUInt32LE(W.ENDOFF),i=s.readUInt16LE(W.ENDCOM)):(t=Tr.readBigUInt64LE(s,W.ZIP64SUB),e=Tr.readBigUInt64LE(s,W.ZIP64TOT),r=Tr.readBigUInt64LE(s,W.ZIP64SIZE),n=Tr.readBigUInt64LE(s,W.ZIP64OFF),i=0)},toBinary:function(){var s=Buffer.alloc(W.ENDHDR+i);return s.writeUInt32LE(W.ENDSIG,0),s.writeUInt32LE(0,4),s.writeUInt16LE(t,W.ENDSUB),s.writeUInt16LE(e,W.ENDTOT),s.writeUInt32LE(r,W.ENDSIZ),s.writeUInt32LE(n,W.ENDOFF),s.writeUInt16LE(i,W.ENDCOM),s.fill(" ",W.ENDHDR),s},toJSON:function(){let s=function(o,a){let c=o.toString(16).toUpperCase();for(;c.length<a;)c="0"+c;return"0x"+c};return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:s(n,4),commentLength:i}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var vo=z(Io=>{Io.EntryHeader=Fl();Io.MainHeader=Bl()});var zl=z((Xv,Ul)=>{Ul.exports=function(t){var e=$("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,r)},deflateAsync:function(n){var i=e.createDeflateRaw(r),s=[],o=0;i.on("data",function(a){s.push(a),o+=a.length}),i.on("end",function(){var a=Buffer.alloc(o),c=0;a.fill(0);for(var l=0;l<s.length;l++){var d=s[l];d.copy(a,c),c+=d.length}n&&n(a)}),i.end(t)}}}});var Gl=z((Qv,$l)=>{var Lg=+(process.versions?process.versions.node:"").split(".")[0]||0;$l.exports=function(t,e){var r=$("zlib");let n=Lg>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return r.inflateRawSync(t,n)},inflateAsync:function(i){var s=r.createInflateRaw(n),o=[],a=0;s.on("data",function(c){o.push(c),a+=c.length}),s.on("end",function(){var c=Buffer.alloc(a),l=0;c.fill(0);for(var d=0;d<o.length;d++){var p=o[d];p.copy(c,l),l+=p.length}i&&i(c)}),s.end(t)}}}});var Jl=z((Yv,ql)=>{"use strict";var{randomFillSync:Hl}=$("crypto"),Fg=xi(),Mg=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Wl=(t,e)=>Math.imul(t,e)>>>0,jl=(t,e)=>Mg[(t^e)&255]^t>>>8,un=()=>typeof Hl=="function"?Hl(Buffer.alloc(12)):un.node();un.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var Oi={genSalt:un};function Pi(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}Pi.prototype.updateKeys=function(t){let e=this.keys;return e[0]=jl(e[0],t),e[1]+=e[0]&255,e[1]=Wl(e[1],134775813)+1,e[2]=jl(e[2],e[1]>>>24),t};Pi.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Wl(t,t^1)>>8&255};function Bg(t){let e=new Pi(t);return function(r){let n=Buffer.alloc(r.length),i=0;for(let s of r)n[i++]=e.updateKeys(s^e.next());return n}}function Ug(t){let e=new Pi(t);return function(r,n,i=0){n||(n=Buffer.alloc(r.length));for(let s of r){let o=e.next();n[i++]=s^o,e.updateKeys(s)}return n}}function zg(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=Bg(r),i=n(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw Fg.WRONG_PASSWORD();return n(t.slice(12))}function $g(t){Buffer.isBuffer(t)&&t.length>=12?Oi.genSalt=function(){return t.slice(0,12)}:t==="node"?Oi.genSalt=un.node:Oi.genSalt=un}function Gg(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=Ug(r),s=Oi.genSalt();s[11]=e.crc>>>24&255,n&&(s[10]=e.crc>>>16&255);let o=Buffer.alloc(t.length+12);return i(s,o),i(t,o,12)}ql.exports={decrypt:zg,encrypt:Gg,_salter:$g}});var Vl=z(Ci=>{Ci.Deflater=zl();Ci.Inflater=Gl();Ci.ZipCrypto=Jl()});var Ro=z((tT,Zl)=>{var B=vr(),Hg=vo(),K=B.Constants,To=Vl();Zl.exports=function(t,e){var r=new Hg.EntryHeader,n=Buffer.alloc(0),i=Buffer.alloc(0),s=!1,o=null,a=Buffer.alloc(0),c=Buffer.alloc(0),l=!0;let d=t,p=typeof d.decoder=="object"?d.decoder:B.decoder;l=p.hasOwnProperty("efs")?p.efs:!1;function m(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(c=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}function f(h){if(!r.flags_desc&&!r.localHeader.flags_desc){if(B.crc32(h)!==r.localHeader.crc)return!1}else{let y={},S=r.realDataOffset+r.compressedSize;if(e.readUInt32LE(S)==K.LOCSIG||e.readUInt32LE(S)==K.CENSIG)throw B.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(S)==K.EXTSIG)y.crc=e.readUInt32LE(S+K.EXTCRC),y.compressedSize=e.readUInt32LE(S+K.EXTSIZ),y.size=e.readUInt32LE(S+K.EXTLEN);else if(e.readUInt16LE(S+12)===19280)y.crc=e.readUInt32LE(S+K.EXTCRC-4),y.compressedSize=e.readUInt32LE(S+K.EXTSIZ-4),y.size=e.readUInt32LE(S+K.EXTLEN-4);else throw B.Errors.DESCRIPTOR_UNKNOWN();if(y.compressedSize!==r.compressedSize||y.size!==r.size||y.crc!==r.crc)throw B.Errors.DESCRIPTOR_FAULTY();if(B.crc32(h)!==y.crc)return!1}return!0}function u(h,y,S){if(typeof y>"u"&&typeof h=="string"&&(S=h,h=void 0),s)return h&&y&&y(Buffer.alloc(0),B.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var k=m();if(k.length===0)return h&&y&&y(k),k;if(r.encrypted){if(typeof S!="string"&&!Buffer.isBuffer(S))throw B.Errors.INVALID_PASS_PARAM();k=To.ZipCrypto.decrypt(k,r,S)}var R=Buffer.alloc(r.size);switch(r.method){case B.Constants.STORED:if(k.copy(R),f(R))return h&&y&&y(R),R;throw h&&y&&y(R,B.Errors.BAD_CRC()),B.Errors.BAD_CRC();case B.Constants.DEFLATED:var I=new To.Inflater(k,r.size);if(h)I.inflateAsync(function(T){T.copy(T,0),y&&(f(T)?y(T):y(T,B.Errors.BAD_CRC()))});else{if(I.inflate(R).copy(R,0),!f(R))throw B.Errors.BAD_CRC(`"${p.decode(n)}"`);return R}break;default:throw h&&y&&y(Buffer.alloc(0),B.Errors.UNKNOWN_METHOD()),B.Errors.UNKNOWN_METHOD()}}function g(h,y){if((!o||!o.length)&&Buffer.isBuffer(e))return h&&y&&y(m()),m();if(o.length&&!s){var S;switch(r.method){case B.Constants.STORED:return r.compressedSize=r.size,S=Buffer.alloc(o.length),o.copy(S),h&&y&&y(S),S;default:case B.Constants.DEFLATED:var k=new To.Deflater(o);if(h)k.deflateAsync(function(I){S=Buffer.alloc(I.length),r.compressedSize=I.length,I.copy(S),y&&y(S)});else{var R=k.deflate();return r.compressedSize=R.length,R}k=null;break}}else if(h&&y)y(Buffer.alloc(0));else return Buffer.alloc(0)}function w(h,y){return B.readBigUInt64LE(h,y)}function E(h){try{for(var y=0,S,k,R;y+4<h.length;)S=h.readUInt16LE(y),y+=2,k=h.readUInt16LE(y),y+=2,R=h.slice(y,y+k),y+=k,K.ID_ZIP64===S&&v(R)}catch{throw B.Errors.EXTRA_FIELD_PARSE_ERROR()}}function v(h){var y,S,k,R;h.length>=K.EF_ZIP64_SCOMP&&(y=w(h,K.EF_ZIP64_SUNCOMP),r.size===K.EF_ZIP64_OR_32&&(r.size=y)),h.length>=K.EF_ZIP64_RHO&&(S=w(h,K.EF_ZIP64_SCOMP),r.compressedSize===K.EF_ZIP64_OR_32&&(r.compressedSize=S)),h.length>=K.EF_ZIP64_DSN&&(k=w(h,K.EF_ZIP64_RHO),r.offset===K.EF_ZIP64_OR_32&&(r.offset=k)),h.length>=K.EF_ZIP64_DSN+4&&(R=h.readUInt32LE(K.EF_ZIP64_DSN),r.diskNumStart===K.EF_ZIP64_OR_16&&(r.diskNumStart=R))}return{get entryName(){return p.decode(n)},get rawEntryName(){return n},set entryName(h){n=B.toBuffer(h,p.encode);var y=n[n.length-1];s=y===47||y===92,r.fileNameLength=n.length},get efs(){return typeof l=="function"?l(this.entryName):l},get extra(){return a},set extra(h){a=h,r.extraLength=h.length,E(h)},get comment(){return p.decode(i)},set comment(h){if(i=B.toBuffer(h,p.encode),r.commentLength=i.length,i.length>65535)throw B.Errors.COMMENT_TOO_LONG()},get name(){var h=p.decode(n);return s?h.substr(h.length-1).split("/").pop():h.split("/").pop()},get isDirectory(){return s},getCompressedData:function(){return g(!1,null)},getCompressedDataAsync:function(h){g(!0,h)},setData:function(h){o=B.toBuffer(h,B.decoder.encode),!s&&o.length?(r.size=o.length,r.method=B.Constants.DEFLATED,r.crc=B.crc32(h),r.changed=!0):r.method=B.Constants.STORED},getData:function(h){return r.changed?o:u(!1,null,h)},getDataAsync:function(h,y){r.changed?h(o):u(!0,h,y)},set attr(h){r.attr=h},get attr(){return r.attr},set header(h){r.loadFromBinary(h)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=a.length;var h=r.centralHeaderToBinary(),y=B.Constants.CENHDR;return n.copy(h,y),y+=n.length,a.copy(h,y),y+=r.extraLength,i.copy(h,y),h},packLocalHeader:function(){let h=0;r.flags_efs=this.efs,r.extraLocalLength=c.length;let y=r.localHeaderToBinary(),S=Buffer.alloc(y.length+n.length+r.extraLocalLength);return y.copy(S,h),h+=y.length,n.copy(S,h),h+=n.length,c.copy(S,h),h+=c.length,S},toJSON:function(){let h=function(y){return"<"+(y&&y.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:h(e),data:h(o)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ql=z((rT,Xl)=>{var Kl=Ro(),jg=vo(),fe=vr();Xl.exports=function(t,e){var r=[],n={},i=Buffer.alloc(0),s=new jg.MainHeader,o=!1,a=null;let c=new Set,l=e,{noSort:d,decoder:p}=l;t?u(l.readEntries):o=!0;function m(){let w=new Set;for(let E of Object.keys(n)){let v=E.split("/");if(v.pop(),!!v.length)for(let h=0;h<v.length;h++){let y=v.slice(0,h+1).join("/")+"/";w.add(y)}}for(let E of w)if(!(E in n)){let v=new Kl(l);v.entryName=E,v.attr=16,v.temporary=!0,r.push(v),n[v.entryName]=v,c.add(v)}}function f(){if(o=!0,n={},s.diskEntries>(t.length-s.offset)/fe.Constants.CENHDR)throw fe.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(s.diskEntries);for(var w=s.offset,E=0;E<r.length;E++){var v=w,h=new Kl(l,t);h.header=t.slice(v,v+=fe.Constants.CENHDR),h.entryName=t.slice(v,v+=h.header.fileNameLength),h.header.extraLength&&(h.extra=t.slice(v,v+=h.header.extraLength)),h.header.commentLength&&(h.comment=t.slice(v,v+h.header.commentLength)),w+=h.header.centralHeaderSize,r[E]=h,n[h.entryName]=h}c.clear(),m()}function u(w){var E=t.length-fe.Constants.ENDHDR,v=Math.max(0,E-65535),h=v,y=t.length,S=-1,k=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(v=0),E;E>=h;E--)if(t[E]===80){if(t.readUInt32LE(E)===fe.Constants.ENDSIG){S=E,k=E,y=E+fe.Constants.ENDHDR,h=E-fe.Constants.END64HDR;continue}if(t.readUInt32LE(E)===fe.Constants.END64SIG){h=v;continue}if(t.readUInt32LE(E)===fe.Constants.ZIP64SIG){S=E,y=E+fe.readBigUInt64LE(t,E+fe.Constants.ZIP64SIZE)+fe.Constants.ZIP64LEAD;break}}if(S==-1)throw fe.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(S,y)),s.commentLength&&(i=t.slice(k+fe.Constants.ENDHDR)),w&&f()}function g(){r.length>1&&!d&&r.sort((w,E)=>w.entryName.toLowerCase().localeCompare(E.entryName.toLowerCase()))}return{get entries(){return o||f(),r.filter(w=>!c.has(w))},get comment(){return p.decode(i)},set comment(w){i=fe.toBuffer(w,p.encode),s.commentLength=i.length},getEntryCount:function(){return o?r.length:s.diskEntries},forEach:function(w){this.entries.forEach(w)},getEntry:function(w){return o||f(),n[w]||null},setEntry:function(w){o||f(),r.push(w),n[w.entryName]=w,s.totalEntries=r.length},deleteFile:function(w,E=!0){o||f();let v=n[w];this.getEntryChildren(v,E).map(y=>y.entryName).forEach(this.deleteEntry)},deleteEntry:function(w){o||f();let E=n[w],v=r.indexOf(E);v>=0&&(r.splice(v,1),delete n[w],s.totalEntries=r.length)},getEntryChildren:function(w,E=!0){if(o||f(),typeof w=="object")if(w.isDirectory&&E){let v=[],h=w.entryName;for(let y of r)y.entryName.startsWith(h)&&v.push(y);return v}else return[w];return[]},getChildCount:function(w){if(w&&w.isDirectory){let E=this.getEntryChildren(w);return E.includes(w)?E.length-1:E.length}return 0},compressToBuffer:function(){o||f(),g();let w=[],E=[],v=0,h=0;s.size=0,s.offset=0;let y=0;for(let R of this.entries){let I=R.getCompressedData();R.header.offset=h;let T=R.packLocalHeader(),A=T.length+I.length;h+=A,w.push(T),w.push(I);let P=R.packCentralHeader();E.push(P),s.size+=P.length,v+=A+P.length,y++}v+=s.mainHeaderSize,s.offset=h,s.totalEntries=y,h=0;let S=Buffer.alloc(v);for(let R of w)R.copy(S,h),h+=R.length;for(let R of E)R.copy(S,h),h+=R.length;let k=s.toBinary();return i&&i.copy(k,fe.Constants.ENDHDR),k.copy(S,h),t=S,o=!1,S},toAsyncBuffer:function(w,E,v,h){try{o||f(),g();let y=[],S=[],k=0,R=0,I=0;s.size=0,s.offset=0;let T=function(A){if(A.length>0){let P=A.shift(),G=P.entryName+P.extra.toString();v&&v(G),P.getCompressedDataAsync(function(X){h&&h(G),P.header.offset=R;let Pe=P.packLocalHeader(),at=Pe.length+X.length;R+=at,y.push(Pe),y.push(X);let ct=P.packCentralHeader();S.push(ct),s.size+=ct.length,k+=at+ct.length,I++,T(A)})}else{k+=s.mainHeaderSize,s.offset=R,s.totalEntries=I,R=0;let P=Buffer.alloc(k);y.forEach(function(X){X.copy(P,R),R+=X.length}),S.forEach(function(X){X.copy(P,R),R+=X.length});let G=s.toBinary();i&&i.copy(G,fe.Constants.ENDHDR),G.copy(P,R),t=P,o=!1,w(P)}};T(Array.from(this.entries))}catch(y){E(y)}}}}});var td=z((nT,ed)=>{var J=vr(),q=$("path"),Wg=Ro(),qg=Ql(),Jt=(...t)=>J.findLast(t,e=>typeof e=="boolean"),Yl=(...t)=>J.findLast(t,e=>typeof e=="string"),Jg=(...t)=>J.findLast(t,e=>typeof e=="function"),Vg={noSort:!1,readEntries:!1,method:J.Constants.NONE,fs:null};ed.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),Vg);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=J.Constants.BUFFER,t=void 0)),Object.assign(n,e);let i=new J(n);if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=J.decoder),t&&typeof t=="string")if(i.fs.existsSync(t))n.method=J.Constants.FILE,n.filename=t,r=i.fs.readFileSync(t);else throw J.Errors.INVALID_FILENAME();let s=new qg(r,n),{canonical:o,sanitize:a,zipnamefix:c}=J;function l(f){if(f&&s){var u;if(typeof f=="string"&&(u=s.getEntry(q.posix.normalize(f))),typeof f=="object"&&typeof f.entryName<"u"&&typeof f.header<"u"&&(u=s.getEntry(f.entryName)),u)return u}return null}function d(f){let{join:u,normalize:g,sep:w}=q.posix;return u(q.isAbsolute(f)?"/":".",g(w+f.split("\\").join(w)+w))}function p(f){return f instanceof RegExp?(function(u){return function(g){return u.test(g)}})(f):typeof f!="function"?()=>!0:f}let m=(f,u)=>{let g=u.slice(-1);return g=g===i.sep?i.sep:"",q.relative(f,u)+g};return{readFile:function(f,u){var g=l(f);return g&&g.getData(u)||null},childCount:function(f){let u=l(f);if(u)return s.getChildCount(u)},readFileAsync:function(f,u){var g=l(f);g?g.getDataAsync(u):u(null,"getEntry failed for:"+f)},readAsText:function(f,u){var g=l(f);if(g){var w=g.getData();if(w&&w.length)return w.toString(u||"utf8")}return""},readAsTextAsync:function(f,u,g){var w=l(f);w?w.getDataAsync(function(E,v){if(v){u(E,v);return}E&&E.length?u(E.toString(g||"utf8")):u("")}):u("")},deleteFile:function(f,u=!0){var g=l(f);g&&s.deleteFile(g.entryName,u)},deleteEntry:function(f){var u=l(f);u&&s.deleteEntry(u.entryName)},addZipComment:function(f){s.comment=f},getZipComment:function(){return s.comment||""},addZipEntryComment:function(f,u){var g=l(f);g&&(g.comment=u)},getZipEntryComment:function(f){var u=l(f);return u&&u.comment||""},updateFile:function(f,u){var g=l(f);g&&g.setData(u)},addLocalFile:function(f,u,g,w){if(i.fs.existsSync(f)){u=u?d(u):"";let E=q.win32.basename(q.win32.normalize(f));u+=g||E;let v=i.fs.statSync(f),h=v.isFile()?i.fs.readFileSync(f):Buffer.alloc(0);v.isDirectory()&&(u+=i.sep),this.addFile(u,h,w,v)}else throw J.Errors.FILE_NOT_FOUND(f)},addLocalFileAsync:function(f,u){f=typeof f=="object"?f:{localPath:f};let g=q.resolve(f.localPath),{comment:w}=f,{zipPath:E,zipName:v}=f,h=this;i.fs.stat(g,function(y,S){if(y)return u(y,!1);E=E?d(E):"";let k=q.win32.basename(q.win32.normalize(g));if(E+=v||k,S.isFile())i.fs.readFile(g,function(R,I){return R?u(R,!1):(h.addFile(E,I,w,S),setImmediate(u,void 0,!0))});else if(S.isDirectory())return E+=i.sep,h.addFile(E,Buffer.alloc(0),w,S),setImmediate(u,void 0,!0)})},addLocalFolder:function(f,u,g){if(g=p(g),u=u?d(u):"",f=q.normalize(f),i.fs.existsSync(f)){let w=i.findFiles(f),E=this;if(w.length)for(let v of w){let h=q.join(u,m(f,v));g(h)&&E.addLocalFile(v,q.dirname(h))}}else throw J.Errors.FILE_NOT_FOUND(f)},addLocalFolderAsync:function(f,u,g,w){w=p(w),g=g?d(g):"",f=q.normalize(f);var E=this;i.fs.open(f,"r",function(v){if(v&&v.code==="ENOENT")u(void 0,J.Errors.FILE_NOT_FOUND(f));else if(v)u(void 0,v);else{var h=i.findFiles(f),y=-1,S=function(){if(y+=1,y<h.length){var k=h[y],R=m(f,k).split("\\").join("/");R=R.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),w(R)?i.fs.stat(k,function(I,T){I&&u(void 0,I),T.isFile()?i.fs.readFile(k,function(A,P){A?u(void 0,A):(E.addFile(g+R,P,"",T),S())}):(E.addFile(g+R+"/",Buffer.alloc(0),"",T),S())}):process.nextTick(()=>{S()})}else u(!0,void 0)};S()}})},addLocalFolderAsync2:function(f,u){let g=this;f=typeof f=="object"?f:{localPath:f},localPath=q.resolve(d(f.localPath));let{zipPath:w,filter:E,namefix:v}=f;E instanceof RegExp?E=(function(S){return function(k){return S.test(k)}})(E):typeof E!="function"&&(E=function(){return!0}),w=w?d(w):"",v=="latin1"&&(v=S=>S.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof v!="function"&&(v=S=>S);let h=S=>q.join(w,v(m(localPath,S))),y=S=>q.win32.basename(q.win32.normalize(v(S)));i.fs.open(localPath,"r",function(S){S&&S.code==="ENOENT"?u(void 0,J.Errors.FILE_NOT_FOUND(localPath)):S?u(void 0,S):i.findFilesAsync(localPath,function(k,R){if(k)return u(k);R=R.filter(I=>E(h(I))),R.length||u(void 0,!1),setImmediate(R.reverse().reduce(function(I,T){return function(A,P){if(A||P===!1)return setImmediate(I,A,!1);g.addLocalFileAsync({localPath:T,zipPath:q.dirname(h(T)),zipName:y(T)},I)}},u))})})},addLocalFolderPromise:function(f,u){return new Promise((g,w)=>{this.addLocalFolderAsync2(Object.assign({localPath:f},u),(E,v)=>{E&&w(E),v&&g(this)})})},addFile:function(f,u,g,w){f=c(f);let E=l(f),v=E!=null;v||(E=new Wg(n),E.entryName=f),E.comment=g||"";let h=typeof w=="object"&&w instanceof i.fs.Stats;h&&(E.header.time=w.mtime);var y=E.isDirectory?16:0;let S=E.isDirectory?16384:32768;return h?S|=4095&w.mode:typeof w=="number"?S|=4095&w:S|=E.isDirectory?493:420,y=(y|S<<16)>>>0,E.attr=y,E.setData(u),v||s.setEntry(E),E},getEntries:function(f){return s.password=f,s?s.entries:[]},getEntry:function(f){return l(f)},getEntryCount:function(){return s.getEntryCount()},forEach:function(f){return s.forEach(f)},extractEntryTo:function(f,u,g,w,E,v){w=Jt(!1,w),E=Jt(!1,E),g=Jt(!0,g),v=Yl(E,v);var h=l(f);if(!h)throw J.Errors.NO_ENTRY();var y=o(h.entryName),S=a(u,v&&!h.isDirectory?v:g?y:q.basename(y));if(h.isDirectory){var k=s.getEntryChildren(h);return k.forEach(function(T){if(T.isDirectory)return;var A=T.getData();if(!A)throw J.Errors.CANT_EXTRACT_FILE();var P=o(T.entryName),G=a(u,g?P:q.basename(P));let X=E?T.header.fileAttr:void 0;i.writeFileTo(G,A,w,X)}),!0}var R=h.getData(s.password);if(!R)throw J.Errors.CANT_EXTRACT_FILE();if(i.fs.existsSync(S)&&!w)throw J.Errors.CANT_OVERRIDE();let I=E?f.header.fileAttr:void 0;return i.writeFileTo(S,R,w,I),!0},test:function(f){if(!s)return!1;for(var u in s.entries)try{if(u.isDirectory)continue;var g=s.entries[u].getData(f);if(!g)return!1}catch{return!1}return!0},extractAllTo:function(f,u,g,w){if(g=Jt(!1,g),w=Yl(g,w),u=Jt(!1,u),!s)throw J.Errors.NO_ZIP();s.entries.forEach(function(E){var v=a(f,o(E.entryName));if(E.isDirectory){i.makeDir(v);return}var h=E.getData(w);if(!h)throw J.Errors.CANT_EXTRACT_FILE();let y=g?E.header.fileAttr:void 0;i.writeFileTo(v,h,u,y);try{i.fs.utimesSync(v,E.header.time,E.header.time)}catch{throw J.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(f,u,g,w){if(w=Jg(u,g,w),g=Jt(!1,g),u=Jt(!1,u),!w)return new Promise((S,k)=>{this.extractAllToAsync(f,u,g,function(R){R?k(R):S(this)})});if(!s){w(J.Errors.NO_ZIP());return}f=q.resolve(f);let E=S=>a(f,q.normalize(o(S.entryName))),v=(S,k)=>new Error(S+': "'+k+'"'),h=[],y=[];s.entries.forEach(S=>{S.isDirectory?h.push(S):y.push(S)});for(let S of h){let k=E(S),R=g?S.header.fileAttr:void 0;try{i.makeDir(k),R&&i.fs.chmodSync(k,R),i.fs.utimesSync(k,S.header.time,S.header.time)}catch{w(v("Unable to create folder",k))}}y.reverse().reduce(function(S,k){return function(R){if(R)S(R);else{let I=q.normalize(o(k.entryName)),T=a(f,I);k.getDataAsync(function(A,P){if(P)S(P);else if(!A)S(J.Errors.CANT_EXTRACT_FILE());else{let G=g?k.header.fileAttr:void 0;i.writeFileToAsync(T,A,u,G,function(X){X||S(v("Unable to write file",T)),i.fs.utimes(T,k.header.time,k.header.time,function(Pe){Pe?S(v("Unable to set times",T)):S()})})}})}}},w)()},writeZip:function(f,u){if(arguments.length===1&&typeof f=="function"&&(u=f,f=""),!f&&n.filename&&(f=n.filename),!!f){var g=s.compressToBuffer();if(g){var w=i.writeFileTo(f,g,!0);typeof u=="function"&&u(w?null:new Error("failed"),"")}}},writeZipPromise:function(f,u){let{overwrite:g,perm:w}=Object.assign({overwrite:!0},u);return new Promise((E,v)=>{!f&&n.filename&&(f=n.filename),f||v("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(h=>{let y=S=>S?E(S):v("ADM-ZIP: Wasn't able to write zip file");i.writeFileToAsync(f,h,g,w,y)},v)})},toBufferPromise:function(){return new Promise((f,u)=>{s.toAsyncBuffer(f,u)})},toBuffer:function(f,u,g,w){return typeof f=="function"?(s.toAsyncBuffer(f,u,g,w),null):s.compressToBuffer()}}}});function aE(){return Of||(Of=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function cE(){return Pf||(Pf=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function lE(t){let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{r(Ne(t.result)),i()},o=()=>{n(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(r=>{r instanceof IDBCursor&&Cf.set(r,t)}).catch(()=>{}),Za.set(e,t),e}function dE(t){if(Ja.has(t))return;let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o)},s=()=>{r(),i()},o=()=>{n(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o)});Ja.set(t,e)}function Nf(t){Va=t(Va)}function hE(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(Qn(this),e,...r);return Df.set(n,e.sort?e.sort():[e]),Ne(n)}:cE().includes(t)?function(...e){return t.apply(Qn(this),e),Ne(Cf.get(this))}:function(...e){return Ne(t.apply(Qn(this),e))}}function fE(t){return typeof t=="function"?hE(t):(t instanceof IDBTransaction&&dE(t),oE(t,aE())?new Proxy(t,Va):t)}function Ne(t){if(t instanceof IDBRequest)return lE(t);if(qa.has(t))return qa.get(t);let e=fE(t);return e!==t&&(qa.set(t,e),Za.set(e,t)),e}var oE,Of,Pf,Cf,Ja,Df,qa,Za,Va,Qn,Ka=Ie(()=>{oE=(t,e)=>e.some(r=>t instanceof r);Cf=new WeakMap,Ja=new WeakMap,Df=new WeakMap,qa=new WeakMap,Za=new WeakMap;Va={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return Ja.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Df.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Ne(t[e])},set(t,e,r){return t[e]=r,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};Qn=t=>Za.get(t)});var Ff={};gi(Ff,{deleteDB:()=>pE,openDB:()=>uE,unwrap:()=>Qn,wrap:()=>Ne});function uE(t,e,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=Ne(o);return n&&o.addEventListener("upgradeneeded",c=>{n(Ne(o.result),c.oldVersion,c.newVersion,Ne(o.transaction))}),r&&o.addEventListener("blocked",()=>r()),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",()=>i())}).catch(()=>{}),a}function pE(t,{blocked:e}={}){let r=indexedDB.deleteDatabase(t);return e&&r.addEventListener("blocked",()=>e()),Ne(r).then(()=>{})}function Lf(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Xa.get(e))return Xa.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,i=mE.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||gE.includes(r)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return n&&(l=l.index(a.shift())),(await Promise.all([l[r](...a),i&&c.done]))[0]};return Xa.set(e,s),s}var gE,mE,Xa,Mf=Ie(()=>{Ka();Ka();gE=["get","getKey","getAll","getAllKeys","count"],mE=["put","add","delete","clear"],Xa=new Map;Nf(t=>({...t,get:(e,r,n)=>Lf(e,r)||t.get(e,r,n),has:(e,r)=>!!Lf(e,r)||t.has(e,r)}))});var yt=z((OA,lu)=>{"use strict";var au=["nodebuffer","arraybuffer","fragments"],cu=typeof Blob<"u";cu&&au.push("blob");lu.exports={BINARY_TYPES:au,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:cu,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ii=z((PA,Us)=>{"use strict";var{EMPTY_BUFFER:_0}=yt(),Ec=Buffer[Symbol.species];function E0(t,e){if(t.length===0)return _0;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let i=0;i<t.length;i++){let s=t[i];r.set(s,n),n+=s.length}return n<e?new Ec(r.buffer,r.byteOffset,n):r}function du(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}function hu(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function S0(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Sc(t){if(Sc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Ec(t):ArrayBuffer.isView(t)?e=new Ec(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Sc.readOnly=!1),e}Us.exports={concat:E0,mask:du,toArrayBuffer:S0,toBuffer:Sc,unmask:hu};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=$("bufferutil");Us.exports.mask=function(e,r,n,i,s){s<48?du(e,r,n,i,s):t.mask(e,r,n,i,s)},Us.exports.unmask=function(e,r){e.length<32?hu(e,r):t.unmask(e,r)}}catch{}});var pu=z((CA,uu)=>{"use strict";var fu=Symbol("kDone"),Ic=Symbol("kRun"),vc=class{constructor(e){this[fu]=()=>{this.pending--,this[Ic]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ic]()}[Ic](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[fu])}}};uu.exports=vc});var Yr=z((DA,yu)=>{"use strict";var si=$("zlib"),gu=ii(),I0=pu(),{kStatusCode:mu}=yt(),v0=Buffer[Symbol.species],T0=Buffer.from([0,0,255,255]),$s=Symbol("permessage-deflate"),_t=Symbol("total-length"),Xr=Symbol("callback"),Ht=Symbol("buffers"),Qr=Symbol("error"),zs,Tc=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,!zs){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zs=new I0(r)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Xr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(i=>!(r.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>i.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let i=r[n];if(i.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(i=i[0],n==="client_max_window_bits"){if(i!==!0){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else if(n==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${i}`);i=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${i}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=i})}),e}decompress(e,r,n){zs.add(i=>{this._decompress(e,r,(s,o)=>{i(),n(s,o)})})}compress(e,r,n){zs.add(i=>{this._compress(e,r,(s,o)=>{i(),n(s,o)})})}_decompress(e,r,n){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?si.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=si.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[$s]=this,this._inflate[_t]=0,this._inflate[Ht]=[],this._inflate.on("error",k0),this._inflate.on("data",wu)}this._inflate[Xr]=n,this._inflate.write(e),r&&this._inflate.write(T0),this._inflate.flush(()=>{let s=this._inflate[Qr];if(s){this._inflate.close(),this._inflate=null,n(s);return}let o=gu.concat(this._inflate[Ht],this._inflate[_t]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[_t]=0,this._inflate[Ht]=[],r&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),n(null,o)})}_compress(e,r,n){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?si.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=si.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[_t]=0,this._deflate[Ht]=[],this._deflate.on("data",R0)}this._deflate[Xr]=n,this._deflate.write(e),this._deflate.flush(si.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=gu.concat(this._deflate[Ht],this._deflate[_t]);r&&(s=new v0(s.buffer,s.byteOffset,s.length-4)),this._deflate[Xr]=null,this._deflate[_t]=0,this._deflate[Ht]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};yu.exports=Tc;function R0(t){this[Ht].push(t),this[_t]+=t.length}function wu(t){if(this[_t]+=t.length,this[$s]._maxPayload<1||this[_t]<=this[$s]._maxPayload){this[Ht].push(t);return}this[Qr]=new RangeError("Max payload size exceeded"),this[Qr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Qr][mu]=1009,this.removeListener("data",wu),this.reset()}function k0(t){if(this[$s]._inflate=null,this[Qr]){this[Xr](this[Qr]);return}t[mu]=1007,this[Xr](t)}});var en=z((NA,Gs)=>{"use strict";var{isUtf8:_u}=$("buffer"),{hasBlob:b0}=yt(),A0=[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 x0(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Rc(t){let e=t.length,r=0;for(;r<e;)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function O0(t){return b0&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Gs.exports={isBlob:O0,isValidStatusCode:x0,isValidUTF8:Rc,tokenChars:A0};if(_u)Gs.exports.isValidUTF8=function(t){return t.length<24?Rc(t):_u(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=$("utf-8-validate");Gs.exports.isValidUTF8=function(e){return e.length<32?Rc(e):t(e)}}catch{}});var Oc=z((LA,ku)=>{"use strict";var{Writable:P0}=$("stream"),Eu=Yr(),{BINARY_TYPES:C0,EMPTY_BUFFER:Su,kStatusCode:D0,kWebSocket:N0}=yt(),{concat:kc,toArrayBuffer:L0,unmask:F0}=ii(),{isValidStatusCode:M0,isValidUTF8:Iu}=en(),Hs=Buffer[Symbol.species],Fe=0,vu=1,Tu=2,Ru=3,bc=4,Ac=5,js=6,xc=class extends P0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||C0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[N0]=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=Fe}_write(e,r,n){if(this._opcode===8&&this._state==Fe)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Hs(n.buffer,n.byteOffset+e,n.length-e),new Hs(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],i=r.length-e;e>=n.length?r.set(this._buffers.shift(),i):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),i),this._buffers[0]=new Hs(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case Fe:this.getInfo(e);break;case vu:this.getPayloadLength16(e);break;case Tu:this.getPayloadLength64(e);break;case Ru:this.getMask();break;case bc:this.getData(e);break;case Ac:case js:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if((r[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let n=(r[0]&64)===64;if(n&&!this._extensions[Eu.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(i);return}if(n){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(i);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(i);return}this._payloadLength===126?this._state=vu:this._payloadLength===127?this._state=Tu:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(i);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=Ru:this._state=bc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=bc}getData(e){let r=Su;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&F0(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Ac,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Eu.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return r(i);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(o);return}this._fragments.push(s)}this.dataMessage(r),this._state===Fe&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=Fe;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=kc(n,r):this._binaryType==="arraybuffer"?i=L0(kc(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Fe):(this._state=js,setImmediate(()=>{this.emit("message",i,!0),this._state=Fe,this.startLoop(e)}))}else{let i=kc(n,r);if(!this._skipUTF8Validation&&!Iu(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Ac||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Fe):(this._state=js,setImmediate(()=>{this.emit("message",i,!1),this._state=Fe,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Su),this.end();else{let n=e.readUInt16BE(0);if(!M0(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new Hs(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Iu(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,i),this.end()}this._state=Fe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Fe):(this._state=js,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Fe,this.startLoop(r)}))}createError(e,r,n,i,s){this._loop=!1,this._errored=!0;let o=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(o,this.createError),o.code=s,o[D0]=i,o}};ku.exports=xc});var Dc=z((MA,xu)=>{"use strict";var{Duplex:FA}=$("stream"),{randomFillSync:B0}=$("crypto"),bu=Yr(),{EMPTY_BUFFER:U0,kWebSocket:z0,NOOP:$0}=yt(),{isBlob:tn,isValidStatusCode:G0}=en(),{mask:Au,toBuffer:fr}=ii(),Me=Symbol("kByteLength"),H0=Buffer.alloc(4),Ws=8*1024,ur,rn=Ws,We=0,j0=1,W0=2,Pc=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=We,this.onerror=$0,this[z0]=void 0}static frame(e,r){let n,i=!1,s=2,o=!1;r.mask&&(n=r.maskBuffer||H0,r.generateMask?r.generateMask(n):(rn===Ws&&(ur===void 0&&(ur=Buffer.alloc(Ws)),B0(ur,0,Ws),rn=0),n[0]=ur[rn++],n[1]=ur[rn++],n[2]=ur[rn++],n[3]=ur[rn++]),o=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||o)&&r[Me]!==void 0?a=r[Me]:(e=Buffer.from(e),a=e.length):(a=e.length,i=r.mask&&r.readOnly&&!o);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(i?a+s:s);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[s-4]=n[0],l[s-3]=n[1],l[s-2]=n[2],l[s-1]=n[3],o?[l,e]:i?(Au(e,n,l,s,a),[l]):(Au(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,i){let s;if(e===void 0)s=U0;else{if(typeof e!="number"||!G0(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let o={[Me]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==We?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):tn(e)?(i=e.size,s=!1):(e=fr(e),i=e.length,s=fr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};tn(e)?this._state!==We?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==We?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}pong(e,r,n){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):tn(e)?(i=e.size,s=!1):(e=fr(e),i=e.length,s=fr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};tn(e)?this._state!==We?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==We?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let i=this._extensions[bu.extensionName],s=r.binary?2:1,o=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):tn(e)?(a=e.size,c=!1):(e=fr(e),a=e.length,c=fr.readOnly),this._firstFragment?(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=i._threshold),this._compress=o):(o=!1,s=0),r.fin&&(this._firstFragment=!0);let l={[Me]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};tn(e)?this._state!==We?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==We?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[Me],this._state=W0,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Cc,this,a,i);return}this._bufferedBytes-=n[Me];let o=fr(s);r?this.dispatch(o,r,n,i):(this._state=We,this.sendFrame(t.frame(o,n),i),this.dequeue())}).catch(s=>{process.nextTick(q0,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[bu.extensionName];this._bufferedBytes+=n[Me],this._state=j0,s.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Cc(this,c,i);return}this._bufferedBytes-=n[Me],this._state=We,n.readOnly=!1,this.sendFrame(t.frame(a,n),i),this.dequeue()})}dequeue(){for(;this._state===We&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};xu.exports=Pc;function Cc(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let i=t._queue[n],s=i[i.length-1];typeof s=="function"&&s(e)}}function q0(t,e,r){Cc(t,e,r),t.onerror(e)}});var Bu=z((BA,Mu)=>{"use strict";var{kForOnEventAttribute:oi,kListener:Nc}=yt(),Ou=Symbol("kCode"),Pu=Symbol("kData"),Cu=Symbol("kError"),Du=Symbol("kMessage"),Nu=Symbol("kReason"),nn=Symbol("kTarget"),Lu=Symbol("kType"),Fu=Symbol("kWasClean"),Et=class{constructor(e){this[nn]=null,this[Lu]=e}get target(){return this[nn]}get type(){return this[Lu]}};Object.defineProperty(Et.prototype,"target",{enumerable:!0});Object.defineProperty(Et.prototype,"type",{enumerable:!0});var pr=class extends Et{constructor(e,r={}){super(e),this[Ou]=r.code===void 0?0:r.code,this[Nu]=r.reason===void 0?"":r.reason,this[Fu]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Ou]}get reason(){return this[Nu]}get wasClean(){return this[Fu]}};Object.defineProperty(pr.prototype,"code",{enumerable:!0});Object.defineProperty(pr.prototype,"reason",{enumerable:!0});Object.defineProperty(pr.prototype,"wasClean",{enumerable:!0});var sn=class extends Et{constructor(e,r={}){super(e),this[Cu]=r.error===void 0?null:r.error,this[Du]=r.message===void 0?"":r.message}get error(){return this[Cu]}get message(){return this[Du]}};Object.defineProperty(sn.prototype,"error",{enumerable:!0});Object.defineProperty(sn.prototype,"message",{enumerable:!0});var ai=class extends Et{constructor(e,r={}){super(e),this[Pu]=r.data===void 0?null:r.data}get data(){return this[Pu]}};Object.defineProperty(ai.prototype,"data",{enumerable:!0});var J0={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[oi]&&i[Nc]===e&&!i[oi])return;let n;if(t==="message")n=function(s,o){let a=new ai("message",{data:o?s:s.toString()});a[nn]=this,qs(e,this,a)};else if(t==="close")n=function(s,o){let a=new pr("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[nn]=this,qs(e,this,a)};else if(t==="error")n=function(s){let o=new sn("error",{error:s,message:s.message});o[nn]=this,qs(e,this,o)};else if(t==="open")n=function(){let s=new Et("open");s[nn]=this,qs(e,this,s)};else return;n[oi]=!!r[oi],n[Nc]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Nc]===e&&!r[oi]){this.removeListener(t,r);break}}};Mu.exports={CloseEvent:pr,ErrorEvent:sn,Event:Et,EventTarget:J0,MessageEvent:ai};function qs(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var Js=z((UA,Uu)=>{"use strict";var{tokenChars:ci}=en();function ot(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function V0(t){let e=Object.create(null),r=Object.create(null),n=!1,i=!1,s=!1,o,a,c=-1,l=-1,d=-1,p=0;for(;p<t.length;p++)if(l=t.charCodeAt(p),o===void 0)if(d===-1&&ci[l]===1)c===-1&&(c=p);else if(p!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(c,d);l===44?(ot(e,f,r),r=Object.create(null)):o=f,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&ci[l]===1)c===-1&&(c=p);else if(l===32||l===9)d===-1&&c!==-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p),ot(r,t.slice(c,d),!0),l===44&&(ot(e,o,r),r=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=t.slice(c,p),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(i){if(ci[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),i=!1}else if(s)if(ci[l]===1)c===-1&&(c=p);else if(l===34&&c!==-1)s=!1,d=p;else if(l===92)i=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&t.charCodeAt(p-1)===61)s=!0;else if(d===-1&&ci[l]===1)c===-1&&(c=p);else if(c!==-1&&(l===32||l===9))d===-1&&(d=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);d===-1&&(d=p);let f=t.slice(c,d);n&&(f=f.replace(/\\/g,""),n=!1),ot(r,a,f),l===44&&(ot(e,o,r),r=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=p);let m=t.slice(c,d);return o===void 0?ot(e,m,r):(a===void 0?ot(r,m,!0):n?ot(r,a,m.replace(/\\/g,"")):ot(r,a,m),ot(e,o,r)),e}function Z0(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(i=>{let s=n[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Uu.exports={format:Z0,parse:V0}});var Xs=z((GA,Xu)=>{"use strict";var K0=$("events"),X0=$("https"),Q0=$("http"),Gu=$("net"),Y0=$("tls"),{randomBytes:eS,createHash:tS}=$("crypto"),{Duplex:zA,Readable:$A}=$("stream"),{URL:Lc}=$("url"),jt=Yr(),rS=Oc(),nS=Dc(),{isBlob:iS}=en(),{BINARY_TYPES:zu,CLOSE_TIMEOUT:sS,EMPTY_BUFFER:Vs,GUID:oS,kForOnEventAttribute:Fc,kListener:aS,kStatusCode:cS,kWebSocket:ce,NOOP:Hu}=yt(),{EventTarget:{addEventListener:lS,removeEventListener:dS}}=Bu(),{format:hS,parse:fS}=Js(),{toBuffer:uS}=ii(),ju=Symbol("kAborted"),Mc=[8,13],St=["CONNECTING","OPEN","CLOSING","CLOSED"],pS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,j=class t extends K0{constructor(e,r,n){super(),this._binaryType=zu[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Vs,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),Wu(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){zu.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let i=new rS({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new nS(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[ce]=this,s[ce]=this,e[ce]=this,i.on("conclude",wS),i.on("drain",yS),i.on("error",_S),i.on("message",ES),i.on("ping",SS),i.on("pong",IS),s.onerror=vS,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",Vu),e.on("data",Ks),e.on("end",Zu),e.on("error",Ku),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[jt.extensionName]&&this._extensions[jt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Oe(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ju(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Vs,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Vs,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){Bc(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[jt.extensionName]||(i.compress=!1),this._sender.send(e||Vs,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Oe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(j,"CONNECTING",{enumerable:!0,value:St.indexOf("CONNECTING")});Object.defineProperty(j.prototype,"CONNECTING",{enumerable:!0,value:St.indexOf("CONNECTING")});Object.defineProperty(j,"OPEN",{enumerable:!0,value:St.indexOf("OPEN")});Object.defineProperty(j.prototype,"OPEN",{enumerable:!0,value:St.indexOf("OPEN")});Object.defineProperty(j,"CLOSING",{enumerable:!0,value:St.indexOf("CLOSING")});Object.defineProperty(j.prototype,"CLOSING",{enumerable:!0,value:St.indexOf("CLOSING")});Object.defineProperty(j,"CLOSED",{enumerable:!0,value:St.indexOf("CLOSED")});Object.defineProperty(j.prototype,"CLOSED",{enumerable:!0,value:St.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(j.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(j.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[Fc])return e[aS];return null},set(e){for(let r of this.listeners(t))if(r[Fc]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Fc]:!0})}})});j.prototype.addEventListener=lS;j.prototype.removeEventListener=dS;Xu.exports=j;function Wu(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:sS,protocolVersion:Mc[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,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=i.autoPong,t._closeTimeout=i.closeTimeout,!Mc.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Mc.join(", ")})`);let s;if(e instanceof Lc)s=e;else try{s=new Lc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let o=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(t._redirects===0)throw g;Zs(t,g);return}let l=o?443:80,d=eS(16).toString("base64"),p=o?X0.request:Q0.request,m=new Set,f;if(i.createConnection=i.createConnection||(o?mS:gS),i.defaultPort=i.defaultPort||l,i.port=s.port||l,i.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},i.path=s.pathname+s.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(f=new jt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=hS({[jt.extensionName]:f.offer()})),r.length){for(let g of r){if(typeof g!="string"||!pS.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}i.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(s.username||s.password)&&(i.auth=`${s.username}:${s.password}`),a){let g=i.path.split(":");i.socketPath=g[0],i.path=g[1]}let u;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let g=n&&n.headers;if(n={...n,headers:{}},g)for(let[w,E]of Object.entries(g))n.headers[w.toLowerCase()]=E}else if(t.listenerCount("redirect")===0){let g=a?t._originalIpc?i.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!g||t._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,g||delete i.headers.host,i.auth=void 0)}i.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),u=t._req=p(i),t._redirects&&t.emit("redirect",t.url,u)}else u=t._req=p(i);i.timeout&&u.on("timeout",()=>{Oe(t,u,"Opening handshake has timed out")}),u.on("error",g=>{u===null||u[ju]||(u=t._req=null,Zs(t,g))}),u.on("response",g=>{let w=g.headers.location,E=g.statusCode;if(w&&i.followRedirects&&E>=300&&E<400){if(++t._redirects>i.maxRedirects){Oe(t,u,"Maximum redirects exceeded");return}u.abort();let v;try{v=new Lc(w,e)}catch{let y=new SyntaxError(`Invalid URL: ${w}`);Zs(t,y);return}Wu(t,v,r,n)}else t.emit("unexpected-response",u,g)||Oe(t,u,`Unexpected server response: ${g.statusCode}`)}),u.on("upgrade",(g,w,E)=>{if(t.emit("upgrade",g),t.readyState!==j.CONNECTING)return;u=t._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Oe(t,w,"Invalid Upgrade header");return}let h=tS("sha1").update(d+oS).digest("base64");if(g.headers["sec-websocket-accept"]!==h){Oe(t,w,"Invalid Sec-WebSocket-Accept header");return}let y=g.headers["sec-websocket-protocol"],S;if(y!==void 0?m.size?m.has(y)||(S="Server sent an invalid subprotocol"):S="Server sent a subprotocol but none was requested":m.size&&(S="Server sent no subprotocol"),S){Oe(t,w,S);return}y&&(t._protocol=y);let k=g.headers["sec-websocket-extensions"];if(k!==void 0){if(!f){Oe(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=fS(k)}catch{Oe(t,w,"Invalid Sec-WebSocket-Extensions header");return}let I=Object.keys(R);if(I.length!==1||I[0]!==jt.extensionName){Oe(t,w,"Server indicated an extension that was not requested");return}try{f.accept(R[jt.extensionName])}catch{Oe(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[jt.extensionName]=f}t.setSocket(w,E,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(u,t):u.end()}function Zs(t,e){t._readyState=j.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function gS(t){return t.path=t.socketPath,Gu.connect(t)}function mS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Gu.isIP(t.host)?"":t.host),Y0.connect(t)}function Oe(t,e,r){t._readyState=j.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Oe),e.setHeader?(e[ju]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Zs,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Bc(t,e,r){if(e){let n=iS(e)?e.size:uS(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${St[t.readyState]})`);process.nextTick(r,n)}}function wS(t,e){let r=this[ce];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[ce]!==void 0&&(r._socket.removeListener("data",Ks),process.nextTick(qu,r._socket),t===1005?r.close():r.close(t,e))}function yS(){let t=this[ce];t.isPaused||t._socket.resume()}function _S(t){let e=this[ce];e._socket[ce]!==void 0&&(e._socket.removeListener("data",Ks),process.nextTick(qu,e._socket),e.close(t[cS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function $u(){this[ce].emitClose()}function ES(t,e){this[ce].emit("message",t,e)}function SS(t){let e=this[ce];e._autoPong&&e.pong(t,!this._isServer,Hu),e.emit("ping",t)}function IS(t){this[ce].emit("pong",t)}function qu(t){t.resume()}function vS(t){let e=this[ce];e.readyState!==j.CLOSED&&(e.readyState===j.OPEN&&(e._readyState=j.CLOSING,Ju(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ju(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Vu(){let t=this[ce];if(this.removeListener("close",Vu),this.removeListener("data",Ks),this.removeListener("end",Zu),t._readyState=j.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[ce]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",$u),t._receiver.on("finish",$u))}function Ks(t){this[ce]._receiver.write(t)||this.pause()}function Zu(){let t=this[ce];t._readyState=j.CLOSING,t._receiver.end(),this.end()}function Ku(){let t=this[ce];this.removeListener("error",Ku),this.on("error",Hu),t&&(t._readyState=j.CLOSING,this.destroy())}});var tp=z((jA,ep)=>{"use strict";var HA=Xs(),{Duplex:TS}=$("stream");function Qu(t){t.emit("close")}function RS(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Yu(t){this.removeListener("error",Yu),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function kS(t,e){let r=!0,n=new TS({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&n._readableState.objectMode?s.toString():s;n.push(a)||t.pause()}),t.once("error",function(s){n.destroyed||(r=!1,n.destroy(s))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(Qu,n);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(Qu,n)}),r&&t.terminate()},n._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(i,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(i,s,o)});return}t.send(i,o)},n.on("end",RS),n.on("error",Yu),n}ep.exports=kS});var Uc=z((WA,rp)=>{"use strict";var{tokenChars:bS}=en();function AS(t){let e=new Set,r=-1,n=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(n===-1&&bS[o]===1)r===-1&&(r=i);else if(i!==0&&(o===32||o===9))n===-1&&r!==-1&&(n=i);else if(o===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${i}`);n===-1&&(n=i);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}rp.exports={parse:AS}});var lp=z((JA,cp)=>{"use strict";var xS=$("events"),Qs=$("http"),{Duplex:qA}=$("stream"),{createHash:OS}=$("crypto"),np=Js(),gr=Yr(),PS=Uc(),CS=Xs(),{CLOSE_TIMEOUT:DS,GUID:NS,kWebSocket:LS}=yt(),FS=/^[+/0-9A-Za-z]{22}==$/,ip=0,sp=1,ap=2,zc=class extends xS{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:DS,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:CS,...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=Qs.createServer((n,i)=>{let s=Qs.STATUS_CODES[426];i.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),i.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=MS(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,n)}})}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===ap){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(li,this);return}if(e&&this.once("close",e),this._state!==sp)if(this._state=sp,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(li,this):process.nextTick(li,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{li(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,i){r.on("error",op);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){mr(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){mr(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!FS.test(s)){mr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){mr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){di(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=PS.parse(c)}catch{mr(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&d!==void 0){let m=new gr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=np.parse(d);f[gr.extensionName]&&(m.accept(f[gr.extensionName]),p[gr.extensionName]=m)}catch{mr(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,u,g,w)=>{if(!f)return di(r,u||401,g,w);this.completeUpgrade(p,s,l,e,r,n,i)});return}if(!this.options.verifyClient(m))return di(r,401)}this.completeUpgrade(p,s,l,e,r,n,i)}completeUpgrade(e,r,n,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[LS])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ip)return di(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${OS("sha1").update(r+NS).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,i):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[gr.extensionName]){let p=e[gr.extensionName].params,m=np.format({[gr.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
13
13
  `).join(`\r
14
- `)),s.removeListener("error",sp),d.setSocket(s,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(li,this)})),a(d,i)}};ap.exports=zc;function FS(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function li(t){t._state=op,t.emit("close")}function sp(){this.destroy()}function di(t,e,r,n){r=r||Qs.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Qs.STATUS_CODES[e]}\r
14
+ `)),s.removeListener("error",op),d.setSocket(s,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(li,this)})),a(d,i)}};cp.exports=zc;function MS(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function li(t){t._state=ap,t.emit("close")}function op(){this.destroy()}function di(t,e,r,n){r=r||Qs.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Qs.STATUS_CODES[e]}\r
15
15
  `+Object.keys(n).map(i=>`${i}: ${n[i]}`).join(`\r
16
16
  `)+`\r
17
17
  \r
18
- `+r)}function gr(t,e,r,n,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,gr),t.emit("wsClientError",o,r,e)}else di(r,n,i,s)}});import{existsSync as dI,openSync as hI}from"node:fs";import{mkdir as fI}from"node:fs/promises";import{dirname as uI}from"node:path";import{fileURLToPath as pI}from"node:url";function jc(t=M()){return dI(t.libEntry)?t.libEntry:pI(new URL("../index.ts",import.meta.url))}async function Wc(t={}){let e=t.paths??M(),r=t.entryOverride??jc(e);await fI(uI(e.logFile),{recursive:!0});let n=hI(e.logFile,"a"),s=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],o=It(process.execPath,s,{detached:!0,stdio:["ignore",n,n],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(o.unref(),typeof o.pid!="number")throw new Error("failed to spawn daemon (no pid)");return gI.info("daemon spawned",{pid:o.pid,entry:r}),{pid:o.pid,entry:r}}var gI,qc=Ie(()=>{"use strict";mr();F();de();gI=O("spawn-daemon")});import{spawn as xI}from"node:child_process";import{mkdir as PI,unlink as CI,writeFile as DI}from"node:fs/promises";import{dirname as NI,join as LI}from"node:path";function ao(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Op(t,e){return new Promise((r,n)=>{let i=xI(t,e,{stdio:["ignore","pipe","pipe"]}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var oo,Kc,Xc,xp=Ie(()=>{"use strict";F();oo=O("supervisor.launchd"),Kc="ai.coze.bridge",Xc={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
18
+ `+r)}function mr(t,e,r,n,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,mr),t.emit("wsClientError",o,r,e)}else di(r,n,i,s)}});import{existsSync as hI,openSync as fI}from"node:fs";import{mkdir as uI}from"node:fs/promises";import{dirname as pI}from"node:path";import{fileURLToPath as gI}from"node:url";function jc(t=M()){return hI(t.libEntry)?t.libEntry:gI(new URL("../index.ts",import.meta.url))}async function Wc(t={}){let e=t.paths??M(),r=t.entryOverride??jc(e);await uI(pI(e.logFile),{recursive:!0});let n=fI(e.logFile,"a"),s=r.endsWith(".ts")?["--import","tsx/esm",r,"--daemon"]:[r,"--daemon"],o=Je(process.execPath,s,{detached:!0,stdio:["ignore",n,n],env:{...process.env,COZE_BRIDGE_DAEMON:"1"}});if(o.unref(),typeof o.pid!="number")throw new Error("failed to spawn daemon (no pid)");return mI.info("daemon spawned",{pid:o.pid,entry:r}),{pid:o.pid,entry:r}}var mI,qc=Ie(()=>{"use strict";Wt();F();de();mI=x("spawn-daemon")});import{spawn as PI}from"node:child_process";import{mkdir as CI,unlink as DI,writeFile as NI}from"node:fs/promises";import{dirname as LI,join as FI}from"node:path";function ao(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function Op(t,e){return new Promise((r,n)=>{let i=PI(t,e,{stdio:["ignore","pipe","pipe"]}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var oo,Kc,Xc,Pp=Ie(()=>{"use strict";F();oo=x("supervisor.launchd"),Kc="ai.coze.bridge",Xc={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
19
19
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
20
20
  <plist version="1.0">
21
21
  <dict>
@@ -39,7 +39,7 @@ var $p=Object.create;var go=Object.defineProperty;var Gp=Object.getOwnPropertyDe
39
39
  <string>${ao(t.logFile)}</string>
40
40
  </dict>
41
41
  </plist>
42
- `},configPath(t){return LI(t.homeDir,"Library","LaunchAgents",`${Kc}.plist`)},async install(t){let e=this.configPath(t);await PI(NI(e),{recursive:!0}),await DI(e,this.renderConfig(t),"utf8"),oo.info("plist written",{plistPath:e}),await Op("launchctl",["load","-w",e]),oo.info("launchd job loaded",{label:Kc})},async uninstall(t){let e=this.configPath(t);await Op("launchctl",["unload","-w",e]).catch(r=>oo.warn("launchctl unload failed (ignored)",{err:String(r)})),await CI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),oo.info("launchd job removed",{plistPath:e})}}});import{spawn as FI}from"node:child_process";import{mkdir as MI,unlink as BI,writeFile as UI}from"node:fs/promises";import{dirname as zI,join as $I}from"node:path";function ho(t,e){return new Promise((r,n)=>{let i=FI(t,e,{stdio:["ignore","pipe","pipe"]}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var co,lo,Qc,Pp=Ie(()=>{"use strict";F();co=O("supervisor.systemd"),lo="coze-bridge.service",Qc={platform:"linux",renderConfig(t){return`[Unit]
42
+ `},configPath(t){return FI(t.homeDir,"Library","LaunchAgents",`${Kc}.plist`)},async install(t){let e=this.configPath(t);await CI(LI(e),{recursive:!0}),await NI(e,this.renderConfig(t),"utf8"),oo.info("plist written",{plistPath:e}),await Op("launchctl",["load","-w",e]),oo.info("launchd job loaded",{label:Kc})},async uninstall(t){let e=this.configPath(t);await Op("launchctl",["unload","-w",e]).catch(r=>oo.warn("launchctl unload failed (ignored)",{err:String(r)})),await DI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),oo.info("launchd job removed",{plistPath:e})}}});import{spawn as MI}from"node:child_process";import{mkdir as BI,unlink as UI,writeFile as zI}from"node:fs/promises";import{dirname as $I,join as GI}from"node:path";function ho(t,e){return new Promise((r,n)=>{let i=MI(t,e,{stdio:["ignore","pipe","pipe"]}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var co,lo,Qc,Cp=Ie(()=>{"use strict";F();co=x("supervisor.systemd"),lo="coze-bridge.service",Qc={platform:"linux",renderConfig(t){return`[Unit]
43
43
  Description=Coze Bridge daemon
44
44
  After=network.target
45
45
 
@@ -53,7 +53,7 @@ StandardError=append:${t.logFile}
53
53
 
54
54
  [Install]
55
55
  WantedBy=default.target
56
- `},configPath(t){return $I(t.homeDir,".config","systemd","user",lo)},async install(t){let e=this.configPath(t);await MI(zI(e),{recursive:!0}),await UI(e,this.renderConfig(t),"utf8"),co.info("systemd unit written",{unitPath:e}),await ho("systemctl",["--user","daemon-reload"]),await ho("systemctl",["--user","enable","--now",lo]),co.info("systemd unit enabled",{unitName:lo})},async uninstall(t){let e=this.configPath(t);await ho("systemctl",["--user","disable","--now",lo]).catch(r=>co.warn("systemctl disable failed (ignored)",{err:String(r)})),await BI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ho("systemctl",["--user","daemon-reload"]).catch(()=>{}),co.info("systemd unit removed",{unitPath:e})}}});import{spawn as GI}from"node:child_process";import{join as HI}from"node:path";function Cp(t,e){return new Promise((r,n)=>{let i=GI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var Yc,fo,el,Dp=Ie(()=>{"use strict";F();Yc=O("supervisor.taskscheduler"),fo="CozeBridge",el={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
56
+ `},configPath(t){return GI(t.homeDir,".config","systemd","user",lo)},async install(t){let e=this.configPath(t);await BI($I(e),{recursive:!0}),await zI(e,this.renderConfig(t),"utf8"),co.info("systemd unit written",{unitPath:e}),await ho("systemctl",["--user","daemon-reload"]),await ho("systemctl",["--user","enable","--now",lo]),co.info("systemd unit enabled",{unitName:lo})},async uninstall(t){let e=this.configPath(t);await ho("systemctl",["--user","disable","--now",lo]).catch(r=>co.warn("systemctl disable failed (ignored)",{err:String(r)})),await UI(e).catch(r=>{if(r.code!=="ENOENT")throw r}),await ho("systemctl",["--user","daemon-reload"]).catch(()=>{}),co.info("systemd unit removed",{unitPath:e})}}});import{spawn as HI}from"node:child_process";import{join as jI}from"node:path";function Dp(t,e){return new Promise((r,n)=>{let i=HI(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var Yc,fo,el,Np=Ie(()=>{"use strict";F();Yc=x("supervisor.taskscheduler"),fo="CozeBridge",el={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
57
57
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
58
58
  <RegistrationInfo>
59
59
  <Description>Coze Bridge daemon</Description>
@@ -77,32 +77,32 @@ WantedBy=default.target
77
77
  </Exec>
78
78
  </Actions>
79
79
  </Task>
80
- `},configPath(t){return HI(t.homeDir,".coze","bridge","task.xml")},async install(t){let r=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await Cp("schtasks",["/Create","/SC","ONLOGON","/TN",fo,"/TR",r,"/RU",t.userName,"/F"]),Yc.info("task scheduler entry created",{task:fo,logFile:t.logFile})},async uninstall(t){await Cp("schtasks",["/Delete","/TN",fo,"/F"]).catch(e=>Yc.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Yc.info("task scheduler entry removed",{task:fo})}}});var Np={};gi(Np,{buildContext:()=>JI,getSupervisor:()=>qI,launchdSupervisor:()=>Xc,systemdSupervisor:()=>Qc,taskSchedulerSupervisor:()=>el});import{homedir as jI,userInfo as WI}from"node:os";function qI(t=process.platform){switch(t){case"darwin":return Xc;case"linux":return Qc;case"win32":return el;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function JI(){let t=M();return{nodeBin:process.execPath,entry:jc(t),logFile:t.logFile,homeDir:jI(),userName:WI().username}}var Lp=Ie(()=>{"use strict";de();qc();xp();Pp();Dp()});F();Wt();var ul=O("acp-installer-warmup"),pg=["claude-code","codex"];async function pl(t={}){let e=t.ensure??yr,n=(await Promise.allSettled(pg.map(async i=>{let s=await e(i);ul.info("acp wrapper warmup ok",{framework:i,path:s})}))).filter(i=>i.status==="rejected");n.length>0&&ul.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:n.length,reasons:n.map(i=>i.reason instanceof Error?i.reason.message:String(i.reason))})}vt();F();import{readdir as Rg}from"node:fs/promises";import{mkdir as El,writeFile as Sl}from"node:fs/promises";import{join as Eo}from"node:path";var Tg={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Sr(t,e,r){await El(t,{recursive:!0});let n=Tg[e],i=Eo(t,n);return await Sl(i,r??"","utf8"),i}async function Il(t){let e=Eo(t,".claude");await El(e,{recursive:!0});let r=Eo(e,"settings.local.json"),n=JSON.stringify({permissions:{defaultMode:"bypassPermissions"}},null,2);return await Sl(r,n,"utf8"),r}var Re=O("agent-detail-sync"),kg=6e4,bg=5*6e4,Ai=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,n;try{n=await Rg(r)}catch(i){Re.info("agents dir not found, skip detail sync",{root:r,err:String(i)});return}Re.info("starting detail sync",{reason:e,count:n.length}),await Promise.allSettled(n.map(async i=>{let s=await he(i,this.opts.paths).catch(()=>null);if(s){if(s.disconnectedAt){Re.debug("detail sync: skip disconnected agent",{agentId:i});return}try{await this.syncOne(i,s)}catch(o){Re.warn("detail sync failed for agent, skipping",{agentId:i,err:String(o)})}}})),Re.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[n,i]of this.retryQueue)e>=i.dueAt&&r.push(n);if(r.length!==0){Re.info("retrying pending detail syncs",{count:r.length});for(let n of r)try{await this.syncOne(n)}catch(i){Re.debug("detail sync retry still failing, will try again",{agentId:n,err:String(i)})}}}async syncOne(e,r){let n=r??await he(e,this.opts.paths);if(!n){Re.info("detail sync: agent config missing, skip",{agentId:e});return}let i;try{i=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(a){Re.warn("detail RPC failed, using local data",{agentId:e,err:String(a)});let c=this.retryQueue.get(e),l=c?Math.min(c.currentDelay*2,bg):kg;this.retryQueue.set(e,{dueAt:Date.now()+l,currentDelay:l});return}if(i.agentId&&i.agentId!==e){Re.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:i.agentId});return}let s=!1,o=!1;if(i.agentName&&i.agentName!==n.agentName&&(n.agentName=i.agentName,s=!0),i.description!==void 0&&i.description!==n.description&&(n.description=i.description,s=!0),i.cozeIdentity&&i.cozeIdentity!==n.cozeIdentity&&(n.cozeIdentity=i.cozeIdentity,s=!0,o=!0),i.deployType&&Re.info("detail.deployType",{agentId:e,deployType:i.deployType}),!s){Re.debug("detail sync: no diff",{agentId:e});return}await ve(n,this.opts.paths),Re.info("detail sync: config updated",{agentId:e,identityChanged:o,agentName:n.agentName}),o&&(await Sr(n.workspace,n.framework,n.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Bh=ct(td(),1);import{lstat as Da,mkdir as Na,readFile as Nh,readdir as e_,rm as t_,stat as r_,writeFile as La}from"node:fs/promises";import{dirname as n_,join as et,normalize as i_,relative as Ba,resolve as Fa,sep as Lh}from"node:path";import{Readable as Fh}from"node:stream";import{pipeline as Mh}from"node:stream/promises";import Zg from"events";import Te from"fs";import{EventEmitter as ya}from"node:events";import Fd from"node:stream";import{StringDecoder as Kg}from"node:string_decoder";import Ud from"node:path";import Dr from"node:fs";import{dirname as lm,parse as dm}from"path";import{EventEmitter as _m}from"events";import ea from"assert";import{Buffer as rr}from"buffer";import*as od from"zlib";import ym from"zlib";import{posix as kr}from"node:path";import{basename as qm}from"node:path";import os from"fs";import Ke from"fs";import ud from"path";import{win32 as nw}from"node:path";import Ed from"path";import eh from"node:fs";import Ew from"node:assert";import{randomBytes as th}from"node:crypto";import N from"node:fs";import te from"node:path";import rh from"fs";import gs from"node:fs";import Pn from"node:path";import Ae from"node:fs";import bw from"node:fs/promises";import ls from"node:path";import{join as uh}from"node:path";import be from"node:fs";import mh from"node:path";var Jg=Object.defineProperty,Vg=(t,e)=>{for(var r in e)Jg(t,r,{get:e[r],enumerable:!0})},rd=typeof process=="object"&&process?process:{stdout:null,stderr:null},Xg=t=>!!t&&typeof t=="object"&&(t instanceof sr||t instanceof Fd||Qg(t)||Yg(t)),Qg=t=>!!t&&typeof t=="object"&&t instanceof ya&&typeof t.pipe=="function"&&t.pipe!==Fd.Writable.prototype.pipe,Yg=t=>!!t&&typeof t=="object"&&t instanceof ya&&typeof t.write=="function"&&typeof t.end=="function",dt=Symbol("EOF"),ht=Symbol("maybeEmitEnd"),Rt=Symbol("emittedEnd"),Di=Symbol("emittingEnd"),pn=Symbol("emittedError"),Ni=Symbol("closed"),nd=Symbol("read"),Li=Symbol("flush"),id=Symbol("flushChunk"),Be=Symbol("encoding"),Rr=Symbol("decoder"),ie=Symbol("flowing"),gn=Symbol("paused"),xr=Symbol("resume"),se=Symbol("buffer"),Ee=Symbol("pipes"),oe=Symbol("bufferLength"),ko=Symbol("bufferPush"),Fi=Symbol("bufferShift"),we=Symbol("objectMode"),Q=Symbol("destroyed"),bo=Symbol("error"),Ao=Symbol("emitData"),sd=Symbol("emitEnd"),Oo=Symbol("emitEnd2"),Je=Symbol("async"),xo=Symbol("abort"),Mi=Symbol("aborted"),mn=Symbol("signal"),Jt=Symbol("dataListeners"),ke=Symbol("discarded"),wn=t=>Promise.resolve().then(t),em=t=>t(),tm=t=>t==="end"||t==="finish"||t==="prefinish",rm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,nm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Md=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[xr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},im=class extends Md{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=n=>this.dest.emit("error",n),t.on("error",this.proxyErrors)}},sm=t=>!!t.objectMode,om=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",sr=class extends ya{[ie]=!1;[gn]=!1;[Ee]=[];[se]=[];[we];[Be];[Je];[Rr];[dt]=!1;[Rt]=!1;[Di]=!1;[Ni]=!1;[pn]=null;[oe]=0;[Q]=!1;[mn];[Mi]=!1;[Jt]=0;[ke]=!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");sm(e)?(this[we]=!0,this[Be]=null):om(e)?(this[Be]=e.encoding,this[we]=!1):(this[we]=!1,this[Be]=null),this[Je]=!!e.async,this[Rr]=this[Be]?new Kg(this[Be]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[se]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ee]});let{signal:r}=e;r&&(this[mn]=r,r.aborted?this[xo]():r.addEventListener("abort",()=>this[xo]()))}get bufferLength(){return this[oe]}get encoding(){return this[Be]}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[we]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Je]}set async(t){this[Je]=this[Je]||!!t}[xo](){this[Mi]=!0,this.emit("abort",this[mn]?.reason),this.destroy(this[mn]?.reason)}get aborted(){return this[Mi]}set aborted(t){}write(t,e,r){if(this[Mi])return!1;if(this[dt])throw new Error("write after end");if(this[Q])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let n=this[Je]?wn:em;if(!this[we]&&!Buffer.isBuffer(t)){if(nm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(rm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[we]?(this[ie]&&this[oe]!==0&&this[Li](!0),this[ie]?this.emit("data",t):this[ko](t),this[oe]!==0&&this.emit("readable"),r&&n(r),this[ie]):t.length?(typeof t=="string"&&!(e===this[Be]&&!this[Rr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Be]&&(t=this[Rr].write(t)),this[ie]&&this[oe]!==0&&this[Li](!0),this[ie]?this.emit("data",t):this[ko](t),this[oe]!==0&&this.emit("readable"),r&&n(r),this[ie]):(this[oe]!==0&&this.emit("readable"),r&&n(r),this[ie])}read(t){if(this[Q])return null;if(this[ke]=!1,this[oe]===0||t===0||t&&t>this[oe])return this[ht](),null;this[we]&&(t=null),this[se].length>1&&!this[we]&&(this[se]=[this[Be]?this[se].join(""):Buffer.concat(this[se],this[oe])]);let e=this[nd](t||null,this[se][0]);return this[ht](),e}[nd](t,e){if(this[we])this[Fi]();else{let r=e;t===r.length||t===null?this[Fi]():typeof r=="string"?(this[se][0]=r.slice(t),e=r.slice(0,t),this[oe]-=t):(this[se][0]=r.subarray(t),e=r.subarray(0,t),this[oe]-=t)}return this.emit("data",e),!this[se].length&&!this[dt]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[dt]=!0,this.writable=!1,(this[ie]||!this[gn])&&this[ht](),this}[xr](){this[Q]||(!this[Jt]&&!this[Ee].length&&(this[ke]=!0),this[gn]=!1,this[ie]=!0,this.emit("resume"),this[se].length?this[Li]():this[dt]?this[ht]():this.emit("drain"))}resume(){return this[xr]()}pause(){this[ie]=!1,this[gn]=!0,this[ke]=!1}get destroyed(){return this[Q]}get flowing(){return this[ie]}get paused(){return this[gn]}[ko](t){this[we]?this[oe]+=1:this[oe]+=t.length,this[se].push(t)}[Fi](){return this[we]?this[oe]-=1:this[oe]-=this[se][0].length,this[se].shift()}[Li](t=!1){do;while(this[id](this[Fi]())&&this[se].length);!t&&!this[se].length&&!this[dt]&&this.emit("drain")}[id](t){return this.emit("data",t),this[ie]}pipe(t,e){if(this[Q])return t;this[ke]=!1;let r=this[Rt];return e=e||{},t===rd.stdout||t===rd.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Ee].push(e.proxyErrors?new im(this,t,e):new Md(this,t,e)),this[Je]?wn(()=>this[xr]()):this[xr]()),t}unpipe(t){let e=this[Ee].find(r=>r.dest===t);e&&(this[Ee].length===1?(this[ie]&&this[Jt]===0&&(this[ie]=!1),this[Ee]=[]):this[Ee].splice(this[Ee].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[ke]=!1,this[Jt]++,!this[Ee].length&&!this[ie]&&this[xr]();else if(t==="readable"&&this[oe]!==0)super.emit("readable");else if(tm(t)&&this[Rt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[pn]){let n=e;this[Je]?wn(()=>n.call(this,this[pn])):n.call(this,this[pn])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Jt]=this.listeners("data").length,this[Jt]===0&&!this[ke]&&!this[Ee].length&&(this[ie]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Jt]=0,!this[ke]&&!this[Ee].length&&(this[ie]=!1)),e}get emittedEnd(){return this[Rt]}[ht](){!this[Di]&&!this[Rt]&&!this[Q]&&this[se].length===0&&this[dt]&&(this[Di]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ni]&&this.emit("close"),this[Di]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Q&&this[Q])return!1;if(t==="data")return!this[we]&&!r?!1:this[Je]?(wn(()=>this[Ao](r)),!0):this[Ao](r);if(t==="end")return this[sd]();if(t==="close"){if(this[Ni]=!0,!this[Rt]&&!this[Q])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[pn]=r,super.emit(bo,r);let i=!this[mn]||this.listeners("error").length?super.emit("error",r):!1;return this[ht](),i}else if(t==="resume"){let i=super.emit("resume");return this[ht](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let n=super.emit(t,...e);return this[ht](),n}[Ao](t){for(let r of this[Ee])r.dest.write(t)===!1&&this.pause();let e=this[ke]?!1:super.emit("data",t);return this[ht](),e}[sd](){return this[Rt]?!1:(this[Rt]=!0,this.readable=!1,this[Je]?(wn(()=>this[Oo]()),!0):this[Oo]())}[Oo](){if(this[Rr]){let e=this[Rr].end();if(e){for(let r of this[Ee])r.dest.write(e);this[ke]||super.emit("data",e)}}for(let e of this[Ee])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[we]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[we]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[we])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Be]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Q,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ke]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[dt])return e();let n,i,s=l=>{this.off("data",o),this.off("end",a),this.off(Q,c),e(),i(l)},o=l=>{this.off("error",s),this.off("end",a),this.off(Q,c),this.pause(),n({value:l,done:!!this[dt]})},a=()=>{this.off("error",s),this.off("data",o),this.off(Q,c),e(),n({done:!0,value:void 0})},c=()=>s(new Error("stream destroyed"));return new Promise((l,d)=>{i=d,n=l,this.once(Q,c),this.once("error",s),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ke]=!1;let t=!1,e=()=>(this.pause(),this.off(bo,e),this.off(Q,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let n=this.read();return n===null?e():{done:!1,value:n}};return this.once("end",e),this.once(bo,e),this.once(Q,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Q])return t?this.emit("error",t):this.emit(Q),this;this[Q]=!0,this[ke]=!0,this[se].length=0,this[oe]=0;let e=this;return typeof e.close=="function"&&!this[Ni]&&e.close(),t?this.emit("error",t):this.emit(Q),this}static get isStream(){return Xg}},am=Te.writev,Lt=Symbol("_autoClose"),Ge=Symbol("_close"),_n=Symbol("_ended"),U=Symbol("_fd"),Po=Symbol("_finished"),gt=Symbol("_flags"),Co=Symbol("_flush"),Qo=Symbol("_handleChunk"),Yo=Symbol("_makeBuf"),On=Symbol("_mode"),Bi=Symbol("_needDrain"),Lr=Symbol("_onerror"),Fr=Symbol("_onopen"),Do=Symbol("_onread"),Pr=Symbol("_onwrite"),Ft=Symbol("_open"),$e=Symbol("_path"),xt=Symbol("_pos"),Ve=Symbol("_queue"),Cr=Symbol("_read"),No=Symbol("_readSize"),pt=Symbol("_reading"),yn=Symbol("_remain"),Lo=Symbol("_size"),Vi=Symbol("_write"),Vt=Symbol("_writing"),Zi=Symbol("_defaultFlag"),tr=Symbol("_errored"),Ea=class extends sr{[tr]=!1;[U];[$e];[No];[pt]=!1;[Lo];[yn];[Lt];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[tr]=!1,this[U]=typeof e.fd=="number"?e.fd:void 0,this[$e]=t,this[No]=e.readSize||16*1024*1024,this[pt]=!1,this[Lo]=typeof e.size=="number"?e.size:1/0,this[yn]=this[Lo],this[Lt]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[U]=="number"?this[Cr]():this[Ft]()}get fd(){return this[U]}get path(){return this[$e]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Ft](){Te.open(this[$e],"r",(t,e)=>this[Fr](t,e))}[Fr](t,e){t?this[Lr](t):(this[U]=e,this.emit("open",e),this[Cr]())}[Yo](){return Buffer.allocUnsafe(Math.min(this[No],this[yn]))}[Cr](){if(!this[pt]){this[pt]=!0;let t=this[Yo]();if(t.length===0)return process.nextTick(()=>this[Do](null,0,t));Te.read(this[U],t,0,t.length,null,(e,r,n)=>this[Do](e,r,n))}}[Do](t,e,r){this[pt]=!1,t?this[Lr](t):this[Qo](e,r)&&this[Cr]()}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Lr](t){this[pt]=!0,this[Ge](),this.emit("error",t)}[Qo](t,e){let r=!1;return this[yn]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[yn]<=0)&&(r=!1,this[Ge](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[U]=="number"&&this[Cr](),!1;case"error":return this[tr]?!1:(this[tr]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},cm=class extends Ea{[Ft](){let t=!0;try{this[Fr](null,Te.openSync(this[$e],"r")),t=!1}finally{t&&this[Ge]()}}[Cr](){let t=!0;try{if(!this[pt]){this[pt]=!0;do{let e=this[Yo](),r=e.length===0?0:Te.readSync(this[U],e,0,e.length,null);if(!this[Qo](r,e))break}while(!0);this[pt]=!1}t=!1}finally{t&&this[Ge]()}}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.closeSync(t),this.emit("close")}}},ds=class extends Zg{readable=!1;writable=!0;[tr]=!1;[Vt]=!1;[_n]=!1;[Ve]=[];[Bi]=!1;[$e];[On];[Lt];[U];[Zi];[gt];[Po]=!1;[xt];constructor(t,e){e=e||{},super(e),this[$e]=t,this[U]=typeof e.fd=="number"?e.fd:void 0,this[On]=e.mode===void 0?438:e.mode,this[xt]=typeof e.start=="number"?e.start:void 0,this[Lt]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[xt]!==void 0?"r+":"w";this[Zi]=e.flags===void 0,this[gt]=e.flags===void 0?r:e.flags,this[U]===void 0&&this[Ft]()}emit(t,...e){if(t==="error"){if(this[tr])return!1;this[tr]=!0}return super.emit(t,...e)}get fd(){return this[U]}get path(){return this[$e]}[Lr](t){this[Ge](),this[Vt]=!0,this.emit("error",t)}[Ft](){Te.open(this[$e],this[gt],this[On],(t,e)=>this[Fr](t,e))}[Fr](t,e){this[Zi]&&this[gt]==="r+"&&t&&t.code==="ENOENT"?(this[gt]="w",this[Ft]()):t?this[Lr](t):(this[U]=e,this.emit("open",e),this[Vt]||this[Co]())}end(t,e){return t&&this.write(t,e),this[_n]=!0,!this[Vt]&&!this[Ve].length&&typeof this[U]=="number"&&this[Pr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[_n]?(this.emit("error",new Error("write() after end()")),!1):this[U]===void 0||this[Vt]||this[Ve].length?(this[Ve].push(t),this[Bi]=!0,!1):(this[Vt]=!0,this[Vi](t),!0)}[Vi](t){Te.write(this[U],t,0,t.length,this[xt],(e,r)=>this[Pr](e,r))}[Pr](t,e){t?this[Lr](t):(this[xt]!==void 0&&typeof e=="number"&&(this[xt]+=e),this[Ve].length?this[Co]():(this[Vt]=!1,this[_n]&&!this[Po]?(this[Po]=!0,this[Ge](),this.emit("finish")):this[Bi]&&(this[Bi]=!1,this.emit("drain"))))}[Co](){if(this[Ve].length===0)this[_n]&&this[Pr](null,0);else if(this[Ve].length===1)this[Vi](this[Ve].pop());else{let t=this[Ve];this[Ve]=[],am(this[U],t,this[xt],(e,r)=>this[Pr](e,r))}}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Bd=class extends ds{[Ft](){let t;if(this[Zi]&&this[gt]==="r+")try{t=Te.openSync(this[$e],this[gt],this[On])}catch(e){if(e?.code==="ENOENT")return this[gt]="w",this[Ft]();throw e}else t=Te.openSync(this[$e],this[gt],this[On]);this[Fr](null,t)}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.closeSync(t),this.emit("close")}}[Vi](t){let e=!0;try{this[Pr](null,Te.writeSync(this[U],t,0,t.length,this[xt])),e=!1}finally{if(e)try{this[Ge]()}catch{}}}},hm=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"]]),fm=t=>!!t.sync&&!!t.file,um=t=>!t.sync&&!!t.file,pm=t=>!!t.sync&&!t.file,gm=t=>!t.sync&&!t.file,mm=t=>!!t.file,wm=t=>hm.get(t)||t,Sa=(t={})=>{if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){let i=wm(r);e[i]=n}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Bn=(t,e,r,n,i)=>Object.assign((s=[],o,a)=>{Array.isArray(s)&&(o=s,s={}),typeof o=="function"&&(a=o,o=void 0),o=o?Array.from(o):[];let c=Sa(s);if(i?.(c,o),fm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return t(c,o)}else if(um(c)){let l=e(c,o);return a?l.then(()=>a(),a):l}else if(pm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,o)}else if(gm(c)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return n(c,o)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:n,validate:i}),Em=ym.constants||{ZLIB_VERNUM:4736},Qe=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},Em)),Sm=rr.concat,ad=Object.getOwnPropertyDescriptor(rr,"concat"),Im=t=>t,Fo=ad?.writable===!0||ad?.set!==void 0?t=>{rr.concat=t?Im:Sm}:t=>{},nr=Symbol("_superWrite"),Ui=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"}},Mo=Symbol("flushFlag"),Ia=class extends sr{#e=!1;#r=!1;#n;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#n}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#n=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof od[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new od[e](t)}catch(r){throw new Ui(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ui(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return ea(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(rr.alloc(0),{[Mo]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#r=!0,super.end(r)}get ended(){return this.#r}[nr](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=rr.from(t,e)),this.#e)return;ea(this.#t,"zlib binding closed");let n=this.#t._handle,i=n.close;n.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},Fo(!0);let o;try{let c=typeof t[Mo]=="number"?t[Mo]:this.#n;o=this.#t._processChunk(t,c),Fo(!1)}catch(c){Fo(!1),this.#o(new Ui(c,this.write))}finally{this.#t&&(this.#t._handle=n,n.close=i,this.#t.close=s,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",c=>this.#o(new Ui(c,this.write)));let a;if(o)if(Array.isArray(o)&&o.length>0){let c=o[0];a=this[nr](rr.from(c));for(let l=1;l<o.length;l++)a=this[nr](o[l])}else a=this[nr](rr.from(o));return r&&r(),a}},zd=class extends Ia{#e;#r;constructor(t,e){t=t||{},t.flush=t.flush||Qe.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Qe.Z_FINISH,t.fullFlushFlag=Qe.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#r=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.#r!==e){this.flush(Qe.Z_SYNC_FLUSH),ea(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(n,i)=>{typeof n=="function"&&(i=n,n=this.flushFlag),this.flush(n),i?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#r=e)}}}},vm=class extends zd{#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)}},Tm=class extends zd{constructor(t){super(t,"Unzip")}},$d=class extends Ia{constructor(t,e){t=t||{},t.flush=t.flush||Qe.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Qe.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Qe.BROTLI_OPERATION_FLUSH,super(t,e)}},Rm=class extends $d{constructor(t){super(t,"BrotliCompress")}},km=class extends $d{constructor(t){super(t,"BrotliDecompress")}},Gd=class extends Ia{constructor(t,e){t=t||{},t.flush=t.flush||Qe.ZSTD_e_continue,t.finishFlush=t.finishFlush||Qe.ZSTD_e_end,t.fullFlushFlag=Qe.ZSTD_e_flush,super(t,e)}},bm=class extends Gd{constructor(t){super(t,"ZstdCompress")}},Am=class extends Gd{constructor(t){super(t,"ZstdDecompress")}},Om=(t,e)=>{if(Number.isSafeInteger(t))t<0?Pm(t,e):xm(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},xm=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Pm=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var n=e.length;n>1;n--){var i=t&255;t=Math.floor(t/256),r?e[n-1]=Hd(i):i===0?e[n-1]=0:(r=!0,e[n-1]=jd(i))}},Cm=t=>{let e=t[0],r=e===128?Nm(t.subarray(1,t.length)):e===255?Dm(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},Dm=t=>{for(var e=t.length,r=0,n=!1,i=e-1;i>-1;i--){var s=Number(t[i]),o;n?o=Hd(s):s===0?o=s:(n=!0,o=jd(s)),o!==0&&(r-=o*Math.pow(256,e-i-1))}return r},Nm=t=>{for(var e=t.length,r=0,n=e-1;n>-1;n--){var i=Number(t[n]);i!==0&&(r+=i*Math.pow(256,e-n-1))}return r},Hd=t=>(255^t)&255,jd=t=>(255^t)+1&255,Lm={};Vg(Lm,{code:()=>va,isCode:()=>Ki,isName:()=>Fm,name:()=>hs});var Ki=t=>hs.has(t),Fm=t=>va.has(t),hs=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"]]),va=new Map(Array.from(hs).map(t=>[t[1],t[0]])),ir=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,n){Buffer.isBuffer(t)?this.decode(t,e||0,r,n):t&&this.#r(t)}decode(t,e,r,n){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");this.path=r?.path??Zt(t,e,100),this.mode=r?.mode??n?.mode??Pt(t,e+100,8),this.uid=r?.uid??n?.uid??Pt(t,e+108,8),this.gid=r?.gid??n?.gid??Pt(t,e+116,8),this.size=r?.size??n?.size??Pt(t,e+124,12),this.mtime=r?.mtime??n?.mtime??Bo(t,e+136,12),this.cksum=Pt(t,e+148,12),n&&this.#r(n,!0),r&&this.#r(r);let i=Zt(t,e+156,1);if(Ki(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Zt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=r?.uname??n?.uname??Zt(t,e+265,32),this.gname=r?.gname??n?.gname??Zt(t,e+297,32),this.devmaj=r?.devmaj??n?.devmaj??Pt(t,e+329,8)??0,this.devmin=r?.devmin??n?.devmin??Pt(t,e+337,8)??0,t[e+475]!==0){let o=Zt(t,e+345,155);this.path=o+"/"+this.path}else{let o=Zt(t,e+345,130);o&&(this.path=o+"/"+this.path),this.atime=r?.atime??n?.atime??Bo(t,e+476,12),this.ctime=r?.ctime??n?.ctime??Bo(t,e+488,12)}let s=256;for(let o=e;o<e+148;o++)s+=t[o];for(let o=e+156;o<e+512;o++)s+=t[o];this.cksumValid=s===this.cksum,this.cksum===void 0&&s===256&&(this.nullBlock=!0)}#r(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,n])=>!(n==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,n=Mm(this.path||"",r),i=n[0],s=n[1];this.needPax=!!n[2],this.needPax=Kt(t,e,100,i)||this.needPax,this.needPax=Ct(t,e+100,8,this.mode)||this.needPax,this.needPax=Ct(t,e+108,8,this.uid)||this.needPax,this.needPax=Ct(t,e+116,8,this.gid)||this.needPax,this.needPax=Ct(t,e+124,12,this.size)||this.needPax,this.needPax=Uo(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Kt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Kt(t,e+265,32,this.uname)||this.needPax,this.needPax=Kt(t,e+297,32,this.gname)||this.needPax,this.needPax=Ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Kt(t,e+345,r,s)||this.needPax,t[e+475]!==0?this.needPax=Kt(t,e+345,155,s)||this.needPax:(this.needPax=Kt(t,e+345,130,s)||this.needPax,this.needPax=Uo(t,e+476,12,this.atime)||this.needPax,this.needPax=Uo(t,e+488,12,this.ctime)||this.needPax);let o=256;for(let a=e;a<e+148;a++)o+=t[a];for(let a=e+156;a<e+512;a++)o+=t[a];return this.cksum=o,Ct(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:hs.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(va.get(t));if(Ki(e)||e==="Unsupported")this.#e=e;else if(Ki(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Mm=(t,e)=>{let r=t,n="",i,s=kr.parse(t).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=kr.dirname(r),r=kr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(n)<=e?i=[r,n,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(n)<=e?i=[r.slice(0,99),n,!0]:(r=kr.join(kr.basename(n),r),n=kr.dirname(n));while(n!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},Zt=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Bo=(t,e,r)=>Bm(Pt(t,e,r)),Bm=t=>t===void 0?void 0:new Date(t*1e3),Pt=(t,e,r)=>Number(t[e])&128?Cm(t.subarray(e,e+r)):zm(t,e,r),Um=t=>isNaN(t)?void 0:t,zm=(t,e,r)=>Um(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),$m={12:8589934591,8:2097151},Ct=(t,e,r,n)=>n===void 0?!1:n>$m[r]||n<0?(Om(n,t.subarray(e,e+r)),!0):(Gm(t,e,r,n),!1),Gm=(t,e,r,n)=>t.write(Hm(n,r),e,r,"ascii"),Hm=(t,e)=>jm(Math.floor(t).toString(8),e),jm=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Uo=(t,e,r,n)=>n===void 0?!1:Ct(t,e,r,n.getTime()/1e3),Wm=new Array(156).join("\0"),Kt=(t,e,r,n)=>n===void 0?!1:(t.write(n+Wm,e,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),ss=class Wd{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),n=512*Math.ceil(1+r/512),i=Buffer.allocUnsafe(n);for(let s=0;s<512;s++)i[s]=0;new ir({path:("PaxHeader/"+qm(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(e,512,r,"utf8");for(let s=r+512;s<i.length;s++)i[s]=0;return i}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],n=r instanceof Date?r.getTime()/1e3:r,i=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+n+`
81
- `,s=Buffer.byteLength(i),o=Math.floor(Math.log(s)/Math.log(10))+1;return s+o>=Math.pow(10,o)&&(o+=1),o+s+i}static parse(e,r,n=!1){return new Wd(Jm(Vm(e),r),n)}},Jm=(t,e)=>e?Object.assign({},e,t):t,Vm=t=>t.replace(/\n$/,"").split(`
82
- `).reduce(Zm,Object.create(null)),Zm=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let n=e.split("="),i=n.shift();if(!i)return t;let s=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=n.join("=");return t[s]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(s)?new Date(Number(o)*1e3):/^[0-9]+$/.test(o)?+o:o,t},Km=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,D=Km!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),qd=class extends sr{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=D(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?D(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,n-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=D(t.path)),t.linkpath&&(t.linkpath=D(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,n])=>!(n==null||r==="path"&&e))))}},fs=(t,e,r,n={})=>{t.file&&(n.file=t.file),t.cwd&&(n.cwd=t.cwd),n.code=r instanceof Error&&r.code||e,n.tarCode=e,!t.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),t.emit("warn",e,r,n)):r instanceof Error?t.emit("error",Object.assign(r,n)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),n))},Xm=1024*1024,ta=Buffer.from([31,139]),ra=Buffer.from([40,181,47,253]),Qm=Math.max(ta.length,ra.length),Ce=Symbol("state"),Xt=Symbol("writeEntry"),ft=Symbol("readEntry"),zo=Symbol("nextEntry"),cd=Symbol("processEntry"),Ze=Symbol("extendedHeader"),En=Symbol("globalExtendedHeader"),kt=Symbol("meta"),ld=Symbol("emitMeta"),H=Symbol("buffer"),ut=Symbol("queue"),bt=Symbol("ended"),$o=Symbol("emittedEnd"),Qt=Symbol("emit"),Y=Symbol("unzip"),zi=Symbol("consumeChunk"),$i=Symbol("consumeChunkSub"),Go=Symbol("consumeBody"),dd=Symbol("consumeMeta"),hd=Symbol("consumeHeader"),Sn=Symbol("consuming"),Ho=Symbol("bufferConcat"),Gi=Symbol("maybeEnd"),br=Symbol("writing"),At=Symbol("aborted"),Hi=Symbol("onDone"),Yt=Symbol("sawValidEntry"),ji=Symbol("sawNullBlock"),Wi=Symbol("sawEOF"),fd=Symbol("closeStream"),Ym=()=>!0,Mn=class extends _m{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[ut]=[];[H];[ft];[Xt];[Ce]="begin";[kt]="";[Ze];[En];[bt]=!1;[Y];[At]=!1;[Yt];[ji]=!1;[Wi]=!1;[br]=!1;[Sn]=!1;[$o]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Hi,()=>{(this[Ce]==="begin"||this[Yt]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Hi,t.ondone):this.on(Hi,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Xm,this.filter=typeof t.filter=="function"?t.filter:Ym;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[fd]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){fs(this,t,e,r)}[hd](t,e){this[Yt]===void 0&&(this[Yt]=!1);let r;try{r=new ir(t,e,this[Ze],this[En])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[ji]?(this[Wi]=!0,this[Ce]==="begin"&&(this[Ce]="header"),this[Qt]("eof")):(this[ji]=!0,this[Qt]("nullBlock"));else if(this[ji]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[Xt]=new qd(r,this[Ze],this[En]);if(!this[Yt])if(i.remain){let s=()=>{i.invalid||(this[Yt]=!0)};i.on("end",s)}else this[Yt]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[Qt]("ignoredEntry",i),this[Ce]="ignore",i.resume()):i.size>0&&(this[kt]="",i.on("data",s=>this[kt]+=s),this[Ce]="meta"):(this[Ze]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[Qt]("ignoredEntry",i),this[Ce]=i.remain?"ignore":"header",i.resume()):(i.remain?this[Ce]="body":(this[Ce]="header",i.end()),this[ft]?this[ut].push(i):(this[ut].push(i),this[zo]())))}}}[fd](){queueMicrotask(()=>this.emit("close"))}[cd](t){let e=!0;if(!t)this[ft]=void 0,e=!1;else if(Array.isArray(t)){let[r,...n]=t;this.emit(r,...n)}else this[ft]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[zo]()),e=!1);return e}[zo](){do;while(this[cd](this[ut].shift()));if(this[ut].length===0){let t=this[ft];!t||t.flowing||t.size===t.remain?this[br]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Go](t,e){let r=this[Xt];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=t.length&&e===0?t:t.subarray(e,e+n);return r.write(i),r.blockRemain||(this[Ce]="header",this[Xt]=void 0,r.end()),i.length}[dd](t,e){let r=this[Xt],n=this[Go](t,e);return!this[Xt]&&r&&this[ld](r),n}[Qt](t,e,r){this[ut].length===0&&!this[ft]?this.emit(t,e,r):this[ut].push([t,e,r])}[ld](t){switch(this[Qt]("meta",this[kt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ze]=ss.parse(this[kt],this[Ze],!1);break;case"GlobalExtendedHeader":this[En]=ss.parse(this[kt],this[En],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ze]??Object.create(null);this[Ze]=e,e.path=this[kt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ze]||Object.create(null);this[Ze]=e,e.linkpath=this[kt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[At]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[At])return r?.(),!1;if((this[Y]===void 0||this.brotli===void 0&&this[Y]===!1)&&t){if(this[H]&&(t=Buffer.concat([this[H],t]),this[H]=void 0),t.length<Qm)return this[H]=t,r?.(),!0;for(let o=0;this[Y]===void 0&&o<ta.length;o++)t[o]!==ta[o]&&(this[Y]=!1);let i=!1;if(this[Y]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<ra.length;o++)if(t[o]!==ra[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[Y]===!1&&s)if(t.length<512)if(this[bt])this.brotli=!0;else return this[H]=t,r?.(),!0;else try{new ir(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Y]===void 0||this[Y]===!1&&(this.brotli||i)){let o=this[bt];this[bt]=!1,this[Y]=this[Y]===void 0?new Tm({}):i?new Am({}):new km({}),this[Y].on("data",c=>this[zi](c)),this[Y].on("error",c=>this.abort(c)),this[Y].on("end",()=>{this[bt]=!0,this[zi]()}),this[br]=!0;let a=!!this[Y][o?"end":"write"](t);return this[br]=!1,r?.(),a}}this[br]=!0,this[Y]?this[Y].write(t):this[zi](t),this[br]=!1;let n=this[ut].length>0?!1:this[ft]?this[ft].flowing:!0;return!n&&this[ut].length===0&&this[ft]?.once("drain",()=>this.emit("drain")),r?.(),n}[Ho](t){t&&!this[At]&&(this[H]=this[H]?Buffer.concat([this[H],t]):t)}[Gi](){if(this[bt]&&!this[$o]&&!this[At]&&!this[Sn]){this[$o]=!0;let t=this[Xt];if(t&&t.blockRemain){let e=this[H]?this[H].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[H]&&t.write(this[H]),t.end()}this[Qt](Hi)}}[zi](t){if(this[Sn]&&t)this[Ho](t);else if(!t&&!this[H])this[Gi]();else if(t){if(this[Sn]=!0,this[H]){this[Ho](t);let e=this[H];this[H]=void 0,this[$i](e)}else this[$i](t);for(;this[H]&&this[H]?.length>=512&&!this[At]&&!this[Wi];){let e=this[H];this[H]=void 0,this[$i](e)}this[Sn]=!1}(!this[H]||this[bt])&&this[Gi]()}[$i](t){let e=0,r=t.length;for(;e+512<=r&&!this[At]&&!this[Wi];)switch(this[Ce]){case"begin":case"header":this[hd](t,e),e+=512;break;case"ignore":case"body":e+=this[Go](t,e);break;case"meta":e+=this[dd](t,e);break;default:throw new Error("invalid state: "+this[Ce])}e<r&&(this[H]=this[H]?Buffer.concat([t.subarray(e),this[H]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[At]||(this[Y]?(t&&this[Y].write(t),this[Y].end()):(this[bt]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Gi]())),this}},xn=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},ew=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},Jd=(t,e)=>{let r=new Map(e.map(s=>[xn(s),!0])),n=t.filter,i=(s,o="")=>{let a=o||dm(s).root||".",c;if(s===a)c=!1;else{let l=r.get(s);c=l!==void 0?l:i(lm(s),a)}return r.set(s,c),c};t.filter=n?(s,o)=>n(s,o)&&i(xn(s)):s=>i(xn(s))},tw=t=>{let e=new Mn(t),r=t.file,n;try{n=Dr.openSync(r,"r");let i=Dr.fstatSync(n),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),a=Dr.readSync(n,o,0,i.size,0);e.end(a===o.byteLength?o:o.subarray(0,a))}else{let o=0,a=Buffer.allocUnsafe(s);for(;o<i.size;){let c=Dr.readSync(n,a,0,s,o);if(c===0)break;o+=c,e.write(a.subarray(0,c))}e.end()}}finally{if(typeof n=="number")try{Dr.closeSync(n)}catch{}}},rw=(t,e)=>{let r=new Mn(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("end",s),Dr.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ea(i,{readSize:n,size:c.size});l.on("error",o),l.pipe(r)}})})},Mr=Bn(tw,rw,t=>new Mn(t),t=>new Mn(t),(t,e)=>{e?.length&&Jd(t,e),t.noResume||ew(t)}),Vd=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:iw,parse:pd}=nw,Ta=t=>{let e="",r=pd(t);for(;iw(t)||r.root;){let n=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(n.length),e+=n,r=pd(t)}return[e,t]},us=["|","<",">","?",":"],Ra=us.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),sw=new Map(us.map((t,e)=>[t,Ra[e]])),ow=new Map(Ra.map((t,e)=>[t,us[e]])),gd=t=>us.reduce((e,r)=>e.split(r).join(sw.get(r)),t),aw=t=>Ra.reduce((e,r)=>e.split(r).join(ow.get(r)),t),Zd=(t,e)=>e?(t=D(t).replace(/^\.(\/|$)/,""),xn(e)+"/"+t):D(t),cw=16*1024*1024,md=Symbol("process"),wd=Symbol("file"),_d=Symbol("directory"),na=Symbol("symlink"),yd=Symbol("hardlink"),In=Symbol("header"),Xi=Symbol("read"),ia=Symbol("lstat"),Qi=Symbol("onlstat"),sa=Symbol("onread"),oa=Symbol("onreadlink"),aa=Symbol("openfile"),ca=Symbol("onopenfile"),Dt=Symbol("close"),as=Symbol("mode"),la=Symbol("awaitDrain"),jo=Symbol("ondrain"),Xe=Symbol("prefix"),Kd=class extends sr{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Sa(e);super(),this.path=D(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||cw,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=D(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?D(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[s,o]=Ta(this.path);s&&typeof o=="string"&&(this.path=o,n=s)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=aw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=D(r.absolute||ud.resolve(this.cwd,t)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[Qi](i):this[ia]()}warn(t,e,r={}){return fs(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[ia](){Ke.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Qi](e)})}[Qi](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=hw(t),this.emit("stat",t),this[md]()}[md](){switch(this.type){case"File":return this[wd]();case"Directory":return this[_d]();case"SymbolicLink":return this[na]();default:return this.end()}}[as](t){return Vd(t,this.type==="Directory",this.portable)}[Xe](t){return Zd(t,this.prefix)}[In](){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 ir({path:this[Xe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Xe](this.linkpath):this.linkpath,mode:this[as](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 ss({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[Xe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Xe](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)}[_d](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[In](),this.end()}[na](){Ke.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[oa](e)})}[oa](t){this.linkpath=D(t),this[In](),this.end()}[yd](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=D(ud.relative(this.cwd,t)),this.stat.size=0,this[In](),this.end()}[wd](){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[yd](e);this.linkCache.set(t,this.absolute)}if(this[In](),this.stat.size===0)return this.end();this[aa]()}[aa](){Ke.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[ca](e)})}[ca](t){if(this.fd=t,this.#e)return this[Dt]();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[Xi]()}[Xi](){let{fd:t,buf:e,offset:r,length:n,pos:i}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Ke.read(t,e,r,n,i,(s,o)=>{if(s)return this[Dt](()=>this.emit("error",s));this[sa](o)})}[Dt](t=()=>{}){this.fd!==void 0&&Ke.close(this.fd,t)}[sa](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Dt](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Dt](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[jo]():this[la](()=>this[jo]())}[la](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[jo](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Dt](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[Xi]()}},lw=class extends Kd{sync=!0;[ia](){this[Qi](Ke.lstatSync(this.absolute))}[na](){this[oa](Ke.readlinkSync(this.absolute))}[aa](){this[ca](Ke.openSync(this.absolute,"r"))}[Xi](){let t=!0;try{let{fd:e,buf:r,offset:n,length:i,pos:s}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let o=Ke.readSync(e,r,n,i,s);this[sa](o),t=!1}finally{if(t)try{this[Dt](()=>{})}catch{}}}[la](t){t()}[Dt](t=()=>{}){this.fd!==void 0&&Ke.closeSync(this.fd),t()}},dw=class extends sr{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return fs(this,t,e,r)}constructor(t,e={}){let r=Sa(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:n}=t;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=D(t.path),this.mode=t.mode!==void 0?this[as](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?D(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[o,a]=Ta(this.path);o&&typeof a=="string"&&(this.path=a,i=o)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new ir({path:this[Xe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Xe](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}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new ss({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[Xe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Xe](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 s=this.header?.block;if(!s)throw new Error("failed to encode header");super.write(s),t.pipe(this)}[Xe](t){return Zd(t,this.prefix)}[as](t){return Vd(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let n=t.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},hw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",fw=class Nr{tail;head;length=0;static create(e=[]){return new Nr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,n=e.prev;return r&&(r.prev=n),n&&(n.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=n),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,n=e.length;r<n;r++)pw(this,e[r]);return this.length}unshift(...e){for(var r=0,n=e.length;r<n;r++)gw(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let n=this.head,i=0;n;i++)e.call(r,n.value,i,this),n=n.next}forEachReverse(e,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)e.call(r,n.value,i,this),n=n.prev}get(e){let r=0,n=this.head;for(;n&&r<e;r++)n=n.next;if(r===e&&n)return n.value}getReverse(e){let r=0,n=this.tail;for(;n&&r<e;r++)n=n.prev;if(r===e&&n)return n.value}map(e,r){r=r||this;let n=new Nr;for(let i=this.head;i;)n.push(e.call(r,i.value,this)),i=i.next;return n}mapReverse(e,r){r=r||this;var n=new Nr;for(let i=this.tail;i;)n.push(e.call(r,i.value,this)),i=i.prev;return n}reduce(e,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var s=0;i;s++)n=e(n,i.value,s),i=i.next;return n}reduceReverse(e,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let s=this.length-1;i;s--)n=e(n,i.value,s),i=i.prev;return n}toArray(){let e=new Array(this.length);for(let r=0,n=this.head;n;r++)e[r]=n.value,n=n.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,n=this.tail;n;r++)e[r]=n.value,n=n.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let n=new Nr;if(r<e||r<0)return n;e<0&&(e=0),r>this.length&&(r=this.length);let i=this.head,s=0;for(s=0;i&&s<e;s++)i=i.next;for(;i&&s<r;s++,i=i.next)n.push(i.value);return n}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let n=new Nr;if(r<e||r<0)return n;e<0&&(e=0),r>this.length&&(r=this.length);let i=this.length,s=this.tail;for(;s&&i>r;i--)s=s.prev;for(;s&&i>e;i--,s=s.prev)n.push(s.value);return n}splice(e,r=0,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let i=this.head;for(let o=0;i&&o<e;o++)i=i.next;let s=[];for(let o=0;i&&o<r;o++)s.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let o of n)i=uw(this,i,o);return s}reverse(){let e=this.head,r=this.tail;for(let n=e;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=e,this}};function uw(t,e,r){let n=e,i=e?e.next:t.head,s=new ka(r,n,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function pw(t,e){t.tail=new ka(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function gw(t,e){t.head=new ka(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var ka=class{list;next;prev;value;constructor(t,e,r,n){this.list=n,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Sd=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Id=Buffer.alloc(1024),Yi=Symbol("onStat"),vn=Symbol("ended"),Ue=Symbol("queue"),Tn=Symbol("queue"),Ot=Symbol("current"),er=Symbol("process"),Rn=Symbol("processing"),qi=Symbol("processJob"),ze=Symbol("jobs"),Wo=Symbol("jobDone"),es=Symbol("addFSEntry"),vd=Symbol("addTarEntry"),da=Symbol("stat"),ha=Symbol("readdir"),ts=Symbol("onreaddir"),rs=Symbol("pipe"),Td=Symbol("entry"),qo=Symbol("entryOpt"),ns=Symbol("writeEntryClass"),Xd=Symbol("write"),Jo=Symbol("ondrain"),ps=class extends sr{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ns];onWriteEntry;[Ue];[Tn]=new Map;[ze]=0;[Rn]=!1;[vn]=!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=D(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[ns]=Kd,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 vm(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Rm(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new bm(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[Jo]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Jo]);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[Ue]=new fw,this[ze]=0,this.jobs=Number(t.jobs)||4,this[Rn]=!1,this[vn]=!1}[Xd](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[vn]=!0,this[er](),r&&r(),this}write(t){if(this[vn])throw new Error("write after end");return t instanceof qd?this[vd](t):this[es](t),this.flowing}[vd](t){let e=D(Ed.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Sd(t.path,e);r.entry=new dw(t,this[qo](r)),r.entry.on("end",()=>this[Wo](r)),this[ze]+=1,this[Ue].push(r)}this[er]()}[es](t){let e=D(Ed.resolve(this.cwd,t));this[Ue].push(new Sd(t,e)),this[er]()}[da](t){t.pending=!0,this[ze]+=1;let e=this.follow?"stat":"lstat";os[e](t.absolute,(r,n)=>{t.pending=!1,this[ze]-=1,r?this.emit("error",r):this[Yi](t,n)})}[Yi](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[Ot])this[qi](t);else{let r=`${e.dev}:${e.ino}`,n=this[Tn].get(r);n?n.push(t):this[Tn].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[er]()}[ha](t){t.pending=!0,this[ze]+=1,os.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[ze]-=1,e)return this.emit("error",e);this[ts](t,r)})}[ts](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[er]()}[er](){if(!this[Rn]){this[Rn]=!0;for(let t=this[Ue].head;t&&this[ze]<this.jobs;t=t.next)if(this[qi](t.value),t.value.ignore){let e=t.next;this[Ue].removeNode(t),t.next=e}this[Rn]=!1,this[vn]&&this[Ue].length===0&&this[ze]===0&&(this.zip?this.zip.end(Id):(super.write(Id),super.end()))}}get[Ot](){return this[Ue]&&this[Ue].head&&this[Ue].head.value}[Wo](t){this[Ue].shift(),this[ze]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,n=this[Tn].get(r);if(n){this[Tn].delete(r);for(let i of n)i.pending=!1,this[qi](i)}}this[er]()}[qi](t){if(t.pending&&t.pendingLink&&t===this[Ot]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Ot]&&!t.piped&&this[rs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Yi](t,e):this[da](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[ts](t,e):this[ha](t),!t.readdir)return}if(t.entry=this[Td](t),!t.entry){t.ignore=!0;return}t===this[Ot]&&!t.piped&&this[rs](t)}}}[qo](t){return{onwarn:(e,r,n)=>this.warn(e,r,n),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}}[Td](t){this[ze]+=1;try{return new this[ns](t.path,this[qo](t)).on("end",()=>this[Wo](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Jo](){this[Ot]&&this[Ot].entry&&this[Ot].entry.resume()}[rs](t){t.piped=!0,t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[es](s+n)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",n=>{r.write(n)||e.pause()}):e.on("data",n=>{super.write(n)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){fs(this,t,e,r)}},ba=class extends ps{sync=!0;constructor(t){super(t),this[ns]=lw}pause(){}resume(){}[da](t){let e=this.follow?"statSync":"lstatSync";this[Yi](t,os[e](t.absolute))}[ha](t){this[ts](t,os.readdirSync(t.absolute))}[rs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[es](s+n)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",n=>{r.write(n)}):e.on("data",n=>{super[Xd](n)})}},mw=(t,e)=>{let r=new ba(t),n=new Bd(t.file,{mode:t.mode||438});r.pipe(n),Qd(r,e)},ww=(t,e)=>{let r=new ps(t),n=new ds(t.file,{mode:t.mode||438});r.pipe(n);let i=new Promise((s,o)=>{n.on("error",o),n.on("close",s),r.on("error",o)});return Yd(r,e).catch(s=>r.emit("error",s)),i},Qd=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Mr({file:Ud.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r)}),t.end()},Yd=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Mr({file:Ud.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{t.add(n)}}):t.add(r);t.end()},_w=(t,e)=>{let r=new ba(t);return Qd(r,e),r},yw=(t,e)=>{let r=new ps(t);return Yd(r,e).catch(n=>r.emit("error",n)),r},ST=Bn(mw,ww,_w,yw,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),Sw=process.env.__FAKE_PLATFORM__||process.platform,nh=Sw==="win32",{O_CREAT:ih,O_NOFOLLOW:Rd,O_TRUNC:sh,O_WRONLY:oh}=rh.constants,ah=Number(process.env.__FAKE_FS_O_FILENAME__)||rh.constants.UV_FS_O_FILEMAP||0,Iw=nh&&!!ah,vw=512*1024,Tw=ah|sh|ih|oh,kd=!nh&&typeof Rd=="number"?Rd|sh|ih|oh:null,ch=kd!==null?()=>kd:Iw?t=>t<vw?Tw:"w":()=>"w",fa=(t,e,r)=>{try{return gs.lchownSync(t,e,r)}catch(n){if(n?.code!=="ENOENT")throw n}},cs=(t,e,r,n)=>{gs.lchown(t,e,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},Rw=(t,e,r,n,i)=>{if(e.isDirectory())lh(Pn.resolve(t,e.name),r,n,s=>{if(s)return i(s);let o=Pn.resolve(t,e.name);cs(o,r,n,i)});else{let s=Pn.resolve(t,e.name);cs(s,r,n,i)}},lh=(t,e,r,n)=>{gs.readdir(t,{withFileTypes:!0},(i,s)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!s.length)return cs(t,e,r,n);let o=s.length,a=null,c=l=>{if(!a){if(l)return n(a=l);if(--o===0)return cs(t,e,r,n)}};for(let l of s)Rw(t,l,e,r,c)})},kw=(t,e,r,n)=>{e.isDirectory()&&dh(Pn.resolve(t,e.name),r,n),fa(Pn.resolve(t,e.name),r,n)},dh=(t,e,r)=>{let n;try{n=gs.readdirSync(t,{withFileTypes:!0})}catch(i){let s=i;if(s?.code==="ENOENT")return;if(s?.code==="ENOTDIR"||s?.code==="ENOTSUP")return fa(t,e,r);throw s}for(let i of n)kw(t,i,e,r);return fa(t,e,r)},hh=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"}},ms=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"}},Aw=(t,e)=>{Ae.stat(t,(r,n)=>{(r||!n.isDirectory())&&(r=new hh(t,r?.code||"ENOTDIR")),e(r)})},Ow=(t,e,r)=>{t=D(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,o=e.uid,a=e.gid,c=typeof o=="number"&&typeof a=="number"&&(o!==e.processUid||a!==e.processGid),l=e.preserve,d=e.unlink,p=D(e.cwd),m=(u,g)=>{u?r(u):g&&c?lh(g,o,a,w=>m(w)):s?Ae.chmod(t,i,r):r()};if(t===p)return Aw(t,m);if(l)return bw.mkdir(t,{mode:i,recursive:!0}).then(u=>m(null,u??void 0),m);let f=D(ls.relative(p,t)).split("/");ua(p,f,i,d,p,void 0,m)},ua=(t,e,r,n,i,s,o)=>{if(e.length===0)return o(null,s);let a=e.shift(),c=D(ls.resolve(t+"/"+a));Ae.mkdir(c,r,fh(c,e,r,n,i,s,o))},fh=(t,e,r,n,i,s,o)=>a=>{a?Ae.lstat(t,(c,l)=>{if(c)c.path=c.path&&D(c.path),o(c);else if(l.isDirectory())ua(t,e,r,n,i,s,o);else if(n)Ae.unlink(t,d=>{if(d)return o(d);Ae.mkdir(t,r,fh(t,e,r,n,i,s,o))});else{if(l.isSymbolicLink())return o(new ms(t,t+"/"+e.join("/")));o(a)}}):(s=s||t,ua(t,e,r,n,i,s,o))},xw=t=>{let e=!1,r;try{e=Ae.statSync(t).isDirectory()}catch(n){r=n?.code}finally{if(!e)throw new hh(t,r??"ENOTDIR")}},Pw=(t,e)=>{t=D(t);let r=e.umask??18,n=e.mode|448,i=(n&r)!==0,s=e.uid,o=e.gid,a=typeof s=="number"&&typeof o=="number"&&(s!==e.processUid||o!==e.processGid),c=e.preserve,l=e.unlink,d=D(e.cwd),p=u=>{u&&a&&dh(u,s,o),i&&Ae.chmodSync(t,n)};if(t===d)return xw(d),p();if(c)return p(Ae.mkdirSync(t,{mode:n,recursive:!0})??void 0);let m=D(ls.relative(d,t)).split("/"),f;for(let u=m.shift(),g=d;u&&(g+="/"+u);u=m.shift()){g=D(ls.resolve(g));try{Ae.mkdirSync(g,n),f=f||g}catch{let w=Ae.lstatSync(g);if(w.isDirectory())continue;if(l){Ae.unlinkSync(g),Ae.mkdirSync(g,n),f=f||g;continue}else if(w.isSymbolicLink())return new ms(g,g+"/"+m.join("/"))}}return p(f)},Vo=Object.create(null),bd=1e4,Ar=new Set,Cw=t=>{Ar.has(t)?Ar.delete(t):Vo[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Ar.add(t);let e=Vo[t],r=Ar.size-bd;if(r>bd/10){for(let n of Ar)if(Ar.delete(n),delete Vo[n],--r<=0)break}return e},Dw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Nw=Dw==="win32",Lw=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let n=e.at(-1);return n!==void 0&&(r=uh(n,r)),e.push(r||"/"),e},[]),Fw=class{#e=new Map;#r=new Map;#n=new Set;reserve(t,e){t=Nw?["win32 parallelization disabled"]:t.map(n=>xn(uh(Cw(n))));let r=new Set(t.map(n=>Lw(n)).reduce((n,i)=>n.concat(i)));this.#r.set(e,{dirs:r,paths:t});for(let n of t){let i=this.#e.get(n);i?i.push(e):this.#e.set(n,[e])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([e])]);else{let s=i.at(-1);s instanceof Set?s.add(e):i.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#r.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(n=>n&&n[0]===t)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(t))}#i(t){return this.#n.has(t)||!this.check(t)?!1:(this.#n.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#n.has(t))return!1;let e=this.#r.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:n}=e,i=new Set;for(let s of r){let o=this.#e.get(s);if(!o||o?.[0]!==t)continue;let a=o[1];if(!a){this.#e.delete(s);continue}if(o.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let s of n){let o=this.#e.get(s),a=o?.[0];if(!(!o||!(a instanceof Set)))if(a.size===1&&o.length===1){this.#e.delete(s);continue}else if(a.size===1){o.shift();let c=o[0];typeof c=="function"&&i.add(c)}else a.delete(t)}return this.#n.delete(t),i.forEach(s=>this.#i(s)),!0}},Mw=()=>process.umask(),Ad=Symbol("onEntry"),pa=Symbol("checkFs"),Od=Symbol("checkFs2"),ga=Symbol("isReusable"),De=Symbol("makeFs"),ma=Symbol("file"),wa=Symbol("directory"),is=Symbol("link"),xd=Symbol("symlink"),Pd=Symbol("hardlink"),An=Symbol("ensureNoSymlink"),Cd=Symbol("unsupported"),Dd=Symbol("checkPath"),Zo=Symbol("stripAbsolutePath"),Nt=Symbol("mkdir"),ae=Symbol("onError"),Ji=Symbol("pending"),Nd=Symbol("pend"),Or=Symbol("unpend"),Ko=Symbol("ended"),Xo=Symbol("maybeClose"),_a=Symbol("skip"),Cn=Symbol("doChown"),Dn=Symbol("uid"),Nn=Symbol("gid"),Ln=Symbol("checkedCwd"),Bw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Fn=Bw==="win32",Uw=1024,zw=(t,e)=>{if(!Fn)return N.unlink(t,e);let r=t+".DELETE."+th(16).toString("hex");N.rename(t,r,n=>{if(n)return e(n);N.unlink(r,e)})},$w=t=>{if(!Fn)return N.unlinkSync(t);let e=t+".DELETE."+th(16).toString("hex");N.renameSync(t,e),N.unlinkSync(e)},Ld=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Aa=class extends Mn{[Ko]=!1;[Ln]=!1;[Ji]=0;reservations=new Fw;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[Ko]=!0,this[Xo]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:Uw,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Fn,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=D(te.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Mw():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[Ad](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[Xo](){this[Ko]&&this[Ji]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Zo](t,e){let r=t[e],{type:n}=t;if(!r||this.preservePaths)return!0;let[i,s]=Ta(r),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||Fn&&/^[a-z]:\.\.$/i.test(o[0]??"")){if(e==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let a=te.posix.dirname(t.path),c=te.posix.normalize(te.posix.join(a,o.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return i&&(t[e]=String(s),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${e}`,{entry:t,[e]:r})),!0}[Dd](t){let e=D(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let n=D(String(t.linkpath)).split("/");if(n.length>=this.strip)t.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[Zo](t,"path")||!this[Zo](t,"linkpath"))return!1;if(t.absolute=te.isAbsolute(t.path)?D(te.resolve(t.path)):D(te.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:D(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:n}=te.win32.parse(String(t.absolute));t.absolute=n+gd(String(t.absolute).slice(n.length));let{root:i}=te.win32.parse(t.path);t.path=i+gd(t.path.slice(i.length))}return!0}[Ad](t){if(!this[Dd](t))return t.resume();switch(Ew.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[pa](t);default:return this[Cd](t)}}[ae](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Or](),e.resume())}[Nt](t,e,r){Ow(D(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Cn](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}[Dn](t){return Ld(this.uid,t.uid,this.processUid)}[Nn](t){return Ld(this.gid,t.gid,this.processGid)}[ma](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=new ds(String(t.absolute),{flags:ch(t.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&N.close(n.fd,()=>{}),n.write=()=>!0,this[ae](a,t),e()});let i=1,s=a=>{if(a){n.fd&&N.close(n.fd,()=>{}),this[ae](a,t),e();return}--i===0&&n.fd!==void 0&&N.close(n.fd,c=>{c?this[ae](c,t):this[Or](),e()})};n.on("finish",()=>{let a=String(t.absolute),c=n.fd;if(typeof c=="number"&&t.mtime&&!this.noMtime){i++;let l=t.atime||new Date,d=t.mtime;N.futimes(c,l,d,p=>p?N.utimes(a,l,d,m=>s(m&&p)):s())}if(typeof c=="number"&&this[Cn](t)){i++;let l=this[Dn](t),d=this[Nn](t);typeof l=="number"&&typeof d=="number"&&N.fchown(c,l,d,p=>p?N.chown(a,l,d,m=>s(m&&p)):s())}s()});let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",a=>{this[ae](a,t),e()}),t.pipe(o)),o.pipe(n)}[wa](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Nt](String(t.absolute),r,n=>{if(n){this[ae](n,t),e();return}let i=1,s=()=>{--i===0&&(e(),this[Or](),t.resume())};t.mtime&&!this.noMtime&&(i++,N.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[Cn](t)&&(i++,N.chown(String(t.absolute),Number(this[Dn](t)),Number(this[Nn](t)),s)),s()})}[Cd](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[xd](t,e){let r=D(te.relative(this.cwd,te.resolve(te.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[An](t,this.cwd,r,()=>this[is](t,String(t.linkpath),"symlink",e),n=>{this[ae](n,t),e()})}[Pd](t,e){let r=D(te.resolve(this.cwd,String(t.linkpath))),n=D(String(t.linkpath)).split("/");this[An](t,this.cwd,n,()=>this[is](t,r,"link",e),i=>{this[ae](i,t),e()})}[An](t,e,r,n,i){let s=r.shift();if(this.preservePaths||s===void 0)return n();let o=te.resolve(e,s);N.lstat(o,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new ms(o,te.resolve(o,r.join("/"))));this[An](t,o,r,n,i)})}[Nd](){this[Ji]++}[Or](){this[Ji]--,this[Xo]()}[_a](t){this[Or](),t.resume()}[ga](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Fn}[pa](t){this[Nd]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[Od](t,r))}[Od](t,e){let r=o=>{e(o)},n=()=>{this[Nt](this.cwd,this.dmode,o=>{if(o){this[ae](o,t),r();return}this[Ln]=!0,i()})},i=()=>{if(t.absolute!==this.cwd){let o=D(te.dirname(String(t.absolute)));if(o!==this.cwd)return this[Nt](o,this.dmode,a=>{if(a){this[ae](a,t),r();return}s()})}s()},s=()=>{N.lstat(String(t.absolute),(o,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[_a](t),r();return}if(o||this[ga](t,a))return this[De](null,t,r);if(a.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,l=d=>this[De](d??null,t,r);return c?N.chmod(String(t.absolute),Number(t.mode),l):l()}if(t.absolute!==this.cwd)return N.rmdir(String(t.absolute),c=>this[De](c??null,t,r))}if(t.absolute===this.cwd)return this[De](null,t,r);zw(String(t.absolute),c=>this[De](c??null,t,r))})};this[Ln]?i():n()}[De](t,e,r){if(t){this[ae](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[ma](e,r);case"Link":return this[Pd](e,r);case"SymbolicLink":return this[xd](e,r);case"Directory":case"GNUDumpDir":return this[wa](e,r)}}[is](t,e,r,n){N[r](e,String(t.absolute),i=>{i?this[ae](i,t):(this[Or](),t.resume()),n()})}},kn=t=>{try{return[null,t()]}catch(e){return[e,null]}},ph=class extends Aa{sync=!0;[De](t,e){return super[De](t,e,()=>{})}[pa](t){if(!this[Ln]){let i=this[Nt](this.cwd,this.dmode);if(i)return this[ae](i,t);this[Ln]=!0}if(t.absolute!==this.cwd){let i=D(te.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[Nt](i,this.dmode);if(s)return this[ae](s,t)}}let[e,r]=kn(()=>N.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[_a](t);if(e||this[ga](t,r))return this[De](null,t);if(r.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[o]=s?kn(()=>{N.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[De](o,t)}let[i]=kn(()=>N.rmdirSync(String(t.absolute)));this[De](i,t)}let[n]=t.absolute===this.cwd?[]:kn(()=>$w(String(t.absolute)));this[De](n,t)}[ma](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=o=>{let a;try{N.closeSync(i)}catch(c){a=c}(o||a)&&this[ae](o||a,t),e()},i;try{i=N.openSync(String(t.absolute),ch(t.size),r)}catch(o){return n(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[ae](o,t)),t.pipe(s)),s.on("data",o=>{try{N.writeSync(i,o,0,o.length)}catch(a){n(a)}}),s.on("end",()=>{let o=null;if(t.mtime&&!this.noMtime){let a=t.atime||new Date,c=t.mtime;try{N.futimesSync(i,a,c)}catch(l){try{N.utimesSync(String(t.absolute),a,c)}catch{o=l}}}if(this[Cn](t)){let a=this[Dn](t),c=this[Nn](t);try{N.fchownSync(i,Number(a),Number(c))}catch(l){try{N.chownSync(String(t.absolute),Number(a),Number(c))}catch{o=o||l}}}n(o)})}[wa](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,n=this[Nt](String(t.absolute),r);if(n){this[ae](n,t),e();return}if(t.mtime&&!this.noMtime)try{N.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Cn](t))try{N.chownSync(String(t.absolute),Number(this[Dn](t)),Number(this[Nn](t)))}catch{}e(),t.resume()}[Nt](t,e){try{return Pw(D(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[An](t,e,r,n,i){if(this.preservePaths||r.length===0)return n();let s=e;for(let o of r){s=te.resolve(s,o);let[a,c]=kn(()=>N.lstatSync(s));if(a)return n();if(c.isSymbolicLink())return i(new ms(s,te.resolve(e,r.join("/"))))}n()}[is](t,e,r,n){let i=`${r}Sync`;try{N[i](e,String(t.absolute)),n(),t.resume()}catch(s){return this[ae](s,t)}}},Gw=t=>{let e=new ph(t),r=t.file,n=eh.statSync(r),i=t.maxReadSize||16*1024*1024;new cm(r,{readSize:i,size:n.size}).pipe(e)},Hw=(t,e)=>{let r=new Aa(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("close",s),eh.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ea(i,{readSize:n,size:c.size});l.on("error",o),l.pipe(r)}})})},gh=Bn(Gw,Hw,t=>new ph(t),t=>new Aa(t),(t,e)=>{e?.length&&Jd(t,e)}),jw=(t,e)=>{let r=new ba(t),n=!0,i,s;try{try{i=be.openSync(t.file,"r+")}catch(c){if(c?.code==="ENOENT")i=be.openSync(t.file,"w+");else throw c}let o=be.fstatSync(i),a=Buffer.alloc(512);e:for(s=0;s<o.size;s+=512){for(let d=0,p=0;d<512;d+=p){if(p=be.readSync(i,a,d,a.length-d,s+d),s===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new ir(a);if(!c.cksumValid)break;let l=512*Math.ceil((c.size||0)/512);if(s+l+512>o.size)break;s+=l,t.mtimeCache&&c.mtime&&t.mtimeCache.set(String(c.path),c.mtime)}n=!1,Ww(t,r,s,i,e)}finally{if(n)try{be.closeSync(i)}catch{}}},Ww=(t,e,r,n,i)=>{let s=new Bd(t.file,{fd:n,start:r});e.pipe(s),Jw(e,i)},qw=(t,e)=>{e=Array.from(e);let r=new ps(t),n=(i,s,o)=>{let a=(m,f)=>{m?be.close(i,u=>o(m)):o(null,f)},c=0;if(s===0)return a(null,0);let l=0,d=Buffer.alloc(512),p=(m,f)=>{if(m||f===void 0)return a(m);if(l+=f,l<512&&f)return be.read(i,d,l,d.length-l,c+l,p);if(c===0&&d[0]===31&&d[1]===139)return a(new Error("cannot append to compressed archives"));if(l<512)return a(null,c);let u=new ir(d);if(!u.cksumValid)return a(null,c);let g=512*Math.ceil((u.size??0)/512);if(c+g+512>s||(c+=g+512,c>=s))return a(null,c);t.mtimeCache&&u.mtime&&t.mtimeCache.set(String(u.path),u.mtime),l=0,be.read(i,d,0,512,c,p)};be.read(i,d,0,512,c,p)};return new Promise((i,s)=>{r.on("error",s);let o="r+",a=(c,l)=>{if(c&&c.code==="ENOENT"&&o==="r+")return o="w+",be.open(t.file,o,a);if(c||!l)return s(c);be.fstat(l,(d,p)=>{if(d)return be.close(l,()=>s(d));n(l,p.size,(m,f)=>{if(m)return s(m);let u=new ds(t.file,{fd:l,start:f});r.pipe(u),u.on("error",s),u.on("close",i),Vw(r,e)})})};be.open(t.file,o,a)})},Jw=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Mr({file:mh.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r)}),t.end()},Vw=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Mr({file:mh.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r);t.end()},bn=Bn(jw,qw,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!mm(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")}),FT=Bn(bn.syncFile,bn.asyncFile,bn.syncNoFile,bn.asyncNoFile,(t,e=[])=>{bn.validate?.(t,e),Zw(t)}),Zw=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,n)=>e(r,n)&&!((t.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((t.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))};vt();var He={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",DELETE:"_agent/delete"};function Un(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function wh(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function _h(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function yh(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Br(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}ye();F();de();ye();function mt(t,e){if(Un(t)!=="cloud")throw new y("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function ws(t){return t.startsWith("http://")||t.startsWith("https://")}function _s(t){return t.endsWith("/")?t.slice(0,-1):t}ye();F();var ys="1008033",Eh="1289";var Sh="pbbp2",Ih="https://www.coze.cn",vh="/api/coze_claw/resource/get_frontier_key",Xw="https://www.coze.cn",Qw="wss://frontier.coze.cn";function Es(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Xw}function Th(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Qw}function Ur(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,n=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),n&&(e["x-use-ppe"]=n),e}function $n(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var zn=O("handshake");async function Oa(t){let e=Es(t.endpoint),r=t.timeoutMs??1e4,n=`${_s(e)}${vh}?aid=${encodeURIComponent(ys)}`,i={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Ur(t.ppeOverride)},s=new AbortController,o=setTimeout(()=>s.abort(),r);zn.info("frontier key handshake",{base:e});try{let a=await fetch(n,{method:"GET",headers:i,signal:s.signal}),c=a.headers.get("x-tt-logid")??"",l=a.headers.get("x-tt-trace-id")??"";if(!a.ok){let u=await a.text().catch(()=>"");throw new y("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${u.slice(0,200)}`)}let d=await a.json();if(d.code!==void 0&&d.code!==0)throw new y("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${d.code} msg=${d.msg??"-"} logid=${c}`);let p=d.data??{},m=typeof p.access_key=="string"&&p.access_key||typeof p.accessKey=="string"&&p.accessKey||void 0,f=typeof p.device_id=="string"&&p.device_id||typeof p.deviceId=="string"&&p.deviceId||void 0;if(!m||!f){let u=JSON.stringify(d).slice(0,500);throw new y("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${c}: ${u}`)}return zn.info("handshake ok",{remoteDeviceId:f,logid:c,traceId:l}),{accessKey:m,deviceId:f}}catch(a){if(a instanceof y)throw zn.error("handshake failed (bridge error)",{base:e,message:a.message,code:a.code}),a;if(a.name==="AbortError")throw zn.warn("handshake timeout",{base:e,timeoutMs:r}),new y("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:a});let c=a.cause;throw zn.error("handshake error",{base:e,message:a instanceof Error?a.message:String(a),errno:c?.code,syscall:c?.syscall,cause:String(a).slice(0,300)}),new y("UPSTREAM_HANDSHAKE_FAILED",String(a),{cause:a})}finally{clearTimeout(o)}}var xa=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ye="auto",Yw=2e5;function Rh(t){return{model:t.model??Ye,...t.modelToken?{modelToken:t.modelToken}:{}}}function kh(t){return!t||t===Ye}function bh(t){let e={};return t.modelToken?(e.ANTHROPIC_BASE_URL=xa,e.ANTHROPIC_AUTH_TOKEN=t.modelToken,e.ANTHROPIC_MODEL=t.model||Ye,t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))):kh(t.model)||(e.ANTHROPIC_MODEL=t.model),e}function Ah(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Ye}"`):kh(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${xa}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let r=t.modelInfo?.contextWindow??Yw;e.push("-c",`model_context_window=${r}`)}return e}function Oh(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Pa(t,e){let{ttEnv:r,usePpe:n}=$n(t),i={};return r&&(i["x-tt-env"]=r),n&&(i["x-use-ppe"]=n),e&&(i["x-mock-scenario"]=e),i}function xh(t,e,r){if(!t.modelToken)return{};let n=Pa(e,r);return Object.keys(n).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(n).map(([s,o])=>`${s}:${o}`).join(`
83
- `)}}function Ca(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Ph(t,e,r){if(!t.modelToken)return null;let n=t.model||Ye,i=Pa(e,r),s=["text"];t.modelInfo?.capabilities?.image===!0&&s.push("image");let o={baseUrl:`${xa}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:n,name:n,reasoning:!1,input:s,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??128e3,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(o.headers=i),o}function Ch(t,e,r){if(!t.modelToken)return[];let n=Pa(e,r),i=[];for(let[s,o]of Object.entries(n))i.push("-c",`model_providers.coze.http_headers.${s}="${o}"`);return i}var re=O("agent-handlers"),Dh=5*1024*1024,s_=1,o_=6,a_=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ss=class{constructor(e){this.opts=e}opts;async listSkills(e){mt(e._meta,"_agent/listSkills");let r=Br(e._meta),n=await this.loadAgentCfg(r),i=n?.workspace??lt(r).workspace,s=n?.skills??[],o=[];for(let a of s){let c=et(i,a.relPath,"SKILL.md");await r_(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(f_(a))}return{skills:o}}async addSkills(e){mt(e._meta,"_agent/addSkills");let r=Br(e._meta),n=await this.requireAgentCfg(r),i=e.skills??[],s=[...n.skills??[]],o=new Map(s.map((c,l)=>[c.skillId,l])),a=[];for(let c of i){let l=await Ua({agentId:r,workspace:n.workspace,framework:n.framework,skill:c});za(s,o,l),a.push(c)}return await ki(r,s),this.reloadAgentSessions(r,"skills-added"),{installedSkills:a}}async removeSkills(e){mt(e._meta,"_agent/removeSkills");let r=Br(e._meta),n=await this.requireAgentCfg(r),i=new Set(e.skillIds??[]),s=n.skills??[],o=[];for(let a of s){if(!i.has(a.skillId)){o.push(a);continue}let c=et(n.workspace,a.relPath);await t_(c,{recursive:!0,force:!0}),re.info("skill removed",{agentId:r,skillId:a.skillId,relPath:a.relPath})}return await ki(r,o),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let n=this.opts.agents.get(e);if(n)for(let[i,s]of n.sessions){if(!s.downstream)continue;let o=s.acpSessionId;if(o&&n.activeTriggers.has(o)||this.isRuntimePendingPermission(s)){s.reloadAfterTurn=!0,re.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:n.framework,cloudId:i,acpId:o});continue}let c=s.downstream;s.downstream=void 0,re.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:n.framework,cloudId:i,acpId:o}),c.stop(r).catch(l=>re.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:i,err:String(l)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return re.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,n=await he(r);if(!n)throw new y("AGENT_NOT_FOUND",`agent not found: ${r}`);if(n.cozeIdentity===e.cozeIdentity)return re.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await Sr(n.workspace,n.framework,e.cozeIdentity)}catch(i){throw re.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:n.framework,workspace:n.workspace,err:String(i)}),new y("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(i)}`,{cause:i})}return n.cozeIdentity=e.cozeIdentity,await ve(n),re.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:n.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new y("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let n=await he(r);return n?(n.disconnectedAt=Date.now(),n.disconnectReason=e.reason??"",await ve(n),re.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(re.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async switchModel(e){if(mt(e._meta,"_agent/switchModel"),!e.agentId)throw new y("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=e.model?.trim()?e.model:Ye,n=await he(e.agentId);if(!n)throw new y("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);n.model=r,e.modelInfo&&(n.modelInfo=e.modelInfo),await ve(n),re.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let i=this.opts.agents.get(e.agentId);if(!i)return re.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};i.model=r,e.modelInfo&&i.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(i).catch(o=>re.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(o)}));let s=[];for(let[o,a]of i.allSessionQueues())s.push(a.enqueue(async()=>{let c=i.sessions.get(o);c?.downstream&&(await c.downstream.stop(`switchModel: ${r}`).catch(()=>{}),c.downstream=void 0)}));return await Promise.all(s),re.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:s.length}),{ok:!0}}async resetAgent(e){if(mt(e._meta,He.RESET),!e.agentId)throw new y("IPC_BAD_REQUEST",`${He.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,He.RESET),await this.runDetailSync(e.agentId,He.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let n=this.opts.agents.get(e);if(!n){await this.clearPersistedAcpSessionIds(e),re.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await n.killAllRuntimes(r);for(let s of n.sessions.values())s.acpSessionId=void 0,s.replySeq=0,s.loadingSession=!1,s.spawnFailCount=void 0,s.spawnFailedAt=void 0;let i=new Map;for(let[s,o]of n.sessions)i.set(s,{modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt});await fn(e,i)}async clearPersistedAcpSessionIds(e){let r=await he(e).catch(()=>null);if(!r?.sessions)return;let n=!1;for(let i of Object.values(r.sessions))i.acpSessionId&&(i.acpSessionId=void 0,n=!0);n&&await ve(r)}async repairAgent(e){if(mt(e._meta,He.REPAIR),!e.agentId)throw new y("IPC_BAD_REQUEST",`${He.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new y("IPC_BAD_REQUEST",`${He.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(n){re.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(n)})}return await this.runDetailSync(e.agentId,He.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,n){if(!this.opts.detailSyncer){re.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(i){re.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:n,err:String(i)})}}async getFileTree(e){mt(e._meta,"_agent/getFileTree");let r=e._meta,n=Br(r),i=await this.resolveWorkspace(n),s=e.filePath??"",o=this.safeJoin(i,s),a=await Da(o).catch(()=>null);if(!a)throw new y("IPC_BAD_REQUEST",`path not found: ${s}`);if(a.isSymbolicLink())throw new y("IPC_BAD_REQUEST",`symlink not allowed: ${s}`);if(!await hn(o,i))throw new y("IPC_BAD_REQUEST",`path escapes workspace: ${s}`);let c=v_(e.depth);return a.isDirectory()?{tree:await I_(i,o,s,c)}:{tree:[{name:T_(s),path:zh(s||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){mt(e._meta,"_agent/getFileContent");let r=Br(e._meta),n=await this.resolveWorkspace(r);if(!e.filePath)throw new y("IPC_BAD_REQUEST","filePath required");let i=this.safeJoin(n,e.filePath),s=await Da(i).catch(()=>null);if(!s||!s.isFile())throw new y("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(s.isSymbolicLink())throw new y("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await hn(i,n))throw new y("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(s.size>Dh)throw new y("IPC_BAD_REQUEST",`file too large: ${s.size} bytes (max ${Dh})`);let o=await Nh(i);return o.includes(0)?{content:o.toString("base64"),encoding:"base64",size:s.size}:{content:o.toString("utf8"),encoding:"utf-8",size:s.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await he(e).catch(()=>null))?.workspace??lt(e).workspace}safeJoin(e,r){let n=Fa(e,r||"."),i=Ba(e,n);if(i.startsWith("..")||i===".."||i.startsWith(`..${Lh}`))throw new y("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return n}loadAgentCfg(e){return he(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new y("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function c_(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new y("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new y("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function l_(t){return t==="claude-code"?et(".claude","skills"):et(".agents","skills")}var d_=3e4,h_=50*1024*1024,zr=3e4;async function Ua(t){let{agentId:e,workspace:r,framework:n,skill:i}=t;if(!i.skillName)throw new y("IPC_BAD_REQUEST","skill missing skillName");let s=typeof i.content=="string"&&i.content.length>0,o=typeof i.downloadUrl=="string"&&i.downloadUrl.length>0;if(!s&&!o)throw new y("IPC_BAD_REQUEST",`skill ${i.skillId} missing both content and downloadUrl`);let a=c_(i.skillName),c=l_(n),l=et(c,a),d=et(r,l);if(await Na(d,{recursive:!0}),s){let m=Buffer.from(i.content,"utf8");Gn(m.length),await La(et(d,"SKILL.md"),m,"utf8")}else{let m=await u_(i.downloadUrl);g_(m)?await y_(m,d):m_(m)?await w_(m,d):await La(et(d,"SKILL.md"),m.toString("utf8"),"utf8")}let p={skillId:i.skillId,skillName:i.skillName,relPath:l,installedAt:Date.now(),...i.description?{description:i.description}:{},...i.icon?{icon:i.icon}:{},...i.version?{version:i.version}:{},...i.downloadUrl?{downloadUrl:i.downloadUrl}:{},...i.config?{config:i.config}:{},...i.builtin?{builtin:i.builtin}:{}};return re.info("skill installed",{agentId:e,skillId:i.skillId,skillName:i.skillName,relPath:l,source:s?"content":"downloadUrl"}),p}function za(t,e,r){let n=e.get(r.skillId);if(n!==void 0){t[n]=r;return}e.set(r.skillId,t.length),t.push(r)}function f_(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}:{}}}async function u_(t){if(!t)throw new y("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Gn(e);let r=p_(t);return Gn(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await Nh(e);return Gn(r.length),r}if(ws(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),d_);try{let n=await fetch(t,{signal:e.signal});if(!n.ok)throw new y("IPC_BAD_REQUEST",`fetch skill failed HTTP ${n.status} ${t}`);let i=await n.arrayBuffer();return Gn(i.byteLength),Buffer.from(i)}finally{clearTimeout(r)}}throw new y("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Gn(t){if(t>h_)throw new y("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function p_(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new y("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],n=e[3]??"";return r?Buffer.from(n,"base64"):Buffer.from(decodeURIComponent(n),"utf8")}function g_(t){return t.length>=2&&t[0]===31&&t[1]===139}function m_(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function Ma(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function w_(t,e){let r,n;try{r=new Bh.default(t),n=r.getEntries()}catch(o){throw new y("IPC_BAD_REQUEST",`zip parse failed: ${o.message}`,{cause:o})}for(let o of n){let a=o.entryName;if(!a||Ma(a))continue;if(a.startsWith("/")||/^[A-Za-z]:[\\/]/.test(a))throw new y("IPC_BAD_REQUEST",`zip entry absolute path: ${a}`);if(a.split(/[/\\]/).some(l=>l===".."))throw new y("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${a}`);let c=o.header.attr>>>16&61440;if(c!==0&&c!==32768&&c!==16384)throw new y("IPC_BAD_REQUEST",`zip entry kind 0x${c.toString(16)} not allowed (symlink/hardlink/special): ${a}`)}let i=__(n),s=Fa(e);for(let o of n){if(Ma(o.entryName))continue;let a=o.entryName;if(i&&a.startsWith(i)&&(a=a.slice(i.length)),!a)continue;let c=Fa(e,a),l=Ba(s,c);if(l.startsWith("..")||l==="..")throw new y("IPC_BAD_REQUEST",`zip entry escapes destDir: ${a}`);if(o.isDirectory){await Na(c,{recursive:!0});continue}await Na(n_(c),{recursive:!0});let d;try{d=o.getData()}catch(p){throw new y("IPC_BAD_REQUEST",`zip entry getData failed (${o.entryName}): ${p.message}`,{cause:p})}await La(c,d)}}function __(t){let e;for(let r of t){let n=r.entryName;if(!n||Ma(n))continue;let i=n.indexOf("/");if(i<=0)return;let s=n.slice(0,i+1);if(e===void 0)e=s;else if(e!==s)return}return e}async function y_(t,e){await E_(t);let r=gh({cwd:e,strip:1}),n=!1,i=setTimeout(()=>{n=!0,r.destroy(new y("IPC_BAD_REQUEST",`tar extract timeout (${zr}ms)`))},zr);try{await Mh(Fh.from(t),r)}catch(s){throw s instanceof y?s:n?new y("IPC_BAD_REQUEST",`tar extract timeout (${zr}ms)`):new y("IPC_BAD_REQUEST",`tar extract failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}}async function E_(t){let e=[],r=Mr({onReadEntry:s=>{let o=s.path,a=s.type;if(a!=="File"&&a!=="Directory"){e.push(`tar entry kind '${a}' not allowed (symlink/hardlink/special): ${o.slice(0,100)}`);return}if(o.startsWith("/")||o.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(o)){e.push(`tar entry absolute path: ${o}`);return}o.split(/[/\\]/).some(l=>l==="..")&&e.push(`tar entry contains '..': ${o}`)}}),n=!1,i=setTimeout(()=>{n=!0,r.destroy(new y("IPC_BAD_REQUEST",`tar list timeout (${zr}ms)`))},zr);try{await Mh(Fh.from(t),r)}catch(s){throw n?new y("IPC_BAD_REQUEST",`tar list timeout (${zr}ms)`):new y("IPC_BAD_REQUEST",`tar list failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}if(e.length>0)throw new y("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var S_=5e3;async function I_(t,e,r,n){return Uh(t,e,r,n,{count:0})}async function Uh(t,e,r,n,i){if(n<=0)return[];let s;try{s=await e_(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let a of s){if(a_.has(a.name)||a.isSymbolicLink())continue;if(i.count>=S_){o.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let c=et(e,a.name),l=i_(et(r,a.name)),d=null;try{d=await Da(c)}catch{continue}if(d.isSymbolicLink())continue;i.count++;let p={name:a.name,path:zh(Ba(t,c)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&n>1&&(p.children=await Uh(t,c,l,n-1,i)),o.push(p)}return o.sort((a,c)=>a.isDir!==c.isDir?a.isDir?-1:1:a.name.localeCompare(c.name)),o}function v_(t){return!t||t<=0?s_:Math.min(t,o_)}function T_(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function zh(t){return t.split(Lh).join("/")}F();import{readFileSync as qR}from"node:fs";import{dirname as VR,join as ZR}from"node:path";import{fileURLToPath as XR}from"node:url";var $r="0.1.86";var Mt=O("agent-health-reporter"),R_=1e4,Hn=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??R_}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Mt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Mt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Mt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Mt.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let o of this.opts.core.agents.values()){let a=k_(o);if(!a)continue;let c={agentId:o.agentId,status:a};o.patToken&&(c.patToken=o.patToken),o.accountId&&(c.accountId=o.accountId),r.push(c)}if(r.length===0)return;let n={agents:r,bridgeVersion:$r,_meta:{cozeDeviceId:e}},i;try{i=await this.opts.core.sendRequest("_agent/health",n,5e3)}catch(o){Mt.warn("heartbeat batch send failed",{count:r.length,err:String(o)})}let s=i?.authFailures;if(s&&s.length>0&&(Mt.warn("heartbeat received authFailures from cloud",{count:s.length,agentIds:s.map(o=>o.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(s)}catch(o){Mt.warn("onAuthFailures callback failed (ignored)",{err:String(o)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){Mt.warn("onTickEnd hook failed",{err:String(r)})}}};function k_(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}vt();import{chmod as ry,mkdir as xs,rm as ny,stat as iy,writeFile as sy}from"node:fs/promises";import{homedir as oy}from"node:os";import{join as tf}from"node:path";Wt();import{spawnSync as N_}from"node:child_process";function jn(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Wn(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Gr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Bt(t,e){return{jsonrpc:"2.0",id:t,error:e}}ye();var Is=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)}},L={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};function $h(t){return"method"in t&&"id"in t&&t.id!==void 0}function Gh(t){return"method"in t&&!("id"in t)}function vs(t){return!("method"in t)&&"id"in t}var b_={AGENT_NOT_FOUND:L.AGENT_NOT_FOUND,AGENT_BUSY:L.AGENT_BUSY,AGENT_DISCONNECTED:L.AGENT_DISCONNECTED,AGENT_TIMEOUT:L.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:L.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:L.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:L.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:L.INTERNAL_ERROR,BRIDGE_INTERNAL:L.INTERNAL_ERROR,IPC_AUTH_FAILED:L.INTERNAL_ERROR,IPC_BAD_REQUEST:L.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:L.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:L.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:L.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:L.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:L.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:L.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:L.FILE_TOO_LARGE,UNSUPPORTED_MIME:L.UNSUPPORTED_MIME,UPLOAD_FAILED:L.UPLOAD_FAILED,UPSTREAM_NOT_READY:L.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:L.AGENT_DEPENDENCY_INSTALL_FAILED};function A_(t){if(t!=null)return t instanceof Error?{name:t.name,message:qn(t.message)}:typeof t=="string"?qn(t):typeof t=="object"?x_(t):t}var O_=[[/\/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 qn(t){let e=t;for(let[r,n]of O_)e=e.replace(r,n);return e}function x_(t){let e={};for(let[r,n]of Object.entries(t))typeof n=="string"?e[r]=qn(n):e[r]=n;return e}function Jn(t){if(t instanceof y){let e=A_(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),{code:b_[t.code]??L.INTERNAL_ERROR,message:qn(t.message),data:r}}return{code:L.INTERNAL_ERROR,message:qn(t instanceof Error?t.message:String(t))}}function Hh(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",n=!!e&&typeof e.message=="string"&&!!e.message,i=n?e?.message:t.message,s=t.data;if(n&&e){let{message:o,...a}=e;s=a}return new y(r,i,{retriable:e?.retriable??!1,cause:s})}function Wh(t){return`${JSON.stringify(t)}
84
- `}var jh=10*1024*1024,Ts=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>jh){let i=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${i} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${jh} bytes`)}),[]}let r=this.buffer.split(`
85
- `);this.buffer=r.pop()??"";let n=[];for(let i of r){let s=i.replace(/\r$/,"").trim();if(s)try{n.push(JSON.parse(s))}catch(o){this.onError?.({line:s,error:o})}}return n}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var Jh={"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",initialize:"initialize"},ck=Object.fromEntries(Object.entries(Jh).map(([t,e])=>[e,t])),P_={"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"],"agent.pair":[],initialize:[]},Hr=class{seq=0;next(e,r){this.seq+=1;let n=Jh[e]??C_(e),i=P_[n]??[],s=[n,String(this.seq)];if(i.length>0){let o=i.map(c=>qh(r?.[c]??"")),a=D_(o).join(":");a&&s.push(a)}else r&&Object.values(r).some(o=>o)&&s.push(Object.values(r).filter(Boolean).map(o=>qh(String(o))).join(":"));return s.join("_")}reset(){this.seq=0}};function C_(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function qh(t){return t.replace(/[:_\s]+/g,"-")}function D_(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}mr();function jr(t,e){let r=process.env[t];if(!r)return e;let n=Number(r);return Number.isFinite(n)&&n>0?n:e}ye();F();var L_=jr("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),F_=200,M_=jr("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),B_=jr("COZE_BRIDGE_SESSION_PROMPT_FRAME_IDLE_MS",600*1e3),Vh=500;function U_(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Vh?t:`${e.slice(0,Vh)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Zh(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),N_("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var rt=class{constructor(e){this.opts=e;this.log=O(`downstream.${this.constructor.name}`),this.decoder=new Ts({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Hr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new y("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=It(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=r,r.stdout?.setEncoding("utf8"),r.stdout?.on("data",n=>{try{for(let i of this.decoder.push(n))this.dispatch(i)}catch(i){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(i)})}}),r.stderr?.setEncoding("utf8"),r.stderr?.on("data",n=>{let i=n.trimEnd();this.stderrRing.push(i),this.stderrRing.length>F_&&this.stderrRing.shift(),this.log.debug("stderr",{text:i})}),r.stdin?.on("error",n=>{this.log.warn("child stdin error",{err:String(n)})}),r.stdout?.on("error",n=>{this.log.warn("child stdout error",{err:String(n)})}),r.stderr?.on("error",n=>{this.log.warn("child stderr error",{err:String(n)})}),r.on("exit",(n,i)=>{this.stopped=!0,(n!==0||i!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:n,signal:i,recentStderr:[...this.stderrRing]});try{for(let o of this.decoder.flush())this.dispatch(o)}catch(o){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(o)})}this.failAllPending(new y("AGENT_PROTOCOL_ERROR",`agent exited (${n}/${i})`));for(let o of this.exitHandlers)o(n,i)}),r.on("error",n=>{this.log.error("child error",{err:String(n)}),this.failAllPending(new y("AGENT_SPAWN_FAILED",String(n),{cause:n}))}),this.log.info("downstream started",{command:this.opts.command,pid:r.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let r=this.child,n=new Promise(s=>r.once("exit",()=>s()));Zh(r.pid,"SIGTERM");let i=setTimeout(()=>{r.killed||Zh(r.pid,"SIGKILL")},5e3);try{await n}finally{clearTimeout(i)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(){return[...this.stderrRing]}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r=M_,n=B_){return this.call("session/prompt",e,r,n)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Wn("session/cancel",e))}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Gr(e,r))}catch(n){this.log.warn("respondAgentRequest write failed",{id:e,err:String(n)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Bt(e,r))}catch(n){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(n)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,n=L_,i=0){if(!this.child||this.stopped)return Promise.reject(new y("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),o=jn(s,e,r),a=(()=>{if(typeof r!="object"||r===null)return;let d=r.sessionId;return typeof d=="string"?d:void 0})(),c=n>0&&Number.isFinite(n),l=i>0&&Number.isFinite(i);return new Promise((d,p)=>{let m={resolve:d,reject:p,timer:null,frameIdleTimer:null,armFrameIdle:null,method:e};c&&(m.timer=setTimeout(()=>{this.pending.delete(s),m.frameIdleTimer&&clearTimeout(m.frameIdleTimer),this.log.warn("downstream call timeout",{id:s,method:e,timeoutMs:n,...a?{sessionId:a}:{}}),p(new y("AGENT_TIMEOUT",`${e} timed out after ${n}ms`))},n));let f=l?()=>{m.frameIdleTimer&&clearTimeout(m.frameIdleTimer),m.frameIdleTimer=setTimeout(()=>{if(this.inflightAgentRequests.size>0){this.log.debug("frame-idle fired but agent request inflight, re-arming",{id:s,method:e,inflight:this.inflightAgentRequests.size,...a?{sessionId:a}:{}}),f?.();return}m.timer&&clearTimeout(m.timer),this.pending.delete(s),this.log.warn("frame-idle timeout, rejecting pending call",{id:s,method:e,frameIdleMs:i,...a?{sessionId:a}:{}}),p(new y("AGENT_FRAME_IDLE_TIMEOUT",`${e} no session/update for ${i}ms (no inflight agent request)`))},i)}:null;m.armFrameIdle=f,this.pending.set(s,m),f?.();try{this.writeFrame(o)}catch(u){m.timer&&clearTimeout(m.timer),m.frameIdleTimer&&clearTimeout(m.frameIdleTimer),this.pending.delete(s),p(u)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new y("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(Wh(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(vs(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),r.frameIdleTimer&&clearTimeout(r.frameIdleTimer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(Hh(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new y("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:U_(e.result)}),r.resolve(e.result));return}if(Gh(e)){if(e.method==="session/update"){for(let r of this.pending.values())r.armFrameIdle?.();for(let r of this.updateHandlers)try{Promise.resolve(r(e.params)).catch(n=>this.log.warn("update handler failed (async)",{err:String(n)}))}catch(n){this.log.warn("update handler threw sync, swallowed",{err:String(n)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if($h(e)){let r=e;try{this.handleAgentRequest(r).catch(n=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(n)}))}catch(n){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(n)})}}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Bt(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(n){this.log.error("agentRequestHandler threw",{method:e.method,err:String(n)});try{this.writeFrame(Bt(e.id,Jn(n)))}catch{}this.inflightAgentRequests.delete(e.id)}}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.frameIdleTimer&&clearTimeout(r.frameIdleTimer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function z_(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=n));return e}var Rs=class extends rt{framework="claude-code";constructor(e){let r=dn("claude-code",e.command),n=e.args??[],i={command:r,args:n,cwd:e.cwd,...e.env?{env:e.env}:{}};super(i)}sanitizeEnv(e){return z_(e)}};Wt();import{mkdtempSync as $_,rmSync as G_}from"node:fs";import{tmpdir as H_}from"node:os";import{join as j_}from"node:path";var ks=class extends rt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=dn("codex",e.command),n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,s=e.isolateCodexHome?$_(j_(H_(),"coze-bridge-codex-home-")):void 0,o=s?{...e.env??{},CODEX_HOME:s}:e.env,a={command:r,args:i,cwd:e.cwd,...o?{env:o}:{}};super(a),this.authMethodId=e.authMethodId,this.codexHomeDir=s}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async stop(e){if(await super.stop(e),this.codexHomeDir)try{G_(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var W_=3e4,Wr=class extends rt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",n=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&n.push("--token",e.gatewayToken);let i={command:e.command,args:n,cwd:e.cwd,...e.env?{env:e.env}:{}};super(i),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},W_))}get acpSessionName(){return this.sessionName}};ye();F();de();function $a(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}Wt();var qr=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((r,n)=>{this.slots.push({task:e,resolve:r,reject:n}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var bs=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new qr,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let n of this.sessionQueues.values())n.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,n]of this.sessions)Vn(n),n.downstream&&(r.push(n.downstream.stop(e).catch(()=>{})),n.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Vn(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}mr();F();import{constants as Kh,access as q_}from"node:fs/promises";import{delimiter as J_,join as V_}from"node:path";var Ut=O("framework-detector"),Xh={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Z_=[".exe",".cmd",".bat",".ps1"],zt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??It,access:e.access??q_}}async detect(e){let r=Xh[e],n=await this.which(r);if(!n)return Ut.debug("framework binary not found",{framework:e,bin:r}),null;let i=e==="openclaw"?["--log-level","silent"]:[],[s,o]=await Promise.all([this.probeVersion(n,i),e==="openclaw"?this.probeOpenclawDefaultAgent(n):Promise.resolve(null)]),a={path:n,version:s};return o&&(a.defaultAgent=o),a}async detectAll(){let e=await Promise.all(Object.keys(Xh).map(async n=>[n,await this.detect(n)])),r={};for(let[n,i]of e)i&&(r[n]=i);return r}async which(e){let r=this.env.pathEnv.split(J_).filter(Boolean),n=this.env.platform==="win32"?["",...Z_]:[""];for(let i of r)for(let s of n){let o=V_(i,e+s);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?Kh.F_OK:Kh.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return Ut.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return Ut.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let n=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!n)return Ut.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let i=JSON.parse(n[0]);if(!Array.isArray(i))return Ut.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let s=i.find(o=>o?.isDefault===!0);return s?!s.id||!s.workspace?(Ut.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!s.id,hasWorkspace:!!s.workspace}),null):{id:s.id,workspace:s.workspace}:(Ut.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:i.length}),null)}catch(i){return Ut.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(i),matchHead:n[0].slice(0,200)}),null}}async probeVersion(e,r=[]){let n=await this.runProbe(e,[...r,"--version"]);return n&&(X_(n.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(n=>{let i="",s=!1,o,a=c=>{s||(s=!0,o&&clearTimeout(o),n(c))};try{let c=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});o=setTimeout(()=>{c.kill("SIGKILL"),a(null)},15e3),c.stdout?.on("data",l=>{i+=l.toString("utf8")}),c.on("error",()=>a(null)),c.on("close",l=>a({code:l,stdout:i}))}catch{a(null)}})}},K_=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function X_(t){return t.replace(K_,"")}import{spawn as Q_}from"node:child_process";import{homedir as Y_}from"node:os";import{join as ey}from"node:path";ye();Ti();F();async function ef(){let t=ey(Y_(),".openclaw/openclaw.json");return(await Er(t))?.gateway?.auth?.token??""}var Qh=O("openclaw.config"),ty=[0,5e3,5e3],Yh="models.providers.",As="agents.defaults.models",Os=class{command;env;retryDelaysMs;queue=new qr;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??ty}async withRetry(e,r){let n;for(let i=0;i<this.retryDelaysMs.length;i++){let s=this.retryDelaysMs[i]??0;s>0&&await new Promise(o=>setTimeout(o,s));try{return await r()}catch(o){n=o,Qh.warn("openclaw cli failed, will retry",{label:e,attempt:i+1,err:String(o)})}}throw new y("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${n?.message??"unknown"}`)}runCli(e){return new Promise((r,n)=>{let i=Q_(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`exit ${o}: ${s.trim().slice(0,500)}`))})})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(n){let i=String(n);if(r.some(s=>i.includes(s)))return;throw n}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(n){Qh.warn(`${e} failed (best-effort)`,{configPath:r,err:String(n)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${Yh}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Yh}${e}`)}addModelToAllowlist(e,r){let n={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${As}[${e}]`,()=>this.runCli(["config","set",As,JSON.stringify(n),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${As}[${e}]`,`${As}.${e}`)}ensureAgent(e,r,n){let i=["agents","add",e,"--workspace",r,"--non-interactive"];return n&&i.push("--model",n),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(i,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var V=O("agent-manager"),ay=(t,e,r,n,i,s,o,a,c)=>{switch(t){case"claude-code":{let l={...i?{...bh(i),...xh(i,o,a)}:{},...c??{},IS_SANDBOX:"1"};return new Rs({cwd:r,env:l})}case"codex":{let d=[...i?[...Ah(i),...Ch(i,o,a)]:[],"-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"'],p={...i?Oh(i):{},...c??{}},m=!!i;return new ks({cwd:r,...d.length>0?{extraArgs:d}:{},...Object.keys(p).length>0?{env:p}:{},...m?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Wr({command:e,cwd:r,agentId:n,...s?{sessionName:$a(s)}:{}})}};function Ga(t){return t==="claude-code"||t==="codex"}function cy(t){let e=[],r=Object.keys(t).sort();for(let n of r){let i=t[n];i!==void 0&&(ly(i)||e.push(`${n}=${i}`))}return e.length===0?"":`${e.join(`
80
+ `},configPath(t){return jI(t.homeDir,".coze","bridge","task.xml")},async install(t){let r=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await Dp("schtasks",["/Create","/SC","ONLOGON","/TN",fo,"/TR",r,"/RU",t.userName,"/F"]),Yc.info("task scheduler entry created",{task:fo,logFile:t.logFile})},async uninstall(t){await Dp("schtasks",["/Delete","/TN",fo,"/F"]).catch(e=>Yc.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Yc.info("task scheduler entry removed",{task:fo})}}});var Lp={};gi(Lp,{buildContext:()=>VI,getSupervisor:()=>JI,launchdSupervisor:()=>Xc,systemdSupervisor:()=>Qc,taskSchedulerSupervisor:()=>el});import{homedir as WI,userInfo as qI}from"node:os";function JI(t=process.platform){switch(t){case"darwin":return Xc;case"linux":return Qc;case"win32":return el;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function VI(){let t=M();return{nodeBin:process.execPath,entry:jc(t),logFile:t.logFile,homeDir:WI(),userName:qI().username}}var Fp=Ie(()=>{"use strict";de();qc();Pp();Cp();Np()});F();qt();var ul=x("acp-installer-warmup"),mg=["claude-code","codex"];async function pl(t={}){let e=t.ensure??_r,n=(await Promise.allSettled(mg.map(async i=>{let s=await e(i);ul.info("acp wrapper warmup ok",{framework:i,path:s})}))).filter(i=>i.status==="rejected");n.length>0&&ul.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:n.length,reasons:n.map(i=>i.reason instanceof Error?i.reason.message:String(i.reason))})}vt();F();import{readdir as bg}from"node:fs/promises";import{mkdir as El,writeFile as Sl}from"node:fs/promises";import{join as Eo}from"node:path";var kg={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Sr(t,e,r){await El(t,{recursive:!0});let n=kg[e],i=Eo(t,n);return await Sl(i,r??"","utf8"),i}async function Il(t){let e=Eo(t,".claude");await El(e,{recursive:!0});let r=Eo(e,"settings.local.json"),n=JSON.stringify({permissions:{defaultMode:"bypassPermissions"}},null,2);return await Sl(r,n,"utf8"),r}var Re=x("agent-detail-sync"),Ag=6e4,xg=5*6e4,Ai=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,n;try{n=await bg(r)}catch(i){Re.info("agents dir not found, skip detail sync",{root:r,err:String(i)});return}Re.info("starting detail sync",{reason:e,count:n.length}),await Promise.allSettled(n.map(async i=>{let s=await he(i,this.opts.paths).catch(()=>null);if(s){if(s.disconnectedAt){Re.debug("detail sync: skip disconnected agent",{agentId:i});return}try{await this.syncOne(i,s)}catch(o){Re.warn("detail sync failed for agent, skipping",{agentId:i,err:String(o)})}}})),Re.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),r=[];for(let[n,i]of this.retryQueue)e>=i.dueAt&&r.push(n);if(r.length!==0){Re.info("retrying pending detail syncs",{count:r.length});for(let n of r)try{await this.syncOne(n)}catch(i){Re.debug("detail sync retry still failing, will try again",{agentId:n,err:String(i)})}}}async syncOne(e,r){let n=r??await he(e,this.opts.paths);if(!n){Re.info("detail sync: agent config missing, skip",{agentId:e});return}let i;try{i=await this.opts.sendDetail({_meta:{cozeAgentId:e}}),this.retryQueue.delete(e)}catch(a){Re.warn("detail RPC failed, using local data",{agentId:e,err:String(a)});let c=this.retryQueue.get(e),l=c?Math.min(c.currentDelay*2,xg):Ag;this.retryQueue.set(e,{dueAt:Date.now()+l,currentDelay:l});return}if(i.agentId&&i.agentId!==e){Re.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:i.agentId});return}let s=!1,o=!1;if(i.agentName&&i.agentName!==n.agentName&&(n.agentName=i.agentName,s=!0),i.description!==void 0&&i.description!==n.description&&(n.description=i.description,s=!0),i.cozeIdentity&&i.cozeIdentity!==n.cozeIdentity&&(n.cozeIdentity=i.cozeIdentity,s=!0,o=!0),i.deployType&&Re.info("detail.deployType",{agentId:e,deployType:i.deployType}),!s){Re.debug("detail sync: no diff",{agentId:e});return}await ve(n,this.opts.paths),Re.info("detail sync: config updated",{agentId:e,identityChanged:o,agentName:n.agentName}),o&&(await Sr(n.workspace,n.framework,n.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Uh=lt(td(),1);import{lstat as Da,mkdir as Na,readFile as Lh,readdir as ty,rm as ry,stat as ny,writeFile as La}from"node:fs/promises";import{dirname as iy,join as rt,normalize as sy,relative as Ba,resolve as Fa,sep as Fh}from"node:path";import{Readable as Mh}from"node:stream";import{pipeline as Bh}from"node:stream/promises";import Xg from"events";import Te from"fs";import{EventEmitter as _a}from"node:events";import Fd from"node:stream";import{StringDecoder as Qg}from"node:string_decoder";import Ud from"node:path";import Dr from"node:fs";import{dirname as hm,parse as fm}from"path";import{EventEmitter as Em}from"events";import ea from"assert";import{Buffer as nr}from"buffer";import*as od from"zlib";import Sm from"zlib";import{posix as kr}from"node:path";import{basename as Vm}from"node:path";import os from"fs";import Xe from"fs";import ud from"path";import{win32 as sw}from"node:path";import Ed from"path";import eh from"node:fs";import Iw from"node:assert";import{randomBytes as th}from"node:crypto";import N from"node:fs";import te from"node:path";import rh from"fs";import gs from"node:fs";import Pn from"node:path";import Ae from"node:fs";import xw from"node:fs/promises";import ls from"node:path";import{join as uh}from"node:path";import be from"node:fs";import mh from"node:path";var Zg=Object.defineProperty,Kg=(t,e)=>{for(var r in e)Zg(t,r,{get:e[r],enumerable:!0})},rd=typeof process=="object"&&process?process:{stdout:null,stderr:null},Yg=t=>!!t&&typeof t=="object"&&(t instanceof or||t instanceof Fd||em(t)||tm(t)),em=t=>!!t&&typeof t=="object"&&t instanceof _a&&typeof t.pipe=="function"&&t.pipe!==Fd.Writable.prototype.pipe,tm=t=>!!t&&typeof t=="object"&&t instanceof _a&&typeof t.write=="function"&&typeof t.end=="function",ht=Symbol("EOF"),ft=Symbol("maybeEmitEnd"),Rt=Symbol("emittedEnd"),Di=Symbol("emittingEnd"),pn=Symbol("emittedError"),Ni=Symbol("closed"),nd=Symbol("read"),Li=Symbol("flush"),id=Symbol("flushChunk"),Be=Symbol("encoding"),Rr=Symbol("decoder"),ie=Symbol("flowing"),gn=Symbol("paused"),Or=Symbol("resume"),se=Symbol("buffer"),Ee=Symbol("pipes"),oe=Symbol("bufferLength"),ko=Symbol("bufferPush"),Fi=Symbol("bufferShift"),we=Symbol("objectMode"),Q=Symbol("destroyed"),bo=Symbol("error"),Ao=Symbol("emitData"),sd=Symbol("emitEnd"),xo=Symbol("emitEnd2"),Ve=Symbol("async"),Oo=Symbol("abort"),Mi=Symbol("aborted"),mn=Symbol("signal"),Vt=Symbol("dataListeners"),ke=Symbol("discarded"),wn=t=>Promise.resolve().then(t),rm=t=>t(),nm=t=>t==="end"||t==="finish"||t==="prefinish",im=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,sm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Md=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,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()}},om=class extends Md{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,r){super(t,e,r),this.proxyErrors=n=>this.dest.emit("error",n),t.on("error",this.proxyErrors)}},am=t=>!!t.objectMode,cm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",or=class extends _a{[ie]=!1;[gn]=!1;[Ee]=[];[se]=[];[we];[Be];[Ve];[Rr];[ht]=!1;[Rt]=!1;[Di]=!1;[Ni]=!1;[pn]=null;[oe]=0;[Q]=!1;[mn];[Mi]=!1;[Vt]=0;[ke]=!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");am(e)?(this[we]=!0,this[Be]=null):cm(e)?(this[Be]=e.encoding,this[we]=!1):(this[we]=!1,this[Be]=null),this[Ve]=!!e.async,this[Rr]=this[Be]?new Qg(this[Be]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[se]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Ee]});let{signal:r}=e;r&&(this[mn]=r,r.aborted?this[Oo]():r.addEventListener("abort",()=>this[Oo]()))}get bufferLength(){return this[oe]}get encoding(){return this[Be]}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[we]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ve]}set async(t){this[Ve]=this[Ve]||!!t}[Oo](){this[Mi]=!0,this.emit("abort",this[mn]?.reason),this.destroy(this[mn]?.reason)}get aborted(){return this[Mi]}set aborted(t){}write(t,e,r){if(this[Mi])return!1;if(this[ht])throw new Error("write after end");if(this[Q])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(r=e,e="utf8"),e||(e="utf8");let n=this[Ve]?wn:rm;if(!this[we]&&!Buffer.isBuffer(t)){if(sm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(im(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[we]?(this[ie]&&this[oe]!==0&&this[Li](!0),this[ie]?this.emit("data",t):this[ko](t),this[oe]!==0&&this.emit("readable"),r&&n(r),this[ie]):t.length?(typeof t=="string"&&!(e===this[Be]&&!this[Rr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Be]&&(t=this[Rr].write(t)),this[ie]&&this[oe]!==0&&this[Li](!0),this[ie]?this.emit("data",t):this[ko](t),this[oe]!==0&&this.emit("readable"),r&&n(r),this[ie]):(this[oe]!==0&&this.emit("readable"),r&&n(r),this[ie])}read(t){if(this[Q])return null;if(this[ke]=!1,this[oe]===0||t===0||t&&t>this[oe])return this[ft](),null;this[we]&&(t=null),this[se].length>1&&!this[we]&&(this[se]=[this[Be]?this[se].join(""):Buffer.concat(this[se],this[oe])]);let e=this[nd](t||null,this[se][0]);return this[ft](),e}[nd](t,e){if(this[we])this[Fi]();else{let r=e;t===r.length||t===null?this[Fi]():typeof r=="string"?(this[se][0]=r.slice(t),e=r.slice(0,t),this[oe]-=t):(this[se][0]=r.subarray(t),e=r.subarray(0,t),this[oe]-=t)}return this.emit("data",e),!this[se].length&&!this[ht]&&this.emit("drain"),e}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e="utf8"),t!==void 0&&this.write(t,e),r&&this.once("end",r),this[ht]=!0,this.writable=!1,(this[ie]||!this[gn])&&this[ft](),this}[Or](){this[Q]||(!this[Vt]&&!this[Ee].length&&(this[ke]=!0),this[gn]=!1,this[ie]=!0,this.emit("resume"),this[se].length?this[Li]():this[ht]?this[ft]():this.emit("drain"))}resume(){return this[Or]()}pause(){this[ie]=!1,this[gn]=!0,this[ke]=!1}get destroyed(){return this[Q]}get flowing(){return this[ie]}get paused(){return this[gn]}[ko](t){this[we]?this[oe]+=1:this[oe]+=t.length,this[se].push(t)}[Fi](){return this[we]?this[oe]-=1:this[oe]-=this[se][0].length,this[se].shift()}[Li](t=!1){do;while(this[id](this[Fi]())&&this[se].length);!t&&!this[se].length&&!this[ht]&&this.emit("drain")}[id](t){return this.emit("data",t),this[ie]}pipe(t,e){if(this[Q])return t;this[ke]=!1;let r=this[Rt];return e=e||{},t===rd.stdout||t===rd.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Ee].push(e.proxyErrors?new om(this,t,e):new Md(this,t,e)),this[Ve]?wn(()=>this[Or]()):this[Or]()),t}unpipe(t){let e=this[Ee].find(r=>r.dest===t);e&&(this[Ee].length===1?(this[ie]&&this[Vt]===0&&(this[ie]=!1),this[Ee]=[]):this[Ee].splice(this[Ee].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let r=super.on(t,e);if(t==="data")this[ke]=!1,this[Vt]++,!this[Ee].length&&!this[ie]&&this[Or]();else if(t==="readable"&&this[oe]!==0)super.emit("readable");else if(nm(t)&&this[Rt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[pn]){let n=e;this[Ve]?wn(()=>n.call(this,this[pn])):n.call(this,this[pn])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Vt]=this.listeners("data").length,this[Vt]===0&&!this[ke]&&!this[Ee].length&&(this[ie]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Vt]=0,!this[ke]&&!this[Ee].length&&(this[ie]=!1)),e}get emittedEnd(){return this[Rt]}[ft](){!this[Di]&&!this[Rt]&&!this[Q]&&this[se].length===0&&this[ht]&&(this[Di]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[Ni]&&this.emit("close"),this[Di]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Q&&this[Q])return!1;if(t==="data")return!this[we]&&!r?!1:this[Ve]?(wn(()=>this[Ao](r)),!0):this[Ao](r);if(t==="end")return this[sd]();if(t==="close"){if(this[Ni]=!0,!this[Rt]&&!this[Q])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[pn]=r,super.emit(bo,r);let i=!this[mn]||this.listeners("error").length?super.emit("error",r):!1;return this[ft](),i}else if(t==="resume"){let i=super.emit("resume");return this[ft](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let n=super.emit(t,...e);return this[ft](),n}[Ao](t){for(let r of this[Ee])r.dest.write(t)===!1&&this.pause();let e=this[ke]?!1:super.emit("data",t);return this[ft](),e}[sd](){return this[Rt]?!1:(this[Rt]=!0,this.readable=!1,this[Ve]?(wn(()=>this[xo]()),!0):this[xo]())}[xo](){if(this[Rr]){let e=this[Rr].end();if(e){for(let r of this[Ee])r.dest.write(e);this[ke]||super.emit("data",e)}}for(let e of this[Ee])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[we]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[we]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[we])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Be]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Q,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[ke]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[ht])return e();let n,i,s=l=>{this.off("data",o),this.off("end",a),this.off(Q,c),e(),i(l)},o=l=>{this.off("error",s),this.off("end",a),this.off(Q,c),this.pause(),n({value:l,done:!!this[ht]})},a=()=>{this.off("error",s),this.off("data",o),this.off(Q,c),e(),n({done:!0,value:void 0})},c=()=>s(new Error("stream destroyed"));return new Promise((l,d)=>{i=d,n=l,this.once(Q,c),this.once("error",s),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[ke]=!1;let t=!1,e=()=>(this.pause(),this.off(bo,e),this.off(Q,e),this.off("end",e),t=!0,{done:!0,value:void 0}),r=()=>{if(t)return e();let n=this.read();return n===null?e():{done:!1,value:n}};return this.once("end",e),this.once(bo,e),this.once(Q,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Q])return t?this.emit("error",t):this.emit(Q),this;this[Q]=!0,this[ke]=!0,this[se].length=0,this[oe]=0;let e=this;return typeof e.close=="function"&&!this[Ni]&&e.close(),t?this.emit("error",t):this.emit(Q),this}static get isStream(){return Yg}},lm=Te.writev,Lt=Symbol("_autoClose"),Ge=Symbol("_close"),yn=Symbol("_ended"),U=Symbol("_fd"),Po=Symbol("_finished"),mt=Symbol("_flags"),Co=Symbol("_flush"),Qo=Symbol("_handleChunk"),Yo=Symbol("_makeBuf"),xn=Symbol("_mode"),Bi=Symbol("_needDrain"),Lr=Symbol("_onerror"),Fr=Symbol("_onopen"),Do=Symbol("_onread"),Pr=Symbol("_onwrite"),Ft=Symbol("_open"),$e=Symbol("_path"),Ot=Symbol("_pos"),Ze=Symbol("_queue"),Cr=Symbol("_read"),No=Symbol("_readSize"),gt=Symbol("_reading"),_n=Symbol("_remain"),Lo=Symbol("_size"),Vi=Symbol("_write"),Zt=Symbol("_writing"),Zi=Symbol("_defaultFlag"),rr=Symbol("_errored"),Ea=class extends or{[rr]=!1;[U];[$e];[No];[gt]=!1;[Lo];[_n];[Lt];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[rr]=!1,this[U]=typeof e.fd=="number"?e.fd:void 0,this[$e]=t,this[No]=e.readSize||16*1024*1024,this[gt]=!1,this[Lo]=typeof e.size=="number"?e.size:1/0,this[_n]=this[Lo],this[Lt]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[U]=="number"?this[Cr]():this[Ft]()}get fd(){return this[U]}get path(){return this[$e]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Ft](){Te.open(this[$e],"r",(t,e)=>this[Fr](t,e))}[Fr](t,e){t?this[Lr](t):(this[U]=e,this.emit("open",e),this[Cr]())}[Yo](){return Buffer.allocUnsafe(Math.min(this[No],this[_n]))}[Cr](){if(!this[gt]){this[gt]=!0;let t=this[Yo]();if(t.length===0)return process.nextTick(()=>this[Do](null,0,t));Te.read(this[U],t,0,t.length,null,(e,r,n)=>this[Do](e,r,n))}}[Do](t,e,r){this[gt]=!1,t?this[Lr](t):this[Qo](e,r)&&this[Cr]()}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Lr](t){this[gt]=!0,this[Ge](),this.emit("error",t)}[Qo](t,e){let r=!1;return this[_n]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[_n]<=0)&&(r=!1,this[Ge](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[U]=="number"&&this[Cr](),!1;case"error":return this[rr]?!1:(this[rr]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},dm=class extends Ea{[Ft](){let t=!0;try{this[Fr](null,Te.openSync(this[$e],"r")),t=!1}finally{t&&this[Ge]()}}[Cr](){let t=!0;try{if(!this[gt]){this[gt]=!0;do{let e=this[Yo](),r=e.length===0?0:Te.readSync(this[U],e,0,e.length,null);if(!this[Qo](r,e))break}while(!0);this[gt]=!1}t=!1}finally{t&&this[Ge]()}}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.closeSync(t),this.emit("close")}}},ds=class extends Xg{readable=!1;writable=!0;[rr]=!1;[Zt]=!1;[yn]=!1;[Ze]=[];[Bi]=!1;[$e];[xn];[Lt];[U];[Zi];[mt];[Po]=!1;[Ot];constructor(t,e){e=e||{},super(e),this[$e]=t,this[U]=typeof e.fd=="number"?e.fd:void 0,this[xn]=e.mode===void 0?438:e.mode,this[Ot]=typeof e.start=="number"?e.start:void 0,this[Lt]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[Ot]!==void 0?"r+":"w";this[Zi]=e.flags===void 0,this[mt]=e.flags===void 0?r:e.flags,this[U]===void 0&&this[Ft]()}emit(t,...e){if(t==="error"){if(this[rr])return!1;this[rr]=!0}return super.emit(t,...e)}get fd(){return this[U]}get path(){return this[$e]}[Lr](t){this[Ge](),this[Zt]=!0,this.emit("error",t)}[Ft](){Te.open(this[$e],this[mt],this[xn],(t,e)=>this[Fr](t,e))}[Fr](t,e){this[Zi]&&this[mt]==="r+"&&t&&t.code==="ENOENT"?(this[mt]="w",this[Ft]()):t?this[Lr](t):(this[U]=e,this.emit("open",e),this[Zt]||this[Co]())}end(t,e){return t&&this.write(t,e),this[yn]=!0,!this[Zt]&&!this[Ze].length&&typeof this[U]=="number"&&this[Pr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[yn]?(this.emit("error",new Error("write() after end()")),!1):this[U]===void 0||this[Zt]||this[Ze].length?(this[Ze].push(t),this[Bi]=!0,!1):(this[Zt]=!0,this[Vi](t),!0)}[Vi](t){Te.write(this[U],t,0,t.length,this[Ot],(e,r)=>this[Pr](e,r))}[Pr](t,e){t?this[Lr](t):(this[Ot]!==void 0&&typeof e=="number"&&(this[Ot]+=e),this[Ze].length?this[Co]():(this[Zt]=!1,this[yn]&&!this[Po]?(this[Po]=!0,this[Ge](),this.emit("finish")):this[Bi]&&(this[Bi]=!1,this.emit("drain"))))}[Co](){if(this[Ze].length===0)this[yn]&&this[Pr](null,0);else if(this[Ze].length===1)this[Vi](this[Ze].pop());else{let t=this[Ze];this[Ze]=[],lm(this[U],t,this[Ot],(e,r)=>this[Pr](e,r))}}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Bd=class extends ds{[Ft](){let t;if(this[Zi]&&this[mt]==="r+")try{t=Te.openSync(this[$e],this[mt],this[xn])}catch(e){if(e?.code==="ENOENT")return this[mt]="w",this[Ft]();throw e}else t=Te.openSync(this[$e],this[mt],this[xn]);this[Fr](null,t)}[Ge](){if(this[Lt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Te.closeSync(t),this.emit("close")}}[Vi](t){let e=!0;try{this[Pr](null,Te.writeSync(this[U],t,0,t.length,this[Ot])),e=!1}finally{if(e)try{this[Ge]()}catch{}}}},um=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"]]),pm=t=>!!t.sync&&!!t.file,gm=t=>!t.sync&&!!t.file,mm=t=>!!t.sync&&!t.file,wm=t=>!t.sync&&!t.file,ym=t=>!!t.file,_m=t=>um.get(t)||t,Sa=(t={})=>{if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){let i=_m(r);e[i]=n}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Bn=(t,e,r,n,i)=>Object.assign((s=[],o,a)=>{Array.isArray(s)&&(o=s,s={}),typeof o=="function"&&(a=o,o=void 0),o=o?Array.from(o):[];let c=Sa(s);if(i?.(c,o),pm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return t(c,o)}else if(gm(c)){let l=e(c,o);return a?l.then(()=>a(),a):l}else if(mm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,o)}else if(wm(c)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return n(c,o)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:r,asyncNoFile:n,validate:i}),Im=Sm.constants||{ZLIB_VERNUM:4736},Ye=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},Im)),vm=nr.concat,ad=Object.getOwnPropertyDescriptor(nr,"concat"),Tm=t=>t,Fo=ad?.writable===!0||ad?.set!==void 0?t=>{nr.concat=t?Tm:vm}:t=>{},ir=Symbol("_superWrite"),Ui=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"}},Mo=Symbol("flushFlag"),Ia=class extends or{#e=!1;#r=!1;#n;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#n}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#n=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof od[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new od[e](t)}catch(r){throw new Ui(r,this.constructor)}this.#o=r=>{this.#e||(this.#e=!0,this.close(),this.emit("error",r))},this.#t?.on("error",r=>this.#o(new Ui(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return ea(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(nr.alloc(0),{[Mo]:t})))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#r=!0,super.end(r)}get ended(){return this.#r}[ir](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=nr.from(t,e)),this.#e)return;ea(this.#t,"zlib binding closed");let n=this.#t._handle,i=n.close;n.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},Fo(!0);let o;try{let c=typeof t[Mo]=="number"?t[Mo]:this.#n;o=this.#t._processChunk(t,c),Fo(!1)}catch(c){Fo(!1),this.#o(new Ui(c,this.write))}finally{this.#t&&(this.#t._handle=n,n.close=i,this.#t.close=s,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",c=>this.#o(new Ui(c,this.write)));let a;if(o)if(Array.isArray(o)&&o.length>0){let c=o[0];a=this[ir](nr.from(c));for(let l=1;l<o.length;l++)a=this[ir](o[l])}else a=this[ir](nr.from(o));return r&&r(),a}},zd=class extends Ia{#e;#r;constructor(t,e){t=t||{},t.flush=t.flush||Ye.Z_NO_FLUSH,t.finishFlush=t.finishFlush||Ye.Z_FINISH,t.fullFlushFlag=Ye.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#r=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.#r!==e){this.flush(Ye.Z_SYNC_FLUSH),ea(this.handle,"zlib binding closed");let r=this.handle.flush;this.handle.flush=(n,i)=>{typeof n=="function"&&(i=n,n=this.flushFlag),this.flush(n),i?.()};try{this.handle.params(t,e)}finally{this.handle.flush=r}this.handle&&(this.#e=t,this.#r=e)}}}},Rm=class extends zd{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[ir](t){return this.#e?(this.#e=!1,t[9]=255,super[ir](t)):super[ir](t)}},km=class extends zd{constructor(t){super(t,"Unzip")}},$d=class extends Ia{constructor(t,e){t=t||{},t.flush=t.flush||Ye.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||Ye.BROTLI_OPERATION_FINISH,t.fullFlushFlag=Ye.BROTLI_OPERATION_FLUSH,super(t,e)}},bm=class extends $d{constructor(t){super(t,"BrotliCompress")}},Am=class extends $d{constructor(t){super(t,"BrotliDecompress")}},Gd=class extends Ia{constructor(t,e){t=t||{},t.flush=t.flush||Ye.ZSTD_e_continue,t.finishFlush=t.finishFlush||Ye.ZSTD_e_end,t.fullFlushFlag=Ye.ZSTD_e_flush,super(t,e)}},xm=class extends Gd{constructor(t){super(t,"ZstdCompress")}},Om=class extends Gd{constructor(t){super(t,"ZstdDecompress")}},Pm=(t,e)=>{if(Number.isSafeInteger(t))t<0?Dm(t,e):Cm(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},Cm=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Dm=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var n=e.length;n>1;n--){var i=t&255;t=Math.floor(t/256),r?e[n-1]=Hd(i):i===0?e[n-1]=0:(r=!0,e[n-1]=jd(i))}},Nm=t=>{let e=t[0],r=e===128?Fm(t.subarray(1,t.length)):e===255?Lm(t):null;if(r===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(r))throw Error("parsed number outside of javascript safe integer range");return r},Lm=t=>{for(var e=t.length,r=0,n=!1,i=e-1;i>-1;i--){var s=Number(t[i]),o;n?o=Hd(s):s===0?o=s:(n=!0,o=jd(s)),o!==0&&(r-=o*Math.pow(256,e-i-1))}return r},Fm=t=>{for(var e=t.length,r=0,n=e-1;n>-1;n--){var i=Number(t[n]);i!==0&&(r+=i*Math.pow(256,e-n-1))}return r},Hd=t=>(255^t)&255,jd=t=>(255^t)+1&255,Mm={};Kg(Mm,{code:()=>va,isCode:()=>Ki,isName:()=>Bm,name:()=>hs});var Ki=t=>hs.has(t),Bm=t=>va.has(t),hs=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"]]),va=new Map(Array.from(hs).map(t=>[t[1],t[0]])),sr=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,r,n){Buffer.isBuffer(t)?this.decode(t,e||0,r,n):t&&this.#r(t)}decode(t,e,r,n){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");this.path=r?.path??Kt(t,e,100),this.mode=r?.mode??n?.mode??Pt(t,e+100,8),this.uid=r?.uid??n?.uid??Pt(t,e+108,8),this.gid=r?.gid??n?.gid??Pt(t,e+116,8),this.size=r?.size??n?.size??Pt(t,e+124,12),this.mtime=r?.mtime??n?.mtime??Bo(t,e+136,12),this.cksum=Pt(t,e+148,12),n&&this.#r(n,!0),r&&this.#r(r);let i=Kt(t,e+156,1);if(Ki(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Kt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=r?.uname??n?.uname??Kt(t,e+265,32),this.gname=r?.gname??n?.gname??Kt(t,e+297,32),this.devmaj=r?.devmaj??n?.devmaj??Pt(t,e+329,8)??0,this.devmin=r?.devmin??n?.devmin??Pt(t,e+337,8)??0,t[e+475]!==0){let o=Kt(t,e+345,155);this.path=o+"/"+this.path}else{let o=Kt(t,e+345,130);o&&(this.path=o+"/"+this.path),this.atime=r?.atime??n?.atime??Bo(t,e+476,12),this.ctime=r?.ctime??n?.ctime??Bo(t,e+488,12)}let s=256;for(let o=e;o<e+148;o++)s+=t[o];for(let o=e+156;o<e+512;o++)s+=t[o];this.cksumValid=s===this.cksum,this.cksum===void 0&&s===256&&(this.nullBlock=!0)}#r(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,n])=>!(n==null||r==="path"&&e||r==="linkpath"&&e||r==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let r=this.ctime||this.atime?130:155,n=Um(this.path||"",r),i=n[0],s=n[1];this.needPax=!!n[2],this.needPax=Xt(t,e,100,i)||this.needPax,this.needPax=Ct(t,e+100,8,this.mode)||this.needPax,this.needPax=Ct(t,e+108,8,this.uid)||this.needPax,this.needPax=Ct(t,e+116,8,this.gid)||this.needPax,this.needPax=Ct(t,e+124,12,this.size)||this.needPax,this.needPax=Uo(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Xt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Xt(t,e+265,32,this.uname)||this.needPax,this.needPax=Xt(t,e+297,32,this.gname)||this.needPax,this.needPax=Ct(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Ct(t,e+337,8,this.devmin)||this.needPax,this.needPax=Xt(t,e+345,r,s)||this.needPax,t[e+475]!==0?this.needPax=Xt(t,e+345,155,s)||this.needPax:(this.needPax=Xt(t,e+345,130,s)||this.needPax,this.needPax=Uo(t,e+476,12,this.atime)||this.needPax,this.needPax=Uo(t,e+488,12,this.ctime)||this.needPax);let o=256;for(let a=e;a<e+148;a++)o+=t[a];for(let a=e+156;a<e+512;a++)o+=t[a];return this.cksum=o,Ct(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:hs.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(va.get(t));if(Ki(e)||e==="Unsupported")this.#e=e;else if(Ki(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Um=(t,e)=>{let r=t,n="",i,s=kr.parse(t).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=kr.dirname(r),r=kr.basename(r);do Buffer.byteLength(r)<=100&&Buffer.byteLength(n)<=e?i=[r,n,!1]:Buffer.byteLength(r)>100&&Buffer.byteLength(n)<=e?i=[r.slice(0,99),n,!0]:(r=kr.join(kr.basename(n),r),n=kr.dirname(n));while(n!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},Kt=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Bo=(t,e,r)=>zm(Pt(t,e,r)),zm=t=>t===void 0?void 0:new Date(t*1e3),Pt=(t,e,r)=>Number(t[e])&128?Nm(t.subarray(e,e+r)):Gm(t,e,r),$m=t=>isNaN(t)?void 0:t,Gm=(t,e,r)=>$m(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Hm={12:8589934591,8:2097151},Ct=(t,e,r,n)=>n===void 0?!1:n>Hm[r]||n<0?(Pm(n,t.subarray(e,e+r)),!0):(jm(t,e,r,n),!1),jm=(t,e,r,n)=>t.write(Wm(n,r),e,r,"ascii"),Wm=(t,e)=>qm(Math.floor(t).toString(8),e),qm=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Uo=(t,e,r,n)=>n===void 0?!1:Ct(t,e,r,n.getTime()/1e3),Jm=new Array(156).join("\0"),Xt=(t,e,r,n)=>n===void 0?!1:(t.write(n+Jm,e,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),ss=class Wd{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,r=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=r,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let r=Buffer.byteLength(e),n=512*Math.ceil(1+r/512),i=Buffer.allocUnsafe(n);for(let s=0;s<512;s++)i[s]=0;new sr({path:("PaxHeader/"+Vm(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:r,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(e,512,r,"utf8");for(let s=r+512;s<i.length;s++)i[s]=0;return i}encodeBody(){return this.encodeField("path")+this.encodeField("ctime")+this.encodeField("atime")+this.encodeField("dev")+this.encodeField("ino")+this.encodeField("nlink")+this.encodeField("charset")+this.encodeField("comment")+this.encodeField("gid")+this.encodeField("gname")+this.encodeField("linkpath")+this.encodeField("mtime")+this.encodeField("size")+this.encodeField("uid")+this.encodeField("uname")}encodeField(e){if(this[e]===void 0)return"";let r=this[e],n=r instanceof Date?r.getTime()/1e3:r,i=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+n+`
81
+ `,s=Buffer.byteLength(i),o=Math.floor(Math.log(s)/Math.log(10))+1;return s+o>=Math.pow(10,o)&&(o+=1),o+s+i}static parse(e,r,n=!1){return new Wd(Zm(Km(e),r),n)}},Zm=(t,e)=>e?Object.assign({},e,t):t,Km=t=>t.replace(/\n$/,"").split(`
82
+ `).reduce(Xm,Object.create(null)),Xm=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.slice((r+" ").length);let n=e.split("="),i=n.shift();if(!i)return t;let s=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=n.join("=");return t[s]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(s)?new Date(Number(o)*1e3):/^[0-9]+$/.test(o)?+o:o,t},Qm=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,D=Qm!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),qd=class extends or{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,r){switch(super({}),this.pause(),this.extended=e,this.globalExtended=r,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=D(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?D(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),r&&this.#e(r,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let r=this.remain,n=this.blockRemain;return this.remain=Math.max(0,r-e),this.blockRemain=Math.max(0,n-e),this.ignore?!0:r>=e?super.write(t):super.write(t.subarray(0,r))}#e(t,e=!1){t.path&&(t.path=D(t.path)),t.linkpath&&(t.linkpath=D(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([r,n])=>!(n==null||r==="path"&&e))))}},fs=(t,e,r,n={})=>{t.file&&(n.file=t.file),t.cwd&&(n.cwd=t.cwd),n.code=r instanceof Error&&r.code||e,n.tarCode=e,!t.strict&&n.recoverable!==!1?(r instanceof Error&&(n=Object.assign(r,n),r=r.message),t.emit("warn",e,r,n)):r instanceof Error?t.emit("error",Object.assign(r,n)):t.emit("error",Object.assign(new Error(`${e}: ${r}`),n))},Ym=1024*1024,ta=Buffer.from([31,139]),ra=Buffer.from([40,181,47,253]),ew=Math.max(ta.length,ra.length),Ce=Symbol("state"),Qt=Symbol("writeEntry"),ut=Symbol("readEntry"),zo=Symbol("nextEntry"),cd=Symbol("processEntry"),Ke=Symbol("extendedHeader"),En=Symbol("globalExtendedHeader"),kt=Symbol("meta"),ld=Symbol("emitMeta"),H=Symbol("buffer"),pt=Symbol("queue"),bt=Symbol("ended"),$o=Symbol("emittedEnd"),Yt=Symbol("emit"),Y=Symbol("unzip"),zi=Symbol("consumeChunk"),$i=Symbol("consumeChunkSub"),Go=Symbol("consumeBody"),dd=Symbol("consumeMeta"),hd=Symbol("consumeHeader"),Sn=Symbol("consuming"),Ho=Symbol("bufferConcat"),Gi=Symbol("maybeEnd"),br=Symbol("writing"),At=Symbol("aborted"),Hi=Symbol("onDone"),er=Symbol("sawValidEntry"),ji=Symbol("sawNullBlock"),Wi=Symbol("sawEOF"),fd=Symbol("closeStream"),tw=()=>!0,Mn=class extends Em{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[pt]=[];[H];[ut];[Qt];[Ce]="begin";[kt]="";[Ke];[En];[bt]=!1;[Y];[At]=!1;[er];[ji]=!1;[Wi]=!1;[br]=!1;[Sn]=!1;[$o]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Hi,()=>{(this[Ce]==="begin"||this[er]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Hi,t.ondone):this.on(Hi,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Ym,this.filter=typeof t.filter=="function"?t.filter:tw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let r=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:r?!0:void 0,this.on("end",()=>this[fd]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){fs(this,t,e,r)}[hd](t,e){this[er]===void 0&&(this[er]=!1);let r;try{r=new sr(t,e,this[Ke],this[En])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[ji]?(this[Wi]=!0,this[Ce]==="begin"&&(this[Ce]="header"),this[Yt]("eof")):(this[ji]=!0,this[Yt]("nullBlock"));else if(this[ji]=!1,!r.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:r});else if(!r.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:r});else{let n=r.type;if(/^(Symbolic)?Link$/.test(n)&&!r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:r});else if(!/^(Symbolic)?Link$/.test(n)&&!/^(Global)?ExtendedHeader$/.test(n)&&r.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:r});else{let i=this[Qt]=new qd(r,this[Ke],this[En]);if(!this[er])if(i.remain){let s=()=>{i.invalid||(this[er]=!0)};i.on("end",s)}else this[er]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[Yt]("ignoredEntry",i),this[Ce]="ignore",i.resume()):i.size>0&&(this[kt]="",i.on("data",s=>this[kt]+=s),this[Ce]="meta"):(this[Ke]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[Yt]("ignoredEntry",i),this[Ce]=i.remain?"ignore":"header",i.resume()):(i.remain?this[Ce]="body":(this[Ce]="header",i.end()),this[ut]?this[pt].push(i):(this[pt].push(i),this[zo]())))}}}[fd](){queueMicrotask(()=>this.emit("close"))}[cd](t){let e=!0;if(!t)this[ut]=void 0,e=!1;else if(Array.isArray(t)){let[r,...n]=t;this.emit(r,...n)}else this[ut]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[zo]()),e=!1);return e}[zo](){do;while(this[cd](this[pt].shift()));if(this[pt].length===0){let t=this[ut];!t||t.flowing||t.size===t.remain?this[br]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Go](t,e){let r=this[Qt];if(!r)throw new Error("attempt to consume body without entry??");let n=r.blockRemain??0,i=n>=t.length&&e===0?t:t.subarray(e,e+n);return r.write(i),r.blockRemain||(this[Ce]="header",this[Qt]=void 0,r.end()),i.length}[dd](t,e){let r=this[Qt],n=this[Go](t,e);return!this[Qt]&&r&&this[ld](r),n}[Yt](t,e,r){this[pt].length===0&&!this[ut]?this.emit(t,e,r):this[pt].push([t,e,r])}[ld](t){switch(this[Yt]("meta",this[kt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ke]=ss.parse(this[kt],this[Ke],!1);break;case"GlobalExtendedHeader":this[En]=ss.parse(this[kt],this[En],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ke]??Object.create(null);this[Ke]=e,e.path=this[kt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ke]||Object.create(null);this[Ke]=e,e.linkpath=this[kt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[At]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[At])return r?.(),!1;if((this[Y]===void 0||this.brotli===void 0&&this[Y]===!1)&&t){if(this[H]&&(t=Buffer.concat([this[H],t]),this[H]=void 0),t.length<ew)return this[H]=t,r?.(),!0;for(let o=0;this[Y]===void 0&&o<ta.length;o++)t[o]!==ta[o]&&(this[Y]=!1);let i=!1;if(this[Y]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<ra.length;o++)if(t[o]!==ra[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[Y]===!1&&s)if(t.length<512)if(this[bt])this.brotli=!0;else return this[H]=t,r?.(),!0;else try{new sr(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Y]===void 0||this[Y]===!1&&(this.brotli||i)){let o=this[bt];this[bt]=!1,this[Y]=this[Y]===void 0?new km({}):i?new Om({}):new Am({}),this[Y].on("data",c=>this[zi](c)),this[Y].on("error",c=>this.abort(c)),this[Y].on("end",()=>{this[bt]=!0,this[zi]()}),this[br]=!0;let a=!!this[Y][o?"end":"write"](t);return this[br]=!1,r?.(),a}}this[br]=!0,this[Y]?this[Y].write(t):this[zi](t),this[br]=!1;let n=this[pt].length>0?!1:this[ut]?this[ut].flowing:!0;return!n&&this[pt].length===0&&this[ut]?.once("drain",()=>this.emit("drain")),r?.(),n}[Ho](t){t&&!this[At]&&(this[H]=this[H]?Buffer.concat([this[H],t]):t)}[Gi](){if(this[bt]&&!this[$o]&&!this[At]&&!this[Sn]){this[$o]=!0;let t=this[Qt];if(t&&t.blockRemain){let e=this[H]?this[H].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[H]&&t.write(this[H]),t.end()}this[Yt](Hi)}}[zi](t){if(this[Sn]&&t)this[Ho](t);else if(!t&&!this[H])this[Gi]();else if(t){if(this[Sn]=!0,this[H]){this[Ho](t);let e=this[H];this[H]=void 0,this[$i](e)}else this[$i](t);for(;this[H]&&this[H]?.length>=512&&!this[At]&&!this[Wi];){let e=this[H];this[H]=void 0,this[$i](e)}this[Sn]=!1}(!this[H]||this[bt])&&this[Gi]()}[$i](t){let e=0,r=t.length;for(;e+512<=r&&!this[At]&&!this[Wi];)switch(this[Ce]){case"begin":case"header":this[hd](t,e),e+=512;break;case"ignore":case"body":e+=this[Go](t,e);break;case"meta":e+=this[dd](t,e);break;default:throw new Error("invalid state: "+this[Ce])}e<r&&(this[H]=this[H]?Buffer.concat([t.subarray(e),this[H]]):t.subarray(e))}end(t,e,r){return typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),r&&this.once("finish",r),this[At]||(this[Y]?(t&&this[Y].write(t),this[Y].end()):(this[bt]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Gi]())),this}},On=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},rw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},Jd=(t,e)=>{let r=new Map(e.map(s=>[On(s),!0])),n=t.filter,i=(s,o="")=>{let a=o||fm(s).root||".",c;if(s===a)c=!1;else{let l=r.get(s);c=l!==void 0?l:i(hm(s),a)}return r.set(s,c),c};t.filter=n?(s,o)=>n(s,o)&&i(On(s)):s=>i(On(s))},nw=t=>{let e=new Mn(t),r=t.file,n;try{n=Dr.openSync(r,"r");let i=Dr.fstatSync(n),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),a=Dr.readSync(n,o,0,i.size,0);e.end(a===o.byteLength?o:o.subarray(0,a))}else{let o=0,a=Buffer.allocUnsafe(s);for(;o<i.size;){let c=Dr.readSync(n,a,0,s,o);if(c===0)break;o+=c,e.write(a.subarray(0,c))}e.end()}}finally{if(typeof n=="number")try{Dr.closeSync(n)}catch{}}},iw=(t,e)=>{let r=new Mn(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("end",s),Dr.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ea(i,{readSize:n,size:c.size});l.on("error",o),l.pipe(r)}})})},Mr=Bn(nw,iw,t=>new Mn(t),t=>new Mn(t),(t,e)=>{e?.length&&Jd(t,e),t.noResume||rw(t)}),Vd=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:ow,parse:pd}=sw,Ta=t=>{let e="",r=pd(t);for(;ow(t)||r.root;){let n=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(n.length),e+=n,r=pd(t)}return[e,t]},us=["|","<",">","?",":"],Ra=us.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),aw=new Map(us.map((t,e)=>[t,Ra[e]])),cw=new Map(Ra.map((t,e)=>[t,us[e]])),gd=t=>us.reduce((e,r)=>e.split(r).join(aw.get(r)),t),lw=t=>Ra.reduce((e,r)=>e.split(r).join(cw.get(r)),t),Zd=(t,e)=>e?(t=D(t).replace(/^\.(\/|$)/,""),On(e)+"/"+t):D(t),dw=16*1024*1024,md=Symbol("process"),wd=Symbol("file"),yd=Symbol("directory"),na=Symbol("symlink"),_d=Symbol("hardlink"),In=Symbol("header"),Xi=Symbol("read"),ia=Symbol("lstat"),Qi=Symbol("onlstat"),sa=Symbol("onread"),oa=Symbol("onreadlink"),aa=Symbol("openfile"),ca=Symbol("onopenfile"),Dt=Symbol("close"),as=Symbol("mode"),la=Symbol("awaitDrain"),jo=Symbol("ondrain"),Qe=Symbol("prefix"),Kd=class extends or{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let r=Sa(e);super(),this.path=D(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||dw,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=D(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime,this.prefix=r.prefix?D(r.prefix):void 0,this.onWriteEntry=r.onWriteEntry,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let n=!1;if(!this.preservePaths){let[s,o]=Ta(this.path);s&&typeof o=="string"&&(this.path=o,n=s)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=lw(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=D(r.absolute||ud.resolve(this.cwd,t)),this.path===""&&(this.path="./"),n&&this.warn("TAR_ENTRY_INFO",`stripping ${n} from absolute path`,{entry:this,path:n+this.path});let i=this.statCache.get(this.absolute);i?this[Qi](i):this[ia]()}warn(t,e,r={}){return fs(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[ia](){Xe.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Qi](e)})}[Qi](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=uw(t),this.emit("stat",t),this[md]()}[md](){switch(this.type){case"File":return this[wd]();case"Directory":return this[yd]();case"SymbolicLink":return this[na]();default:return this.end()}}[as](t){return Vd(t,this.type==="Directory",this.portable)}[Qe](t){return Zd(t,this.prefix)}[In](){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 sr({path:this[Qe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qe](this.linkpath):this.linkpath,mode:this[as](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 ss({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[Qe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qe](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)}[yd](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[In](),this.end()}[na](){Xe.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[oa](e)})}[oa](t){this.linkpath=D(t),this[In](),this.end()}[_d](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=D(ud.relative(this.cwd,t)),this.stat.size=0,this[In](),this.end()}[wd](){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[_d](e);this.linkCache.set(t,this.absolute)}if(this[In](),this.stat.size===0)return this.end();this[aa]()}[aa](){Xe.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[ca](e)})}[ca](t){if(this.fd=t,this.#e)return this[Dt]();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[Xi]()}[Xi](){let{fd:t,buf:e,offset:r,length:n,pos:i}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");Xe.read(t,e,r,n,i,(s,o)=>{if(s)return this[Dt](()=>this.emit("error",s));this[sa](o)})}[Dt](t=()=>{}){this.fd!==void 0&&Xe.close(this.fd,t)}[sa](t){if(t<=0&&this.remain>0){let r=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Dt](()=>this.emit("error",r))}if(t>this.remain){let r=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Dt](()=>this.emit("error",r))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let r=t;r<this.length&&t<this.blockRemain;r++)this.buf[r+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[jo]():this[la](()=>this[jo]())}[la](t){this.once("drain",t)}write(t,e,r){if(typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let n=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",n)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,r)}[jo](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Dt](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[Xi]()}},hw=class extends Kd{sync=!0;[ia](){this[Qi](Xe.lstatSync(this.absolute))}[na](){this[oa](Xe.readlinkSync(this.absolute))}[aa](){this[ca](Xe.openSync(this.absolute,"r"))}[Xi](){let t=!0;try{let{fd:e,buf:r,offset:n,length:i,pos:s}=this;if(e===void 0||r===void 0)throw new Error("fd and buf must be set in READ method");let o=Xe.readSync(e,r,n,i,s);this[sa](o),t=!1}finally{if(t)try{this[Dt](()=>{})}catch{}}}[la](t){t()}[Dt](t=()=>{}){this.fd!==void 0&&Xe.closeSync(this.fd),t()}},fw=class extends or{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,r={}){return fs(this,t,e,r)}constructor(t,e={}){let r=Sa(e);super(),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.onWriteEntry=r.onWriteEntry,this.readEntry=t;let{type:n}=t;if(n==="Unsupported")throw new Error("writing entry that should be ignored");this.type=n,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix,this.path=D(t.path),this.mode=t.mode!==void 0?this[as](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:r.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?D(t.linkpath):void 0,typeof r.onwarn=="function"&&this.on("warn",r.onwarn);let i=!1;if(!this.preservePaths){let[o,a]=Ta(this.path);o&&typeof a=="string"&&(this.path=a,i=o)}this.remain=t.size,this.blockRemain=t.startBlockSize,this.onWriteEntry?.(this),this.header=new sr({path:this[Qe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qe](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}),i&&this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute path`,{entry:this,path:i+this.path}),this.header.encode()&&!this.noPax&&super.write(new ss({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[Qe](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[Qe](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 s=this.header?.block;if(!s)throw new Error("failed to encode header");super.write(s),t.pipe(this)}[Qe](t){return Zd(t,this.prefix)}[as](t){return Vd(t,this.type==="Directory",this.portable)}write(t,e,r){typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let n=t.length;if(n>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=n,super.write(t,r)}end(t,e,r){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(r=t,e=void 0,t=void 0),typeof e=="function"&&(r=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),r&&this.once("finish",r),t?super.end(t,r):super.end(r),this}},uw=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",pw=class Nr{tail;head;length=0;static create(e=[]){return new Nr(e)}constructor(e=[]){for(let r of e)this.push(r)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let r=e.next,n=e.prev;return r&&(r.prev=n),n&&(n.next=r),e===this.head&&(this.head=r),e===this.tail&&(this.tail=n),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,r}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let r=this.head;e.list=this,e.next=r,r&&(r.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let r=this.tail;e.list=this,e.prev=r,r&&(r.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let r=0,n=e.length;r<n;r++)mw(this,e[r]);return this.length}unshift(...e){for(var r=0,n=e.length;r<n;r++)ww(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let n=this.head,i=0;n;i++)e.call(r,n.value,i,this),n=n.next}forEachReverse(e,r){r=r||this;for(let n=this.tail,i=this.length-1;n;i--)e.call(r,n.value,i,this),n=n.prev}get(e){let r=0,n=this.head;for(;n&&r<e;r++)n=n.next;if(r===e&&n)return n.value}getReverse(e){let r=0,n=this.tail;for(;n&&r<e;r++)n=n.prev;if(r===e&&n)return n.value}map(e,r){r=r||this;let n=new Nr;for(let i=this.head;i;)n.push(e.call(r,i.value,this)),i=i.next;return n}mapReverse(e,r){r=r||this;var n=new Nr;for(let i=this.tail;i;)n.push(e.call(r,i.value,this)),i=i.prev;return n}reduce(e,r){let n,i=this.head;if(arguments.length>1)n=r;else if(this.head)i=this.head.next,n=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var s=0;i;s++)n=e(n,i.value,s),i=i.next;return n}reduceReverse(e,r){let n,i=this.tail;if(arguments.length>1)n=r;else if(this.tail)i=this.tail.prev,n=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let s=this.length-1;i;s--)n=e(n,i.value,s),i=i.prev;return n}toArray(){let e=new Array(this.length);for(let r=0,n=this.head;n;r++)e[r]=n.value,n=n.next;return e}toArrayReverse(){let e=new Array(this.length);for(let r=0,n=this.tail;n;r++)e[r]=n.value,n=n.prev;return e}slice(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let n=new Nr;if(r<e||r<0)return n;e<0&&(e=0),r>this.length&&(r=this.length);let i=this.head,s=0;for(s=0;i&&s<e;s++)i=i.next;for(;i&&s<r;s++,i=i.next)n.push(i.value);return n}sliceReverse(e=0,r=this.length){r<0&&(r+=this.length),e<0&&(e+=this.length);let n=new Nr;if(r<e||r<0)return n;e<0&&(e=0),r>this.length&&(r=this.length);let i=this.length,s=this.tail;for(;s&&i>r;i--)s=s.prev;for(;s&&i>e;i--,s=s.prev)n.push(s.value);return n}splice(e,r=0,...n){e>this.length&&(e=this.length-1),e<0&&(e=this.length+e);let i=this.head;for(let o=0;i&&o<e;o++)i=i.next;let s=[];for(let o=0;i&&o<r;o++)s.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let o of n)i=gw(this,i,o);return s}reverse(){let e=this.head,r=this.tail;for(let n=e;n;n=n.prev){let i=n.prev;n.prev=n.next,n.next=i}return this.head=r,this.tail=e,this}};function gw(t,e,r){let n=e,i=e?e.next:t.head,s=new ka(r,n,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function mw(t,e){t.tail=new ka(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function ww(t,e){t.head=new ka(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var ka=class{list;next;prev;value;constructor(t,e,r,n){this.list=n,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,r?(r.prev=this,this.next=r):this.next=void 0}},Sd=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Id=Buffer.alloc(1024),Yi=Symbol("onStat"),vn=Symbol("ended"),Ue=Symbol("queue"),Tn=Symbol("queue"),xt=Symbol("current"),tr=Symbol("process"),Rn=Symbol("processing"),qi=Symbol("processJob"),ze=Symbol("jobs"),Wo=Symbol("jobDone"),es=Symbol("addFSEntry"),vd=Symbol("addTarEntry"),da=Symbol("stat"),ha=Symbol("readdir"),ts=Symbol("onreaddir"),rs=Symbol("pipe"),Td=Symbol("entry"),qo=Symbol("entryOpt"),ns=Symbol("writeEntryClass"),Xd=Symbol("write"),Jo=Symbol("ondrain"),ps=class extends or{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ns];onWriteEntry;[Ue];[Tn]=new Map;[ze]=0;[Rn]=!1;[vn]=!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=D(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[ns]=Kd,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 Rm(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new bm(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new xm(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[Jo]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Jo]);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[Ue]=new pw,this[ze]=0,this.jobs=Number(t.jobs)||4,this[Rn]=!1,this[vn]=!1}[Xd](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,r){return typeof t=="function"&&(r=t,t=void 0),typeof e=="function"&&(r=e,e=void 0),t&&this.add(t),this[vn]=!0,this[tr](),r&&r(),this}write(t){if(this[vn])throw new Error("write after end");return t instanceof qd?this[vd](t):this[es](t),this.flowing}[vd](t){let e=D(Ed.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Sd(t.path,e);r.entry=new fw(t,this[qo](r)),r.entry.on("end",()=>this[Wo](r)),this[ze]+=1,this[Ue].push(r)}this[tr]()}[es](t){let e=D(Ed.resolve(this.cwd,t));this[Ue].push(new Sd(t,e)),this[tr]()}[da](t){t.pending=!0,this[ze]+=1;let e=this.follow?"stat":"lstat";os[e](t.absolute,(r,n)=>{t.pending=!1,this[ze]-=1,r?this.emit("error",r):this[Yi](t,n)})}[Yi](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[xt])this[qi](t);else{let r=`${e.dev}:${e.ino}`,n=this[Tn].get(r);n?n.push(t):this[Tn].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[tr]()}[ha](t){t.pending=!0,this[ze]+=1,os.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[ze]-=1,e)return this.emit("error",e);this[ts](t,r)})}[ts](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[tr]()}[tr](){if(!this[Rn]){this[Rn]=!0;for(let t=this[Ue].head;t&&this[ze]<this.jobs;t=t.next)if(this[qi](t.value),t.value.ignore){let e=t.next;this[Ue].removeNode(t),t.next=e}this[Rn]=!1,this[vn]&&this[Ue].length===0&&this[ze]===0&&(this.zip?this.zip.end(Id):(super.write(Id),super.end()))}}get[xt](){return this[Ue]&&this[Ue].head&&this[Ue].head.value}[Wo](t){this[Ue].shift(),this[ze]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,n=this[Tn].get(r);if(n){this[Tn].delete(r);for(let i of n)i.pending=!1,this[qi](i)}}this[tr]()}[qi](t){if(t.pending&&t.pendingLink&&t===this[xt]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[xt]&&!t.piped&&this[rs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Yi](t,e):this[da](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[ts](t,e):this[ha](t),!t.readdir)return}if(t.entry=this[Td](t),!t.entry){t.ignore=!0;return}t===this[xt]&&!t.piped&&this[rs](t)}}}[qo](t){return{onwarn:(e,r,n)=>this.warn(e,r,n),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}}[Td](t){this[ze]+=1;try{return new this[ns](t.path,this[qo](t)).on("end",()=>this[Wo](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Jo](){this[xt]&&this[xt].entry&&this[xt].entry.resume()}[rs](t){t.piped=!0,t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[es](s+n)});let e=t.entry,r=this.zip;if(!e)throw new Error("cannot pipe without source");r?e.on("data",n=>{r.write(n)||e.pause()}):e.on("data",n=>{super.write(n)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,r={}){fs(this,t,e,r)}},ba=class extends ps{sync=!0;constructor(t){super(t),this[ns]=hw}pause(){}resume(){}[da](t){let e=this.follow?"statSync":"lstatSync";this[Yi](t,os[e](t.absolute))}[ha](t){this[ts](t,os.readdirSync(t.absolute))}[rs](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[es](s+n)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",n=>{r.write(n)}):e.on("data",n=>{super[Xd](n)})}},yw=(t,e)=>{let r=new ba(t),n=new Bd(t.file,{mode:t.mode||438});r.pipe(n),Qd(r,e)},_w=(t,e)=>{let r=new ps(t),n=new ds(t.file,{mode:t.mode||438});r.pipe(n);let i=new Promise((s,o)=>{n.on("error",o),n.on("close",s),r.on("error",o)});return Yd(r,e).catch(s=>r.emit("error",s)),i},Qd=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Mr({file:Ud.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r)}),t.end()},Yd=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Mr({file:Ud.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{t.add(n)}}):t.add(r);t.end()},Ew=(t,e)=>{let r=new ba(t);return Qd(r,e),r},Sw=(t,e)=>{let r=new ps(t);return Yd(r,e).catch(n=>r.emit("error",n)),r},vT=Bn(yw,_w,Ew,Sw,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),vw=process.env.__FAKE_PLATFORM__||process.platform,nh=vw==="win32",{O_CREAT:ih,O_NOFOLLOW:Rd,O_TRUNC:sh,O_WRONLY:oh}=rh.constants,ah=Number(process.env.__FAKE_FS_O_FILENAME__)||rh.constants.UV_FS_O_FILEMAP||0,Tw=nh&&!!ah,Rw=512*1024,kw=ah|sh|ih|oh,kd=!nh&&typeof Rd=="number"?Rd|sh|ih|oh:null,ch=kd!==null?()=>kd:Tw?t=>t<Rw?kw:"w":()=>"w",fa=(t,e,r)=>{try{return gs.lchownSync(t,e,r)}catch(n){if(n?.code!=="ENOENT")throw n}},cs=(t,e,r,n)=>{gs.lchown(t,e,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},bw=(t,e,r,n,i)=>{if(e.isDirectory())lh(Pn.resolve(t,e.name),r,n,s=>{if(s)return i(s);let o=Pn.resolve(t,e.name);cs(o,r,n,i)});else{let s=Pn.resolve(t,e.name);cs(s,r,n,i)}},lh=(t,e,r,n)=>{gs.readdir(t,{withFileTypes:!0},(i,s)=>{if(i){if(i.code==="ENOENT")return n();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return n(i)}if(i||!s.length)return cs(t,e,r,n);let o=s.length,a=null,c=l=>{if(!a){if(l)return n(a=l);if(--o===0)return cs(t,e,r,n)}};for(let l of s)bw(t,l,e,r,c)})},Aw=(t,e,r,n)=>{e.isDirectory()&&dh(Pn.resolve(t,e.name),r,n),fa(Pn.resolve(t,e.name),r,n)},dh=(t,e,r)=>{let n;try{n=gs.readdirSync(t,{withFileTypes:!0})}catch(i){let s=i;if(s?.code==="ENOENT")return;if(s?.code==="ENOTDIR"||s?.code==="ENOTSUP")return fa(t,e,r);throw s}for(let i of n)Aw(t,i,e,r);return fa(t,e,r)},hh=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"}},ms=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"}},Ow=(t,e)=>{Ae.stat(t,(r,n)=>{(r||!n.isDirectory())&&(r=new hh(t,r?.code||"ENOTDIR")),e(r)})},Pw=(t,e,r)=>{t=D(t);let n=e.umask??18,i=e.mode|448,s=(i&n)!==0,o=e.uid,a=e.gid,c=typeof o=="number"&&typeof a=="number"&&(o!==e.processUid||a!==e.processGid),l=e.preserve,d=e.unlink,p=D(e.cwd),m=(u,g)=>{u?r(u):g&&c?lh(g,o,a,w=>m(w)):s?Ae.chmod(t,i,r):r()};if(t===p)return Ow(t,m);if(l)return xw.mkdir(t,{mode:i,recursive:!0}).then(u=>m(null,u??void 0),m);let f=D(ls.relative(p,t)).split("/");ua(p,f,i,d,p,void 0,m)},ua=(t,e,r,n,i,s,o)=>{if(e.length===0)return o(null,s);let a=e.shift(),c=D(ls.resolve(t+"/"+a));Ae.mkdir(c,r,fh(c,e,r,n,i,s,o))},fh=(t,e,r,n,i,s,o)=>a=>{a?Ae.lstat(t,(c,l)=>{if(c)c.path=c.path&&D(c.path),o(c);else if(l.isDirectory())ua(t,e,r,n,i,s,o);else if(n)Ae.unlink(t,d=>{if(d)return o(d);Ae.mkdir(t,r,fh(t,e,r,n,i,s,o))});else{if(l.isSymbolicLink())return o(new ms(t,t+"/"+e.join("/")));o(a)}}):(s=s||t,ua(t,e,r,n,i,s,o))},Cw=t=>{let e=!1,r;try{e=Ae.statSync(t).isDirectory()}catch(n){r=n?.code}finally{if(!e)throw new hh(t,r??"ENOTDIR")}},Dw=(t,e)=>{t=D(t);let r=e.umask??18,n=e.mode|448,i=(n&r)!==0,s=e.uid,o=e.gid,a=typeof s=="number"&&typeof o=="number"&&(s!==e.processUid||o!==e.processGid),c=e.preserve,l=e.unlink,d=D(e.cwd),p=u=>{u&&a&&dh(u,s,o),i&&Ae.chmodSync(t,n)};if(t===d)return Cw(d),p();if(c)return p(Ae.mkdirSync(t,{mode:n,recursive:!0})??void 0);let m=D(ls.relative(d,t)).split("/"),f;for(let u=m.shift(),g=d;u&&(g+="/"+u);u=m.shift()){g=D(ls.resolve(g));try{Ae.mkdirSync(g,n),f=f||g}catch{let w=Ae.lstatSync(g);if(w.isDirectory())continue;if(l){Ae.unlinkSync(g),Ae.mkdirSync(g,n),f=f||g;continue}else if(w.isSymbolicLink())return new ms(g,g+"/"+m.join("/"))}}return p(f)},Vo=Object.create(null),bd=1e4,Ar=new Set,Nw=t=>{Ar.has(t)?Ar.delete(t):Vo[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Ar.add(t);let e=Vo[t],r=Ar.size-bd;if(r>bd/10){for(let n of Ar)if(Ar.delete(n),delete Vo[n],--r<=0)break}return e},Lw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Fw=Lw==="win32",Mw=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let n=e.at(-1);return n!==void 0&&(r=uh(n,r)),e.push(r||"/"),e},[]),Bw=class{#e=new Map;#r=new Map;#n=new Set;reserve(t,e){t=Fw?["win32 parallelization disabled"]:t.map(n=>On(uh(Nw(n))));let r=new Set(t.map(n=>Mw(n)).reduce((n,i)=>n.concat(i)));this.#r.set(e,{dirs:r,paths:t});for(let n of t){let i=this.#e.get(n);i?i.push(e):this.#e.set(n,[e])}for(let n of r){let i=this.#e.get(n);if(!i)this.#e.set(n,[new Set([e])]);else{let s=i.at(-1);s instanceof Set?s.add(e):i.push(new Set([e]))}}return this.#i(e)}#s(t){let e=this.#r.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(r=>this.#e.get(r)),dirs:[...e.dirs].map(r=>this.#e.get(r))}}check(t){let{paths:e,dirs:r}=this.#s(t);return e.every(n=>n&&n[0]===t)&&r.every(n=>n&&n[0]instanceof Set&&n[0].has(t))}#i(t){return this.#n.has(t)||!this.check(t)?!1:(this.#n.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#n.has(t))return!1;let e=this.#r.get(t);if(!e)throw new Error("invalid reservation");let{paths:r,dirs:n}=e,i=new Set;for(let s of r){let o=this.#e.get(s);if(!o||o?.[0]!==t)continue;let a=o[1];if(!a){this.#e.delete(s);continue}if(o.shift(),typeof a=="function")i.add(a);else for(let c of a)i.add(c)}for(let s of n){let o=this.#e.get(s),a=o?.[0];if(!(!o||!(a instanceof Set)))if(a.size===1&&o.length===1){this.#e.delete(s);continue}else if(a.size===1){o.shift();let c=o[0];typeof c=="function"&&i.add(c)}else a.delete(t)}return this.#n.delete(t),i.forEach(s=>this.#i(s)),!0}},Uw=()=>process.umask(),Ad=Symbol("onEntry"),pa=Symbol("checkFs"),xd=Symbol("checkFs2"),ga=Symbol("isReusable"),De=Symbol("makeFs"),ma=Symbol("file"),wa=Symbol("directory"),is=Symbol("link"),Od=Symbol("symlink"),Pd=Symbol("hardlink"),An=Symbol("ensureNoSymlink"),Cd=Symbol("unsupported"),Dd=Symbol("checkPath"),Zo=Symbol("stripAbsolutePath"),Nt=Symbol("mkdir"),ae=Symbol("onError"),Ji=Symbol("pending"),Nd=Symbol("pend"),xr=Symbol("unpend"),Ko=Symbol("ended"),Xo=Symbol("maybeClose"),ya=Symbol("skip"),Cn=Symbol("doChown"),Dn=Symbol("uid"),Nn=Symbol("gid"),Ln=Symbol("checkedCwd"),zw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Fn=zw==="win32",$w=1024,Gw=(t,e)=>{if(!Fn)return N.unlink(t,e);let r=t+".DELETE."+th(16).toString("hex");N.rename(t,r,n=>{if(n)return e(n);N.unlink(r,e)})},Hw=t=>{if(!Fn)return N.unlinkSync(t);let e=t+".DELETE."+th(16).toString("hex");N.renameSync(t,e),N.unlinkSync(e)},Ld=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Aa=class extends Mn{[Ko]=!1;[Ln]=!1;[Ji]=0;reservations=new Bw;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[Ko]=!0,this[Xo]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:$w,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||Fn,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=D(te.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Uw():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[Ad](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[Xo](){this[Ko]&&this[Ji]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Zo](t,e){let r=t[e],{type:n}=t;if(!r||this.preservePaths)return!0;let[i,s]=Ta(r),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||Fn&&/^[a-z]:\.\.$/i.test(o[0]??"")){if(e==="path"||n==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:r}),!1;let a=te.posix.dirname(t.path),c=te.posix.normalize(te.posix.join(a,o.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:r}),!1}return i&&(t[e]=String(s),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${e}`,{entry:t,[e]:r})),!0}[Dd](t){let e=D(t.path),r=e.split("/");if(this.strip){if(r.length<this.strip)return!1;if(t.type==="Link"){let n=D(String(t.linkpath)).split("/");if(n.length>=this.strip)t.linkpath=n.slice(this.strip).join("/");else return!1}r.splice(0,this.strip),t.path=r.join("/")}if(isFinite(this.maxDepth)&&r.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:r.length,maxDepth:this.maxDepth}),!1;if(!this[Zo](t,"path")||!this[Zo](t,"linkpath"))return!1;if(t.absolute=te.isAbsolute(t.path)?D(te.resolve(t.path)):D(te.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:D(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:n}=te.win32.parse(String(t.absolute));t.absolute=n+gd(String(t.absolute).slice(n.length));let{root:i}=te.win32.parse(t.path);t.path=i+gd(t.path.slice(i.length))}return!0}[Ad](t){if(!this[Dd](t))return t.resume();switch(Iw.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[pa](t);default:return this[Cd](t)}}[ae](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[xr](),e.resume())}[Nt](t,e,r){Pw(D(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},r)}[Cn](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}[Dn](t){return Ld(this.uid,t.uid,this.processUid)}[Nn](t){return Ld(this.gid,t.gid,this.processGid)}[ma](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=new ds(String(t.absolute),{flags:ch(t.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&N.close(n.fd,()=>{}),n.write=()=>!0,this[ae](a,t),e()});let i=1,s=a=>{if(a){n.fd&&N.close(n.fd,()=>{}),this[ae](a,t),e();return}--i===0&&n.fd!==void 0&&N.close(n.fd,c=>{c?this[ae](c,t):this[xr](),e()})};n.on("finish",()=>{let a=String(t.absolute),c=n.fd;if(typeof c=="number"&&t.mtime&&!this.noMtime){i++;let l=t.atime||new Date,d=t.mtime;N.futimes(c,l,d,p=>p?N.utimes(a,l,d,m=>s(m&&p)):s())}if(typeof c=="number"&&this[Cn](t)){i++;let l=this[Dn](t),d=this[Nn](t);typeof l=="number"&&typeof d=="number"&&N.fchown(c,l,d,p=>p?N.chown(a,l,d,m=>s(m&&p)):s())}s()});let o=this.transform&&this.transform(t)||t;o!==t&&(o.on("error",a=>{this[ae](a,t),e()}),t.pipe(o)),o.pipe(n)}[wa](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Nt](String(t.absolute),r,n=>{if(n){this[ae](n,t),e();return}let i=1,s=()=>{--i===0&&(e(),this[xr](),t.resume())};t.mtime&&!this.noMtime&&(i++,N.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[Cn](t)&&(i++,N.chown(String(t.absolute),Number(this[Dn](t)),Number(this[Nn](t)),s)),s()})}[Cd](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Od](t,e){let r=D(te.relative(this.cwd,te.resolve(te.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[An](t,this.cwd,r,()=>this[is](t,String(t.linkpath),"symlink",e),n=>{this[ae](n,t),e()})}[Pd](t,e){let r=D(te.resolve(this.cwd,String(t.linkpath))),n=D(String(t.linkpath)).split("/");this[An](t,this.cwd,n,()=>this[is](t,r,"link",e),i=>{this[ae](i,t),e()})}[An](t,e,r,n,i){let s=r.shift();if(this.preservePaths||s===void 0)return n();let o=te.resolve(e,s);N.lstat(o,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new ms(o,te.resolve(o,r.join("/"))));this[An](t,o,r,n,i)})}[Nd](){this[Ji]++}[xr](){this[Ji]--,this[Xo]()}[ya](t){this[xr](),t.resume()}[ga](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!Fn}[pa](t){this[Nd]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[xd](t,r))}[xd](t,e){let r=o=>{e(o)},n=()=>{this[Nt](this.cwd,this.dmode,o=>{if(o){this[ae](o,t),r();return}this[Ln]=!0,i()})},i=()=>{if(t.absolute!==this.cwd){let o=D(te.dirname(String(t.absolute)));if(o!==this.cwd)return this[Nt](o,this.dmode,a=>{if(a){this[ae](a,t),r();return}s()})}s()},s=()=>{N.lstat(String(t.absolute),(o,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[ya](t),r();return}if(o||this[ga](t,a))return this[De](null,t,r);if(a.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,l=d=>this[De](d??null,t,r);return c?N.chmod(String(t.absolute),Number(t.mode),l):l()}if(t.absolute!==this.cwd)return N.rmdir(String(t.absolute),c=>this[De](c??null,t,r))}if(t.absolute===this.cwd)return this[De](null,t,r);Gw(String(t.absolute),c=>this[De](c??null,t,r))})};this[Ln]?i():n()}[De](t,e,r){if(t){this[ae](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[ma](e,r);case"Link":return this[Pd](e,r);case"SymbolicLink":return this[Od](e,r);case"Directory":case"GNUDumpDir":return this[wa](e,r)}}[is](t,e,r,n){N[r](e,String(t.absolute),i=>{i?this[ae](i,t):(this[xr](),t.resume()),n()})}},kn=t=>{try{return[null,t()]}catch(e){return[e,null]}},ph=class extends Aa{sync=!0;[De](t,e){return super[De](t,e,()=>{})}[pa](t){if(!this[Ln]){let i=this[Nt](this.cwd,this.dmode);if(i)return this[ae](i,t);this[Ln]=!0}if(t.absolute!==this.cwd){let i=D(te.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[Nt](i,this.dmode);if(s)return this[ae](s,t)}}let[e,r]=kn(()=>N.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[ya](t);if(e||this[ga](t,r))return this[De](null,t);if(r.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[o]=s?kn(()=>{N.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[De](o,t)}let[i]=kn(()=>N.rmdirSync(String(t.absolute)));this[De](i,t)}let[n]=t.absolute===this.cwd?[]:kn(()=>Hw(String(t.absolute)));this[De](n,t)}[ma](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=o=>{let a;try{N.closeSync(i)}catch(c){a=c}(o||a)&&this[ae](o||a,t),e()},i;try{i=N.openSync(String(t.absolute),ch(t.size),r)}catch(o){return n(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[ae](o,t)),t.pipe(s)),s.on("data",o=>{try{N.writeSync(i,o,0,o.length)}catch(a){n(a)}}),s.on("end",()=>{let o=null;if(t.mtime&&!this.noMtime){let a=t.atime||new Date,c=t.mtime;try{N.futimesSync(i,a,c)}catch(l){try{N.utimesSync(String(t.absolute),a,c)}catch{o=l}}}if(this[Cn](t)){let a=this[Dn](t),c=this[Nn](t);try{N.fchownSync(i,Number(a),Number(c))}catch(l){try{N.chownSync(String(t.absolute),Number(a),Number(c))}catch{o=o||l}}}n(o)})}[wa](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,n=this[Nt](String(t.absolute),r);if(n){this[ae](n,t),e();return}if(t.mtime&&!this.noMtime)try{N.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Cn](t))try{N.chownSync(String(t.absolute),Number(this[Dn](t)),Number(this[Nn](t)))}catch{}e(),t.resume()}[Nt](t,e){try{return Dw(D(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(r){return r}}[An](t,e,r,n,i){if(this.preservePaths||r.length===0)return n();let s=e;for(let o of r){s=te.resolve(s,o);let[a,c]=kn(()=>N.lstatSync(s));if(a)return n();if(c.isSymbolicLink())return i(new ms(s,te.resolve(e,r.join("/"))))}n()}[is](t,e,r,n){let i=`${r}Sync`;try{N[i](e,String(t.absolute)),n(),t.resume()}catch(s){return this[ae](s,t)}}},jw=t=>{let e=new ph(t),r=t.file,n=eh.statSync(r),i=t.maxReadSize||16*1024*1024;new dm(r,{readSize:i,size:n.size}).pipe(e)},Ww=(t,e)=>{let r=new Aa(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("close",s),eh.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ea(i,{readSize:n,size:c.size});l.on("error",o),l.pipe(r)}})})},gh=Bn(jw,Ww,t=>new ph(t),t=>new Aa(t),(t,e)=>{e?.length&&Jd(t,e)}),qw=(t,e)=>{let r=new ba(t),n=!0,i,s;try{try{i=be.openSync(t.file,"r+")}catch(c){if(c?.code==="ENOENT")i=be.openSync(t.file,"w+");else throw c}let o=be.fstatSync(i),a=Buffer.alloc(512);e:for(s=0;s<o.size;s+=512){for(let d=0,p=0;d<512;d+=p){if(p=be.readSync(i,a,d,a.length-d,s+d),s===0&&a[0]===31&&a[1]===139)throw new Error("cannot append to compressed archives");if(!p)break e}let c=new sr(a);if(!c.cksumValid)break;let l=512*Math.ceil((c.size||0)/512);if(s+l+512>o.size)break;s+=l,t.mtimeCache&&c.mtime&&t.mtimeCache.set(String(c.path),c.mtime)}n=!1,Jw(t,r,s,i,e)}finally{if(n)try{be.closeSync(i)}catch{}}},Jw=(t,e,r,n,i)=>{let s=new Bd(t.file,{fd:n,start:r});e.pipe(s),Zw(e,i)},Vw=(t,e)=>{e=Array.from(e);let r=new ps(t),n=(i,s,o)=>{let a=(m,f)=>{m?be.close(i,u=>o(m)):o(null,f)},c=0;if(s===0)return a(null,0);let l=0,d=Buffer.alloc(512),p=(m,f)=>{if(m||f===void 0)return a(m);if(l+=f,l<512&&f)return be.read(i,d,l,d.length-l,c+l,p);if(c===0&&d[0]===31&&d[1]===139)return a(new Error("cannot append to compressed archives"));if(l<512)return a(null,c);let u=new sr(d);if(!u.cksumValid)return a(null,c);let g=512*Math.ceil((u.size??0)/512);if(c+g+512>s||(c+=g+512,c>=s))return a(null,c);t.mtimeCache&&u.mtime&&t.mtimeCache.set(String(u.path),u.mtime),l=0,be.read(i,d,0,512,c,p)};be.read(i,d,0,512,c,p)};return new Promise((i,s)=>{r.on("error",s);let o="r+",a=(c,l)=>{if(c&&c.code==="ENOENT"&&o==="r+")return o="w+",be.open(t.file,o,a);if(c||!l)return s(c);be.fstat(l,(d,p)=>{if(d)return be.close(l,()=>s(d));n(l,p.size,(m,f)=>{if(m)return s(m);let u=new ds(t.file,{fd:l,start:f});r.pipe(u),u.on("error",s),u.on("close",i),Kw(r,e)})})};be.open(t.file,o,a)})},Zw=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?Mr({file:mh.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r)}),t.end()},Kw=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await Mr({file:mh.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r);t.end()},bn=Bn(qw,Vw,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!ym(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")}),BT=Bn(bn.syncFile,bn.asyncFile,bn.syncNoFile,bn.asyncNoFile,(t,e=[])=>{bn.validate?.(t,e),Xw(t)}),Xw=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,n)=>e(r,n)&&!((t.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0)):(r,n)=>!((t.mtimeCache?.get(r)??n.mtime??0)>(n.mtime??0))};vt();var He={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",DELETE:"_agent/delete"};function Un(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function wh(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function yh(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function _h(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Br(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}_e();F();de();_e();function wt(t,e){if(Un(t)!=="cloud")throw new _("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function ws(t){return t.startsWith("http://")||t.startsWith("https://")}function ys(t){return t.endsWith("/")?t.slice(0,-1):t}_e();F();var _s="1008033",Eh="1289";var Sh="pbbp2",Ih="https://www.coze.cn",vh="/api/coze_claw/resource/get_frontier_key",Yw="https://www.coze.cn",ey="wss://frontier.coze.cn";function Es(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Yw}function Th(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??ey}function Ur(t){let e={},r=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,n=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return r&&(e["x-tt-env"]=r),n&&(e["x-use-ppe"]=n),e}function $n(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var zn=x("handshake");async function xa(t){let e=Es(t.endpoint),r=t.timeoutMs??1e4,n=`${ys(e)}${vh}?aid=${encodeURIComponent(_s)}`,i={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Ur(t.ppeOverride)},s=new AbortController,o=setTimeout(()=>s.abort(),r);zn.info("frontier key handshake",{base:e});try{let a=await fetch(n,{method:"GET",headers:i,signal:s.signal}),c=a.headers.get("x-tt-logid")??"",l=a.headers.get("x-tt-trace-id")??"";if(!a.ok){let u=await a.text().catch(()=>"");throw new _("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${u.slice(0,200)}`)}let d=await a.json();if(d.code!==void 0&&d.code!==0)throw new _("UPSTREAM_HANDSHAKE_FAILED",`handshake code=${d.code} msg=${d.msg??"-"} logid=${c}`);let p=d.data??{},m=typeof p.access_key=="string"&&p.access_key||typeof p.accessKey=="string"&&p.accessKey||void 0,f=typeof p.device_id=="string"&&p.device_id||typeof p.deviceId=="string"&&p.deviceId||void 0;if(!m||!f){let u=JSON.stringify(d).slice(0,500);throw new _("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${c}: ${u}`)}return zn.info("handshake ok",{remoteDeviceId:f,logid:c,traceId:l}),{accessKey:m,deviceId:f}}catch(a){if(a instanceof _)throw zn.error("handshake failed (bridge error)",{base:e,message:a.message,code:a.code}),a;if(a.name==="AbortError")throw zn.warn("handshake timeout",{base:e,timeoutMs:r}),new _("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:a});let c=a.cause;throw zn.error("handshake error",{base:e,message:a instanceof Error?a.message:String(a),errno:c?.code,syscall:c?.syscall,cause:String(a).slice(0,300)}),new _("UPSTREAM_HANDSHAKE_FAILED",String(a),{cause:a})}finally{clearTimeout(o)}}var Oa=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",et="auto",Rh=2e5;function kh(t){return{model:t.model??et,...t.modelToken?{modelToken:t.modelToken}:{}}}function bh(t){return!t||t===et}function Ah(t){let e={};return t.modelToken?(e.ANTHROPIC_BASE_URL=Oa,e.ANTHROPIC_AUTH_TOKEN=t.modelToken,e.ANTHROPIC_MODEL=t.model||et,t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))):bh(t.model)||(e.ANTHROPIC_MODEL=t.model),e}function xh(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||et}"`):bh(t.model)||e.push("-c",`model="${t.model}"`),t.modelToken){e.push("-c",'model_providers.coze.name="coze"'),e.push("-c",`model_providers.coze.base_url="${Oa}/v1"`),e.push("-c",'model_providers.coze.env_key="OPENAI_API_KEY"'),e.push("-c",'model_providers.coze.wire_api="responses"'),e.push("-c","model_providers.coze.requires_openai_auth=false"),e.push("-c","model_providers.coze.supports_websockets=false"),e.push("-c",'model_provider="coze"');let r=t.modelInfo?.contextWindow??Rh;e.push("-c",`model_context_window=${r}`)}return e}function Oh(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Pa(t,e){let{ttEnv:r,usePpe:n}=$n(t),i={};return r&&(i["x-tt-env"]=r),n&&(i["x-use-ppe"]=n),e&&(i["x-mock-scenario"]=e),i}function Ph(t,e,r){if(!t.modelToken)return{};let n=Pa(e,r);return Object.keys(n).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(n).map(([s,o])=>`${s}:${o}`).join(`
83
+ `)}}function Ca(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Ch(t,e,r){if(!t.modelToken)return null;let n=t.model||et,i=Pa(e,r),s=["text"];t.modelInfo?.capabilities?.image===!0&&s.push("image");let o={baseUrl:`${Oa}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:n,name:n,reasoning:!1,input:s,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??Rh,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(o.headers=i),o}function Dh(t,e,r){if(!t.modelToken)return[];let n=Pa(e,r),i=[];for(let[s,o]of Object.entries(n))i.push("-c",`model_providers.coze.http_headers.${s}="${o}"`);return i}var re=x("agent-handlers"),Nh=5*1024*1024,oy=1,ay=6,cy=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ss=class{constructor(e){this.opts=e}opts;async listSkills(e){wt(e._meta,"_agent/listSkills");let r=Br(e._meta),n=await this.loadAgentCfg(r),i=n?.workspace??dt(r).workspace,s=n?.skills??[],o=[];for(let a of s){let c=rt(i,a.relPath,"SKILL.md");await ny(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(uy(a))}return{skills:o}}async addSkills(e){wt(e._meta,"_agent/addSkills");let r=Br(e._meta),n=await this.requireAgentCfg(r),i=e.skills??[],s=[...n.skills??[]],o=new Map(s.map((c,l)=>[c.skillId,l])),a=[];for(let c of i){let l=await Ua({agentId:r,workspace:n.workspace,framework:n.framework,skill:c});za(s,o,l),a.push(c)}return await ki(r,s),this.reloadAgentSessions(r,"skills-added"),{installedSkills:a}}async removeSkills(e){wt(e._meta,"_agent/removeSkills");let r=Br(e._meta),n=await this.requireAgentCfg(r),i=new Set(e.skillIds??[]),s=n.skills??[],o=[];for(let a of s){if(!i.has(a.skillId)){o.push(a);continue}let c=rt(n.workspace,a.relPath);await ry(c,{recursive:!0,force:!0}),re.info("skill removed",{agentId:r,skillId:a.skillId,relPath:a.relPath})}return await ki(r,o),this.reloadAgentSessions(r,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,r){this.reloadAgentSessions(e,r)}reloadAgentSessions(e,r){let n=this.opts.agents.get(e);if(n)for(let[i,s]of n.sessions){if(!s.downstream)continue;let o=s.acpSessionId;if(o&&n.activeTriggers.has(o)||this.isRuntimePendingPermission(s)){s.reloadAfterTurn=!0,re.info("downstream busy, scheduling reload after turn",{reason:r,agentId:e,framework:n.framework,cloudId:i,acpId:o});continue}let c=s.downstream;s.downstream=void 0,re.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:n.framework,cloudId:i,acpId:o}),c.stop(r).catch(l=>re.warn("downstream stop failed during reload (ignored)",{reason:r,agentId:e,cloudId:i,err:String(l)}))}}isRuntimePendingPermission(e){let r=this.opts.isRuntimePendingPermission;return!r||!e.downstream?!1:r(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return re.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,n=await he(r);if(!n)throw new _("AGENT_NOT_FOUND",`agent not found: ${r}`);if(n.cozeIdentity===e.cozeIdentity)return re.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await Sr(n.workspace,n.framework,e.cozeIdentity)}catch(i){throw re.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:r,framework:n.framework,workspace:n.workspace,err:String(i)}),new _("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${r}: ${String(i)}`,{cause:i})}return n.cozeIdentity=e.cozeIdentity,await ve(n),re.info("_agent/update: cozeIdentity rewritten",{agentId:r,framework:n.framework}),this.reloadAgentSessions(r,"identity-changed"),{ok:!0}}async disconnectAgent(e){let r=e.agentId;if(!r)throw new _("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let n=await he(r);return n?(n.disconnectedAt=Date.now(),n.disconnectReason=e.reason??"",await ve(n),re.info("agent disconnected",{agentId:r,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(r,e.reason??"disconnect"),{ok:!0}):(re.warn("_agent/disconnect: agent not found, ignoring",{agentId:r}),{ok:!0})}async switchModel(e){if(wt(e._meta,"_agent/switchModel"),!e.agentId)throw new _("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let r=e.model?.trim()?e.model:et,n=await he(e.agentId);if(!n)throw new _("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);n.model=r,e.modelInfo&&(n.modelInfo=e.modelInfo),await ve(n),re.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let i=this.opts.agents.get(e.agentId);if(!i)return re.info("_agent/switchModel: agent not running, config persisted only",{agentId:e.agentId}),{ok:!0};i.model=r,e.modelInfo&&i.setModelInfo(e.modelInfo),this.opts.cleanupOpenclawProviders&&await this.opts.cleanupOpenclawProviders(i).catch(o=>re.warn("cleanupOpenclawProviders before switchModel failed (ignored)",{agentId:e.agentId,err:String(o)}));let s=[];for(let[o,a]of i.allSessionQueues())s.push(a.enqueue(async()=>{let c=i.sessions.get(o);c?.downstream&&(await c.downstream.stop(`switchModel: ${r}`).catch(()=>{}),c.downstream=void 0)}));return await Promise.all(s),re.info("_agent/switchModel: all session runtimes killed, next prompt will respawn",{agentId:e.agentId,model:r,cloudSessions:s.length}),{ok:!0}}async resetAgent(e){if(wt(e._meta,He.RESET),!e.agentId)throw new _("IPC_BAD_REQUEST",`${He.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,He.RESET),await this.runDetailSync(e.agentId,He.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let n=this.opts.agents.get(e);if(!n){await this.clearPersistedAcpSessionIds(e),re.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await n.killAllRuntimes(r);for(let s of n.sessions.values())s.acpSessionId=void 0,s.replySeq=0,s.loadingSession=!1,s.spawnFailCount=void 0,s.spawnFailedAt=void 0;let i=new Map;for(let[s,o]of n.sessions)i.set(s,{modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt});await fn(e,i)}async clearPersistedAcpSessionIds(e){let r=await he(e).catch(()=>null);if(!r?.sessions)return;let n=!1;for(let i of Object.values(r.sessions))i.acpSessionId&&(i.acpSessionId=void 0,n=!0);n&&await ve(r)}async repairAgent(e){if(wt(e._meta,He.REPAIR),!e.agentId)throw new _("IPC_BAD_REQUEST",`${He.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new _("IPC_BAD_REQUEST",`${He.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(n){re.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(n)})}return await this.runDetailSync(e.agentId,He.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,n){if(!this.opts.detailSyncer){re.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(i){re.warn("detail sync failed (ignored)",{method:r,agentId:e,reason:n,err:String(i)})}}async getFileTree(e){wt(e._meta,"_agent/getFileTree");let r=e._meta,n=Br(r),i=await this.resolveWorkspace(n),s=e.filePath??"",o=this.safeJoin(i,s),a=await Da(o).catch(()=>null);if(!a)throw new _("IPC_BAD_REQUEST",`path not found: ${s}`);if(a.isSymbolicLink())throw new _("IPC_BAD_REQUEST",`symlink not allowed: ${s}`);if(!await hn(o,i))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${s}`);let c=Ty(e.depth);return a.isDirectory()?{tree:await vy(i,o,s,c)}:{tree:[{name:Ry(s),path:$h(s||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){wt(e._meta,"_agent/getFileContent");let r=Br(e._meta),n=await this.resolveWorkspace(r);if(!e.filePath)throw new _("IPC_BAD_REQUEST","filePath required");let i=this.safeJoin(n,e.filePath),s=await Da(i).catch(()=>null);if(!s||!s.isFile())throw new _("IPC_BAD_REQUEST",`not a file: ${e.filePath}`);if(s.isSymbolicLink())throw new _("IPC_BAD_REQUEST",`symlink not allowed: ${e.filePath}`);if(!await hn(i,n))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(s.size>Nh)throw new _("IPC_BAD_REQUEST",`file too large: ${s.size} bytes (max ${Nh})`);let o=await Lh(i);return o.includes(0)?{content:o.toString("base64"),encoding:"base64",size:s.size}:{content:o.toString("utf8"),encoding:"utf-8",size:s.size}}async resolveWorkspace(e){let r=this.opts.agents.get(e);return r?r.workspace:(await he(e).catch(()=>null))?.workspace??dt(e).workspace}safeJoin(e,r){let n=Fa(e,r||"."),i=Ba(e,n);if(i.startsWith("..")||i===".."||i.startsWith(`..${Fh}`))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return n}loadAgentCfg(e){return he(e)}async requireAgentCfg(e){let r=await this.loadAgentCfg(e);if(!r)throw new _("AGENT_NOT_FOUND",`no config for agent: ${e}`);return r}};function ly(t){let e=t.trim().replace(/[\x00-\x1f<>:"|?*/\\]+/g,"-").replace(/^[\s.-]+|[\s.-]+$/g,"").slice(0,64);if(!e||e==="."||e==="..")throw new _("IPC_BAD_REQUEST",`invalid skill name: ${t}`);if(/^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(e))throw new _("IPC_BAD_REQUEST",`reserved windows filename: ${t}`);return e}function dy(t){return t==="claude-code"?rt(".claude","skills"):rt(".agents","skills")}var hy=3e4,fy=50*1024*1024,zr=3e4;async function Ua(t){let{agentId:e,workspace:r,framework:n,skill:i}=t;if(!i.skillName)throw new _("IPC_BAD_REQUEST","skill missing skillName");let s=typeof i.content=="string"&&i.content.length>0,o=typeof i.downloadUrl=="string"&&i.downloadUrl.length>0;if(!s&&!o)throw new _("IPC_BAD_REQUEST",`skill ${i.skillId} missing both content and downloadUrl`);let a=ly(i.skillName),c=dy(n),l=rt(c,a),d=rt(r,l);if(await Na(d,{recursive:!0}),s){let m=Buffer.from(i.content,"utf8");Gn(m.length),await La(rt(d,"SKILL.md"),m,"utf8")}else{let m=await py(i.downloadUrl);my(m)?await Ey(m,d):wy(m)?await yy(m,d):await La(rt(d,"SKILL.md"),m.toString("utf8"),"utf8")}let p={skillId:i.skillId,skillName:i.skillName,relPath:l,installedAt:Date.now(),...i.description?{description:i.description}:{},...i.icon?{icon:i.icon}:{},...i.version?{version:i.version}:{},...i.downloadUrl?{downloadUrl:i.downloadUrl}:{},...i.config?{config:i.config}:{},...i.builtin?{builtin:i.builtin}:{}};return re.info("skill installed",{agentId:e,skillId:i.skillId,skillName:i.skillName,relPath:l,source:s?"content":"downloadUrl"}),p}function za(t,e,r){let n=e.get(r.skillId);if(n!==void 0){t[n]=r;return}e.set(r.skillId,t.length),t.push(r)}function uy(t){return{skillId:t.skillId,skillName:t.skillName,...t.description?{description:t.description}:{},...t.icon?{icon:t.icon}:{},...t.version?{version:t.version}:{},...t.config?{config:t.config}:{},...t.builtin?{builtin:t.builtin}:{}}}async function py(t){if(!t)throw new _("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Gn(e);let r=gy(t);return Gn(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await Lh(e);return Gn(r.length),r}if(ws(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),hy);try{let n=await fetch(t,{signal:e.signal});if(!n.ok)throw new _("IPC_BAD_REQUEST",`fetch skill failed HTTP ${n.status} ${t}`);let i=await n.arrayBuffer();return Gn(i.byteLength),Buffer.from(i)}finally{clearTimeout(r)}}throw new _("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Gn(t){if(t>fy)throw new _("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function gy(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new _("IPC_BAD_REQUEST","bad data URL");let r=!!e[2],n=e[3]??"";return r?Buffer.from(n,"base64"):Buffer.from(decodeURIComponent(n),"utf8")}function my(t){return t.length>=2&&t[0]===31&&t[1]===139}function wy(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],r=t[3];return e===3&&r===4||e===5&&r===6}function Ma(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function yy(t,e){let r,n;try{r=new Uh.default(t),n=r.getEntries()}catch(o){throw new _("IPC_BAD_REQUEST",`zip parse failed: ${o.message}`,{cause:o})}for(let o of n){let a=o.entryName;if(!a||Ma(a))continue;if(a.startsWith("/")||/^[A-Za-z]:[\\/]/.test(a))throw new _("IPC_BAD_REQUEST",`zip entry absolute path: ${a}`);if(a.split(/[/\\]/).some(l=>l===".."))throw new _("IPC_BAD_REQUEST",`zip entry contains '..' (traversal): ${a}`);let c=o.header.attr>>>16&61440;if(c!==0&&c!==32768&&c!==16384)throw new _("IPC_BAD_REQUEST",`zip entry kind 0x${c.toString(16)} not allowed (symlink/hardlink/special): ${a}`)}let i=_y(n),s=Fa(e);for(let o of n){if(Ma(o.entryName))continue;let a=o.entryName;if(i&&a.startsWith(i)&&(a=a.slice(i.length)),!a)continue;let c=Fa(e,a),l=Ba(s,c);if(l.startsWith("..")||l==="..")throw new _("IPC_BAD_REQUEST",`zip entry escapes destDir: ${a}`);if(o.isDirectory){await Na(c,{recursive:!0});continue}await Na(iy(c),{recursive:!0});let d;try{d=o.getData()}catch(p){throw new _("IPC_BAD_REQUEST",`zip entry getData failed (${o.entryName}): ${p.message}`,{cause:p})}await La(c,d)}}function _y(t){let e;for(let r of t){let n=r.entryName;if(!n||Ma(n))continue;let i=n.indexOf("/");if(i<=0)return;let s=n.slice(0,i+1);if(e===void 0)e=s;else if(e!==s)return}return e}async function Ey(t,e){await Sy(t);let r=gh({cwd:e,strip:1}),n=!1,i=setTimeout(()=>{n=!0,r.destroy(new _("IPC_BAD_REQUEST",`tar extract timeout (${zr}ms)`))},zr);try{await Bh(Mh.from(t),r)}catch(s){throw s instanceof _?s:n?new _("IPC_BAD_REQUEST",`tar extract timeout (${zr}ms)`):new _("IPC_BAD_REQUEST",`tar extract failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}}async function Sy(t){let e=[],r=Mr({onReadEntry:s=>{let o=s.path,a=s.type;if(a!=="File"&&a!=="Directory"){e.push(`tar entry kind '${a}' not allowed (symlink/hardlink/special): ${o.slice(0,100)}`);return}if(o.startsWith("/")||o.startsWith("\\")||/^[a-zA-Z]:[\\/]/.test(o)){e.push(`tar entry absolute path: ${o}`);return}o.split(/[/\\]/).some(l=>l==="..")&&e.push(`tar entry contains '..': ${o}`)}}),n=!1,i=setTimeout(()=>{n=!0,r.destroy(new _("IPC_BAD_REQUEST",`tar list timeout (${zr}ms)`))},zr);try{await Bh(Mh.from(t),r)}catch(s){throw n?new _("IPC_BAD_REQUEST",`tar list timeout (${zr}ms)`):new _("IPC_BAD_REQUEST",`tar list failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}if(e.length>0)throw new _("IPC_BAD_REQUEST",e[0]??"tar entry validation failed")}var Iy=5e3;async function vy(t,e,r,n){return zh(t,e,r,n,{count:0})}async function zh(t,e,r,n,i){if(n<=0)return[];let s;try{s=await ty(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let a of s){if(cy.has(a.name)||a.isSymbolicLink())continue;if(i.count>=Iy){o.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let c=rt(e,a.name),l=sy(rt(r,a.name)),d=null;try{d=await Da(c)}catch{continue}if(d.isSymbolicLink())continue;i.count++;let p={name:a.name,path:$h(Ba(t,c)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&n>1&&(p.children=await zh(t,c,l,n-1,i)),o.push(p)}return o.sort((a,c)=>a.isDir!==c.isDir?a.isDir?-1:1:a.name.localeCompare(c.name)),o}function Ty(t){return!t||t<=0?oy:Math.min(t,ay)}function Ry(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function $h(t){return t.split(Fh).join("/")}F();import{readFileSync as VR}from"node:fs";import{dirname as KR,join as XR}from"node:path";import{fileURLToPath as YR}from"node:url";var $r="0.1.88";var Mt=x("agent-health-reporter"),ky=1e4,Hn=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??ky}opts;timer=null;inFlight=!1;unsubscribeRegister=null;intervalMs;start(){this.timer||(this.timer=setInterval(()=>{this.tick()},this.intervalMs),this.timer.unref?.(),this.unsubscribeRegister=this.opts.core.onAgentRegister(()=>{this.tick()}),Mt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Mt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Mt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Mt.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let r=[];for(let o of this.opts.core.agents.values()){let a=by(o);if(!a)continue;let c={agentId:o.agentId,status:a};o.patToken&&(c.patToken=o.patToken),o.accountId&&(c.accountId=o.accountId),r.push(c)}if(r.length===0)return;let n={agents:r,bridgeVersion:$r,_meta:{cozeDeviceId:e}},i;try{i=await this.opts.core.sendRequest("_agent/health",n,5e3)}catch(o){Mt.warn("heartbeat batch send failed",{count:r.length,err:String(o)})}let s=i?.authFailures;if(s&&s.length>0&&(Mt.warn("heartbeat received authFailures from cloud",{count:s.length,agentIds:s.map(o=>o.agentId)}),this.opts.onAuthFailures))try{await this.opts.onAuthFailures(s)}catch(o){Mt.warn("onAuthFailures callback failed (ignored)",{err:String(o)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){Mt.warn("onTickEnd hook failed",{err:String(r)})}}};function by(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}vt();import{chmod as n_,mkdir as Os,rm as i_,stat as s_,writeFile as o_}from"node:fs/promises";import{homedir as a_}from"node:os";import{join as rf}from"node:path";qt();import{spawnSync as Ly}from"node:child_process";function jn(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Wn(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Gr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Bt(t,e){return{jsonrpc:"2.0",id:t,error:e}}_e();var Is=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)}},L={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};function Gh(t){return"method"in t&&"id"in t&&t.id!==void 0}function Hh(t){return"method"in t&&!("id"in t)}function vs(t){return!("method"in t)&&"id"in t}var Ay={AGENT_NOT_FOUND:L.AGENT_NOT_FOUND,AGENT_BUSY:L.AGENT_BUSY,AGENT_DISCONNECTED:L.AGENT_DISCONNECTED,AGENT_TIMEOUT:L.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:L.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:L.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:L.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:L.INTERNAL_ERROR,BRIDGE_INTERNAL:L.INTERNAL_ERROR,IPC_AUTH_FAILED:L.INTERNAL_ERROR,IPC_BAD_REQUEST:L.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:L.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:L.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:L.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:L.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:L.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:L.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:L.FILE_TOO_LARGE,UNSUPPORTED_MIME:L.UNSUPPORTED_MIME,UPLOAD_FAILED:L.UPLOAD_FAILED,UPSTREAM_NOT_READY:L.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:L.AGENT_DEPENDENCY_INSTALL_FAILED};function xy(t){if(t!=null)return t instanceof Error?{name:t.name,message:qn(t.message)}:typeof t=="string"?qn(t):typeof t=="object"?Py(t):t}var Oy=[[/\/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 qn(t){let e=t;for(let[r,n]of Oy)e=e.replace(r,n);return e}function Py(t){let e={};for(let[r,n]of Object.entries(t))typeof n=="string"?e[r]=qn(n):e[r]=n;return e}function Jn(t){if(t instanceof _){let e=xy(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),{code:Ay[t.code]??L.INTERNAL_ERROR,message:qn(t.message),data:r}}return{code:L.INTERNAL_ERROR,message:qn(t instanceof Error?t.message:String(t))}}function jh(t){let e=t.data,r=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",n=!!e&&typeof e.message=="string"&&!!e.message,i=n?e?.message:t.message,s=t.data;if(n&&e){let{message:o,...a}=e;s=a}return new _(r,i,{retriable:e?.retriable??!1,cause:s})}function qh(t){return`${JSON.stringify(t)}
84
+ `}var Wh=10*1024*1024,Ts=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>Wh){let i=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${i} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${Wh} bytes`)}),[]}let r=this.buffer.split(`
85
+ `);this.buffer=r.pop()??"";let n=[];for(let i of r){let s=i.replace(/\r$/,"").trim();if(s)try{n.push(JSON.parse(s))}catch(o){this.onError?.({line:s,error:o})}}return n}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(r){return this.onError?.({line:e,error:r}),[]}}};var 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",initialize:"initialize"},dk=Object.fromEntries(Object.entries(Vh).map(([t,e])=>[e,t])),Cy={"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"],"agent.pair":[],initialize:[]},Hr=class{seq=0;next(e,r){this.seq+=1;let n=Vh[e]??Dy(e),i=Cy[n]??[],s=[n,String(this.seq)];if(i.length>0){let o=i.map(c=>Jh(r?.[c]??"")),a=Ny(o).join(":");a&&s.push(a)}else r&&Object.values(r).some(o=>o)&&s.push(Object.values(r).filter(Boolean).map(o=>Jh(String(o))).join(":"));return s.join("_")}reset(){this.seq=0}};function Dy(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Jh(t){return t.replace(/[:_\s]+/g,"-")}function Ny(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Wt();function jr(t,e){let r=process.env[t];if(!r)return e;let n=Number(r);return Number.isFinite(n)&&n>0?n:e}_e();F();var Fy=jr("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),My=200,By=jr("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),Uy=jr("COZE_BRIDGE_SESSION_PROMPT_FRAME_IDLE_MS",600*1e3),Zh=500;function zy(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Zh?t:`${e.slice(0,Zh)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Kh(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),Ly("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var nt=class{constructor(e){this.opts=e;this.log=x(`downstream.${this.constructor.name}`),this.decoder=new Ts({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Hr;updateHandlers=[];agentRequestHandlers=[];exitHandlers=[];log;stopped=!1;stderrRing=[];sanitizeEnv(e){return e}async start(){if(this.child)throw new _("BRIDGE_INTERNAL","Downstream already started");let e=process.platform!=="win32",r=Je(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:{...this.sanitizeEnv(process.env),...this.opts.env},stdio:["pipe","pipe","pipe"],detached:e});this.child=r,r.stdout?.setEncoding("utf8"),r.stdout?.on("data",n=>{try{for(let i of this.decoder.push(n))this.dispatch(i)}catch(i){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(i)})}}),r.stderr?.setEncoding("utf8"),r.stderr?.on("data",n=>{let i=n.trimEnd();this.stderrRing.push(i),this.stderrRing.length>My&&this.stderrRing.shift(),this.log.debug("stderr",{text:i})}),r.stdin?.on("error",n=>{this.log.warn("child stdin error",{err:String(n)})}),r.stdout?.on("error",n=>{this.log.warn("child stdout error",{err:String(n)})}),r.stderr?.on("error",n=>{this.log.warn("child stderr error",{err:String(n)})}),r.on("exit",(n,i)=>{this.stopped=!0,(n!==0||i!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:n,signal:i,recentStderr:[...this.stderrRing]});try{for(let o of this.decoder.flush())this.dispatch(o)}catch(o){this.log.debug("decoder.flush on exit threw (ignored)",{err:String(o)})}this.failAllPending(new _("AGENT_PROTOCOL_ERROR",`agent exited (${n}/${i})`));for(let o of this.exitHandlers)o(n,i)}),r.on("error",n=>{this.log.error("child error",{err:String(n)}),this.failAllPending(new _("AGENT_SPAWN_FAILED",String(n),{cause:n}))}),this.log.info("downstream started",{command:this.opts.command,pid:r.pid,cwd:this.opts.cwd})}async stop(e){if(!this.child||this.stopped)return;this.stopped=!0,this.log.info("downstream stopping",{reason:e});let r=this.child,n=new Promise(s=>r.once("exit",()=>s()));Kh(r.pid,"SIGTERM");let i=setTimeout(()=>{r.killed||Kh(r.pid,"SIGKILL")},5e3);try{await n}finally{clearTimeout(i)}}pid(){return this.child?.pid}isAlive(){return!!this.child&&!this.stopped}getStderrTail(){return[...this.stderrRing]}initialize(e){return this.call("initialize",e)}sessionNew(e){return this.call("session/new",{mcpServers:[],...e})}sessionLoad(e){return this.call("session/load",{mcpServers:[],...e})}sessionPrompt(e,r=By,n=Uy){return this.call("session/prompt",e,r,n)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Wn("session/cancel",e))}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Gr(e,r))}catch(n){this.log.warn("respondAgentRequest write failed",{id:e,err:String(n)})}}respondAgentRequestError(e,r){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Bt(e,r))}catch(n){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(n)})}}onExit(e){this.exitHandlers.push(e)}call(e,r,n=Fy,i=0){if(!this.child||this.stopped)return Promise.reject(new _("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),o=jn(s,e,r),a=(()=>{if(typeof r!="object"||r===null)return;let d=r.sessionId;return typeof d=="string"?d:void 0})(),c=n>0&&Number.isFinite(n),l=i>0&&Number.isFinite(i);return new Promise((d,p)=>{let m={resolve:d,reject:p,timer:null,frameIdleTimer:null,armFrameIdle:null,method:e};c&&(m.timer=setTimeout(()=>{this.pending.delete(s),m.frameIdleTimer&&clearTimeout(m.frameIdleTimer),this.log.warn("downstream call timeout",{id:s,method:e,timeoutMs:n,...a?{sessionId:a}:{}}),p(new _("AGENT_TIMEOUT",`${e} timed out after ${n}ms`))},n));let f=l?()=>{m.frameIdleTimer&&clearTimeout(m.frameIdleTimer),m.frameIdleTimer=setTimeout(()=>{if(this.inflightAgentRequests.size>0){this.log.debug("frame-idle fired but agent request inflight, re-arming",{id:s,method:e,inflight:this.inflightAgentRequests.size,...a?{sessionId:a}:{}}),f?.();return}m.timer&&clearTimeout(m.timer),this.pending.delete(s),this.log.warn("frame-idle timeout, rejecting pending call",{id:s,method:e,frameIdleMs:i,...a?{sessionId:a}:{}}),p(new _("AGENT_FRAME_IDLE_TIMEOUT",`${e} no session/update for ${i}ms (no inflight agent request)`))},i)}:null;m.armFrameIdle=f,this.pending.set(s,m),f?.();try{this.writeFrame(o)}catch(u){m.timer&&clearTimeout(m.timer),m.frameIdleTimer&&clearTimeout(m.frameIdleTimer),this.pending.delete(s),p(u)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new _("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(qh(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(vs(e)){let r=e.id!==null?this.pending.get(e.id):void 0;if(!r){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),r.timer&&clearTimeout(r.timer),r.frameIdleTimer&&clearTimeout(r.frameIdleTimer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:r.method,code:e.error.code,message:e.error.message,data:e.error.data}),r.reject(jh(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:r.method}),r.reject(new _("AGENT_PROTOCOL_ERROR",`${r.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:r.method,result:zy(e.result)}),r.resolve(e.result));return}if(Hh(e)){if(e.method==="session/update"){for(let r of this.pending.values())r.armFrameIdle?.();for(let r of this.updateHandlers)try{Promise.resolve(r(e.params)).catch(n=>this.log.warn("update handler failed (async)",{err:String(n)}))}catch(n){this.log.warn("update handler threw sync, swallowed",{err:String(n)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(Gh(e)){let r=e;try{this.handleAgentRequest(r).catch(n=>this.log.error("agent request handler failed (async)",{method:r.method,err:String(n)}))}catch(n){this.log.warn("handleAgentRequest threw sync, swallowed",{method:r.method,err:String(n)})}}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(Bt(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let r of this.agentRequestHandlers)try{await r(e)}catch(n){this.log.error("agentRequestHandler threw",{method:e.method,err:String(n)});try{this.writeFrame(Bt(e.id,Jn(n)))}catch{}this.inflightAgentRequests.delete(e.id)}}failAllPending(e){for(let r of this.pending.values())r.timer&&clearTimeout(r.timer),r.frameIdleTimer&&clearTimeout(r.frameIdleTimer),r.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function $y(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(r.startsWith("CLAUDE")||r==="AI_AGENT"||r==="BAGGAGE"||(e[r]=n));return e}var Rs=class extends nt{framework="claude-code";constructor(e){let r=dn("claude-code",e.command),n=e.args??[],i={command:r,args:n,cwd:e.cwd,...e.env?{env:e.env}:{}};super(i)}sanitizeEnv(e){return $y(e)}};qt();import{mkdtempSync as Gy,rmSync as Hy}from"node:fs";import{tmpdir as jy}from"node:os";import{join as Wy}from"node:path";var ks=class extends nt{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=dn("codex",e.command),n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,s=e.isolateCodexHome?Gy(Wy(jy(),"coze-bridge-codex-home-")):void 0,o=s?{...e.env??{},CODEX_HOME:s}:e.env,a={command:r,args:i,cwd:e.cwd,...o?{env:o}:{}};super(a),this.authMethodId=e.authMethodId,this.codexHomeDir=s}async initialize(e){let r=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),r}async stop(e){if(await super.stop(e),this.codexHomeDir)try{Hy(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var qy=3e4,Wr=class extends nt{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let r=e.sessionName??"default",n=["acp","--session",`agent:${e.agentId}:${r}`];e.gatewayToken&&n.push("--token",e.gatewayToken);let i={command:e.command,args:n,cwd:e.cwd,...e.env?{env:e.env}:{}};super(i),this.agentId=e.agentId,this.sessionName=r,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},qy))}get acpSessionName(){return this.sessionName}};_e();F();de();function $a(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}qt();var qr=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((r,n)=>{this.slots.push({task:e,resolve:r,reject:n}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let r=await e.task();e.resolve(r)}catch(r){e.reject(r)}}}finally{this.running=!1}}}};var bs=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let r=this.sessionQueues.get(e);return(!r||r.isDisposed)&&(r=new qr,this.sessionQueues.set(e,r)),r}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let r=this.sessionQueues.get(e);return!!r&&!r.isDisposed}async dispose(e){this.status="stopped";let r=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let n of this.sessionQueues.values())n.dispose(r);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let r=[];for(let[,n]of this.sessions)Vn(n),n.downstream&&(r.push(n.downstream.stop(e).catch(()=>{})),n.downstream=void 0);await Promise.all(r),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function Vn(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}Wt();F();import{constants as Xh,access as Jy}from"node:fs/promises";import{delimiter as Vy,join as Zy}from"node:path";var Ut=x("framework-detector"),Qh={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},Ky=[".exe",".cmd",".bat",".ps1"],zt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Je,access:e.access??Jy}}async detect(e){let r=Qh[e],n=await this.which(r);if(!n)return Ut.debug("framework binary not found",{framework:e,bin:r}),null;let i=e==="openclaw"?["--log-level","silent"]:[],[s,o]=await Promise.all([this.probeVersion(n,i),e==="openclaw"?this.probeOpenclawDefaultAgent(n):Promise.resolve(null)]),a={path:n,version:s};return o&&(a.defaultAgent=o),a}async detectAll(){let e=await Promise.all(Object.keys(Qh).map(async n=>[n,await this.detect(n)])),r={};for(let[n,i]of e)i&&(r[n]=i);return r}async which(e){let r=this.env.pathEnv.split(Vy).filter(Boolean),n=this.env.platform==="win32"?["",...Ky]:[""];for(let i of r)for(let s of n){let o=Zy(i,e+s);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?Xh.F_OK:Xh.X_OK;return await this.env.access(e,r),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let r=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!r)return Ut.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return Ut.warn("openclaw default agent probe: non-zero exit",{path:e,code:r.code,stdoutHead:r.stdout.slice(0,200)}),null;let n=r.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!n)return Ut.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:r.stdout.slice(0,200)}),null;try{let i=JSON.parse(n[0]);if(!Array.isArray(i))return Ut.warn("openclaw default agent probe: JSON parsed but not an array",{path:e}),null;let s=i.find(o=>o?.isDefault===!0);return s?!s.id||!s.workspace?(Ut.warn("openclaw default agent probe: default agent missing id or workspace",{path:e,hasId:!!s.id,hasWorkspace:!!s.workspace}),null):{id:s.id,workspace:s.workspace}:(Ut.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:i.length}),null)}catch(i){return Ut.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(i),matchHead:n[0].slice(0,200)}),null}}async probeVersion(e,r=[]){let n=await this.runProbe(e,[...r,"--version"]);return n&&(Qy(n.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,r){return new Promise(n=>{let i="",s=!1,o,a=c=>{s||(s=!0,o&&clearTimeout(o),n(c))};try{let c=this.env.spawn(e,r,{stdio:["ignore","pipe","pipe"]});o=setTimeout(()=>{c.kill("SIGKILL"),a(null)},15e3),c.stdout?.on("data",l=>{i+=l.toString("utf8")}),c.on("error",()=>a(null)),c.on("close",l=>a({code:l,stdout:i}))}catch{a(null)}})}},Xy=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Qy(t){return t.replace(Xy,"")}import{spawn as Yy}from"node:child_process";import{homedir as e_}from"node:os";import{join as t_}from"node:path";_e();Ti();F();async function tf(){let t=t_(e_(),".openclaw/openclaw.json");return(await Er(t))?.gateway?.auth?.token??""}var Yh=x("openclaw.config"),r_=[0,5e3,5e3],ef="models.providers.",As="agents.defaults.models",xs=class{command;env;retryDelaysMs;queue=new qr;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??r_}async withRetry(e,r){let n;for(let i=0;i<this.retryDelaysMs.length;i++){let s=this.retryDelaysMs[i]??0;s>0&&await new Promise(o=>setTimeout(o,s));try{return await r()}catch(o){n=o,Yh.warn("openclaw cli failed, will retry",{label:e,attempt:i+1,err:String(o)})}}throw new _("AGENT_SPAWN_FAILED",`openclaw cli ${e} failed after ${this.retryDelaysMs.length} attempts: ${n?.message??"unknown"}`)}runCli(e){return new Promise((r,n)=>{let i=Yy(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",n),i.on("close",o=>{o===0?r():n(new Error(`exit ${o}: ${s.trim().slice(0,500)}`))})})}async runCliTolerant(e,r){try{await this.runCli(e)}catch(n){let i=String(n);if(r.some(s=>i.includes(s)))return;throw n}}async bestEffortUnset(e,r){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",r])))}catch(n){Yh.warn(`${e} failed (best-effort)`,{configPath:r,err:String(n)})}}ensureProvider(e,r){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${ef}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${ef}${e}`)}addModelToAllowlist(e,r){let n={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${As}[${e}]`,()=>this.runCli(["config","set",As,JSON.stringify(n),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${As}[${e}]`,`${As}.${e}`)}ensureAgent(e,r,n){let i=["agents","add",e,"--workspace",r,"--non-interactive"];return n&&i.push("--model",n),this.queue.enqueue(()=>this.withRetry(`agents add ${e}`,()=>this.runCliTolerant(i,["already exists","already registered"])))}restartGateway(){return this.queue.enqueue(()=>this.withRetry("gateway restart",()=>this.runCli(["gateway","restart"])))}deleteAgent(e){return this.queue.enqueue(()=>this.withRetry(`agents delete ${e}`,()=>this.runCliTolerant(["agents","delete",e,"--force"],["not found","does not exist"])))}};var V=x("agent-manager"),c_=(t,e,r,n,i,s,o,a,c)=>{switch(t){case"claude-code":{let l={...i?{...Ah(i),...Ph(i,o,a)}:{},...c??{},IS_SANDBOX:"1"};return new Rs({cwd:r,env:l})}case"codex":{let d=[...i?[...xh(i),...Dh(i,o,a)]:[],"-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"'],p={...i?Oh(i):{},...c??{}},m=!!i;return new ks({cwd:r,...d.length>0?{extraArgs:d}:{},...Object.keys(p).length>0?{env:p}:{},...m?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Wr({command:e,cwd:r,agentId:n,...s?{sessionName:$a(s)}:{}})}};function Ga(t){return t==="claude-code"||t==="codex"}function l_(t){let e=[],r=Object.keys(t).sort();for(let n of r){let i=t[n];i!==void 0&&(d_(i)||e.push(`${n}=${i}`))}return e.length===0?"":`${e.join(`
86
86
  `)}
87
- `}function ly(t){if(t.includes(`
88
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var dy={path:"",version:"cloud-deployed"},hy={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},fy=6e4,Ps=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??ay,this.createTimeoutMs=e.createTimeoutMs??fy,this.detectorFactory=e.detectorFactory??(()=>new zt),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Os({command:r})),this.openclawConfigDir=e.openclawConfigDir??tf(oy(),".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 y("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=>{V.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=tf(e,".env");if(await iy(r).then(s=>s.isFile()).catch(()=>!1)){V.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}await xs(e,{recursive:!0});let i=cy(process.env);if(await sy(r,i,"utf8"),process.platform!=="win32")try{await ry(r,384)}catch(s){V.warn("chmod ~/.openclaw/.env to 0600 failed (ignored)",{err:String(s)})}V.info("openclaw .env bootstrapped",{envFile:r,bytes:i.length}),await this.getOpenclawConfig().restartGateway(),V.info("openclaw gateway restarted after env bootstrap")}async createAgent(e){if(!e.agentId)throw new y("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new y("IPC_BAD_REQUEST","framework required");let r=Un(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let n=this.registry.get(e.agentId);if(n){if(n.framework!==e.framework)throw new y("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${n.framework})`);if(n.status==="error")V.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await n.dispose("rebuild after error").catch(u=>V.warn("dispose stale agent failed (ignored)",{err:String(u)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==n.patToken){V.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),n.setPatToken(e.patToken);let u=await he(e.agentId,this.paths).catch(()=>null);u&&(u.patToken=e.patToken,await ve(u,this.paths))}if(n.deployType==="cloud"&&e.modelInfo){V.info("updating agent modelInfo on re-create",{agentId:e.agentId}),n.setModelInfo(e.modelInfo);let u=await he(e.agentId,this.paths).catch(()=>null);u&&(u.modelInfo=e.modelInfo,await ve(u,this.paths))}return V.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:n.agentId,workspace:n.workspace,framework:n.framework}}}if(!r&&!this.config.frameworksCache?.[e.framework])throw new y("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let s=lt(e.agentId,this.paths),o=Un(e._meta),a=e.framework==="openclaw"&&o==="local",c=a?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0,l=e.workspace??c??s.workspace,d=new AbortController,p=setTimeout(()=>d.abort(new y("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),m,f=!1;try{r&&Ga(e.framework)&&await yr(e.framework,d.signal);let u=()=>{if(d.signal.aborted)throw d.signal.reason instanceof Error?d.signal.reason:new y("AGENT_TIMEOUT","_agent/create aborted")};await xs(s.root,{recursive:!0}),await xs(l,{recursive:!0}),await xs(s.logs,{recursive:!0}),u(),a||await Sr(l,e.framework,e.cozeIdentity),e.framework==="claude-code"&&await Il(l),u();let g=await he(e.agentId,this.paths).catch(()=>null),w=Rh({model:e.model??g?.model}),E=wh(e._meta)??g?.accountId,v=e.patToken??g?.patToken,h=o==="cloud"?e.modelInfo??g?.modelInfo:void 0;if(m=new bs({agentId:e.agentId,framework:e.framework,workspace:l,model:w.model??Ye,deployType:o,...E?{accountId:E}:{},...v?{patToken:v}:{},...h?{modelInfo:h}:{}}),m.status="ok",g?.sessions){for(let[R,I]of Object.entries(g.sessions))m.sessions.set(R,{acpSessionId:I.acpSessionId,modelToken:I.modelToken,tokenGeneratedAt:I.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let k=Object.keys(g.sessions).length;k>0&&V.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:k})}this.registry.register(m),f=!0;let _={agentId:e.agentId,framework:e.framework,workspace:l,cozeIdentity:e.cozeIdentity,createdAt:g?.createdAt??Date.now(),sessions:g?.sessions??{},model:w.model};o==="cloud"&&(_.deployType="cloud"),E&&(_.accountId=E),v&&(_.patToken=v),h&&(_.modelInfo=h),g?.skills&&(_.skills=g.skills),g?.agentName&&(_.agentName=g.agentName),g?.description&&(_.description=g.description),e.framework==="openclaw"&&o==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,l)):V.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let S=e.initialSkills??[];if(S.length>0){let k=[..._.skills??[]],R=new Map(k.map((A,P)=>[A.skillId,P])),I=await Promise.allSettled(S.map(A=>Ua({agentId:e.agentId,workspace:l,framework:e.framework,skill:A}))),T=0;for(let[A,P]of I.entries()){let G=S[A];G&&(P.status==="fulfilled"?(za(k,R,P.value),T++):V.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(P.reason)}))}T>0&&(_.skills=k,V.info("initialSkills installed",{agentId:e.agentId,installed:T,requested:S.length}))}return await ve(_,this.paths),V.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:o}),{ok:!0,agentId:e.agentId,workspace:l,framework:e.framework}}catch(u){throw V.error("agent create failed, rolling back",{agentId:e.agentId,err:String(u)}),f&&m&&(await m.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await ny(s.root,{recursive:!0,force:!0}).catch(g=>V.warn("rm agent dir failed (ignored)",{err:String(g)})),u instanceof y?u:new y("AGENT_SPAWN_FAILED",String(u),{cause:u})}finally{clearTimeout(p)}}async spawnSessionDownstream(e,r,n,i,s){let a=this.config.frameworksCache?.[e.framework];if(!a)if(e.deployType==="cloud"&&Ga(e.framework))a=dy;else throw new y("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);if(Ga(e.framework)&&!ln(e.framework)){let d=yo(e.framework);V.info("spawn: ensuring acp wrapper installed",{agentId:e.agentId,framework:e.framework,reusingInFlight:!!d}),await yr(e.framework)}let c=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,l;e.framework==="openclaw"?l=await this.buildOpenclawDownstream({session:e,modelConfig:c,cloudSessionId:n,cozeEnv:i,mockScenario:s,command:a.path}):l=this.factory(e.framework,a.path,e.workspace,e.agentId,c,n,i,s,this.buildBinShimPathEnv());try{return await l.start(),await l.initialize(hy),l}catch(d){let p=l instanceof rt?l.getStderrTail():[];throw p.length>0&&V.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:d instanceof y?d.code:"unknown",recentStderr:p}),await l.stop("spawnSessionDownstream failed").catch(()=>{}),d instanceof y?new y(d.code,d.message,{retriable:d.retriable,cause:d}):new y("AGENT_SPAWN_FAILED",d instanceof Error?d.message:String(d),{cause:d})}}async buildOpenclawDownstream(e){let{session:r,modelConfig:n,cloudSessionId:i,cozeEnv:s,mockScenario:o,command:a}=e,c=$a(i);if(r.deployType==="local"){let m=this.config.frameworksCache?.openclaw?.defaultAgent;if(!m?.id||!m.workspace){V.warn("openclaw default agent stale or missing, attempting lazy re-detect");let u=await this.detectorFactory().detect("openclaw");if(u?.defaultAgent?.id&&u?.defaultAgent?.workspace)V.info("openclaw lazy re-detect success",{agentId:u.defaultAgent.id,workspace:u.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=u,m=u.defaultAgent;else throw new y("AGENT_SPAWN_FAILED","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent")}return new Wr({command:a,cwd:m.workspace,agentId:m.id,sessionName:c})}let l=await ef(),d=n?Ph(n,s,o):null,p;if(d){let m=Ca(i),u=d.models[0]?.id??Ye,g=`${m}/${u}`;if(!this.ensuredProviders.has(g)){let w=this.getOpenclawConfig();await w.ensureProvider(m,d),await w.addModelToAllowlist(g),this.ensuredProviders.add(g)}p=g}return new Wr({command:a,cwd:r.workspace,agentId:r.agentId,sessionName:c,...l?{gatewayToken:l}:{},...p?{slashModelOnStart:p}:{}})}async openclawRepair(e,r){let n=this.getOpenclawConfig();await n.deleteAgent(e),await n.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let n of e.sessions.keys()){let i=Ca(n),s=`${i}/${e.model}`,o=!0;try{await r.removeProvider(i)}catch(a){o=!1,V.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:i,err:String(a)})}try{await r.removeModelFromAllowlist(s)}catch(a){o=!1,V.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:s,err:String(a)})}o&&this.ensuredProviders.delete(s)}}};import{randomUUID as af}from"node:crypto";import{promises as Ey}from"node:fs";import{basename as cf}from"node:path";ye();F();import{promises as py}from"node:fs";import{basename as gy}from"node:path";var rf=O("file-upload"),my="/api/coze_claw/file/agent_upload",wy=6e4;async function nf(t,e={}){let n=`${_s(Es(e.handshakeBase))}${my}`,i=e.timeoutMs??wy,s=await py.readFile(t.path),o=new FormData;o.append("agent_id",t.agentId),o.append("session_id",t.sessionId),o.append("file_name",t.name),o.append("file_content",new Blob([s],{type:t.mimeType}),t.name);let a={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Ur(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},c=new AbortController,l=setTimeout(()=>c.abort(),i);rf.info("file upload start",{url:n,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let d=await fetch(n,{method:"POST",headers:a,body:o,signal:c.signal}),p=d.headers.get("x-tt-logid")??"";if(!d.ok){let u=await d.text().catch(()=>"");throw new y("UPLOAD_FAILED",`upload HTTP ${d.status} logid=${p}: ${u.slice(0,200)}`)}let m=await d.json();if(m.code!==void 0&&m.code!==0)throw new y("UPLOAD_FAILED",`upload code=${m.code} msg=${m.msg??"-"} logid=${p}`);let f=m.data?.file?.file_url;if(!f)throw new y("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${p}: ${JSON.stringify(m).slice(0,200)}`);return rf.info("file upload ok",{uri:f,logid:p}),{uri:f}}catch(d){throw d instanceof y?d:d.name==="AbortError"?new y("UPLOAD_FAILED",`upload timeout (${i}ms) for ${gy(t.path)}`):new y("UPLOAD_FAILED",String(d),{cause:d})}finally{clearTimeout(l)}}ye();F();import{extname as _y}from"node:path";var yy={".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 sf(t){let e=_y(t).toLowerCase();return yy[e]??"application/octet-stream"}de();var Cs=O("agent-send"),of=50*1024*1024;function lf(t,e,r){let n=t.get(e);if(!n)throw new y("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new y("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let i=n.sessions.get(r);if(!i)throw new y("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:n,runtime:i}}async function df(t,e,r,n,i,s){let a;for(let c=0;c<=2;c++)try{await t.core.sendAgentFileUpdate(e,r,n,i);return}catch(l){a=l,c<2&&(Cs.warn("sendAgentFileUpdate failed, retrying",{attempt:c+1,err:String(l)}),await new Promise(d=>setTimeout(d,5e3)))}throw new y("UPSTREAM_NOT_READY",`${s} after 3 attempts: ${String(a)}`,{cause:a})}async function hf(t,e){let{session:r,runtime:n}=lf(e.core,t.agentId,t.sessionId);if(!await hn(t.path,r.workspace))throw new y("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let i=await Ey.stat(t.path).catch(()=>null);if(!i||!i.isFile())throw new y("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(i.size>of)throw new y("FILE_TOO_LARGE",`${i.size} bytes > limit ${of}`);let s=await sf(t.path);if(t.kind==="image"&&!s.startsWith("image/"))throw new y("UNSUPPORTED_MIME",`kind=image but mime=${s}`);if(!e.core.upstream.isConnected())throw new y("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??cf(t.path),a;try{a=await nf({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:s,name:o,sizeBytes:i.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(l){throw Cs.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:i.size,mime:s,code:l instanceof y?l.code:"UNKNOWN",message:l instanceof Error?l.message:String(l)}),l}let c={sessionUpdate:"agent_file",messageId:af(),content:{type:t.kind==="image"?"image":"resource",uri:a.uri,mimeType:s,name:o,sizeBytes:i.size,...a.fileId!==void 0?{fileId:a.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await df(e,r,n,t.sessionId,c,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Cs.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:o,bytes:i.size,mime:s,uri:a.uri}),{ok:!0,uri:a.uri,bytes:i.size,mimeType:s,...a.fileId!==void 0?{fileId:a.fileId}:{}}}async function ff(t,e){let{session:r,runtime:n}=lf(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new y("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new y("UPSTREAM_NOT_READY","cloud WS not connected");let i=t.name??cf(t.path),s={sessionUpdate:"group_file",messageId:af(),content:{uri:t.path,name:i,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await df(e,r,n,t.sessionId,s,"agent group file sendAgentFileUpdate failed"),Cs.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:i,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function uf(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number),i=Math.max(r.length,n.length);for(let s=0;s<i;s++){let o=r[s]??0,a=n[s]??0;if(o<a)return!0;if(o>a)return!1}return!1}Wt();mr();F();var nt=O("coze-cli-installer"),pf="@coze/cli@latest",Sy="coze",gf="0.1.8",Iy=5e3,vy=5e3,Ty=9e4,mf=1e4,Zn=null,Ds=!1;async function Ha(t,e={}){if(Ds)return;if(Zn)return Zn;let r=e.exec??yi;return Zn=(async()=>{try{let n=await Ry(Sy,r),i=!1;if(n){let o=await ky(r);if(o===void 0)nt.warn("coze-cli found but version unparseable, fall through to full install",{path:n});else if(uf(o,gf))nt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:n,version:o,min:gf}),i=!0;else{nt.info("coze-cli already on PATH with sufficient version, skip",{path:n,version:o}),Ds=!0;return}}let s=i?"upgrade-only":"full";nt.info("coze-cli install start",{package:pf,mode:s});try{await r("npm",["i","-g","--prefer-online",pf],{timeout:Ty,maxBuffer:10*1024*1024}),nt.info("coze-cli install ok")}catch(o){nt.warn("coze-cli install failed (skip subsequent steps)",{err:String(o)});return}if(i){Ds=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:mf}),nt.info("coze config set xTTEnv ok",{env:t.env})}catch(o){nt.warn("coze config set failed (continue to auth login)",{err:String(o)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:mf}),nt.info("coze auth login ok")}catch(o){nt.warn("coze auth login failed",{err:String(o)});return}Ds=!0}finally{Zn=null}})(),Zn}async function Ry(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:n}=await e(r,[t],{timeout:Iy});return Ii(n)}catch{return}}async function ky(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:vy});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Ti();de();var by=10*6e4;function wf(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?by:e}function Ns(t){return Er(t??M().configFile)}function Jr(t,e){return vi(e??M().configFile,t)}import{randomBytes as Wy}from"node:crypto";import{createReadStream as Ay}from"node:fs";import{mkdir as Oy,readFile as xy,realpath as Py,stat as Cy,writeFile as Dy}from"node:fs/promises";import{basename as Ny,dirname as ja,join as Ly,relative as Fy,resolve as _f,sep as My}from"node:path";import{createInterface as By}from"node:readline";ye();F();var Ef=O("fs-rpc"),Kn=jr("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Sf(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Kn)throw new y("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Kn} bytes`);let n=await vf(t.path,e);return await Oy(ja(n),{recursive:!0}),await Dy(n,t.content,"utf8"),Ef.info("fs/write_text_file ok",{path:n,size:t.content.length}),null}async function If(t,e){let r=await vf(t.path,e),n=await Cy(r),i=typeof t.line=="number"||typeof t.limit=="number";if(n.size>Kn&&!i)throw new y("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${n.size} bytes > ${Kn} bytes`);let s;if(i&&n.size>Kn)s=await Uy(r,t.line??1,t.limit);else{let o=await xy(r,"utf8");if(i){let a=o.split(`
87
+ `}function d_(t){if(t.includes(`
88
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var h_={path:"",version:"cloud-deployed"},f_={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},u_=6e4,Ps=class{paths;config;registry;factory;createTimeoutMs;openclawConfigCache;ensuredProviders=new Set;detectorFactory;openclawEnvBootstrapPromise;openclawConfigFactory;openclawConfigDir;constructor(e){this.paths=e.paths,this.config=e.config,this.registry=e.registry,this.factory=e.downstreamFactory??c_,this.createTimeoutMs=e.createTimeoutMs??u_,this.detectorFactory=e.detectorFactory??(()=>new zt),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new xs({command:r})),this.openclawConfigDir=e.openclawConfigDir??rf(a_(),".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 _("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=>{V.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,r=rf(e,".env");if(await s_(r).then(s=>s.isFile()).catch(()=>!1)){V.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}await Os(e,{recursive:!0});let i=l_(process.env);if(await o_(r,i,"utf8"),process.platform!=="win32")try{await n_(r,384)}catch(s){V.warn("chmod ~/.openclaw/.env to 0600 failed (ignored)",{err:String(s)})}V.info("openclaw .env bootstrapped",{envFile:r,bytes:i.length}),await this.getOpenclawConfig().restartGateway(),V.info("openclaw gateway restarted after env bootstrap")}async createAgent(e){if(!e.agentId)throw new _("IPC_BAD_REQUEST","agentId required");if(!e.framework)throw new _("IPC_BAD_REQUEST","framework required");let r=Un(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let n=this.registry.get(e.agentId);if(n){if(n.framework!==e.framework)throw new _("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${n.framework})`);if(n.status==="error")V.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await n.dispose("rebuild after error").catch(u=>V.warn("dispose stale agent failed (ignored)",{err:String(u)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==n.patToken){V.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),n.setPatToken(e.patToken);let u=await he(e.agentId,this.paths).catch(()=>null);u&&(u.patToken=e.patToken,await ve(u,this.paths))}if(n.deployType==="cloud"&&e.modelInfo){V.info("updating agent modelInfo on re-create",{agentId:e.agentId}),n.setModelInfo(e.modelInfo);let u=await he(e.agentId,this.paths).catch(()=>null);u&&(u.modelInfo=e.modelInfo,await ve(u,this.paths))}return V.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:n.agentId,workspace:n.workspace,framework:n.framework}}}if(!r&&!this.config.frameworksCache?.[e.framework])throw new _("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine; rerun daemon to refresh frameworks_cache`);let s=dt(e.agentId,this.paths),o=Un(e._meta),a=e.framework==="openclaw"&&o==="local",c=a?this.config.frameworksCache?.openclaw?.defaultAgent?.workspace:void 0,l=e.workspace??c??s.workspace,d=new AbortController,p=setTimeout(()=>d.abort(new _("AGENT_TIMEOUT",`_agent/create timed out after ${this.createTimeoutMs}ms`)),this.createTimeoutMs),m,f=!1;try{r&&Ga(e.framework)&&await _r(e.framework,d.signal);let u=()=>{if(d.signal.aborted)throw d.signal.reason instanceof Error?d.signal.reason:new _("AGENT_TIMEOUT","_agent/create aborted")};await Os(s.root,{recursive:!0}),await Os(l,{recursive:!0}),await Os(s.logs,{recursive:!0}),u(),a||await Sr(l,e.framework,e.cozeIdentity),e.framework==="claude-code"&&await Il(l),u();let g=await he(e.agentId,this.paths).catch(()=>null),w=kh({model:e.model??g?.model}),E=wh(e._meta)??g?.accountId,v=e.patToken??g?.patToken,h=o==="cloud"?e.modelInfo??g?.modelInfo:void 0;if(m=new bs({agentId:e.agentId,framework:e.framework,workspace:l,model:w.model??et,deployType:o,...E?{accountId:E}:{},...v?{patToken:v}:{},...h?{modelInfo:h}:{}}),m.status="ok",g?.sessions){for(let[R,I]of Object.entries(g.sessions))m.sessions.set(R,{acpSessionId:I.acpSessionId,modelToken:I.modelToken,tokenGeneratedAt:I.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let k=Object.keys(g.sessions).length;k>0&&V.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:k})}this.registry.register(m),f=!0;let y={agentId:e.agentId,framework:e.framework,workspace:l,cozeIdentity:e.cozeIdentity,createdAt:g?.createdAt??Date.now(),sessions:g?.sessions??{},model:w.model};o==="cloud"&&(y.deployType="cloud"),E&&(y.accountId=E),v&&(y.patToken=v),h&&(y.modelInfo=h),g?.skills&&(y.skills=g.skills),g?.agentName&&(y.agentName=g.agentName),g?.description&&(y.description=g.description),e.framework==="openclaw"&&o==="cloud"&&(this.config.frameworksCache?.openclaw?.path?(await this.bootstrapOpenclawEnvIfNeeded(),await this.getOpenclawConfig().ensureAgent(e.agentId,l)):V.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let S=e.initialSkills??[];if(S.length>0){let k=[...y.skills??[]],R=new Map(k.map((A,P)=>[A.skillId,P])),I=await Promise.allSettled(S.map(A=>Ua({agentId:e.agentId,workspace:l,framework:e.framework,skill:A}))),T=0;for(let[A,P]of I.entries()){let G=S[A];G&&(P.status==="fulfilled"?(za(k,R,P.value),T++):V.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:G.skillId,skillName:G.skillName,err:String(P.reason)}))}T>0&&(y.skills=k,V.info("initialSkills installed",{agentId:e.agentId,installed:T,requested:S.length}))}return await ve(y,this.paths),V.info("agent created (no spawn, lazy on first prompt)",{agentId:e.agentId,framework:e.framework,deployType:o}),{ok:!0,agentId:e.agentId,workspace:l,framework:e.framework}}catch(u){throw V.error("agent create failed, rolling back",{agentId:e.agentId,err:String(u)}),f&&m&&(await m.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await i_(s.root,{recursive:!0,force:!0}).catch(g=>V.warn("rm agent dir failed (ignored)",{err:String(g)})),u instanceof _?u:new _("AGENT_SPAWN_FAILED",String(u),{cause:u})}finally{clearTimeout(p)}}async spawnSessionDownstream(e,r,n,i,s){let a=this.config.frameworksCache?.[e.framework];if(!a)if(e.deployType==="cloud"&&Ga(e.framework))a=h_;else throw new _("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);if(Ga(e.framework)&&!ln(e.framework)){let d=_o(e.framework);V.info("spawn: ensuring acp wrapper installed",{agentId:e.agentId,framework:e.framework,reusingInFlight:!!d}),await _r(e.framework)}let c=e.deployType==="cloud"?{model:e.model,modelToken:r,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,l;e.framework==="openclaw"?l=await this.buildOpenclawDownstream({session:e,modelConfig:c,cloudSessionId:n,cozeEnv:i,mockScenario:s,command:a.path}):l=this.factory(e.framework,a.path,e.workspace,e.agentId,c,n,i,s,this.buildBinShimPathEnv());try{return await l.start(),await l.initialize(f_),l}catch(d){let p=l instanceof nt?l.getStderrTail():[];throw p.length>0&&V.warn("spawnSessionDownstream failed, recent stderr (D94)",{agentId:e.agentId,framework:e.framework,method:d instanceof _?d.code:"unknown",recentStderr:p}),await l.stop("spawnSessionDownstream failed").catch(()=>{}),d instanceof _?new _(d.code,d.message,{retriable:d.retriable,cause:d}):new _("AGENT_SPAWN_FAILED",d instanceof Error?d.message:String(d),{cause:d})}}async buildOpenclawDownstream(e){let{session:r,modelConfig:n,cloudSessionId:i,cozeEnv:s,mockScenario:o,command:a}=e,c=$a(i);if(r.deployType==="local"){let m=this.config.frameworksCache?.openclaw?.defaultAgent;if(!m?.id||!m.workspace){V.warn("openclaw default agent stale or missing, attempting lazy re-detect");let u=await this.detectorFactory().detect("openclaw");if(u?.defaultAgent?.id&&u?.defaultAgent?.workspace)V.info("openclaw lazy re-detect success",{agentId:u.defaultAgent.id,workspace:u.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=u,m=u.defaultAgent;else throw new _("AGENT_SPAWN_FAILED","openclaw default agent \u672A\u63A2\u6D4B\u5230; \u8BF7\u5148\u8DD1 `openclaw setup` \u6216 `openclaw agents add` \u521B\u5EFA\u9ED8\u8BA4 agent")}return new Wr({command:a,cwd:m.workspace,agentId:m.id,sessionName:c})}let l=await tf(),d=n?Ch(n,s,o):null,p;if(d){let m=Ca(i),u=d.models[0]?.id??et,g=`${m}/${u}`;if(!this.ensuredProviders.has(g)){let w=this.getOpenclawConfig();await w.ensureProvider(m,d),await w.addModelToAllowlist(g),this.ensuredProviders.add(g)}p=g}return new Wr({command:a,cwd:r.workspace,agentId:r.agentId,sessionName:c,...l?{gatewayToken:l}:{},...p?{slashModelOnStart:p}:{}})}async openclawRepair(e,r){let n=this.getOpenclawConfig();await n.deleteAgent(e),await n.ensureAgent(e,r)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let r=this.openclawConfigCache;for(let n of e.sessions.keys()){let i=Ca(n),s=`${i}/${e.model}`,o=!0;try{await r.removeProvider(i)}catch(a){o=!1,V.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:i,err:String(a)})}try{await r.removeModelFromAllowlist(s)}catch(a){o=!1,V.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:s,err:String(a)})}o&&this.ensuredProviders.delete(s)}}};import{randomUUID as cf}from"node:crypto";import{promises as S_}from"node:fs";import{basename as lf}from"node:path";_e();F();import{promises as g_}from"node:fs";import{basename as m_}from"node:path";var nf=x("file-upload"),w_="/api/coze_claw/file/agent_upload",y_=6e4;async function sf(t,e={}){let n=`${ys(Es(e.handshakeBase))}${w_}`,i=e.timeoutMs??y_,s=await g_.readFile(t.path),o=new FormData;o.append("agent_id",t.agentId),o.append("session_id",t.sessionId),o.append("file_name",t.name),o.append("file_content",new Blob([s],{type:t.mimeType}),t.name);let a={Authorization:`Bearer ${t.patToken}`,Accept:"application/json","x-coze-version":"3.0",...Ur(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},c=new AbortController,l=setTimeout(()=>c.abort(),i);nf.info("file upload start",{url:n,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let d=await fetch(n,{method:"POST",headers:a,body:o,signal:c.signal}),p=d.headers.get("x-tt-logid")??"";if(!d.ok){let u=await d.text().catch(()=>"");throw new _("UPLOAD_FAILED",`upload HTTP ${d.status} logid=${p}: ${u.slice(0,200)}`)}let m=await d.json();if(m.code!==void 0&&m.code!==0)throw new _("UPLOAD_FAILED",`upload code=${m.code} msg=${m.msg??"-"} logid=${p}`);let f=m.data?.file?.file_url;if(!f)throw new _("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${p}: ${JSON.stringify(m).slice(0,200)}`);return nf.info("file upload ok",{uri:f,logid:p}),{uri:f}}catch(d){throw d instanceof _?d:d.name==="AbortError"?new _("UPLOAD_FAILED",`upload timeout (${i}ms) for ${m_(t.path)}`):new _("UPLOAD_FAILED",String(d),{cause:d})}finally{clearTimeout(l)}}_e();F();import{extname as __}from"node:path";var E_={".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 of(t){let e=__(t).toLowerCase();return E_[e]??"application/octet-stream"}de();var Cs=x("agent-send"),af=50*1024*1024;function df(t,e,r){let n=t.get(e);if(!n)throw new _("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new _("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let i=n.sessions.get(r);if(!i)throw new _("AGENT_NOT_FOUND",`session=${r} not active in agent=${e}`);return{session:n,runtime:i}}async function hf(t,e,r,n,i,s){let a;for(let c=0;c<=2;c++)try{await t.core.sendAgentFileUpdate(e,r,n,i);return}catch(l){a=l,c<2&&(Cs.warn("sendAgentFileUpdate failed, retrying",{attempt:c+1,err:String(l)}),await new Promise(d=>setTimeout(d,5e3)))}throw new _("UPSTREAM_NOT_READY",`${s} after 3 attempts: ${String(a)}`,{cause:a})}async function ff(t,e){let{session:r,runtime:n}=df(e.core,t.agentId,t.sessionId);if(!await hn(t.path,r.workspace))throw new _("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let i=await S_.stat(t.path).catch(()=>null);if(!i||!i.isFile())throw new _("IPC_BAD_REQUEST",`path is not a regular file: ${t.path}`);if(i.size>af)throw new _("FILE_TOO_LARGE",`${i.size} bytes > limit ${af}`);let s=await of(t.path);if(t.kind==="image"&&!s.startsWith("image/"))throw new _("UNSUPPORTED_MIME",`kind=image but mime=${s}`);if(!e.core.upstream.isConnected())throw new _("UPSTREAM_NOT_READY","cloud WS not connected");let o=t.name??lf(t.path),a;try{a=await sf({patToken:r.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:s,name:o,sizeBytes:i.size,...r.accountId?{accountId:r.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(l){throw Cs.warn("agent file upload failed",{agentId:t.agentId,sessionId:t.sessionId,path:t.path,sizeBytes:i.size,mime:s,code:l instanceof _?l.code:"UNKNOWN",message:l instanceof Error?l.message:String(l)}),l}let c={sessionUpdate:"agent_file",messageId:cf(),content:{type:t.kind==="image"?"image":"resource",uri:a.uri,mimeType:s,name:o,sizeBytes:i.size,...a.fileId!==void 0?{fileId:a.fileId}:{},...t.caption!==void 0?{caption:t.caption}:{}}};return await hf(e,r,n,t.sessionId,c,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Cs.info("agent file sent",{agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,name:o,bytes:i.size,mime:s,uri:a.uri}),{ok:!0,uri:a.uri,bytes:i.size,mimeType:s,...a.fileId!==void 0?{fileId:a.fileId}:{}}}async function uf(t,e){let{session:r,runtime:n}=df(e.core,t.agentId,t.sessionId);if(!t.mimeType)throw new _("IPC_BAD_REQUEST","group-file requires mimeType");if(!e.core.upstream.isConnected())throw new _("UPSTREAM_NOT_READY","cloud WS not connected");let i=t.name??lf(t.path),s={sessionUpdate:"group_file",messageId:cf(),content:{uri:t.path,name:i,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await hf(e,r,n,t.sessionId,s,"agent group file sendAgentFileUpdate failed"),Cs.info("agent group file sent",{agentId:t.agentId,sessionId:t.sessionId,uri:t.path,name:i,mime:t.mimeType}),{ok:!0,uri:t.path,bytes:0,mimeType:t.mimeType}}function pf(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number),i=Math.max(r.length,n.length);for(let s=0;s<i;s++){let o=r[s]??0,a=n[s]??0;if(o<a)return!0;if(o>a)return!1}return!1}qt();Wt();F();var it=x("coze-cli-installer"),gf="@coze/cli@latest",I_="coze",mf="0.1.8",v_=5e3,T_=5e3,R_=9e4,wf=1e4,Zn=null,Ds=!1;async function Ha(t,e={}){if(Ds)return;if(Zn)return Zn;let r=e.exec??_i;return Zn=(async()=>{try{let n=await k_(I_,r),i=!1;if(n){let o=await b_(r);if(o===void 0)it.warn("coze-cli found but version unparseable, fall through to full install",{path:n});else if(pf(o,mf))it.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:n,version:o,min:mf}),i=!0;else{it.info("coze-cli already on PATH with sufficient version, skip",{path:n,version:o}),Ds=!0;return}}let s=i?"upgrade-only":"full";it.info("coze-cli install start",{package:gf,mode:s});try{await r("npm",["i","-g","--prefer-online",gf],{timeout:R_,maxBuffer:10*1024*1024}),it.info("coze-cli install ok")}catch(o){it.warn("coze-cli install failed (skip subsequent steps)",{err:String(o)});return}if(i){Ds=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:wf}),it.info("coze config set xTTEnv ok",{env:t.env})}catch(o){it.warn("coze config set failed (continue to auth login)",{err:String(o)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:wf}),it.info("coze auth login ok")}catch(o){it.warn("coze auth login failed",{err:String(o)});return}Ds=!0}finally{Zn=null}})(),Zn}async function k_(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:n}=await e(r,[t],{timeout:v_});return Ii(n)}catch{return}}async function b_(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:T_});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Ti();de();var A_=10*6e4;function yf(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?A_:e}function Ns(t){return Er(t??M().configFile)}function Jr(t,e){return vi(e??M().configFile,t)}import{randomBytes as q_}from"node:crypto";import{createReadStream as x_}from"node:fs";import{mkdir as O_,readFile as P_,realpath as C_,stat as D_,writeFile as N_}from"node:fs/promises";import{basename as L_,dirname as ja,join as F_,relative as M_,resolve as _f,sep as B_}from"node:path";import{createInterface as U_}from"node:readline";_e();F();var Sf=x("fs-rpc"),Kn=jr("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function If(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>Kn)throw new _("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${Kn} bytes`);let n=await Tf(t.path,e);return await O_(ja(n),{recursive:!0}),await N_(n,t.content,"utf8"),Sf.info("fs/write_text_file ok",{path:n,size:t.content.length}),null}async function vf(t,e){let r=await Tf(t.path,e),n=await D_(r),i=typeof t.line=="number"||typeof t.limit=="number";if(n.size>Kn&&!i)throw new _("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${n.size} bytes > ${Kn} bytes`);let s;if(i&&n.size>Kn)s=await z_(r,t.line??1,t.limit);else{let o=await P_(r,"utf8");if(i){let a=o.split(`
89
89
  `),c=Math.max(0,(t.line??1)-1),l=typeof t.limit=="number"?c+t.limit:void 0;s=a.slice(c,l).join(`
90
- `)}else s=o}return Ef.info("fs/read_text_file ok",{path:r,size:s.length}),{content:s}}async function Uy(t,e,r){let n=By({input:Ay(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),i=Math.max(0,e-1),s=typeof r=="number"?i+r:Number.POSITIVE_INFINITY,o=[],a=0;try{for await(let c of n)if(a>=i&&a<s&&o.push(c),a++,a>=s)break}finally{n.close()}return o.join(`
91
- `)}async function vf(t,e){if(typeof t!="string"||t.length===0)throw new y("IPC_BAD_REQUEST","path must be a non-empty string");let[r,n]=await Promise.all([yf(_f(e)),yf(_f(t))]),i=Fy(r,n);if(i.startsWith("..")||i===".."||i.startsWith(`..${My}`))throw new y("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return n}async function yf(t){let e=[],r=t;for(;r!==ja(r);)try{let n=await Py(r);return e.length?Ly(n,...e.reverse()):n}catch{e.push(Ny(r)),r=ja(r)}return t}F();var Tf=O("prompt-multimodal"),Rf=10*1024*1024,zy=15e3,$y=6;async function kf(t){let e=new Array(t.length),r=0;async function n(){for(;r<t.length;){let s=r++,o=t[s];o!==void 0&&(e[s]=await Gy(o))}}let i=Array.from({length:Math.min($y,t.length)},()=>n());return await Promise.all(i),e}function bf(t){return t.some(e=>e.type==="image")}async function Gy(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!ws(e.uri))return t;try{let{buf:r,contentType:n}=await jy(e.uri),i=e.mimeType||Hy(n)||"application/octet-stream";return Tf.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:i}),{type:"image",data:r.toString("base64"),mimeType:i}}catch(r){return Tf.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function Hy(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function jy(t){let e=new AbortController,r=setTimeout(()=>e.abort(),zy);try{let n=await fetch(t,{signal:e.signal});if(!n.ok)throw new Error(`HTTP ${n.status} ${n.statusText}`);let i=await n.arrayBuffer();if(i.byteLength>Rf)throw new Error(`image too large: ${i.byteLength} bytes (max ${Rf})`);return{buf:Buffer.from(i),contentType:n.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}vt();ye();F();var C=O("core"),qy=3e4,Jy=/^(boe|ppe)_[A-Za-z0-9_-]+$/,Vy=3e4,Ls=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Hr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=wf(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),C.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){C.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),C.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(n){C.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(n)})}}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)&&C.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,n){let i=n.downstream;i&&(i.onUpdate(s=>{n.loadingSession||this.forwardUpdate(e,s)}),i.onAgentRequest(s=>{this.handleAgentRequest(e,i,s)}),i.onExit((s,o)=>{C.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:s,signal:o}),Vn(n),n.downstream=void 0,n.replySeq=0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId),this.rejectPendingForDownstream(i,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let n=[];for(let[i,s]of this.pendingUpstream)s.downstream===e&&n.push(i);if(n.length!==0){C.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:n.length});for(let i of n){let s=this.pendingUpstream.get(i);if(s){this.pendingUpstream.delete(i),this.upstream.send(Bt(i,{code:L.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(o=>C.debug("send error response to upstream failed (ignored)",{err:String(o)}));try{s.downstream.respondAgentRequestError(s.agentRequestId,{code:L.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){C.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,n]of this.pendingUpstream)try{n.downstream.respondAgentRequestError(n.agentRequestId,{code:L.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.pendingUpstream.clear();for(let[,n]of this.pendingBridge)clearTimeout(n.timer),n.reject(new y("UPSTREAM_DISCONNECTED",`${n.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(vs(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,n=e.params?._meta?.cozeEnv;n&&Jy.test(n)?this.currentCozeEnv=n:n&&C.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:n});try{if(e.method.startsWith("_agent/")){let i=this.extensions[e.method];if(!i){r!==null?await this.sendError(r,L.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):C.warn("drop notification: extension not registered",{method:e.method});return}let s=await i(e,this);r!==null&&await this.upstream.send(Gr(r,s));return}if(e.method.startsWith("session/")){let i=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Gr(r,i));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Gr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,L.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):C.warn("drop unknown notification",{method:e.method})}catch(i){C.error("handleFrame failed",{method:e.method,err:String(i)}),r!==null&&await this.upstream.send(Bt(r,Jn(i)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new y("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,n=r._meta?.cozeAgentId;if(!n)throw new y("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let i=this.agents.get(n);if(!i)throw this.disconnectedAgents.has(n)?new y("AGENT_DISCONNECTED",`agent ${n} has been disconnected; cloud must _agent/create to revive`):new y("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!s)return this.dispatchSessionCall(i,e.method,r);let o=Date.now(),a=!1;try{let c=await i.getSessionQueue(s).enqueue(()=>this.dispatchSessionCall(i,e.method,r));return a=!0,c}finally{C.info("session call done",{agentId:i.agentId,method:e.method,durationMs:Date.now()-o,ok:a})}}async dispatchSessionCall(e,r,n){e.lastActiveAt=Date.now();let{stripped:i}=yh(n);switch(r){case"session/new":{let s=Zy();return C.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:s}),{sessionId:s}}case"session/load":{let s=i;return C.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:s.sessionId}),{}}case"session/prompt":{let s=i,o=s.sessionId;if(!o)throw new y("IPC_BAD_REQUEST","session/prompt: missing sessionId");let a=await this.ensureRuntime(e,o);if(a.replySeq=0,await this.ensureDownstream(e,o,a),!a.downstream||!a.acpSessionId)throw new y("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let c=n._meta?.cozeTriggerMsgId;c?e.activeTriggers.set(a.acpSessionId,c):e.activeTriggers.delete(a.acpSessionId);let l=_h(n._meta);if(l?e.activeGroupIds.set(a.acpSessionId,l):e.activeGroupIds.delete(a.acpSessionId),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&bf(s.prompt))throw new y("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let d=await kf(s.prompt);try{let p=await a.downstream.sessionPrompt({...s,sessionId:a.acpSessionId,prompt:d});return a.lastActiveAt=Date.now(),p}finally{if(e.activeTriggers.delete(a.acpSessionId),e.activeGroupIds.delete(a.acpSessionId),a.reloadAfterTurn){a.reloadAfterTurn=!1;let p=a.downstream;p&&(a.downstream=void 0,C.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:o,acpId:a.acpSessionId}),p.stop("reload-after-turn").catch(m=>C.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:o,err:String(m)})))}else a.downstream?.isAlive()&&this.armIdleTimer(e,o,a)}}case"session/cancel":{let o=i.sessionId;if(!o)throw new y("IPC_BAD_REQUEST","session/cancel: missing sessionId");let a=e.sessions.get(o);if(e.hasSessionQueue(o)){let c=e.getSessionQueue(o);c.size>0&&(C.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:o,queuedCount:c.size}),c.dispose(new y("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${o}`)))}return a?.downstream?.isAlive()&&a.acpSessionId&&await a.downstream.sessionCancel({sessionId:a.acpSessionId}),{ok:!0}}default:throw new y("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async ensureRuntime(e,r){let n=e.sessions.get(r);if(n)return n;let s={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(r,s),await this.persistSessionMapping(e),s}async requestSessionToken(e,r){let n={sessionId:r,_meta:{cozeAgentId:e}};try{let i=await this.sendRequest(He.GEN_MODEL_TOKEN,n,Vy);if(!i?.modelToken)throw new y("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return i.modelToken}catch(i){throw i instanceof y&&i.code==="MODEL_TOKEN_GEN_FAILED"?i:new y("MODEL_TOKEN_GEN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}}async ensureDownstream(e,r,n){if(Vn(n),n.downstream?.isAlive())return;if(!this.sessionSpawner)throw new y("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let i=3,s=3e4,o=n.spawnFailCount??0,a=n.spawnFailedAt??0;if(o>=i&&Date.now()-a<s)throw new y("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${o} times in a row; please check framework binary / network and retry after ${Math.ceil((s-(Date.now()-a))/1e3)}s`);let c;try{c=await this.sessionSpawner(e,n.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(l){throw n.spawnFailCount=o+1,n.spawnFailedAt=Date.now(),n.spawnFailCount>=i&&n.acpSessionId&&(C.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:n.acpSessionId}),n.acpSessionId=void 0),l}if(n.spawnFailCount=0,n.spawnFailedAt=void 0,n.downstream=c,this.attachRuntimeHooks(e,r,n),n.acpSessionId){n.loadingSession=!0;try{await c.sessionLoad({sessionId:n.acpSessionId,cwd:e.workspace}),C.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:n.acpSessionId})}catch(l){C.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:n.acpSessionId,err:String(l)}),n.acpSessionId=void 0;let d=await c.sessionNew({cwd:e.workspace});n.acpSessionId=d.sessionId,await this.persistSessionMapping(e)}finally{n.loadingSession=!1}}else{let l=await c.sessionNew({cwd:e.workspace});n.acpSessionId=l.sessionId,await this.persistSessionMapping(e)}c.afterSessionEstablished&&n.acpSessionId&&await c.afterSessionEstablished(n.acpSessionId)}armIdleTimer(e,r,n){if(Vn(n),this.isRuntimeBusy(e,n)){C.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}n.idleTimer=setTimeout(()=>{if(n.idleTimer=void 0,this.isRuntimeBusy(e,n)){C.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,n);return}C.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let i=n.downstream;n.downstream=void 0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId),i&&i.stop("idle timeout").catch(s=>C.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(s)}))},this.sessionIdleTimeoutMs),n.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let n=r.downstream;if(!n)return!1;for(let i of this.pendingUpstream.values())if(i.downstream===n)return!0;return!1}async sendAgentFileUpdate(e,r,n,i){let s={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let o=e.activeTriggers.get(r.acpSessionId);o&&(s.cozeTriggerMsgId=o);let a=e.activeGroupIds.get(r.acpSessionId);a&&(s.cozeGroupId=a)}await this.upstream.send(Wn("session/update",{sessionId:n,update:i,_meta:s}))}forwardUpdate(e,r){let n=r.sessionId,i=this.reverseSessionId(e,n);if(!i){C.debug("drop update for unknown session",{agentId:e.agentId,acpId:n});return}let s=e.sessions.get(i);if(!s){C.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:i});return}if(Xy(r)){C.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:n});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++s.replySeq},a=e.activeTriggers.get(n);a&&(o.cozeTriggerMsgId=a);let c=e.activeGroupIds.get(n);c&&(o.cozeGroupId=c),this.upstream.send(Wn("session/update",{...r,sessionId:i,_meta:o})).catch(l=>C.warn("forward update failed",{agentId:e.agentId,err:String(l)}))}handleAgentRequest(e,r,n){if(n.method==="session/request_permission"){this.forwardPermissionRequest(e,r,n);return}if(n.method==="fs/write_text_file"||n.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,n);return}C.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:n.method}),r.respondAgentRequestError(n.id,{code:L.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${n.method}`})}async handleFsRpcRequest(e,r,n){try{let i=e.workspace;if(n.method==="fs/write_text_file"){let s=n.params??{},o=await Sf(s,i);r.respondAgentRequest(n.id,o)}else{let s=n.params??{},o=await If(s,i);r.respondAgentRequest(n.id,o)}}catch(i){C.warn("fs rpc handler failed",{agentId:e.agentId,method:n.method,err:String(i)}),r.respondAgentRequestError(n.id,Jn(i))}}forwardPermissionRequest(e,r,n){let i=this.upstreamIds.next("session/request_permission"),s=n.params??{},a=s.sessionId,c=a?e.activeTriggers.get(a):void 0,l={cozeAgentId:e.agentId};c&&(l.cozeTriggerMsgId=c);let d=a?e.activeGroupIds.get(a):void 0;d&&(l.cozeGroupId=d);let p=a?this.reverseSessionId(e,a):void 0,m={...s,...p?{sessionId:p}:{},_meta:l};this.pendingUpstream.set(i,{agentRequestId:n.id,agentId:e.agentId,downstream:r,method:n.method}),C.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:i,acpSessionId:a,cloudSessionId:p,toolCallId:s.toolCall?.toolCallId,options:s.options?.map(f=>({optionId:f.optionId,kind:f.kind,name:f.name}))}),this.upstream.send(jn(i,"session/request_permission",m)).catch(f=>{this.pendingUpstream.delete(i),C.error("forward permission request failed",{agentId:e.agentId,err:String(f)}),r.respondAgentRequestError(n.id,{code:L.INTERNAL_ERROR,message:`upstream send failed: ${String(f)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let i=r.value;e.error?(C.info("upstream \u2192 permission response (error)",{agentId:i.agentId,upstreamId:e.id,method:i.method,error:e.error}),i.downstream.respondAgentRequestError(i.agentRequestId,e.error)):(i.method==="session/request_permission"&&Ky(e.result,i),C.info("upstream \u2192 permission response (result)",{agentId:i.agentId,upstreamId:e.id,method:i.method,result:e.result}),i.downstream.respondAgentRequest(i.agentRequestId,e.result));return}let n=this.lookupPending(this.pendingBridge,e.id,"bridge");if(n){this.pendingBridge.delete(n.key),clearTimeout(n.value.timer),e.error?n.value.reject(new Is(e.error)):n.value.resolve(e.result);return}C.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,n){let i=e.get(r);if(i)return{value:i,key:r};if(typeof r=="number"){let s=String(r),o=e.get(s);if(o)return C.warn(`${n} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:s}),{value:o,key:s}}}sendRequest(e,r,n=qy){let i=this.upstreamIds.next(e);return new Promise((s,o)=>{let a=setTimeout(()=>{this.pendingBridge.delete(i),o(new y("AGENT_TIMEOUT",`${e} timed out after ${n}ms`))},n);this.pendingBridge.set(i,{method:e,resolve:s,reject:o,timer:a}),this.upstream.send(jn(i,e,r)).catch(c=>{let l=this.pendingBridge.get(i);l&&(clearTimeout(l.timer),this.pendingBridge.delete(i)),o(c)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[n,i]of e.sessions){let s={modelToken:i.modelToken,tokenGeneratedAt:i.tokenGeneratedAt};i.acpSessionId&&(s.acpSessionId=i.acpSessionId),r.set(n,s)}await fn(e.agentId,r,this.paths)}catch(r){C.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[n,i]of e.sessions.entries())if(i.acpSessionId===r)return n}sendError(e,r,n){return this.upstream.send(Bt(e,{code:r,message:n,data:{bridgeVersion:$r}}))}};function Zy(){return Wy(16).toString("hex")}function Ky(t,e){if(!t||typeof t!="object"){C.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){C.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let n=r.outcome;if(!n||typeof n!="object"){C.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let s=n.outcome;(typeof s!="string"||s!=="selected"&&s!=="cancelled")&&C.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:s,result:t})}function Xy(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let n=r;return n.type!=="text"||typeof n.text!="string"?!1:n.text.startsWith("Model metadata for `")}F();de();import{randomBytes as Qy}from"node:crypto";import{chmod as Yy,mkdir as eE,writeFile as Af}from"node:fs/promises";import{createServer as tE}from"node:http";import{dirname as rE}from"node:path";var nE=1e6,Wa=O("ipc"),Fs=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??M()}async start(){this.token=Qy(32).toString("hex");let e=tE((n,i)=>{this.dispatch(n,i)});this.server=e,await new Promise((n,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>n())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),Wa.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,n)=>{e.close(i=>i?n(i):r())}),this.server=null)}async persistAuthFiles(){await eE(rE(this.paths.portFile),{recursive:!0}),await Af(this.paths.portFile,String(this.port),"utf8"),await Af(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await Yy(this.paths.tokenFile,384)}catch(e){Wa.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Xn(r,401,{error:"unauthorized"});return}let i=`${e.method} ${(e.url??"").split("?")[0]}`,s=this.routes.get(i);if(!s){Xn(r,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await iE(e)}catch(a){Xn(r,400,{error:"invalid json",detail:String(a)});return}try{let a=await s.handler(o,e);Xn(r,200,a??{ok:!0})}catch(a){Wa.error("IPC handler failed",{key:i,err:String(a)}),Xn(r,500,{error:a instanceof Error?a.message:String(a)})}}};function Xn(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function iE(t){let e=[],r=0;for await(let i of t){let s=i;if(r+=s.length,r>nE)throw new Error("body too large");e.push(s)}let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):null}var Mf="";function mE(t=""){let r=`${Date.now()}`,n=Mf||(Mf=EE(t)),i=Math.random().toString(16).slice(-6);return"02"+r+n+i}function wE(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function _E(t){return(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8)}function Bf(t){return(Array(4).join("0")+parseInt(t,2).toString(16)).slice(-4)}function yE(t){let e=t.split(/\./).map(i=>_E(i)),r=[];return r[0]=Bf(e[0]+e[1]),r[1]=Bf(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",r[0],r[1]].join("")}function EE(t){let e=/(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(t),r=/(([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(t);return e?yE(t):r?SE(t):"00000000000000000000000000000000"}function SE(t){let e="",r=[],n=0,i=0,s=!0,o="0000";if(t.indexOf("::")>-1){let a=t.split("::");for(let l=0;l<a.length;l++){let d=a[l];if(d.indexOf(":")>0){let p=d.split(":");s&&(n=p.length),i+=p.length;for(let m=0;m<p.length;m++)if(p[m].length!==4){let u=o.substring(0,4-p[m].length).concat(p[m]);r.push(u)}else r.push(p[m]);s=!1}else{if(d.length!==4){let m=o.substring(0,4-d.length).concat(d);r.push(m)}else r.push(d);s&&(n+=1),i+=1,s=!1}}let c="";for(let l=0;l<8-i;l++)c=c.concat(o);for(let l=0;l<r.length;l++)l===n&&(e=e.concat(c)),e=e.concat(r[l]);return e}{let a=t.split(":");for(let c=0;c<a.length;c++){let l=a[c];if(a[c].length!==4){let p=o.substring(0,4-a[c].length).concat(l);e=e.concat(p)}else e=e.concat(l)}return e}}function IE(t,e){let r=t.key;r!==void 0&&(ue(e,10),cr(e,r));let n=t.value;n!==void 0&&(ue(e,18),cr(e,n))}function vE(t){let e={};e:for(;!Qf(t);){let r=Se(t);switch(r>>>3){case 0:break e;case 1:e.key=ar(t,Se(t));break;case 2:e.value=ar(t,Se(t));break;default:Zf(t,7&r)}}if(e.key===void 0)throw new Error("Missing required field: key");if(e.value===void 0)throw new Error("Missing required field: value");return e}function Vf(t){let e=Xf();return TE(t,e),xE(e)}function TE(t,e){let r=t.SeqID;r!==void 0&&(ue(e,8),Yn(e,r));let n=t.LogID;n!==void 0&&(ue(e,16),Yn(e,n));let i=t.service;i!==void 0&&(ue(e,24),Yn(e,Qa(i)));let s=t.method;s!==void 0&&(ue(e,32),Yn(e,Qa(s)));let o=t.headers;if(o!==void 0)for(let u of o){ue(e,42);let g=Xf();IE(u,g),ue(e,g.limit),DE(e,g),AE(g)}let a=t.payloadEncoding;a!==void 0&&(ue(e,50),cr(e,a));let c=t.payloadType;c!==void 0&&(ue(e,58),cr(e,c));let l=t.payload;l!==void 0&&(ue(e,66),ue(e,l.length),CE(e,l));let d=t.LogIDNew;d!==void 0&&(ue(e,74),cr(e,d));let p=t.serverTiming;p!==void 0&&(ue(e,82),cr(e,p));let m=t.msgID;m!==void 0&&(ue(e,90),cr(e,m));let f=t.frameType;f!==void 0&&(ue(e,96),Yn(e,Qa(f)))}function RE(t){return kE(OE(t))}function kE(t){let e={};e:for(;!Qf(t);){let r=Se(t);switch(r>>>3){case 0:break e;case 1:e.SeqID=zf(t,!0);break;case 2:e.LogID=zf(t,!0);break;case 3:e.service=Se(t);break;case 4:e.method=Se(t);break;case 5:{let n=bE(t);(e.headers||(e.headers=[])).push(vE(t)),t.limit=n;break}case 6:e.payloadEncoding=ar(t,Se(t));break;case 7:e.payloadType=ar(t,Se(t));break;case 8:e.payload=PE(t,Se(t));break;case 9:e.LogIDNew=ar(t,Se(t));break;case 10:e.serverTiming=ar(t,Se(t));break;case 11:e.msgID=ar(t,Se(t));break;case 12:e.frameType=Se(t);break;default:Zf(t,7&r)}}if(e.SeqID===void 0)throw new Error("Missing required field: SeqID");if(e.LogID===void 0)throw new Error("Missing required field: LogID");if(e.service===void 0)throw new Error("Missing required field: service");if(e.method===void 0)throw new Error("Missing required field: method");return e}function bE(t){let e=Se(t),r=t.limit;return t.limit=t.offset+e,r}function Zf(t,e){switch(e){case 0:for(;128&Le(t););break;case 2:Ya(t,Se(t));break;case 5:Ya(t,4);break;case 1:Ya(t,8);break;default:throw new Error("Unimplemented type: "+e)}}function Qa(t){return t|=0,{low:t,high:t>>31,unsigned:t>=0}}var Kf=[];function Xf(){let t=Kf.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function AE(t){Kf.push(t)}function OE(t){return{bytes:t,offset:0,limit:t.length}}function xE(t){let e=t.bytes,r=t.limit;return e.length===r?e:e.subarray(0,r)}function Ya(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function Qf(t){return t.offset>=t.limit}function ri(t,e){let r=t.bytes,n=t.offset,i=t.limit,s=n+e;if(s>r.length){let o=new Uint8Array(2*s);o.set(r),t.bytes=o}return t.offset=s,s>i&&(t.limit=s),n}function wc(t,e){let r=t.offset;if(r+e>t.limit)throw new Error("Read past limit");return t.offset+=e,r}function PE(t,e){let r=wc(t,e);return t.bytes.subarray(r,r+e)}function CE(t,e){let r=ri(t,e.length);t.bytes.set(e,r)}function ar(t,e){let r=wc(t,e),n=String.fromCharCode,i=t.bytes,s="\uFFFD",o="";for(let a=0;a<e;a++){let c=i[a+r],l,d,p,m;(128&c)===0?o+=n(c):(224&c)===192?a+1>=e?o+=s:(l=i[a+r+1],(192&l)!==128?o+=s:(m=(31&c)<<6|63&l,m<128?o+=s:(o+=n(m),a++))):(240&c)==224?a+2>=e?o+=s:(l=i[a+r+1],d=i[a+r+2],((l|d<<8)&49344)!==32896?o+=s:(m=(15&c)<<12|(63&l)<<6|63&d,m<2048||m>=55296&&m<=57343?o+=s:(o+=n(m),a+=2))):(248&c)==240?a+3>=e?o+=s:(l=i[a+r+1],d=i[a+r+2],p=i[a+r+3],((l|d<<8|p<<16)&12632256)!==8421504?o+=s:(m=(7&c)<<18|(63&l)<<12|(63&d)<<6|63&p,m<65536||m>1114111?o+=s:(m-=65536,o+=n((m>>10)+55296,(1023&m)+56320),a+=3))):o+=s}return o}function cr(t,e){let r=e.length,n=0;for(let o=0;o<r;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<r&&(a=(a<<10)+e.charCodeAt(++o)-56613888),n+=a<128?1:a<2048?2:a<65536?3:4}ue(t,n);let i=ri(t,n),s=t.bytes;for(let o=0;o<r;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<r&&(a=(a<<10)+e.charCodeAt(++o)-56613888),a<128?s[i++]=a:(a<2048?s[i++]=a>>6&31|192:(a<65536?s[i++]=a>>12&15|224:(s[i++]=a>>18&7|240,s[i++]=a>>12&63|128),s[i++]=a>>6&63|128),s[i++]=63&a|128)}}function DE(t,e){let r=ri(t,e.limit),n=t.bytes,i=e.bytes;for(let s=0,o=e.limit;s<o;s++)n[s+r]=i[s]}function Le(t){return t.bytes[wc(t,1)]}function Uf(t,e){let r=ri(t,1);t.bytes[r]=e}function Se(t){let e=0,r=0,n;do n=Le(t),e<32&&(r|=(127&n)<<e),e+=7;while(128&n);return r}function ue(t,e){for(e>>>=0;e>=128;)Uf(t,127&e|128),e>>>=7;Uf(t,e)}function zf(t,e){let r=0,n=0,i=0,s;return s=Le(t),r=127&s,128&s&&(s=Le(t),r|=(127&s)<<7,128&s&&(s=Le(t),r|=(127&s)<<14,128&s&&(s=Le(t),r|=(127&s)<<21,128&s&&(s=Le(t),n=127&s,128&s&&(s=Le(t),n|=(127&s)<<7,128&s&&(s=Le(t),n|=(127&s)<<14,128&s&&(s=Le(t),n|=(127&s)<<21,128&s&&(s=Le(t),i=127&s,128&s&&(s=Le(t),i|=(127&s)<<7))))))))),{low:r|n<<28,high:n>>>4|i<<24,unsigned:e}}function Yn(t,e){let r=e.low>>>0,n=(e.low>>>28|e.high<<4)>>>0,i=e.high>>>24,s=i===0?n===0?r<16384?r<128?1:2:r<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:i<128?9:10,o=ri(t,s),a=t.bytes;switch(s){case 10:a[o+9]=i>>>7&1;case 9:a[o+8]=s!==9?128|i:127&i;case 8:a[o+7]=s!==8?n>>>21|128:n>>>21&127;case 7:a[o+6]=s!==7?n>>>14|128:n>>>14&127;case 6:a[o+5]=s!==6?n>>>7|128:n>>>7&127;case 5:a[o+4]=s!==5?128|n:127&n;case 4:a[o+3]=s!==4?r>>>21|128:r>>>21&127;case 3:a[o+2]=s!==3?r>>>14|128:r>>>14&127;case 2:a[o+1]=s!==2?r>>>7|128:r>>>7&127;case 1:a[o]=s!==1?128|r:127&r}}function NE(t){return RE(t)}function $f(t){return Vf(t)}var Gf=65536,LE="\0\0\0\0\0\0\0\0",Vr=Gf*Gf,Yf=Vr*Vr,Hf=Yf/2,$t=String.prototype.charCodeAt,Oe=class t{constructor(e,r,n){this.isLong=!0,this.low=0|e,this.high=0|r,this.unsigned=!!n}static isLong(e){return e&&e.isLong===!0}static fromBits(e,r,n){return new t(e,r,n)}static fromBytes(e,r,n){return n?t.fromBytesLE(e,r):t.fromBytesBE(e,r)}static fromBytesLE(e,r){return new t(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,r)}static fromBytesBE(e,r){return new t(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],r)}static fromHash(e){return e===LE?jf:new t(($t.call(e,0)|$t.call(e,1)<<8|$t.call(e,2)<<16|$t.call(e,3)<<24)>>>0,($t.call(e,4)|$t.call(e,5)<<8|$t.call(e,6)<<16|$t.call(e,7)<<24)>>>0,!0)}toHash(){return String.fromCharCode(255&this.low,this.low>>>8&255,this.low>>>16&255,this.low>>>24,255&this.high,this.high>>>8&255,this.high>>>16&255,this.high>>>24)}static fromNumber(e,r=!0){if(isNaN(e))return r?FE:jf;if(r){if(e>=Yf)return BE}else{if(e<=-Hf)return UE;if(e+1>=Hf)return ME}return t.fromBits(e%Vr|0,e/Vr|0,r)}toNumber(){return this.unsigned?(this.high>>>0)*Vr+(this.low>>>0):this.high*Vr+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){t.isLong(e)||(e=t.fromNumber(e));let r=this.high>>>16,n=65535&this.high,i=this.low>>>16,s=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,l=65535&e.low,d=0,p=0,m=0,f=0;return f+=s+l,m+=f>>>16,f&=65535,m+=i+c,p+=m>>>16,m&=65535,p+=n+a,d+=p>>>16,p&=65535,d+=r+o,d&=65535,t.fromBits(m<<16|f,d<<16|p,this.unsigned)}equals(e){return t.isLong(e)||(e=t.fromNumber(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}addOne(){return this.low===-1&&this.high===-1?t.fromBits(0,0,this.unsigned):this.low===-1?t.fromBits(0,this.high+1,this.unsigned):t.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){let e=this.high,r=this.low;return[255&r,r>>>8&255,r>>>16&255,r>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){let e=this.high,r=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,r>>>24,r>>>16&255,r>>>8&255,255&r]}},jf=new Oe(0,0,!1),FE=new Oe(0,0,!0),ME=Oe.fromBits(-1,2147483647,!1),BE=Oe.fromBits(-1,-1,!0),UE=Oe.fromBits(0,-2147483648,!1),or=(function(t){return t[t.NATIVE_ERROR=5001]="NATIVE_ERROR",t[t.CONNECTING_ERROR=5002]="CONNECTING_ERROR",t[t.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",t[t.MESSAGE_ERROR=5004]="MESSAGE_ERROR",t[t.OPEN_ERROR=5005]="OPEN_ERROR",t})({}),lr=class{constructor(e){this.type=e,this.target=null}},tc=class extends lr{constructor(e,r){super(e),this.message=r&&r.message||null}},rc=class extends lr{constructor(e,r){super(e),this.error=r&&r.error||null,this.colno=r&&r.colno||0,this.filename=r&&r.filename||"",this.lineno=r&&r.lineno||0,this.message=r&&r.message||"",this.code=r&&r.code||5001}},nc=class extends lr{constructor(e,r){super(e),this.code=r&&r.code||0,this.reason=r&&r.reason||"",this.wasClean=r&&r.wasClean||!1,this.willReconnect=r&&r.willReconnect||!1}},ic=class extends lr{constructor(e,r){super(e),this.data=r&&r.data||null}},sc=class extends ic{constructor(e,r){super(e),this.data=r&&r.data||null,this.message=r&&r.message||null}},oc=class extends lr{constructor(e,r){super(e),this.data=r&&r.data||null}};function je(t,{message:e,code:r,error:n}){return new rc(t,{message:e,code:r,error:n})}function it(t,{code:e,reason:r,wasClean:n,willReconnect:i}){return new nc(t,{code:e,reason:r,wasClean:n,willReconnect:i})}function zE(t,{data:e,message:r}){return new sc(t,{data:e,message:r})}function $E(t,{data:e}){return new oc(t,{data:e})}function Wf(t,{message:e}){return new tc(t,{message:e})}var Ms=class{constructor(e,r){this.endpoints=e,this.maxRetries=r,this.currentIndex=0,this.currentEndpointTriesCount=0}resetEndpointConfig(){this.currentIndex=0,this.currentEndpointTriesCount=0}resetTries(){this.currentEndpointTriesCount=0}getCurrentEndpoint(){return this.endpoints[this.currentIndex]}getCurrentEndpointTriesCount(){return this.currentEndpointTriesCount}checkReachMaxTries(){return this.currentIndex>=this.endpoints.length||this.currentIndex===this.endpoints.length-1&&this.currentEndpointTriesCount===this.maxRetries}checkCurrentEndpointReachedMaxRetries(){return this.currentIndex==this.endpoints.length?!0:this.currentEndpointTriesCount>this.maxRetries}replaceBackupEndpointAndUpdateCount(){return this.currentEndpointTriesCount=1,this.currentIndex++,this.endpoints[this.currentIndex]}getCurrentEndpointAndUpdateCount(){return this.currentEndpointTriesCount++,this.getCurrentEndpoint()}},Kr=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",dr=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",ni=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",ei=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",GE=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,ti=class{constructor(){this._listeners={}}emit(e,...r){let n=this._listeners[e];if(n)n.slice().forEach(i=>i.fn.apply(i.ctx,r));else if(e==="error"&&!this.onerror){let i=r.length&&r[0];if(i instanceof Error)throw i;let s=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw s.context=i,i}return this}off(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=null;else{let n=this._listeners[e];if(n)for(let i=0;i<n.length;)n[i].fn===r?n.splice(i,1):++i}return this}on(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this}},ac=class extends ti{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,r,n){super(),this._socket=null,ni&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:r,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),dr&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:r,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let r=je("error",{message:this._formatErrorMessage(e)});this.emit("error",r);let n=it("close",{reason:this._formatErrorMessage(e)});this.emit("close",n)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",$E("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",it("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",zE("message",{...e}))}),this._socket.onError(e=>{this.emit("error",je("error",{...e,message:e.errMsg||""}))})}send(e){if(e instanceof Uint8Array){let r=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:r,fail:n=>{this.emit("error",je("error",{message:this._formatErrorMessage(n)}))}})}else this._socket&&this._socket.send({data:e,fail:r=>{this.emit("error",je("error",{message:this._formatErrorMessage(r)}))}})}close(e,r){this._socket&&this._socket.close({code:e,reason:r})}addEventListener(e,r){this.on(e,r)}removeEventListener(e,r){this.off(e,r)}get readyState(){return this._socket.readyState}get binaryType(){return this._socket.binaryType}set binaryType(e){}get url(){return this._socket.url}get protocol(){return this._socket.protocol}get extensions(){return this._socket.extensions}get bufferedAmount(){return 0}};function HE(t,e){if(e)return new e(t.url,t.protocol);if(ni||dr)return new ac(t.url,t.protocol,t.headers);if((Kr||ei)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(t.url,t.protocols)}function jE(t){return!!(t||ni&&wx.connectSocket||dr&&tt.connectSocket||(Kr||ei)&&typeof WebSocket<"u"&&WebSocket)}function qf(t,e,r){let n=-1;async function i(s){return s<=n?Promise.reject(new Error("next() called multiple times in process")):(n=s,s===r.length?Promise.resolve():r[s].bind(t)(e,i.bind(null,s+1)))}i(0)}function eu(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(64512&r)===55296&&(64512&t.charCodeAt(n+1))===56320?(++n,e+=4):e+=3;return e}function tu(t,e,r){if(r-e<1)return"";let n="";for(let i=e;i<r;){let s=t[i++];if(s<=127)n+=String.fromCharCode(s);else if(s>=192&&s<224)n+=String.fromCharCode((31&s)<<6|63&t[i++]);else if(s>=224&&s<240)n+=String.fromCharCode((15&s)<<12|(63&t[i++])<<6|63&t[i++]);else if(s>=240){let o=((7&s)<<18|(63&t[i++])<<12|(63&t[i++])<<6|63&t[i++])-65536;n+=String.fromCharCode(55296+(o>>10)),n+=String.fromCharCode(56320+(1023&o))}}return n}function cc(t,e,r){let n=r,i,s;for(let o=0;o<t.length;++o)i=t.charCodeAt(o),i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=63&i|128):(64512&i)===55296&&(64512&(s=t.charCodeAt(o+1)))===56320?(i=65536+((1023&i)<<10)+(1023&s),++o,e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=63&i|128):(e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=63&i|128);return r-n}async function ru(t){if(typeof t=="string"){let e=new Uint8Array(eu(t));return cc(t,e,0),e}return t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function WE(t){try{return typeof t!="string"&&(t instanceof ArrayBuffer||t.buffer&&t.buffer instanceof ArrayBuffer)||typeof t!="string"?"":(JSON.parse(t),"application/json")}catch{return typeof t=="string"?"text/plain;charset=utf-8":""}}var qE=(t,e)=>{switch(t){case"boe":case"ppe":return{[`x-use-${t}`]:1,"x-tt-env":e};default:return{}}},lc=class{constructor(e){this.maxLossCount=e,this.count=0}addCount(){this.count++}checkReachMaxCount(){return this.count>=this.maxLossCount}resetCounter(e=0){this.maxLossCount=e,this.count=0}};async function JE(t){return new Promise(e=>{if(!Kr)return e("unknown reason");try{let r=document.createElement("script");window.frontierJSONP=n=>{document.body.removeChild(r),window.frontierJSONP=void 0,e(n&&n.msg||"unknown reason")},r.type="text/javascript",r.src=t.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(r)}catch{document.body.removeChild(r)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function Gt(t,e,r){return!!t?.find(n=>n.key===e&&n.value===r)}function Zr(t,e){return t?.find(r=>r.key===e)?.value}var ec=null;async function VE(){return ec||(ec=Promise.resolve().then(()=>(Ff(),Lf))),ec}var dc=class extends ti{constructor(e,r){super(),this._dbName=e,this._keyPath=r,this._qosDB=void 0,this._initPromise=null}async openDB(){await this._init()}async _init(){if(!this._qosDB){if(this._initPromise)return this._initPromise;try{let e=this._dbName,r=this._keyPath;this._initPromise=(async()=>{let{openDB:n}=await VE();this._qosDB=await n(`frontier_${e}`,1,{upgrade(i){i.createObjectStore(e,{keyPath:r})}})})(),await this._initPromise}catch(e){console.log(e)}finally{this._initPromise=null}}}async get(e){try{return await this._init(),this._qosDB?.get(this._dbName,e)}catch(r){console.log(r)}}async set(e,r){return await this._init(),this._qosDB?.put(this._dbName,e)}async del(e){try{return await this._init(),this._qosDB?.delete(this._dbName,e)}catch(r){console.log(r)}}async clear(){try{return await this._init(),this._qosDB?.clear(this._dbName)}catch(e){console.log(e)}}async keys(){return await this._init(),this._qosDB?.getAllKeys(this._dbName)}async getAll(){return await this._init(),this._qosDB?.getAll(this._dbName)}async closeDB(){try{this._qosDB?.close(),this._qosDB=void 0}catch(e){console.log(e)}}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}},hc=class{constructor(e,r){this._DBName=e,this._pathKey=r,this._qosDB=localStorage}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let r=this._qosDB.getItem(this._prefix);return JSON.parse(r||"{}")[e]}async set(e,r){let n=this._qosDB.getItem(this._prefix),i=JSON.parse(n||"{}");return i[r||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(i)),r||e[this._pathKey]}async del(e){let r=this._qosDB.getItem(this._prefix),n=JSON.parse(r||"{}");return n[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(n))}async clear(){return this._qosDB.clear()}async keys(){let e=this._qosDB.getItem(this._prefix),r=JSON.parse(e||"{}");return Object.keys(r)}async getAll(){let e=this._qosDB.getItem(this._prefix),r=JSON.parse(e||"{}");return Object.values(r)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}},fc=class{constructor(e,r){this._DBName=e,this._pathKey=r,this._qosDB=dr?tt:ni?wx:null}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let r=this._qosDB.getStorageSync(this._prefix);return JSON.parse(r||"{}")[e]}async set(e,r){let n=this._qosDB.getStorageSync(this._prefix),i=JSON.parse(n||"{}");return i[r||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(i)),r||e[this._pathKey]}async del(e){let r=this._qosDB.getStorageSync(this._prefix),n=JSON.parse(r||"{}");return n[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(n))}async clear(){return this._qosDB.clearStorageSync()}async keys(){let e=this._qosDB.getStorageInfoSync(this._prefix),r=JSON.parse(e||"{}");return Object.keys(r)}async getAll(){let e=this._qosDB.getStorageInfoSync(this._prefix),r=JSON.parse(e||"{}");return Object.values(r)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}};function nu(t,e){if(dr||dr)return new fc(t,e);if((Kr||ei)&&typeof indexedDB<"u")return new dc(t,e);if((Kr||ei)&&typeof localStorage<"u")return new hc(t,e);throw new Error("init QoSDB failed")}var uc=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=nu("qos","message_id")}async _intervalFlush(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this._interval)}async openDB(){await this._qosDB.openDB().then(()=>{this._intervalFlush()})}async flushExpired(){(await this._qosDB?.getAll()||[]).filter(({timestamp:n})=>n<Date.now()).forEach(n=>{this._qosDB?.del(n.message_id)})}async del(e){return this._qosDB?.del(e)}async set(e,r){return this._qosDB?.set({message_id:e,timestamp:r})}async get(e){return this._qosDB?.get(e)}async closeDB(){clearInterval(this._intervalTimeoutId),await this._qosDB?.closeDB()}get isReady(){return this._qosDB?.isReady}};function _c(t){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let r=Gt(t.message.headers,"x_frontier_qos","2"),n=r&&Gt(t.message.headers,"x_frontier_qos_ack","1"),i=r&&Gt(t.message.headers,"x_frontier_is_ack","1"),s=i?Zr(t.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:r,isQoSAck:n,isAckCleanupMessage:i,ackMsgIds:s}}async function iu(){return this._QoSManager||(this._QoSManager=new uc),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function ZE(t,e){let{enableAutoAck:r}=this._options,n=Gt(t.message.headers,"need_ack","1"),i=Gt(t.message.headers,"is_ack","1"),s=_c.call(this,t);if(r&&n){let{SeqID:o,LogID:a,service:c,LogIDNew:l,method:d}=t.message;this._sendAck({SeqID:o,LogID:a,LogIDNew:l,service:c,method:d,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:l||""},{key:"ack_code",value:"0"}]})}i&&!s.isQoSAck&&this._dispatchAckMessageEvent(t),e()}async function KE(t,e){this._debug("received",t.message),e()}async function XE(t,e){let r=NE(await ru(t.data));try{if(r.payload instanceof Uint8Array){let n=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},i=r.payloadEncoding?r.payloadEncoding.replace(/\s/g,"").toLowerCase():"",s=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},o=r.payloadType?r.payloadType.replace(/\s/g,"").toLowerCase():"",a=s.force?s.type:o||s.type,c=n.force?n.encoding:i||n.encoding,l=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],d=["none_none","binary"];this._options.enableTransformTextPayload&&l.includes(a)&&(!c||d.includes(c))?r.textPayload=tu(r.payload,0,r.payload.byteLength):r.textPayload=""}else r.textPayload=""}catch(n){r.textPayload="",console.log(n)}t.message=r,e()}function QE(t,e,r){let n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);let c=e.call(s,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var YE=4294967295;function e0(t,e,r){if(r>YE)throw new Error("integer too large");let n=3;for(;n>=0;){let i=255&r;gc(i,t,e+n),r>>>=8,n--}return e+4}function t0(t,e){let r=0,n=e,i=e+4;for(;n<i;){let{value:s,offset:o}=pc(t,n);n=o,r=r<<8>>>0,r+=s}return{value:r,offset:i}}function r0(t,e,r){return t?t.length<40?cc(t,e,r)+r:e.utf8Write?e.utf8Write(t,r)+r:e.write?e.write(t,r)+r:cc(t,e,r)+r:r}function n0(t,e){let r=new Oe(t[e+4]<<24|t[e+5]<<16|t[e+6]<<8|t[e+7],t[e+0]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3],!0);return e+=8,{value:r,offset:e+8}}function i0(t,e,r){let n=t.low,i=t.high;return e[r]=i>>>24,e[r+1]=i>>>16&255,e[r+2]=i>>>8&255,e[r+3]=255&i,e[r+4]=n>>>24,e[r+5]=n>>>16&255,e[r+6]=n>>>8&255,e[r+7]=255&n,r+=8,r}function pc(t,e){return t.readUInt8?{value:t.readUInt8(e),offset:e+1}:{value:255&t[e],offset:e+1}}function gc(t,e,r){return e.writeUint8?e.writeUint8(t,r):e[r]=255&t,r+1}var s0=function(t){return new Uint8Array(t)},o0=typeof Buffer<"u"?Buffer.allocUnsafe:QE(s0,Uint8Array.prototype.subarray),a0=16,yc=32;function c0(t){let e=0,r={};for(let n=0;n<t.length;n++)r[t[n].cursor_name]=eu(t[n].cursor_name),e+=14+r[t[n].cursor_name];return[e,r]}function Jf(t,e,r){let[n,i]=c0(t),s=o0(n),o=0;return t.forEach(a=>{console.log("cursor.service",a,a.service),o=gc(0,s,o),console.log("header",o),o=e0(s,o,a.service||0),console.log("service",o),o=gc(i[a.cursor_name],s,o),console.log("service-name",o),o=r0(a.cursor_name,s,o),console.log("name",o),o=i0(Oe.fromNumber(a.cursor||e),s,o),console.log("curvalue",o)}),{frameType:yc,headers:[{key:"cursor_file_name",value:r}],payload:s}}function l0(t){let e=0,r=[];for(;e<t.byteLength;){let{offset:n}=pc(t,e);e=n;let i={cursor_name:"",cursor:0,service:0},{value:s,offset:o}=t0(t,e);i.service=s,e=o;let{value:a,offset:c}=pc(t,e);e=c,i.cursor_name=tu(t,e,e+a),e+=a;let{value:l,offset:d}=n0(t,e);i.cursor=l.toNumber(),e=d,r.push(i)}return r}function d0(){return{frameType:yc,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var mc=class{constructor(e,r,n){this._cursorNameSpace=e,this._cursorFileName=r,this._messageStrategy=n,this._qosDB=nu(this._cursorNameSpace,"cursor_name")}async openDB(){await this._qosDB.openDB()}async getCursors(){if(!this._qosDB.isReady)return;let e=this._messageStrategy,r=await this._qosDB.getAll();switch(console.log("allCursorValues",r),e){case"ALL":return r&&r.length?Jf(r,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return r&&r.length?Jf(r,0,this._cursorFileName):d0()}}async set(e,r,n){return console.log("setdb",e,r,n),this._qosDB.set({cursor_name:e,cursor:r,service:n})}async setCursors(e){let r=l0(e);for(let n of r)console.log("setcursor",r),await this._qosDB.set(n)}async get(e){return(await this._qosDB.get(e))?.cursor}async closeDB(){await this._qosDB.closeDB()}updateCursorFileName(e){this._cursorFileName=e}get isReady(){return this._qosDB.isReady}},h0="__x_msg_qos__";async function su(t){if(!this._options.enableQoS)return null;let{aID:e,fpID:r,messageStrategy:n}=this._options,i=t||h0;try{return this._cursorManager?t&&this._cursorManager.updateCursorFileName(t):this._cursorManager=new mc(`${r}_${e}_${i}`,i,n),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function f0(t,e){let r=Gt(t.message.headers,"code","-1"),n=Gt(t.message.headers,"is_ack","1"),i=Zr(t.message.headers,"x_frontier_msgid"),s=Number(Zr(t.message.headers,"x_frontier_ttl"))||0,o=_c.call(this,t),a=Gt(t.message.headers,"x-msg-qos","2"),c=Zr(t.message.headers,"x-msg-cursor_name"),l=Number(Zr(t.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await iu.call(this):null;if(t.message.service>0&&n&&!r||t.message.service>0){if(i&&o.isQoSMessage&&d)return await d.get(i)||(this._dispatchMessageEvent(t),await d.set(i,Date.now()+s)),e();if(a){let p=await su.call(this);if(!p)return this._dispatchMessageEvent(t),e();let m=await p.get(c)??-1;if(m<l)this._dispatchMessageEvent(t),p.set(c,l,t.message.service);else throw new Error(`recevied message cursor ${l} larger than local cursor ${m}`);return e()}return this._dispatchMessageEvent(t),e()}}async function u0(t,e){let r=_c.call(this,t);if(!r.isQoSMessage)return e();let n=await iu.call(this);if(r.isAckCleanupMessage&&r.ackMsgIds.length)for(let i of r.ackMsgIds)await n.del(i);e()}async function p0(t,e){let r=t.message.frameType===a0,n=t.message.frameType===yc;if(!r&&!n)return e();let i=Zr(t.message.headers,"cursor_file_name");if(!i)return e();let s=await su.call(this,i);if(!s)return e();if(r){let o=await s.getCursors(),a={frameType:o?.frameType,SeqID:Oe.fromNumber(this._seqId++),LogID:Oe.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=Vf(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(n){let o=t.message.payload;o&&s.setCursors(o)}}var g0=async function(t,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},m0=async function(t,e){let r=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${r}`),e()},w0=async function(t,e){if(!this._ws||this._ws.readyState!==this.OPEN)return e();let{pingInterval:r}=this._options;this._endpointManager?.resetEndpointConfig();for(let i=0;i<this._messageQueue.length;i++){let s=this._messageQueue[i];if(this._ws.readyState===this.OPEN&&s!==null)this._ws&&this._ws.send(s),this._messageQueue[i]=null;else break}this._messageQueue=this._messageQueue.filter(i=>!!i),this._pingPongTimeoutId=setTimeout(()=>this._ping(),r),this._dispatchOpenEvent(t),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let n=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${n} success`),e()},Bs=class extends ti{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=Kr,this._isNode=GE,this._isMiniTT=dr,this._isMiniWX=ni,this._isWorker=ei,this._messageQueue=[],this._endpointManager=null,this._readyClosed=!1,this._binaryType="arraybuffer",this._connectLock=!1,this._connectionTimeoutId=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this._isInit=!1,this._url="",this._QoSManager=null,this._cursorManager=null,this._pingLossCounter=null,this._protocols="pbbp2",this.CLOSED=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this._onOpen=s=>{try{qf(this,s,[g0,w0,m0])}catch(o){let a=je("error",{message:o.message,code:or.OPEN_ERROR,error:o});this._dispatchErrorEvent(a)}},this._onMessage=async s=>{let{pingInterval:o,pingFrequency:a}=this._options;if((s.data==="hi"&&a==="always"||a==="auto")&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),o)),s.data!=="hi")try{qf(this,s,[XE,ZE,u0,p0,f0,KE])}catch(c){let l=je("error",{message:c.message,code:or.MESSAGE_ERROR,error:c});this._dispatchErrorEvent(l)}},this._onError=s=>{let o=this._endpointManager?.checkReachMaxTries(),a=this._endpointManager?.getCurrentEndpoint();if(o&&!s.message){let c=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(je("error",{message:c,code:or.MAX_RETRIES_ERROR,error:s}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(je("error",{message:s.message,code:or.NATIVE_ERROR,error:s}))},this._onClose=async s=>{this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;let o=this._endpointManager?.checkReachMaxTries();if(!o&&this._navigatorOnline()&&!this._readyClosed){let a=this._endpointManager?.getCurrentEndpoint(),c=this._options.reconnectInterceptor(s.code,s.reason);this._dispatchCloseEvent(it("close",{code:1006,reason:s.reason||`connecting failed, unknown reason, hostname: ${a}`,willReconnect:c})),c&&this._connect();return}if(s.code!==1e3&&this._readyClosed){this._dispatchCloseEvent(it("close",{code:1e3,reason:"bye"})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&o){let a=this._endpointManager?.getCurrentEndpoint(),c=s.reason;c||(c=await JE(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(it("close",{code:s.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(je("error",{message:l,code:or.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&!s.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(it("close",{code:s.code,reason:`connecting failed, unknown reason, hostname: ${a}`})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}this._dispatchCloseEvent(s),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this.onReceiveAck=null,this.onStopImmediatelyReconnect=null,this._handleOnLine=this._handleOnLine.bind(this),this._handleOffLine=this._handleOffLine.bind(this),this._handlePageHide=this._handlePageHide.bind(this),this._handlePageShow=this._handlePageShow.bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:wE,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:r,ws:n}=e,i=Array.isArray(r)?r:typeof r=="string"?[r]:[];if(!i||i.length===0)throw new Error("please provide valid url");if(!jE(n))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new Ms(i,this._options.maxRetries),this._pingLossCounter=new lc(this._options.pingLossCount),this._options.automaticOpen&&(this._isInit=!0,this._connect()),this._options.listenNetworkChanged&&(this._isMiniTT||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this._initGlobalEventListener())}_handleOnLine(){this._options.disableAutoReconnect||this._readyClosed||this._handleReconnect()}_handleOffLine(){this._destroyWebSocket();let e=Wf("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(this._navigatorOnline()&&(!this._ws||this._ws.readyState!==this.OPEN||this._ws.readyState!==this.CONNECTING)&&this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}async _generateUrl(e){let{fpID:r,deviceID:n,bddID:i,ttwID:s,accessKey:o,aID:a,customParams:c={},enableAutoAck:l,enableQoS:d,QoSLevel:p,env:m}=this._options,f,u,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(f=location&&location.protocol=="https:"?"wss://":"ws://",u=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${f}${u}`):(f="wss://",u=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(u)?u:`${f}${u}`);let w=i?"bd_did":s?"ttwid":"device_id",E=i||s||n;if(!E||!w)throw new Error("please provide bddID, deviceID or ttwID");let v=typeof c=="function"?await c():c,h=m?qE(m.xUseEnv,m.xTTEnv):{},_=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:r,aid:a,[w]:E,xsack:l?1:0,xaack:l?1:0,xsqos:d?1:0,qos_level:d?p:void 0,qos_sdk_version:2,...h},v),S=Object.keys(_).reduce((k,R)=>_[R]!==void 0?`${k}${k?"&":"?"}${R}=${_[R]}`:k,"");return`${g}/ws/v2${S}`}async _connect(){if(!(this._connectLock||this._readyClosed)){this._connectLock=!0;try{let e=this._endpointManager?.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:r}=this._options;if(e){let i=this._endpointManager?.getCurrentEndpoint(),s=this._endpointManager?.replaceBackupEndpointAndUpdateCount(),o=this._endpointManager?.getCurrentEndpointTriesCount();if(s){let a=`connect ${i} timeout, max retries reached, will use backup endpoint ${s} to retry`,c=je("error",{message:a,code:or.MAX_RETRIES_ERROR});this._debug(a),this._dispatchErrorEvent(c),this._url=await this._generateUrl(s),this._debug(`connect ${s} ${o} times`),this._removeWsListeners()}else{let a=`connect ${i} timeout, max retries reached`;this._debug(a),this._dispatchErrorEvent(je("error",{message:a,code:or.MAX_RETRIES_ERROR}));return}}else{let i=this._endpointManager?.getCurrentEndpointAndUpdateCount(),s=this._endpointManager?.getCurrentEndpointTriesCount();this._url=await this._generateUrl(i||""),this._debug(`connect ${i} ${s} times`),this._removeWsListeners()}if(this._isInit)this._isInit=!1;else{let i=Wf("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(i)}let n=this._endpointManager?.getCurrentEndpointTriesCount()||0;n>1&&await this._wait(n-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=HE({url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},this._options.ws),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),r)}catch(e){throw this._connectLock=!1,e}}}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){let{initReconnectInterval:r,maxReconnectInterval:n,reconnectIntervalGrowFactor:i}=this._options,s=r*Math.pow(i,e-1);return s>n?n:s}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING){this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);return}if(!this._ws||this._ws.readyState!==this.OPEN)return void this._handleReconnect();this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)}_handleReconnectTimeout(){this._pingLossCounter?.addCount(),this.emit("ping_once_timeout","timeout"),this._pingLossCounter?.checkReachMaxCount()?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:(this._isBrowser||this._isWorker)&&this._options.listenNetworkChanged?navigator.onLine:!0}_handleReconnect(){!this._navigatorOnline()||this._readyClosed||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}):this._isMiniWX&&wx.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})}_wait(e){return new Promise(r=>{setTimeout(r,this._getIntervalValue(e))})}_disconnect(e=1e3,r="",n=!1){this._ws&&this._destroyWebSocket(e,r,n)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let r=$f(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(r),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,r=""){try{this._ws&&this._ws.close(e,r)}catch{}}_destroyWebSocket(e=1e3,r="",n=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,r),this._connectLock=!1,n&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let s=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(it("close",{code:1006,reason:`connect ${s} timeout, max retries reached`,wasClean:!0}))}else{let s=this._options.reconnectInterceptor(e,r);this._dispatchCloseEvent(it("close",{code:e,reason:r,wasClean:!0,willReconnect:s})),s&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(it("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(it("close",{code:1006,reason:"going away, network offline"})),this._ws=null,this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return this._endpointManager?.getCurrentEndpointTriesCount()||0}get bufferedAmount(){return this._messageQueue.reduce((r,n)=>(r+=n&&n.byteLength||0,r),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,r){if(this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),this._QoSManager?.closeDB(),!this._ws)return void this._debug("close, ws instance not initialized");if(this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING)return void this._debug("close, ws already closed");this._destroyWebSocket(e,r)}async send(e,r){if(e==null)throw new Error("please provide a valid data, data must be a string or an arraybuffer");typeof e=="number"&&(e=JSON.stringify(e)),typeof e!="string"&&!(e instanceof ArrayBuffer)&&!(e.buffer&&e.buffer instanceof ArrayBuffer)&&(e=JSON.stringify(e));let n=await ru(e),i=WE(e),{method:s=0,service:o=this._options.service,logID:a=this._options.logIDGenerator(),headers:c=this._options.headers,payloadEncoding:l=this._options.payloadEncoding,payloadType:d=this._options.payloadType,logIDNew:p=this._options.logIDNewConfig.enableAutoGenerateLogIDNew?mE(this._options.logIDNewConfig.userIp):""}=r||{};if(!o)throw new Error("please provide a valid service");let m={SeqID:Oe.fromNumber(this._seqId++),LogID:Oe.fromNumber(a),service:o,method:s,headers:c,payloadEncoding:l instanceof Object?l.encoding?l.encoding:"":l,payloadType:d instanceof Object?d.type?d.type:i:d||i,payload:n,LogIDNew:p},f=$f(m);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(f),this._debug("sent",m)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(f),this._debug("enqueue",m)):(this._messageQueue.shift(),this._messageQueue.push(f)),{seqID:this._seqId,logID:a,logIDNew:p}}async reconnect(e){let{url:r}=e||{},n=Array.isArray(r)?r:typeof r=="string"?[r]:[];e&&Object.assign(this._options,e),n&&n.length?this._endpointManager=new Ms(n,this._options.maxRetries):this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}async connect(){this._connectLock||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}addEventListener(e,r){this.on(e,r)}dispatchEvent(e){let{type:r}=e;this.emit(r,e)}removeEventListener(e,r){this.off(e,r)}pingOnce(){return new Promise((e,r)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);let n=()=>{e("success"),this.off("ping_once_success",n),this.off("ping_once_timeout",i)},i=()=>{r("timeout"),this.off("ping_once_success",n),this.off("ping_once_timeout",i)};this.on("ping_once_success",n),this.on("ping_once_timeout",i),this._ping()})}};var MS=ct(ep(),1),BS=ct(Js(),1),US=ct(Yr(),1),zS=ct(xc(),1),$S=ct(Dc(),1),GS=ct(Uc(),1),lp=ct(Xs(),1),HS=ct(cp(),1);var dp=lp.default;ye();F();var ne=O("upstream.frontier"),fp="application/json",up="none",WS=15e3,hi=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:Ih,...Ur(this.opts.ppeOverride)};class r extends dp{constructor(u){super(u,Sh,{headers:e})}send(u,...g){if(il("debug"))try{let w;typeof u=="string"?w=Buffer.from(u,"utf8"):u instanceof Buffer?w=u:u instanceof ArrayBuffer?w=new Uint8Array(u):ArrayBuffer.isView(u)?w=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):w=new Uint8Array(0);let E=Buffer.from(w.slice(0,128)).toString("hex");ne.debug("WS raw frame out",{bytes:w.byteLength,headHex:E})}catch(w){ne.warn("WS raw frame dump failed",{err:String(w)})}super.send(u,...g)}}let n=Th(this.opts.urlOverride),i={url:n,ws:r,fpID:Eh,aID:ys,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:fp,force:!0},payloadEncoding:{encoding:up,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},s=new Bs(i),o=!1,a=null,c,l,d=new Promise((f,u)=>{c=f,l=u}),p=f=>{o||(o=!0,a&&(clearTimeout(a),a=null),f?l(f):c())};s.onopen=()=>{this.opened=!0,this.openCount+=1;let f=this.openCount===1;ne.info("frontier opened",{url:n,remoteDeviceId:this.opts.handshake.deviceId,initial:f,openCount:this.openCount}),f&&p();for(let u of this.connectHandlers)Promise.resolve(u({initial:f})).catch(g=>ne.warn("onConnect handler threw (ignored)",{err:String(g)}))},s.onclose=f=>{this.opened=!1,ne.info("frontier closed",{code:f.code,reason:f.reason,willReconnect:f.willReconnect})},s.onerror=f=>{ne.warn("frontier error",{code:f.code,msg:f.message}),p(new y("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${f.code} msg=${f.message??""}`))},s.onmessage=f=>this.handleMessage(f),this.fws=s;let m=this.opts.openTimeoutMs??WS;a=setTimeout(()=>{p(new y("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${m}ms (handshake or upgrade slow)`))},m),await s.connect();try{await d}catch(f){try{s.close(1e3,"open failed")}catch(u){ne.warn("fws close during start failure threw (ignored)",{err:String(u)})}throw this.fws=null,this.opened=!1,f}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(n){ne.warn("frontier close threw (ignored)",{err:String(n)})}}}async send(e){let r=this.fws,n=e.method;if(!r)throw ne.warn("frontier send refused: upstream not started",{method:n}),new y("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let a=Date.now();throw a-this.lastSendRefusedLogAt>1e3?(ne.warn("frontier send refused: ws not open",{method:n,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=a,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new y("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let i=JSON.stringify(e),s=e;pp(s)||ne.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:i.length});try{await r.send(i,{service:33555712,method:1,payloadType:fp,payloadEncoding:up})}catch(a){throw ne.warn("frontier frame send failed",{method:s.method,jsonrpcId:s.id,err:String(a)}),new y("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(a)}`,{cause:a})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let n=e.params?._meta;if(!n?.cozeAgentId)return;let i=r(n.cozeAgentId);i&&(n.cozePatToken=i)}handleMessage(e){let r=e.message?.service;if(r!==33555712){ne.debug("drop non-adapter frontier frame",{service:r});return}let n=VS(e);if(!n){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:n.length});return}let i;try{i=JSON.parse(n)}catch(o){ne.warn("frontier message JSON parse failed",{err:String(o),head:n.slice(0,80)});return}let s=i;pp(s)||ne.info("frontier frame in",{logid:JS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id,method:s.method,body:qS(n)}),Promise.resolve(this.handler(i)).catch(o=>ne.warn("frontier frame handler threw",{err:String(o)}))}};function pp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var gp=2e3;function qS(t){return t.length<=gp?t:`${t.slice(0,gp)}...<truncated, total ${t.length} chars>`}function JS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function VS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}F();var $c=O("upstream.switchable"),Ys=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;$c.info("swap upstream",{reason:r});let n=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let i of this.connectHandlers)e.onConnect(i);try{await e.start()}catch(i){throw $c.error("swap target start failed, reverting",{err:String(i)}),this.inner=n,i}await n.stop(r??"swapped").catch(i=>$c.warn("previous upstream stop threw (ignored)",{err:String(i)}))}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()}};F();var Gc=O("upstream"),on=class{handler=null;async start(){Gc.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Gc.info("NoopUpstream stopped",{reason:e})}async send(e){Gc.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};ye();F();F();de();import{promises as Hc}from"node:fs";import{dirname as ZS}from"node:path";var KS=O("pat-token-store");async function mp(t=M()){try{let r=(await Hc.readFile(t.patTokenFile,"utf8")).trim();return r.length>0?r:null}catch(e){let r=e?.code;return r!=="ENOENT"&&KS.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function fi(t,e=M()){if(!t)throw new Error("writePatToken: empty patToken");await Hc.mkdir(ZS(e.patTokenFile),{recursive:!0}),await Hc.writeFile(e.patTokenFile,t,{encoding:"utf8",mode:384})}de();de();import{promises as eo}from"node:fs";import{join as XS}from"node:path";function QS(t,e){return`#!/bin/sh
90
+ `)}else s=o}return Sf.info("fs/read_text_file ok",{path:r,size:s.length}),{content:s}}async function z_(t,e,r){let n=U_({input:x_(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),i=Math.max(0,e-1),s=typeof r=="number"?i+r:Number.POSITIVE_INFINITY,o=[],a=0;try{for await(let c of n)if(a>=i&&a<s&&o.push(c),a++,a>=s)break}finally{n.close()}return o.join(`
91
+ `)}async function Tf(t,e){if(typeof t!="string"||t.length===0)throw new _("IPC_BAD_REQUEST","path must be a non-empty string");let[r,n]=await Promise.all([Ef(_f(e)),Ef(_f(t))]),i=M_(r,n);if(i.startsWith("..")||i===".."||i.startsWith(`..${B_}`))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return n}async function Ef(t){let e=[],r=t;for(;r!==ja(r);)try{let n=await C_(r);return e.length?F_(n,...e.reverse()):n}catch{e.push(L_(r)),r=ja(r)}return t}F();var Rf=x("prompt-multimodal"),kf=10*1024*1024,$_=15e3,G_=6;async function bf(t){let e=new Array(t.length),r=0;async function n(){for(;r<t.length;){let s=r++,o=t[s];o!==void 0&&(e[s]=await H_(o))}}let i=Array.from({length:Math.min(G_,t.length)},()=>n());return await Promise.all(i),e}function Af(t){return t.some(e=>e.type==="image")}async function H_(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!ws(e.uri))return t;try{let{buf:r,contentType:n}=await W_(e.uri),i=e.mimeType||j_(n)||"application/octet-stream";return Rf.info("image uri fetched and inlined",{uri:e.uri,bytes:r.length,mimeType:i}),{type:"image",data:r.toString("base64"),mimeType:i}}catch(r){return Rf.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function j_(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function W_(t){let e=new AbortController,r=setTimeout(()=>e.abort(),$_);try{let n=await fetch(t,{signal:e.signal});if(!n.ok)throw new Error(`HTTP ${n.status} ${n.statusText}`);let i=await n.arrayBuffer();if(i.byteLength>kf)throw new Error(`image too large: ${i.byteLength} bytes (max ${kf})`);return{buf:Buffer.from(i),contentType:n.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}vt();_e();F();var C=x("core"),J_=3e4,V_=/^(boe|ppe)_[A-Za-z0-9_-]+$/,Z_=3e4,Ls=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Hr;pendingUpstream=new Map;pendingBridge=new Map;currentCozeEnv;currentMockScenario;constructor(e){this.upstream=e.upstream,this.extensions=e.extensions??{},this.paths=e.paths,this.sessionSpawner=e.sessionSpawner,this.sessionIdleTimeoutMs=yf(e.bridgeConfig)}registerExtension(e,r){this.extensions[e]=r}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),C.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){C.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(r=>r.dispose(e))),this.agents.clear(),await this.upstream.stop(e)}get(e){return this.agents.get(e)}register(e){this.agents.set(e.agentId,e),C.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let r of this.registerHandlers)try{r(e.agentId)}catch(n){C.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(n)})}}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)&&C.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,r,n){let i=n.downstream;i&&(i.onUpdate(s=>{n.loadingSession||this.forwardUpdate(e,s)}),i.onAgentRequest(s=>{this.handleAgentRequest(e,i,s)}),i.onExit((s,o)=>{C.info("session runtime exited",{agentId:e.agentId,cloudId:r,code:s,signal:o}),Vn(n),n.downstream=void 0,n.replySeq=0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId),this.rejectPendingForDownstream(i,"downstream exited")}))}hasPendingPermissionFor(e){for(let r of this.pendingUpstream.values())if(r.downstream===e)return!0;return!1}rejectPendingForDownstream(e,r){let n=[];for(let[i,s]of this.pendingUpstream)s.downstream===e&&n.push(i);if(n.length!==0){C.info("reject pendingUpstream entries (downstream gone)",{reason:r,count:n.length});for(let i of n){let s=this.pendingUpstream.get(i);if(s){this.pendingUpstream.delete(i),this.upstream.send(Bt(i,{code:L.INTERNAL_ERROR,message:`bridge downstream gone: ${r}`})).catch(o=>C.debug("send error response to upstream failed (ignored)",{err:String(o)}));try{s.downstream.respondAgentRequestError(s.agentRequestId,{code:L.INTERNAL_ERROR,message:`bridge: ${r}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,r=this.pendingBridge.size;if(!(e===0&&r===0)){C.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:r});for(let[,n]of this.pendingUpstream)try{n.downstream.respondAgentRequestError(n.agentRequestId,{code:L.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.pendingUpstream.clear();for(let[,n]of this.pendingBridge)clearTimeout(n.timer),n.reject(new _("UPSTREAM_DISCONNECTED",`${n.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(vs(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let r="id"in e&&e.id!==void 0?e.id:null,n=e.params?._meta?.cozeEnv;n&&V_.test(n)?this.currentCozeEnv=n:n&&C.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:n});try{if(e.method.startsWith("_agent/")){let i=this.extensions[e.method];if(!i){r!==null?await this.sendError(r,L.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):C.warn("drop notification: extension not registered",{method:e.method});return}let s=await i(e,this);r!==null&&await this.upstream.send(Gr(r,s));return}if(e.method.startsWith("session/")){let i=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(Gr(r,i));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(Gr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,L.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):C.warn("drop unknown notification",{method:e.method})}catch(i){C.error("handleFrame failed",{method:e.method,err:String(i)}),r!==null&&await this.upstream.send(Bt(r,Jn(i)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new _("IPC_BAD_REQUEST",`${e.method} requires params`);let r=e.params,n=r._meta?.cozeAgentId;if(!n)throw new _("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let i=this.agents.get(n);if(!i)throw this.disconnectedAgents.has(n)?new _("AGENT_DISCONNECTED",`agent ${n} has been disconnected; cloud must _agent/create to revive`):new _("AGENT_NOT_FOUND",`agent not found: ${n}`);let s=typeof r.sessionId=="string"?r.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!s)return this.dispatchSessionCall(i,e.method,r);let o=Date.now(),a=!1;try{let c=await i.getSessionQueue(s).enqueue(()=>this.dispatchSessionCall(i,e.method,r));return a=!0,c}finally{C.info("session call done",{agentId:i.agentId,method:e.method,durationMs:Date.now()-o,ok:a})}}async dispatchSessionCall(e,r,n){e.lastActiveAt=Date.now();let{stripped:i}=_h(n);switch(r){case"session/new":{let s=K_();return C.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:s}),{sessionId:s}}case"session/load":{let s=i;return C.info("session/load ack (lazy spawn)",{agentId:e.agentId,cloudId:s.sessionId}),{}}case"session/prompt":{let s=i,o=s.sessionId;if(!o)throw new _("IPC_BAD_REQUEST","session/prompt: missing sessionId");let a=await this.ensureRuntime(e,o);if(a.replySeq=0,await this.ensureDownstream(e,o,a),!a.downstream||!a.acpSessionId)throw new _("BRIDGE_INTERNAL","session runtime not ready after ensureDownstream");let c=n._meta?.cozeTriggerMsgId;c?e.activeTriggers.set(a.acpSessionId,c):e.activeTriggers.delete(a.acpSessionId);let l=yh(n._meta);if(l?e.activeGroupIds.set(a.acpSessionId,l):e.activeGroupIds.delete(a.acpSessionId),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Af(s.prompt))throw new _("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let d=await bf(s.prompt);try{let p=await a.downstream.sessionPrompt({...s,sessionId:a.acpSessionId,prompt:d});return a.lastActiveAt=Date.now(),p}finally{if(e.activeTriggers.delete(a.acpSessionId),e.activeGroupIds.delete(a.acpSessionId),a.reloadAfterTurn){a.reloadAfterTurn=!1;let p=a.downstream;p&&(a.downstream=void 0,C.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:o,acpId:a.acpSessionId}),p.stop("reload-after-turn").catch(m=>C.warn("reload-after-turn stop failed (ignored)",{agentId:e.agentId,cloudId:o,err:String(m)})))}else a.downstream?.isAlive()&&this.armIdleTimer(e,o,a)}}case"session/cancel":{let o=i.sessionId;if(!o)throw new _("IPC_BAD_REQUEST","session/cancel: missing sessionId");let a=e.sessions.get(o);if(e.hasSessionQueue(o)){let c=e.getSessionQueue(o);c.size>0&&(C.info("session/cancel: draining queued tasks",{agentId:e.agentId,cloudId:o,queuedCount:c.size}),c.dispose(new _("AGENT_PROTOCOL_ERROR",`cancelled by session/cancel on ${o}`)))}return a?.downstream?.isAlive()&&a.acpSessionId&&await a.downstream.sessionCancel({sessionId:a.acpSessionId}),{ok:!0}}default:throw new _("IPC_BAD_REQUEST",`session method not supported: ${r}`)}}async ensureRuntime(e,r){let n=e.sessions.get(r);if(n)return n;let s={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,r):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(r,s),await this.persistSessionMapping(e),s}async requestSessionToken(e,r){let n={sessionId:r,_meta:{cozeAgentId:e}};try{let i=await this.sendRequest(He.GEN_MODEL_TOKEN,n,Z_);if(!i?.modelToken)throw new _("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${r})`);return i.modelToken}catch(i){throw i instanceof _&&i.code==="MODEL_TOKEN_GEN_FAILED"?i:new _("MODEL_TOKEN_GEN_FAILED",i instanceof Error?i.message:String(i),{cause:i})}}async ensureDownstream(e,r,n){if(Vn(n),n.downstream?.isAlive())return;if(!this.sessionSpawner)throw new _("AGENT_SPAWN_FAILED","sessionSpawner not wired (cannot spawn per-session downstream)");let i=3,s=3e4,o=n.spawnFailCount??0,a=n.spawnFailedAt??0;if(o>=i&&Date.now()-a<s)throw new _("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${r} spawn failed ${o} times in a row; please check framework binary / network and retry after ${Math.ceil((s-(Date.now()-a))/1e3)}s`);let c;try{c=await this.sessionSpawner(e,n.modelToken,r,this.currentCozeEnv,this.currentMockScenario)}catch(l){throw n.spawnFailCount=o+1,n.spawnFailedAt=Date.now(),n.spawnFailCount>=i&&n.acpSessionId&&(C.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:r,staleAcpId:n.acpSessionId}),n.acpSessionId=void 0),l}if(n.spawnFailCount=0,n.spawnFailedAt=void 0,n.downstream=c,this.attachRuntimeHooks(e,r,n),n.acpSessionId){n.loadingSession=!0;try{await c.sessionLoad({sessionId:n.acpSessionId,cwd:e.workspace}),C.info("session restored via session/load",{agentId:e.agentId,cloudId:r,acpId:n.acpSessionId})}catch(l){C.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:r,acpId:n.acpSessionId,err:String(l)}),n.acpSessionId=void 0;let d=await c.sessionNew({cwd:e.workspace});n.acpSessionId=d.sessionId,await this.persistSessionMapping(e)}finally{n.loadingSession=!1}}else{let l=await c.sessionNew({cwd:e.workspace});n.acpSessionId=l.sessionId,await this.persistSessionMapping(e)}c.afterSessionEstablished&&n.acpSessionId&&await c.afterSessionEstablished(n.acpSessionId)}armIdleTimer(e,r,n){if(Vn(n),this.isRuntimeBusy(e,n)){C.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:r});return}n.idleTimer=setTimeout(()=>{if(n.idleTimer=void 0,this.isRuntimeBusy(e,n)){C.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:r}),this.armIdleTimer(e,r,n);return}C.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:r});let i=n.downstream;n.downstream=void 0,n.acpSessionId&&e.activeTriggers.delete(n.acpSessionId),i&&i.stop("idle timeout").catch(s=>C.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:r,err:String(s)}))},this.sessionIdleTimeoutMs),n.idleTimer.unref?.()}isRuntimeBusy(e,r){if(r.acpSessionId&&e.activeTriggers.has(r.acpSessionId))return!0;let n=r.downstream;if(!n)return!1;for(let i of this.pendingUpstream.values())if(i.downstream===n)return!0;return!1}async sendAgentFileUpdate(e,r,n,i){let s={cozeAgentId:e.agentId,cozeReplySeqID:++r.replySeq};if(r.acpSessionId){let o=e.activeTriggers.get(r.acpSessionId);o&&(s.cozeTriggerMsgId=o);let a=e.activeGroupIds.get(r.acpSessionId);a&&(s.cozeGroupId=a)}await this.upstream.send(Wn("session/update",{sessionId:n,update:i,_meta:s}))}forwardUpdate(e,r){let n=r.sessionId,i=this.reverseSessionId(e,n);if(!i){C.debug("drop update for unknown session",{agentId:e.agentId,acpId:n});return}let s=e.sessions.get(i);if(!s){C.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:i});return}if(Q_(r)){C.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:n});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++s.replySeq},a=e.activeTriggers.get(n);a&&(o.cozeTriggerMsgId=a);let c=e.activeGroupIds.get(n);c&&(o.cozeGroupId=c),this.upstream.send(Wn("session/update",{...r,sessionId:i,_meta:o})).catch(l=>C.warn("forward update failed",{agentId:e.agentId,err:String(l)}))}handleAgentRequest(e,r,n){if(n.method==="session/request_permission"){this.forwardPermissionRequest(e,r,n);return}if(n.method==="fs/write_text_file"||n.method==="fs/read_text_file"){this.handleFsRpcRequest(e,r,n);return}C.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:n.method}),r.respondAgentRequestError(n.id,{code:L.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${n.method}`})}async handleFsRpcRequest(e,r,n){try{let i=e.workspace;if(n.method==="fs/write_text_file"){let s=n.params??{},o=await If(s,i);r.respondAgentRequest(n.id,o)}else{let s=n.params??{},o=await vf(s,i);r.respondAgentRequest(n.id,o)}}catch(i){C.warn("fs rpc handler failed",{agentId:e.agentId,method:n.method,err:String(i)}),r.respondAgentRequestError(n.id,Jn(i))}}forwardPermissionRequest(e,r,n){let i=this.upstreamIds.next("session/request_permission"),s=n.params??{},a=s.sessionId,c=a?e.activeTriggers.get(a):void 0,l={cozeAgentId:e.agentId};c&&(l.cozeTriggerMsgId=c);let d=a?e.activeGroupIds.get(a):void 0;d&&(l.cozeGroupId=d);let p=a?this.reverseSessionId(e,a):void 0,m={...s,...p?{sessionId:p}:{},_meta:l};this.pendingUpstream.set(i,{agentRequestId:n.id,agentId:e.agentId,downstream:r,method:n.method}),C.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:i,acpSessionId:a,cloudSessionId:p,toolCallId:s.toolCall?.toolCallId,options:s.options?.map(f=>({optionId:f.optionId,kind:f.kind,name:f.name}))}),this.upstream.send(jn(i,"session/request_permission",m)).catch(f=>{this.pendingUpstream.delete(i),C.error("forward permission request failed",{agentId:e.agentId,err:String(f)}),r.respondAgentRequestError(n.id,{code:L.INTERNAL_ERROR,message:`upstream send failed: ${String(f)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let r=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(r){this.pendingUpstream.delete(r.key);let i=r.value;e.error?(C.info("upstream \u2192 permission response (error)",{agentId:i.agentId,upstreamId:e.id,method:i.method,error:e.error}),i.downstream.respondAgentRequestError(i.agentRequestId,e.error)):(i.method==="session/request_permission"&&X_(e.result,i),C.info("upstream \u2192 permission response (result)",{agentId:i.agentId,upstreamId:e.id,method:i.method,result:e.result}),i.downstream.respondAgentRequest(i.agentRequestId,e.result));return}let n=this.lookupPending(this.pendingBridge,e.id,"bridge");if(n){this.pendingBridge.delete(n.key),clearTimeout(n.value.timer),e.error?n.value.reject(new Is(e.error)):n.value.resolve(e.result);return}C.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,r,n){let i=e.get(r);if(i)return{value:i,key:r};if(typeof r=="number"){let s=String(r),o=e.get(s);if(o)return C.warn(`${n} id type mismatch: number received but Bridge expected string`,{rawId:r,normalizedId:s}),{value:o,key:s}}}sendRequest(e,r,n=J_){let i=this.upstreamIds.next(e);return new Promise((s,o)=>{let a=setTimeout(()=>{this.pendingBridge.delete(i),o(new _("AGENT_TIMEOUT",`${e} timed out after ${n}ms`))},n);this.pendingBridge.set(i,{method:e,resolve:s,reject:o,timer:a}),this.upstream.send(jn(i,e,r)).catch(c=>{let l=this.pendingBridge.get(i);l&&(clearTimeout(l.timer),this.pendingBridge.delete(i)),o(c)})})}async persistSessionMapping(e){if(this.paths)try{let r=new Map;for(let[n,i]of e.sessions){let s={modelToken:i.modelToken,tokenGeneratedAt:i.tokenGeneratedAt};i.acpSessionId&&(s.acpSessionId=i.acpSessionId),r.set(n,s)}await fn(e.agentId,r,this.paths)}catch(r){C.warn("persist session mapping failed",{agentId:e.agentId,err:String(r)})}}reverseSessionId(e,r){for(let[n,i]of e.sessions.entries())if(i.acpSessionId===r)return n}sendError(e,r,n){return this.upstream.send(Bt(e,{code:r,message:n,data:{bridgeVersion:$r}}))}};function K_(){return q_(16).toString("hex")}function X_(t,e){if(!t||typeof t!="object"){C.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let r=t;if("kind"in r&&!("outcome"in r)){C.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let n=r.outcome;if(!n||typeof n!="object"){C.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let s=n.outcome;(typeof s!="string"||s!=="selected"&&s!=="cancelled")&&C.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:s,result:t})}function Q_(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let r=e.content;if(!r||typeof r!="object")return!1;let n=r;return n.type!=="text"||typeof n.text!="string"?!1:n.text.startsWith("Model metadata for `")}F();de();import{randomBytes as Y_}from"node:crypto";import{chmod as eE,mkdir as tE,writeFile as xf}from"node:fs/promises";import{createServer as rE}from"node:http";import{dirname as nE}from"node:path";var iE=1e6,Wa=x("ipc"),Fs=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(r=>[`${r.method} ${r.path}`,r])),this.paths=e.paths??M()}async start(){this.token=Y_(32).toString("hex");let e=rE((n,i)=>{this.dispatch(n,i)});this.server=e,await new Promise((n,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>n())});let r=e.address();if(!r||typeof r!="object")throw new Error("failed to obtain IPC port");return this.port=r.port,await this.persistAuthFiles(),Wa.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((r,n)=>{e.close(i=>i?n(i):r())}),this.server=null)}async persistAuthFiles(){await tE(nE(this.paths.portFile),{recursive:!0}),await xf(this.paths.portFile,String(this.port),"utf8"),await xf(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await eE(this.paths.tokenFile,384)}catch(e){Wa.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){Xn(r,401,{error:"unauthorized"});return}let i=`${e.method} ${(e.url??"").split("?")[0]}`,s=this.routes.get(i);if(!s){Xn(r,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await sE(e)}catch(a){Xn(r,400,{error:"invalid json",detail:String(a)});return}try{let a=await s.handler(o,e);Xn(r,200,a??{ok:!0})}catch(a){Wa.error("IPC handler failed",{key:i,err:String(a)}),Xn(r,500,{error:a instanceof Error?a.message:String(a)})}}};function Xn(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function sE(t){let e=[],r=0;for await(let i of t){let s=i;if(r+=s.length,r>iE)throw new Error("body too large");e.push(s)}let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):null}var Bf="";function wE(t=""){let r=`${Date.now()}`,n=Bf||(Bf=SE(t)),i=Math.random().toString(16).slice(-6);return"02"+r+n+i}function yE(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function _E(t){return(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8)}function Uf(t){return(Array(4).join("0")+parseInt(t,2).toString(16)).slice(-4)}function EE(t){let e=t.split(/\./).map(i=>_E(i)),r=[];return r[0]=Uf(e[0]+e[1]),r[1]=Uf(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",r[0],r[1]].join("")}function SE(t){let e=/(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(t),r=/(([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(t);return e?EE(t):r?IE(t):"00000000000000000000000000000000"}function IE(t){let e="",r=[],n=0,i=0,s=!0,o="0000";if(t.indexOf("::")>-1){let a=t.split("::");for(let l=0;l<a.length;l++){let d=a[l];if(d.indexOf(":")>0){let p=d.split(":");s&&(n=p.length),i+=p.length;for(let m=0;m<p.length;m++)if(p[m].length!==4){let u=o.substring(0,4-p[m].length).concat(p[m]);r.push(u)}else r.push(p[m]);s=!1}else{if(d.length!==4){let m=o.substring(0,4-d.length).concat(d);r.push(m)}else r.push(d);s&&(n+=1),i+=1,s=!1}}let c="";for(let l=0;l<8-i;l++)c=c.concat(o);for(let l=0;l<r.length;l++)l===n&&(e=e.concat(c)),e=e.concat(r[l]);return e}{let a=t.split(":");for(let c=0;c<a.length;c++){let l=a[c];if(a[c].length!==4){let p=o.substring(0,4-a[c].length).concat(l);e=e.concat(p)}else e=e.concat(l)}return e}}function vE(t,e){let r=t.key;r!==void 0&&(ue(e,10),lr(e,r));let n=t.value;n!==void 0&&(ue(e,18),lr(e,n))}function TE(t){let e={};e:for(;!Yf(t);){let r=Se(t);switch(r>>>3){case 0:break e;case 1:e.key=cr(t,Se(t));break;case 2:e.value=cr(t,Se(t));break;default:Kf(t,7&r)}}if(e.key===void 0)throw new Error("Missing required field: key");if(e.value===void 0)throw new Error("Missing required field: value");return e}function Zf(t){let e=Qf();return RE(t,e),PE(e)}function RE(t,e){let r=t.SeqID;r!==void 0&&(ue(e,8),Yn(e,r));let n=t.LogID;n!==void 0&&(ue(e,16),Yn(e,n));let i=t.service;i!==void 0&&(ue(e,24),Yn(e,Qa(i)));let s=t.method;s!==void 0&&(ue(e,32),Yn(e,Qa(s)));let o=t.headers;if(o!==void 0)for(let u of o){ue(e,42);let g=Qf();vE(u,g),ue(e,g.limit),NE(e,g),xE(g)}let a=t.payloadEncoding;a!==void 0&&(ue(e,50),lr(e,a));let c=t.payloadType;c!==void 0&&(ue(e,58),lr(e,c));let l=t.payload;l!==void 0&&(ue(e,66),ue(e,l.length),DE(e,l));let d=t.LogIDNew;d!==void 0&&(ue(e,74),lr(e,d));let p=t.serverTiming;p!==void 0&&(ue(e,82),lr(e,p));let m=t.msgID;m!==void 0&&(ue(e,90),lr(e,m));let f=t.frameType;f!==void 0&&(ue(e,96),Yn(e,Qa(f)))}function kE(t){return bE(OE(t))}function bE(t){let e={};e:for(;!Yf(t);){let r=Se(t);switch(r>>>3){case 0:break e;case 1:e.SeqID=$f(t,!0);break;case 2:e.LogID=$f(t,!0);break;case 3:e.service=Se(t);break;case 4:e.method=Se(t);break;case 5:{let n=AE(t);(e.headers||(e.headers=[])).push(TE(t)),t.limit=n;break}case 6:e.payloadEncoding=cr(t,Se(t));break;case 7:e.payloadType=cr(t,Se(t));break;case 8:e.payload=CE(t,Se(t));break;case 9:e.LogIDNew=cr(t,Se(t));break;case 10:e.serverTiming=cr(t,Se(t));break;case 11:e.msgID=cr(t,Se(t));break;case 12:e.frameType=Se(t);break;default:Kf(t,7&r)}}if(e.SeqID===void 0)throw new Error("Missing required field: SeqID");if(e.LogID===void 0)throw new Error("Missing required field: LogID");if(e.service===void 0)throw new Error("Missing required field: service");if(e.method===void 0)throw new Error("Missing required field: method");return e}function AE(t){let e=Se(t),r=t.limit;return t.limit=t.offset+e,r}function Kf(t,e){switch(e){case 0:for(;128&Le(t););break;case 2:Ya(t,Se(t));break;case 5:Ya(t,4);break;case 1:Ya(t,8);break;default:throw new Error("Unimplemented type: "+e)}}function Qa(t){return t|=0,{low:t,high:t>>31,unsigned:t>=0}}var Xf=[];function Qf(){let t=Xf.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function xE(t){Xf.push(t)}function OE(t){return{bytes:t,offset:0,limit:t.length}}function PE(t){let e=t.bytes,r=t.limit;return e.length===r?e:e.subarray(0,r)}function Ya(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function Yf(t){return t.offset>=t.limit}function ri(t,e){let r=t.bytes,n=t.offset,i=t.limit,s=n+e;if(s>r.length){let o=new Uint8Array(2*s);o.set(r),t.bytes=o}return t.offset=s,s>i&&(t.limit=s),n}function wc(t,e){let r=t.offset;if(r+e>t.limit)throw new Error("Read past limit");return t.offset+=e,r}function CE(t,e){let r=wc(t,e);return t.bytes.subarray(r,r+e)}function DE(t,e){let r=ri(t,e.length);t.bytes.set(e,r)}function cr(t,e){let r=wc(t,e),n=String.fromCharCode,i=t.bytes,s="\uFFFD",o="";for(let a=0;a<e;a++){let c=i[a+r],l,d,p,m;(128&c)===0?o+=n(c):(224&c)===192?a+1>=e?o+=s:(l=i[a+r+1],(192&l)!==128?o+=s:(m=(31&c)<<6|63&l,m<128?o+=s:(o+=n(m),a++))):(240&c)==224?a+2>=e?o+=s:(l=i[a+r+1],d=i[a+r+2],((l|d<<8)&49344)!==32896?o+=s:(m=(15&c)<<12|(63&l)<<6|63&d,m<2048||m>=55296&&m<=57343?o+=s:(o+=n(m),a+=2))):(248&c)==240?a+3>=e?o+=s:(l=i[a+r+1],d=i[a+r+2],p=i[a+r+3],((l|d<<8|p<<16)&12632256)!==8421504?o+=s:(m=(7&c)<<18|(63&l)<<12|(63&d)<<6|63&p,m<65536||m>1114111?o+=s:(m-=65536,o+=n((m>>10)+55296,(1023&m)+56320),a+=3))):o+=s}return o}function lr(t,e){let r=e.length,n=0;for(let o=0;o<r;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<r&&(a=(a<<10)+e.charCodeAt(++o)-56613888),n+=a<128?1:a<2048?2:a<65536?3:4}ue(t,n);let i=ri(t,n),s=t.bytes;for(let o=0;o<r;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<r&&(a=(a<<10)+e.charCodeAt(++o)-56613888),a<128?s[i++]=a:(a<2048?s[i++]=a>>6&31|192:(a<65536?s[i++]=a>>12&15|224:(s[i++]=a>>18&7|240,s[i++]=a>>12&63|128),s[i++]=a>>6&63|128),s[i++]=63&a|128)}}function NE(t,e){let r=ri(t,e.limit),n=t.bytes,i=e.bytes;for(let s=0,o=e.limit;s<o;s++)n[s+r]=i[s]}function Le(t){return t.bytes[wc(t,1)]}function zf(t,e){let r=ri(t,1);t.bytes[r]=e}function Se(t){let e=0,r=0,n;do n=Le(t),e<32&&(r|=(127&n)<<e),e+=7;while(128&n);return r}function ue(t,e){for(e>>>=0;e>=128;)zf(t,127&e|128),e>>>=7;zf(t,e)}function $f(t,e){let r=0,n=0,i=0,s;return s=Le(t),r=127&s,128&s&&(s=Le(t),r|=(127&s)<<7,128&s&&(s=Le(t),r|=(127&s)<<14,128&s&&(s=Le(t),r|=(127&s)<<21,128&s&&(s=Le(t),n=127&s,128&s&&(s=Le(t),n|=(127&s)<<7,128&s&&(s=Le(t),n|=(127&s)<<14,128&s&&(s=Le(t),n|=(127&s)<<21,128&s&&(s=Le(t),i=127&s,128&s&&(s=Le(t),i|=(127&s)<<7))))))))),{low:r|n<<28,high:n>>>4|i<<24,unsigned:e}}function Yn(t,e){let r=e.low>>>0,n=(e.low>>>28|e.high<<4)>>>0,i=e.high>>>24,s=i===0?n===0?r<16384?r<128?1:2:r<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:i<128?9:10,o=ri(t,s),a=t.bytes;switch(s){case 10:a[o+9]=i>>>7&1;case 9:a[o+8]=s!==9?128|i:127&i;case 8:a[o+7]=s!==8?n>>>21|128:n>>>21&127;case 7:a[o+6]=s!==7?n>>>14|128:n>>>14&127;case 6:a[o+5]=s!==6?n>>>7|128:n>>>7&127;case 5:a[o+4]=s!==5?128|n:127&n;case 4:a[o+3]=s!==4?r>>>21|128:r>>>21&127;case 3:a[o+2]=s!==3?r>>>14|128:r>>>14&127;case 2:a[o+1]=s!==2?r>>>7|128:r>>>7&127;case 1:a[o]=s!==1?128|r:127&r}}function LE(t){return kE(t)}function Gf(t){return Zf(t)}var Hf=65536,FE="\0\0\0\0\0\0\0\0",Vr=Hf*Hf,eu=Vr*Vr,jf=eu/2,$t=String.prototype.charCodeAt,xe=class t{constructor(e,r,n){this.isLong=!0,this.low=0|e,this.high=0|r,this.unsigned=!!n}static isLong(e){return e&&e.isLong===!0}static fromBits(e,r,n){return new t(e,r,n)}static fromBytes(e,r,n){return n?t.fromBytesLE(e,r):t.fromBytesBE(e,r)}static fromBytesLE(e,r){return new t(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,r)}static fromBytesBE(e,r){return new t(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],r)}static fromHash(e){return e===FE?Wf:new t(($t.call(e,0)|$t.call(e,1)<<8|$t.call(e,2)<<16|$t.call(e,3)<<24)>>>0,($t.call(e,4)|$t.call(e,5)<<8|$t.call(e,6)<<16|$t.call(e,7)<<24)>>>0,!0)}toHash(){return String.fromCharCode(255&this.low,this.low>>>8&255,this.low>>>16&255,this.low>>>24,255&this.high,this.high>>>8&255,this.high>>>16&255,this.high>>>24)}static fromNumber(e,r=!0){if(isNaN(e))return r?ME:Wf;if(r){if(e>=eu)return UE}else{if(e<=-jf)return zE;if(e+1>=jf)return BE}return t.fromBits(e%Vr|0,e/Vr|0,r)}toNumber(){return this.unsigned?(this.high>>>0)*Vr+(this.low>>>0):this.high*Vr+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){t.isLong(e)||(e=t.fromNumber(e));let r=this.high>>>16,n=65535&this.high,i=this.low>>>16,s=65535&this.low,o=e.high>>>16,a=65535&e.high,c=e.low>>>16,l=65535&e.low,d=0,p=0,m=0,f=0;return f+=s+l,m+=f>>>16,f&=65535,m+=i+c,p+=m>>>16,m&=65535,p+=n+a,d+=p>>>16,p&=65535,d+=r+o,d&=65535,t.fromBits(m<<16|f,d<<16|p,this.unsigned)}equals(e){return t.isLong(e)||(e=t.fromNumber(e)),this.unsigned!==e.unsigned&&this.high>>>31===1&&e.high>>>31===1?!1:this.high===e.high&&this.low===e.low}addOne(){return this.low===-1&&this.high===-1?t.fromBits(0,0,this.unsigned):this.low===-1?t.fromBits(0,this.high+1,this.unsigned):t.fromBits(this.low+1,this.high,this.unsigned)}toBytes(e){return e?this.toBytesLE():this.toBytesBE()}toBytesLE(){let e=this.high,r=this.low;return[255&r,r>>>8&255,r>>>16&255,r>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){let e=this.high,r=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,r>>>24,r>>>16&255,r>>>8&255,255&r]}},Wf=new xe(0,0,!1),ME=new xe(0,0,!0),BE=xe.fromBits(-1,2147483647,!1),UE=xe.fromBits(-1,-1,!0),zE=xe.fromBits(0,-2147483648,!1),ar=(function(t){return t[t.NATIVE_ERROR=5001]="NATIVE_ERROR",t[t.CONNECTING_ERROR=5002]="CONNECTING_ERROR",t[t.MAX_RETRIES_ERROR=5003]="MAX_RETRIES_ERROR",t[t.MESSAGE_ERROR=5004]="MESSAGE_ERROR",t[t.OPEN_ERROR=5005]="OPEN_ERROR",t})({}),dr=class{constructor(e){this.type=e,this.target=null}},tc=class extends dr{constructor(e,r){super(e),this.message=r&&r.message||null}},rc=class extends dr{constructor(e,r){super(e),this.error=r&&r.error||null,this.colno=r&&r.colno||0,this.filename=r&&r.filename||"",this.lineno=r&&r.lineno||0,this.message=r&&r.message||"",this.code=r&&r.code||5001}},nc=class extends dr{constructor(e,r){super(e),this.code=r&&r.code||0,this.reason=r&&r.reason||"",this.wasClean=r&&r.wasClean||!1,this.willReconnect=r&&r.willReconnect||!1}},ic=class extends dr{constructor(e,r){super(e),this.data=r&&r.data||null}},sc=class extends ic{constructor(e,r){super(e),this.data=r&&r.data||null,this.message=r&&r.message||null}},oc=class extends dr{constructor(e,r){super(e),this.data=r&&r.data||null}};function je(t,{message:e,code:r,error:n}){return new rc(t,{message:e,code:r,error:n})}function st(t,{code:e,reason:r,wasClean:n,willReconnect:i}){return new nc(t,{code:e,reason:r,wasClean:n,willReconnect:i})}function $E(t,{data:e,message:r}){return new sc(t,{data:e,message:r})}function GE(t,{data:e}){return new oc(t,{data:e})}function qf(t,{message:e}){return new tc(t,{message:e})}var Ms=class{constructor(e,r){this.endpoints=e,this.maxRetries=r,this.currentIndex=0,this.currentEndpointTriesCount=0}resetEndpointConfig(){this.currentIndex=0,this.currentEndpointTriesCount=0}resetTries(){this.currentEndpointTriesCount=0}getCurrentEndpoint(){return this.endpoints[this.currentIndex]}getCurrentEndpointTriesCount(){return this.currentEndpointTriesCount}checkReachMaxTries(){return this.currentIndex>=this.endpoints.length||this.currentIndex===this.endpoints.length-1&&this.currentEndpointTriesCount===this.maxRetries}checkCurrentEndpointReachedMaxRetries(){return this.currentIndex==this.endpoints.length?!0:this.currentEndpointTriesCount>this.maxRetries}replaceBackupEndpointAndUpdateCount(){return this.currentEndpointTriesCount=1,this.currentIndex++,this.endpoints[this.currentIndex]}getCurrentEndpointAndUpdateCount(){return this.currentEndpointTriesCount++,this.getCurrentEndpoint()}},Kr=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",hr=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",ni=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",ei=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",HE=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,ti=class{constructor(){this._listeners={}}emit(e,...r){let n=this._listeners[e];if(n)n.slice().forEach(i=>i.fn.apply(i.ctx,r));else if(e==="error"&&!this.onerror){let i=r.length&&r[0];if(i instanceof Error)throw i;let s=new Error("Unhandled error."+(i?" ("+i.message+")":""));throw s.context=i,i}return this}off(e,r){if(e===void 0)this._listeners={};else if(r===void 0)this._listeners[e]=null;else{let n=this._listeners[e];if(n)for(let i=0;i<n.length;)n[i].fn===r?n.splice(i,1):++i}return this}on(e,r,n){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:r,ctx:n||this}),this}},ac=class extends ti{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,r,n){super(),this._socket=null,ni&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:r,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),hr&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:r,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let r=je("error",{message:this._formatErrorMessage(e)});this.emit("error",r);let n=st("close",{reason:this._formatErrorMessage(e)});this.emit("close",n)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",GE("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",st("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",$E("message",{...e}))}),this._socket.onError(e=>{this.emit("error",je("error",{...e,message:e.errMsg||""}))})}send(e){if(e instanceof Uint8Array){let r=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:r,fail:n=>{this.emit("error",je("error",{message:this._formatErrorMessage(n)}))}})}else this._socket&&this._socket.send({data:e,fail:r=>{this.emit("error",je("error",{message:this._formatErrorMessage(r)}))}})}close(e,r){this._socket&&this._socket.close({code:e,reason:r})}addEventListener(e,r){this.on(e,r)}removeEventListener(e,r){this.off(e,r)}get readyState(){return this._socket.readyState}get binaryType(){return this._socket.binaryType}set binaryType(e){}get url(){return this._socket.url}get protocol(){return this._socket.protocol}get extensions(){return this._socket.extensions}get bufferedAmount(){return 0}};function jE(t,e){if(e)return new e(t.url,t.protocol);if(ni||hr)return new ac(t.url,t.protocol,t.headers);if((Kr||ei)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(t.url,t.protocols)}function WE(t){return!!(t||ni&&wx.connectSocket||hr&&tt.connectSocket||(Kr||ei)&&typeof WebSocket<"u"&&WebSocket)}function Jf(t,e,r){let n=-1;async function i(s){return s<=n?Promise.reject(new Error("next() called multiple times in process")):(n=s,s===r.length?Promise.resolve():r[s].bind(t)(e,i.bind(null,s+1)))}i(0)}function tu(t){let e=0,r=0;for(let n=0;n<t.length;++n)r=t.charCodeAt(n),r<128?e+=1:r<2048?e+=2:(64512&r)===55296&&(64512&t.charCodeAt(n+1))===56320?(++n,e+=4):e+=3;return e}function ru(t,e,r){if(r-e<1)return"";let n="";for(let i=e;i<r;){let s=t[i++];if(s<=127)n+=String.fromCharCode(s);else if(s>=192&&s<224)n+=String.fromCharCode((31&s)<<6|63&t[i++]);else if(s>=224&&s<240)n+=String.fromCharCode((15&s)<<12|(63&t[i++])<<6|63&t[i++]);else if(s>=240){let o=((7&s)<<18|(63&t[i++])<<12|(63&t[i++])<<6|63&t[i++])-65536;n+=String.fromCharCode(55296+(o>>10)),n+=String.fromCharCode(56320+(1023&o))}}return n}function cc(t,e,r){let n=r,i,s;for(let o=0;o<t.length;++o)i=t.charCodeAt(o),i<128?e[r++]=i:i<2048?(e[r++]=i>>6|192,e[r++]=63&i|128):(64512&i)===55296&&(64512&(s=t.charCodeAt(o+1)))===56320?(i=65536+((1023&i)<<10)+(1023&s),++o,e[r++]=i>>18|240,e[r++]=i>>12&63|128,e[r++]=i>>6&63|128,e[r++]=63&i|128):(e[r++]=i>>12|224,e[r++]=i>>6&63|128,e[r++]=63&i|128);return r-n}async function nu(t){if(typeof t=="string"){let e=new Uint8Array(tu(t));return cc(t,e,0),e}return t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function qE(t){try{return typeof t!="string"&&(t instanceof ArrayBuffer||t.buffer&&t.buffer instanceof ArrayBuffer)||typeof t!="string"?"":(JSON.parse(t),"application/json")}catch{return typeof t=="string"?"text/plain;charset=utf-8":""}}var JE=(t,e)=>{switch(t){case"boe":case"ppe":return{[`x-use-${t}`]:1,"x-tt-env":e};default:return{}}},lc=class{constructor(e){this.maxLossCount=e,this.count=0}addCount(){this.count++}checkReachMaxCount(){return this.count>=this.maxLossCount}resetCounter(e=0){this.maxLossCount=e,this.count=0}};async function VE(t){return new Promise(e=>{if(!Kr)return e("unknown reason");try{let r=document.createElement("script");window.frontierJSONP=n=>{document.body.removeChild(r),window.frontierJSONP=void 0,e(n&&n.msg||"unknown reason")},r.type="text/javascript",r.src=t.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(r)}catch{document.body.removeChild(r)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function Gt(t,e,r){return!!t?.find(n=>n.key===e&&n.value===r)}function Zr(t,e){return t?.find(r=>r.key===e)?.value}var ec=null;async function ZE(){return ec||(ec=Promise.resolve().then(()=>(Mf(),Ff))),ec}var dc=class extends ti{constructor(e,r){super(),this._dbName=e,this._keyPath=r,this._qosDB=void 0,this._initPromise=null}async openDB(){await this._init()}async _init(){if(!this._qosDB){if(this._initPromise)return this._initPromise;try{let e=this._dbName,r=this._keyPath;this._initPromise=(async()=>{let{openDB:n}=await ZE();this._qosDB=await n(`frontier_${e}`,1,{upgrade(i){i.createObjectStore(e,{keyPath:r})}})})(),await this._initPromise}catch(e){console.log(e)}finally{this._initPromise=null}}}async get(e){try{return await this._init(),this._qosDB?.get(this._dbName,e)}catch(r){console.log(r)}}async set(e,r){return await this._init(),this._qosDB?.put(this._dbName,e)}async del(e){try{return await this._init(),this._qosDB?.delete(this._dbName,e)}catch(r){console.log(r)}}async clear(){try{return await this._init(),this._qosDB?.clear(this._dbName)}catch(e){console.log(e)}}async keys(){return await this._init(),this._qosDB?.getAllKeys(this._dbName)}async getAll(){return await this._init(),this._qosDB?.getAll(this._dbName)}async closeDB(){try{this._qosDB?.close(),this._qosDB=void 0}catch(e){console.log(e)}}get isReady(){try{return!!this._qosDB}catch(e){return console.log(e),!1}}},hc=class{constructor(e,r){this._DBName=e,this._pathKey=r,this._qosDB=localStorage}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let r=this._qosDB.getItem(this._prefix);return JSON.parse(r||"{}")[e]}async set(e,r){let n=this._qosDB.getItem(this._prefix),i=JSON.parse(n||"{}");return i[r||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(i)),r||e[this._pathKey]}async del(e){let r=this._qosDB.getItem(this._prefix),n=JSON.parse(r||"{}");return n[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(n))}async clear(){return this._qosDB.clear()}async keys(){let e=this._qosDB.getItem(this._prefix),r=JSON.parse(e||"{}");return Object.keys(r)}async getAll(){let e=this._qosDB.getItem(this._prefix),r=JSON.parse(e||"{}");return Object.values(r)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}},fc=class{constructor(e,r){this._DBName=e,this._pathKey=r,this._qosDB=hr?tt:ni?wx:null}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let r=this._qosDB.getStorageSync(this._prefix);return JSON.parse(r||"{}")[e]}async set(e,r){let n=this._qosDB.getStorageSync(this._prefix),i=JSON.parse(n||"{}");return i[r||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(i)),r||e[this._pathKey]}async del(e){let r=this._qosDB.getStorageSync(this._prefix),n=JSON.parse(r||"{}");return n[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(n))}async clear(){return this._qosDB.clearStorageSync()}async keys(){let e=this._qosDB.getStorageInfoSync(this._prefix),r=JSON.parse(e||"{}");return Object.keys(r)}async getAll(){let e=this._qosDB.getStorageInfoSync(this._prefix),r=JSON.parse(e||"{}");return Object.values(r)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}};function iu(t,e){if(hr||hr)return new fc(t,e);if((Kr||ei)&&typeof indexedDB<"u")return new dc(t,e);if((Kr||ei)&&typeof localStorage<"u")return new hc(t,e);throw new Error("init QoSDB failed")}var uc=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=iu("qos","message_id")}async _intervalFlush(){clearInterval(this._intervalTimeoutId),this._intervalTimeoutId=setInterval(()=>{this.flushExpired()},this._interval)}async openDB(){await this._qosDB.openDB().then(()=>{this._intervalFlush()})}async flushExpired(){(await this._qosDB?.getAll()||[]).filter(({timestamp:n})=>n<Date.now()).forEach(n=>{this._qosDB?.del(n.message_id)})}async del(e){return this._qosDB?.del(e)}async set(e,r){return this._qosDB?.set({message_id:e,timestamp:r})}async get(e){return this._qosDB?.get(e)}async closeDB(){clearInterval(this._intervalTimeoutId),await this._qosDB?.closeDB()}get isReady(){return this._qosDB?.isReady}};function yc(t){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let r=Gt(t.message.headers,"x_frontier_qos","2"),n=r&&Gt(t.message.headers,"x_frontier_qos_ack","1"),i=r&&Gt(t.message.headers,"x_frontier_is_ack","1"),s=i?Zr(t.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:r,isQoSAck:n,isAckCleanupMessage:i,ackMsgIds:s}}async function su(){return this._QoSManager||(this._QoSManager=new uc),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function KE(t,e){let{enableAutoAck:r}=this._options,n=Gt(t.message.headers,"need_ack","1"),i=Gt(t.message.headers,"is_ack","1"),s=yc.call(this,t);if(r&&n){let{SeqID:o,LogID:a,service:c,LogIDNew:l,method:d}=t.message;this._sendAck({SeqID:o,LogID:a,LogIDNew:l,service:c,method:d,headers:[{key:"is_ack",value:"1"},{key:"ack_id",value:l||""},{key:"ack_code",value:"0"}]})}i&&!s.isQoSAck&&this._dispatchAckMessageEvent(t),e()}async function XE(t,e){this._debug("received",t.message),e()}async function QE(t,e){let r=LE(await nu(t.data));try{if(r.payload instanceof Uint8Array){let n=this._options.payloadEncoding instanceof Object?{force:!!this._options.payloadEncoding.force,encoding:this._options.payloadEncoding.encoding?this._options.payloadEncoding.encoding.replace(/\s/g,"").toLowerCase():""}:{force:!1,encoding:this._options.payloadEncoding?this._options.payloadEncoding.replace(/\s/g,"").toLowerCase():""},i=r.payloadEncoding?r.payloadEncoding.replace(/\s/g,"").toLowerCase():"",s=this._options.payloadType instanceof Object?{force:!!this._options.payloadType.force,type:this._options.payloadType.type?this._options.payloadType.type.replace(/\s/g,"").toLowerCase():""}:{force:!1,type:this._options.payloadType?this._options.payloadType.replace(/\s/g,"").toLowerCase():""},o=r.payloadType?r.payloadType.replace(/\s/g,"").toLowerCase():"",a=s.force?s.type:o||s.type,c=n.force?n.encoding:i||n.encoding,l=["text/plain;charset=utf-8","application/json","application/json;charset=utf-8","string"],d=["none_none","binary"];this._options.enableTransformTextPayload&&l.includes(a)&&(!c||d.includes(c))?r.textPayload=ru(r.payload,0,r.payload.byteLength):r.textPayload=""}else r.textPayload=""}catch(n){r.textPayload="",console.log(n)}t.message=r,e()}function YE(t,e,r){let n=r||8192,i=n>>>1,s=null,o=n;return function(a){if(a<1||a>i)return t(a);o+a>n&&(s=t(n),o=0);let c=e.call(s,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var e0=4294967295;function t0(t,e,r){if(r>e0)throw new Error("integer too large");let n=3;for(;n>=0;){let i=255&r;gc(i,t,e+n),r>>>=8,n--}return e+4}function r0(t,e){let r=0,n=e,i=e+4;for(;n<i;){let{value:s,offset:o}=pc(t,n);n=o,r=r<<8>>>0,r+=s}return{value:r,offset:i}}function n0(t,e,r){return t?t.length<40?cc(t,e,r)+r:e.utf8Write?e.utf8Write(t,r)+r:e.write?e.write(t,r)+r:cc(t,e,r)+r:r}function i0(t,e){let r=new xe(t[e+4]<<24|t[e+5]<<16|t[e+6]<<8|t[e+7],t[e+0]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3],!0);return e+=8,{value:r,offset:e+8}}function s0(t,e,r){let n=t.low,i=t.high;return e[r]=i>>>24,e[r+1]=i>>>16&255,e[r+2]=i>>>8&255,e[r+3]=255&i,e[r+4]=n>>>24,e[r+5]=n>>>16&255,e[r+6]=n>>>8&255,e[r+7]=255&n,r+=8,r}function pc(t,e){return t.readUInt8?{value:t.readUInt8(e),offset:e+1}:{value:255&t[e],offset:e+1}}function gc(t,e,r){return e.writeUint8?e.writeUint8(t,r):e[r]=255&t,r+1}var o0=function(t){return new Uint8Array(t)},a0=typeof Buffer<"u"?Buffer.allocUnsafe:YE(o0,Uint8Array.prototype.subarray),c0=16,_c=32;function l0(t){let e=0,r={};for(let n=0;n<t.length;n++)r[t[n].cursor_name]=tu(t[n].cursor_name),e+=14+r[t[n].cursor_name];return[e,r]}function Vf(t,e,r){let[n,i]=l0(t),s=a0(n),o=0;return t.forEach(a=>{console.log("cursor.service",a,a.service),o=gc(0,s,o),console.log("header",o),o=t0(s,o,a.service||0),console.log("service",o),o=gc(i[a.cursor_name],s,o),console.log("service-name",o),o=n0(a.cursor_name,s,o),console.log("name",o),o=s0(xe.fromNumber(a.cursor||e),s,o),console.log("curvalue",o)}),{frameType:_c,headers:[{key:"cursor_file_name",value:r}],payload:s}}function d0(t){let e=0,r=[];for(;e<t.byteLength;){let{offset:n}=pc(t,e);e=n;let i={cursor_name:"",cursor:0,service:0},{value:s,offset:o}=r0(t,e);i.service=s,e=o;let{value:a,offset:c}=pc(t,e);e=c,i.cursor_name=ru(t,e,e+a),e+=a;let{value:l,offset:d}=i0(t,e);i.cursor=l.toNumber(),e=d,r.push(i)}return r}function h0(){return{frameType:_c,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var mc=class{constructor(e,r,n){this._cursorNameSpace=e,this._cursorFileName=r,this._messageStrategy=n,this._qosDB=iu(this._cursorNameSpace,"cursor_name")}async openDB(){await this._qosDB.openDB()}async getCursors(){if(!this._qosDB.isReady)return;let e=this._messageStrategy,r=await this._qosDB.getAll();switch(console.log("allCursorValues",r),e){case"ALL":return r&&r.length?Vf(r,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return r&&r.length?Vf(r,0,this._cursorFileName):h0()}}async set(e,r,n){return console.log("setdb",e,r,n),this._qosDB.set({cursor_name:e,cursor:r,service:n})}async setCursors(e){let r=d0(e);for(let n of r)console.log("setcursor",r),await this._qosDB.set(n)}async get(e){return(await this._qosDB.get(e))?.cursor}async closeDB(){await this._qosDB.closeDB()}updateCursorFileName(e){this._cursorFileName=e}get isReady(){return this._qosDB.isReady}},f0="__x_msg_qos__";async function ou(t){if(!this._options.enableQoS)return null;let{aID:e,fpID:r,messageStrategy:n}=this._options,i=t||f0;try{return this._cursorManager?t&&this._cursorManager.updateCursorFileName(t):this._cursorManager=new mc(`${r}_${e}_${i}`,i,n),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function u0(t,e){let r=Gt(t.message.headers,"code","-1"),n=Gt(t.message.headers,"is_ack","1"),i=Zr(t.message.headers,"x_frontier_msgid"),s=Number(Zr(t.message.headers,"x_frontier_ttl"))||0,o=yc.call(this,t),a=Gt(t.message.headers,"x-msg-qos","2"),c=Zr(t.message.headers,"x-msg-cursor_name"),l=Number(Zr(t.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await su.call(this):null;if(t.message.service>0&&n&&!r||t.message.service>0){if(i&&o.isQoSMessage&&d)return await d.get(i)||(this._dispatchMessageEvent(t),await d.set(i,Date.now()+s)),e();if(a){let p=await ou.call(this);if(!p)return this._dispatchMessageEvent(t),e();let m=await p.get(c)??-1;if(m<l)this._dispatchMessageEvent(t),p.set(c,l,t.message.service);else throw new Error(`recevied message cursor ${l} larger than local cursor ${m}`);return e()}return this._dispatchMessageEvent(t),e()}}async function p0(t,e){let r=yc.call(this,t);if(!r.isQoSMessage)return e();let n=await su.call(this);if(r.isAckCleanupMessage&&r.ackMsgIds.length)for(let i of r.ackMsgIds)await n.del(i);e()}async function g0(t,e){let r=t.message.frameType===c0,n=t.message.frameType===_c;if(!r&&!n)return e();let i=Zr(t.message.headers,"cursor_file_name");if(!i)return e();let s=await ou.call(this,i);if(!s)return e();if(r){let o=await s.getCursors(),a={frameType:o?.frameType,SeqID:xe.fromNumber(this._seqId++),LogID:xe.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=Zf(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(n){let o=t.message.payload;o&&s.setCursors(o)}}var m0=async function(t,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},w0=async function(t,e){let r=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${r}`),e()},y0=async function(t,e){if(!this._ws||this._ws.readyState!==this.OPEN)return e();let{pingInterval:r}=this._options;this._endpointManager?.resetEndpointConfig();for(let i=0;i<this._messageQueue.length;i++){let s=this._messageQueue[i];if(this._ws.readyState===this.OPEN&&s!==null)this._ws&&this._ws.send(s),this._messageQueue[i]=null;else break}this._messageQueue=this._messageQueue.filter(i=>!!i),this._pingPongTimeoutId=setTimeout(()=>this._ping(),r),this._dispatchOpenEvent(t),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let n=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${n} success`),e()},Bs=class extends ti{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=Kr,this._isNode=HE,this._isMiniTT=hr,this._isMiniWX=ni,this._isWorker=ei,this._messageQueue=[],this._endpointManager=null,this._readyClosed=!1,this._binaryType="arraybuffer",this._connectLock=!1,this._connectionTimeoutId=null,this._reconnectTimeoutId=null,this._pingPongTimeoutId=null,this._seqId=0,this._isInit=!1,this._url="",this._QoSManager=null,this._cursorManager=null,this._pingLossCounter=null,this._protocols="pbbp2",this.CLOSED=3,this.CONNECTING=0,this.OPEN=1,this.CLOSING=2,this._onOpen=s=>{try{Jf(this,s,[m0,y0,w0])}catch(o){let a=je("error",{message:o.message,code:ar.OPEN_ERROR,error:o});this._dispatchErrorEvent(a)}},this._onMessage=async s=>{let{pingInterval:o,pingFrequency:a}=this._options;if((s.data==="hi"&&a==="always"||a==="auto")&&(this._clearPingTimer(),this.emit("ping_once_success","success"),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),o)),s.data!=="hi")try{Jf(this,s,[QE,KE,p0,g0,u0,XE])}catch(c){let l=je("error",{message:c.message,code:ar.MESSAGE_ERROR,error:c});this._dispatchErrorEvent(l)}},this._onError=s=>{let o=this._endpointManager?.checkReachMaxTries(),a=this._endpointManager?.getCurrentEndpoint();if(o&&!s.message){let c=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(je("error",{message:c,code:ar.MAX_RETRIES_ERROR,error:s}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(je("error",{message:s.message,code:ar.NATIVE_ERROR,error:s}))},this._onClose=async s=>{this._clearTimer(),this._clearPingTimer(),this._removeWsListeners(),this._ws=null,this._connectLock=!1;let o=this._endpointManager?.checkReachMaxTries();if(!o&&this._navigatorOnline()&&!this._readyClosed){let a=this._endpointManager?.getCurrentEndpoint(),c=this._options.reconnectInterceptor(s.code,s.reason);this._dispatchCloseEvent(st("close",{code:1006,reason:s.reason||`connecting failed, unknown reason, hostname: ${a}`,willReconnect:c})),c&&this._connect();return}if(s.code!==1e3&&this._readyClosed){this._dispatchCloseEvent(st("close",{code:1e3,reason:"bye"})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&o){let a=this._endpointManager?.getCurrentEndpoint(),c=s.reason;c||(c=await VE(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(st("close",{code:s.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(je("error",{message:l,code:ar.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&!s.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(st("close",{code:s.code,reason:`connecting failed, unknown reason, hostname: ${a}`})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}this._dispatchCloseEvent(s),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()},this.onclose=null,this.onerror=null,this.onmessage=null,this.onopen=null,this.onStartReconnect=null,this.onReceiveAck=null,this.onStopImmediatelyReconnect=null,this._handleOnLine=this._handleOnLine.bind(this),this._handleOffLine=this._handleOffLine.bind(this),this._handlePageHide=this._handlePageHide.bind(this),this._handlePageShow=this._handlePageShow.bind(this),this._options={url:"",automaticOpen:!0,initReconnectInterval:1e3,maxReconnectInterval:1e4,reconnectIntervalGrowFactor:2,timeoutInterval:5e3,maxRetries:5,debug:!1,maxMessageQueueLength:1/0,service:0,logIDGenerator:yE,headers:void 0,payloadEncoding:"",payloadType:"",fpID:"",deviceID:"",accessKey:"",ttwID:"",bddID:"",aID:"",disableAutoReconnect:!1,customParams:{},pingInterval:15e3,pingTimeoutInterval:4e3,pingFrequency:"auto",pingLossCount:2,enableTransformTextPayload:!1,logIDNewConfig:{enableAutoGenerateLogIDNew:!1,userIp:""},miniProgramParams:{customHttpHeader:{}},enableAutoAck:!1,reconnectInterceptor:()=>!0,enableQoS:!1,QoSLevel:2,messageStrategy:"CONTINUE",env:{xTTEnv:"",xUseEnv:""},listenNetworkChanged:!0};let{url:r,ws:n}=e,i=Array.isArray(r)?r:typeof r=="string"?[r]:[];if(!i||i.length===0)throw new Error("please provide valid url");if(!WE(n))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new Ms(i,this._options.maxRetries),this._pingLossCounter=new lc(this._options.pingLossCount),this._options.automaticOpen&&(this._isInit=!0,this._connect()),this._options.listenNetworkChanged&&(this._isMiniTT||this._isMiniWX?this._onPageNetWorkChange():this._isBrowser&&this._initGlobalEventListener())}_handleOnLine(){this._options.disableAutoReconnect||this._readyClosed||this._handleReconnect()}_handleOffLine(){this._destroyWebSocket();let e=qf("reconnect",{message:"stop immediately reconnect"});this.onStopImmediatelyReconnect&&this.onStopImmediatelyReconnect(e)}_initGlobalEventListener(){this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine),this._isBrowser&&window.addEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.addEventListener("pageshow",this._handlePageShow)}_dropGlobalEventListener(){this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine),this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow)}_handlePageHide(e){e.persisted||(this._isBrowser&&window.removeEventListener("pagehide",this._handlePageHide),this._isBrowser&&window.removeEventListener("pageshow",this._handlePageShow),this.close()),this._isBrowser&&window.removeEventListener("online",this._handleOnLine),this._isBrowser&&window.removeEventListener("offline",this._handleOffLine)}_handlePageShow(e){e.persisted&&(this._navigatorOnline()&&(!this._ws||this._ws.readyState!==this.OPEN||this._ws.readyState!==this.CONNECTING)&&this._handleOnLine(),this._isBrowser&&window.addEventListener("online",this._handleOnLine),this._isBrowser&&window.addEventListener("offline",this._handleOffLine))}async _generateUrl(e){let{fpID:r,deviceID:n,bddID:i,ttwID:s,accessKey:o,aID:a,customParams:c={},enableAutoAck:l,enableQoS:d,QoSLevel:p,env:m}=this._options,f,u,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(f=location&&location.protocol=="https:"?"wss://":"ws://",u=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${f}${u}`):(f="wss://",u=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(u)?u:`${f}${u}`);let w=i?"bd_did":s?"ttwid":"device_id",E=i||s||n;if(!E||!w)throw new Error("please provide bddID, deviceID or ttwID");let v=typeof c=="function"?await c():c,h=m?JE(m.xUseEnv,m.xTTEnv):{},y=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:r,aid:a,[w]:E,xsack:l?1:0,xaack:l?1:0,xsqos:d?1:0,qos_level:d?p:void 0,qos_sdk_version:2,...h},v),S=Object.keys(y).reduce((k,R)=>y[R]!==void 0?`${k}${k?"&":"?"}${R}=${y[R]}`:k,"");return`${g}/ws/v2${S}`}async _connect(){if(!(this._connectLock||this._readyClosed)){this._connectLock=!0;try{let e=this._endpointManager?.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:r}=this._options;if(e){let i=this._endpointManager?.getCurrentEndpoint(),s=this._endpointManager?.replaceBackupEndpointAndUpdateCount(),o=this._endpointManager?.getCurrentEndpointTriesCount();if(s){let a=`connect ${i} timeout, max retries reached, will use backup endpoint ${s} to retry`,c=je("error",{message:a,code:ar.MAX_RETRIES_ERROR});this._debug(a),this._dispatchErrorEvent(c),this._url=await this._generateUrl(s),this._debug(`connect ${s} ${o} times`),this._removeWsListeners()}else{let a=`connect ${i} timeout, max retries reached`;this._debug(a),this._dispatchErrorEvent(je("error",{message:a,code:ar.MAX_RETRIES_ERROR}));return}}else{let i=this._endpointManager?.getCurrentEndpointAndUpdateCount(),s=this._endpointManager?.getCurrentEndpointTriesCount();this._url=await this._generateUrl(i||""),this._debug(`connect ${i} ${s} times`),this._removeWsListeners()}if(this._isInit)this._isInit=!1;else{let i=qf("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(i)}let n=this._endpointManager?.getCurrentEndpointTriesCount()||0;n>1&&await this._wait(n-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=jE({url:this._url,protocols:[this._protocols],headers:this._options.miniProgramParams.customHttpHeader},this._options.ws),(this._isBrowser||this._isWorker)&&this._ws&&(this._ws.binaryType=this._binaryType),this._addWsListeners(),this._connectionTimeoutId=setTimeout(this._onTimeout.bind(this),r)}catch(e){throw this._connectLock=!1,e}}}_clearTimer(){clearTimeout(this._connectionTimeoutId),this._connectionTimeoutId=null}_clearPingTimer(){clearTimeout(this._pingPongTimeoutId),clearTimeout(this._reconnectTimeoutId),this._pingPongTimeoutId=null,this._reconnectTimeoutId=null}_debug(...e){this._options.debug&&console.log.apply(console,["FRONTIER>",...e])}_getIntervalValue(e){let{initReconnectInterval:r,maxReconnectInterval:n,reconnectIntervalGrowFactor:i}=this._options,s=r*Math.pow(i,e-1);return s>n?n:s}_ping(){if(this._ws&&this._ws.readyState===this.CONNECTING){this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);return}if(!this._ws||this._ws.readyState!==this.OPEN)return void this._handleReconnect();this._ws&&this._ws.send("hi"),this._reconnectTimeoutId=setTimeout(this._handleReconnectTimeout.bind(this),this._options.pingTimeoutInterval)}_handleReconnectTimeout(){this._pingLossCounter?.addCount(),this.emit("ping_once_timeout","timeout"),this._pingLossCounter?.checkReachMaxCount()?this._handleReconnect():this._ping()}_navigatorOnline(){return this._isMiniTT||this._isMiniWX?this._miniNavigatorOnline:(this._isBrowser||this._isWorker)&&this._options.listenNetworkChanged?navigator.onLine:!0}_handleReconnect(){!this._navigatorOnline()||this._readyClosed||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._ws?this._disconnect(1001,"going away, try reconnecting server",!0):this._connect())}_onPageNetWorkChange(){this._isMiniTT?tt.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()}):this._isMiniWX&&wx.onNetworkStatusChange(({isConnected:e})=>{this._miniNavigatorOnline=e,e?this._handleOnLine():this._handleOffLine()})}_wait(e){return new Promise(r=>{setTimeout(r,this._getIntervalValue(e))})}_disconnect(e=1e3,r="",n=!1){this._ws&&this._destroyWebSocket(e,r,n)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let r=Gf(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(r),this._debug("send_ack",e))}_removeWsListeners(){this._ws&&(this._ws.removeEventListener("open",this._onOpen),this._ws.removeEventListener("close",this._onClose),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("error",this._onError))}_addWsListeners(){this._ws&&(this._ws.addEventListener("open",this._onOpen),this._ws.addEventListener("close",this._onClose),this._ws.addEventListener("message",this._onMessage),this._ws.addEventListener("error",this._onError))}_wsInstanceClose(e=1e3,r=""){try{this._ws&&this._ws.close(e,r)}catch{}}_destroyWebSocket(e=1e3,r="",n=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,r),this._connectLock=!1,n&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let s=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(st("close",{code:1006,reason:`connect ${s} timeout, max retries reached`,wasClean:!0}))}else{let s=this._options.reconnectInterceptor(e,r);this._dispatchCloseEvent(st("close",{code:e,reason:r,wasClean:!0,willReconnect:s})),s&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(st("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(st("close",{code:1006,reason:"going away, network offline"})),this._ws=null,this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter()}_dispatchOpenEvent(e){this.emit("open",e),this.onopen&&this.onopen(e)}_dispatchMessageEvent(e){this.emit("message",e),this.onmessage&&this.onmessage(e)}_dispatchAckMessageEvent(e){this.emit("ack",e),this.onReceiveAck&&this.onReceiveAck(e)}_dispatchErrorEvent(e){this.emit("error",e),this.onerror&&this.onerror(e)}_dispatchCloseEvent(e){this.emit("close",e),this.onclose&&this.onclose(e)}get binaryType(){return this._ws?this._ws.binaryType:this._binaryType}set binaryType(e){this._binaryType=e,this._ws&&(this._ws.binaryType=e)}get retryCount(){return this._endpointManager?.getCurrentEndpointTriesCount()||0}get bufferedAmount(){return this._messageQueue.reduce((r,n)=>(r+=n&&n.byteLength||0,r),0)+(this._ws?this._ws.bufferedAmount:0)}get extensions(){return this._ws?this._ws.extensions:""}get protocol(){return this._ws?this._ws.protocol:""}get readyState(){return this._ws?this._ws.readyState:this._options.automaticOpen?this.CONNECTING:this.CLOSED}get url(){return this._ws?this._ws.url:this._url}close(e=1e3,r){if(this._readyClosed=!0,this._clearTimer(),this._clearPingTimer(),this._dropGlobalEventListener(),this._QoSManager?.closeDB(),!this._ws)return void this._debug("close, ws instance not initialized");if(this._ws.readyState===this.CLOSED||this._ws.readyState===this.CLOSING)return void this._debug("close, ws already closed");this._destroyWebSocket(e,r)}async send(e,r){if(e==null)throw new Error("please provide a valid data, data must be a string or an arraybuffer");typeof e=="number"&&(e=JSON.stringify(e)),typeof e!="string"&&!(e instanceof ArrayBuffer)&&!(e.buffer&&e.buffer instanceof ArrayBuffer)&&(e=JSON.stringify(e));let n=await nu(e),i=qE(e),{method:s=0,service:o=this._options.service,logID:a=this._options.logIDGenerator(),headers:c=this._options.headers,payloadEncoding:l=this._options.payloadEncoding,payloadType:d=this._options.payloadType,logIDNew:p=this._options.logIDNewConfig.enableAutoGenerateLogIDNew?wE(this._options.logIDNewConfig.userIp):""}=r||{};if(!o)throw new Error("please provide a valid service");let m={SeqID:xe.fromNumber(this._seqId++),LogID:xe.fromNumber(a),service:o,method:s,headers:c,payloadEncoding:l instanceof Object?l.encoding?l.encoding:"":l,payloadType:d instanceof Object?d.type?d.type:i:d||i,payload:n,LogIDNew:p},f=Gf(m);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(f),this._debug("sent",m)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(f),this._debug("enqueue",m)):(this._messageQueue.shift(),this._messageQueue.push(f)),{seqID:this._seqId,logID:a,logIDNew:p}}async reconnect(e){let{url:r}=e||{},n=Array.isArray(r)?r:typeof r=="string"?[r]:[];e&&Object.assign(this._options,e),n&&n.length?this._endpointManager=new Ms(n,this._options.maxRetries):this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(this._options.pingLossCount),this._readyClosed=!1,this._ws&&this._ws.readyState!==this.CLOSED?this._disconnect(1e3,"manual reconnecting",!0):(this._isInit=!0,this._connect())}async connect(){this._connectLock||(this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter(),this._readyClosed=!1,this._isInit=!0,this._connect())}addEventListener(e,r){this.on(e,r)}dispatchEvent(e){let{type:r}=e;this.emit(r,e)}removeEventListener(e,r){this.off(e,r)}pingOnce(){return new Promise((e,r)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);let n=()=>{e("success"),this.off("ping_once_success",n),this.off("ping_once_timeout",i)},i=()=>{r("timeout"),this.off("ping_once_success",n),this.off("ping_once_timeout",i)};this.on("ping_once_success",n),this.on("ping_once_timeout",i),this._ping()})}};var BS=lt(tp(),1),US=lt(Js(),1),zS=lt(Yr(),1),$S=lt(Oc(),1),GS=lt(Dc(),1),HS=lt(Uc(),1),dp=lt(Xs(),1),jS=lt(lp(),1);var hp=dp.default;_e();F();var ne=x("upstream.frontier"),up="application/json",pp="none",qS=15e3,hi=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:Ih,...Ur(this.opts.ppeOverride)};class r extends hp{constructor(u){super(u,Sh,{headers:e})}send(u,...g){if(il("debug"))try{let w;typeof u=="string"?w=Buffer.from(u,"utf8"):u instanceof Buffer?w=u:u instanceof ArrayBuffer?w=new Uint8Array(u):ArrayBuffer.isView(u)?w=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):w=new Uint8Array(0);let E=Buffer.from(w.slice(0,128)).toString("hex");ne.debug("WS raw frame out",{bytes:w.byteLength,headHex:E})}catch(w){ne.warn("WS raw frame dump failed",{err:String(w)})}super.send(u,...g)}}let n=Th(this.opts.urlOverride),i={url:n,ws:r,fpID:Eh,aID:_s,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:up,force:!0},payloadEncoding:{encoding:pp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},s=new Bs(i),o=!1,a=null,c,l,d=new Promise((f,u)=>{c=f,l=u}),p=f=>{o||(o=!0,a&&(clearTimeout(a),a=null),f?l(f):c())};s.onopen=()=>{this.opened=!0,this.openCount+=1;let f=this.openCount===1;ne.info("frontier opened",{url:n,remoteDeviceId:this.opts.handshake.deviceId,initial:f,openCount:this.openCount}),f&&p();for(let u of this.connectHandlers)Promise.resolve(u({initial:f})).catch(g=>ne.warn("onConnect handler threw (ignored)",{err:String(g)}))},s.onclose=f=>{this.opened=!1,ne.info("frontier closed",{code:f.code,reason:f.reason,willReconnect:f.willReconnect})},s.onerror=f=>{ne.warn("frontier error",{code:f.code,msg:f.message}),p(new _("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${f.code} msg=${f.message??""}`))},s.onmessage=f=>this.handleMessage(f),this.fws=s;let m=this.opts.openTimeoutMs??qS;a=setTimeout(()=>{p(new _("UPSTREAM_DISCONNECTED",`frontier ws open timeout after ${m}ms (handshake or upgrade slow)`))},m),await s.connect();try{await d}catch(f){try{s.close(1e3,"open failed")}catch(u){ne.warn("fws close during start failure threw (ignored)",{err:String(u)})}throw this.fws=null,this.opened=!1,f}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(n){ne.warn("frontier close threw (ignored)",{err:String(n)})}}}async send(e){let r=this.fws,n=e.method;if(!r)throw ne.warn("frontier send refused: upstream not started",{method:n}),new _("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let a=Date.now();throw a-this.lastSendRefusedLogAt>1e3?(ne.warn("frontier send refused: ws not open",{method:n,opened:this.opened,readyState:r.readyState,...this.sendRefusedSuppressed>0?{suppressedSinceLast:this.sendRefusedSuppressed}:{}}),this.lastSendRefusedLogAt=a,this.sendRefusedSuppressed=0):this.sendRefusedSuppressed+=1,new _("UPSTREAM_DISCONNECTED",`frontier ws not open (opened=${this.opened}, readyState=${r.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let i=JSON.stringify(e),s=e;gp(s)||ne.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:i.length});try{await r.send(i,{service:33555712,method:1,payloadType:up,payloadEncoding:pp})}catch(a){throw ne.warn("frontier frame send failed",{method:s.method,jsonrpcId:s.id,err:String(a)}),new _("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(a)}`,{cause:a})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let r=this.opts.getPatTokenForAgent;if(!r)return;let n=e.params?._meta;if(!n?.cozeAgentId)return;let i=r(n.cozeAgentId);i&&(n.cozePatToken=i)}handleMessage(e){let r=e.message?.service;if(r!==33555712){ne.debug("drop non-adapter frontier frame",{service:r});return}let n=ZS(e);if(!n){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:n.length});return}let i;try{i=JSON.parse(n)}catch(o){ne.warn("frontier message JSON parse failed",{err:String(o),head:n.slice(0,80)});return}let s=i;gp(s)||ne.info("frontier frame in",{logid:VS(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id,method:s.method,body:JS(n)}),Promise.resolve(this.handler(i)).catch(o=>ne.warn("frontier frame handler threw",{err:String(o)}))}};function gp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var mp=2e3;function JS(t){return t.length<=mp?t:`${t.slice(0,mp)}...<truncated, total ${t.length} chars>`}function VS(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function ZS(t){let e=t.message;if(e?.textPayload)return e.textPayload;let r=e?.payload;if(!r)return null;try{return Buffer.from(r).toString("utf8")}catch{return null}}F();var $c=x("upstream.switchable"),Ys=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;$c.info("swap upstream",{reason:r});let n=this.inner;if(this.inner=e,this.handler&&e.onFrame(this.handler),e.onConnect)for(let i of this.connectHandlers)e.onConnect(i);try{await e.start()}catch(i){throw $c.error("swap target start failed, reverting",{err:String(i)}),this.inner=n,i}await n.stop(r??"swapped").catch(i=>$c.warn("previous upstream stop threw (ignored)",{err:String(i)}))}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()}};F();var Gc=x("upstream"),on=class{handler=null;async start(){Gc.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Gc.info("NoopUpstream stopped",{reason:e})}async send(e){Gc.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)}};_e();F();F();de();import{promises as Hc}from"node:fs";import{dirname as KS}from"node:path";var XS=x("pat-token-store");async function wp(t=M()){try{let r=(await Hc.readFile(t.patTokenFile,"utf8")).trim();return r.length>0?r:null}catch(e){let r=e?.code;return r!=="ENOENT"&&XS.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function fi(t,e=M()){if(!t)throw new Error("writePatToken: empty patToken");await Hc.mkdir(KS(e.patTokenFile),{recursive:!0}),await Hc.writeFile(e.patTokenFile,t,{encoding:"utf8",mode:384})}de();de();import{promises as eo}from"node:fs";import{join as QS}from"node:path";function YS(t,e){return`#!/bin/sh
92
92
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
93
- `}function YS(t,e){return`@echo off\r
93
+ `}function eI(t,e){return`@echo off\r
94
94
  "${e}" "${t}" %*\r
95
- `}async function wp(t,e=M()){let r=e.binDir;await eo.mkdir(r,{recursive:!0});let n=XS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),i=process.execPath,s=process.platform==="win32"?YS(t,i):QS(t,i);return await eo.readFile(n,"utf8").catch(()=>null)===s||(await eo.writeFile(n,s,"utf8"),process.platform!=="win32"&&await eo.chmod(n,493)),r}F();de();import{execSync as yp}from"node:child_process";import{readFileSync as Ep,unlinkSync as eI}from"node:fs";import{mkdir as tI,readFile as Sp,unlink as Ip,writeFile as rI}from"node:fs/promises";import{dirname as nI}from"node:path";function _p(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var iI=O("single-instance"),to=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??M().pidFile,e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();return e!==null&&this.isAlive(e)?{kind:"already-running",pid:e}:(e!==null&&(iI.warn("removing stale pid file",{stalePid:e}),await Ip(this.pidFile).catch(()=>{})),await tI(nI(this.pidFile),{recursive:!0}),await rI(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Sp(this.pidFile,"utf8")).trim()===String(process.pid)&&await Ip(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Sp(this.pidFile,"utf8"),r=Number.parseInt(e.trim(),10);return Number.isFinite(r)&&r>0?r:null}catch(e){if(e.code==="ENOENT")return null;throw e}}isAlive(e){return _p(e)?this.matchesDaemonTitle(e):!1}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=Ep(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes("coze-bridge-daemon")||r.includes("lib/index.js"))}catch{}try{let r=yp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes("coze-bridge-daemon")||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let n=yp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!n||/^(INFO|信息)[::]/.test(n))return!1;let i=n.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return i.includes("node")||i.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Ep(this.pidFile,"utf8").trim()===String(process.pid)&&eI(this.pidFile)}catch{}})}};var x=O("daemon"),sI="coze-bridge-daemon";async function Tp(){let t=new to({processTitle:sI}),e=await t.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let r=await Ns(),n=r??{};_i({pid:process.pid}),x.info(r?"loaded bridge config":"initialized bridge config");try{let I=new zt;n.frameworksCache=await I.detectAll(),x.info("refreshed frameworks_cache",{detected:Object.keys(n.frameworksCache)})}catch(I){x.warn("framework detection failed",{err:String(I)})}await Jr(n);let i=new Ys(new on),s=M(),o=null,a=new Ls({upstream:i,paths:s,bridgeConfig:n,sessionSpawner:async(I,T,A,P)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(I,T,A,P)}});await aI(s,a);let c=new Ps({paths:s,config:n,registry:a});o=c;let l,d,p=null,m={},f,u=null;a.registerExtension("_agent/create",async I=>c.createAgent(I.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let g={},w=new Ss({agents:a.agents,disposeAndMarkDisconnected:async(I,T)=>{let A=a.agents.get(I);if(A){await c.cleanupOpenclawSessionProviders(A).catch(G=>x.warn("cleanup openclaw providers failed (ignored)",{agentId:I,err:String(G)}));let P=!0;try{await A.dispose(`disconnect: ${T}`)}catch(G){P=!1,x.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:I,err:String(G)}),A.status="error"}P&&(A.status="disconnected",a.unregister(I),a.disconnectedAgents.add(I))}else a.disconnectedAgents.add(I)},detailSyncer:async I=>{if(!g.ref)throw new Error("agent-detail-sync not initialized yet");await g.ref.syncOne(I)},cleanupOpenclawProviders:async I=>{await c.cleanupOpenclawSessionProviders(I)},openclawRepair:async(I,T)=>{await c.openclawRepair(I,T)},isRuntimePendingPermission:I=>a.hasPendingPermissionFor(I)});a.registerExtension("_agent/listSkills",I=>w.listSkills(I.params)),a.registerExtension("_agent/addSkills",I=>w.addSkills(I.params)),a.registerExtension("_agent/removeSkills",I=>w.removeSkills(I.params)),a.registerExtension("_agent/getFileTree",I=>w.getFileTree(I.params)),a.registerExtension("_agent/getFileContent",I=>w.getFileContent(I.params)),a.registerExtension("_agent/update",I=>w.updateAgent(I.params)),a.registerExtension("_agent/disconnect",I=>w.disconnectAgent(I.params)),a.registerExtension("_agent/switchModel",I=>w.switchModel(I.params)),a.registerExtension("_agent/reset",I=>w.resetAgent(I.params)),a.registerExtension("_agent/repair",I=>w.repairAgent(I.params));let E=new Ai({paths:s,handlers:w,sendDetail:I=>a.sendRequest("_agent/detail",I)});g.ref=E;let v=async I=>{await Promise.allSettled(I.map(async T=>{try{await w.disconnectAgent({agentId:T.agentId,reason:`auth_failure: code=${T.code} ${T.message}`}),x.info("agent disconnected due to auth failure from heartbeat response",{agentId:T.agentId,code:T.code,message:T.message})}catch(A){x.warn("disconnect during authFailure handling failed (ignored)",{agentId:T.agentId,err:String(A)})}}))};i.onConnect(({initial:I})=>{x.info("frontier upstream connected, triggering detail sync",{initial:I}),E.syncAll(I?"initial-connect":"reconnect").catch(T=>x.warn("detail sync top-level error (ignored)",{err:String(T)}))});let h=new Fs({paths:s,routes:[{method:"GET",path:"/status",handler:async()=>{let I=a.getMockScenario();return{running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:p??"",frameworksCache:n.frameworksCache??{},...I?{mockScenario:I}:{}}}},{method:"POST",path:"/pair",handler:async I=>{let T=I,A=T?.privatecode,P=T?.pairing_code;if(!A||!P)throw new y("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let G=$n(T.env),X=T.handshake_url,Pe=T.frontier_url,ot=vp(T.env,X,Pe),at=!!l&&l!==A,an=d!==void 0&&d!==ot,cn=at||an,pi=await Oa({privatecode:A,...X?{endpoint:X}:{},ppeOverride:G});if(cn){x.warn("pair config switched, resetting agents",{pcChanged:at,envChanged:an,previousPc:l?ro(l):"",nextPc:ro(A),previousEnvKey:d??"",nextEnvKey:ot});for(let _e of[...a.agents.values()])await _e.dispose("pair config switch").catch(()=>{}),a.agents.delete(_e.agentId);a.disconnectedAgents.size>0&&(x.info("clearing disconnectedAgents set on pair config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await i.swap(new on,"pair switch").catch(()=>{})}p=pi.deviceId,_i({deviceId:p,pid:process.pid}),Ha({patToken:A,env:T.env}).catch(_e=>x.warn("coze-cli setup error (ignored)",{err:String(_e)}));let ge=new hi({handshake:pi,privatecode:A,...Pe?{urlOverride:Pe}:{},ppeOverride:G,getPatTokenForAgent:_e=>a.agents.get(_e)?.patToken});await i.swap(ge,"pair");try{let _e=new zt;n.frameworksCache=await _e.detectAll(),await Jr(n),x.info("frameworks_cache refreshed before pair",{detected:Object.keys(n.frameworksCache)})}catch(_e){x.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(_e)})}let uo=Object.keys(n.frameworksCache??{});try{let _e=await a.sendRequest("_agent/pair",{pairCode:P,patToken:A,frameworks:uo,_meta:{cozeDeviceId:p}});x.info("_agent/pair ok",{pairResult:_e}),l=A,d=ot,m=G,f=X,T.mock_scenario!==void 0&&(a.setMockScenario(T.mock_scenario),x.info("mock scenario set",{scenario:T.mock_scenario})),fi(A,s).catch(qe=>x.warn("writePatToken after /pair failed (ignored)",{err:String(qe)})),u||(u=new Hn({core:a,getDeviceId:()=>p??"",onTickEnd:()=>E.retryPending().catch(qe=>x.warn("detailSync.retryPending failed (ignored)",{err:String(qe)})),onAuthFailures:v})),u.start(),cn&&no(s,c).catch(qe=>x.warn("post-pair-switch auto-revive error (ignored)",{err:String(qe)}));let po;return T.agent_id&&(po=await cI(T.agent_id,s,c,qe=>a.sendRequest("_agent/detail",qe),A).catch(qe=>(x.error("--agent-id ensureAgent failed",{agentId:T.agent_id,err:String(qe)}),{ok:!1,agentId:T.agent_id??"",note:String(qe)}))),{ok:!0,note:"paired with cloud",...po?{agent:po}:{}}}catch(_e){return x.error("_agent/pair failed",{err:String(_e)}),{ok:!1,note:`pair failed: ${String(_e)}`}}}},{method:"POST",path:"/connect",handler:async I=>{let T=I,A=T?.privatecode;if(!A)throw new y("IPC_BAD_REQUEST","/connect requires privatecode");let P=$n(T.env),G=T.handshake_url,X=T.frontier_url,Pe=vp(T.env,G,X);if(l===A&&d===Pe){let ge=await oI(s);return a.agents.size===0&&ge?(x.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),no(s,c).catch(uo=>x.warn("connect-noop auto-revive error (ignored)",{err:String(uo)}))):x.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let ot=!!l&&l!==A,at=d!==void 0&&d!==Pe,an=ot||at,cn=await Oa({privatecode:A,...G?{endpoint:G}:{},ppeOverride:P});if(an){x.warn("connect config switched, resetting agents",{pcChanged:ot,envChanged:at,previousPc:l?ro(l):"",nextPc:ro(A)});for(let ge of[...a.agents.values()])await ge.dispose("connect config switch").catch(()=>{}),a.agents.delete(ge.agentId);a.disconnectedAgents.size>0&&(x.info("clearing disconnectedAgents set on connect config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await i.swap(new on,"connect switch").catch(()=>{})}p=cn.deviceId,_i({deviceId:p,pid:process.pid}),Ha({patToken:A,env:T.env}).catch(ge=>x.warn("coze-cli setup error (ignored)",{err:String(ge)}));let pi=new hi({handshake:cn,privatecode:A,...X?{urlOverride:X}:{},ppeOverride:P,getPatTokenForAgent:ge=>a.agents.get(ge)?.patToken});return await i.swap(pi,"connect"),l=A,d=Pe,m=P,f=G,T.mock_scenario!==void 0&&(a.setMockScenario(T.mock_scenario),x.info("mock scenario set",{scenario:T.mock_scenario})),u||(u=new Hn({core:a,getDeviceId:()=>p??"",onTickEnd:()=>E.retryPending().catch(ge=>x.warn("detailSync.retryPending failed (ignored)",{err:String(ge)})),onAuthFailures:v})),u.start(),an&&no(s,c).catch(ge=>x.warn("post-connect-switch auto-revive error (ignored)",{err:String(ge)})),fi(A,s).catch(ge=>x.warn("writePatToken after /connect failed (ignored)",{err:String(ge)})),x.info("/connect: WS established",{deviceId:p}),{ok:!0,note:"connected"}}},{method:"POST",path:"/_agent/create",handler:async I=>{let T=I;return{ok:!0,result:await c.createAgent(T)}}},{method:"POST",path:"/agent/send",handler:async I=>{let T=I;if(!T?.agentId||!T?.sessionId||!T?.kind||!T?.path)throw new y("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!l)throw new y("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let A=T;return await(A.groupFile?ff:hf)(A,{core:a,patToken:l,handshakeBase:f,ppeOverride:m})}catch(A){if(A instanceof y)return{ok:!1,code:A.code,message:A.message};throw A}}},{method:"POST",path:"/refresh",handler:async()=>{x.info("IPC /refresh: re-detecting frameworks");let I=new zt;return n.frameworksCache=await I.detectAll(),await Jr(n),{ok:!0,frameworks:n.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(x.info("IPC /shutdown received"),setImmediate(()=>{R.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:_,token:S}=await h.start();try{await wp(s.libEntry,s)}catch(I){x.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(I)})}await a.start(),no(s,c).catch(I=>x.warn("auto-revive top-level error (ignored)",{err:String(I)})),pl().then(async()=>{let{probeAcpVersion:I}=await Promise.resolve().then(()=>(Wt(),fl));for(let T of["claude-code","codex"]){let A=await I(T);A&&x.info("acp wrapper version",{framework:T,version:A})}}).catch(I=>x.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(I)}));let k=null,R={port:_,token:S,core:a,ipc:h,shutdown(I){return k||(x.info("daemon shutdown",{reason:I}),k=(async()=>{u?.stop(),await a.stop(I),await h.stop(),await t.release()})(),k)}};for(let I of["SIGTERM","SIGINT"])process.on(I,()=>{R.shutdown(I).then(()=>process.exit(0))});return process.on("unhandledRejection",I=>{x.error("unhandledRejection",{reason:I instanceof Error?I.message:String(I),stack:I instanceof Error?I.stack:void 0})}),process.on("uncaughtException",I=>{x.error("uncaughtException (will exit, supervisor will restart)",{message:I.message,stack:I.stack,name:I.name}),process.exit(1)}),x.info("daemon ready",{port:_,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(n.frameworksCache??{}),libVersion:n.libVersion??"dev"}),R}async function oI(t){let{readdir:e}=await import("node:fs/promises");try{return(await e(t.agentsRoot)).length>0}catch{return!1}}function ro(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function vp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function aI(t,e){let{readdir:r}=await import("node:fs/promises"),n;try{n=await r(t.agentsRoot)}catch{return}let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(vt(),bi));for(let o of n){await s(o,t).catch(a=>x.warn("enforceAgentConfigMode failed (ignored)",{agentId:o,err:String(a)}));try{let a=await i(o,t);a?.disconnectedAt&&(e.disconnectedAgents.add(o),x.info("agent marked disconnected on startup",{agentId:o,disconnectedAt:a.disconnectedAt,reason:a.disconnectReason??""}))}catch(a){x.warn("failed to load agent config on startup, skipping",{agentId:o,err:String(a)})}}}async function cI(t,e,r,n,i){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(vt(),bi)),o=await s(t,e);if(o){x.info("--agent-id: local config found, reconnecting",{agentId:t,framework:o.framework,hadDisconnect:!!o.disconnectedAt});let d={agentId:o.agentId,framework:o.framework,...o.cozeIdentity?{cozeIdentity:o.cozeIdentity}:{},...o.model?{model:o.model}:{},...i?{patToken:i}:{}};return await r.createAgent(d),{ok:!0,agentId:t,note:o.disconnectedAt?"revived from local config":"connected from local config"}}x.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let a=await n({_meta:{cozeAgentId:t}});if(!a.framework)throw new y("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 c={agentId:a.agentId,framework:a.framework,...a.cozeIdentity?{cozeIdentity:a.cozeIdentity}:{},...a.model?{model:a.model}:{},...i?{patToken:i}:{},...a.deployType?{_meta:{cozeDeployType:a.deployType}}:{}};await r.createAgent(c);let l=a.deployType==="cloud"&&a.framework==="openclaw";return{ok:!0,agentId:t,note:l?"cloud agent acknowledged":"created from cloud detail"}}async function no(t,e){let{readdir:r}=await import("node:fs/promises"),n;try{n=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(n.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:i}=await Promise.resolve().then(()=>(vt(),bi));x.info("auto-revive: scanning local agents on startup",{count:n.length});let s=0,o=0;for(let a of n){let c;try{c=await i(a,t)}catch(l){x.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(l)}),o+=1;continue}if(!c){o+=1;continue}if(c.disconnectedAt){x.info("auto-revive: skip disconnected agent",{agentId:a,disconnectedAt:c.disconnectedAt}),o+=1;continue}try{x.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:a,framework:c.framework});let l=lI(c);await e.createAgent({agentId:c.agentId,framework:c.framework,...c.cozeIdentity?{cozeIdentity:c.cozeIdentity}:{},...c.model?{model:c.model}:{},...l?{_meta:l}:{}}),s+=1}catch(l){x.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(l)}),o+=1}}return x.info("auto-revive: done",{revived:s,skipped:o,total:n.length}),{revived:s,skipped:o,total:n.length}}function lI(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}qc();de();import{readFile as Rp}from"node:fs/promises";var St=class{paths;constructor(e){this.paths=e??M()}async probe(e=1e3){let r=await io(this.paths);if(!r)return{kind:"not-running"};try{let n=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return n.status===200?{kind:"connected",...r}:{kind:"stale",reason:`unexpected status ${n.status}`}}catch(n){return{kind:"stale",reason:wI(n)}}}async request(e){let r=await io(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let n=r.body!==void 0,i={Authorization:`Bearer ${e.token}`};n&&(i["content-type"]="application/json");let s=new AbortController,o=setTimeout(()=>s.abort(),r.timeoutMs??5e3);try{let a=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:i,body:n?JSON.stringify(r.body):void 0,signal:s.signal}),c=await a.text();return{status:a.status,body:mI(c)}}finally{clearTimeout(o)}}};async function io(t){try{let[e,r]=await Promise.all([Rp(t.portFile,"utf8"),Rp(t.tokenFile,"utf8")]),n=Number.parseInt(e.trim(),10),i=r.trim();return!Number.isFinite(n)||n<=0||!i?null:{port:n,token:i}}catch(e){if(e.code==="ENOENT")return null;throw e}}function mI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function wI(t){return t instanceof Error?t.message:String(t)}F();de();import{copyFile as kp,mkdir as _I,readFile as Jc,writeFile as yI}from"node:fs/promises";import{homedir as rx}from"node:os";import{dirname as EI,resolve as Vc,sep as so}from"node:path";import{fileURLToPath as SI}from"node:url";F();de();var bp=O("dist-install");function II(t){let e=SI(t),r=EI(e),n=`${so}src${so}`;if(r.includes(n)||r.endsWith(`${so}src${so}cli`))return null;let i=Vc(r,"index.js"),s=Vc(r,"..","package.json");return{dist:i,pkgJson:s}}async function Zc(t={}){let e=t.paths??M(),r=II(import.meta.url),n=t.sourceDist??r?.dist,i=t.sourcePackageJson??r?.pkgJson;if(!n||!i)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(n===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let s;try{s=JSON.parse(await Jc(i,"utf8")).version??"unknown"}catch(p){return bp.warn("cannot read source package.json,skip dist install",{err:String(p)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(p)}`}}let o=await Ns(e.configFile)??{},a=o.libVersion;if(a===s)try{return await Jc(e.libEntry),{kind:"already-current",libVersion:s}}catch{}await _I(e.libDir,{recursive:!0}),await kp(n,e.libEntry),await kp(`${n}.map`,`${e.libEntry}.map`).catch(()=>{});let c=Vc(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
96
- `;return await Jc(c,"utf8").catch(()=>null)!==l&&await yI(c,l),o.libVersion=s,await Jr(o,e.configFile),bp.info("dist installed",{libEntry:e.libEntry,fromVersion:a,toVersion:s}),a?{kind:"version-changed",fromVersion:a,toVersion:s,libEntry:e.libEntry}:{kind:"first-install",libVersion:s,libEntry:e.libEntry}}import{basename as vI,resolve as TI}from"node:path";de();var RI=9e4,kI={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,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,AGENT_DEPENDENCY_INSTALL_FAILED:1};function bI(t){return kI[t]??1}async function Ap(t,e={}){let r=e.paths??M();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>
95
+ `}async function yp(t,e=M()){let r=e.binDir;await eo.mkdir(r,{recursive:!0});let n=QS(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),i=process.execPath,s=process.platform==="win32"?eI(t,i):YS(t,i);return await eo.readFile(n,"utf8").catch(()=>null)===s||(await eo.writeFile(n,s,"utf8"),process.platform!=="win32"&&await eo.chmod(n,493)),r}F();de();import{execSync as Ep}from"node:child_process";import{readFileSync as Sp,unlinkSync as tI}from"node:fs";import{mkdir as rI,readFile as Ip,unlink as vp,writeFile as nI}from"node:fs/promises";import{dirname as iI}from"node:path";function _p(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var sI=x("single-instance"),to=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??M().pidFile,e.processTitle&&(process.title=e.processTitle)}async acquire(){let e=await this.readExistingPid();return e!==null&&this.isAlive(e)?{kind:"already-running",pid:e}:(e!==null&&(sI.warn("removing stale pid file",{stalePid:e}),await vp(this.pidFile).catch(()=>{})),await rI(iI(this.pidFile),{recursive:!0}),await nI(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Ip(this.pidFile,"utf8")).trim()===String(process.pid)&&await vp(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Ip(this.pidFile,"utf8"),r=Number.parseInt(e.trim(),10);return Number.isFinite(r)&&r>0?r:null}catch(e){if(e.code==="ENOENT")return null;throw e}}isAlive(e){return _p(e)?this.matchesDaemonTitle(e):!1}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=Sp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes("coze-bridge-daemon")||r.includes("lib/index.js"))}catch{}try{let r=Ep(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return r.trim()?r.includes("coze-bridge-daemon")||r.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let n=Ep(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!n||/^(INFO|信息)[::]/.test(n))return!1;let i=n.split(",",1)[0]?.replace(/^"|"$/g,"").toLowerCase()??"";return i.includes("node")||i.includes("coze-bridge")}catch{return!0}}installCleanupHooks(){process.once("exit",()=>{if(this.acquired)try{Sp(this.pidFile,"utf8").trim()===String(process.pid)&&tI(this.pidFile)}catch{}})}};var O=x("daemon"),oI="coze-bridge-daemon";async function Rp(){let t=new to({processTitle:oI}),e=await t.acquire();if(e.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${e.pid})`);let r=await Ns(),n=r??{};yi({pid:process.pid}),O.info(r?"loaded bridge config":"initialized bridge config");try{let I=new zt;n.frameworksCache=await I.detectAll(),O.info("refreshed frameworks_cache",{detected:Object.keys(n.frameworksCache)})}catch(I){O.warn("framework detection failed",{err:String(I)})}await Jr(n);let i=new Ys(new on),s=M(),o=null,a=new Ls({upstream:i,paths:s,bridgeConfig:n,sessionSpawner:async(I,T,A,P)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(I,T,A,P)}});await cI(s,a);let c=new Ps({paths:s,config:n,registry:a});o=c;let l,d,p=null,m={},f,u=null;a.registerExtension("_agent/create",async I=>c.createAgent(I.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let g={},w=new Ss({agents:a.agents,disposeAndMarkDisconnected:async(I,T)=>{let A=a.agents.get(I);if(A){await c.cleanupOpenclawSessionProviders(A).catch(G=>O.warn("cleanup openclaw providers failed (ignored)",{agentId:I,err:String(G)}));let P=!0;try{await A.dispose(`disconnect: ${T}`)}catch(G){P=!1,O.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:I,err:String(G)}),A.status="error"}P&&(A.status="disconnected",a.unregister(I),a.disconnectedAgents.add(I))}else a.disconnectedAgents.add(I)},detailSyncer:async I=>{if(!g.ref)throw new Error("agent-detail-sync not initialized yet");await g.ref.syncOne(I)},cleanupOpenclawProviders:async I=>{await c.cleanupOpenclawSessionProviders(I)},openclawRepair:async(I,T)=>{await c.openclawRepair(I,T)},isRuntimePendingPermission:I=>a.hasPendingPermissionFor(I)});a.registerExtension("_agent/listSkills",I=>w.listSkills(I.params)),a.registerExtension("_agent/addSkills",I=>w.addSkills(I.params)),a.registerExtension("_agent/removeSkills",I=>w.removeSkills(I.params)),a.registerExtension("_agent/getFileTree",I=>w.getFileTree(I.params)),a.registerExtension("_agent/getFileContent",I=>w.getFileContent(I.params)),a.registerExtension("_agent/update",I=>w.updateAgent(I.params)),a.registerExtension("_agent/disconnect",I=>w.disconnectAgent(I.params)),a.registerExtension("_agent/switchModel",I=>w.switchModel(I.params)),a.registerExtension("_agent/reset",I=>w.resetAgent(I.params)),a.registerExtension("_agent/repair",I=>w.repairAgent(I.params));let E=new Ai({paths:s,handlers:w,sendDetail:I=>a.sendRequest("_agent/detail",I)});g.ref=E;let v=async I=>{await Promise.allSettled(I.map(async T=>{try{await w.disconnectAgent({agentId:T.agentId,reason:`auth_failure: code=${T.code} ${T.message}`}),O.info("agent disconnected due to auth failure from heartbeat response",{agentId:T.agentId,code:T.code,message:T.message})}catch(A){O.warn("disconnect during authFailure handling failed (ignored)",{agentId:T.agentId,err:String(A)})}}))};i.onConnect(({initial:I})=>{O.info("frontier upstream connected, triggering detail sync",{initial:I}),E.syncAll(I?"initial-connect":"reconnect").catch(T=>O.warn("detail sync top-level error (ignored)",{err:String(T)}))});let h=new Fs({paths:s,routes:[{method:"GET",path:"/status",handler:async()=>{let I=a.getMockScenario();return{running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:p??"",frameworksCache:n.frameworksCache??{},...I?{mockScenario:I}:{}}}},{method:"POST",path:"/pair",handler:async I=>{let T=I,A=T?.privatecode,P=T?.pairing_code;if(!A||!P)throw new _("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let G=$n(T.env),X=T.handshake_url,Pe=T.frontier_url,at=Tp(T.env,X,Pe),ct=!!l&&l!==A,an=d!==void 0&&d!==at,cn=ct||an,pi=await xa({privatecode:A,...X?{endpoint:X}:{},ppeOverride:G});if(cn){O.warn("pair config switched, resetting agents",{pcChanged:ct,envChanged:an,previousPc:l?ro(l):"",nextPc:ro(A),previousEnvKey:d??"",nextEnvKey:at});for(let ye of[...a.agents.values()])await ye.dispose("pair config switch").catch(()=>{}),a.agents.delete(ye.agentId);a.disconnectedAgents.size>0&&(O.info("clearing disconnectedAgents set on pair config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await i.swap(new on,"pair switch").catch(()=>{})}p=pi.deviceId,yi({deviceId:p,pid:process.pid}),Ha({patToken:A,env:T.env}).catch(ye=>O.warn("coze-cli setup error (ignored)",{err:String(ye)}));let ge=new hi({handshake:pi,privatecode:A,...Pe?{urlOverride:Pe}:{},ppeOverride:G,getPatTokenForAgent:ye=>a.agents.get(ye)?.patToken});await i.swap(ge,"pair");try{let ye=new zt;n.frameworksCache=await ye.detectAll(),await Jr(n),O.info("frameworks_cache refreshed before pair",{detected:Object.keys(n.frameworksCache)})}catch(ye){O.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ye)})}let uo=Object.keys(n.frameworksCache??{});try{let ye=await a.sendRequest("_agent/pair",{pairCode:P,patToken:A,frameworks:uo,_meta:{cozeDeviceId:p}});O.info("_agent/pair ok",{pairResult:ye}),l=A,d=at,m=G,f=X,T.mock_scenario!==void 0&&(a.setMockScenario(T.mock_scenario),O.info("mock scenario set",{scenario:T.mock_scenario})),fi(A,s).catch(qe=>O.warn("writePatToken after /pair failed (ignored)",{err:String(qe)})),u||(u=new Hn({core:a,getDeviceId:()=>p??"",onTickEnd:()=>E.retryPending().catch(qe=>O.warn("detailSync.retryPending failed (ignored)",{err:String(qe)})),onAuthFailures:v})),u.start(),cn&&no(s,c).catch(qe=>O.warn("post-pair-switch auto-revive error (ignored)",{err:String(qe)}));let po;return T.agent_id&&(po=await lI(T.agent_id,s,c,qe=>a.sendRequest("_agent/detail",qe),A).catch(qe=>(O.error("--agent-id ensureAgent failed",{agentId:T.agent_id,err:String(qe)}),{ok:!1,agentId:T.agent_id??"",note:String(qe)}))),{ok:!0,note:"paired with cloud",...po?{agent:po}:{}}}catch(ye){return O.error("_agent/pair failed",{err:String(ye)}),{ok:!1,note:`pair failed: ${String(ye)}`}}}},{method:"POST",path:"/connect",handler:async I=>{let T=I,A=T?.privatecode;if(!A)throw new _("IPC_BAD_REQUEST","/connect requires privatecode");let P=$n(T.env),G=T.handshake_url,X=T.frontier_url,Pe=Tp(T.env,G,X);if(l===A&&d===Pe){let ge=await aI(s);return a.agents.size===0&&ge?(O.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),no(s,c).catch(uo=>O.warn("connect-noop auto-revive error (ignored)",{err:String(uo)}))):O.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let at=!!l&&l!==A,ct=d!==void 0&&d!==Pe,an=at||ct,cn=await xa({privatecode:A,...G?{endpoint:G}:{},ppeOverride:P});if(an){O.warn("connect config switched, resetting agents",{pcChanged:at,envChanged:ct,previousPc:l?ro(l):"",nextPc:ro(A)});for(let ge of[...a.agents.values()])await ge.dispose("connect config switch").catch(()=>{}),a.agents.delete(ge.agentId);a.disconnectedAgents.size>0&&(O.info("clearing disconnectedAgents set on connect config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await i.swap(new on,"connect switch").catch(()=>{})}p=cn.deviceId,yi({deviceId:p,pid:process.pid}),Ha({patToken:A,env:T.env}).catch(ge=>O.warn("coze-cli setup error (ignored)",{err:String(ge)}));let pi=new hi({handshake:cn,privatecode:A,...X?{urlOverride:X}:{},ppeOverride:P,getPatTokenForAgent:ge=>a.agents.get(ge)?.patToken});return await i.swap(pi,"connect"),l=A,d=Pe,m=P,f=G,T.mock_scenario!==void 0&&(a.setMockScenario(T.mock_scenario),O.info("mock scenario set",{scenario:T.mock_scenario})),u||(u=new Hn({core:a,getDeviceId:()=>p??"",onTickEnd:()=>E.retryPending().catch(ge=>O.warn("detailSync.retryPending failed (ignored)",{err:String(ge)})),onAuthFailures:v})),u.start(),an&&no(s,c).catch(ge=>O.warn("post-connect-switch auto-revive error (ignored)",{err:String(ge)})),fi(A,s).catch(ge=>O.warn("writePatToken after /connect failed (ignored)",{err:String(ge)})),O.info("/connect: WS established",{deviceId:p}),{ok:!0,note:"connected"}}},{method:"POST",path:"/_agent/create",handler:async I=>{let T=I;return{ok:!0,result:await c.createAgent(T)}}},{method:"POST",path:"/agent/send",handler:async I=>{let T=I;if(!T?.agentId||!T?.sessionId||!T?.kind||!T?.path)throw new _("IPC_BAD_REQUEST","/agent/send requires agentId, sessionId, kind, path");if(!l)throw new _("UPSTREAM_NOT_READY","daemon not yet paired with cloud (run --pair-code first)");try{let A=T;return await(A.groupFile?uf:ff)(A,{core:a,patToken:l,handshakeBase:f,ppeOverride:m})}catch(A){if(A instanceof _)return{ok:!1,code:A.code,message:A.message};throw A}}},{method:"POST",path:"/refresh",handler:async()=>{O.info("IPC /refresh: re-detecting frameworks");let I=new zt;return n.frameworksCache=await I.detectAll(),await Jr(n),{ok:!0,frameworks:n.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(O.info("IPC /shutdown received"),setImmediate(()=>{R.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:y,token:S}=await h.start();try{await yp(s.libEntry,s)}catch(I){O.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(I)})}await a.start(),no(s,c).catch(I=>O.warn("auto-revive top-level error (ignored)",{err:String(I)})),pl().then(async()=>{let{probeAcpVersion:I}=await Promise.resolve().then(()=>(qt(),fl));for(let T of["claude-code","codex"]){let A=await I(T);A&&O.info("acp wrapper version",{framework:T,version:A})}}).catch(I=>O.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(I)}));let k=null,R={port:y,token:S,core:a,ipc:h,shutdown(I){return k||(O.info("daemon shutdown",{reason:I}),k=(async()=>{u?.stop(),await a.stop(I),await h.stop(),await t.release()})(),k)}};for(let I of["SIGTERM","SIGINT"])process.on(I,()=>{R.shutdown(I).then(()=>process.exit(0))});return process.on("unhandledRejection",I=>{O.error("unhandledRejection",{reason:I instanceof Error?I.message:String(I),stack:I instanceof Error?I.stack:void 0})}),process.on("uncaughtException",I=>{O.error("uncaughtException (will exit, supervisor will restart)",{message:I.message,stack:I.stack,name:I.name}),process.exit(1)}),O.info("daemon ready",{port:y,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(n.frameworksCache??{}),libVersion:n.libVersion??"dev"}),R}async function aI(t){let{readdir:e}=await import("node:fs/promises");try{return(await e(t.agentsRoot)).length>0}catch{return!1}}function ro(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Tp(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function cI(t,e){let{readdir:r}=await import("node:fs/promises"),n;try{n=await r(t.agentsRoot)}catch{return}let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(vt(),bi));for(let o of n){await s(o,t).catch(a=>O.warn("enforceAgentConfigMode failed (ignored)",{agentId:o,err:String(a)}));try{let a=await i(o,t);a?.disconnectedAt&&(e.disconnectedAgents.add(o),O.info("agent marked disconnected on startup",{agentId:o,disconnectedAt:a.disconnectedAt,reason:a.disconnectReason??""}))}catch(a){O.warn("failed to load agent config on startup, skipping",{agentId:o,err:String(a)})}}}async function lI(t,e,r,n,i){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(vt(),bi)),o=await s(t,e);if(o){O.info("--agent-id: local config found, reconnecting",{agentId:t,framework:o.framework,hadDisconnect:!!o.disconnectedAt});let d={agentId:o.agentId,framework:o.framework,...o.cozeIdentity?{cozeIdentity:o.cozeIdentity}:{},...o.model?{model:o.model}:{},...i?{patToken:i}:{}};return await r.createAgent(d),{ok:!0,agentId:t,note:o.disconnectedAt?"revived from local config":"connected from local config"}}O.info("--agent-id: local config missing, pulling _agent/detail from cloud",{agentId:t});let a=await n({_meta:{cozeAgentId:t}});if(!a.framework)throw new _("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 c={agentId:a.agentId,framework:a.framework,...a.cozeIdentity?{cozeIdentity:a.cozeIdentity}:{},...a.model?{model:a.model}:{},...i?{patToken:i}:{},...a.deployType?{_meta:{cozeDeployType:a.deployType}}:{}};await r.createAgent(c);let l=a.deployType==="cloud"&&a.framework==="openclaw";return{ok:!0,agentId:t,note:l?"cloud agent acknowledged":"created from cloud detail"}}async function no(t,e){let{readdir:r}=await import("node:fs/promises"),n;try{n=await r(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(n.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:i}=await Promise.resolve().then(()=>(vt(),bi));O.info("auto-revive: scanning local agents on startup",{count:n.length});let s=0,o=0;for(let a of n){let c;try{c=await i(a,t)}catch(l){O.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(l)}),o+=1;continue}if(!c){o+=1;continue}if(c.disconnectedAt){O.info("auto-revive: skip disconnected agent",{agentId:a,disconnectedAt:c.disconnectedAt}),o+=1;continue}try{O.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:a,framework:c.framework});let l=dI(c);await e.createAgent({agentId:c.agentId,framework:c.framework,...c.cozeIdentity?{cozeIdentity:c.cozeIdentity}:{},...c.model?{model:c.model}:{},...l?{_meta:l}:{}}),s+=1}catch(l){O.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(l)}),o+=1}}return O.info("auto-revive: done",{revived:s,skipped:o,total:n.length}),{revived:s,skipped:o,total:n.length}}function dI(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}qc();de();import{readFile as kp}from"node:fs/promises";var It=class{paths;constructor(e){this.paths=e??M()}async probe(e=1e3){let r=await io(this.paths);if(!r)return{kind:"not-running"};try{let n=await this.fetch(r,{method:"GET",path:"/status",timeoutMs:e});return n.status===200?{kind:"connected",...r}:{kind:"stale",reason:`unexpected status ${n.status}`}}catch(n){return{kind:"stale",reason:yI(n)}}}async request(e){let r=await io(this.paths);if(!r)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(r,e)}async fetch(e,r){let n=r.body!==void 0,i={Authorization:`Bearer ${e.token}`};n&&(i["content-type"]="application/json");let s=new AbortController,o=setTimeout(()=>s.abort(),r.timeoutMs??5e3);try{let a=await fetch(`http://127.0.0.1:${e.port}${r.path}`,{method:r.method,headers:i,body:n?JSON.stringify(r.body):void 0,signal:s.signal}),c=await a.text();return{status:a.status,body:wI(c)}}finally{clearTimeout(o)}}};async function io(t){try{let[e,r]=await Promise.all([kp(t.portFile,"utf8"),kp(t.tokenFile,"utf8")]),n=Number.parseInt(e.trim(),10),i=r.trim();return!Number.isFinite(n)||n<=0||!i?null:{port:n,token:i}}catch(e){if(e.code==="ENOENT")return null;throw e}}function wI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function yI(t){return t instanceof Error?t.message:String(t)}Wt();F();de();import{copyFile as bp,mkdir as _I,readFile as Jc,writeFile as EI}from"node:fs/promises";import{homedir as sO}from"node:os";import{dirname as SI,resolve as Vc,sep as so}from"node:path";import{fileURLToPath as II}from"node:url";F();de();var Ap=x("dist-install");function vI(t){let e=II(t),r=SI(e),n=`${so}src${so}`;if(r.includes(n)||r.endsWith(`${so}src${so}cli`))return null;let i=Vc(r,"index.js"),s=Vc(r,"..","package.json");return{dist:i,pkgJson:s}}async function Zc(t={}){let e=t.paths??M(),r=vI(import.meta.url),n=t.sourceDist??r?.dist,i=t.sourcePackageJson??r?.pkgJson;if(!n||!i)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(n===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let s;try{s=JSON.parse(await Jc(i,"utf8")).version??"unknown"}catch(p){return Ap.warn("cannot read source package.json,skip dist install",{err:String(p)}),{kind:"dev-mode-skip",reason:`package.json read failed: ${String(p)}`}}let o=await Ns(e.configFile)??{},a=o.libVersion;if(a===s)try{return await Jc(e.libEntry),{kind:"already-current",libVersion:s}}catch{}await _I(e.libDir,{recursive:!0}),await bp(n,e.libEntry),await bp(`${n}.map`,`${e.libEntry}.map`).catch(()=>{});let c=Vc(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
96
+ `;return await Jc(c,"utf8").catch(()=>null)!==l&&await EI(c,l),o.libVersion=s,await Jr(o,e.configFile),Ap.info("dist installed",{libEntry:e.libEntry,fromVersion:a,toVersion:s}),a?{kind:"version-changed",fromVersion:a,toVersion:s,libEntry:e.libEntry}:{kind:"first-install",libVersion:s,libEntry:e.libEntry}}import{basename as TI,resolve as RI}from"node:path";de();var kI=9e4,bI={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,BRIDGE_CONFIG_INVALID:1,BRIDGE_INTERNAL:1,MODEL_TOKEN_GEN_FAILED:1,OPERATION_NOT_ALLOWED_FOR_LOCAL:1,AGENT_DEPENDENCY_INSTALL_FAILED:1};function AI(t){return bI[t]??1}async function xp(t,e={}){let r=e.paths??M();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>
97
97
  `),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.
98
98
  `),3;let n=await io(r).catch(()=>null);if(!n)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${r.portFile} / ${r.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
99
- `),4;let i={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:TI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},s;try{s=await AI(n,"/agent/send",i,RI)}catch(o){return process.stderr.write(`Error: daemon IPC failed: ${o instanceof Error?o.message:String(o)}
99
+ `),4;let i={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:RI(process.cwd(),t.path),...t.caption?{caption:t.caption}:{},...t.name?{name:t.name}:{},...t.groupFile?{groupFile:!0}:{},...t.mimeType?{mimeType:t.mimeType}:{}},s;try{s=await xI(n,"/agent/send",i,kI)}catch(o){return process.stderr.write(`Error: daemon IPC failed: ${o instanceof Error?o.message:String(o)}
100
100
  `),4}if(!s.ok)return process.stderr.write(`Error: ${s.code}: ${s.message}
101
- `),bI(s.code);if(t.json)process.stdout.write(`${JSON.stringify(s)}
102
- `);else{let o=t.name??vI(i.path);if(t.groupFile){let a=s.uri.length>60?`${s.uri.slice(0,57)}...`:s.uri;process.stdout.write(`Sent group file ${o} (uri=${a})
101
+ `),AI(s.code);if(t.json)process.stdout.write(`${JSON.stringify(s)}
102
+ `);else{let o=t.name??TI(i.path);if(t.groupFile){let a=s.uri.length>60?`${s.uri.slice(0,57)}...`:s.uri;process.stdout.write(`Sent group file ${o} (uri=${a})
103
103
  `)}else process.stdout.write(`Sent ${t.kind} ${o} (${OI(s.bytes)})
104
- `)}return 0}async function AI(t,e,r,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n);try{let o=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:i.signal}),a=await o.text(),c=a?JSON.parse(a):null;return c&&typeof c=="object"&&"ok"in c?c:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${o.status}): ${a.slice(0,200)}`}}finally{clearTimeout(s)}}function OI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Fp=O("cli");function pe(t,e){let r=[],n;for(let i=0;i<t.length;i++){let s=t[i];if(s===e){n=t[i+1],i+=1;continue}if(s.startsWith(`${e}=`)){n=s.slice(e.length+1);continue}r.push(s)}return{value:n,rest:r}}function ui(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
105
- `)}function VI(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]==="refresh")return{mode:"refresh"};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 ZI(e.slice(1));if(e[0]==="connect")return KI(e.slice(1));if(e.includes("--status"))return ui("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ui("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--refresh"))return ui("--refresh","coze-bridge refresh"),{mode:"refresh"};if(e.includes("--uninstall"))return ui("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ui("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:n,rest:i}=pe(r,"--pat-token");r=i;let{value:s,rest:o}=pe(r,"--pair-code");r=o;let{value:a,rest:c}=pe(r,"--env");r=c;let{value:l,rest:d}=pe(r,"--handshake-url");r=d;let{value:p,rest:m}=pe(r,"--frontier-url");r=m;let{value:f,rest:u}=pe(r,"--mock-scenario");r=u;let{value:g}=pe(r,"--agent-id");if(!n||!s)return{mode:"help"};let w={mode:"pair",privatecode:n,pairingCode:s};return a&&(w.env=a),l&&(w.handshakeUrl=l),p&&(w.frontierUrl=p),f&&(w.mockScenario=f),g&&(w.agentId=g),w}function ZI(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let n=t.slice(2),{value:i,rest:s}=pe(n,"--caption");n=s;let{value:o,rest:a}=pe(n,"--name");n=a;let{value:c,rest:l}=pe(n,"--agent-id");n=l;let{value:d,rest:p}=pe(n,"--session-id");n=p;let{value:m,rest:f}=pe(n,"--mime");n=f;let u=n.includes("--group-file");n=n.filter(E=>E!=="--group-file");let g=n.includes("--json"),w={mode:"send",kind:e,path:r,json:g};return i&&(w.caption=i),o&&(w.name=o),c&&(w.agentId=c),d&&(w.sessionId=d),u&&(w.groupFile=!0),m&&(w.mimeType=m),w}function KI(t){let e=t,{value:r,rest:n}=pe(e,"--pat-token");e=n;let{value:i,rest:s}=pe(e,"--env");e=s;let{value:o,rest:a}=pe(e,"--handshake-url");e=a;let{value:c,rest:l}=pe(e,"--frontier-url");e=l;let{value:d,rest:p}=pe(e,"--mock-scenario");e=p;let m={mode:"connect"};return r&&(m.privatecode=r),i&&(m.env=i),o&&(m.handshakeUrl=o),c&&(m.frontierUrl=c),d&&(m.mockScenario=d),m}var XI=`
104
+ `)}return 0}async function xI(t,e,r,n){let i=new AbortController,s=setTimeout(()=>i.abort(),n);try{let o=await fetch(`http://127.0.0.1:${t.port}${e}`,{method:"POST",headers:{Authorization:`Bearer ${t.token}`,"content-type":"application/json"},body:JSON.stringify(r),signal:i.signal}),a=await o.text(),c=a?JSON.parse(a):null;return c&&typeof c=="object"&&"ok"in c?c:{ok:!1,code:"BRIDGE_INTERNAL",message:`unexpected daemon response (status=${o.status}): ${a.slice(0,200)}`}}finally{clearTimeout(s)}}function OI(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Mp=x("cli");function pe(t,e){let r=[],n;for(let i=0;i<t.length;i++){let s=t[i];if(s===e){n=t[i+1],i+=1;continue}if(s.startsWith(`${e}=`)){n=s.slice(e.length+1);continue}r.push(s)}return{value:n,rest:r}}function ui(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
105
+ `)}function ZI(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]==="refresh")return{mode:"refresh"};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 KI(e.slice(1));if(e[0]==="connect")return XI(e.slice(1));if(e.includes("--status"))return ui("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return ui("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--refresh"))return ui("--refresh","coze-bridge refresh"),{mode:"refresh"};if(e.includes("--uninstall"))return ui("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return ui("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let r=e,{value:n,rest:i}=pe(r,"--pat-token");r=i;let{value:s,rest:o}=pe(r,"--pair-code");r=o;let{value:a,rest:c}=pe(r,"--env");r=c;let{value:l,rest:d}=pe(r,"--handshake-url");r=d;let{value:p,rest:m}=pe(r,"--frontier-url");r=m;let{value:f,rest:u}=pe(r,"--mock-scenario");r=u;let{value:g}=pe(r,"--agent-id");if(!n||!s)return{mode:"help"};let w={mode:"pair",privatecode:n,pairingCode:s};return a&&(w.env=a),l&&(w.handshakeUrl=l),p&&(w.frontierUrl=p),f&&(w.mockScenario=f),g&&(w.agentId=g),w}function KI(t){let e=t[0],r=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!r||r.startsWith("--"))return{mode:"help"};let n=t.slice(2),{value:i,rest:s}=pe(n,"--caption");n=s;let{value:o,rest:a}=pe(n,"--name");n=a;let{value:c,rest:l}=pe(n,"--agent-id");n=l;let{value:d,rest:p}=pe(n,"--session-id");n=p;let{value:m,rest:f}=pe(n,"--mime");n=f;let u=n.includes("--group-file");n=n.filter(E=>E!=="--group-file");let g=n.includes("--json"),w={mode:"send",kind:e,path:r,json:g};return i&&(w.caption=i),o&&(w.name=o),c&&(w.agentId=c),d&&(w.sessionId=d),u&&(w.groupFile=!0),m&&(w.mimeType=m),w}function XI(t){let e=t,{value:r,rest:n}=pe(e,"--pat-token");e=n;let{value:i,rest:s}=pe(e,"--env");e=s;let{value:o,rest:a}=pe(e,"--handshake-url");e=a;let{value:c,rest:l}=pe(e,"--frontier-url");e=l;let{value:d,rest:p}=pe(e,"--mock-scenario");e=p;let m={mode:"connect"};return r&&(m.privatecode=r),i&&(m.env=i),o&&(m.handshakeUrl=o),c&&(m.frontierUrl=c),d&&(m.mockScenario=d),m}var QI=`
106
106
  coze-bridge - local bridge daemon for cloud Agent Service
107
107
 
108
108
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -112,6 +112,9 @@ Daemon control:
112
112
  coze-bridge status show daemon status
113
113
  coze-bridge stop stop daemon
114
114
  coze-bridge refresh re-detect agent binaries (claude/codex/openclaw)
115
+ coze-bridge update \u5F3A\u5236\u5347\u7EA7\u5230 npm latest:
116
+ stop (inline) +
117
+ npx -y --ignore-existing coze-bridge@latest connect
115
118
  coze-bridge purge stop daemon + unregister supervisor +
116
119
  remove ~/.coze/bridge (preserves
117
120
  ~/.coze/agents workspaces)
@@ -169,46 +172,47 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
169
172
 
170
173
  Internal:
171
174
  <node> <entry> --daemon daemon mode (OS supervisor only)
172
- `.trimStart();async function Mp(t=process.argv,e={}){let r=VI(t);switch(r.mode){case"help":return process.stdout.write(XI),0;case"version":return process.stdout.write(`${$r}
173
- `),0;case"daemon":{try{await Tp()}catch(n){return Fp.error("daemon start failed",{err:String(n)}),1}return new Promise(()=>{})}case"status":return QI(e);case"stop":return YI(e);case"refresh":return ev(e);case"purge":return tv(e);case"service-install":return rv(e);case"service-uninstall":return nv(e);case"pair":{let n={};return r.env&&(n.env=r.env),r.handshakeUrl&&(n.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(n.frontierUrl=r.frontierUrl),r.mockScenario&&(n.mockScenario=r.mockScenario),iv(r.privatecode,r.pairingCode,e,n,r.agentId)}case"connect":{let n={};return r.env&&(n.env=r.env),r.handshakeUrl&&(n.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(n.frontierUrl=r.frontierUrl),r.mockScenario&&(n.mockScenario=r.mockScenario),sv(r.privatecode,e,n)}case"send":return Ap({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function Bp(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 QI(t){let e=t.paths??M(),r=new St(e),n=await r.probe();if(n.kind==="not-running")return process.stdout.write(`coze-bridge: not running
174
- `),1;if(n.kind==="stale")return await Bp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
175
+ `.trimStart();async function Bp(t=process.argv,e={}){let r=ZI(t);switch(r.mode){case"help":return process.stdout.write(QI),0;case"version":return process.stdout.write(`${$r}
176
+ `),0;case"daemon":{try{await Rp()}catch(n){return Mp.error("daemon start failed",{err:String(n)}),1}return new Promise(()=>{})}case"status":return YI(e);case"stop":return zp(e);case"refresh":return rv(e);case"update":return ev(e);case"purge":return nv(e);case"service-install":return iv(e);case"service-uninstall":return sv(e);case"pair":{let n={};return r.env&&(n.env=r.env),r.handshakeUrl&&(n.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(n.frontierUrl=r.frontierUrl),r.mockScenario&&(n.mockScenario=r.mockScenario),ov(r.privatecode,r.pairingCode,e,n,r.agentId)}case"connect":{let n={};return r.env&&(n.env=r.env),r.handshakeUrl&&(n.handshakeUrl=r.handshakeUrl),r.frontierUrl&&(n.frontierUrl=r.frontierUrl),r.mockScenario&&(n.mockScenario=r.mockScenario),av(r.privatecode,e,n)}case"send":return xp({kind:r.kind,path:r.path,...r.agentId?{agentId:r.agentId}:{},...r.sessionId?{sessionId:r.sessionId}:{},...r.caption?{caption:r.caption}:{},...r.name?{name:r.name}:{},...r.groupFile?{groupFile:!0}:{},...r.mimeType?{mimeType:r.mimeType}:{},json:r.json},e)}}async function Up(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 YI(t){let e=t.paths??M(),r=new It(e),n=await r.probe();if(n.kind==="not-running")return process.stdout.write(`coze-bridge: not running
177
+ `),1;if(n.kind==="stale")return await Up(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
175
178
  `),1;let i=await r.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
176
179
  ${JSON.stringify(i.body,null,2)}
177
- `),0}async function YI(t){let e=t.paths??M(),r=new St(e),n=await r.probe();if(n.kind==="not-running")return process.stdout.write(`coze-bridge: not running
178
- `),0;if(n.kind==="stale")return await Bp(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
180
+ `),0}async function zp(t){let e=t.paths??M(),r=new It(e),n=await r.probe();if(n.kind==="not-running")return process.stdout.write(`coze-bridge: not running
181
+ `),0;if(n.kind==="stale")return await Up(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
179
182
  `),0;try{return await r.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
180
183
  `),0}catch(i){return process.stdout.write(`coze-bridge: stop failed: ${String(i)}
181
- `),1}}async function ev(t){let e=new St(t.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
184
+ `),1}}async function ev(t){return await zp(t),(t.spawnNpx??tv)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function tv(t){return new Promise(e=>{let r=Je("npx",t,{stdio:"inherit"});r.on("exit",n=>e(n??1)),r.on("error",n=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(n)}
185
+ `),e(1)})})}async function rv(t){let e=new It(t.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
182
186
  `),1;try{let n=await e.request({method:"POST",path:"/refresh",timeoutMs:35e3});return n.status===200?(process.stdout.write(`coze-bridge: refreshed
183
187
  ${JSON.stringify(n.body,null,2)}
184
188
  `),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(n.body)}
185
189
  `),1)}catch(n){return process.stderr.write(`coze-bridge: refresh failed: ${String(n)}
186
- `),1}}async function tl(t){if(t.supervisor){let s=t.supervisor,o={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:s.platform,install:()=>s.install(o),uninstall:()=>s.uninstall(o)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Lp(),Np)),n=e(),i=r();return{platform:n.platform,install:()=>n.install(i),uninstall:()=>n.uninstall(i)}}async function tv(t){let e=new St(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
190
+ `),1}}async function tl(t){if(t.supervisor){let s=t.supervisor,o={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:s.platform,install:()=>s.install(o),uninstall:()=>s.uninstall(o)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:r}=await Promise.resolve().then(()=>(Fp(),Lp)),n=e(),i=r();return{platform:n.platform,install:()=>n.install(i),uninstall:()=>n.uninstall(i)}}async function nv(t){let e=new It(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
187
191
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(o){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(o)}
188
192
  `)}await new Promise(o=>setTimeout(o,500))}let n=await tl(t);if(n)try{await n.uninstall(),process.stdout.write(`coze-bridge: ${n.platform} supervisor unregistered
189
193
  `)}catch(o){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(o)}
190
194
  `)}let i=t.paths??M(),{rm:s}=await import("node:fs/promises");try{await s(i.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${i.bridgeRoot}
191
195
  `)}catch(o){return process.stderr.write(`coze-bridge: remove failed: ${String(o)}
192
196
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
193
- `),0}async function rv(t){let e=await tl(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
197
+ `),0}async function iv(t){let e=await tl(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
194
198
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
195
199
  `),0}catch(r){return process.stderr.write(`coze-bridge: service install failed: ${String(r)}
196
- `),1}}async function nv(t){let e=await tl(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
200
+ `),1}}async function sv(t){let e=await tl(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
197
201
  `),0}catch(r){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(r)}
198
- `),1}}async function iv(t,e,r,n={},i){let s=new St(r.paths),o=r.spawnDaemon??Wc;if(!r.skipDistInstall){let l=await Zc({paths:r.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
202
+ `),1}}async function ov(t,e,r,n={},i){let s=new It(r.paths),o=r.spawnDaemon??Wc;if(!r.skipDistInstall){let l=await Zc({paths:r.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
199
203
  `),(await s.probe()).kind==="connected"&&(await s.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(p=>setTimeout(p,500)))):l.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${l.libVersion}
200
204
  `)}let a=await s.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
201
- `),await o({paths:r.paths}),a=await Up(s,r.waitTimeoutMs??1e4,r.sleep??zp),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
205
+ `),await o({paths:r.paths}),a=await $p(s,r.waitTimeoutMs??1e4,r.sleep??Gp),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
202
206
  `),1;let c={privatecode:t,pairing_code:e};n.env&&(c.env=n.env),n.handshakeUrl&&(c.handshake_url=n.handshakeUrl),n.frontierUrl&&(c.frontier_url=n.frontierUrl),n.mockScenario&&(c.mock_scenario=n.mockScenario),i&&(c.agent_id=i);try{let l=await s.request({method:"POST",path:"/pair",body:c,timeoutMs:35e3});if(l.status===200&&l.body?.ok){let d=l.body.agent;return d&&!d.ok?(process.stderr.write(`coze-bridge: paired but agent ensure failed (agentId=${d.agentId}): ${d.note}
203
207
  `),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"
204
208
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(l.body)}
205
209
  `),1}catch(l){return process.stderr.write(`coze-bridge: pair failed: ${String(l)}
206
- `),1}}async function sv(t,e,r={}){let n=e.paths??M(),i=t??await mp(n);if(!i)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 s=new St(e.paths),o=e.spawnDaemon??Wc;if(!e.skipDistInstall){let l=await Zc({paths:e.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
210
+ `),1}}async function av(t,e,r={}){let n=e.paths??M(),i=t??await wp(n);if(!i)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 s=new It(e.paths),o=e.spawnDaemon??Wc;if(!e.skipDistInstall){let l=await Zc({paths:e.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
207
211
  `),(await s.probe()).kind==="connected"&&(await s.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(p=>setTimeout(p,500)))):l.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${l.libVersion}
208
212
  `)}let a=await s.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
209
- `),await o({paths:e.paths}),a=await Up(s,e.waitTimeoutMs??1e4,e.sleep??zp),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
213
+ `),await o({paths:e.paths}),a=await $p(s,e.waitTimeoutMs??1e4,e.sleep??Gp),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
210
214
  `),1;let c={privatecode:i};r.env&&(c.env=r.env),r.handshakeUrl&&(c.handshake_url=r.handshakeUrl),r.frontierUrl&&(c.frontier_url=r.frontierUrl),r.mockScenario&&(c.mock_scenario=r.mockScenario);try{let l=await s.request({method:"POST",path:"/connect",body:c,timeoutMs:35e3});return l.status===200&&l.body?.ok?(process.stdout.write(`coze-bridge: connected (${l.body.note??"ok"})
211
- `),await fi(i,n).catch(d=>Fp.warn("writePatToken after connect failed (ignored)",{err:String(d)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(l.body)}
215
+ `),await fi(i,n).catch(d=>Mp.warn("writePatToken after connect failed (ignored)",{err:String(d)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(l.body)}
212
216
  `),1)}catch(l){return process.stderr.write(`coze-bridge: connect failed: ${String(l)}
213
- `),1}}async function Up(t,e,r){let n=Date.now()+e;for(;Date.now()<n;){let i=await t.probe(500);if(i.kind==="connected")return i;await r(200)}return t.probe(500)}function zp(t){return new Promise(e=>setTimeout(e,t))}F();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&nl("warn");Mp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
217
+ `),1}}async function $p(t,e,r){let n=Date.now()+e;for(;Date.now()<n;){let i=await t.probe(500);if(i.kind==="connected")return i;await r(200)}return t.probe(500)}function Gp(t){return new Promise(e=>setTimeout(e,t))}F();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&nl("warn");Bp(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
214
218
  `),process.exit(1)});