coze-bridge 0.1.90 → 0.1.91-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +71 -71
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -5,27 +5,27 @@ 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
|
|
9
|
-
`)),this.stream=
|
|
10
|
-
`),this.stream=void 0;return}this.currentDate!==void 0&&
|
|
11
|
-
`;if(
|
|
12
|
-
`)}async function
|
|
13
|
-
`,i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{r?.mode!==void 0?await Ol(i,n,{encoding:"utf8",mode:r.mode}):await Ol(i,n,"utf8"),await xl(i,t),r?.mode!==void 0&&await Vg(t,r.mode)}catch(s){await xl(i,i).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(i,{force:!0}).catch(()=>{}),s}}var Pi=me(()=>{"use strict"});import{promises as Pl,readdirSync as Yg}from"node:fs";import{homedir as Qg}from"node:os";import{sep as em,join as ee,resolve as Cl}from"node:path";function N(t){let e=t??Qg(),r=ee(e,".coze"),n=ee(r,"bridge"),i=ee(n,"lib"),s=ee(n,"logs");return{cozeRoot:r,bridgeRoot:n,libDir:i,libEntry:ee(i,"index.js"),binDir:ee(n,"bin"),pidFile:ee(n,"bridge.pid"),portFile:ee(n,"bridge.port"),tokenFile:ee(n,"bridge.token"),patTokenFile:ee(n,"pat-token"),logFile:ee(n,"bridge.log"),bridgeLogsDir:s,daemonStdioLog:ee(s,"daemon-stdio.log"),installLock:ee(n,"install.lock"),configFile:ee(n,"config.json"),agentsRoot:ee(r,"agents")}}function ve(t,e=N()){let r=ee(e.agentsRoot,t);return{root:r,config:ee(r,"config.json"),workspace:ee(r,"workspace"),logs:ee(r,"logs")}}function Dl(t=N()){try{return Yg(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function gn(t,e){let r=await Pl.realpath(Cl(t)).catch(()=>null);if(!r)return!1;let n=await Pl.realpath(Cl(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+em)}var se=me(()=>{"use strict"});var Ni={};_i(Ni,{AGENT_CONFIG_FILE_MODE:()=>Ci,enforceAgentConfigMode:()=>nm,loadAgentConfig:()=>ue,persistAgentSessions:()=>mn,persistAgentSkills:()=>Di,saveAgentConfig:()=>Te});import{chmod as tm,stat as rm}from"node:fs/promises";function ue(t,e){return Tr(ve(t,e).config)}function Te(t,e){return Oi(ve(t.agentId,e).config,t,{mode:Ci})}async function nm(t,e){if(process.platform==="win32")return;let r=ve(t,e).config;try{let n=await rm(r);if(!n.isFile())return;let i=n.mode&511;i!==Ci&&(await tm(r,Ci),Nl.warn("agent config mode auto-corrected to 0600",{path:r,from:i.toString(8)}))}catch(n){if(n.code==="ENOENT")return;Nl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:r,err:String(n)})}}async function mn(t,e,r){let n=await ue(t,r);n&&(n.sessions=Object.fromEntries(e),await Te(n,r))}async function Di(t,e,r){let n=await ue(t,r);n&&(n.skills=e,await Te(n,r))}var Nl,Ci,Rt=me(()=>{"use strict";Pi();F();se();Nl=x("agent-config"),Ci=384});var Po=z((HT,Bl)=>{Bl.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 Fi=z(zl=>{var Ul={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function cm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Ul))zl[t]=cm(Ul[t])});var Wl=z((WT,jl)=>{var lm=$("fs"),te=$("path"),$l=Po(),dm=Fi(),um=typeof process=="object"&&process.platform==="win32",Gl=t=>typeof t=="object"&&t!==null,Hl=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=te.sep,this.fs=lm,Gl(t)&&Gl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}jl.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 dm.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=te.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=te.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(h,f){s.fs.write(f,e,0,e.length,0,function(){s.fs.close(f,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=te.join(n,a),l=e.fs.statSync(c);(!i||i.test(c))&&o.push(te.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=te.join(t,a),r.fs.stat(a,function(c,l){if(c)return e(c);l&&(n.push(te.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 Hl[(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 $l.STORED:return"STORED ("+t+")";case $l.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};Z.canonical=function(t){if(!t)return"";let e=te.posix.normalize("/"+t.split("\\").join("/"));return te.join(".",e)};Z.zipnamefix=function(t){if(!t)return"";let e=te.posix.normalize("/"+t.split("\\").join("/"));return te.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=te.resolve(te.normalize(t));for(var r=e.split("/"),n=0,i=r.length;n<i;n++){var s=te.normalize(te.join(t,r.slice(n,i).join(te.sep)));if(s.indexOf(t)===0)return s}return te.normalize(te.join(t,te.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=um;Z.crcTable=Hl});var Jl=z((qT,ql)=>{var hm=$("path");ql.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=hm.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 Zl=z((JT,Vl)=>{Vl.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var br=z((VT,kr)=>{kr.exports=Wl();kr.exports.Constants=Po();kr.exports.Errors=Fi();kr.exports.FileAttr=Jl();kr.exports.decoder=Zl()});var Xl=z((ZT,Kl)=>{var kt=br(),b=kt.Constants;Kl.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,h=0,f=0;t|=kt.isWin?2560:768,r|=b.FLG_EFS;let g={extraLen:0},w=u=>Math.max(0,u)>>>0,E=u=>Math.max(0,u)&65535,v=u=>Math.max(0,u)&255;return i=kt.fromDate2DOS(new Date),{get made(){return t},set made(u){t=u},get version(){return e},set version(u){e=u},get flags(){return r},set flags(u){r=u},get flags_efs(){return(r&b.FLG_EFS)>0},set flags_efs(u){u?r|=b.FLG_EFS:r&=~b.FLG_EFS},get flags_desc(){return(r&b.FLG_DESC)>0},set flags_desc(u){u?r|=b.FLG_DESC:r&=~b.FLG_DESC},get method(){return n},set method(u){switch(u){case b.STORED:this.version=10;case b.DEFLATED:default:this.version=20}n=u},get time(){return kt.fromDOS2Date(this.timeval)},set time(u){u=new Date(u),this.timeval=kt.fromDate2DOS(u)},get timeval(){return i},set timeval(u){i=w(u)},get timeHighByte(){return v(i>>>8)},get crc(){return s},set crc(u){s=w(u)},get compressedSize(){return o},set compressedSize(u){o=w(u)},get size(){return a},set size(u){a=w(u)},get fileNameLength(){return c},set fileNameLength(u){c=u},get extraLength(){return l},set extraLength(u){l=u},get extraLocalLength(){return g.extraLen},set extraLocalLength(u){g.extraLen=u},get commentLength(){return d},set commentLength(u){d=u},get diskNumStart(){return p},set diskNumStart(u){p=w(u)},get inAttr(){return m},set inAttr(u){m=w(u)},get attr(){return h},set attr(u){h=w(u)},get fileAttr(){return(h||0)>>16&4095},get offset(){return f},set offset(u){f=w(u)},get encrypted(){return(r&b.FLG_ENC)===b.FLG_ENC},get centralHeaderSize(){return b.CENHDR+c+l+d},get realDataOffset(){return f+b.LOCHDR+g.fnameLen+g.extraLen},get localHeader(){return g},loadLocalHeaderFromBinary:function(u){var y=u.slice(f,f+b.LOCHDR);if(y.readUInt32LE(0)!==b.LOCSIG)throw kt.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=f+b.LOCHDR+g.fnameLen,k=S+g.extraLen;return u.slice(S,k)},loadFromBinary:function(u){if(u.length!==b.CENHDR||u.readUInt32LE(0)!==b.CENSIG)throw kt.Errors.INVALID_CEN();t=u.readUInt16LE(b.CENVEM),e=u.readUInt16LE(b.CENVER),r=u.readUInt16LE(b.CENFLG),n=u.readUInt16LE(b.CENHOW),i=u.readUInt32LE(b.CENTIM),s=u.readUInt32LE(b.CENCRC),o=u.readUInt32LE(b.CENSIZ),a=u.readUInt32LE(b.CENLEN),c=u.readUInt16LE(b.CENNAM),l=u.readUInt16LE(b.CENEXT),d=u.readUInt16LE(b.CENCOM),p=u.readUInt16LE(b.CENDSK),m=u.readUInt16LE(b.CENATT),h=u.readUInt32LE(b.CENATX),f=u.readUInt32LE(b.CENOFF)},localHeaderToBinary:function(){var u=Buffer.alloc(b.LOCHDR);return u.writeUInt32LE(b.LOCSIG,0),u.writeUInt16LE(e,b.LOCVER),u.writeUInt16LE(r,b.LOCFLG),u.writeUInt16LE(n,b.LOCHOW),u.writeUInt32LE(i,b.LOCTIM),u.writeUInt32LE(s,b.LOCCRC),u.writeUInt32LE(o,b.LOCSIZ),u.writeUInt32LE(a,b.LOCLEN),u.writeUInt16LE(c,b.LOCNAM),u.writeUInt16LE(g.extraLen,b.LOCEXT),u},centralHeaderToBinary:function(){var u=Buffer.alloc(b.CENHDR+c+l+d);return u.writeUInt32LE(b.CENSIG,0),u.writeUInt16LE(t,b.CENVEM),u.writeUInt16LE(e,b.CENVER),u.writeUInt16LE(r,b.CENFLG),u.writeUInt16LE(n,b.CENHOW),u.writeUInt32LE(i,b.CENTIM),u.writeUInt32LE(s,b.CENCRC),u.writeUInt32LE(o,b.CENSIZ),u.writeUInt32LE(a,b.CENLEN),u.writeUInt16LE(c,b.CENNAM),u.writeUInt16LE(l,b.CENEXT),u.writeUInt16LE(d,b.CENCOM),u.writeUInt16LE(p,b.CENDSK),u.writeUInt16LE(m,b.CENATT),u.writeUInt32LE(h,b.CENATX),u.writeUInt32LE(f,b.CENOFF),u},toJSON:function(){let u=function(y){return y+" bytes"};return{made:t,version:e,flags:r,method:kt.methodToString(n),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:u(o),size:u(a),fileNameLength:u(c),extraLength:u(l),commentLength:u(d),diskNumStart:p,inAttr:m,attr:h,offset:f,centralHeaderSize:u(b.CENHDR+c+l+d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Ql=z((KT,Yl)=>{var Ar=br(),W=Ar.Constants;Yl.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 Ar.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=Ar.readBigUInt64LE(s,W.ZIP64SUB),e=Ar.readBigUInt64LE(s,W.ZIP64TOT),r=Ar.readBigUInt64LE(s,W.ZIP64SIZE),n=Ar.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 Do=z(Co=>{Co.EntryHeader=Xl();Co.MainHeader=Ql()});var td=z((YT,ed)=>{ed.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 nd=z((QT,rd)=>{var fm=+(process.versions?process.versions.node:"").split(".")[0]||0;rd.exports=function(t,e){var r=$("zlib");let n=fm>=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 cd=z((eR,ad)=>{"use strict";var{randomFillSync:id}=$("crypto"),pm=Fi(),gm=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),od=(t,e)=>Math.imul(t,e)>>>0,sd=(t,e)=>gm[(t^e)&255]^t>>>8,wn=()=>typeof id=="function"?id(Buffer.alloc(12)):wn.node();wn.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 Mi={genSalt:wn};function Bi(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])}Bi.prototype.updateKeys=function(t){let e=this.keys;return e[0]=sd(e[0],t),e[1]+=e[0]&255,e[1]=od(e[1],134775813)+1,e[2]=sd(e[2],e[1]>>>24),t};Bi.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return od(t,t^1)>>8&255};function mm(t){let e=new Bi(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 wm(t){let e=new Bi(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 ym(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=mm(r),i=n(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw pm.WRONG_PASSWORD();return n(t.slice(12))}function _m(t){Buffer.isBuffer(t)&&t.length>=12?Mi.genSalt=function(){return t.slice(0,12)}:t==="node"?Mi.genSalt=wn.node:Mi.genSalt=wn}function Em(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=wm(r),s=Mi.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)}ad.exports={decrypt:ym,encrypt:Em,_salter:_m}});var ld=z(Ui=>{Ui.Deflater=td();Ui.Inflater=nd();Ui.ZipCrypto=cd()});var Lo=z((rR,dd)=>{var B=br(),Sm=Do(),K=B.Constants,No=ld();dd.exports=function(t,e){var r=new Sm.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 h(u){if(!r.flags_desc&&!r.localHeader.flags_desc){if(B.crc32(u)!==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(u)!==y.crc)return!1}return!0}function f(u,y,S){if(typeof y>"u"&&typeof u=="string"&&(S=u,u=void 0),s)return u&&y&&y(Buffer.alloc(0),B.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var k=m();if(k.length===0)return u&&y&&y(k),k;if(r.encrypted){if(typeof S!="string"&&!Buffer.isBuffer(S))throw B.Errors.INVALID_PASS_PARAM();k=No.ZipCrypto.decrypt(k,r,S)}var R=Buffer.alloc(r.size);switch(r.method){case B.Constants.STORED:if(k.copy(R),h(R))return u&&y&&y(R),R;throw u&&y&&y(R,B.Errors.BAD_CRC()),B.Errors.BAD_CRC();case B.Constants.DEFLATED:var I=new No.Inflater(k,r.size);if(u)I.inflateAsync(function(T){T.copy(T,0),y&&(h(T)?y(T):y(T,B.Errors.BAD_CRC()))});else{if(I.inflate(R).copy(R,0),!h(R))throw B.Errors.BAD_CRC(`"${p.decode(n)}"`);return R}break;default:throw u&&y&&y(Buffer.alloc(0),B.Errors.UNKNOWN_METHOD()),B.Errors.UNKNOWN_METHOD()}}function g(u,y){if((!o||!o.length)&&Buffer.isBuffer(e))return u&&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),u&&y&&y(S),S;default:case B.Constants.DEFLATED:var k=new No.Deflater(o);if(u)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(u&&y)y(Buffer.alloc(0));else return Buffer.alloc(0)}function w(u,y){return B.readBigUInt64LE(u,y)}function E(u){try{for(var y=0,S,k,R;y+4<u.length;)S=u.readUInt16LE(y),y+=2,k=u.readUInt16LE(y),y+=2,R=u.slice(y,y+k),y+=k,K.ID_ZIP64===S&&v(R)}catch{throw B.Errors.EXTRA_FIELD_PARSE_ERROR()}}function v(u){var y,S,k,R;u.length>=K.EF_ZIP64_SCOMP&&(y=w(u,K.EF_ZIP64_SUNCOMP),r.size===K.EF_ZIP64_OR_32&&(r.size=y)),u.length>=K.EF_ZIP64_RHO&&(S=w(u,K.EF_ZIP64_SCOMP),r.compressedSize===K.EF_ZIP64_OR_32&&(r.compressedSize=S)),u.length>=K.EF_ZIP64_DSN&&(k=w(u,K.EF_ZIP64_RHO),r.offset===K.EF_ZIP64_OR_32&&(r.offset=k)),u.length>=K.EF_ZIP64_DSN+4&&(R=u.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(u){n=B.toBuffer(u,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(u){a=u,r.extraLength=u.length,E(u)},get comment(){return p.decode(i)},set comment(u){if(i=B.toBuffer(u,p.encode),r.commentLength=i.length,i.length>65535)throw B.Errors.COMMENT_TOO_LONG()},get name(){var u=p.decode(n);return s?u.substr(u.length-1).split("/").pop():u.split("/").pop()},get isDirectory(){return s},getCompressedData:function(){return g(!1,null)},getCompressedDataAsync:function(u){g(!0,u)},setData:function(u){o=B.toBuffer(u,B.decoder.encode),!s&&o.length?(r.size=o.length,r.method=B.Constants.DEFLATED,r.crc=B.crc32(u),r.changed=!0):r.method=B.Constants.STORED},getData:function(u){return r.changed?o:f(!1,null,u)},getDataAsync:function(u,y){r.changed?u(o):f(!0,u,y)},set attr(u){r.attr=u},get attr(){return r.attr},set header(u){r.loadFromBinary(u)},get header(){return r},packCentralHeader:function(){r.flags_efs=this.efs,r.extraLength=a.length;var u=r.centralHeaderToBinary(),y=B.Constants.CENHDR;return n.copy(u,y),y+=n.length,a.copy(u,y),y+=r.extraLength,i.copy(u,y),u},packLocalHeader:function(){let u=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,u),u+=y.length,n.copy(S,u),u+=n.length,c.copy(S,u),u+=c.length,S},toJSON:function(){let u=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:u(e),data:u(o)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var fd=z((nR,hd)=>{var ud=Lo(),Im=Do(),he=br();hd.exports=function(t,e){var r=[],n={},i=Buffer.alloc(0),s=new Im.MainHeader,o=!1,a=null;let c=new Set,l=e,{noSort:d,decoder:p}=l;t?f(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 u=0;u<v.length;u++){let y=v.slice(0,u+1).join("/")+"/";w.add(y)}}for(let E of w)if(!(E in n)){let v=new ud(l);v.entryName=E,v.attr=16,v.temporary=!0,r.push(v),n[v.entryName]=v,c.add(v)}}function h(){if(o=!0,n={},s.diskEntries>(t.length-s.offset)/he.Constants.CENHDR)throw he.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(s.diskEntries);for(var w=s.offset,E=0;E<r.length;E++){var v=w,u=new ud(l,t);u.header=t.slice(v,v+=he.Constants.CENHDR),u.entryName=t.slice(v,v+=u.header.fileNameLength),u.header.extraLength&&(u.extra=t.slice(v,v+=u.header.extraLength)),u.header.commentLength&&(u.comment=t.slice(v,v+u.header.commentLength)),w+=u.header.centralHeaderSize,r[E]=u,n[u.entryName]=u}c.clear(),m()}function f(w){var E=t.length-he.Constants.ENDHDR,v=Math.max(0,E-65535),u=v,y=t.length,S=-1,k=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(v=0),E;E>=u;E--)if(t[E]===80){if(t.readUInt32LE(E)===he.Constants.ENDSIG){S=E,k=E,y=E+he.Constants.ENDHDR,u=E-he.Constants.END64HDR;continue}if(t.readUInt32LE(E)===he.Constants.END64SIG){u=v;continue}if(t.readUInt32LE(E)===he.Constants.ZIP64SIG){S=E,y=E+he.readBigUInt64LE(t,E+he.Constants.ZIP64SIZE)+he.Constants.ZIP64LEAD;break}}if(S==-1)throw he.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(S,y)),s.commentLength&&(i=t.slice(k+he.Constants.ENDHDR)),w&&h()}function g(){r.length>1&&!d&&r.sort((w,E)=>w.entryName.toLowerCase().localeCompare(E.entryName.toLowerCase()))}return{get entries(){return o||h(),r.filter(w=>!c.has(w))},get comment(){return p.decode(i)},set comment(w){i=he.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||h(),n[w]||null},setEntry:function(w){o||h(),r.push(w),n[w.entryName]=w,s.totalEntries=r.length},deleteFile:function(w,E=!0){o||h();let v=n[w];this.getEntryChildren(v,E).map(y=>y.entryName).forEach(this.deleteEntry)},deleteEntry:function(w){o||h();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||h(),typeof w=="object")if(w.isDirectory&&E){let v=[],u=w.entryName;for(let y of r)y.entryName.startsWith(u)&&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||h(),g();let w=[],E=[],v=0,u=0;s.size=0,s.offset=0;let y=0;for(let R of this.entries){let I=R.getCompressedData();R.header.offset=u;let T=R.packLocalHeader(),A=T.length+I.length;u+=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=u,s.totalEntries=y,u=0;let S=Buffer.alloc(v);for(let R of w)R.copy(S,u),u+=R.length;for(let R of E)R.copy(S,u),u+=R.length;let k=s.toBinary();return i&&i.copy(k,he.Constants.ENDHDR),k.copy(S,u),t=S,o=!1,S},toAsyncBuffer:function(w,E,v,u){try{o||h(),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){u&&u(G),P.header.offset=R;let Ce=P.packLocalHeader(),ct=Ce.length+X.length;R+=ct,y.push(Ce),y.push(X);let lt=P.packCentralHeader();S.push(lt),s.size+=lt.length,k+=ct+lt.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,he.Constants.ENDHDR),G.copy(P,R),t=P,o=!1,w(P)}};T(Array.from(this.entries))}catch(y){E(y)}}}}});var md=z((iR,gd)=>{var J=br(),q=$("path"),vm=Lo(),Tm=fd(),Zt=(...t)=>J.findLast(t,e=>typeof e=="boolean"),pd=(...t)=>J.findLast(t,e=>typeof e=="string"),Rm=(...t)=>J.findLast(t,e=>typeof e=="function"),km={noSort:!1,readEntries:!1,method:J.Constants.NONE,fs:null};gd.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),km);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 Tm(r,n),{canonical:o,sanitize:a,zipnamefix:c}=J;function l(h){if(h&&s){var f;if(typeof h=="string"&&(f=s.getEntry(q.posix.normalize(h))),typeof h=="object"&&typeof h.entryName<"u"&&typeof h.header<"u"&&(f=s.getEntry(h.entryName)),f)return f}return null}function d(h){let{join:f,normalize:g,sep:w}=q.posix;return f(q.isAbsolute(h)?"/":".",g(w+h.split("\\").join(w)+w))}function p(h){return h instanceof RegExp?(function(f){return function(g){return f.test(g)}})(h):typeof h!="function"?()=>!0:h}let m=(h,f)=>{let g=f.slice(-1);return g=g===i.sep?i.sep:"",q.relative(h,f)+g};return{readFile:function(h,f){var g=l(h);return g&&g.getData(f)||null},childCount:function(h){let f=l(h);if(f)return s.getChildCount(f)},readFileAsync:function(h,f){var g=l(h);g?g.getDataAsync(f):f(null,"getEntry failed for:"+h)},readAsText:function(h,f){var g=l(h);if(g){var w=g.getData();if(w&&w.length)return w.toString(f||"utf8")}return""},readAsTextAsync:function(h,f,g){var w=l(h);w?w.getDataAsync(function(E,v){if(v){f(E,v);return}E&&E.length?f(E.toString(g||"utf8")):f("")}):f("")},deleteFile:function(h,f=!0){var g=l(h);g&&s.deleteFile(g.entryName,f)},deleteEntry:function(h){var f=l(h);f&&s.deleteEntry(f.entryName)},addZipComment:function(h){s.comment=h},getZipComment:function(){return s.comment||""},addZipEntryComment:function(h,f){var g=l(h);g&&(g.comment=f)},getZipEntryComment:function(h){var f=l(h);return f&&f.comment||""},updateFile:function(h,f){var g=l(h);g&&g.setData(f)},addLocalFile:function(h,f,g,w){if(i.fs.existsSync(h)){f=f?d(f):"";let E=q.win32.basename(q.win32.normalize(h));f+=g||E;let v=i.fs.statSync(h),u=v.isFile()?i.fs.readFileSync(h):Buffer.alloc(0);v.isDirectory()&&(f+=i.sep),this.addFile(f,u,w,v)}else throw J.Errors.FILE_NOT_FOUND(h)},addLocalFileAsync:function(h,f){h=typeof h=="object"?h:{localPath:h};let g=q.resolve(h.localPath),{comment:w}=h,{zipPath:E,zipName:v}=h,u=this;i.fs.stat(g,function(y,S){if(y)return f(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?f(R,!1):(u.addFile(E,I,w,S),setImmediate(f,void 0,!0))});else if(S.isDirectory())return E+=i.sep,u.addFile(E,Buffer.alloc(0),w,S),setImmediate(f,void 0,!0)})},addLocalFolder:function(h,f,g){if(g=p(g),f=f?d(f):"",h=q.normalize(h),i.fs.existsSync(h)){let w=i.findFiles(h),E=this;if(w.length)for(let v of w){let u=q.join(f,m(h,v));g(u)&&E.addLocalFile(v,q.dirname(u))}}else throw J.Errors.FILE_NOT_FOUND(h)},addLocalFolderAsync:function(h,f,g,w){w=p(w),g=g?d(g):"",h=q.normalize(h);var E=this;i.fs.open(h,"r",function(v){if(v&&v.code==="ENOENT")f(void 0,J.Errors.FILE_NOT_FOUND(h));else if(v)f(void 0,v);else{var u=i.findFiles(h),y=-1,S=function(){if(y+=1,y<u.length){var k=u[y],R=m(h,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&&f(void 0,I),T.isFile()?i.fs.readFile(k,function(A,P){A?f(void 0,A):(E.addFile(g+R,P,"",T),S())}):(E.addFile(g+R+"/",Buffer.alloc(0),"",T),S())}):process.nextTick(()=>{S()})}else f(!0,void 0)};S()}})},addLocalFolderAsync2:function(h,f){let g=this;h=typeof h=="object"?h:{localPath:h},localPath=q.resolve(d(h.localPath));let{zipPath:w,filter:E,namefix:v}=h;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 u=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"?f(void 0,J.Errors.FILE_NOT_FOUND(localPath)):S?f(void 0,S):i.findFilesAsync(localPath,function(k,R){if(k)return f(k);R=R.filter(I=>E(u(I))),R.length||f(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(u(T)),zipName:y(T)},I)}},f))})})},addLocalFolderPromise:function(h,f){return new Promise((g,w)=>{this.addLocalFolderAsync2(Object.assign({localPath:h},f),(E,v)=>{E&&w(E),v&&g(this)})})},addFile:function(h,f,g,w){h=c(h);let E=l(h),v=E!=null;v||(E=new vm(n),E.entryName=h),E.comment=g||"";let u=typeof w=="object"&&w instanceof i.fs.Stats;u&&(E.header.time=w.mtime);var y=E.isDirectory?16:0;let S=E.isDirectory?16384:32768;return u?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(f),v||s.setEntry(E),E},getEntries:function(h){return s.password=h,s?s.entries:[]},getEntry:function(h){return l(h)},getEntryCount:function(){return s.getEntryCount()},forEach:function(h){return s.forEach(h)},extractEntryTo:function(h,f,g,w,E,v){w=Zt(!1,w),E=Zt(!1,E),g=Zt(!0,g),v=pd(E,v);var u=l(h);if(!u)throw J.Errors.NO_ENTRY();var y=o(u.entryName),S=a(f,v&&!u.isDirectory?v:g?y:q.basename(y));if(u.isDirectory){var k=s.getEntryChildren(u);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(f,g?P:q.basename(P));let X=E?T.header.fileAttr:void 0;i.writeFileTo(G,A,w,X)}),!0}var R=u.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?h.header.fileAttr:void 0;return i.writeFileTo(S,R,w,I),!0},test:function(h){if(!s)return!1;for(var f in s.entries)try{if(f.isDirectory)continue;var g=s.entries[f].getData(h);if(!g)return!1}catch{return!1}return!0},extractAllTo:function(h,f,g,w){if(g=Zt(!1,g),w=pd(g,w),f=Zt(!1,f),!s)throw J.Errors.NO_ZIP();s.entries.forEach(function(E){var v=a(h,o(E.entryName));if(E.isDirectory){i.makeDir(v);return}var u=E.getData(w);if(!u)throw J.Errors.CANT_EXTRACT_FILE();let y=g?E.header.fileAttr:void 0;i.writeFileTo(v,u,f,y);try{i.fs.utimesSync(v,E.header.time,E.header.time)}catch{throw J.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(h,f,g,w){if(w=Rm(f,g,w),g=Zt(!1,g),f=Zt(!1,f),!w)return new Promise((S,k)=>{this.extractAllToAsync(h,f,g,function(R){R?k(R):S(this)})});if(!s){w(J.Errors.NO_ZIP());return}h=q.resolve(h);let E=S=>a(h,q.normalize(o(S.entryName))),v=(S,k)=>new Error(S+': "'+k+'"'),u=[],y=[];s.entries.forEach(S=>{S.isDirectory?u.push(S):y.push(S)});for(let S of u){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(h,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,f,G,function(X){X||S(v("Unable to write file",T)),i.fs.utimes(T,k.header.time,k.header.time,function(Ce){Ce?S(v("Unable to set times",T)):S()})})}})}}},w)()},writeZip:function(h,f){if(arguments.length===1&&typeof h=="function"&&(f=h,h=""),!h&&n.filename&&(h=n.filename),!!h){var g=s.compressToBuffer();if(g){var w=i.writeFileTo(h,g,!0);typeof f=="function"&&f(w?null:new Error("failed"),"")}}},writeZipPromise:function(h,f){let{overwrite:g,perm:w}=Object.assign({overwrite:!0},f);return new Promise((E,v)=>{!h&&n.filename&&(h=n.filename),h||v("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(u=>{let y=S=>S?E(S):v("ADM-ZIP: Wasn't able to write zip file");i.writeFileToAsync(h,u,g,w,y)},v)})},toBufferPromise:function(){return new Promise((h,f)=>{s.toAsyncBuffer(h,f)})},toBuffer:function(h,f,g,w){return typeof h=="function"?(s.toAsyncBuffer(h,f,g,w),null):s.compressToBuffer()}}}});function $E(){return jh||(jh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function GE(){return Wh||(Wh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function HE(t){let e=new Promise((r,n)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{r(Fe(t.result)),i()},o=()=>{n(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(r=>{r instanceof IDBCursor&&qh.set(r,t)}).catch(()=>{}),oc.set(e,t),e}function jE(t){if(ic.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)});ic.set(t,e)}function Vh(t){sc=t(sc)}function WE(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...r){let n=t.call(ri(this),e,...r);return Jh.set(n,e.sort?e.sort():[e]),Fe(n)}:GE().includes(t)?function(...e){return t.apply(ri(this),e),Fe(qh.get(this))}:function(...e){return Fe(t.apply(ri(this),e))}}function qE(t){return typeof t=="function"?WE(t):(t instanceof IDBTransaction&&jE(t),zE(t,$E())?new Proxy(t,sc):t)}function Fe(t){if(t instanceof IDBRequest)return HE(t);if(nc.has(t))return nc.get(t);let e=qE(t);return e!==t&&(nc.set(t,e),oc.set(e,t)),e}var zE,jh,Wh,qh,ic,Jh,nc,oc,sc,ri,ac=me(()=>{zE=(t,e)=>e.some(r=>t instanceof r);qh=new WeakMap,ic=new WeakMap,Jh=new WeakMap,nc=new WeakMap,oc=new WeakMap;sc={get(t,e,r){if(t instanceof IDBTransaction){if(e==="done")return ic.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Jh.get(t);if(e==="store")return r.objectStoreNames[1]?void 0:r.objectStore(r.objectStoreNames[0])}return Fe(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}};ri=t=>oc.get(t)});var Kh={};_i(Kh,{deleteDB:()=>VE,openDB:()=>JE,unwrap:()=>ri,wrap:()=>Fe});function JE(t,e,{blocked:r,upgrade:n,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=Fe(o);return n&&o.addEventListener("upgradeneeded",c=>{n(Fe(o.result),c.oldVersion,c.newVersion,Fe(o.transaction))}),r&&o.addEventListener("blocked",()=>r()),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",()=>i())}).catch(()=>{}),a}function VE(t,{blocked:e}={}){let r=indexedDB.deleteDatabase(t);return e&&r.addEventListener("blocked",()=>e()),Fe(r).then(()=>{})}function Zh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(cc.get(e))return cc.get(e);let r=e.replace(/FromIndex$/,""),n=e!==r,i=KE.includes(r);if(!(r in(n?IDBIndex:IDBObjectStore).prototype)||!(i||ZE.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 cc.set(e,s),s}var ZE,KE,cc,Xh=me(()=>{ac();ac();ZE=["get","getKey","getAll","getAllKeys","count"],KE=["put","add","delete","clear"],cc=new Map;Vh(t=>({...t,get:(e,r,n)=>Zh(e,r)||t.get(e,r,n),has:(e,r)=>!!Zh(e,r)||t.has(e,r)}))});var yt=z((Px,Tf)=>{"use strict";var If=["nodebuffer","arraybuffer","fragments"],vf=typeof Blob<"u";vf&&If.push("blob");Tf.exports={BINARY_TYPES:If,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:vf,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ci=z((Cx,qs)=>{"use strict";var{EMPTY_BUFFER:Q0}=yt(),Pc=Buffer[Symbol.species];function eS(t,e){if(t.length===0)return Q0;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 Pc(r.buffer,r.byteOffset,n):r}function Rf(t,e,r,n,i){for(let s=0;s<i;s++)r[n+s]=t[s]^e[s&3]}function kf(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function tS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Cc(t){if(Cc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Pc(t):ArrayBuffer.isView(t)?e=new Pc(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Cc.readOnly=!1),e}qs.exports={concat:eS,mask:Rf,toArrayBuffer:tS,toBuffer:Cc,unmask:kf};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=$("bufferutil");qs.exports.mask=function(e,r,n,i,s){s<48?Rf(e,r,n,i,s):t.mask(e,r,n,i,s)},qs.exports.unmask=function(e,r){e.length<32?kf(e,r):t.unmask(e,r)}}catch{}});var xf=z((Dx,Af)=>{"use strict";var bf=Symbol("kDone"),Dc=Symbol("kRun"),Nc=class{constructor(e){this[bf]=()=>{this.pending--,this[Dc]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Dc]()}[Dc](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bf])}}};Af.exports=Nc});var rn=z((Nx,Df)=>{"use strict";var li=$("zlib"),Of=ci(),rS=xf(),{kStatusCode:Pf}=yt(),nS=Buffer[Symbol.species],iS=Buffer.from([0,0,255,255]),Vs=Symbol("permessage-deflate"),_t=Symbol("total-length"),en=Symbol("callback"),Wt=Symbol("buffers"),tn=Symbol("error"),Js,Lc=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,!Js){let r=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Js=new rS(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[en];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){Js.add(i=>{this._decompress(e,r,(s,o)=>{i(),n(s,o)})})}compress(e,r,n){Js.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"?li.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=li.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Vs]=this,this._inflate[_t]=0,this._inflate[Wt]=[],this._inflate.on("error",oS),this._inflate.on("data",Cf)}this._inflate[en]=n,this._inflate.write(e),r&&this._inflate.write(iS),this._inflate.flush(()=>{let s=this._inflate[tn];if(s){this._inflate.close(),this._inflate=null,n(s);return}let o=Of.concat(this._inflate[Wt],this._inflate[_t]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[_t]=0,this._inflate[Wt]=[],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"?li.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=li.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[_t]=0,this._deflate[Wt]=[],this._deflate.on("data",sS)}this._deflate[en]=n,this._deflate.write(e),this._deflate.flush(li.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=Of.concat(this._deflate[Wt],this._deflate[_t]);r&&(s=new nS(s.buffer,s.byteOffset,s.length-4)),this._deflate[en]=null,this._deflate[_t]=0,this._deflate[Wt]=[],r&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};Df.exports=Lc;function sS(t){this[Wt].push(t),this[_t]+=t.length}function Cf(t){if(this[_t]+=t.length,this[Vs]._maxPayload<1||this[_t]<=this[Vs]._maxPayload){this[Wt].push(t);return}this[tn]=new RangeError("Max payload size exceeded"),this[tn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[tn][Pf]=1009,this.removeListener("data",Cf),this.reset()}function oS(t){if(this[Vs]._inflate=null,this[tn]){this[en](this[tn]);return}t[Pf]=1007,this[en](t)}});var nn=z((Lx,Zs)=>{"use strict";var{isUtf8:Nf}=$("buffer"),{hasBlob:aS}=yt(),cS=[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 lS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function Fc(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 dS(t){return aS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Zs.exports={isBlob:dS,isValidStatusCode:lS,isValidUTF8:Fc,tokenChars:cS};if(Nf)Zs.exports.isValidUTF8=function(t){return t.length<24?Fc(t):Nf(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=$("utf-8-validate");Zs.exports.isValidUTF8=function(e){return e.length<32?Fc(e):t(e)}}catch{}});var $c=z((Fx,$f)=>{"use strict";var{Writable:uS}=$("stream"),Lf=rn(),{BINARY_TYPES:hS,EMPTY_BUFFER:Ff,kStatusCode:fS,kWebSocket:pS}=yt(),{concat:Mc,toArrayBuffer:gS,unmask:mS}=ci(),{isValidStatusCode:wS,isValidUTF8:Mf}=nn(),Ks=Buffer[Symbol.species],Be=0,Bf=1,Uf=2,zf=3,Bc=4,Uc=5,Xs=6,zc=class extends uS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||hS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[pS]=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=Be}_write(e,r,n){if(this._opcode===8&&this._state==Be)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 Ks(n.buffer,n.byteOffset+e,n.length-e),new Ks(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 Ks(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 Be:this.getInfo(e);break;case Bf:this.getPayloadLength16(e);break;case Uf:this.getPayloadLength64(e);break;case zf:this.getMask();break;case Bc:this.getData(e);break;case Uc:case Xs: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[Lf.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=Bf:this._payloadLength===127?this._state=Uf: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=zf:this._state=Bc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Bc}getData(e){let r=Ff;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&&mS(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=Uc,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[Lf.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===Be&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=Be;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=Mc(n,r):this._binaryType==="arraybuffer"?i=gS(Mc(n,r)):this._binaryType==="blob"?i=new Blob(n):i=n,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=Be):(this._state=Xs,setImmediate(()=>{this.emit("message",i,!0),this._state=Be,this.startLoop(e)}))}else{let i=Mc(n,r);if(!this._skipUTF8Validation&&!Mf(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Uc||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=Be):(this._state=Xs,setImmediate(()=>{this.emit("message",i,!1),this._state=Be,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Ff),this.end();else{let n=e.readUInt16BE(0);if(!wS(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let i=new Ks(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Mf(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=Be;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Be):(this._state=Xs,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Be,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[fS]=i,o}};$f.exports=zc});var jc=z((Bx,jf)=>{"use strict";var{Duplex:Mx}=$("stream"),{randomFillSync:yS}=$("crypto"),Gf=rn(),{EMPTY_BUFFER:_S,kWebSocket:ES,NOOP:SS}=yt(),{isBlob:sn,isValidStatusCode:IS}=nn(),{mask:Hf,toBuffer:pr}=ci(),Ue=Symbol("kByteLength"),vS=Buffer.alloc(4),Ys=8*1024,gr,on=Ys,Ve=0,TS=1,RS=2,Gc=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=Ve,this.onerror=SS,this[ES]=void 0}static frame(e,r){let n,i=!1,s=2,o=!1;r.mask&&(n=r.maskBuffer||vS,r.generateMask?r.generateMask(n):(on===Ys&&(gr===void 0&&(gr=Buffer.alloc(Ys)),yS(gr,0,Ys),on=0),n[0]=gr[on++],n[1]=gr[on++],n[2]=gr[on++],n[3]=gr[on++]),o=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||o)&&r[Ue]!==void 0?a=r[Ue]:(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?(Hf(e,n,l,s,a),[l]):(Hf(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,i){let s;if(e===void 0)s=_S;else{if(typeof e!="number"||!IS(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={[Ue]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ve?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):sn(e)?(i=e.size,s=!1):(e=pr(e),i=e.length,s=pr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ue]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};sn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Ve?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):sn(e)?(i=e.size,s=!1):(e=pr(e),i=e.length,s=pr.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ue]:i,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};sn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,!1,o,n]):this.getBlobData(e,!1,o,n):this._state!==Ve?this.enqueue([this.dispatch,e,!1,o,n]):this.sendFrame(t.frame(e,o),n)}send(e,r,n){let i=this._extensions[Gf.extensionName],s=r.binary?2:1,o=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):sn(e)?(a=e.size,c=!1):(e=pr(e),a=e.length,c=pr.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={[Ue]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};sn(e)?this._state!==Ve?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Ve?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,i){this._bufferedBytes+=n[Ue],this._state=RS,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Hc,this,a,i);return}this._bufferedBytes-=n[Ue];let o=pr(s);r?this.dispatch(o,r,n,i):(this._state=Ve,this.sendFrame(t.frame(o,n),i),this.dequeue())}).catch(s=>{process.nextTick(kS,this,s,i)})}dispatch(e,r,n,i){if(!r){this.sendFrame(t.frame(e,n),i);return}let s=this._extensions[Gf.extensionName];this._bufferedBytes+=n[Ue],this._state=TS,s.compress(e,n.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Hc(this,c,i);return}this._bufferedBytes-=n[Ue],this._state=Ve,n.readOnly=!1,this.sendFrame(t.frame(a,n),i),this.dequeue()})}dequeue(){for(;this._state===Ve&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ue],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ue],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)}};jf.exports=Gc;function Hc(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 kS(t,e,r){Hc(t,e,r),t.onerror(e)}});var Qf=z((Ux,Yf)=>{"use strict";var{kForOnEventAttribute:di,kListener:Wc}=yt(),Wf=Symbol("kCode"),qf=Symbol("kData"),Jf=Symbol("kError"),Vf=Symbol("kMessage"),Zf=Symbol("kReason"),an=Symbol("kTarget"),Kf=Symbol("kType"),Xf=Symbol("kWasClean"),Et=class{constructor(e){this[an]=null,this[Kf]=e}get target(){return this[an]}get type(){return this[Kf]}};Object.defineProperty(Et.prototype,"target",{enumerable:!0});Object.defineProperty(Et.prototype,"type",{enumerable:!0});var mr=class extends Et{constructor(e,r={}){super(e),this[Wf]=r.code===void 0?0:r.code,this[Zf]=r.reason===void 0?"":r.reason,this[Xf]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[Wf]}get reason(){return this[Zf]}get wasClean(){return this[Xf]}};Object.defineProperty(mr.prototype,"code",{enumerable:!0});Object.defineProperty(mr.prototype,"reason",{enumerable:!0});Object.defineProperty(mr.prototype,"wasClean",{enumerable:!0});var cn=class extends Et{constructor(e,r={}){super(e),this[Jf]=r.error===void 0?null:r.error,this[Vf]=r.message===void 0?"":r.message}get error(){return this[Jf]}get message(){return this[Vf]}};Object.defineProperty(cn.prototype,"error",{enumerable:!0});Object.defineProperty(cn.prototype,"message",{enumerable:!0});var ui=class extends Et{constructor(e,r={}){super(e),this[qf]=r.data===void 0?null:r.data}get data(){return this[qf]}};Object.defineProperty(ui.prototype,"data",{enumerable:!0});var bS={addEventListener(t,e,r={}){for(let i of this.listeners(t))if(!r[di]&&i[Wc]===e&&!i[di])return;let n;if(t==="message")n=function(s,o){let a=new ui("message",{data:o?s:s.toString()});a[an]=this,Qs(e,this,a)};else if(t==="close")n=function(s,o){let a=new mr("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[an]=this,Qs(e,this,a)};else if(t==="error")n=function(s){let o=new cn("error",{error:s,message:s.message});o[an]=this,Qs(e,this,o)};else if(t==="open")n=function(){let s=new Et("open");s[an]=this,Qs(e,this,s)};else return;n[di]=!!r[di],n[Wc]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[Wc]===e&&!r[di]){this.removeListener(t,r);break}}};Yf.exports={CloseEvent:mr,ErrorEvent:cn,Event:Et,EventTarget:bS,MessageEvent:ui};function Qs(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var eo=z((zx,ep)=>{"use strict";var{tokenChars:hi}=nn();function at(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function AS(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&&hi[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 h=t.slice(c,d);l===44?(at(e,h,r),r=Object.create(null)):o=h,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&hi[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),at(r,t.slice(c,d),!0),l===44&&(at(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(hi[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),i=!1}else if(s)if(hi[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&&hi[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 h=t.slice(c,d);n&&(h=h.replace(/\\/g,""),n=!1),at(r,a,h),l===44&&(at(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?at(e,m,r):(a===void 0?at(r,m,!0):n?at(r,a,m.replace(/\\/g,"")):at(r,a,m),at(e,o,r)),e}function xS(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(", ")}ep.exports={format:xS,parse:AS}});var io=z((Hx,hp)=>{"use strict";var OS=$("events"),PS=$("https"),CS=$("http"),np=$("net"),DS=$("tls"),{randomBytes:NS,createHash:LS}=$("crypto"),{Duplex:$x,Readable:Gx}=$("stream"),{URL:qc}=$("url"),qt=rn(),FS=$c(),MS=jc(),{isBlob:BS}=nn(),{BINARY_TYPES:tp,CLOSE_TIMEOUT:US,EMPTY_BUFFER:to,GUID:zS,kForOnEventAttribute:Jc,kListener:$S,kStatusCode:GS,kWebSocket:de,NOOP:ip}=yt(),{EventTarget:{addEventListener:HS,removeEventListener:jS}}=Qf(),{format:WS,parse:qS}=eo(),{toBuffer:JS}=ci(),sp=Symbol("kAborted"),Vc=[8,13],St=["CONNECTING","OPEN","CLOSING","CLOSED"],VS=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,j=class t extends OS{constructor(e,r,n){super(),this._binaryType=tp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=to,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]),op(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){tp.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 FS({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new MS(e,this._extensions,n.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[de]=this,s[de]=this,e[de]=this,i.on("conclude",XS),i.on("drain",YS),i.on("error",QS),i.on("message",eI),i.on("ping",tI),i.on("pong",rI),s.onerror=nI,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",lp),e.on("data",no),e.on("end",dp),e.on("error",up),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[qt.extensionName]&&this._extensions[qt.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){Pe(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())}),cp(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){Zc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||to,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){Zc(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||to,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){Zc(this,e,n);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[qt.extensionName]||(i.compress=!1),this._sender.send(e||to,i,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Pe(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[Jc])return e[$S];return null},set(e){for(let r of this.listeners(t))if(r[Jc]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[Jc]:!0})}})});j.prototype.addEventListener=HS;j.prototype.removeEventListener=jS;hp.exports=j;function op(t,e,r,n){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:US,protocolVersion:Vc[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,!Vc.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Vc.join(", ")})`);let s;if(e instanceof qc)s=e;else try{s=new qc(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;ro(t,g);return}let l=o?443:80,d=NS(16).toString("base64"),p=o?PS.request:CS.request,m=new Set,h;if(i.createConnection=i.createConnection||(o?KS:ZS),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&&(h=new qt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=WS({[qt.extensionName]:h.offer()})),r.length){for(let g of r){if(typeof g!="string"||!VS.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 f;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")),f=t._req=p(i),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=p(i);i.timeout&&f.on("timeout",()=>{Pe(t,f,"Opening handshake has timed out")}),f.on("error",g=>{f===null||f[sp]||(f=t._req=null,ro(t,g))}),f.on("response",g=>{let w=g.headers.location,E=g.statusCode;if(w&&i.followRedirects&&E>=300&&E<400){if(++t._redirects>i.maxRedirects){Pe(t,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new qc(w,e)}catch{let y=new SyntaxError(`Invalid URL: ${w}`);ro(t,y);return}op(t,v,r,n)}else t.emit("unexpected-response",f,g)||Pe(t,f,`Unexpected server response: ${g.statusCode}`)}),f.on("upgrade",(g,w,E)=>{if(t.emit("upgrade",g),t.readyState!==j.CONNECTING)return;f=t._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Pe(t,w,"Invalid Upgrade header");return}let u=LS("sha1").update(d+zS).digest("base64");if(g.headers["sec-websocket-accept"]!==u){Pe(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){Pe(t,w,S);return}y&&(t._protocol=y);let k=g.headers["sec-websocket-extensions"];if(k!==void 0){if(!h){Pe(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=qS(k)}catch{Pe(t,w,"Invalid Sec-WebSocket-Extensions header");return}let I=Object.keys(R);if(I.length!==1||I[0]!==qt.extensionName){Pe(t,w,"Server indicated an extension that was not requested");return}try{h.accept(R[qt.extensionName])}catch{Pe(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[qt.extensionName]=h}t.setSocket(w,E,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(f,t):f.end()}function ro(t,e){t._readyState=j.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function ZS(t){return t.path=t.socketPath,np.connect(t)}function KS(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=np.isIP(t.host)?"":t.host),DS.connect(t)}function Pe(t,e,r){t._readyState=j.CLOSING;let n=new Error(r);Error.captureStackTrace(n,Pe),e.setHeader?(e[sp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ro,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function Zc(t,e,r){if(e){let n=BS(e)?e.size:JS(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 XS(t,e){let r=this[de];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[de]!==void 0&&(r._socket.removeListener("data",no),process.nextTick(ap,r._socket),t===1005?r.close():r.close(t,e))}function YS(){let t=this[de];t.isPaused||t._socket.resume()}function QS(t){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",no),process.nextTick(ap,e._socket),e.close(t[GS])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function rp(){this[de].emitClose()}function eI(t,e){this[de].emit("message",t,e)}function tI(t){let e=this[de];e._autoPong&&e.pong(t,!this._isServer,ip),e.emit("ping",t)}function rI(t){this[de].emit("pong",t)}function ap(t){t.resume()}function nI(t){let e=this[de];e.readyState!==j.CLOSED&&(e.readyState===j.OPEN&&(e._readyState=j.CLOSING,cp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function cp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function lp(){let t=this[de];if(this.removeListener("close",lp),this.removeListener("data",no),this.removeListener("end",dp),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[de]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",rp),t._receiver.on("finish",rp))}function no(t){this[de]._receiver.write(t)||this.pause()}function dp(){let t=this[de];t._readyState=j.CLOSING,t._receiver.end(),this.end()}function up(){let t=this[de];this.removeListener("error",up),this.on("error",ip),t&&(t._readyState=j.CLOSING,this.destroy())}});var mp=z((Wx,gp)=>{"use strict";var jx=io(),{Duplex:iI}=$("stream");function fp(t){t.emit("close")}function sI(){!this.destroyed&&this._writableState.finished&&this.destroy()}function pp(t){this.removeListener("error",pp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function oI(t,e){let r=!0,n=new iI({...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(fp,n);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(fp,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",sI),n.on("error",pp),n}gp.exports=oI});var Kc=z((qx,wp)=>{"use strict";var{tokenChars:aI}=nn();function cI(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&&aI[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}wp.exports={parse:cI}});var Tp=z((Vx,vp)=>{"use strict";var lI=$("events"),so=$("http"),{Duplex:Jx}=$("stream"),{createHash:dI}=$("crypto"),yp=eo(),wr=rn(),uI=Kc(),hI=io(),{CLOSE_TIMEOUT:fI,GUID:pI,kWebSocket:gI}=yt(),mI=/^[+/0-9A-Za-z]{22}==$/,_p=0,Ep=1,Ip=2,Xc=class extends lI{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:fI,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:hI,...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=so.createServer((n,i)=>{let s=so.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=wI(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=_p}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===Ip){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(fi,this);return}if(e&&this.once("close",e),this._state!==Ep)if(this._state=Ep,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(fi,this):process.nextTick(fi,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{fi(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"){yr(this,e,r,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){yr(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!mI.test(s)){yr(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){yr(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){pi(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=uI.parse(c)}catch{yr(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 wr({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=yp.parse(d);h[wr.extensionName]&&(m.accept(h[wr.extensionName]),p[wr.extensionName]=m)}catch{yr(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,(h,f,g,w)=>{if(!h)return pi(r,f||401,g,w);this.completeUpgrade(p,s,l,e,r,n,i)});return}if(!this.options.verifyClient(m))return pi(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[gI])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>_p)return pi(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${dI("sha1").update(r+pI).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[wr.extensionName]){let p=e[wr.extensionName].params,m=yp.format({[wr.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
|
|
8
|
+
var Rg=Object.create;var Oo=Object.defineProperty;var kg=Object.getOwnPropertyDescriptor;var bg=Object.getOwnPropertyNames;var Ag=Object.getPrototypeOf,xg=Object.prototype.hasOwnProperty;var H=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var we=(t,e)=>()=>(t&&(e=t(t=0)),e);var G=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ri=(t,e)=>{for(var n in e)Oo(t,n,{get:e[n],enumerable:!0})},Og=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of bg(e))!xg.call(t,i)&&i!==n&&Oo(t,i,{get:()=>e[i],enumerable:!(r=kg(e,i))||r.enumerable});return t};var dt=(t,e,n)=>(n=t!=null?Rg(Ag(t)):{},Og(e||!t||!t.__esModule?Oo(n,"default",{value:t,enumerable:!0}):n,t));function ut(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var ki=we(()=>{"use strict"});import{createWriteStream as Pg,mkdirSync as Cg,readdirSync as Dg,unlinkSync as Ng}from"node:fs";import{join as vl}from"node:path";function Rn(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function bi(t,e){return`${t}-${e}.log`}function Po(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Lg(t,e,n){let r=s=>{let[o,a,c]=s.split("-").map(Number);return Date.UTC(o??0,(a??1)-1,c??1)};return Math.floor((r(e)-r(t))/864e5)>n}function Ai(t,e,n,r){let i;try{i=Dg(t)}catch{return}for(let s of i){let o=Po(s,e);if(o&&Lg(o,n,r))try{Ng(vl(t,s))}catch{}}}var yr,Co=we(()=>{"use strict";yr=class{constructor(e,n,r){this.dir=e;this.prefix=n;this.opts=r;this.clock=r.clock??(()=>Rn(new Date))}dir;prefix;opts;currentDate;stream;clock;write(e){let n=this.clock();n!==this.currentDate&&this.rotate(n),this.stream?.write(e)}rotate(e){this.stream?.end();try{Cg(this.dir,{recursive:!0});let n=Pg(vl(this.dir,bi(this.prefix,e)),{flags:"a"});n.on("error",r=>process.stderr.write(`[log-sink] stream error: ${String(r)}
|
|
9
|
+
`)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
|
|
10
|
+
`),this.stream=void 0;return}this.currentDate!==void 0&&Ai(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});function Rl(t){let e=t.retentionDays??Bg,n=t.clock??(()=>Rn(new Date));Oi={bridgeSink:new yr(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:i=>new yr(t.agentLogsDir(i),"agent",{retentionDays:e,clock:n})};let r=n();Ai(t.bridgeLogsDir,"bridge",r,e);for(let i of t.listAgentIds?.()??[])Ai(t.agentLogsDir(i),"agent",r,e)}function Ug(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function kl(t){Do=t}function bl(t){return kn[Do]<=kn[t]}function Al(t,e){let n=kn[t];return n===void 0?!0:n>=kn[e]}function Pi(t){Tl={...t}}function zg(t){let e=(a,c=2)=>String(a).padStart(c,"0"),n=-t.getTimezoneOffset(),r=n>=0?"+":"-",i=Math.abs(n),s=e(Math.floor(i/60)),o=e(i%60);return`${Rn(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${r}${s}:${o}`}function $g(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function xi(t,e,n,r,i){if(kn[t]<kn[Do])return;let s=`${JSON.stringify({ts:zg(new Date),level:t,module:e,msg:n,...Tl,...r})}
|
|
11
|
+
`;if(Oi){let o=$g(i,r),a=o?Ug(Oi,o):Oi.bridgeSink;try{a.write(s)}catch{process.stderr.write(s)}return}t==="error"||t==="warn"?Mg.write(s):Fg.write(s)}function A(t,e){return{debug:(n,r)=>xi("debug",t,n,r,e),info:(n,r)=>xi("info",t,n,r,e),warn:(n,r)=>xi("warn",t,n,r,e),error:(n,r)=>xi("error",t,n,r,e),child:n=>A(`${t}.${n}`,e),forAgent:n=>A(t,n)}}var kn,Do,Fg,Mg,Tl,Bg,Oi,L=we(()=>{"use strict";ki();Co();kn={debug:10,info:20,warn:30,error:40},Do=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),Fg=process.stdout,Mg=process.stderr,Tl={},Bg=ut("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Oi=null});import{execFile as Gg,spawn as Hg,spawnSync as DT}from"node:child_process";import{promisify as jg}from"node:util";function qg(t){if(process.platform!=="win32")return!1;if(xl.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(xl,"").toLowerCase();return Wg.has(n)}function Ol(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return qg(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function Le(t,e=[],n={}){return Hg(t,e,Ol(t,n))}function bn(t,e=[],n={}){return Jg(t,e,Ol(t,n))}var Wg,xl,Jg,ft=we(()=>{"use strict";Wg=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),xl=/\.(cmd|bat|ps1)$/i;Jg=jg(Gg)});var _,Ie=we(()=>{"use strict";_=class extends Error{code;retriable;cause;constructor(e,n,r){super(n),this.name="BridgeError",this.code=e,this.retriable=r?.retriable??!1,r?.cause!==void 0&&(this.cause=r.cause)}}});var Fl={};Ri(Fl,{_resetAcpInstallerForTests:()=>rm,_resetInstallTimeoutsForTests:()=>tm,_setBinaryPathCacheForTests:()=>sm,_setInFlightForTests:()=>im,_setInstallTimeoutsForTests:()=>em,buildInstallFailureMessage:()=>Ll,ensureAcpInstalled:()=>Kt,formatExecError:()=>Dl,getAcpBinaryPath:()=>_r,getAcpPackageSpec:()=>Yg,getInFlightInstall:()=>Fo,npmInstallGlobal:()=>Nl,pickWhichLine:()=>Ni,probeAcpVersion:()=>nm,resolveAcpCommand:()=>Er});import{readFile as Vg,realpath as Zg,stat as Kg}from"node:fs/promises";import{dirname as No,join as Xg}from"node:path";function Yg(t){let e=Lo[t];if(e)return`${e.npmPackage}@${e.versionSpec}`}function em(t,e){Ci=t,Di=e}function tm(){Ci=5e4,Di=5e3}function Dl(t){if(t==null||typeof t!="object")return String(t);let e=t,n=[];e.message&&n.push(e.message),e.code!==void 0&&e.code!==null&&n.push(`code=${e.code}`),e.signal&&n.push(`signal=${e.signal}`);let r=e.stderr?.toString().trim();r&&n.push(`stderr=${r.slice(0,2e3)}`);let i=e.stdout?.toString().trim();return i&&n.push(`stdout=${i.slice(0,2e3)}`),n.length>0?n.join(" | "):String(t)}async function Pl(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:n}=await bn(e,[t],{timeout:Qg});return Ni(n)}catch{return}}function Ni(t){let e=t.split(/\r?\n/).map(r=>r.trim()).filter(Boolean);if(e.length===0)return;if(process.platform!=="win32")return e[0];let n=r=>e.find(i=>i.toLowerCase().endsWith(r));return n(".cmd")??n(".exe")??n(".bat")??n(".ps1")??e[0]}async function nm(t){let e=Lo[t];if(!e)return;let n=_r(t);if(!n){ye.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 r;try{r=await Zg(n)}catch(s){ye.warn("acp wrapper probe: realpath failed (symlink target \u4E0D\u5B58\u5728?)",{framework:t,binaryPath:n,err:String(s)});return}let i=No(r);for(let s=0;s<Cl;s++){let o=Xg(i,"package.json");try{if(!(await Kg(o)).isFile()){i=No(i);continue}let l=await Vg(o,"utf8"),d=JSON.parse(l);if(d.name===e.npmPackage){if(typeof d.version=="string"&&d.version.length>0)return d.version;ye.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"&&ye.warn("acp wrapper probe: package.json \u8BFB\u53D6\u5F02\u5E38",{framework:t,candidate:o,errCode:l?.code,err:String(c)})}let a=No(i);if(a===i)break;i=a}ye.warn("acp wrapper probe: \u627E\u4E0D\u5230\u5339\u914D name \u7684 package.json (\u4E0A\u6EAF\u5230 max depth)",{framework:t,binaryPath:n,realBinary:r,expectedName:e.npmPackage,maxDepth:Cl})}async function Nl(t,e,n){let r=`${t}@${e}`;ye.info("npm install -g start",{npmPackage:t,versionSpec:e});let i=Date.now(),s=process.platform==="win32";return new Promise((o,a)=>{let c=Le("npm",["install","-g",r],{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,h=0;c.stdout?.on("data",y=>{f+=y.length,f<d&&p.push(y)}),c.stderr?.on("data",y=>{h+=y.length,h<d&&m.push(y)});let g="running",w,S=y=>{try{return s?c.kill(y):process.kill(-l,y),!0}catch(E){return ye.warn("npm install: kill failed (process already dead?)",{npmPackage:t,pid:l,sig:y,err:String(E)}),!1}},v=setTimeout(()=>{g="terminating",ye.warn("npm install timeout, sending SIGTERM to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,timeoutMs:Ci,graceMs:Di,stdoutBytes:f,stderrBytes:h}),S("SIGTERM"),w=setTimeout(()=>{g="killing",ye.warn("npm install SIGTERM grace expired, escalating to SIGKILL",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,stdoutBytes:f,stderrBytes:h}),S("SIGKILL")},Di)},Ci),u=()=>{g="aborted",ye.warn("npm install externally aborted, sending SIGKILL to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i}),S("SIGKILL")};n&&(n.aborted?u():n.addEventListener("abort",u,{once:!0})),c.on("error",y=>{clearTimeout(v),w&&clearTimeout(w),n?.removeEventListener("abort",u),ye.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,E)=>{clearTimeout(v),w&&clearTimeout(w),n?.removeEventListener("abort",u);let R=Buffer.concat(p).toString("utf8"),T=Buffer.concat(m).toString("utf8"),D=Date.now()-i;if(y===0&&g==="running"){ye.info("npm install -g done",{npmPackage:t,versionSpec:e,elapsedMs:D}),o();return}ye.warn("npm install -g exited non-success",{npmPackage:t,versionSpec:e,pid:l,phase:g,exitCode:y,signal:E,elapsedMs:D,stdoutBytes:f,stderrBytes:h});let C=Object.assign(new Error(`Command failed: npm install -g ${r}`+(E?` (killed by ${E})`:"")+(y!==null?` (exit ${y})`:"")+(g!=="running"?` (phase=${g})`:"")),{code:y,signal:E,stderr:T,stdout:R});a(C)})})}function Ll(t){let{framework:e,npmPackage:n,versionSpec:r,command:i,reason:s,elapsedMs:o}=t;return["ACP wrapper \u5B89\u88C5\u5931\u8D25",`Framework: ${e}`,`Package: ${n}@${r}`,`\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(`
|
|
12
|
+
`)}async function Kt(t,e){let n=Lo[t];if(!n)throw new _("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let r=An.get(t);if(r)return r;let i=xn.get(t);if(i)return i;let s=`npm install -g ${n.npmPackage}@${n.versionSpec}`,o=(c,l,d)=>new _("AGENT_DEPENDENCY_INSTALL_FAILED",Ll({framework:t,npmPackage:n.npmPackage,versionSpec:n.versionSpec,command:s,reason:c,elapsedMs:l}),d!==void 0?{cause:d}:{}),a=(async()=>{let c=await Pl(n.binary);if(c)return An.set(t,c),ye.info("acp wrapper found on PATH",{binary:n.binary,path:c}),c;let l=Date.now();try{await Nl(n.npmPackage,n.versionSpec,e)}catch(p){let m=Dl(p);throw ye.warn("acp wrapper install failed",{framework:t,npmPackage:n.npmPackage,versionSpec:n.versionSpec,binary:n.binary,err:m}),o(m,Date.now()-l,p)}let d=await Pl(n.binary);if(!d)throw ye.warn("acp wrapper installed but binary not found on PATH",{framework:t,npmPackage:n.npmPackage,versionSpec:n.versionSpec,binary:n.binary}),o(`npm install \u6210\u529F\u4F46 \`${process.platform==="win32"?"where":"which"} ${n.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 An.set(t,d),d})().finally(()=>{xn.delete(t)});return xn.set(t,a),a}function _r(t){return An.get(t)}function Er(t,e){if(e)return e;let n=_r(t);if(!n)throw new _("BRIDGE_INTERNAL",`${t} ACP wrapper binary path cache miss (ensureAcpInstalled \u672A\u5728\u6784\u9020\u524D\u8DD1\u901A)`);return n}function Fo(t){return xn.get(t)}function rm(){An.clear(),xn.clear()}function im(t,e){xn.set(t,e)}function sm(t,e){An.set(t,e)}var ye,Lo,Ci,Di,Qg,An,xn,Cl,Xt=we(()=>{"use strict";ft();Ie();L();ye=A("agents.acp-installer"),Lo={"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"}};Ci=5e4,Di=5e3,Qg=5e3;An=new Map,xn=new Map;Cl=6});import{chmod as am,mkdir as cm,readFile as lm,rename as Ul,writeFile as zl}from"node:fs/promises";import{dirname as dm}from"node:path";async function On(t){try{let e=await lm(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Li(t,e,n){await cm(dm(t),{recursive:!0});let r=`${JSON.stringify(e,null,2)}
|
|
13
|
+
`,i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{n?.mode!==void 0?await zl(i,r,{encoding:"utf8",mode:n.mode}):await zl(i,r,"utf8"),await Ul(i,t),n?.mode!==void 0&&await am(t,n.mode)}catch(s){await Ul(i,i).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(i,{force:!0}).catch(()=>{}),s}}var Fi=we(()=>{"use strict"});import{promises as $l,readdirSync as um}from"node:fs";import{homedir as fm}from"node:os";import{sep as hm,join as ee,resolve as Gl}from"node:path";function F(t){let e=t??fm(),n=ee(e,".coze"),r=ee(n,"bridge"),i=ee(r,"lib"),s=ee(r,"logs");return{cozeRoot:n,bridgeRoot:r,libDir:i,libEntry:ee(i,"index.js"),binDir:ee(r,"bin"),pidFile:ee(r,"bridge.pid"),portFile:ee(r,"bridge.port"),tokenFile:ee(r,"bridge.token"),patTokenFile:ee(r,"pat-token"),logFile:ee(r,"bridge.log"),bridgeLogsDir:s,daemonStdioLog:ee(s,"daemon-stdio.log"),installLock:ee(r,"install.lock"),configFile:ee(r,"config.json"),agentsRoot:ee(n,"agents")}}function Re(t,e=F()){let n=ee(e.agentsRoot,t);return{root:n,config:ee(n,"config.json"),workspace:ee(n,"workspace"),logs:ee(n,"logs")}}function Hl(t=F()){try{return um(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function Sr(t,e){let n=await $l.realpath(Gl(t)).catch(()=>null);if(!n)return!1;let r=await $l.realpath(Gl(e)).catch(()=>null);if(!r)return!1;let i=process.platform==="win32"?n.toLowerCase():n,s=process.platform==="win32"?r.toLowerCase():r;return i===s||i.startsWith(s+hm)}var se=we(()=>{"use strict"});var Ui={};Ri(Ui,{AGENT_CONFIG_FILE_MODE:()=>Mi,enforceAgentConfigMode:()=>mm,loadAgentConfig:()=>fe,persistAgentSessions:()=>Ir,persistAgentSkills:()=>Bi,saveAgentConfig:()=>ke});import{chmod as pm,stat as gm}from"node:fs/promises";function fe(t,e){return On(Re(t,e).config)}function ke(t,e){return Li(Re(t.agentId,e).config,t,{mode:Mi})}async function mm(t,e){if(process.platform==="win32")return;let n=Re(t,e).config;try{let r=await gm(n);if(!r.isFile())return;let i=r.mode&511;i!==Mi&&(await pm(n,Mi),jl.warn("agent config mode auto-corrected to 0600",{path:n,from:i.toString(8)}))}catch(r){if(r.code==="ENOENT")return;jl.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(r)})}}async function Ir(t,e,n){let r=await fe(t,n);r&&(r.sessions=Object.fromEntries(e),await ke(r,n))}async function Bi(t,e,n){let r=await fe(t,n);r&&(r.skills=e,await ke(r,n))}var jl,Mi,Rt=we(()=>{"use strict";Fi();L();se();jl=A("agent-config"),Mi=384});var Bo=G((dR,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 $i=G(Kl=>{var Zl={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 Sm(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(n,r)=>e[r]||"")),new Error("ADM-ZIP: "+t)}}for(let t of Object.keys(Zl))Kl[t]=Sm(Zl[t])});var td=G((fR,ed)=>{var Im=H("fs"),te=H("path"),Xl=Bo(),vm=$i(),Tm=typeof process=="object"&&process.platform==="win32",Yl=t=>typeof t=="object"&&t!==null,Ql=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function K(t){this.sep=te.sep,this.fs=Im,Yl(t)&&Yl(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}ed.exports=K;K.prototype.makeDir=function(t){let e=this;function n(r){let i=r.split(e.sep)[0];r.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 vm.FILE_IN_THE_WAY(`"${i}"`)}})}n(t)};K.prototype.writeFileTo=function(t,e,n,r){let i=this;if(i.fs.existsSync(t)){if(!n)return!1;var s=i.fs.statSync(t);if(s.isDirectory())return!1}var o=te.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,r||438),!0};K.prototype.writeFileToAsync=function(t,e,n,r,i){typeof r=="function"&&(i=r,r=void 0);let s=this;s.fs.exists(t,function(o){if(o&&!n)return i(!1);s.fs.stat(t,function(a,c){if(o&&c.isDirectory())return i(!1);var l=te.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,h){s.fs.write(h,e,0,e.length,0,function(){s.fs.close(h,function(){s.fs.chmod(t,r||438,function(){i(!0)})})})})}):m?s.fs.write(m,e,0,e.length,0,function(){s.fs.close(m,function(){s.fs.chmod(t,r||438,function(){i(!0)})})}):s.fs.chmod(t,r||438,function(){i(!0)})})})})})};K.prototype.findFiles=function(t){let e=this;function n(r,i,s){typeof i=="boolean"&&(s=i,i=void 0);let o=[];return e.fs.readdirSync(r).forEach(function(a){let c=te.join(r,a),l=e.fs.statSync(c);(!i||i.test(c))&&o.push(te.normalize(c)+(l.isDirectory()?e.sep:"")),l.isDirectory()&&s&&(o=o.concat(n(c,i,s)))}),o}return n(t,void 0,!0)};K.prototype.findFilesAsync=function(t,e){let n=this,r=[];n.fs.readdir(t,function(i,s){if(i)return e(i);let o=s.length;if(!o)return e(null,r);s.forEach(function(a){a=te.join(t,a),n.fs.stat(a,function(c,l){if(c)return e(c);l&&(r.push(te.normalize(a)+(l.isDirectory()?n.sep:"")),l.isDirectory()?n.findFilesAsync(a,function(d,p){if(d)return e(d);r=r.concat(p),--o||e(null,r)}):--o||e(null,r))})})})};K.prototype.getAttributes=function(){};K.prototype.setAttributes=function(){};K.crc32update=function(t,e){return Ql[(t^e)&255]^t>>>8};K.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let r=0;r<e;)n=K.crc32update(n,t[r++]);return~n>>>0};K.methodToString=function(t){switch(t){case Xl.STORED:return"STORED ("+t+")";case Xl.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};K.canonical=function(t){if(!t)return"";let e=te.posix.normalize("/"+t.split("\\").join("/"));return te.join(".",e)};K.zipnamefix=function(t){if(!t)return"";let e=te.posix.normalize("/"+t.split("\\").join("/"));return te.posix.join(".",e)};K.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let n=t.length>>>0;for(let r=n-1;r>=0;r--)if(e(t[r],r,t))return t[r]};K.sanitize=function(t,e){t=te.resolve(te.normalize(t));for(var n=e.split("/"),r=0,i=n.length;r<i;r++){var s=te.normalize(te.join(t,n.slice(r,i).join(te.sep)));if(s.indexOf(t)===0)return s}return te.normalize(te.join(t,te.basename(e)))};K.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};K.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};K.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)};K.fromDate2DOS=function(t){let e=0,n=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),n=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|n};K.isWin=Tm;K.crcTable=Ql});var rd=G((hR,nd)=>{var Rm=H("path");nd.exports=function(t,{fs:e}){var n=t||"",r=s(),i=null;function s(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return n&&e.existsSync(n)?(i=e.statSync(n),r.directory=i.isDirectory(),r.mtime=i.mtime,r.atime=i.atime,r.executable=(73&i.mode)!==0,r.readonly=(128&i.mode)===0,r.hidden=Rm.basename(n)[0]==="."):console.warn("Invalid path: "+n),{get directory(){return r.directory},get readOnly(){return r.readonly},get hidden(){return r.hidden},get mtime(){return r.mtime},get atime(){return r.atime},get executable(){return r.executable},decodeAttributes:function(){},encodeAttributes:function(){},toJSON:function(){return{path:n,isDirectory:r.directory,isReadOnly:r.readonly,isHidden:r.hidden,isExecutable:r.executable,mTime:r.mtime,aTime:r.atime}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var sd=G((pR,id)=>{id.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Dn=G((gR,Cn)=>{Cn.exports=td();Cn.exports.Constants=Bo();Cn.exports.Errors=$i();Cn.exports.FileAttr=rd();Cn.exports.decoder=sd()});var ad=G((mR,od)=>{var kt=Dn(),k=kt.Constants;od.exports=function(){var t=20,e=10,n=0,r=0,i=0,s=0,o=0,a=0,c=0,l=0,d=0,p=0,m=0,f=0,h=0;t|=kt.isWin?2560:768,n|=k.FLG_EFS;let g={extraLen:0},w=u=>Math.max(0,u)>>>0,S=u=>Math.max(0,u)&65535,v=u=>Math.max(0,u)&255;return i=kt.fromDate2DOS(new Date),{get made(){return t},set made(u){t=u},get version(){return e},set version(u){e=u},get flags(){return n},set flags(u){n=u},get flags_efs(){return(n&k.FLG_EFS)>0},set flags_efs(u){u?n|=k.FLG_EFS:n&=~k.FLG_EFS},get flags_desc(){return(n&k.FLG_DESC)>0},set flags_desc(u){u?n|=k.FLG_DESC:n&=~k.FLG_DESC},get method(){return r},set method(u){switch(u){case k.STORED:this.version=10;case k.DEFLATED:default:this.version=20}r=u},get time(){return kt.fromDOS2Date(this.timeval)},set time(u){u=new Date(u),this.timeval=kt.fromDate2DOS(u)},get timeval(){return i},set timeval(u){i=w(u)},get timeHighByte(){return v(i>>>8)},get crc(){return s},set crc(u){s=w(u)},get compressedSize(){return o},set compressedSize(u){o=w(u)},get size(){return a},set size(u){a=w(u)},get fileNameLength(){return c},set fileNameLength(u){c=u},get extraLength(){return l},set extraLength(u){l=u},get extraLocalLength(){return g.extraLen},set extraLocalLength(u){g.extraLen=u},get commentLength(){return d},set commentLength(u){d=u},get diskNumStart(){return p},set diskNumStart(u){p=w(u)},get inAttr(){return m},set inAttr(u){m=w(u)},get attr(){return f},set attr(u){f=w(u)},get fileAttr(){return(f||0)>>16&4095},get offset(){return h},set offset(u){h=w(u)},get encrypted(){return(n&k.FLG_ENC)===k.FLG_ENC},get centralHeaderSize(){return k.CENHDR+c+l+d},get realDataOffset(){return h+k.LOCHDR+g.fnameLen+g.extraLen},get localHeader(){return g},loadLocalHeaderFromBinary:function(u){var y=u.slice(h,h+k.LOCHDR);if(y.readUInt32LE(0)!==k.LOCSIG)throw kt.Errors.INVALID_LOC();g.version=y.readUInt16LE(k.LOCVER),g.flags=y.readUInt16LE(k.LOCFLG),g.flags_desc=(g.flags&k.FLG_DESC)>0,g.method=y.readUInt16LE(k.LOCHOW),g.time=y.readUInt32LE(k.LOCTIM),g.crc=y.readUInt32LE(k.LOCCRC),g.compressedSize=y.readUInt32LE(k.LOCSIZ),g.size=y.readUInt32LE(k.LOCLEN),g.fnameLen=y.readUInt16LE(k.LOCNAM),g.extraLen=y.readUInt16LE(k.LOCEXT);let E=h+k.LOCHDR+g.fnameLen,R=E+g.extraLen;return u.slice(E,R)},loadFromBinary:function(u){if(u.length!==k.CENHDR||u.readUInt32LE(0)!==k.CENSIG)throw kt.Errors.INVALID_CEN();t=u.readUInt16LE(k.CENVEM),e=u.readUInt16LE(k.CENVER),n=u.readUInt16LE(k.CENFLG),r=u.readUInt16LE(k.CENHOW),i=u.readUInt32LE(k.CENTIM),s=u.readUInt32LE(k.CENCRC),o=u.readUInt32LE(k.CENSIZ),a=u.readUInt32LE(k.CENLEN),c=u.readUInt16LE(k.CENNAM),l=u.readUInt16LE(k.CENEXT),d=u.readUInt16LE(k.CENCOM),p=u.readUInt16LE(k.CENDSK),m=u.readUInt16LE(k.CENATT),f=u.readUInt32LE(k.CENATX),h=u.readUInt32LE(k.CENOFF)},localHeaderToBinary:function(){var u=Buffer.alloc(k.LOCHDR);return u.writeUInt32LE(k.LOCSIG,0),u.writeUInt16LE(e,k.LOCVER),u.writeUInt16LE(n,k.LOCFLG),u.writeUInt16LE(r,k.LOCHOW),u.writeUInt32LE(i,k.LOCTIM),u.writeUInt32LE(s,k.LOCCRC),u.writeUInt32LE(o,k.LOCSIZ),u.writeUInt32LE(a,k.LOCLEN),u.writeUInt16LE(c,k.LOCNAM),u.writeUInt16LE(g.extraLen,k.LOCEXT),u},centralHeaderToBinary:function(){var u=Buffer.alloc(k.CENHDR+c+l+d);return u.writeUInt32LE(k.CENSIG,0),u.writeUInt16LE(t,k.CENVEM),u.writeUInt16LE(e,k.CENVER),u.writeUInt16LE(n,k.CENFLG),u.writeUInt16LE(r,k.CENHOW),u.writeUInt32LE(i,k.CENTIM),u.writeUInt32LE(s,k.CENCRC),u.writeUInt32LE(o,k.CENSIZ),u.writeUInt32LE(a,k.CENLEN),u.writeUInt16LE(c,k.CENNAM),u.writeUInt16LE(l,k.CENEXT),u.writeUInt16LE(d,k.CENCOM),u.writeUInt16LE(p,k.CENDSK),u.writeUInt16LE(m,k.CENATT),u.writeUInt32LE(f,k.CENATX),u.writeUInt32LE(h,k.CENOFF),u},toJSON:function(){let u=function(y){return y+" bytes"};return{made:t,version:e,flags:n,method:kt.methodToString(r),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:u(o),size:u(a),fileNameLength:u(c),extraLength:u(l),commentLength:u(d),diskNumStart:p,inAttr:m,attr:f,offset:h,centralHeaderSize:u(k.CENHDR+c+l+d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var ld=G((wR,cd)=>{var Nn=Dn(),q=Nn.Constants;cd.exports=function(){var t=0,e=0,n=0,r=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 n},set size(s){n=s},get offset(){return r},set offset(s){r=s},get commentLength(){return i},set commentLength(s){i=s},get mainHeaderSize(){return q.ENDHDR+i},loadFromBinary:function(s){if((s.length!==q.ENDHDR||s.readUInt32LE(0)!==q.ENDSIG)&&(s.length<q.ZIP64HDR||s.readUInt32LE(0)!==q.ZIP64SIG))throw Nn.Errors.INVALID_END();s.readUInt32LE(0)===q.ENDSIG?(t=s.readUInt16LE(q.ENDSUB),e=s.readUInt16LE(q.ENDTOT),n=s.readUInt32LE(q.ENDSIZ),r=s.readUInt32LE(q.ENDOFF),i=s.readUInt16LE(q.ENDCOM)):(t=Nn.readBigUInt64LE(s,q.ZIP64SUB),e=Nn.readBigUInt64LE(s,q.ZIP64TOT),n=Nn.readBigUInt64LE(s,q.ZIP64SIZE),r=Nn.readBigUInt64LE(s,q.ZIP64OFF),i=0)},toBinary:function(){var s=Buffer.alloc(q.ENDHDR+i);return s.writeUInt32LE(q.ENDSIG,0),s.writeUInt32LE(0,4),s.writeUInt16LE(t,q.ENDSUB),s.writeUInt16LE(e,q.ENDTOT),s.writeUInt32LE(n,q.ENDSIZ),s.writeUInt32LE(r,q.ENDOFF),s.writeUInt16LE(i,q.ENDCOM),s.fill(" ",q.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:n+" bytes",offset:s(r,4),commentLength:i}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var zo=G(Uo=>{Uo.EntryHeader=ad();Uo.MainHeader=ld()});var ud=G((_R,dd)=>{dd.exports=function(t){var e=H("zlib"),n={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:function(){return e.deflateRawSync(t,n)},deflateAsync:function(r){var i=e.createDeflateRaw(n),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}r&&r(a)}),i.end(t)}}}});var hd=G((ER,fd)=>{var km=+(process.versions?process.versions.node:"").split(".")[0]||0;fd.exports=function(t,e){var n=H("zlib");let r=km>=15&&e>0?{maxOutputLength:e}:{};return{inflate:function(){return n.inflateRawSync(t,r)},inflateAsync:function(i){var s=n.createInflateRaw(r),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 yd=G((SR,wd)=>{"use strict";var{randomFillSync:pd}=H("crypto"),bm=$i(),Am=new Uint32Array(256).map((t,e)=>{for(let n=0;n<8;n++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),md=(t,e)=>Math.imul(t,e)>>>0,gd=(t,e)=>Am[(t^e)&255]^t>>>8,vr=()=>typeof pd=="function"?pd(Buffer.alloc(12)):vr.node();vr.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let n=0;n<e;n++)t[n]=Math.random()*256&255;return t};var Gi={genSalt:vr};function Hi(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let n=0;n<e.length;n++)this.updateKeys(e[n])}Hi.prototype.updateKeys=function(t){let e=this.keys;return e[0]=gd(e[0],t),e[1]+=e[0]&255,e[1]=md(e[1],134775813)+1,e[2]=gd(e[2],e[1]>>>24),t};Hi.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return md(t,t^1)>>8&255};function xm(t){let e=new Hi(t);return function(n){let r=Buffer.alloc(n.length),i=0;for(let s of n)r[i++]=e.updateKeys(s^e.next());return r}}function Om(t){let e=new Hi(t);return function(n,r,i=0){r||(r=Buffer.alloc(n.length));for(let s of n){let o=e.next();r[i++]=s^o,e.updateKeys(s)}return r}}function Pm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let r=xm(n),i=r(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw bm.WRONG_PASSWORD();return r(t.slice(12))}function Cm(t){Buffer.isBuffer(t)&&t.length>=12?Gi.genSalt=function(){return t.slice(0,12)}:t==="node"?Gi.genSalt=vr.node:Gi.genSalt=vr}function Dm(t,e,n,r=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=Om(n),s=Gi.genSalt();s[11]=e.crc>>>24&255,r&&(s[10]=e.crc>>>16&255);let o=Buffer.alloc(t.length+12);return i(s,o),i(t,o,12)}wd.exports={decrypt:Pm,encrypt:Dm,_salter:Cm}});var _d=G(ji=>{ji.Deflater=ud();ji.Inflater=hd();ji.ZipCrypto=yd()});var Go=G((vR,Ed)=>{var z=Dn(),Nm=zo(),X=z.Constants,$o=_d();Ed.exports=function(t,e){var n=new Nm.EntryHeader,r=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:z.decoder;l=p.hasOwnProperty("efs")?p.efs:!1;function m(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(c=n.loadLocalHeaderFromBinary(e),e.slice(n.realDataOffset,n.realDataOffset+n.compressedSize))}function f(u){if(!n.flags_desc&&!n.localHeader.flags_desc){if(z.crc32(u)!==n.localHeader.crc)return!1}else{let y={},E=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(E)==X.LOCSIG||e.readUInt32LE(E)==X.CENSIG)throw z.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(E)==X.EXTSIG)y.crc=e.readUInt32LE(E+X.EXTCRC),y.compressedSize=e.readUInt32LE(E+X.EXTSIZ),y.size=e.readUInt32LE(E+X.EXTLEN);else if(e.readUInt16LE(E+12)===19280)y.crc=e.readUInt32LE(E+X.EXTCRC-4),y.compressedSize=e.readUInt32LE(E+X.EXTSIZ-4),y.size=e.readUInt32LE(E+X.EXTLEN-4);else throw z.Errors.DESCRIPTOR_UNKNOWN();if(y.compressedSize!==n.compressedSize||y.size!==n.size||y.crc!==n.crc)throw z.Errors.DESCRIPTOR_FAULTY();if(z.crc32(u)!==y.crc)return!1}return!0}function h(u,y,E){if(typeof y>"u"&&typeof u=="string"&&(E=u,u=void 0),s)return u&&y&&y(Buffer.alloc(0),z.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var R=m();if(R.length===0)return u&&y&&y(R),R;if(n.encrypted){if(typeof E!="string"&&!Buffer.isBuffer(E))throw z.Errors.INVALID_PASS_PARAM();R=$o.ZipCrypto.decrypt(R,n,E)}var T=Buffer.alloc(n.size);switch(n.method){case z.Constants.STORED:if(R.copy(T),f(T))return u&&y&&y(T),T;throw u&&y&&y(T,z.Errors.BAD_CRC()),z.Errors.BAD_CRC();case z.Constants.DEFLATED:var D=new $o.Inflater(R,n.size);if(u)D.inflateAsync(function(C){C.copy(C,0),y&&(f(C)?y(C):y(C,z.Errors.BAD_CRC()))});else{if(D.inflate(T).copy(T,0),!f(T))throw z.Errors.BAD_CRC(`"${p.decode(r)}"`);return T}break;default:throw u&&y&&y(Buffer.alloc(0),z.Errors.UNKNOWN_METHOD()),z.Errors.UNKNOWN_METHOD()}}function g(u,y){if((!o||!o.length)&&Buffer.isBuffer(e))return u&&y&&y(m()),m();if(o.length&&!s){var E;switch(n.method){case z.Constants.STORED:return n.compressedSize=n.size,E=Buffer.alloc(o.length),o.copy(E),u&&y&&y(E),E;default:case z.Constants.DEFLATED:var R=new $o.Deflater(o);if(u)R.deflateAsync(function(D){E=Buffer.alloc(D.length),n.compressedSize=D.length,D.copy(E),y&&y(E)});else{var T=R.deflate();return n.compressedSize=T.length,T}R=null;break}}else if(u&&y)y(Buffer.alloc(0));else return Buffer.alloc(0)}function w(u,y){return z.readBigUInt64LE(u,y)}function S(u){try{for(var y=0,E,R,T;y+4<u.length;)E=u.readUInt16LE(y),y+=2,R=u.readUInt16LE(y),y+=2,T=u.slice(y,y+R),y+=R,X.ID_ZIP64===E&&v(T)}catch{throw z.Errors.EXTRA_FIELD_PARSE_ERROR()}}function v(u){var y,E,R,T;u.length>=X.EF_ZIP64_SCOMP&&(y=w(u,X.EF_ZIP64_SUNCOMP),n.size===X.EF_ZIP64_OR_32&&(n.size=y)),u.length>=X.EF_ZIP64_RHO&&(E=w(u,X.EF_ZIP64_SCOMP),n.compressedSize===X.EF_ZIP64_OR_32&&(n.compressedSize=E)),u.length>=X.EF_ZIP64_DSN&&(R=w(u,X.EF_ZIP64_RHO),n.offset===X.EF_ZIP64_OR_32&&(n.offset=R)),u.length>=X.EF_ZIP64_DSN+4&&(T=u.readUInt32LE(X.EF_ZIP64_DSN),n.diskNumStart===X.EF_ZIP64_OR_16&&(n.diskNumStart=T))}return{get entryName(){return p.decode(r)},get rawEntryName(){return r},set entryName(u){r=z.toBuffer(u,p.encode);var y=r[r.length-1];s=y===47||y===92,n.fileNameLength=r.length},get efs(){return typeof l=="function"?l(this.entryName):l},get extra(){return a},set extra(u){a=u,n.extraLength=u.length,S(u)},get comment(){return p.decode(i)},set comment(u){if(i=z.toBuffer(u,p.encode),n.commentLength=i.length,i.length>65535)throw z.Errors.COMMENT_TOO_LONG()},get name(){var u=p.decode(r);return s?u.substr(u.length-1).split("/").pop():u.split("/").pop()},get isDirectory(){return s},getCompressedData:function(){return g(!1,null)},getCompressedDataAsync:function(u){g(!0,u)},setData:function(u){o=z.toBuffer(u,z.decoder.encode),!s&&o.length?(n.size=o.length,n.method=z.Constants.DEFLATED,n.crc=z.crc32(u),n.changed=!0):n.method=z.Constants.STORED},getData:function(u){return n.changed?o:h(!1,null,u)},getDataAsync:function(u,y){n.changed?u(o):h(!0,u,y)},set attr(u){n.attr=u},get attr(){return n.attr},set header(u){n.loadFromBinary(u)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=a.length;var u=n.centralHeaderToBinary(),y=z.Constants.CENHDR;return r.copy(u,y),y+=r.length,a.copy(u,y),y+=n.extraLength,i.copy(u,y),u},packLocalHeader:function(){let u=0;n.flags_efs=this.efs,n.extraLocalLength=c.length;let y=n.localHeaderToBinary(),E=Buffer.alloc(y.length+r.length+n.extraLocalLength);return y.copy(E,u),u+=y.length,r.copy(E,u),u+=r.length,c.copy(E,u),u+=c.length,E},toJSON:function(){let u=function(y){return"<"+(y&&y.length+" bytes buffer"||"null")+">"};return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:n.toJSON(),compressedData:u(e),data:u(o)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var vd=G((TR,Id)=>{var Sd=Go(),Lm=zo(),he=Dn();Id.exports=function(t,e){var n=[],r={},i=Buffer.alloc(0),s=new Lm.MainHeader,o=!1,a=null;let c=new Set,l=e,{noSort:d,decoder:p}=l;t?h(l.readEntries):o=!0;function m(){let w=new Set;for(let S of Object.keys(r)){let v=S.split("/");if(v.pop(),!!v.length)for(let u=0;u<v.length;u++){let y=v.slice(0,u+1).join("/")+"/";w.add(y)}}for(let S of w)if(!(S in r)){let v=new Sd(l);v.entryName=S,v.attr=16,v.temporary=!0,n.push(v),r[v.entryName]=v,c.add(v)}}function f(){if(o=!0,r={},s.diskEntries>(t.length-s.offset)/he.Constants.CENHDR)throw he.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(s.diskEntries);for(var w=s.offset,S=0;S<n.length;S++){var v=w,u=new Sd(l,t);u.header=t.slice(v,v+=he.Constants.CENHDR),u.entryName=t.slice(v,v+=u.header.fileNameLength),u.header.extraLength&&(u.extra=t.slice(v,v+=u.header.extraLength)),u.header.commentLength&&(u.comment=t.slice(v,v+u.header.commentLength)),w+=u.header.centralHeaderSize,n[S]=u,r[u.entryName]=u}c.clear(),m()}function h(w){var S=t.length-he.Constants.ENDHDR,v=Math.max(0,S-65535),u=v,y=t.length,E=-1,R=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(v=0),S;S>=u;S--)if(t[S]===80){if(t.readUInt32LE(S)===he.Constants.ENDSIG){E=S,R=S,y=S+he.Constants.ENDHDR,u=S-he.Constants.END64HDR;continue}if(t.readUInt32LE(S)===he.Constants.END64SIG){u=v;continue}if(t.readUInt32LE(S)===he.Constants.ZIP64SIG){E=S,y=S+he.readBigUInt64LE(t,S+he.Constants.ZIP64SIZE)+he.Constants.ZIP64LEAD;break}}if(E==-1)throw he.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(E,y)),s.commentLength&&(i=t.slice(R+he.Constants.ENDHDR)),w&&f()}function g(){n.length>1&&!d&&n.sort((w,S)=>w.entryName.toLowerCase().localeCompare(S.entryName.toLowerCase()))}return{get entries(){return o||f(),n.filter(w=>!c.has(w))},get comment(){return p.decode(i)},set comment(w){i=he.toBuffer(w,p.encode),s.commentLength=i.length},getEntryCount:function(){return o?n.length:s.diskEntries},forEach:function(w){this.entries.forEach(w)},getEntry:function(w){return o||f(),r[w]||null},setEntry:function(w){o||f(),n.push(w),r[w.entryName]=w,s.totalEntries=n.length},deleteFile:function(w,S=!0){o||f();let v=r[w];this.getEntryChildren(v,S).map(y=>y.entryName).forEach(this.deleteEntry)},deleteEntry:function(w){o||f();let S=r[w],v=n.indexOf(S);v>=0&&(n.splice(v,1),delete r[w],s.totalEntries=n.length)},getEntryChildren:function(w,S=!0){if(o||f(),typeof w=="object")if(w.isDirectory&&S){let v=[],u=w.entryName;for(let y of n)y.entryName.startsWith(u)&&v.push(y);return v}else return[w];return[]},getChildCount:function(w){if(w&&w.isDirectory){let S=this.getEntryChildren(w);return S.includes(w)?S.length-1:S.length}return 0},compressToBuffer:function(){o||f(),g();let w=[],S=[],v=0,u=0;s.size=0,s.offset=0;let y=0;for(let T of this.entries){let D=T.getCompressedData();T.header.offset=u;let C=T.packLocalHeader(),U=C.length+D.length;u+=U,w.push(C),w.push(D);let I=T.packCentralHeader();S.push(I),s.size+=I.length,v+=U+I.length,y++}v+=s.mainHeaderSize,s.offset=u,s.totalEntries=y,u=0;let E=Buffer.alloc(v);for(let T of w)T.copy(E,u),u+=T.length;for(let T of S)T.copy(E,u),u+=T.length;let R=s.toBinary();return i&&i.copy(R,he.Constants.ENDHDR),R.copy(E,u),t=E,o=!1,E},toAsyncBuffer:function(w,S,v,u){try{o||f(),g();let y=[],E=[],R=0,T=0,D=0;s.size=0,s.offset=0;let C=function(U){if(U.length>0){let I=U.shift(),b=I.entryName+I.extra.toString();v&&v(b),I.getCompressedDataAsync(function(x){u&&u(b),I.header.offset=T;let ue=I.packLocalHeader(),Ee=ue.length+x.length;T+=Ee,y.push(ue),y.push(x);let Ne=I.packCentralHeader();E.push(Ne),s.size+=Ne.length,R+=Ee+Ne.length,D++,C(U)})}else{R+=s.mainHeaderSize,s.offset=T,s.totalEntries=D,T=0;let I=Buffer.alloc(R);y.forEach(function(x){x.copy(I,T),T+=x.length}),E.forEach(function(x){x.copy(I,T),T+=x.length});let b=s.toBinary();i&&i.copy(b,he.Constants.ENDHDR),b.copy(I,T),t=I,o=!1,w(I)}};C(Array.from(this.entries))}catch(y){S(y)}}}}});var kd=G((RR,Rd)=>{var V=Dn(),J=H("path"),Fm=Go(),Mm=vd(),Yt=(...t)=>V.findLast(t,e=>typeof e=="boolean"),Td=(...t)=>V.findLast(t,e=>typeof e=="string"),Bm=(...t)=>V.findLast(t,e=>typeof e=="function"),Um={noSort:!1,readEntries:!1,method:V.Constants.NONE,fs:null};Rd.exports=function(t,e){let n=null,r=Object.assign(Object.create(null),Um);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(r,t),t=r.input?r.input:void 0,r.input&&delete r.input),Buffer.isBuffer(t)&&(n=t,r.method=V.Constants.BUFFER,t=void 0)),Object.assign(r,e);let i=new V(r);if((typeof r.decoder!="object"||typeof r.decoder.encode!="function"||typeof r.decoder.decode!="function")&&(r.decoder=V.decoder),t&&typeof t=="string")if(i.fs.existsSync(t))r.method=V.Constants.FILE,r.filename=t,n=i.fs.readFileSync(t);else throw V.Errors.INVALID_FILENAME();let s=new Mm(n,r),{canonical:o,sanitize:a,zipnamefix:c}=V;function l(f){if(f&&s){var h;if(typeof f=="string"&&(h=s.getEntry(J.posix.normalize(f))),typeof f=="object"&&typeof f.entryName<"u"&&typeof f.header<"u"&&(h=s.getEntry(f.entryName)),h)return h}return null}function d(f){let{join:h,normalize:g,sep:w}=J.posix;return h(J.isAbsolute(f)?"/":".",g(w+f.split("\\").join(w)+w))}function p(f){return f instanceof RegExp?(function(h){return function(g){return h.test(g)}})(f):typeof f!="function"?()=>!0:f}let m=(f,h)=>{let g=h.slice(-1);return g=g===i.sep?i.sep:"",J.relative(f,h)+g};return{readFile:function(f,h){var g=l(f);return g&&g.getData(h)||null},childCount:function(f){let h=l(f);if(h)return s.getChildCount(h)},readFileAsync:function(f,h){var g=l(f);g?g.getDataAsync(h):h(null,"getEntry failed for:"+f)},readAsText:function(f,h){var g=l(f);if(g){var w=g.getData();if(w&&w.length)return w.toString(h||"utf8")}return""},readAsTextAsync:function(f,h,g){var w=l(f);w?w.getDataAsync(function(S,v){if(v){h(S,v);return}S&&S.length?h(S.toString(g||"utf8")):h("")}):h("")},deleteFile:function(f,h=!0){var g=l(f);g&&s.deleteFile(g.entryName,h)},deleteEntry:function(f){var h=l(f);h&&s.deleteEntry(h.entryName)},addZipComment:function(f){s.comment=f},getZipComment:function(){return s.comment||""},addZipEntryComment:function(f,h){var g=l(f);g&&(g.comment=h)},getZipEntryComment:function(f){var h=l(f);return h&&h.comment||""},updateFile:function(f,h){var g=l(f);g&&g.setData(h)},addLocalFile:function(f,h,g,w){if(i.fs.existsSync(f)){h=h?d(h):"";let S=J.win32.basename(J.win32.normalize(f));h+=g||S;let v=i.fs.statSync(f),u=v.isFile()?i.fs.readFileSync(f):Buffer.alloc(0);v.isDirectory()&&(h+=i.sep),this.addFile(h,u,w,v)}else throw V.Errors.FILE_NOT_FOUND(f)},addLocalFileAsync:function(f,h){f=typeof f=="object"?f:{localPath:f};let g=J.resolve(f.localPath),{comment:w}=f,{zipPath:S,zipName:v}=f,u=this;i.fs.stat(g,function(y,E){if(y)return h(y,!1);S=S?d(S):"";let R=J.win32.basename(J.win32.normalize(g));if(S+=v||R,E.isFile())i.fs.readFile(g,function(T,D){return T?h(T,!1):(u.addFile(S,D,w,E),setImmediate(h,void 0,!0))});else if(E.isDirectory())return S+=i.sep,u.addFile(S,Buffer.alloc(0),w,E),setImmediate(h,void 0,!0)})},addLocalFolder:function(f,h,g){if(g=p(g),h=h?d(h):"",f=J.normalize(f),i.fs.existsSync(f)){let w=i.findFiles(f),S=this;if(w.length)for(let v of w){let u=J.join(h,m(f,v));g(u)&&S.addLocalFile(v,J.dirname(u))}}else throw V.Errors.FILE_NOT_FOUND(f)},addLocalFolderAsync:function(f,h,g,w){w=p(w),g=g?d(g):"",f=J.normalize(f);var S=this;i.fs.open(f,"r",function(v){if(v&&v.code==="ENOENT")h(void 0,V.Errors.FILE_NOT_FOUND(f));else if(v)h(void 0,v);else{var u=i.findFiles(f),y=-1,E=function(){if(y+=1,y<u.length){var R=u[y],T=m(f,R).split("\\").join("/");T=T.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),w(T)?i.fs.stat(R,function(D,C){D&&h(void 0,D),C.isFile()?i.fs.readFile(R,function(U,I){U?h(void 0,U):(S.addFile(g+T,I,"",C),E())}):(S.addFile(g+T+"/",Buffer.alloc(0),"",C),E())}):process.nextTick(()=>{E()})}else h(!0,void 0)};E()}})},addLocalFolderAsync2:function(f,h){let g=this;f=typeof f=="object"?f:{localPath:f},localPath=J.resolve(d(f.localPath));let{zipPath:w,filter:S,namefix:v}=f;S instanceof RegExp?S=(function(E){return function(R){return E.test(R)}})(S):typeof S!="function"&&(S=function(){return!0}),w=w?d(w):"",v=="latin1"&&(v=E=>E.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,"")),typeof v!="function"&&(v=E=>E);let u=E=>J.join(w,v(m(localPath,E))),y=E=>J.win32.basename(J.win32.normalize(v(E)));i.fs.open(localPath,"r",function(E){E&&E.code==="ENOENT"?h(void 0,V.Errors.FILE_NOT_FOUND(localPath)):E?h(void 0,E):i.findFilesAsync(localPath,function(R,T){if(R)return h(R);T=T.filter(D=>S(u(D))),T.length||h(void 0,!1),setImmediate(T.reverse().reduce(function(D,C){return function(U,I){if(U||I===!1)return setImmediate(D,U,!1);g.addLocalFileAsync({localPath:C,zipPath:J.dirname(u(C)),zipName:y(C)},D)}},h))})})},addLocalFolderPromise:function(f,h){return new Promise((g,w)=>{this.addLocalFolderAsync2(Object.assign({localPath:f},h),(S,v)=>{S&&w(S),v&&g(this)})})},addFile:function(f,h,g,w){f=c(f);let S=l(f),v=S!=null;v||(S=new Fm(r),S.entryName=f),S.comment=g||"";let u=typeof w=="object"&&w instanceof i.fs.Stats;u&&(S.header.time=w.mtime);var y=S.isDirectory?16:0;let E=S.isDirectory?16384:32768;return u?E|=4095&w.mode:typeof w=="number"?E|=4095&w:E|=S.isDirectory?493:420,y=(y|E<<16)>>>0,S.attr=y,S.setData(h),v||s.setEntry(S),S},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,h,g,w,S,v){w=Yt(!1,w),S=Yt(!1,S),g=Yt(!0,g),v=Td(S,v);var u=l(f);if(!u)throw V.Errors.NO_ENTRY();var y=o(u.entryName),E=a(h,v&&!u.isDirectory?v:g?y:J.basename(y));if(u.isDirectory){var R=s.getEntryChildren(u);return R.forEach(function(C){if(C.isDirectory)return;var U=C.getData();if(!U)throw V.Errors.CANT_EXTRACT_FILE();var I=o(C.entryName),b=a(h,g?I:J.basename(I));let x=S?C.header.fileAttr:void 0;i.writeFileTo(b,U,w,x)}),!0}var T=u.getData(s.password);if(!T)throw V.Errors.CANT_EXTRACT_FILE();if(i.fs.existsSync(E)&&!w)throw V.Errors.CANT_OVERRIDE();let D=S?f.header.fileAttr:void 0;return i.writeFileTo(E,T,w,D),!0},test:function(f){if(!s)return!1;for(var h in s.entries)try{if(h.isDirectory)continue;var g=s.entries[h].getData(f);if(!g)return!1}catch{return!1}return!0},extractAllTo:function(f,h,g,w){if(g=Yt(!1,g),w=Td(g,w),h=Yt(!1,h),!s)throw V.Errors.NO_ZIP();s.entries.forEach(function(S){var v=a(f,o(S.entryName));if(S.isDirectory){i.makeDir(v);return}var u=S.getData(w);if(!u)throw V.Errors.CANT_EXTRACT_FILE();let y=g?S.header.fileAttr:void 0;i.writeFileTo(v,u,h,y);try{i.fs.utimesSync(v,S.header.time,S.header.time)}catch{throw V.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(f,h,g,w){if(w=Bm(h,g,w),g=Yt(!1,g),h=Yt(!1,h),!w)return new Promise((E,R)=>{this.extractAllToAsync(f,h,g,function(T){T?R(T):E(this)})});if(!s){w(V.Errors.NO_ZIP());return}f=J.resolve(f);let S=E=>a(f,J.normalize(o(E.entryName))),v=(E,R)=>new Error(E+': "'+R+'"'),u=[],y=[];s.entries.forEach(E=>{E.isDirectory?u.push(E):y.push(E)});for(let E of u){let R=S(E),T=g?E.header.fileAttr:void 0;try{i.makeDir(R),T&&i.fs.chmodSync(R,T),i.fs.utimesSync(R,E.header.time,E.header.time)}catch{w(v("Unable to create folder",R))}}y.reverse().reduce(function(E,R){return function(T){if(T)E(T);else{let D=J.normalize(o(R.entryName)),C=a(f,D);R.getDataAsync(function(U,I){if(I)E(I);else if(!U)E(V.Errors.CANT_EXTRACT_FILE());else{let b=g?R.header.fileAttr:void 0;i.writeFileToAsync(C,U,h,b,function(x){x||E(v("Unable to write file",C)),i.fs.utimes(C,R.header.time,R.header.time,function(ue){ue?E(v("Unable to set times",C)):E()})})}})}}},w)()},writeZip:function(f,h){if(arguments.length===1&&typeof f=="function"&&(h=f,f=""),!f&&r.filename&&(f=r.filename),!!f){var g=s.compressToBuffer();if(g){var w=i.writeFileTo(f,g,!0);typeof h=="function"&&h(w?null:new Error("failed"),"")}}},writeZipPromise:function(f,h){let{overwrite:g,perm:w}=Object.assign({overwrite:!0},h);return new Promise((S,v)=>{!f&&r.filename&&(f=r.filename),f||v("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(u=>{let y=E=>E?S(E):v("ADM-ZIP: Wasn't able to write zip file");i.writeFileToAsync(f,u,g,w,y)},v)})},toBufferPromise:function(){return new Promise((f,h)=>{s.toAsyncBuffer(f,h)})},toBuffer:function(f,h,g,w){return typeof f=="function"?(s.toAsyncBuffer(f,h,g,w),null):s.compressToBuffer()}}}});function a0(){return sh||(sh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function c0(){return oh||(oh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function l0(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{n(Be(t.result)),i()},o=()=>{r(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(n=>{n instanceof IDBCursor&&ah.set(n,t)}).catch(()=>{}),mc.set(e,t),e}function d0(t){if(pc.has(t))return;let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("complete",s),t.removeEventListener("error",o),t.removeEventListener("abort",o)},s=()=>{n(),i()},o=()=>{r(t.error||new DOMException("AbortError","AbortError")),i()};t.addEventListener("complete",s),t.addEventListener("error",o),t.addEventListener("abort",o)});pc.set(t,e)}function lh(t){gc=t(gc)}function u0(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(ci(this),e,...n);return ch.set(r,e.sort?e.sort():[e]),Be(r)}:c0().includes(t)?function(...e){return t.apply(ci(this),e),Be(ah.get(this))}:function(...e){return Be(t.apply(ci(this),e))}}function f0(t){return typeof t=="function"?u0(t):(t instanceof IDBTransaction&&d0(t),o0(t,a0())?new Proxy(t,gc):t)}function Be(t){if(t instanceof IDBRequest)return l0(t);if(hc.has(t))return hc.get(t);let e=f0(t);return e!==t&&(hc.set(t,e),mc.set(e,t)),e}var o0,sh,oh,ah,pc,ch,hc,mc,gc,ci,wc=we(()=>{o0=(t,e)=>e.some(n=>t instanceof n);ah=new WeakMap,pc=new WeakMap,ch=new WeakMap,hc=new WeakMap,mc=new WeakMap;gc={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return pc.get(t);if(e==="objectStoreNames")return t.objectStoreNames||ch.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Be(t[e])},set(t,e,n){return t[e]=n,!0},has(t,e){return t instanceof IDBTransaction&&(e==="done"||e==="store")?!0:e in t}};ci=t=>mc.get(t)});var uh={};Ri(uh,{deleteDB:()=>p0,openDB:()=>h0,unwrap:()=>ci,wrap:()=>Be});function h0(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=Be(o);return r&&o.addEventListener("upgradeneeded",c=>{r(Be(o.result),c.oldVersion,c.newVersion,Be(o.transaction))}),n&&o.addEventListener("blocked",()=>n()),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",()=>i())}).catch(()=>{}),a}function p0(t,{blocked:e}={}){let n=indexedDB.deleteDatabase(t);return e&&n.addEventListener("blocked",()=>e()),Be(n).then(()=>{})}function dh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(yc.get(e))return yc.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=m0.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||g0.includes(n)))return;let s=async function(o,...a){let c=this.transaction(o,i?"readwrite":"readonly"),l=c.store;return r&&(l=l.index(a.shift())),(await Promise.all([l[n](...a),i&&c.done]))[0]};return yc.set(e,s),s}var g0,m0,yc,fh=we(()=>{wc();wc();g0=["get","getKey","getAll","getAllKeys","count"],m0=["put","add","delete","clear"],yc=new Map;lh(t=>({...t,get:(e,n,r)=>dh(e,n)||t.get(e,n,r),has:(e,n)=>!!dh(e,n)||t.has(e,n)}))});var Et=G((iO,Bh)=>{"use strict";var Fh=["nodebuffer","arraybuffer","fragments"],Mh=typeof Blob<"u";Mh&&Fh.push("blob");Bh.exports={BINARY_TYPES:Fh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Mh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var pi=G((sO,Xs)=>{"use strict";var{EMPTY_BUFFER:_S}=Et(),$c=Buffer[Symbol.species];function ES(t,e){if(t.length===0)return _S;if(t.length===1)return t[0];let n=Buffer.allocUnsafe(e),r=0;for(let i=0;i<t.length;i++){let s=t[i];n.set(s,r),r+=s.length}return r<e?new $c(n.buffer,n.byteOffset,r):n}function Uh(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function zh(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function SS(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Gc(t){if(Gc.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new $c(t):ArrayBuffer.isView(t)?e=new $c(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Gc.readOnly=!1),e}Xs.exports={concat:ES,mask:Uh,toArrayBuffer:SS,toBuffer:Gc,unmask:zh};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=H("bufferutil");Xs.exports.mask=function(e,n,r,i,s){s<48?Uh(e,n,r,i,s):t.mask(e,n,r,i,s)},Xs.exports.unmask=function(e,n){e.length<32?zh(e,n):t.unmask(e,n)}}catch{}});var Hh=G((oO,Gh)=>{"use strict";var $h=Symbol("kDone"),Hc=Symbol("kRun"),jc=class{constructor(e){this[$h]=()=>{this.pending--,this[Hc]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Hc]()}[Hc](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$h])}}};Gh.exports=jc});var cr=G((aO,Jh)=>{"use strict";var gi=H("zlib"),jh=pi(),IS=Hh(),{kStatusCode:Wh}=Et(),vS=Buffer[Symbol.species],TS=Buffer.from([0,0,255,255]),Qs=Symbol("permessage-deflate"),St=Symbol("total-length"),or=Symbol("callback"),qt=Symbol("buffers"),ar=Symbol("error"),Ys,Wc=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,!Ys){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ys=new IS(n)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[or];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let n=this._options,r=e.find(i=>!(n.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(n.serverMaxWindowBits===!1||typeof n.serverMaxWindowBits=="number"&&n.serverMaxWindowBits>i.server_max_window_bits)||typeof n.clientMaxWindowBits=="number"&&!i.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return n.serverNoContextTakeover&&(r.server_no_context_takeover=!0),n.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof n.serverMaxWindowBits=="number"&&(r.server_max_window_bits=n.serverMaxWindowBits),typeof n.clientMaxWindowBits=="number"?r.client_max_window_bits=n.clientMaxWindowBits:(r.client_max_window_bits===!0||n.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let n=e[0];if(this._options.clientNoContextTakeover===!1&&n.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!n.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(n.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&n.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return n}normalizeParams(e){return e.forEach(n=>{Object.keys(n).forEach(r=>{let i=n[r];if(i.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="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 "${r}": ${i}`);i=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let s=+i;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${r}": ${i}`);i=s}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw new Error(`Unknown parameter "${r}"`);n[r]=i})}),e}decompress(e,n,r){Ys.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){Ys.add(i=>{this._compress(e,n,(s,o)=>{i(),r(s,o)})})}_decompress(e,n,r){let i=this._isServer?"client":"server";if(!this._inflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?gi.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=gi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Qs]=this,this._inflate[St]=0,this._inflate[qt]=[],this._inflate.on("error",kS),this._inflate.on("data",qh)}this._inflate[or]=r,this._inflate.write(e),n&&this._inflate.write(TS),this._inflate.flush(()=>{let s=this._inflate[ar];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=jh.concat(this._inflate[qt],this._inflate[St]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[St]=0,this._inflate[qt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,n,r){let i=this._isServer?"server":"client";if(!this._deflate){let s=`${i}_max_window_bits`,o=typeof this.params[s]!="number"?gi.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=gi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[St]=0,this._deflate[qt]=[],this._deflate.on("data",RS)}this._deflate[or]=r,this._deflate.write(e),this._deflate.flush(gi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=jh.concat(this._deflate[qt],this._deflate[St]);n&&(s=new vS(s.buffer,s.byteOffset,s.length-4)),this._deflate[or]=null,this._deflate[St]=0,this._deflate[qt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};Jh.exports=Wc;function RS(t){this[qt].push(t),this[St]+=t.length}function qh(t){if(this[St]+=t.length,this[Qs]._maxPayload<1||this[St]<=this[Qs]._maxPayload){this[qt].push(t);return}this[ar]=new RangeError("Max payload size exceeded"),this[ar].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ar][Wh]=1009,this.removeListener("data",qh),this.reset()}function kS(t){if(this[Qs]._inflate=null,this[ar]){this[or](this[ar]);return}t[Wh]=1007,this[or](t)}});var lr=G((cO,eo)=>{"use strict";var{isUtf8:Vh}=H("buffer"),{hasBlob:bS}=Et(),AS=[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 xS(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function qc(t){let e=t.length,n=0;for(;n<e;)if((t[n]&128)===0)n++;else if((t[n]&224)===192){if(n+1===e||(t[n+1]&192)!==128||(t[n]&254)===192)return!1;n+=2}else if((t[n]&240)===224){if(n+2>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||t[n]===224&&(t[n+1]&224)===128||t[n]===237&&(t[n+1]&224)===160)return!1;n+=3}else if((t[n]&248)===240){if(n+3>=e||(t[n+1]&192)!==128||(t[n+2]&192)!==128||(t[n+3]&192)!==128||t[n]===240&&(t[n+1]&240)===128||t[n]===244&&t[n+1]>143||t[n]>244)return!1;n+=4}else return!1;return!0}function OS(t){return bS&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}eo.exports={isBlob:OS,isValidStatusCode:xS,isValidUTF8:qc,tokenChars:AS};if(Vh)eo.exports.isValidUTF8=function(t){return t.length<24?qc(t):Vh(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=H("utf-8-validate");eo.exports.isValidUTF8=function(e){return e.length<32?qc(e):t(e)}}catch{}});var Xc=G((lO,tp)=>{"use strict";var{Writable:PS}=H("stream"),Zh=cr(),{BINARY_TYPES:CS,EMPTY_BUFFER:Kh,kStatusCode:DS,kWebSocket:NS}=Et(),{concat:Jc,toArrayBuffer:LS,unmask:FS}=pi(),{isValidStatusCode:MS,isValidUTF8:Xh}=lr(),to=Buffer[Symbol.species],ze=0,Yh=1,Qh=2,ep=3,Vc=4,Zc=5,no=6,Kc=class extends PS{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||CS[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[NS]=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=ze}_write(e,n,r){if(this._opcode===8&&this._state==ze)return r();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(r)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new to(r.buffer,r.byteOffset+e,r.length-e),new to(r.buffer,r.byteOffset,e)}let n=Buffer.allocUnsafe(e);do{let r=this._buffers[0],i=n.length-e;e>=r.length?n.set(this._buffers.shift(),i):(n.set(new Uint8Array(r.buffer,r.byteOffset,e),i),this._buffers[0]=new to(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return n}startLoop(e){this._loop=!0;do switch(this._state){case ze:this.getInfo(e);break;case Yh:this.getPayloadLength16(e);break;case Qh:this.getPayloadLength64(e);break;case ep:this.getMask();break;case Vc:this.getData(e);break;case Zc:case no:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let n=this.consume(2);if((n[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(i);return}let r=(n[0]&64)===64;if(r&&!this._extensions[Zh.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(i);return}if(this._fin=(n[0]&128)===128,this._opcode=n[0]&15,this._payloadLength=n[1]&127,this._opcode===0){if(r){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=r}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(r){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=(n[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=Yh:this._payloadLength===127?this._state=Qh:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let n=this.consume(8),r=n.readUInt32BE(0);if(r>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=r*Math.pow(2,32)+n.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let n=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(n);return}this._masked?this._state=ep:this._state=Vc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Vc}getData(e){let n=Kh;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}n=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&FS(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=Zc,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[Zh.extensionName].decompress(e,this._fin,(i,s)=>{if(i)return n(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");n(o);return}this._fragments.push(s)}this.dataMessage(n),this._state===ze&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=ze;return}let n=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let i;this._binaryType==="nodebuffer"?i=Jc(r,n):this._binaryType==="arraybuffer"?i=LS(Jc(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=ze):(this._state=no,setImmediate(()=>{this.emit("message",i,!0),this._state=ze,this.startLoop(e)}))}else{let i=Jc(r,n);if(!this._skipUTF8Validation&&!Xh(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===Zc||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=ze):(this._state=no,setImmediate(()=>{this.emit("message",i,!1),this._state=ze,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Kh),this.end();else{let r=e.readUInt16BE(0);if(!MS(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new to(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Xh(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");n(s);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=ze;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=ze):(this._state=no,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=ze,this.startLoop(n)}))}createError(e,n,r,i,s){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${n}`:n);return Error.captureStackTrace(o,this.createError),o.code=s,o[DS]=i,o}};tp.exports=Kc});var el=G((uO,ip)=>{"use strict";var{Duplex:dO}=H("stream"),{randomFillSync:BS}=H("crypto"),np=cr(),{EMPTY_BUFFER:US,kWebSocket:zS,NOOP:$S}=Et(),{isBlob:dr,isValidStatusCode:GS}=lr(),{mask:rp,toBuffer:_n}=pi(),$e=Symbol("kByteLength"),HS=Buffer.alloc(4),ro=8*1024,En,ur=ro,Ke=0,jS=1,WS=2,Yc=class t{constructor(e,n,r){this._extensions=n||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ke,this.onerror=$S,this[zS]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||HS,n.generateMask?n.generateMask(r):(ur===ro&&(En===void 0&&(En=Buffer.alloc(ro)),BS(En,0,ro),ur=0),r[0]=En[ur++],r[1]=En[ur++],r[2]=En[ur++],r[3]=En[ur++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[$e]!==void 0?a=n[$e]:(e=Buffer.from(e),a=e.length):(a=e.length,i=n.mask&&n.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]=n.fin?n.opcode|128:n.opcode,n.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)),n.mask?(l[1]|=128,l[s-4]=r[0],l[s-3]=r[1],l[s-2]=r[2],l[s-1]=r[3],o?[l,e]:i?(rp(e,r,l,s,a),[l]):(rp(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,i){let s;if(e===void 0)s=US;else{if(typeof e!="number"||!GS(e))throw new TypeError("First argument must be a valid error code number");if(n===void 0||!n.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(n);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 n=="string"?s.write(n,2):s.set(n,2)}}let o={[$e]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ke?this.enqueue([this.dispatch,s,!1,o,i]):this.sendFrame(t.frame(s,o),i)}ping(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):dr(e)?(i=e.size,s=!1):(e=_n(e),i=e.length,s=_n.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[$e]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};dr(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ke?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}pong(e,n,r){let i,s;if(typeof e=="string"?(i=Buffer.byteLength(e),s=!1):dr(e)?(i=e.size,s=!1):(e=_n(e),i=e.length,s=_n.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[$e]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};dr(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ke?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[np.extensionName],s=n.binary?2:1,o=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):dr(e)?(a=e.size,c=!1):(e=_n(e),a=e.length,c=_n.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),n.fin&&(this._firstFragment=!0);let l={[$e]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};dr(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ke?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[$e],this._state=WS,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Qc,this,a,i);return}this._bufferedBytes-=r[$e];let o=_n(s);n?this.dispatch(o,n,r,i):(this._state=Ke,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(qS,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[np.extensionName];this._bufferedBytes+=r[$e],this._state=jS,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Qc(this,c,i);return}this._bufferedBytes-=r[$e],this._state=Ke,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===Ke&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][$e],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][$e],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};ip.exports=Yc;function Qc(t,e,n){typeof n=="function"&&n(e);for(let r=0;r<t._queue.length;r++){let i=t._queue[r],s=i[i.length-1];typeof s=="function"&&s(e)}}function qS(t,e,n){Qc(t,e,n),t.onerror(e)}});var hp=G((fO,fp)=>{"use strict";var{kForOnEventAttribute:mi,kListener:tl}=Et(),sp=Symbol("kCode"),op=Symbol("kData"),ap=Symbol("kError"),cp=Symbol("kMessage"),lp=Symbol("kReason"),fr=Symbol("kTarget"),dp=Symbol("kType"),up=Symbol("kWasClean"),It=class{constructor(e){this[fr]=null,this[dp]=e}get target(){return this[fr]}get type(){return this[dp]}};Object.defineProperty(It.prototype,"target",{enumerable:!0});Object.defineProperty(It.prototype,"type",{enumerable:!0});var Sn=class extends It{constructor(e,n={}){super(e),this[sp]=n.code===void 0?0:n.code,this[lp]=n.reason===void 0?"":n.reason,this[up]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[sp]}get reason(){return this[lp]}get wasClean(){return this[up]}};Object.defineProperty(Sn.prototype,"code",{enumerable:!0});Object.defineProperty(Sn.prototype,"reason",{enumerable:!0});Object.defineProperty(Sn.prototype,"wasClean",{enumerable:!0});var hr=class extends It{constructor(e,n={}){super(e),this[ap]=n.error===void 0?null:n.error,this[cp]=n.message===void 0?"":n.message}get error(){return this[ap]}get message(){return this[cp]}};Object.defineProperty(hr.prototype,"error",{enumerable:!0});Object.defineProperty(hr.prototype,"message",{enumerable:!0});var wi=class extends It{constructor(e,n={}){super(e),this[op]=n.data===void 0?null:n.data}get data(){return this[op]}};Object.defineProperty(wi.prototype,"data",{enumerable:!0});var JS={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[mi]&&i[tl]===e&&!i[mi])return;let r;if(t==="message")r=function(s,o){let a=new wi("message",{data:o?s:s.toString()});a[fr]=this,io(e,this,a)};else if(t==="close")r=function(s,o){let a=new Sn("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[fr]=this,io(e,this,a)};else if(t==="error")r=function(s){let o=new hr("error",{error:s,message:s.message});o[fr]=this,io(e,this,o)};else if(t==="open")r=function(){let s=new It("open");s[fr]=this,io(e,this,s)};else return;r[mi]=!!n[mi],r[tl]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[tl]===e&&!n[mi]){this.removeListener(t,n);break}}};fp.exports={CloseEvent:Sn,ErrorEvent:hr,Event:It,EventTarget:JS,MessageEvent:wi};function io(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var so=G((hO,pp)=>{"use strict";var{tokenChars:yi}=lr();function lt(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function VS(t){let e=Object.create(null),n=Object.create(null),r=!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&&yi[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?(lt(e,f,n),n=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&&yi[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),lt(n,t.slice(c,d),!0),l===44&&(lt(e,o,n),n=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(yi[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:r||(r=!0),i=!1}else if(s)if(yi[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&&yi[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);r&&(f=f.replace(/\\/g,""),r=!1),lt(n,a,f),l===44&&(lt(e,o,n),n=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?lt(e,m,n):(a===void 0?lt(n,m,!0):r?lt(n,a,m.replace(/\\/g,"")):lt(n,a,m),lt(e,o,n)),e}function ZS(t){return Object.keys(t).map(e=>{let n=t[e];return Array.isArray(n)||(n=[n]),n.map(r=>[e].concat(Object.keys(r).map(i=>{let s=r[i];return Array.isArray(s)||(s=[s]),s.map(o=>o===!0?i:`${i}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}pp.exports={format:ZS,parse:VS}});var lo=G((mO,kp)=>{"use strict";var KS=H("events"),XS=H("https"),YS=H("http"),wp=H("net"),QS=H("tls"),{randomBytes:eI,createHash:tI}=H("crypto"),{Duplex:pO,Readable:gO}=H("stream"),{URL:nl}=H("url"),Jt=cr(),nI=Xc(),rI=el(),{isBlob:iI}=lr(),{BINARY_TYPES:gp,CLOSE_TIMEOUT:sI,EMPTY_BUFFER:oo,GUID:oI,kForOnEventAttribute:rl,kListener:aI,kStatusCode:cI,kWebSocket:de,NOOP:yp}=Et(),{EventTarget:{addEventListener:lI,removeEventListener:dI}}=hp(),{format:uI,parse:fI}=so(),{toBuffer:hI}=pi(),_p=Symbol("kAborted"),il=[8,13],vt=["CONNECTING","OPEN","CLOSING","CLOSED"],pI=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,W=class t extends KS{constructor(e,n,r){super(),this._binaryType=gp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=oo,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,n===void 0?n=[]:Array.isArray(n)||(typeof n=="object"&&n!==null?(r=n,n=[]):n=[n]),Ep(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){gp.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,n,r){let i=new nI({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new rI(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[de]=this,s[de]=this,e[de]=this,i.on("conclude",wI),i.on("drain",yI),i.on("error",_I),i.on("message",EI),i.on("ping",SI),i.on("pong",II),s.onerror=vI,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",vp),e.on("data",co),e.on("end",Tp),e.on("error",Rp),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,n){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){De(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,n,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),Ip(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){sl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||oo,n,r)}pong(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=n=void 0):typeof n=="function"&&(r=n,n=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){sl(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||oo,n,r)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,n,r){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof n=="function"&&(r=n,n={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){sl(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Jt.extensionName]||(i.compress=!1),this._sender.send(e||oo,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){De(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(W,"CONNECTING",{enumerable:!0,value:vt.indexOf("CONNECTING")});Object.defineProperty(W.prototype,"CONNECTING",{enumerable:!0,value:vt.indexOf("CONNECTING")});Object.defineProperty(W,"OPEN",{enumerable:!0,value:vt.indexOf("OPEN")});Object.defineProperty(W.prototype,"OPEN",{enumerable:!0,value:vt.indexOf("OPEN")});Object.defineProperty(W,"CLOSING",{enumerable:!0,value:vt.indexOf("CLOSING")});Object.defineProperty(W.prototype,"CLOSING",{enumerable:!0,value:vt.indexOf("CLOSING")});Object.defineProperty(W,"CLOSED",{enumerable:!0,value:vt.indexOf("CLOSED")});Object.defineProperty(W.prototype,"CLOSED",{enumerable:!0,value:vt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(W.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(W.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[rl])return e[aI];return null},set(e){for(let n of this.listeners(t))if(n[rl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[rl]:!0})}})});W.prototype.addEventListener=lI;W.prototype.removeEventListener=dI;kp.exports=W;function Ep(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:sI,protocolVersion:il[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,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,!il.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${il.join(", ")})`);let s;if(e instanceof nl)s=e;else try{s=new nl(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;ao(t,g);return}let l=o?443:80,d=eI(16).toString("base64"),p=o?XS.request:YS.request,m=new Set,f;if(i.createConnection=i.createConnection||(o?mI:gI),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"]=uI({[Jt.extensionName]:f.offer()})),n.length){for(let g of n){if(typeof g!="string"||!pI.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}i.headers["Sec-WebSocket-Protocol"]=n.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 h;if(i.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=o,t._originalHostOrSocketPath=a?i.socketPath:s.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[w,S]of Object.entries(g))r.headers[w.toLowerCase()]=S}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&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),h=t._req=p(i),t._redirects&&t.emit("redirect",t.url,h)}else h=t._req=p(i);i.timeout&&h.on("timeout",()=>{De(t,h,"Opening handshake has timed out")}),h.on("error",g=>{h===null||h[_p]||(h=t._req=null,ao(t,g))}),h.on("response",g=>{let w=g.headers.location,S=g.statusCode;if(w&&i.followRedirects&&S>=300&&S<400){if(++t._redirects>i.maxRedirects){De(t,h,"Maximum redirects exceeded");return}h.abort();let v;try{v=new nl(w,e)}catch{let y=new SyntaxError(`Invalid URL: ${w}`);ao(t,y);return}Ep(t,v,n,r)}else t.emit("unexpected-response",h,g)||De(t,h,`Unexpected server response: ${g.statusCode}`)}),h.on("upgrade",(g,w,S)=>{if(t.emit("upgrade",g),t.readyState!==W.CONNECTING)return;h=t._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){De(t,w,"Invalid Upgrade header");return}let u=tI("sha1").update(d+oI).digest("base64");if(g.headers["sec-websocket-accept"]!==u){De(t,w,"Invalid Sec-WebSocket-Accept header");return}let y=g.headers["sec-websocket-protocol"],E;if(y!==void 0?m.size?m.has(y)||(E="Server sent an invalid subprotocol"):E="Server sent a subprotocol but none was requested":m.size&&(E="Server sent no subprotocol"),E){De(t,w,E);return}y&&(t._protocol=y);let R=g.headers["sec-websocket-extensions"];if(R!==void 0){if(!f){De(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let T;try{T=fI(R)}catch{De(t,w,"Invalid Sec-WebSocket-Extensions header");return}let D=Object.keys(T);if(D.length!==1||D[0]!==Jt.extensionName){De(t,w,"Server indicated an extension that was not requested");return}try{f.accept(T[Jt.extensionName])}catch{De(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Jt.extensionName]=f}t.setSocket(w,S,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})}),i.finishRequest?i.finishRequest(h,t):h.end()}function ao(t,e){t._readyState=W.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function gI(t){return t.path=t.socketPath,wp.connect(t)}function mI(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=wp.isIP(t.host)?"":t.host),QS.connect(t)}function De(t,e,n){t._readyState=W.CLOSING;let r=new Error(n);Error.captureStackTrace(r,De),e.setHeader?(e[_p]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ao,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function sl(t,e,n){if(e){let r=iI(e)?e.size:hI(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${vt[t.readyState]})`);process.nextTick(n,r)}}function wI(t,e){let n=this[de];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[de]!==void 0&&(n._socket.removeListener("data",co),process.nextTick(Sp,n._socket),t===1005?n.close():n.close(t,e))}function yI(){let t=this[de];t.isPaused||t._socket.resume()}function _I(t){let e=this[de];e._socket[de]!==void 0&&(e._socket.removeListener("data",co),process.nextTick(Sp,e._socket),e.close(t[cI])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function mp(){this[de].emitClose()}function EI(t,e){this[de].emit("message",t,e)}function SI(t){let e=this[de];e._autoPong&&e.pong(t,!this._isServer,yp),e.emit("ping",t)}function II(t){this[de].emit("pong",t)}function Sp(t){t.resume()}function vI(t){let e=this[de];e.readyState!==W.CLOSED&&(e.readyState===W.OPEN&&(e._readyState=W.CLOSING,Ip(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Ip(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function vp(){let t=this[de];if(this.removeListener("close",vp),this.removeListener("data",co),this.removeListener("end",Tp),t._readyState=W.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[de]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",mp),t._receiver.on("finish",mp))}function co(t){this[de]._receiver.write(t)||this.pause()}function Tp(){let t=this[de];t._readyState=W.CLOSING,t._receiver.end(),this.end()}function Rp(){let t=this[de];this.removeListener("error",Rp),this.on("error",yp),t&&(t._readyState=W.CLOSING,this.destroy())}});var Op=G((yO,xp)=>{"use strict";var wO=lo(),{Duplex:TI}=H("stream");function bp(t){t.emit("close")}function RI(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Ap(t){this.removeListener("error",Ap),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function kI(t,e){let n=!0,r=new TI({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,o){let a=!o&&r._readableState.objectMode?s.toString():s;r.push(a)||t.pause()}),t.once("error",function(s){r.destroyed||(n=!1,r.destroy(s))}),t.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(i,s){if(t.readyState===t.CLOSED){s(i),process.nextTick(bp,r);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(bp,r)}),n&&t.terminate()},r._final=function(i){if(t.readyState===t.CONNECTING){t.once("open",function(){r._final(i)});return}t._socket!==null&&(t._socket._writableState.finished?(i(),r._readableState.endEmitted&&r.destroy()):(t._socket.once("finish",function(){i()}),t.close()))},r._read=function(){t.isPaused&&t.resume()},r._write=function(i,s,o){if(t.readyState===t.CONNECTING){t.once("open",function(){r._write(i,s,o)});return}t.send(i,o)},r.on("end",RI),r.on("error",Ap),r}xp.exports=kI});var ol=G((_O,Pp)=>{"use strict";var{tokenChars:bI}=lr();function AI(t){let e=new Set,n=-1,r=-1,i=0;for(i;i<t.length;i++){let o=t.charCodeAt(i);if(r===-1&&bI[o]===1)n===-1&&(n=i);else if(i!==0&&(o===32||o===9))r===-1&&n!==-1&&(r=i);else if(o===44){if(n===-1)throw new SyntaxError(`Unexpected character at index ${i}`);r===-1&&(r=i);let a=t.slice(n,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),n=r=-1}else throw new SyntaxError(`Unexpected character at index ${i}`)}if(n===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(n,i);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}Pp.exports={parse:AI}});var Bp=G((SO,Mp)=>{"use strict";var xI=H("events"),uo=H("http"),{Duplex:EO}=H("stream"),{createHash:OI}=H("crypto"),Cp=so(),In=cr(),PI=ol(),CI=lo(),{CLOSE_TIMEOUT:DI,GUID:NI,kWebSocket:LI}=Et(),FI=/^[+/0-9A-Za-z]{22}==$/,Dp=0,Np=1,Fp=2,al=class extends xI{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:DI,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:CI,...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=uo.createServer((r,i)=>{let s=uo.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,n)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=MI(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,s,o)=>{this.handleUpgrade(i,s,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Dp}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===Fp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(_i,this);return}if(e&&this.once("close",e),this._state!==Np)if(this._state=Np,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(_i,this):process.nextTick(_i,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{_i(this)})}}shouldHandle(e){if(this.options.path){let n=e.url.indexOf("?");if((n!==-1?e.url.slice(0,n):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,n,r,i){n.on("error",Lp);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){vn(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){vn(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!FI.test(s)){vn(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){vn(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ei(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=PI.parse(c)}catch{vn(this,e,n,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 In({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=Cp.parse(d);f[In.extensionName]&&(m.accept(f[In.extensionName]),p[In.extensionName]=m)}catch{vn(this,e,n,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,h,g,w)=>{if(!f)return Ei(n,h||401,g,w);this.completeUpgrade(p,s,l,e,n,r,i)});return}if(!this.options.verifyClient(m))return Ei(n,401)}this.completeUpgrade(p,s,l,e,n,r,i)}completeUpgrade(e,n,r,i,s,o,a){if(!s.readable||!s.writable)return s.destroy();if(s[LI])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Dp)return Ei(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${OI("sha1").update(n+NI).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(r.size){let p=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),d._protocol=p)}if(e[In.extensionName]){let p=e[In.extensionName].params,m=Cp.format({[In.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
|
|
14
14
|
`).join(`\r
|
|
15
|
-
`)),s.removeListener("error",
|
|
16
|
-
`+Object.keys(
|
|
15
|
+
`)),s.removeListener("error",Lp),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(_i,this)})),a(d,i)}};Mp.exports=al;function MI(t,e){for(let n of Object.keys(e))t.on(n,e[n]);return function(){for(let r of Object.keys(e))t.removeListener(r,e[r])}}function _i(t){t._state=Fp,t.emit("close")}function Lp(){this.destroy()}function Ei(t,e,n,r){n=n||uo.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(n),...r},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${uo.STATUS_CODES[e]}\r
|
|
16
|
+
`+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
|
|
17
17
|
`)+`\r
|
|
18
18
|
\r
|
|
19
|
-
`+
|
|
19
|
+
`+n)}function vn(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,vn),t.emit("wsClientError",o,n,e)}else Ei(n,r,i,s)}});import{existsSync as ov,openSync as av}from"node:fs";import{mkdir as cv}from"node:fs/promises";import{dirname as lv}from"node:path";import{fileURLToPath as dv}from"node:url";function fv(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function fl(t=F()){return ov(t.libEntry)?t.libEntry:dv(new URL("../index.ts",import.meta.url))}async function hl(t={}){let e=t.paths??F(),n=t.entryOverride??fl(e),r=fv(e,process.env.COZE_BRIDGE_LOG_MODE);await cv(lv(r),{recursive:!0});let i=av(r,"a"),o=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],a=Le(process.execPath,o,{detached:!0,stdio:["ignore",i,i],env:{...process.env,[ul]:"1"}});if(a.unref(),typeof a.pid!="number")throw new Error("failed to spawn daemon (no pid)");return uv.info("daemon spawned",{pid:a.pid,entry:n}),{pid:a.pid,entry:n}}var uv,ul,mo=we(()=>{"use strict";ft();L();se();uv=A("spawn-daemon"),ul="COZE_BRIDGE_DAEMON"});import{spawn as Jv}from"node:child_process";import{mkdir as Vv,unlink as Zv,writeFile as Kv}from"node:fs/promises";import{dirname as Xv,join as Yv}from"node:path";function vo(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}function fg(t,e){return new Promise((n,r)=>{let i=Jv(t,e,{stdio:["ignore","pipe","pipe"]}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",r),i.on("close",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var Io,wl,yl,hg=we(()=>{"use strict";L();Io=A("supervisor.launchd"),wl="ai.coze.bridge",yl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
|
|
20
20
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
21
21
|
<plist version="1.0">
|
|
22
22
|
<dict>
|
|
23
23
|
<key>Label</key>
|
|
24
|
-
<string>${
|
|
24
|
+
<string>${wl}</string>
|
|
25
25
|
<key>ProgramArguments</key>
|
|
26
26
|
<array>
|
|
27
|
-
<string>${
|
|
28
|
-
<string>${
|
|
27
|
+
<string>${vo(t.nodeBin)}</string>
|
|
28
|
+
<string>${vo(t.entry)}</string>
|
|
29
29
|
<string>--daemon</string>
|
|
30
30
|
</array>
|
|
31
31
|
<key>RunAtLoad</key>
|
|
@@ -35,12 +35,12 @@ var hg=Object.create;var vo=Object.defineProperty;var fg=Object.getOwnPropertyDe
|
|
|
35
35
|
<key>ThrottleInterval</key>
|
|
36
36
|
<integer>10</integer>
|
|
37
37
|
<key>StandardOutPath</key>
|
|
38
|
-
<string>${
|
|
38
|
+
<string>${vo(t.logFile)}</string>
|
|
39
39
|
<key>StandardErrorPath</key>
|
|
40
|
-
<string>${
|
|
40
|
+
<string>${vo(t.logFile)}</string>
|
|
41
41
|
</dict>
|
|
42
42
|
</plist>
|
|
43
|
-
`},configPath(t){return
|
|
43
|
+
`},configPath(t){return Yv(t.homeDir,"Library","LaunchAgents",`${wl}.plist`)},async install(t){let e=this.configPath(t);await Vv(Xv(e),{recursive:!0}),await Kv(e,this.renderConfig(t),"utf8"),Io.info("plist written",{plistPath:e}),await fg("launchctl",["load","-w",e]),Io.info("launchd job loaded",{label:wl})},async uninstall(t){let e=this.configPath(t);await fg("launchctl",["unload","-w",e]).catch(n=>Io.warn("launchctl unload failed (ignored)",{err:String(n)})),await Zv(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Io.info("launchd job removed",{plistPath:e})}}});import{spawn as Qv}from"node:child_process";import{mkdir as eT,unlink as tT,writeFile as nT}from"node:fs/promises";import{dirname as rT,join as iT}from"node:path";function ko(t,e){return new Promise((n,r)=>{let i=Qv(t,e,{stdio:["ignore","pipe","pipe"]}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",r),i.on("close",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var To,Ro,_l,pg=we(()=>{"use strict";L();To=A("supervisor.systemd"),Ro="coze-bridge.service",_l={platform:"linux",renderConfig(t){return`[Unit]
|
|
44
44
|
Description=Coze Bridge daemon
|
|
45
45
|
After=network.target
|
|
46
46
|
|
|
@@ -54,7 +54,7 @@ StandardError=append:${t.logFile}
|
|
|
54
54
|
|
|
55
55
|
[Install]
|
|
56
56
|
WantedBy=default.target
|
|
57
|
-
`},configPath(t){return
|
|
57
|
+
`},configPath(t){return iT(t.homeDir,".config","systemd","user",Ro)},async install(t){let e=this.configPath(t);await eT(rT(e),{recursive:!0}),await nT(e,this.renderConfig(t),"utf8"),To.info("systemd unit written",{unitPath:e}),await ko("systemctl",["--user","daemon-reload"]),await ko("systemctl",["--user","enable","--now",Ro]),To.info("systemd unit enabled",{unitName:Ro})},async uninstall(t){let e=this.configPath(t);await ko("systemctl",["--user","disable","--now",Ro]).catch(n=>To.warn("systemctl disable failed (ignored)",{err:String(n)})),await tT(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await ko("systemctl",["--user","daemon-reload"]).catch(()=>{}),To.info("systemd unit removed",{unitPath:e})}}});import{spawn as sT}from"node:child_process";import{join as oT}from"node:path";function gg(t,e){return new Promise((n,r)=>{let i=sT(t,e,{stdio:["ignore","pipe","pipe"],shell:!1}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",r),i.on("close",o=>{o===0?n():r(new Error(`${t} ${e.join(" ")} exited ${o}: ${s.trim()}`))})})}var El,bo,Sl,mg=we(()=>{"use strict";L();El=A("supervisor.taskscheduler"),bo="CozeBridge",Sl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
|
|
58
58
|
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
59
59
|
<RegistrationInfo>
|
|
60
60
|
<Description>Coze Bridge daemon</Description>
|
|
@@ -78,41 +78,41 @@ WantedBy=default.target
|
|
|
78
78
|
</Exec>
|
|
79
79
|
</Actions>
|
|
80
80
|
</Task>
|
|
81
|
-
`},configPath(t){return Uv(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 rg("schtasks",["/Create","/SC","ONLOGON","/TN",Eo,"/TR",r,"/RU",t.userName,"/F"]),dl.info("task scheduler entry created",{task:Eo,logFile:t.logFile})},async uninstall(t){await rg("schtasks",["/Delete","/TN",Eo,"/F"]).catch(e=>dl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),dl.info("task scheduler entry removed",{task:Eo})}}});var ig={};_i(ig,{buildContext:()=>Hv,getSupervisor:()=>Gv,launchdSupervisor:()=>cl,systemdSupervisor:()=>ll,taskSchedulerSupervisor:()=>ul});import{homedir as zv,userInfo as $v}from"node:os";function Gv(t=process.platform){switch(t){case"darwin":return cl;case"linux":return ll;case"win32":return ul;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function Hv(){let t=N();return{nodeBin:process.execPath,entry:tl(t),logFile:t.logFile,homeDir:zv(),userName:$v().username}}var sg=me(()=>{"use strict";se();nl();eg();tg();ng()});F();Vt();var bl=x("acp-installer-warmup"),Jg=["claude-code","codex"];async function Al(t={}){let e=t.ensure??vr,n=(await Promise.allSettled(Jg.map(async i=>{let s=await e(i);bl.info("acp wrapper warmup ok",{framework:i,path:s})}))).filter(i=>i.status==="rejected");n.length>0&&bl.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))})}Rt();F();import{readdir as sm}from"node:fs/promises";import{mkdir as Ll,writeFile as Fl}from"node:fs/promises";import{join as Oo}from"node:path";var im={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Rr(t,e,r){await Ll(t,{recursive:!0});let n=im[e],i=Oo(t,n);return await Fl(i,r??"","utf8"),i}async function Ml(t){let e=Oo(t,".claude");await Ll(e,{recursive:!0});let r=Oo(e,"settings.local.json"),n=JSON.stringify({permissions:{defaultMode:"bypassPermissions"}},null,2);return await Fl(r,n,"utf8"),r}var ke=x("agent-detail-sync"),om=6e4,am=5*6e4,Li=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let r=this.opts.paths.agentsRoot,n;try{n=await sm(r)}catch(i){ke.info("agents dir not found, skip detail sync",{root:r,err:String(i)});return}ke.info("starting detail sync",{reason:e,count:n.length}),await Promise.allSettled(n.map(async i=>{let s=await ue(i,this.opts.paths).catch(()=>null);if(s){if(s.disconnectedAt){ke.debug("detail sync: skip disconnected agent",{agentId:i});return}try{await this.syncOne(i,s)}catch(o){ke.warn("detail sync failed for agent, skipping",{agentId:i,err:String(o)})}}})),ke.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){ke.info("retrying pending detail syncs",{count:r.length});for(let n of r)try{await this.syncOne(n)}catch(i){ke.debug("detail sync retry still failing, will try again",{agentId:n,err:String(i)})}}}async syncOne(e,r){let n=r??await ue(e,this.opts.paths);if(!n){ke.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){ke.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,am):om;this.retryQueue.set(e,{dueAt:Date.now()+l,currentDelay:l});return}if(i.agentId&&i.agentId!==e){ke.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&&ke.info("detail.deployType",{agentId:e,deployType:i.deployType}),!s){ke.debug("detail sync: no diff",{agentId:e});return}await Te(n,this.opts.paths),ke.info("detail sync: config updated",{agentId:e,identityChanged:o,agentName:n.agentName}),o&&(await Rr(n.workspace,n.framework,n.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var eh=dt(md(),1);import{lstat as ja,mkdir as Wa,readFile as Ku,readdir as Ny,rm as Ly,stat as Fy,writeFile as qa}from"node:fs/promises";import{dirname as My,join as nt,normalize as By,relative as Za,resolve as Ja,sep as Xu}from"node:path";import{Readable as Yu}from"node:stream";import{pipeline as Qu}from"node:stream/promises";import xm from"events";import Re from"fs";import{EventEmitter as xa}from"node:events";import Xd from"node:stream";import{StringDecoder as Om}from"node:string_decoder";import eu from"node:path";import Mr from"node:fs";import{dirname as Hm,parse as jm}from"path";import{EventEmitter as Ym}from"events";import da from"assert";import{Buffer as sr}from"buffer";import*as Sd from"zlib";import Qm from"zlib";import{posix as Or}from"node:path";import{basename as kw}from"node:path";import fs from"fs";import Qe from"fs";import Ad from"path";import{win32 as Mw}from"node:path";import Ld from"path";import gu from"node:fs";import ey from"node:assert";import{randomBytes as mu}from"node:crypto";import L from"node:fs";import re from"node:path";import wu from"fs";import Is from"node:fs";import Ln from"node:path";import xe from"node:fs";import ay from"node:fs/promises";import ms from"node:path";import{join as Au}from"node:path";import Ae from"node:fs";import Pu from"node:path";var bm=Object.defineProperty,Am=(t,e)=>{for(var r in e)bm(t,r,{get:e[r],enumerable:!0})},wd=typeof process=="object"&&process?process:{stdout:null,stderr:null},Pm=t=>!!t&&typeof t=="object"&&(t instanceof cr||t instanceof Xd||Cm(t)||Dm(t)),Cm=t=>!!t&&typeof t=="object"&&t instanceof xa&&typeof t.pipe=="function"&&t.pipe!==Xd.Writable.prototype.pipe,Dm=t=>!!t&&typeof t=="object"&&t instanceof xa&&typeof t.write=="function"&&typeof t.end=="function",ut=Symbol("EOF"),ht=Symbol("maybeEmitEnd"),bt=Symbol("emittedEnd"),zi=Symbol("emittingEnd"),yn=Symbol("emittedError"),$i=Symbol("closed"),yd=Symbol("read"),Gi=Symbol("flush"),_d=Symbol("flushChunk"),ze=Symbol("encoding"),xr=Symbol("decoder"),oe=Symbol("flowing"),_n=Symbol("paused"),Nr=Symbol("resume"),ae=Symbol("buffer"),Se=Symbol("pipes"),ce=Symbol("bufferLength"),Fo=Symbol("bufferPush"),Hi=Symbol("bufferShift"),ye=Symbol("objectMode"),Y=Symbol("destroyed"),Mo=Symbol("error"),Bo=Symbol("emitData"),Ed=Symbol("emitEnd"),Uo=Symbol("emitEnd2"),Ke=Symbol("async"),zo=Symbol("abort"),ji=Symbol("aborted"),En=Symbol("signal"),Kt=Symbol("dataListeners"),be=Symbol("discarded"),Sn=t=>Promise.resolve().then(t),Nm=t=>t(),Lm=t=>t==="end"||t==="finish"||t==="prefinish",Fm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Mm=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Yd=class{src;dest;opts;ondrain;constructor(t,e,r){this.src=t,this.dest=e,this.opts=r,this.ondrain=()=>t[Nr](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Bm=class extends Yd{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)}},Um=t=>!!t.objectMode,zm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",cr=class extends xa{[oe]=!1;[_n]=!1;[Se]=[];[ae]=[];[ye];[ze];[Ke];[xr];[ut]=!1;[bt]=!1;[zi]=!1;[$i]=!1;[yn]=null;[ce]=0;[Y]=!1;[En];[ji]=!1;[Kt]=0;[be]=!1;writable=!0;readable=!0;constructor(...t){let e=t[0]||{};if(super(),e.objectMode&&typeof e.encoding=="string")throw new TypeError("Encoding and objectMode may not be used together");Um(e)?(this[ye]=!0,this[ze]=null):zm(e)?(this[ze]=e.encoding,this[ye]=!1):(this[ye]=!1,this[ze]=null),this[Ke]=!!e.async,this[xr]=this[ze]?new Om(this[ze]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[ae]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Se]});let{signal:r}=e;r&&(this[En]=r,r.aborted?this[zo]():r.addEventListener("abort",()=>this[zo]()))}get bufferLength(){return this[ce]}get encoding(){return this[ze]}set encoding(t){throw new Error("Encoding must be set at instantiation time")}setEncoding(t){throw new Error("Encoding must be set at instantiation time")}get objectMode(){return this[ye]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ke]}set async(t){this[Ke]=this[Ke]||!!t}[zo](){this[ji]=!0,this.emit("abort",this[En]?.reason),this.destroy(this[En]?.reason)}get aborted(){return this[ji]}set aborted(t){}write(t,e,r){if(this[ji])return!1;if(this[ut])throw new Error("write after end");if(this[Y])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[Ke]?Sn:Nm;if(!this[ye]&&!Buffer.isBuffer(t)){if(Mm(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Fm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[ye]?(this[oe]&&this[ce]!==0&&this[Gi](!0),this[oe]?this.emit("data",t):this[Fo](t),this[ce]!==0&&this.emit("readable"),r&&n(r),this[oe]):t.length?(typeof t=="string"&&!(e===this[ze]&&!this[xr]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[ze]&&(t=this[xr].write(t)),this[oe]&&this[ce]!==0&&this[Gi](!0),this[oe]?this.emit("data",t):this[Fo](t),this[ce]!==0&&this.emit("readable"),r&&n(r),this[oe]):(this[ce]!==0&&this.emit("readable"),r&&n(r),this[oe])}read(t){if(this[Y])return null;if(this[be]=!1,this[ce]===0||t===0||t&&t>this[ce])return this[ht](),null;this[ye]&&(t=null),this[ae].length>1&&!this[ye]&&(this[ae]=[this[ze]?this[ae].join(""):Buffer.concat(this[ae],this[ce])]);let e=this[yd](t||null,this[ae][0]);return this[ht](),e}[yd](t,e){if(this[ye])this[Hi]();else{let r=e;t===r.length||t===null?this[Hi]():typeof r=="string"?(this[ae][0]=r.slice(t),e=r.slice(0,t),this[ce]-=t):(this[ae][0]=r.subarray(t),e=r.subarray(0,t),this[ce]-=t)}return this.emit("data",e),!this[ae].length&&!this[ut]&&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[ut]=!0,this.writable=!1,(this[oe]||!this[_n])&&this[ht](),this}[Nr](){this[Y]||(!this[Kt]&&!this[Se].length&&(this[be]=!0),this[_n]=!1,this[oe]=!0,this.emit("resume"),this[ae].length?this[Gi]():this[ut]?this[ht]():this.emit("drain"))}resume(){return this[Nr]()}pause(){this[oe]=!1,this[_n]=!0,this[be]=!1}get destroyed(){return this[Y]}get flowing(){return this[oe]}get paused(){return this[_n]}[Fo](t){this[ye]?this[ce]+=1:this[ce]+=t.length,this[ae].push(t)}[Hi](){return this[ye]?this[ce]-=1:this[ce]-=this[ae][0].length,this[ae].shift()}[Gi](t=!1){do;while(this[_d](this[Hi]())&&this[ae].length);!t&&!this[ae].length&&!this[ut]&&this.emit("drain")}[_d](t){return this.emit("data",t),this[oe]}pipe(t,e){if(this[Y])return t;this[be]=!1;let r=this[bt];return e=e||{},t===wd.stdout||t===wd.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,r?e.end&&t.end():(this[Se].push(e.proxyErrors?new Bm(this,t,e):new Yd(this,t,e)),this[Ke]?Sn(()=>this[Nr]()):this[Nr]()),t}unpipe(t){let e=this[Se].find(r=>r.dest===t);e&&(this[Se].length===1?(this[oe]&&this[Kt]===0&&(this[oe]=!1),this[Se]=[]):this[Se].splice(this[Se].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[be]=!1,this[Kt]++,!this[Se].length&&!this[oe]&&this[Nr]();else if(t==="readable"&&this[ce]!==0)super.emit("readable");else if(Lm(t)&&this[bt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[yn]){let n=e;this[Ke]?Sn(()=>n.call(this,this[yn])):n.call(this,this[yn])}return r}removeListener(t,e){return this.off(t,e)}off(t,e){let r=super.off(t,e);return t==="data"&&(this[Kt]=this.listeners("data").length,this[Kt]===0&&!this[be]&&!this[Se].length&&(this[oe]=!1)),r}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Kt]=0,!this[be]&&!this[Se].length&&(this[oe]=!1)),e}get emittedEnd(){return this[bt]}[ht](){!this[zi]&&!this[bt]&&!this[Y]&&this[ae].length===0&&this[ut]&&(this[zi]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[$i]&&this.emit("close"),this[zi]=!1)}emit(t,...e){let r=e[0];if(t!=="error"&&t!=="close"&&t!==Y&&this[Y])return!1;if(t==="data")return!this[ye]&&!r?!1:this[Ke]?(Sn(()=>this[Bo](r)),!0):this[Bo](r);if(t==="end")return this[Ed]();if(t==="close"){if(this[$i]=!0,!this[bt]&&!this[Y])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[yn]=r,super.emit(Mo,r);let i=!this[En]||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}[Bo](t){for(let r of this[Se])r.dest.write(t)===!1&&this.pause();let e=this[be]?!1:super.emit("data",t);return this[ht](),e}[Ed](){return this[bt]?!1:(this[bt]=!0,this.readable=!1,this[Ke]?(Sn(()=>this[Uo]()),!0):this[Uo]())}[Uo](){if(this[xr]){let e=this[xr].end();if(e){for(let r of this[Se])r.dest.write(e);this[be]||super.emit("data",e)}}for(let e of this[Se])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[ye]||(t.dataLength=0);let e=this.promise();return this.on("data",r=>{t.push(r),this[ye]||(t.dataLength+=r.length)}),await e,t}async concat(){if(this[ye])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[ze]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Y,()=>e(new Error("stream destroyed"))),this.on("error",r=>e(r)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[be]=!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[ut])return e();let n,i,s=l=>{this.off("data",o),this.off("end",a),this.off(Y,c),e(),i(l)},o=l=>{this.off("error",s),this.off("end",a),this.off(Y,c),this.pause(),n({value:l,done:!!this[ut]})},a=()=>{this.off("error",s),this.off("data",o),this.off(Y,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(Y,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[be]=!1;let t=!1,e=()=>(this.pause(),this.off(Mo,e),this.off(Y,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(Mo,e),this.once(Y,e),{next:r,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Y])return t?this.emit("error",t):this.emit(Y),this;this[Y]=!0,this[be]=!0,this[ae].length=0,this[ce]=0;let e=this;return typeof e.close=="function"&&!this[$i]&&e.close(),t?this.emit("error",t):this.emit(Y),this}static get isStream(){return Pm}},$m=Re.writev,Mt=Symbol("_autoClose"),je=Symbol("_close"),In=Symbol("_ended"),U=Symbol("_fd"),$o=Symbol("_finished"),mt=Symbol("_flags"),Go=Symbol("_flush"),ca=Symbol("_handleChunk"),la=Symbol("_makeBuf"),Dn=Symbol("_mode"),Wi=Symbol("_needDrain"),Ur=Symbol("_onerror"),zr=Symbol("_onopen"),Ho=Symbol("_onread"),Lr=Symbol("_onwrite"),Bt=Symbol("_open"),He=Symbol("_path"),Ct=Symbol("_pos"),Xe=Symbol("_queue"),Fr=Symbol("_read"),jo=Symbol("_readSize"),gt=Symbol("_reading"),vn=Symbol("_remain"),Wo=Symbol("_size"),ts=Symbol("_write"),Xt=Symbol("_writing"),rs=Symbol("_defaultFlag"),ir=Symbol("_errored"),Oa=class extends cr{[ir]=!1;[U];[He];[jo];[gt]=!1;[Wo];[vn];[Mt];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[ir]=!1,this[U]=typeof e.fd=="number"?e.fd:void 0,this[He]=t,this[jo]=e.readSize||16*1024*1024,this[gt]=!1,this[Wo]=typeof e.size=="number"?e.size:1/0,this[vn]=this[Wo],this[Mt]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[U]=="number"?this[Fr]():this[Bt]()}get fd(){return this[U]}get path(){return this[He]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Bt](){Re.open(this[He],"r",(t,e)=>this[zr](t,e))}[zr](t,e){t?this[Ur](t):(this[U]=e,this.emit("open",e),this[Fr]())}[la](){return Buffer.allocUnsafe(Math.min(this[jo],this[vn]))}[Fr](){if(!this[gt]){this[gt]=!0;let t=this[la]();if(t.length===0)return process.nextTick(()=>this[Ho](null,0,t));Re.read(this[U],t,0,t.length,null,(e,r,n)=>this[Ho](e,r,n))}}[Ho](t,e,r){this[gt]=!1,t?this[Ur](t):this[ca](e,r)&&this[Fr]()}[je](){if(this[Mt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Re.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Ur](t){this[gt]=!0,this[je](),this.emit("error",t)}[ca](t,e){let r=!1;return this[vn]-=t,t>0&&(r=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[vn]<=0)&&(r=!1,this[je](),super.end()),r}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[U]=="number"&&this[Fr](),!1;case"error":return this[ir]?!1:(this[ir]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},Gm=class extends Oa{[Bt](){let t=!0;try{this[zr](null,Re.openSync(this[He],"r")),t=!1}finally{t&&this[je]()}}[Fr](){let t=!0;try{if(!this[gt]){this[gt]=!0;do{let e=this[la](),r=e.length===0?0:Re.readSync(this[U],e,0,e.length,null);if(!this[ca](r,e))break}while(!0);this[gt]=!1}t=!1}finally{t&&this[je]()}}[je](){if(this[Mt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Re.closeSync(t),this.emit("close")}}},ws=class extends xm{readable=!1;writable=!0;[ir]=!1;[Xt]=!1;[In]=!1;[Xe]=[];[Wi]=!1;[He];[Dn];[Mt];[U];[rs];[mt];[$o]=!1;[Ct];constructor(t,e){e=e||{},super(e),this[He]=t,this[U]=typeof e.fd=="number"?e.fd:void 0,this[Dn]=e.mode===void 0?438:e.mode,this[Ct]=typeof e.start=="number"?e.start:void 0,this[Mt]=typeof e.autoClose=="boolean"?e.autoClose:!0;let r=this[Ct]!==void 0?"r+":"w";this[rs]=e.flags===void 0,this[mt]=e.flags===void 0?r:e.flags,this[U]===void 0&&this[Bt]()}emit(t,...e){if(t==="error"){if(this[ir])return!1;this[ir]=!0}return super.emit(t,...e)}get fd(){return this[U]}get path(){return this[He]}[Ur](t){this[je](),this[Xt]=!0,this.emit("error",t)}[Bt](){Re.open(this[He],this[mt],this[Dn],(t,e)=>this[zr](t,e))}[zr](t,e){this[rs]&&this[mt]==="r+"&&t&&t.code==="ENOENT"?(this[mt]="w",this[Bt]()):t?this[Ur](t):(this[U]=e,this.emit("open",e),this[Xt]||this[Go]())}end(t,e){return t&&this.write(t,e),this[In]=!0,!this[Xt]&&!this[Xe].length&&typeof this[U]=="number"&&this[Lr](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[In]?(this.emit("error",new Error("write() after end()")),!1):this[U]===void 0||this[Xt]||this[Xe].length?(this[Xe].push(t),this[Wi]=!0,!1):(this[Xt]=!0,this[ts](t),!0)}[ts](t){Re.write(this[U],t,0,t.length,this[Ct],(e,r)=>this[Lr](e,r))}[Lr](t,e){t?this[Ur](t):(this[Ct]!==void 0&&typeof e=="number"&&(this[Ct]+=e),this[Xe].length?this[Go]():(this[Xt]=!1,this[In]&&!this[$o]?(this[$o]=!0,this[je](),this.emit("finish")):this[Wi]&&(this[Wi]=!1,this.emit("drain"))))}[Go](){if(this[Xe].length===0)this[In]&&this[Lr](null,0);else if(this[Xe].length===1)this[ts](this[Xe].pop());else{let t=this[Xe];this[Xe]=[],$m(this[U],t,this[Ct],(e,r)=>this[Lr](e,r))}}[je](){if(this[Mt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Re.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Qd=class extends ws{[Bt](){let t;if(this[rs]&&this[mt]==="r+")try{t=Re.openSync(this[He],this[mt],this[Dn])}catch(e){if(e?.code==="ENOENT")return this[mt]="w",this[Bt]();throw e}else t=Re.openSync(this[He],this[mt],this[Dn]);this[zr](null,t)}[je](){if(this[Mt]&&typeof this[U]=="number"){let t=this[U];this[U]=void 0,Re.closeSync(t),this.emit("close")}}[ts](t){let e=!0;try{this[Lr](null,Re.writeSync(this[U],t,0,t.length,this[Ct])),e=!1}finally{if(e)try{this[je]()}catch{}}}},Wm=new Map([["C","cwd"],["f","file"],["z","gzip"],["P","preservePaths"],["U","unlink"],["strip-components","strip"],["stripComponents","strip"],["keep-newer","newer"],["keepNewer","newer"],["keep-newer-files","newer"],["keepNewerFiles","newer"],["k","keep"],["keep-existing","keep"],["keepExisting","keep"],["m","noMtime"],["no-mtime","noMtime"],["p","preserveOwner"],["L","follow"],["h","follow"],["onentry","onReadEntry"]]),qm=t=>!!t.sync&&!!t.file,Jm=t=>!t.sync&&!!t.file,Vm=t=>!!t.sync&&!t.file,Zm=t=>!t.sync&&!t.file,Km=t=>!!t.file,Xm=t=>Wm.get(t)||t,Pa=(t={})=>{if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){let i=Xm(r);e[i]=n}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Gn=(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=Pa(s);if(i?.(c,o),qm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return t(c,o)}else if(Jm(c)){let l=e(c,o);return a?l.then(()=>a(),a):l}else if(Vm(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return r(c,o)}else if(Zm(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}),ew=Qm.constants||{ZLIB_VERNUM:4736},rt=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},ew)),tw=sr.concat,Id=Object.getOwnPropertyDescriptor(sr,"concat"),rw=t=>t,qo=Id?.writable===!0||Id?.set!==void 0?t=>{sr.concat=t?rw:tw}:t=>{},or=Symbol("_superWrite"),qi=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"}},Jo=Symbol("flushFlag"),Ca=class extends cr{#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 Sd[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Sd[e](t)}catch(r){throw new qi(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 qi(r))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return da(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(sr.alloc(0),{[Jo]: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}[or](t){return super.write(t)}write(t,e,r){if(typeof e=="function"&&(r=e,e="utf8"),typeof t=="string"&&(t=sr.from(t,e)),this.#e)return;da(this.#t,"zlib binding closed");let n=this.#t._handle,i=n.close;n.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},qo(!0);let o;try{let c=typeof t[Jo]=="number"?t[Jo]:this.#n;o=this.#t._processChunk(t,c),qo(!1)}catch(c){qo(!1),this.#o(new qi(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 qi(c,this.write)));let a;if(o)if(Array.isArray(o)&&o.length>0){let c=o[0];a=this[or](sr.from(c));for(let l=1;l<o.length;l++)a=this[or](o[l])}else a=this[or](sr.from(o));return r&&r(),a}},tu=class extends Ca{#e;#r;constructor(t,e){t=t||{},t.flush=t.flush||rt.Z_NO_FLUSH,t.finishFlush=t.finishFlush||rt.Z_FINISH,t.fullFlushFlag=rt.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(rt.Z_SYNC_FLUSH),da(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)}}}},nw=class extends tu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[or](t){return this.#e?(this.#e=!1,t[9]=255,super[or](t)):super[or](t)}},iw=class extends tu{constructor(t){super(t,"Unzip")}},ru=class extends Ca{constructor(t,e){t=t||{},t.flush=t.flush||rt.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||rt.BROTLI_OPERATION_FINISH,t.fullFlushFlag=rt.BROTLI_OPERATION_FLUSH,super(t,e)}},sw=class extends ru{constructor(t){super(t,"BrotliCompress")}},ow=class extends ru{constructor(t){super(t,"BrotliDecompress")}},nu=class extends Ca{constructor(t,e){t=t||{},t.flush=t.flush||rt.ZSTD_e_continue,t.finishFlush=t.finishFlush||rt.ZSTD_e_end,t.fullFlushFlag=rt.ZSTD_e_flush,super(t,e)}},aw=class extends nu{constructor(t){super(t,"ZstdCompress")}},cw=class extends nu{constructor(t){super(t,"ZstdDecompress")}},lw=(t,e)=>{if(Number.isSafeInteger(t))t<0?uw(t,e):dw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},dw=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},uw=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var n=e.length;n>1;n--){var i=t&255;t=Math.floor(t/256),r?e[n-1]=iu(i):i===0?e[n-1]=0:(r=!0,e[n-1]=su(i))}},hw=t=>{let e=t[0],r=e===128?pw(t.subarray(1,t.length)):e===255?fw(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},fw=t=>{for(var e=t.length,r=0,n=!1,i=e-1;i>-1;i--){var s=Number(t[i]),o;n?o=iu(s):s===0?o=s:(n=!0,o=su(s)),o!==0&&(r-=o*Math.pow(256,e-i-1))}return r},pw=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},iu=t=>(255^t)&255,su=t=>(255^t)+1&255,gw={};Am(gw,{code:()=>Da,isCode:()=>ns,isName:()=>mw,name:()=>ys});var ns=t=>ys.has(t),mw=t=>Da.has(t),ys=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"]]),Da=new Map(Array.from(ys).map(t=>[t[1],t[0]])),ar=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??Yt(t,e,100),this.mode=r?.mode??n?.mode??Dt(t,e+100,8),this.uid=r?.uid??n?.uid??Dt(t,e+108,8),this.gid=r?.gid??n?.gid??Dt(t,e+116,8),this.size=r?.size??n?.size??Dt(t,e+124,12),this.mtime=r?.mtime??n?.mtime??Vo(t,e+136,12),this.cksum=Dt(t,e+148,12),n&&this.#r(n,!0),r&&this.#r(r);let i=Yt(t,e+156,1);if(ns(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=Yt(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=r?.uname??n?.uname??Yt(t,e+265,32),this.gname=r?.gname??n?.gname??Yt(t,e+297,32),this.devmaj=r?.devmaj??n?.devmaj??Dt(t,e+329,8)??0,this.devmin=r?.devmin??n?.devmin??Dt(t,e+337,8)??0,t[e+475]!==0){let o=Yt(t,e+345,155);this.path=o+"/"+this.path}else{let o=Yt(t,e+345,130);o&&(this.path=o+"/"+this.path),this.atime=r?.atime??n?.atime??Vo(t,e+476,12),this.ctime=r?.ctime??n?.ctime??Vo(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=ww(this.path||"",r),i=n[0],s=n[1];this.needPax=!!n[2],this.needPax=Qt(t,e,100,i)||this.needPax,this.needPax=Nt(t,e+100,8,this.mode)||this.needPax,this.needPax=Nt(t,e+108,8,this.uid)||this.needPax,this.needPax=Nt(t,e+116,8,this.gid)||this.needPax,this.needPax=Nt(t,e+124,12,this.size)||this.needPax,this.needPax=Zo(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=Qt(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=Qt(t,e+265,32,this.uname)||this.needPax,this.needPax=Qt(t,e+297,32,this.gname)||this.needPax,this.needPax=Nt(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Nt(t,e+337,8,this.devmin)||this.needPax,this.needPax=Qt(t,e+345,r,s)||this.needPax,t[e+475]!==0?this.needPax=Qt(t,e+345,155,s)||this.needPax:(this.needPax=Qt(t,e+345,130,s)||this.needPax,this.needPax=Zo(t,e+476,12,this.atime)||this.needPax,this.needPax=Zo(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,Nt(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:ys.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Da.get(t));if(ns(e)||e==="Unsupported")this.#e=e;else if(ns(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},ww=(t,e)=>{let r=t,n="",i,s=Or.parse(t).root||".";if(Buffer.byteLength(r)<100)i=[r,n,!1];else{n=Or.dirname(r),r=Or.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=Or.join(Or.basename(n),r),n=Or.dirname(n));while(n!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},Yt=(t,e,r)=>t.subarray(e,e+r).toString("utf8").replace(/\0.*/,""),Vo=(t,e,r)=>yw(Dt(t,e,r)),yw=t=>t===void 0?void 0:new Date(t*1e3),Dt=(t,e,r)=>Number(t[e])&128?hw(t.subarray(e,e+r)):Ew(t,e,r),_w=t=>isNaN(t)?void 0:t,Ew=(t,e,r)=>_w(parseInt(t.subarray(e,e+r).toString("utf8").replace(/\0.*$/,"").trim(),8)),Sw={12:8589934591,8:2097151},Nt=(t,e,r,n)=>n===void 0?!1:n>Sw[r]||n<0?(lw(n,t.subarray(e,e+r)),!0):(Iw(t,e,r,n),!1),Iw=(t,e,r,n)=>t.write(vw(n,r),e,r,"ascii"),vw=(t,e)=>Tw(Math.floor(t).toString(8),e),Tw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",Zo=(t,e,r,n)=>n===void 0?!1:Nt(t,e,r,n.getTime()/1e3),Rw=new Array(156).join("\0"),Qt=(t,e,r,n)=>n===void 0?!1:(t.write(n+Rw,e,r,"utf8"),n.length!==Buffer.byteLength(n)||n.length>r),hs=class ou{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 ar({path:("PaxHeader/"+kw(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+`
|
|
82
|
-
`,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
|
|
83
|
-
`).reduce(xw,Object.create(null)),xw=(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},Ow=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,D=Ow!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),au=class extends cr{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))))}},_s=(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))},Pw=1024*1024,ua=Buffer.from([31,139]),ha=Buffer.from([40,181,47,253]),Cw=Math.max(ua.length,ha.length),Ne=Symbol("state"),er=Symbol("writeEntry"),ft=Symbol("readEntry"),Ko=Symbol("nextEntry"),vd=Symbol("processEntry"),Ye=Symbol("extendedHeader"),Tn=Symbol("globalExtendedHeader"),At=Symbol("meta"),Td=Symbol("emitMeta"),H=Symbol("buffer"),pt=Symbol("queue"),xt=Symbol("ended"),Xo=Symbol("emittedEnd"),tr=Symbol("emit"),Q=Symbol("unzip"),Ji=Symbol("consumeChunk"),Vi=Symbol("consumeChunkSub"),Yo=Symbol("consumeBody"),Rd=Symbol("consumeMeta"),kd=Symbol("consumeHeader"),Rn=Symbol("consuming"),Qo=Symbol("bufferConcat"),Zi=Symbol("maybeEnd"),Pr=Symbol("writing"),Ot=Symbol("aborted"),Ki=Symbol("onDone"),rr=Symbol("sawValidEntry"),Xi=Symbol("sawNullBlock"),Yi=Symbol("sawEOF"),bd=Symbol("closeStream"),Dw=()=>!0,$n=class extends Ym{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[pt]=[];[H];[ft];[er];[Ne]="begin";[At]="";[Ye];[Tn];[xt]=!1;[Q];[Ot]=!1;[rr];[Xi]=!1;[Yi]=!1;[Pr]=!1;[Rn]=!1;[Xo]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(Ki,()=>{(this[Ne]==="begin"||this[rr]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(Ki,t.ondone):this.on(Ki,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||Pw,this.filter=typeof t.filter=="function"?t.filter:Dw;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[bd]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,r={}){_s(this,t,e,r)}[kd](t,e){this[rr]===void 0&&(this[rr]=!1);let r;try{r=new ar(t,e,this[Ye],this[Tn])}catch(n){return this.warn("TAR_ENTRY_INVALID",n)}if(r.nullBlock)this[Xi]?(this[Yi]=!0,this[Ne]==="begin"&&(this[Ne]="header"),this[tr]("eof")):(this[Xi]=!0,this[tr]("nullBlock"));else if(this[Xi]=!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[er]=new au(r,this[Ye],this[Tn]);if(!this[rr])if(i.remain){let s=()=>{i.invalid||(this[rr]=!0)};i.on("end",s)}else this[rr]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[tr]("ignoredEntry",i),this[Ne]="ignore",i.resume()):i.size>0&&(this[At]="",i.on("data",s=>this[At]+=s),this[Ne]="meta"):(this[Ye]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[tr]("ignoredEntry",i),this[Ne]=i.remain?"ignore":"header",i.resume()):(i.remain?this[Ne]="body":(this[Ne]="header",i.end()),this[ft]?this[pt].push(i):(this[pt].push(i),this[Ko]())))}}}[bd](){queueMicrotask(()=>this.emit("close"))}[vd](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[Ko]()),e=!1);return e}[Ko](){do;while(this[vd](this[pt].shift()));if(this[pt].length===0){let t=this[ft];!t||t.flowing||t.size===t.remain?this[Pr]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[Yo](t,e){let r=this[er];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[Ne]="header",this[er]=void 0,r.end()),i.length}[Rd](t,e){let r=this[er],n=this[Yo](t,e);return!this[er]&&r&&this[Td](r),n}[tr](t,e,r){this[pt].length===0&&!this[ft]?this.emit(t,e,r):this[pt].push([t,e,r])}[Td](t){switch(this[tr]("meta",this[At]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[Ye]=hs.parse(this[At],this[Ye],!1);break;case"GlobalExtendedHeader":this[Tn]=hs.parse(this[At],this[Tn],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[Ye]??Object.create(null);this[Ye]=e,e.path=this[At].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[Ye]||Object.create(null);this[Ye]=e,e.linkpath=this[At].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[Ot]=!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[Ot])return r?.(),!1;if((this[Q]===void 0||this.brotli===void 0&&this[Q]===!1)&&t){if(this[H]&&(t=Buffer.concat([this[H],t]),this[H]=void 0),t.length<Cw)return this[H]=t,r?.(),!0;for(let o=0;this[Q]===void 0&&o<ua.length;o++)t[o]!==ua[o]&&(this[Q]=!1);let i=!1;if(this[Q]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<ha.length;o++)if(t[o]!==ha[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[Q]===!1&&s)if(t.length<512)if(this[xt])this.brotli=!0;else return this[H]=t,r?.(),!0;else try{new ar(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Q]===void 0||this[Q]===!1&&(this.brotli||i)){let o=this[xt];this[xt]=!1,this[Q]=this[Q]===void 0?new iw({}):i?new cw({}):new ow({}),this[Q].on("data",c=>this[Ji](c)),this[Q].on("error",c=>this.abort(c)),this[Q].on("end",()=>{this[xt]=!0,this[Ji]()}),this[Pr]=!0;let a=!!this[Q][o?"end":"write"](t);return this[Pr]=!1,r?.(),a}}this[Pr]=!0,this[Q]?this[Q].write(t):this[Ji](t),this[Pr]=!1;let n=this[pt].length>0?!1:this[ft]?this[ft].flowing:!0;return!n&&this[pt].length===0&&this[ft]?.once("drain",()=>this.emit("drain")),r?.(),n}[Qo](t){t&&!this[Ot]&&(this[H]=this[H]?Buffer.concat([this[H],t]):t)}[Zi](){if(this[xt]&&!this[Xo]&&!this[Ot]&&!this[Rn]){this[Xo]=!0;let t=this[er];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[tr](Ki)}}[Ji](t){if(this[Rn]&&t)this[Qo](t);else if(!t&&!this[H])this[Zi]();else if(t){if(this[Rn]=!0,this[H]){this[Qo](t);let e=this[H];this[H]=void 0,this[Vi](e)}else this[Vi](t);for(;this[H]&&this[H]?.length>=512&&!this[Ot]&&!this[Yi];){let e=this[H];this[H]=void 0,this[Vi](e)}this[Rn]=!1}(!this[H]||this[xt])&&this[Zi]()}[Vi](t){let e=0,r=t.length;for(;e+512<=r&&!this[Ot]&&!this[Yi];)switch(this[Ne]){case"begin":case"header":this[kd](t,e),e+=512;break;case"ignore":case"body":e+=this[Yo](t,e);break;case"meta":e+=this[Rd](t,e);break;default:throw new Error("invalid state: "+this[Ne])}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[Ot]||(this[Q]?(t&&this[Q].write(t),this[Q].end()):(this[xt]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[Zi]())),this}},Nn=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)==="/";)r=e,e--;return r===-1?t:t.slice(0,r)},Nw=t=>{let e=t.onReadEntry;t.onReadEntry=e?r=>{e(r),r.resume()}:r=>r.resume()},cu=(t,e)=>{let r=new Map(e.map(s=>[Nn(s),!0])),n=t.filter,i=(s,o="")=>{let a=o||jm(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(Nn(s)):s=>i(Nn(s))},Lw=t=>{let e=new $n(t),r=t.file,n;try{n=Mr.openSync(r,"r");let i=Mr.fstatSync(n),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),a=Mr.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=Mr.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{Mr.closeSync(n)}catch{}}},Fw=(t,e)=>{let r=new $n(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("end",s),Mr.stat(i,(a,c)=>{if(a)o(a);else{let l=new Oa(i,{readSize:n,size:c.size});l.on("error",o),l.pipe(r)}})})},$r=Gn(Lw,Fw,t=>new $n(t),t=>new $n(t),(t,e)=>{e?.length&&cu(t,e),t.noResume||Nw(t)}),lu=(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:Bw,parse:xd}=Mw,Na=t=>{let e="",r=xd(t);for(;Bw(t)||r.root;){let n=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":r.root;t=t.slice(n.length),e+=n,r=xd(t)}return[e,t]},Es=["|","<",">","?",":"],La=Es.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Uw=new Map(Es.map((t,e)=>[t,La[e]])),zw=new Map(La.map((t,e)=>[t,Es[e]])),Od=t=>Es.reduce((e,r)=>e.split(r).join(Uw.get(r)),t),$w=t=>La.reduce((e,r)=>e.split(r).join(zw.get(r)),t),du=(t,e)=>e?(t=D(t).replace(/^\.(\/|$)/,""),Nn(e)+"/"+t):D(t),Gw=16*1024*1024,Pd=Symbol("process"),Cd=Symbol("file"),Dd=Symbol("directory"),fa=Symbol("symlink"),Nd=Symbol("hardlink"),kn=Symbol("header"),is=Symbol("read"),pa=Symbol("lstat"),ss=Symbol("onlstat"),ga=Symbol("onread"),ma=Symbol("onreadlink"),wa=Symbol("openfile"),ya=Symbol("onopenfile"),Lt=Symbol("close"),ps=Symbol("mode"),_a=Symbol("awaitDrain"),ea=Symbol("ondrain"),et=Symbol("prefix"),uu=class extends cr{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=Pa(e);super(),this.path=D(t),this.portable=!!r.portable,this.maxReadSize=r.maxReadSize||Gw,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]=Na(this.path);s&&typeof o=="string"&&(this.path=o,n=s)}this.win32=!!r.win32||process.platform==="win32",this.win32&&(this.path=$w(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=D(r.absolute||Ad.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[ss](i):this[pa]()}warn(t,e,r={}){return _s(this,t,e,r)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[pa](){Qe.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ss](e)})}[ss](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Ww(t),this.emit("stat",t),this[Pd]()}[Pd](){switch(this.type){case"File":return this[Cd]();case"Directory":return this[Dd]();case"SymbolicLink":return this[fa]();default:return this.end()}}[ps](t){return lu(t,this.type==="Directory",this.portable)}[et](t){return du(t,this.prefix)}[kn](){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 ar({path:this[et](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[et](this.linkpath):this.linkpath,mode:this[ps](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 hs({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[et](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[et](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)}[Dd](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[kn](),this.end()}[fa](){Qe.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ma](e)})}[ma](t){this.linkpath=D(t),this[kn](),this.end()}[Nd](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=D(Ad.relative(this.cwd,t)),this.stat.size=0,this[kn](),this.end()}[Cd](){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[Nd](e);this.linkCache.set(t,this.absolute)}if(this[kn](),this.stat.size===0)return this.end();this[wa]()}[wa](){Qe.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[ya](e)})}[ya](t){if(this.fd=t,this.#e)return this[Lt]();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[is]()}[is](){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");Qe.read(t,e,r,n,i,(s,o)=>{if(s)return this[Lt](()=>this.emit("error",s));this[ga](o)})}[Lt](t=()=>{}){this.fd!==void 0&&Qe.close(this.fd,t)}[ga](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[Lt](()=>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[Lt](()=>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[ea]():this[_a](()=>this[ea]())}[_a](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)}[ea](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Lt](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[is]()}},Hw=class extends uu{sync=!0;[pa](){this[ss](Qe.lstatSync(this.absolute))}[fa](){this[ma](Qe.readlinkSync(this.absolute))}[wa](){this[ya](Qe.openSync(this.absolute,"r"))}[is](){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=Qe.readSync(e,r,n,i,s);this[ga](o),t=!1}finally{if(t)try{this[Lt](()=>{})}catch{}}}[_a](t){t()}[Lt](t=()=>{}){this.fd!==void 0&&Qe.closeSync(this.fd),t()}},jw=class extends cr{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 _s(this,t,e,r)}constructor(t,e={}){let r=Pa(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[ps](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]=Na(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 ar({path:this[et](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[et](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 hs({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[et](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[et](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)}[et](t){return du(t,this.prefix)}[ps](t){return lu(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}},Ww=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",qw=class Br{tail;head;length=0;static create(e=[]){return new Br(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++)Vw(this,e[r]);return this.length}unshift(...e){for(var r=0,n=e.length;r<n;r++)Zw(this,e[r]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,r=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,r.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,r=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,r.list=void 0,this.length--,e}forEach(e,r){r=r||this;for(let 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 Br;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 Br;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 Br;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 Br;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=Jw(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 Jw(t,e,r){let n=e,i=e?e.next:t.head,s=new Fa(r,n,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function Vw(t,e){t.tail=new Fa(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Zw(t,e){t.head=new Fa(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Fa=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}},Fd=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Md=Buffer.alloc(1024),os=Symbol("onStat"),bn=Symbol("ended"),$e=Symbol("queue"),An=Symbol("queue"),Pt=Symbol("current"),nr=Symbol("process"),xn=Symbol("processing"),Qi=Symbol("processJob"),Ge=Symbol("jobs"),ta=Symbol("jobDone"),as=Symbol("addFSEntry"),Bd=Symbol("addTarEntry"),Ea=Symbol("stat"),Sa=Symbol("readdir"),cs=Symbol("onreaddir"),ls=Symbol("pipe"),Ud=Symbol("entry"),ra=Symbol("entryOpt"),ds=Symbol("writeEntryClass"),hu=Symbol("write"),na=Symbol("ondrain"),Ss=class extends cr{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ds];onWriteEntry;[$e];[An]=new Map;[Ge]=0;[xn]=!1;[bn]=!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[ds]=uu,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 nw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new sw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new aw(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",r=>super.write(r)),e.on("end",()=>super.end()),e.on("drain",()=>this[na]()),this.on("resume",()=>e.resume())}else this.on("drain",this[na]);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[$e]=new qw,this[Ge]=0,this.jobs=Number(t.jobs)||4,this[xn]=!1,this[bn]=!1}[hu](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[bn]=!0,this[nr](),r&&r(),this}write(t){if(this[bn])throw new Error("write after end");return t instanceof au?this[Bd](t):this[as](t),this.flowing}[Bd](t){let e=D(Ld.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let r=new Fd(t.path,e);r.entry=new jw(t,this[ra](r)),r.entry.on("end",()=>this[ta](r)),this[Ge]+=1,this[$e].push(r)}this[nr]()}[as](t){let e=D(Ld.resolve(this.cwd,t));this[$e].push(new Fd(t,e)),this[nr]()}[Ea](t){t.pending=!0,this[Ge]+=1;let e=this.follow?"stat":"lstat";fs[e](t.absolute,(r,n)=>{t.pending=!1,this[Ge]-=1,r?this.emit("error",r):this[os](t,n)})}[os](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[Pt])this[Qi](t);else{let r=`${e.dev}:${e.ino}`,n=this[An].get(r);n?n.push(t):this[An].set(r,[t]),t.pendingLink=!0,t.pending=!0}this[nr]()}[Sa](t){t.pending=!0,this[Ge]+=1,fs.readdir(t.absolute,(e,r)=>{if(t.pending=!1,this[Ge]-=1,e)return this.emit("error",e);this[cs](t,r)})}[cs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[nr]()}[nr](){if(!this[xn]){this[xn]=!0;for(let t=this[$e].head;t&&this[Ge]<this.jobs;t=t.next)if(this[Qi](t.value),t.value.ignore){let e=t.next;this[$e].removeNode(t),t.next=e}this[xn]=!1,this[bn]&&this[$e].length===0&&this[Ge]===0&&(this.zip?this.zip.end(Md):(super.write(Md),super.end()))}}get[Pt](){return this[$e]&&this[$e].head&&this[$e].head.value}[ta](t){this[$e].shift(),this[Ge]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let r=`${e.dev}:${e.ino}`,n=this[An].get(r);if(n){this[An].delete(r);for(let i of n)i.pending=!1,this[Qi](i)}}this[nr]()}[Qi](t){if(t.pending&&t.pendingLink&&t===this[Pt]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Pt]&&!t.piped&&this[ls](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[os](t,e):this[Ea](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[cs](t,e):this[Sa](t),!t.readdir)return}if(t.entry=this[Ud](t),!t.entry){t.ignore=!0;return}t===this[Pt]&&!t.piped&&this[ls](t)}}}[ra](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}}[Ud](t){this[Ge]+=1;try{return new this[ds](t.path,this[ra](t)).on("end",()=>this[ta](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[na](){this[Pt]&&this[Pt].entry&&this[Pt].entry.resume()}[ls](t){t.piped=!0,t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[as](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={}){_s(this,t,e,r)}},Ma=class extends Ss{sync=!0;constructor(t){super(t),this[ds]=Hw}pause(){}resume(){}[Ea](t){let e=this.follow?"statSync":"lstatSync";this[os](t,fs[e](t.absolute))}[Sa](t){this[cs](t,fs.readdirSync(t.absolute))}[ls](t){let e=t.entry,r=this.zip;if(t.readdir&&t.readdir.forEach(n=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[as](s+n)}),!e)throw new Error("Cannot pipe without source");r?e.on("data",n=>{r.write(n)}):e.on("data",n=>{super[hu](n)})}},Kw=(t,e)=>{let r=new Ma(t),n=new Qd(t.file,{mode:t.mode||438});r.pipe(n),fu(r,e)},Xw=(t,e)=>{let r=new Ss(t),n=new ws(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 pu(r,e).catch(s=>r.emit("error",s)),i},fu=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?$r({file:eu.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r)}),t.end()},pu=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await $r({file:eu.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>{t.add(n)}}):t.add(r);t.end()},Yw=(t,e)=>{let r=new Ma(t);return fu(r,e),r},Qw=(t,e)=>{let r=new Ss(t);return pu(r,e).catch(n=>r.emit("error",n)),r},TR=Gn(Kw,Xw,Yw,Qw,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),ty=process.env.__FAKE_PLATFORM__||process.platform,yu=ty==="win32",{O_CREAT:_u,O_NOFOLLOW:zd,O_TRUNC:Eu,O_WRONLY:Su}=wu.constants,Iu=Number(process.env.__FAKE_FS_O_FILENAME__)||wu.constants.UV_FS_O_FILEMAP||0,ry=yu&&!!Iu,ny=512*1024,iy=Iu|Eu|_u|Su,$d=!yu&&typeof zd=="number"?zd|Eu|_u|Su:null,vu=$d!==null?()=>$d:ry?t=>t<ny?iy:"w":()=>"w",Ia=(t,e,r)=>{try{return Is.lchownSync(t,e,r)}catch(n){if(n?.code!=="ENOENT")throw n}},gs=(t,e,r,n)=>{Is.lchown(t,e,r,i=>{n(i&&i?.code!=="ENOENT"?i:null)})},sy=(t,e,r,n,i)=>{if(e.isDirectory())Tu(Ln.resolve(t,e.name),r,n,s=>{if(s)return i(s);let o=Ln.resolve(t,e.name);gs(o,r,n,i)});else{let s=Ln.resolve(t,e.name);gs(s,r,n,i)}},Tu=(t,e,r,n)=>{Is.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 gs(t,e,r,n);let o=s.length,a=null,c=l=>{if(!a){if(l)return n(a=l);if(--o===0)return gs(t,e,r,n)}};for(let l of s)sy(t,l,e,r,c)})},oy=(t,e,r,n)=>{e.isDirectory()&&Ru(Ln.resolve(t,e.name),r,n),Ia(Ln.resolve(t,e.name),r,n)},Ru=(t,e,r)=>{let n;try{n=Is.readdirSync(t,{withFileTypes:!0})}catch(i){let s=i;if(s?.code==="ENOENT")return;if(s?.code==="ENOTDIR"||s?.code==="ENOTSUP")return Ia(t,e,r);throw s}for(let i of n)oy(t,i,e,r);return Ia(t,e,r)},ku=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"}},vs=class extends Error{path;symlink;syscall="symlink";code="TAR_SYMLINK_ERROR";constructor(t,e){super("TAR_SYMLINK_ERROR: Cannot extract through symbolic link"),this.symlink=t,this.path=e}get name(){return"SymlinkError"}},cy=(t,e)=>{xe.stat(t,(r,n)=>{(r||!n.isDirectory())&&(r=new ku(t,r?.code||"ENOTDIR")),e(r)})},ly=(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=(f,g)=>{f?r(f):g&&c?Tu(g,o,a,w=>m(w)):s?xe.chmod(t,i,r):r()};if(t===p)return cy(t,m);if(l)return ay.mkdir(t,{mode:i,recursive:!0}).then(f=>m(null,f??void 0),m);let h=D(ms.relative(p,t)).split("/");va(p,h,i,d,p,void 0,m)},va=(t,e,r,n,i,s,o)=>{if(e.length===0)return o(null,s);let a=e.shift(),c=D(ms.resolve(t+"/"+a));xe.mkdir(c,r,bu(c,e,r,n,i,s,o))},bu=(t,e,r,n,i,s,o)=>a=>{a?xe.lstat(t,(c,l)=>{if(c)c.path=c.path&&D(c.path),o(c);else if(l.isDirectory())va(t,e,r,n,i,s,o);else if(n)xe.unlink(t,d=>{if(d)return o(d);xe.mkdir(t,r,bu(t,e,r,n,i,s,o))});else{if(l.isSymbolicLink())return o(new vs(t,t+"/"+e.join("/")));o(a)}}):(s=s||t,va(t,e,r,n,i,s,o))},dy=t=>{let e=!1,r;try{e=xe.statSync(t).isDirectory()}catch(n){r=n?.code}finally{if(!e)throw new ku(t,r??"ENOTDIR")}},uy=(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=f=>{f&&a&&Ru(f,s,o),i&&xe.chmodSync(t,n)};if(t===d)return dy(d),p();if(c)return p(xe.mkdirSync(t,{mode:n,recursive:!0})??void 0);let m=D(ms.relative(d,t)).split("/"),h;for(let f=m.shift(),g=d;f&&(g+="/"+f);f=m.shift()){g=D(ms.resolve(g));try{xe.mkdirSync(g,n),h=h||g}catch{let w=xe.lstatSync(g);if(w.isDirectory())continue;if(l){xe.unlinkSync(g),xe.mkdirSync(g,n),h=h||g;continue}else if(w.isSymbolicLink())return new vs(g,g+"/"+m.join("/"))}}return p(h)},ia=Object.create(null),Gd=1e4,Cr=new Set,hy=t=>{Cr.has(t)?Cr.delete(t):ia[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Cr.add(t);let e=ia[t],r=Cr.size-Gd;if(r>Gd/10){for(let n of Cr)if(Cr.delete(n),delete ia[n],--r<=0)break}return e},fy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,py=fy==="win32",gy=t=>t.split("/").slice(0,-1).reduce((e,r)=>{let n=e.at(-1);return n!==void 0&&(r=Au(n,r)),e.push(r||"/"),e},[]),my=class{#e=new Map;#r=new Map;#n=new Set;reserve(t,e){t=py?["win32 parallelization disabled"]:t.map(n=>Nn(Au(hy(n))));let r=new Set(t.map(n=>gy(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}},wy=()=>process.umask(),Hd=Symbol("onEntry"),Ta=Symbol("checkFs"),jd=Symbol("checkFs2"),Ra=Symbol("isReusable"),Le=Symbol("makeFs"),ka=Symbol("file"),ba=Symbol("directory"),us=Symbol("link"),Wd=Symbol("symlink"),qd=Symbol("hardlink"),Cn=Symbol("ensureNoSymlink"),Jd=Symbol("unsupported"),Vd=Symbol("checkPath"),sa=Symbol("stripAbsolutePath"),Ft=Symbol("mkdir"),le=Symbol("onError"),es=Symbol("pending"),Zd=Symbol("pend"),Dr=Symbol("unpend"),oa=Symbol("ended"),aa=Symbol("maybeClose"),Aa=Symbol("skip"),Fn=Symbol("doChown"),Mn=Symbol("uid"),Bn=Symbol("gid"),Un=Symbol("checkedCwd"),yy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,zn=yy==="win32",_y=1024,Ey=(t,e)=>{if(!zn)return L.unlink(t,e);let r=t+".DELETE."+mu(16).toString("hex");L.rename(t,r,n=>{if(n)return e(n);L.unlink(r,e)})},Sy=t=>{if(!zn)return L.unlinkSync(t);let e=t+".DELETE."+mu(16).toString("hex");L.renameSync(t,e),L.unlinkSync(e)},Kd=(t,e,r)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:r,Ba=class extends $n{[oa]=!1;[Un]=!1;[es]=0;reservations=new my;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[oa]=!0,this[aa]()},super(t),this.transform=t.transform,this.chmod=!!t.chmod,typeof t.uid=="number"||typeof t.gid=="number"){if(typeof t.uid!="number"||typeof t.gid!="number")throw new TypeError("cannot set owner without number uid and gid");if(t.preserveOwner)throw new TypeError("cannot preserve owner in archive and also set owner explicitly");this.uid=t.uid,this.gid=t.gid,this.setOwner=!0}else this.uid=void 0,this.gid=void 0,this.setOwner=!1;this.preserveOwner=t.preserveOwner===void 0&&typeof t.uid!="number"?!!(process.getuid&&process.getuid()===0):!!t.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():void 0,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():void 0,this.maxDepth=typeof t.maxDepth=="number"?t.maxDepth:_y,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||zn,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=D(re.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:wy():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[Hd](e))}warn(t,e,r={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(r.recoverable=!1),super.warn(t,e,r)}[aa](){this[oa]&&this[es]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[sa](t,e){let r=t[e],{type:n}=t;if(!r||this.preservePaths)return!0;let[i,s]=Na(r),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||zn&&/^[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=re.posix.dirname(t.path),c=re.posix.normalize(re.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}[Vd](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[sa](t,"path")||!this[sa](t,"linkpath"))return!1;if(t.absolute=re.isAbsolute(t.path)?D(re.resolve(t.path)):D(re.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}=re.win32.parse(String(t.absolute));t.absolute=n+Od(String(t.absolute).slice(n.length));let{root:i}=re.win32.parse(t.path);t.path=i+Od(t.path.slice(i.length))}return!0}[Hd](t){if(!this[Vd](t))return t.resume();switch(ey.equal(typeof t.absolute,"string"),t.type){case"Directory":case"GNUDumpDir":t.mode&&(t.mode=t.mode|448);case"File":case"OldFile":case"ContiguousFile":case"Link":case"SymbolicLink":return this[Ta](t);default:return this[Jd](t)}}[le](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Dr](),e.resume())}[Ft](t,e,r){ly(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)}[Fn](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}[Mn](t){return Kd(this.uid,t.uid,this.processUid)}[Bn](t){return Kd(this.gid,t.gid,this.processGid)}[ka](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=new ws(String(t.absolute),{flags:vu(t.size),mode:r,autoClose:!1});n.on("error",a=>{n.fd&&L.close(n.fd,()=>{}),n.write=()=>!0,this[le](a,t),e()});let i=1,s=a=>{if(a){n.fd&&L.close(n.fd,()=>{}),this[le](a,t),e();return}--i===0&&n.fd!==void 0&&L.close(n.fd,c=>{c?this[le](c,t):this[Dr](),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;L.futimes(c,l,d,p=>p?L.utimes(a,l,d,m=>s(m&&p)):s())}if(typeof c=="number"&&this[Fn](t)){i++;let l=this[Mn](t),d=this[Bn](t);typeof l=="number"&&typeof d=="number"&&L.fchown(c,l,d,p=>p?L.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[le](a,t),e()}),t.pipe(o)),o.pipe(n)}[ba](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Ft](String(t.absolute),r,n=>{if(n){this[le](n,t),e();return}let i=1,s=()=>{--i===0&&(e(),this[Dr](),t.resume())};t.mtime&&!this.noMtime&&(i++,L.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[Fn](t)&&(i++,L.chown(String(t.absolute),Number(this[Mn](t)),Number(this[Bn](t)),s)),s()})}[Jd](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[Wd](t,e){let r=D(re.relative(this.cwd,re.resolve(re.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Cn](t,this.cwd,r,()=>this[us](t,String(t.linkpath),"symlink",e),n=>{this[le](n,t),e()})}[qd](t,e){let r=D(re.resolve(this.cwd,String(t.linkpath))),n=D(String(t.linkpath)).split("/");this[Cn](t,this.cwd,n,()=>this[us](t,r,"link",e),i=>{this[le](i,t),e()})}[Cn](t,e,r,n,i){let s=r.shift();if(this.preservePaths||s===void 0)return n();let o=re.resolve(e,s);L.lstat(o,(a,c)=>{if(a)return n();if(c?.isSymbolicLink())return i(new vs(o,re.resolve(o,r.join("/"))));this[Cn](t,o,r,n,i)})}[Zd](){this[es]++}[Dr](){this[es]--,this[aa]()}[Aa](t){this[Dr](),t.resume()}[Ra](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!zn}[Ta](t){this[Zd]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,r=>this[jd](t,r))}[jd](t,e){let r=o=>{e(o)},n=()=>{this[Ft](this.cwd,this.dmode,o=>{if(o){this[le](o,t),r();return}this[Un]=!0,i()})},i=()=>{if(t.absolute!==this.cwd){let o=D(re.dirname(String(t.absolute)));if(o!==this.cwd)return this[Ft](o,this.dmode,a=>{if(a){this[le](a,t),r();return}s()})}s()},s=()=>{L.lstat(String(t.absolute),(o,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[Aa](t),r();return}if(o||this[Ra](t,a))return this[Le](null,t,r);if(a.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,l=d=>this[Le](d??null,t,r);return c?L.chmod(String(t.absolute),Number(t.mode),l):l()}if(t.absolute!==this.cwd)return L.rmdir(String(t.absolute),c=>this[Le](c??null,t,r))}if(t.absolute===this.cwd)return this[Le](null,t,r);Ey(String(t.absolute),c=>this[Le](c??null,t,r))})};this[Un]?i():n()}[Le](t,e,r){if(t){this[le](t,e),r();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[ka](e,r);case"Link":return this[qd](e,r);case"SymbolicLink":return this[Wd](e,r);case"Directory":case"GNUDumpDir":return this[ba](e,r)}}[us](t,e,r,n){L[r](e,String(t.absolute),i=>{i?this[le](i,t):(this[Dr](),t.resume()),n()})}},On=t=>{try{return[null,t()]}catch(e){return[e,null]}},xu=class extends Ba{sync=!0;[Le](t,e){return super[Le](t,e,()=>{})}[Ta](t){if(!this[Un]){let i=this[Ft](this.cwd,this.dmode);if(i)return this[le](i,t);this[Un]=!0}if(t.absolute!==this.cwd){let i=D(re.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[Ft](i,this.dmode);if(s)return this[le](s,t)}}let[e,r]=On(()=>L.lstatSync(String(t.absolute)));if(r&&(this.keep||this.newer&&r.mtime>(t.mtime??r.mtime)))return this[Aa](t);if(e||this[Ra](t,r))return this[Le](null,t);if(r.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(r.mode&4095)!==t.mode,[o]=s?On(()=>{L.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[Le](o,t)}let[i]=On(()=>L.rmdirSync(String(t.absolute)));this[Le](i,t)}let[n]=t.absolute===this.cwd?[]:On(()=>Sy(String(t.absolute)));this[Le](n,t)}[ka](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.fmode,n=o=>{let a;try{L.closeSync(i)}catch(c){a=c}(o||a)&&this[le](o||a,t),e()},i;try{i=L.openSync(String(t.absolute),vu(t.size),r)}catch(o){return n(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[le](o,t)),t.pipe(s)),s.on("data",o=>{try{L.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{L.futimesSync(i,a,c)}catch(l){try{L.utimesSync(String(t.absolute),a,c)}catch{o=l}}}if(this[Fn](t)){let a=this[Mn](t),c=this[Bn](t);try{L.fchownSync(i,Number(a),Number(c))}catch(l){try{L.chownSync(String(t.absolute),Number(a),Number(c))}catch{o=o||l}}}n(o)})}[ba](t,e){let r=typeof t.mode=="number"?t.mode&4095:this.dmode,n=this[Ft](String(t.absolute),r);if(n){this[le](n,t),e();return}if(t.mtime&&!this.noMtime)try{L.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Fn](t))try{L.chownSync(String(t.absolute),Number(this[Mn](t)),Number(this[Bn](t)))}catch{}e(),t.resume()}[Ft](t,e){try{return uy(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}}[Cn](t,e,r,n,i){if(this.preservePaths||r.length===0)return n();let s=e;for(let o of r){s=re.resolve(s,o);let[a,c]=On(()=>L.lstatSync(s));if(a)return n();if(c.isSymbolicLink())return i(new vs(s,re.resolve(e,r.join("/"))))}n()}[us](t,e,r,n){let i=`${r}Sync`;try{L[i](e,String(t.absolute)),n(),t.resume()}catch(s){return this[le](s,t)}}},Iy=t=>{let e=new xu(t),r=t.file,n=gu.statSync(r),i=t.maxReadSize||16*1024*1024;new Gm(r,{readSize:i,size:n.size}).pipe(e)},vy=(t,e)=>{let r=new Ba(t),n=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{r.on("error",o),r.on("close",s),gu.stat(i,(a,c)=>{if(a)o(a);else{let l=new Oa(i,{readSize:n,size:c.size});l.on("error",o),l.pipe(r)}})})},Ou=Gn(Iy,vy,t=>new xu(t),t=>new Ba(t),(t,e)=>{e?.length&&cu(t,e)}),Ty=(t,e)=>{let r=new Ma(t),n=!0,i,s;try{try{i=Ae.openSync(t.file,"r+")}catch(c){if(c?.code==="ENOENT")i=Ae.openSync(t.file,"w+");else throw c}let o=Ae.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=Ae.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 ar(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,Ry(t,r,s,i,e)}finally{if(n)try{Ae.closeSync(i)}catch{}}},Ry=(t,e,r,n,i)=>{let s=new Qd(t.file,{fd:n,start:r});e.pipe(s),by(e,i)},ky=(t,e)=>{e=Array.from(e);let r=new Ss(t),n=(i,s,o)=>{let a=(m,h)=>{m?Ae.close(i,f=>o(m)):o(null,h)},c=0;if(s===0)return a(null,0);let l=0,d=Buffer.alloc(512),p=(m,h)=>{if(m||h===void 0)return a(m);if(l+=h,l<512&&h)return Ae.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 f=new ar(d);if(!f.cksumValid)return a(null,c);let g=512*Math.ceil((f.size??0)/512);if(c+g+512>s||(c+=g+512,c>=s))return a(null,c);t.mtimeCache&&f.mtime&&t.mtimeCache.set(String(f.path),f.mtime),l=0,Ae.read(i,d,0,512,c,p)};Ae.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+",Ae.open(t.file,o,a);if(c||!l)return s(c);Ae.fstat(l,(d,p)=>{if(d)return Ae.close(l,()=>s(d));n(l,p.size,(m,h)=>{if(m)return s(m);let f=new ws(t.file,{fd:l,start:h});r.pipe(f),f.on("error",s),f.on("close",i),Ay(r,e)})})};Ae.open(t.file,o,a)})},by=(t,e)=>{e.forEach(r=>{r.charAt(0)==="@"?$r({file:Pu.resolve(t.cwd,r.slice(1)),sync:!0,noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r)}),t.end()},Ay=async(t,e)=>{for(let r of e)r.charAt(0)==="@"?await $r({file:Pu.resolve(String(t.cwd),r.slice(1)),noResume:!0,onReadEntry:n=>t.add(n)}):t.add(r);t.end()},Pn=Gn(Ty,ky,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!Km(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")}),UR=Gn(Pn.syncFile,Pn.asyncFile,Pn.syncNoFile,Pn.asyncNoFile,(t,e=[])=>{Pn.validate?.(t,e),xy(t)}),xy=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))};Rt();var We={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 Hn(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Cu(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function Du(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Nu(t){let{_meta:e,...r}=t;return{stripped:r,meta:e}}function Gr(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Ee();F();se();Ee();function wt(t,e){if(Hn(t)!=="cloud")throw new _("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function Ts(t){return t.startsWith("http://")||t.startsWith("https://")}function Rs(t){return t.endsWith("/")?t.slice(0,-1):t}Ee();F();var ks="1008033",Lu="1289";var Fu="pbbp2",Mu="https://www.coze.cn",Bu="/api/coze_claw/resource/get_frontier_key",Py="https://www.coze.cn",Cy="wss://frontier.coze.cn";function bs(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??Py}function Uu(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Cy}function Hr(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 Wn(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var jn=x("handshake");async function Ua(t){let e=bs(t.endpoint),r=t.timeoutMs??1e4,n=`${Rs(e)}${Bu}?aid=${encodeURIComponent(ks)}`,i={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Hr(t.ppeOverride)},s=new AbortController,o=setTimeout(()=>s.abort(),r);jn.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 f=await a.text().catch(()=>"");throw new _("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${f.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,h=typeof p.device_id=="string"&&p.device_id||typeof p.deviceId=="string"&&p.deviceId||void 0;if(!m||!h){let f=JSON.stringify(d).slice(0,500);throw new _("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${c}: ${f}`)}return jn.info("handshake ok",{remoteDeviceId:h,logid:c,traceId:l}),{accessKey:m,deviceId:h}}catch(a){if(a instanceof _)throw jn.error("handshake failed (bridge error)",{base:e,message:a.message,code:a.code}),a;if(a.name==="AbortError")throw jn.warn("handshake timeout",{base:e,timeoutMs:r}),new _("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${r}ms)`,{cause:a});let c=a.cause;throw jn.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 za=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",qe="auto",zu=2e5;function $u(t){return{model:$a(t.model)??qe,...t.modelToken?{modelToken:t.modelToken}:{}}}function Gu(t){return!t||t===qe}var Dy=new Set(["auto","\u81EA\u52A8"]);function $a(t){let e=t?.trim();if(e)return Dy.has(e.toLowerCase())?qe:e}function Hu(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=za,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let r=t.model||qe;e.ANTHROPIC_MODEL=r,e.ANTHROPIC_SMALL_FAST_MODEL=r,t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else Gu(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function ju(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||qe}"`):Gu(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="${za}/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??zu;e.push("-c",`model_context_window=${r}`)}return e}function Wu(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Ga(t,e){let{ttEnv:r,usePpe:n}=Wn(t),i={};return r&&(i["x-tt-env"]=r),n&&(i["x-use-ppe"]=n),e&&(i["x-mock-scenario"]=e),i}function qu(t,e,r){if(!t.modelToken)return{};let n=Ga(e,r);return Object.keys(n).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(n).map(([s,o])=>`${s}:${o}`).join(`
|
|
84
|
-
`)}}function Ha(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function Ju(t,e,r){if(!t.modelToken)return null;let n=t.model||qe,i=Ga(e,r),s=["text"];t.modelInfo?.capabilities?.image===!0&&s.push("image");let o={baseUrl:`${za}/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??zu,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(o.headers=i),o}function Vu(t,e,r){if(!t.modelToken)return[];let n=Ga(e,r),i=[];for(let[s,o]of Object.entries(n))i.push("-c",`model_providers.coze.http_headers.${s}="${o}"`);return i}var ne=x("agent-handlers"),Zu=5*1024*1024,Uy=1,zy=6,$y=new Set(["node_modules",".git",".coze","dist","build",".next"]),As=class{constructor(e){this.opts=e}opts;async listSkills(e){wt(e._meta,"_agent/listSkills");let r=Gr(e._meta),n=await this.loadAgentCfg(r),i=n?.workspace??ve(r).workspace,s=n?.skills??[],o=[];for(let a of s){let c=nt(i,a.relPath,"SKILL.md");await Fy(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(qy(a))}return{skills:o}}async addSkills(e){wt(e._meta,"_agent/addSkills");let r=Gr(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 Ka({agentId:r,workspace:n.workspace,framework:n.framework,skill:c});Xa(s,o,l),a.push(c)}return await Di(r,s),this.reloadAgentSessions(r,"skills-added"),{installedSkills:a}}async removeSkills(e){wt(e._meta,"_agent/removeSkills");let r=Gr(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=nt(n.workspace,a.relPath);await Ly(c,{recursive:!0,force:!0}),ne.info("skill removed",{agentId:r,skillId:a.skillId,relPath:a.relPath})}return await Di(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,ne.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,ne.info("killing downstream for workspace reload (idle)",{reason:r,agentId:e,framework:n.framework,cloudId:i,acpId:o}),c.stop(r).catch(l=>ne.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 ne.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let r=e.agentId,n=await ue(r);if(!n)throw new _("AGENT_NOT_FOUND",`agent not found: ${r}`);if(n.cozeIdentity===e.cozeIdentity)return ne.info("_agent/update: cozeIdentity unchanged, noop",{agentId:r}),{ok:!0};try{await Rr(n.workspace,n.framework,e.cozeIdentity)}catch(i){throw ne.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 Te(n),ne.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 ue(r);return n?(n.disconnectedAt=Date.now(),n.disconnectReason=e.reason??"",await Te(n),ne.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}):(ne.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=$a(e.model)??qe,n=await ue(e.agentId);if(!n)throw new _("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);n.model=r,e.modelInfo&&(n.modelInfo=e.modelInfo),await Te(n),ne.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:r,reason:e.reason??""});let i=this.opts.agents.get(e.agentId);if(!i)return ne.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=>ne.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),ne.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,We.RESET),!e.agentId)throw new _("IPC_BAD_REQUEST",`${We.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,We.RESET),await this.runDetailSync(e.agentId,We.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,r){let n=this.opts.agents.get(e);if(!n){await this.clearPersistedAcpSessionIds(e),ne.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 mn(e,i)}async clearPersistedAcpSessionIds(e){let r=await ue(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 Te(r)}async repairAgent(e){if(wt(e._meta,We.REPAIR),!e.agentId)throw new _("IPC_BAD_REQUEST",`${We.REPAIR}: missing agentId`);let r=await this.loadAgentCfg(e.agentId);if(r&&r.framework!=="openclaw")throw new _("IPC_BAD_REQUEST",`${We.REPAIR} only allowed for openclaw, got ${r.framework}`);if(r&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,r.workspace)}catch(n){ne.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(n)})}return await this.runDetailSync(e.agentId,We.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,r,n){if(!this.opts.detailSyncer){ne.warn("detailSyncer not wired, skipping sync",{method:r,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(i){ne.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=Gr(r),i=await this.resolveWorkspace(n),s=e.filePath??"",o=this.safeJoin(i,s),a=await ja(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 gn(o,i))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${s}`);let c=n_(e.depth);return a.isDirectory()?{tree:await r_(i,o,s,c)}:{tree:[{name:i_(s),path:rh(s||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){wt(e._meta,"_agent/getFileContent");let r=Gr(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 ja(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 gn(i,n))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(s.size>Zu)throw new _("IPC_BAD_REQUEST",`file too large: ${s.size} bytes (max ${Zu})`);let o=await Ku(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 ue(e).catch(()=>null))?.workspace??ve(e).workspace}safeJoin(e,r){let n=Ja(e,r||"."),i=Za(e,n);if(i.startsWith("..")||i===".."||i.startsWith(`..${Xu}`))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${r}`);return n}loadAgentCfg(e){return ue(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 Gy(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 Hy(t){return t==="claude-code"?nt(".claude","skills"):nt(".agents","skills")}var jy=3e4,Wy=50*1024*1024,jr=3e4;async function Ka(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=Gy(i.skillName),c=Hy(n),l=nt(c,a),d=nt(r,l);if(await Wa(d,{recursive:!0}),s){let m=Buffer.from(i.content,"utf8");qn(m.length),await qa(nt(d,"SKILL.md"),m,"utf8")}else{let m=await Jy(i.downloadUrl);Zy(m)?await Qy(m,d):Ky(m)?await Xy(m,d):await qa(nt(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 ne.info("skill installed",{agentId:e,skillId:i.skillId,skillName:i.skillName,relPath:l,source:s?"content":"downloadUrl"}),p}function Xa(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 qy(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 Jy(t){if(!t)throw new _("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);qn(e);let r=Vy(t);return qn(r.length),r}if(t.startsWith("file:")){let e=new URL(t).pathname,r=await Ku(e);return qn(r.length),r}if(Ts(t)){let e=new AbortController,r=setTimeout(()=>e.abort(),jy);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 qn(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 qn(t){if(t>Wy)throw new _("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function Vy(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 Zy(t){return t.length>=2&&t[0]===31&&t[1]===139}function Ky(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 Va(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function Xy(t,e){let r,n;try{r=new eh.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||Va(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=Yy(n),s=Ja(e);for(let o of n){if(Va(o.entryName))continue;let a=o.entryName;if(i&&a.startsWith(i)&&(a=a.slice(i.length)),!a)continue;let c=Ja(e,a),l=Za(s,c);if(l.startsWith("..")||l==="..")throw new _("IPC_BAD_REQUEST",`zip entry escapes destDir: ${a}`);if(o.isDirectory){await Wa(c,{recursive:!0});continue}await Wa(My(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 qa(c,d)}}function Yy(t){let e;for(let r of t){let n=r.entryName;if(!n||Va(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 Qy(t,e){await e_(t);let r=Ou({cwd:e,strip:1}),n=!1,i=setTimeout(()=>{n=!0,r.destroy(new _("IPC_BAD_REQUEST",`tar extract timeout (${jr}ms)`))},jr);try{await Qu(Yu.from(t),r)}catch(s){throw s instanceof _?s:n?new _("IPC_BAD_REQUEST",`tar extract timeout (${jr}ms)`):new _("IPC_BAD_REQUEST",`tar extract failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}}async function e_(t){let e=[],r=$r({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 (${jr}ms)`))},jr);try{await Qu(Yu.from(t),r)}catch(s){throw n?new _("IPC_BAD_REQUEST",`tar list timeout (${jr}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 t_=5e3;async function r_(t,e,r,n){return th(t,e,r,n,{count:0})}async function th(t,e,r,n,i){if(n<=0)return[];let s;try{s=await Ny(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let a of s){if($y.has(a.name)||a.isSymbolicLink())continue;if(i.count>=t_){o.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let c=nt(e,a.name),l=By(nt(r,a.name)),d=null;try{d=await ja(c)}catch{continue}if(d.isSymbolicLink())continue;i.count++;let p={name:a.name,path:rh(Za(t,c)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&n>1&&(p.children=await th(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 n_(t){return!t||t<=0?Uy:Math.min(t,zy)}function i_(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function rh(t){return t.split(Xu).join("/")}F();import{readFileSync as Zk}from"node:fs";import{dirname as Xk,join as Yk}from"node:path";import{fileURLToPath as eb}from"node:url";var Wr="0.1.90";var Ut=x("agent-health-reporter"),s_=1e4,Jn=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??s_}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()}),Ut.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Ut.info("heartbeat stopped"))}async tick(){if(this.inFlight){Ut.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Ut.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=o_(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:Wr,_meta:{cozeDeviceId:e}},i;try{i=await this.opts.core.sendRequest("_agent/health",n,5e3)}catch(o){Ut.warn("heartbeat batch send failed",{count:r.length,err:String(o)})}let s=i?.authFailures;if(s&&s.length>0&&(Ut.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){Ut.warn("onAuthFailures callback failed (ignored)",{err:String(o)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(r){Ut.warn("onTickEnd hook failed",{err:String(r)})}}};function o_(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Rt();import{chmod as L_,mkdir as Ms,rm as F_,stat as M_,writeFile as B_}from"node:fs/promises";import{homedir as U_}from"node:os";import{join as wh}from"node:path";Vt();import{spawnSync as p_}from"node:child_process";function Vn(t,e,r){return r===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:r}}function Zn(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function qr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function zt(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ee();var xs=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)}},M={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 nh(t){return"method"in t&&"id"in t&&t.id!==void 0}function ih(t){return"method"in t&&!("id"in t)}function Os(t){return!("method"in t)&&"id"in t}var a_={AGENT_NOT_FOUND:M.AGENT_NOT_FOUND,AGENT_BUSY:M.AGENT_BUSY,AGENT_DISCONNECTED:M.AGENT_DISCONNECTED,AGENT_TIMEOUT:M.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:M.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:M.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:M.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:M.INTERNAL_ERROR,BRIDGE_INTERNAL:M.INTERNAL_ERROR,IPC_AUTH_FAILED:M.INTERNAL_ERROR,IPC_BAD_REQUEST:M.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:M.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:M.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:M.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:M.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:M.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:M.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:M.FILE_TOO_LARGE,UNSUPPORTED_MIME:M.UNSUPPORTED_MIME,UPLOAD_FAILED:M.UPLOAD_FAILED,UPSTREAM_NOT_READY:M.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:M.AGENT_DEPENDENCY_INSTALL_FAILED};function c_(t){if(t!=null)return t instanceof Error?{name:t.name,message:Kn(t.message)}:typeof t=="string"?Kn(t):typeof t=="object"?d_(t):t}var l_=[[/\/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 Kn(t){let e=t;for(let[r,n]of l_)e=e.replace(r,n);return e}function d_(t){let e={};for(let[r,n]of Object.entries(t))typeof n=="string"?e[r]=Kn(n):e[r]=n;return e}function Xn(t){if(t instanceof _){let e=c_(t.cause),r={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(r.cause=e),{code:a_[t.code]??M.INTERNAL_ERROR,message:Kn(t.message),data:r}}return{code:M.INTERNAL_ERROR,message:Kn(t instanceof Error?t.message:String(t))}}function sh(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 ah(t){return`${JSON.stringify(t)}
|
|
85
|
-
`}var
|
|
86
|
-
`);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 lh={"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"},ub=Object.fromEntries(Object.entries(lh).map(([t,e])=>[e,t])),u_={"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:[]},Jr=class{seq=0;next(e,r){this.seq+=1;let n=lh[e]??h_(e),i=u_[n]??[],s=[n,String(this.seq)];if(i.length>0){let o=i.map(c=>ch(r?.[c]??"")),a=f_(o).join(":");a&&s.push(a)}else r&&Object.values(r).some(o=>o)&&s.push(Object.values(r).filter(Boolean).map(o=>ch(String(o))).join(":"));return s.join("_")}reset(){this.seq=0}};function h_(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function ch(t){return t.replace(/[:_\s]+/g,"-")}function f_(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Tt();Ei();Ee();F();var g_=vt("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),m_=200,w_=vt("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),y_=vt("COZE_BRIDGE_SESSION_PROMPT_FRAME_IDLE_MS",600*1e3),dh=500;function __(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=dh?t:`${e.slice(0,dh)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function uh(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let r=["/PID",String(t),"/T"];e==="SIGKILL"&&r.push("/F"),p_("taskkill",r,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var it=class{constructor(e){this.opts=e;this.log=x(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Ps({onError:r=>this.log.warn("decode line failed",{line:r.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new Jr;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=De(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>m_&&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()));uh(r.pid,"SIGTERM");let i=setTimeout(()=>{r.killed||uh(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=w_,n=y_){return this.call("session/prompt",e,r,n)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Zn("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(qr(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(zt(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=g_,i=0){if(!this.child||this.stopped)return Promise.reject(new _("AGENT_PROTOCOL_ERROR","downstream not started"));let s=this.idAllocator.next(e),o=Vn(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 h=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}:{}}),h?.();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=h,this.pending.set(s,m),h?.();try{this.writeFrame(o)}catch(f){m.timer&&clearTimeout(m.timer),m.frameIdleTimer&&clearTimeout(m.frameIdleTimer),this.pending.delete(s),p(f)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new _("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(ah(e),r=>{r&&this.log.warn("stdin write callback err",{err:String(r)})})}dispatch(e){if(Os(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(sh(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:__(e.result)}),r.resolve(e.result));return}if(ih(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(nh(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(zt(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(zt(e.id,Xn(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 E_(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 Cs=class extends it{framework="claude-code";constructor(e){let r=pn("claude-code",e.command),n=e.args??[],i={command:r,args:n,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(i)}sanitizeEnv(e){return E_(e)}};Vt();import{mkdtempSync as S_,rmSync as I_}from"node:fs";import{tmpdir as v_}from"node:os";import{join as T_}from"node:path";var Ds=class extends it{framework="codex";authMethodId;codexHomeDir;constructor(e){let r=pn("codex",e.command),n=e.args??[],i=e.extraArgs?[...n,...e.extraArgs]:n,s=e.isolateCodexHome?S_(T_(v_(),"coze-bridge-codex-home-")):void 0,o=s?{...e.env??{},CODEX_HOME:s}:e.env,a={command:r,args:i,cwd:e.cwd,agentId:e.agentId,...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{I_(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var R_=3e4,Vr=class extends it{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,agentId:e.agentId,...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}`}]},R_))}get acpSessionName(){return this.sessionName}};Ee();F();se();function Ya(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}Vt();var Zr=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 Ns=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 Zr,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)Yn(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 Yn(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}Tt();F();import{constants as hh,access as k_}from"node:fs/promises";import{delimiter as b_,join as A_}from"node:path";var $t=x("framework-detector"),fh={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},x_=[".exe",".cmd",".bat",".ps1"],Gt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??De,access:e.access??k_}}async detect(e){let r=fh[e],n=await this.which(r);if(!n)return $t.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(fh).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(b_).filter(Boolean),n=this.env.platform==="win32"?["",...x_]:[""];for(let i of r)for(let s of n){let o=A_(i,e+s);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let r=this.env.platform==="win32"?hh.F_OK:hh.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 $t.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(r.code!==0)return $t.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 $t.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 $t.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?($t.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}:($t.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:i.length}),null)}catch(i){return $t.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&&(P_(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)}})}},O_=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function P_(t){return t.replace(O_,"")}import{homedir as C_}from"node:os";import{join as D_}from"node:path";Tt();Ee();Pi();F();async function mh(){let t=D_(C_(),".openclaw/openclaw.json");return(await Tr(t))?.gateway?.auth?.token??""}var ph=x("openclaw.config"),N_=[0,5e3,5e3],gh="models.providers.",Ls="agents.defaults.models",Fs=class{command;env;retryDelaysMs;queue=new Zr;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??N_}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,ph.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=De(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){ph.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",`${gh}${e}`,JSON.stringify(r),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${gh}${e}`)}addModelToAllowlist(e,r){let n={[e]:r?{alias:r}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ls}[${e}]`,()=>this.runCli(["config","set",Ls,JSON.stringify(n),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ls}[${e}]`,`${Ls}.${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"),z_=(t,e,r,n,i,s,o,a,c)=>{switch(t){case"claude-code":{let l={...i?{...Hu(i),...qu(i,o,a)}:{},...c??{},IS_SANDBOX:"1"};return new Cs({cwd:r,env:l,agentId:n})}case"codex":{let d=[...i?[...ju(i),...Vu(i,o,a)]:[],"-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"'],p={...i?Wu(i):{},...c??{}},m=!!i;return new Ds({cwd:r,agentId:n,...d.length>0?{extraArgs:d}:{},...Object.keys(p).length>0?{env:p}:{},...m?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new Vr({command:e,cwd:r,agentId:n,...s?{sessionName:Ya(s)}:{}})}};function Qa(t){return t==="claude-code"||t==="codex"}function $_(t){let e=[],r=Object.keys(t).sort();for(let n of r){let i=t[n];i!==void 0&&(G_(i)||e.push(`${n}=${i}`))}return e.length===0?"":`${e.join(`
|
|
81
|
+
`},configPath(t){return oT(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await gg("schtasks",["/Create","/SC","ONLOGON","/TN",bo,"/TR",n,"/RU",t.userName,"/F"]),El.info("task scheduler entry created",{task:bo,logFile:t.logFile})},async uninstall(t){await gg("schtasks",["/Delete","/TN",bo,"/F"]).catch(e=>El.warn("schtasks /Delete failed (ignored)",{err:String(e)})),El.info("task scheduler entry removed",{task:bo})}}});var wg={};Ri(wg,{buildContext:()=>dT,getSupervisor:()=>lT,launchdSupervisor:()=>yl,systemdSupervisor:()=>_l,taskSchedulerSupervisor:()=>Sl});import{homedir as aT,userInfo as cT}from"node:os";function lT(t=process.platform){switch(t){case"darwin":return yl;case"linux":return _l;case"win32":return Sl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function dT(){let t=F();return{nodeBin:process.execPath,entry:fl(t),logFile:t.logFile,homeDir:aT(),userName:cT().username}}var yg=we(()=>{"use strict";se();mo();hg();pg();mg()});L();Xt();var Ml=A("acp-installer-warmup"),om=["claude-code","codex"];async function Bl(t={}){let e=t.ensure??Kt,r=(await Promise.allSettled(om.map(async i=>{let s=await e(i);Ml.info("acp wrapper warmup ok",{framework:i,path:s})}))).filter(i=>i.status==="rejected");r.length>0&&Ml.warn("acp wrapper warmup partial failure (\u5C06\u5728\u4E0B\u6B21 createAgent \u65F6\u91CD\u8BD5\u5E76\u629B\u9519\u7ED9\u7528\u6237)",{failedCount:r.length,reasons:r.map(i=>i.reason instanceof Error?i.reason.message:String(i.reason))})}Rt();L();import{readdir as ym}from"node:fs/promises";import{mkdir as Wl,writeFile as ql}from"node:fs/promises";import{join as Mo}from"node:path";var wm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Pn(t,e,n){await Wl(t,{recursive:!0});let r=wm[e],i=Mo(t,r);return await ql(i,n??"","utf8"),i}async function Jl(t){let e=Mo(t,".claude");await Wl(e,{recursive:!0});let n=Mo(e,"settings.local.json"),r=JSON.stringify({permissions:{defaultMode:"acceptEdits"}},null,2);return await ql(n,r,"utf8"),n}var Ae=A("agent-detail-sync"),_m=6e4,Em=5*6e4,zi=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,r;try{r=await ym(n)}catch(i){Ae.info("agents dir not found, skip detail sync",{root:n,err:String(i)});return}Ae.info("starting detail sync",{reason:e,count:r.length}),await Promise.allSettled(r.map(async i=>{let s=await fe(i,this.opts.paths).catch(()=>null);if(s){if(s.disconnectedAt){Ae.debug("detail sync: skip disconnected agent",{agentId:i});return}try{await this.syncOne(i,s)}catch(o){Ae.warn("detail sync failed for agent, skipping",{agentId:i,err:String(o)})}}})),Ae.info("detail sync done",{reason:e})}async retryPending(){if(this.retryQueue.size===0)return;let e=Date.now(),n=[];for(let[r,i]of this.retryQueue)e>=i.dueAt&&n.push(r);if(n.length!==0){Ae.info("retrying pending detail syncs",{count:n.length});for(let r of n)try{await this.syncOne(r)}catch(i){Ae.debug("detail sync retry still failing, will try again",{agentId:r,err:String(i)})}}}async syncOne(e,n){let r=n??await fe(e,this.opts.paths);if(!r){Ae.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){Ae.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,Em):_m;this.retryQueue.set(e,{dueAt:Date.now()+l,currentDelay:l});return}if(i.agentId&&i.agentId!==e){Ae.warn("detail response agentId mismatch, ignoring",{agentId:e,responseAgentId:i.agentId});return}let s=!1,o=!1;if(i.agentName&&i.agentName!==r.agentName&&(r.agentName=i.agentName,s=!0),i.description!==void 0&&i.description!==r.description&&(r.description=i.description,s=!0),i.cozeIdentity&&i.cozeIdentity!==r.cozeIdentity&&(r.cozeIdentity=i.cozeIdentity,s=!0,o=!0),i.deployType&&Ae.info("detail.deployType",{agentId:e,deployType:i.deployType}),!s){Ae.debug("detail sync: no diff",{agentId:e});return}await ke(r,this.opts.paths),Ae.info("detail sync: config updated",{agentId:e,identityChanged:o,agentName:r.agentName}),o&&(await Pn(r.workspace,r.framework,r.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var df=dt(kd(),1);import{lstat as Ya,mkdir as Qa,readFile as of,readdir as Jy,rm as Vy,stat as Zy,writeFile as ec}from"node:fs/promises";import{dirname as Ky,join as st,normalize as Xy,relative as rc,resolve as tc,sep as af}from"node:path";import{Readable as cf}from"node:stream";import{pipeline as lf}from"node:stream/promises";import Gm from"events";import be from"fs";import{EventEmitter as Fa}from"node:events";import au from"node:stream";import{StringDecoder as Hm}from"node:string_decoder";import du from"node:path";import Hn from"node:fs";import{dirname as nw,parse as rw}from"path";import{EventEmitter as uw}from"events";import wa from"assert";import{Buffer as ln}from"buffer";import*as Pd from"zlib";import fw from"zlib";import{posix as Fn}from"node:path";import{basename as Uw}from"node:path";import ys from"fs";import nt from"fs";import Bd from"path";import{win32 as Kw}from"node:path";import Wd from"path";import Ru from"node:fs";import hy from"node:assert";import{randomBytes as ku}from"node:crypto";import M from"node:fs";import ne from"node:path";import bu from"fs";import bs from"node:fs";import $r from"node:path";import Pe from"node:fs";import Ey from"node:fs/promises";import Ss from"node:path";import{join as Bu}from"node:path";import Oe from"node:fs";import $u from"node:path";var zm=Object.defineProperty,$m=(t,e)=>{for(var n in e)zm(t,n,{get:e[n],enumerable:!0})},bd=typeof process=="object"&&process?process:{stdout:null,stderr:null},jm=t=>!!t&&typeof t=="object"&&(t instanceof fn||t instanceof au||Wm(t)||qm(t)),Wm=t=>!!t&&typeof t=="object"&&t instanceof Fa&&typeof t.pipe=="function"&&t.pipe!==au.Writable.prototype.pipe,qm=t=>!!t&&typeof t=="object"&&t instanceof Fa&&typeof t.write=="function"&&typeof t.end=="function",ht=Symbol("EOF"),pt=Symbol("maybeEmitEnd"),bt=Symbol("emittedEnd"),Wi=Symbol("emittingEnd"),Tr=Symbol("emittedError"),qi=Symbol("closed"),Ad=Symbol("read"),Ji=Symbol("flush"),xd=Symbol("flushChunk"),Ge=Symbol("encoding"),Ln=Symbol("decoder"),oe=Symbol("flowing"),Rr=Symbol("paused"),zn=Symbol("resume"),ae=Symbol("buffer"),ve=Symbol("pipes"),ce=Symbol("bufferLength"),Ho=Symbol("bufferPush"),Vi=Symbol("bufferShift"),_e=Symbol("objectMode"),Y=Symbol("destroyed"),jo=Symbol("error"),Wo=Symbol("emitData"),Od=Symbol("emitEnd"),qo=Symbol("emitEnd2"),Ye=Symbol("async"),Jo=Symbol("abort"),Zi=Symbol("aborted"),kr=Symbol("signal"),Qt=Symbol("dataListeners"),xe=Symbol("discarded"),br=t=>Promise.resolve().then(t),Jm=t=>t(),Vm=t=>t==="end"||t==="finish"||t==="prefinish",Zm=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,Km=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),cu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[zn](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},Xm=class extends cu{unpipe(){this.src.removeListener("error",this.proxyErrors),super.unpipe()}constructor(t,e,n){super(t,e,n),this.proxyErrors=r=>this.dest.emit("error",r),t.on("error",this.proxyErrors)}},Ym=t=>!!t.objectMode,Qm=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",fn=class extends Fa{[oe]=!1;[Rr]=!1;[ve]=[];[ae]=[];[_e];[Ge];[Ye];[Ln];[ht]=!1;[bt]=!1;[Wi]=!1;[qi]=!1;[Tr]=null;[ce]=0;[Y]=!1;[kr];[Zi]=!1;[Qt]=0;[xe]=!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");Ym(e)?(this[_e]=!0,this[Ge]=null):Qm(e)?(this[Ge]=e.encoding,this[_e]=!1):(this[_e]=!1,this[Ge]=null),this[Ye]=!!e.async,this[Ln]=this[Ge]?new Hm(this[Ge]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[ae]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[ve]});let{signal:n}=e;n&&(this[kr]=n,n.aborted?this[Jo]():n.addEventListener("abort",()=>this[Jo]()))}get bufferLength(){return this[ce]}get encoding(){return this[Ge]}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[_e]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[Ye]}set async(t){this[Ye]=this[Ye]||!!t}[Jo](){this[Zi]=!0,this.emit("abort",this[kr]?.reason),this.destroy(this[kr]?.reason)}get aborted(){return this[Zi]}set aborted(t){}write(t,e,n){if(this[Zi])return!1;if(this[ht])throw new Error("write after end");if(this[Y])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let r=this[Ye]?br:Jm;if(!this[_e]&&!Buffer.isBuffer(t)){if(Km(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(Zm(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[_e]?(this[oe]&&this[ce]!==0&&this[Ji](!0),this[oe]?this.emit("data",t):this[Ho](t),this[ce]!==0&&this.emit("readable"),n&&r(n),this[oe]):t.length?(typeof t=="string"&&!(e===this[Ge]&&!this[Ln]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[Ge]&&(t=this[Ln].write(t)),this[oe]&&this[ce]!==0&&this[Ji](!0),this[oe]?this.emit("data",t):this[Ho](t),this[ce]!==0&&this.emit("readable"),n&&r(n),this[oe]):(this[ce]!==0&&this.emit("readable"),n&&r(n),this[oe])}read(t){if(this[Y])return null;if(this[xe]=!1,this[ce]===0||t===0||t&&t>this[ce])return this[pt](),null;this[_e]&&(t=null),this[ae].length>1&&!this[_e]&&(this[ae]=[this[Ge]?this[ae].join(""):Buffer.concat(this[ae],this[ce])]);let e=this[Ad](t||null,this[ae][0]);return this[pt](),e}[Ad](t,e){if(this[_e])this[Vi]();else{let n=e;t===n.length||t===null?this[Vi]():typeof n=="string"?(this[ae][0]=n.slice(t),e=n.slice(0,t),this[ce]-=t):(this[ae][0]=n.subarray(t),e=n.subarray(0,t),this[ce]-=t)}return this.emit("data",e),!this[ae].length&&!this[ht]&&this.emit("drain"),e}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e="utf8"),t!==void 0&&this.write(t,e),n&&this.once("end",n),this[ht]=!0,this.writable=!1,(this[oe]||!this[Rr])&&this[pt](),this}[zn](){this[Y]||(!this[Qt]&&!this[ve].length&&(this[xe]=!0),this[Rr]=!1,this[oe]=!0,this.emit("resume"),this[ae].length?this[Ji]():this[ht]?this[pt]():this.emit("drain"))}resume(){return this[zn]()}pause(){this[oe]=!1,this[Rr]=!0,this[xe]=!1}get destroyed(){return this[Y]}get flowing(){return this[oe]}get paused(){return this[Rr]}[Ho](t){this[_e]?this[ce]+=1:this[ce]+=t.length,this[ae].push(t)}[Vi](){return this[_e]?this[ce]-=1:this[ce]-=this[ae][0].length,this[ae].shift()}[Ji](t=!1){do;while(this[xd](this[Vi]())&&this[ae].length);!t&&!this[ae].length&&!this[ht]&&this.emit("drain")}[xd](t){return this.emit("data",t),this[oe]}pipe(t,e){if(this[Y])return t;this[xe]=!1;let n=this[bt];return e=e||{},t===bd.stdout||t===bd.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[ve].push(e.proxyErrors?new Xm(this,t,e):new cu(this,t,e)),this[Ye]?br(()=>this[zn]()):this[zn]()),t}unpipe(t){let e=this[ve].find(n=>n.dest===t);e&&(this[ve].length===1?(this[oe]&&this[Qt]===0&&(this[oe]=!1),this[ve]=[]):this[ve].splice(this[ve].indexOf(e),1),e.unpipe())}addListener(t,e){return this.on(t,e)}on(t,e){let n=super.on(t,e);if(t==="data")this[xe]=!1,this[Qt]++,!this[ve].length&&!this[oe]&&this[zn]();else if(t==="readable"&&this[ce]!==0)super.emit("readable");else if(Vm(t)&&this[bt])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Tr]){let r=e;this[Ye]?br(()=>r.call(this,this[Tr])):r.call(this,this[Tr])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[Qt]=this.listeners("data").length,this[Qt]===0&&!this[xe]&&!this[ve].length&&(this[oe]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[Qt]=0,!this[xe]&&!this[ve].length&&(this[oe]=!1)),e}get emittedEnd(){return this[bt]}[pt](){!this[Wi]&&!this[bt]&&!this[Y]&&this[ae].length===0&&this[ht]&&(this[Wi]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[qi]&&this.emit("close"),this[Wi]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Y&&this[Y])return!1;if(t==="data")return!this[_e]&&!n?!1:this[Ye]?(br(()=>this[Wo](n)),!0):this[Wo](n);if(t==="end")return this[Od]();if(t==="close"){if(this[qi]=!0,!this[bt]&&!this[Y])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Tr]=n,super.emit(jo,n);let i=!this[kr]||this.listeners("error").length?super.emit("error",n):!1;return this[pt](),i}else if(t==="resume"){let i=super.emit("resume");return this[pt](),i}else if(t==="finish"||t==="prefinish"){let i=super.emit(t);return this.removeAllListeners(t),i}let r=super.emit(t,...e);return this[pt](),r}[Wo](t){for(let n of this[ve])n.dest.write(t)===!1&&this.pause();let e=this[xe]?!1:super.emit("data",t);return this[pt](),e}[Od](){return this[bt]?!1:(this[bt]=!0,this.readable=!1,this[Ye]?(br(()=>this[qo]()),!0):this[qo]())}[qo](){if(this[Ln]){let e=this[Ln].end();if(e){for(let n of this[ve])n.dest.write(e);this[xe]||super.emit("data",e)}}for(let e of this[ve])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[_e]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[_e]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[_e])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[Ge]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Y,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[xe]=!1;let t=!1,e=async()=>(this.pause(),t=!0,{value:void 0,done:!0});return{next:()=>{if(t)return e();let n=this.read();if(n!==null)return Promise.resolve({done:!1,value:n});if(this[ht])return e();let r,i,s=l=>{this.off("data",o),this.off("end",a),this.off(Y,c),e(),i(l)},o=l=>{this.off("error",s),this.off("end",a),this.off(Y,c),this.pause(),r({value:l,done:!!this[ht]})},a=()=>{this.off("error",s),this.off("data",o),this.off(Y,c),e(),r({done:!0,value:void 0})},c=()=>s(new Error("stream destroyed"));return new Promise((l,d)=>{i=d,r=l,this.once(Y,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[xe]=!1;let t=!1,e=()=>(this.pause(),this.off(jo,e),this.off(Y,e),this.off("end",e),t=!0,{done:!0,value:void 0}),n=()=>{if(t)return e();let r=this.read();return r===null?e():{done:!1,value:r}};return this.once("end",e),this.once(jo,e),this.once(Y,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Y])return t?this.emit("error",t):this.emit(Y),this;this[Y]=!0,this[xe]=!0,this[ae].length=0,this[ce]=0;let e=this;return typeof e.close=="function"&&!this[qi]&&e.close(),t?this.emit("error",t):this.emit(Y),this}static get isStream(){return jm}},ew=be.writev,Mt=Symbol("_autoClose"),qe=Symbol("_close"),Ar=Symbol("_ended"),$=Symbol("_fd"),Vo=Symbol("_finished"),yt=Symbol("_flags"),Zo=Symbol("_flush"),ga=Symbol("_handleChunk"),ma=Symbol("_makeBuf"),Ur=Symbol("_mode"),Ki=Symbol("_needDrain"),Wn=Symbol("_onerror"),qn=Symbol("_onopen"),Ko=Symbol("_onread"),$n=Symbol("_onwrite"),Bt=Symbol("_open"),We=Symbol("_path"),Ct=Symbol("_pos"),Qe=Symbol("_queue"),Gn=Symbol("_read"),Xo=Symbol("_readSize"),wt=Symbol("_reading"),xr=Symbol("_remain"),Yo=Symbol("_size"),os=Symbol("_write"),en=Symbol("_writing"),as=Symbol("_defaultFlag"),cn=Symbol("_errored"),Ma=class extends fn{[cn]=!1;[$];[We];[Xo];[wt]=!1;[Yo];[xr];[Mt];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[cn]=!1,this[$]=typeof e.fd=="number"?e.fd:void 0,this[We]=t,this[Xo]=e.readSize||16*1024*1024,this[wt]=!1,this[Yo]=typeof e.size=="number"?e.size:1/0,this[xr]=this[Yo],this[Mt]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[$]=="number"?this[Gn]():this[Bt]()}get fd(){return this[$]}get path(){return this[We]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[Bt](){be.open(this[We],"r",(t,e)=>this[qn](t,e))}[qn](t,e){t?this[Wn](t):(this[$]=e,this.emit("open",e),this[Gn]())}[ma](){return Buffer.allocUnsafe(Math.min(this[Xo],this[xr]))}[Gn](){if(!this[wt]){this[wt]=!0;let t=this[ma]();if(t.length===0)return process.nextTick(()=>this[Ko](null,0,t));be.read(this[$],t,0,t.length,null,(e,n,r)=>this[Ko](e,n,r))}}[Ko](t,e,n){this[wt]=!1,t?this[Wn](t):this[ga](e,n)&&this[Gn]()}[qe](){if(this[Mt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,be.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Wn](t){this[wt]=!0,this[qe](),this.emit("error",t)}[ga](t,e){let n=!1;return this[xr]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[xr]<=0)&&(n=!1,this[qe](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[$]=="number"&&this[Gn](),!1;case"error":return this[cn]?!1:(this[cn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},tw=class extends Ma{[Bt](){let t=!0;try{this[qn](null,be.openSync(this[We],"r")),t=!1}finally{t&&this[qe]()}}[Gn](){let t=!0;try{if(!this[wt]){this[wt]=!0;do{let e=this[ma](),n=e.length===0?0:be.readSync(this[$],e,0,e.length,null);if(!this[ga](n,e))break}while(!0);this[wt]=!1}t=!1}finally{t&&this[qe]()}}[qe](){if(this[Mt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,be.closeSync(t),this.emit("close")}}},Is=class extends Gm{readable=!1;writable=!0;[cn]=!1;[en]=!1;[Ar]=!1;[Qe]=[];[Ki]=!1;[We];[Ur];[Mt];[$];[as];[yt];[Vo]=!1;[Ct];constructor(t,e){e=e||{},super(e),this[We]=t,this[$]=typeof e.fd=="number"?e.fd:void 0,this[Ur]=e.mode===void 0?438:e.mode,this[Ct]=typeof e.start=="number"?e.start:void 0,this[Mt]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Ct]!==void 0?"r+":"w";this[as]=e.flags===void 0,this[yt]=e.flags===void 0?n:e.flags,this[$]===void 0&&this[Bt]()}emit(t,...e){if(t==="error"){if(this[cn])return!1;this[cn]=!0}return super.emit(t,...e)}get fd(){return this[$]}get path(){return this[We]}[Wn](t){this[qe](),this[en]=!0,this.emit("error",t)}[Bt](){be.open(this[We],this[yt],this[Ur],(t,e)=>this[qn](t,e))}[qn](t,e){this[as]&&this[yt]==="r+"&&t&&t.code==="ENOENT"?(this[yt]="w",this[Bt]()):t?this[Wn](t):(this[$]=e,this.emit("open",e),this[en]||this[Zo]())}end(t,e){return t&&this.write(t,e),this[Ar]=!0,!this[en]&&!this[Qe].length&&typeof this[$]=="number"&&this[$n](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Ar]?(this.emit("error",new Error("write() after end()")),!1):this[$]===void 0||this[en]||this[Qe].length?(this[Qe].push(t),this[Ki]=!0,!1):(this[en]=!0,this[os](t),!0)}[os](t){be.write(this[$],t,0,t.length,this[Ct],(e,n)=>this[$n](e,n))}[$n](t,e){t?this[Wn](t):(this[Ct]!==void 0&&typeof e=="number"&&(this[Ct]+=e),this[Qe].length?this[Zo]():(this[en]=!1,this[Ar]&&!this[Vo]?(this[Vo]=!0,this[qe](),this.emit("finish")):this[Ki]&&(this[Ki]=!1,this.emit("drain"))))}[Zo](){if(this[Qe].length===0)this[Ar]&&this[$n](null,0);else if(this[Qe].length===1)this[os](this[Qe].pop());else{let t=this[Qe];this[Qe]=[],ew(this[$],t,this[Ct],(e,n)=>this[$n](e,n))}}[qe](){if(this[Mt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,be.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},lu=class extends Is{[Bt](){let t;if(this[as]&&this[yt]==="r+")try{t=be.openSync(this[We],this[yt],this[Ur])}catch(e){if(e?.code==="ENOENT")return this[yt]="w",this[Bt]();throw e}else t=be.openSync(this[We],this[yt],this[Ur]);this[qn](null,t)}[qe](){if(this[Mt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,be.closeSync(t),this.emit("close")}}[os](t){let e=!0;try{this[$n](null,be.writeSync(this[$],t,0,t.length,this[Ct])),e=!1}finally{if(e)try{this[qe]()}catch{}}}},iw=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"]]),sw=t=>!!t.sync&&!!t.file,ow=t=>!t.sync&&!!t.file,aw=t=>!!t.sync&&!t.file,cw=t=>!t.sync&&!t.file,lw=t=>!!t.file,dw=t=>iw.get(t)||t,Ba=(t={})=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){let i=dw(n);e[i]=r}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},Vr=(t,e,n,r,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=Ba(s);if(i?.(c,o),sw(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return t(c,o)}else if(ow(c)){let l=e(c,o);return a?l.then(()=>a(),a):l}else if(aw(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return n(c,o)}else if(cw(c)){if(typeof a=="function")throw new TypeError("callback only supported with file option");return r(c,o)}throw new Error("impossible options??")},{syncFile:t,asyncFile:e,syncNoFile:n,asyncNoFile:r,validate:i}),hw=fw.constants||{ZLIB_VERNUM:4736},it=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},hw)),pw=ln.concat,Cd=Object.getOwnPropertyDescriptor(ln,"concat"),gw=t=>t,Qo=Cd?.writable===!0||Cd?.set!==void 0?t=>{ln.concat=t?gw:pw}:t=>{},dn=Symbol("_superWrite"),Xi=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"}},ea=Symbol("flushFlag"),Ua=class extends fn{#e=!1;#n=!1;#r;#s;#i;#t;#o;get sawError(){return this.#e}get handle(){return this.#t}get flushFlag(){return this.#r}constructor(t,e){if(!t||typeof t!="object")throw new TypeError("invalid options for ZlibBase constructor");if(super(t),this.#r=t.flush??0,this.#s=t.finishFlush??0,this.#i=t.fullFlushFlag??0,typeof Pd[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new Pd[e](t)}catch(n){throw new Xi(n,this.constructor)}this.#o=n=>{this.#e||(this.#e=!0,this.close(),this.emit("error",n))},this.#t?.on("error",n=>this.#o(new Xi(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return wa(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(ln.alloc(0),{[ea]:t})))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&(e?this.write(t,e):this.write(t)),this.flush(this.#s),this.#n=!0,super.end(n)}get ended(){return this.#n}[dn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=ln.from(t,e)),this.#e)return;wa(this.#t,"zlib binding closed");let r=this.#t._handle,i=r.close;r.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},Qo(!0);let o;try{let c=typeof t[ea]=="number"?t[ea]:this.#r;o=this.#t._processChunk(t,c),Qo(!1)}catch(c){Qo(!1),this.#o(new Xi(c,this.write))}finally{this.#t&&(this.#t._handle=r,r.close=i,this.#t.close=s,this.#t.removeAllListeners("error"))}this.#t&&this.#t.on("error",c=>this.#o(new Xi(c,this.write)));let a;if(o)if(Array.isArray(o)&&o.length>0){let c=o[0];a=this[dn](ln.from(c));for(let l=1;l<o.length;l++)a=this[dn](o[l])}else a=this[dn](ln.from(o));return n&&n(),a}},uu=class extends Ua{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||it.Z_NO_FLUSH,t.finishFlush=t.finishFlush||it.Z_FINISH,t.fullFlushFlag=it.Z_FULL_FLUSH,super(t,e),this.#e=t.level,this.#n=t.strategy}params(t,e){if(!this.sawError){if(!this.handle)throw new Error("cannot switch params when binding is closed");if(!this.handle.params)throw new Error("not supported in this implementation");if(this.#e!==t||this.#n!==e){this.flush(it.Z_SYNC_FLUSH),wa(this.handle,"zlib binding closed");let n=this.handle.flush;this.handle.flush=(r,i)=>{typeof r=="function"&&(i=r,r=this.flushFlag),this.flush(r),i?.()};try{this.handle.params(t,e)}finally{this.handle.flush=n}this.handle&&(this.#e=t,this.#n=e)}}}},mw=class extends uu{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[dn](t){return this.#e?(this.#e=!1,t[9]=255,super[dn](t)):super[dn](t)}},ww=class extends uu{constructor(t){super(t,"Unzip")}},fu=class extends Ua{constructor(t,e){t=t||{},t.flush=t.flush||it.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||it.BROTLI_OPERATION_FINISH,t.fullFlushFlag=it.BROTLI_OPERATION_FLUSH,super(t,e)}},yw=class extends fu{constructor(t){super(t,"BrotliCompress")}},_w=class extends fu{constructor(t){super(t,"BrotliDecompress")}},hu=class extends Ua{constructor(t,e){t=t||{},t.flush=t.flush||it.ZSTD_e_continue,t.finishFlush=t.finishFlush||it.ZSTD_e_end,t.fullFlushFlag=it.ZSTD_e_flush,super(t,e)}},Ew=class extends hu{constructor(t){super(t,"ZstdCompress")}},Sw=class extends hu{constructor(t){super(t,"ZstdDecompress")}},Iw=(t,e)=>{if(Number.isSafeInteger(t))t<0?Tw(t,e):vw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},vw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},Tw=(t,e)=>{e[0]=255;var n=!1;t=t*-1;for(var r=e.length;r>1;r--){var i=t&255;t=Math.floor(t/256),n?e[r-1]=pu(i):i===0?e[r-1]=0:(n=!0,e[r-1]=gu(i))}},Rw=t=>{let e=t[0],n=e===128?bw(t.subarray(1,t.length)):e===255?kw(t):null;if(n===null)throw Error("invalid base256 encoding");if(!Number.isSafeInteger(n))throw Error("parsed number outside of javascript safe integer range");return n},kw=t=>{for(var e=t.length,n=0,r=!1,i=e-1;i>-1;i--){var s=Number(t[i]),o;r?o=pu(s):s===0?o=s:(r=!0,o=gu(s)),o!==0&&(n-=o*Math.pow(256,e-i-1))}return n},bw=t=>{for(var e=t.length,n=0,r=e-1;r>-1;r--){var i=Number(t[r]);i!==0&&(n+=i*Math.pow(256,e-r-1))}return n},pu=t=>(255^t)&255,gu=t=>(255^t)+1&255,Aw={};$m(Aw,{code:()=>za,isCode:()=>cs,isName:()=>xw,name:()=>vs});var cs=t=>vs.has(t),xw=t=>za.has(t),vs=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"]]),za=new Map(Array.from(vs).map(t=>[t[1],t[0]])),un=class{cksumValid=!1;needPax=!1;nullBlock=!1;block;path;mode;uid;gid;size;cksum;#e="Unsupported";linkpath;uname;gname;devmaj=0;devmin=0;atime;ctime;mtime;charset;comment;constructor(t,e=0,n,r){Buffer.isBuffer(t)?this.decode(t,e||0,n,r):t&&this.#n(t)}decode(t,e,n,r){if(e||(e=0),!t||!(t.length>=e+512))throw new Error("need 512 bytes for header");this.path=n?.path??tn(t,e,100),this.mode=n?.mode??r?.mode??Dt(t,e+100,8),this.uid=n?.uid??r?.uid??Dt(t,e+108,8),this.gid=n?.gid??r?.gid??Dt(t,e+116,8),this.size=n?.size??r?.size??Dt(t,e+124,12),this.mtime=n?.mtime??r?.mtime??ta(t,e+136,12),this.cksum=Dt(t,e+148,12),r&&this.#n(r,!0),n&&this.#n(n);let i=tn(t,e+156,1);if(cs(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=tn(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=n?.uname??r?.uname??tn(t,e+265,32),this.gname=n?.gname??r?.gname??tn(t,e+297,32),this.devmaj=n?.devmaj??r?.devmaj??Dt(t,e+329,8)??0,this.devmin=n?.devmin??r?.devmin??Dt(t,e+337,8)??0,t[e+475]!==0){let o=tn(t,e+345,155);this.path=o+"/"+this.path}else{let o=tn(t,e+345,130);o&&(this.path=o+"/"+this.path),this.atime=n?.atime??r?.atime??ta(t,e+476,12),this.ctime=n?.ctime??r?.ctime??ta(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)}#n(t,e=!1){Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,r])=>!(r==null||n==="path"&&e||n==="linkpath"&&e||n==="global"))))}encode(t,e=0){if(t||(t=this.block=Buffer.alloc(512)),this.#e==="Unsupported"&&(this.#e="0"),!(t.length>=e+512))throw new Error("need 512 bytes for header");let n=this.ctime||this.atime?130:155,r=Ow(this.path||"",n),i=r[0],s=r[1];this.needPax=!!r[2],this.needPax=nn(t,e,100,i)||this.needPax,this.needPax=Nt(t,e+100,8,this.mode)||this.needPax,this.needPax=Nt(t,e+108,8,this.uid)||this.needPax,this.needPax=Nt(t,e+116,8,this.gid)||this.needPax,this.needPax=Nt(t,e+124,12,this.size)||this.needPax,this.needPax=na(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=nn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=nn(t,e+265,32,this.uname)||this.needPax,this.needPax=nn(t,e+297,32,this.gname)||this.needPax,this.needPax=Nt(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Nt(t,e+337,8,this.devmin)||this.needPax,this.needPax=nn(t,e+345,n,s)||this.needPax,t[e+475]!==0?this.needPax=nn(t,e+345,155,s)||this.needPax:(this.needPax=nn(t,e+345,130,s)||this.needPax,this.needPax=na(t,e+476,12,this.atime)||this.needPax,this.needPax=na(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,Nt(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:vs.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(za.get(t));if(cs(e)||e==="Unsupported")this.#e=e;else if(cs(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Ow=(t,e)=>{let n=t,r="",i,s=Fn.parse(t).root||".";if(Buffer.byteLength(n)<100)i=[n,r,!1];else{r=Fn.dirname(n),n=Fn.basename(n);do Buffer.byteLength(n)<=100&&Buffer.byteLength(r)<=e?i=[n,r,!1]:Buffer.byteLength(n)>100&&Buffer.byteLength(r)<=e?i=[n.slice(0,99),r,!0]:(n=Fn.join(Fn.basename(r),n),r=Fn.dirname(r));while(r!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},tn=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),ta=(t,e,n)=>Pw(Dt(t,e,n)),Pw=t=>t===void 0?void 0:new Date(t*1e3),Dt=(t,e,n)=>Number(t[e])&128?Rw(t.subarray(e,e+n)):Dw(t,e,n),Cw=t=>isNaN(t)?void 0:t,Dw=(t,e,n)=>Cw(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Nw={12:8589934591,8:2097151},Nt=(t,e,n,r)=>r===void 0?!1:r>Nw[n]||r<0?(Iw(r,t.subarray(e,e+n)),!0):(Lw(t,e,n,r),!1),Lw=(t,e,n,r)=>t.write(Fw(r,n),e,n,"ascii"),Fw=(t,e)=>Mw(Math.floor(t).toString(8),e),Mw=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",na=(t,e,n,r)=>r===void 0?!1:Nt(t,e,n,r.getTime()/1e3),Bw=new Array(156).join("\0"),nn=(t,e,n,r)=>r===void 0?!1:(t.write(r+Bw,e,n,"utf8"),r.length!==Buffer.byteLength(r)||r.length>n),ws=class mu{atime;mtime;ctime;charset;comment;gid;uid;gname;uname;linkpath;dev;ino;nlink;path;size;mode;global;constructor(e,n=!1){this.atime=e.atime,this.charset=e.charset,this.comment=e.comment,this.ctime=e.ctime,this.dev=e.dev,this.gid=e.gid,this.global=n,this.gname=e.gname,this.ino=e.ino,this.linkpath=e.linkpath,this.mtime=e.mtime,this.nlink=e.nlink,this.path=e.path,this.size=e.size,this.uid=e.uid,this.uname=e.uname}encode(){let e=this.encodeBody();if(e==="")return Buffer.allocUnsafe(0);let n=Buffer.byteLength(e),r=512*Math.ceil(1+n/512),i=Buffer.allocUnsafe(r);for(let s=0;s<512;s++)i[s]=0;new un({path:("PaxHeader/"+Uw(this.path??"")).slice(0,99),mode:this.mode||420,uid:this.uid,gid:this.gid,size:n,mtime:this.mtime,type:this.global?"GlobalExtendedHeader":"ExtendedHeader",linkpath:"",uname:this.uname||"",gname:this.gname||"",devmaj:0,devmin:0,atime:this.atime,ctime:this.ctime}).encode(i),i.write(e,512,n,"utf8");for(let s=n+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 n=this[e],r=n instanceof Date?n.getTime()/1e3:n,i=" "+(e==="dev"||e==="ino"||e==="nlink"?"SCHILY.":"")+e+"="+r+`
|
|
82
|
+
`,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,n,r=!1){return new mu(zw($w(e),n),r)}},zw=(t,e)=>e?Object.assign({},e,t):t,$w=t=>t.replace(/\n$/,"").split(`
|
|
83
|
+
`).reduce(Gw,Object.create(null)),Gw=(t,e)=>{let n=parseInt(e,10);if(n!==Buffer.byteLength(e)+1)return t;e=e.slice((n+" ").length);let r=e.split("="),i=r.shift();if(!i)return t;let s=i.replace(/^SCHILY\.(dev|ino|nlink)/,"$1"),o=r.join("=");return t[s]=/^([A-Z]+\.)?([mac]|birth|creation)time$/.test(s)?new Date(Number(o)*1e3):/^[0-9]+$/.test(o)?+o:o,t},Hw=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,N=Hw!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),wu=class extends fn{extended;globalExtended;header;startBlockSize;blockRemain;remain;type;meta=!1;ignore=!1;path;mode;uid;gid;uname;gname;size=0;mtime;atime;ctime;linkpath;dev;ino;nlink;invalid=!1;absolute;unsupported=!1;constructor(t,e,n){switch(super({}),this.pause(),this.extended=e,this.globalExtended=n,this.header=t,this.remain=t.size??0,this.startBlockSize=512*Math.ceil(this.remain/512),this.blockRemain=this.startBlockSize,this.type=t.type,this.type){case"File":case"OldFile":case"Link":case"SymbolicLink":case"CharacterDevice":case"BlockDevice":case"Directory":case"FIFO":case"ContiguousFile":case"GNUDumpDir":break;case"NextFileHasLongLinkpath":case"NextFileHasLongPath":case"OldGnuLongPath":case"GlobalExtendedHeader":case"ExtendedHeader":case"OldExtendedHeader":this.meta=!0;break;default:this.ignore=!0}if(!t.path)throw new Error("no path provided for tar.ReadEntry");this.path=N(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?N(t.linkpath):void 0,this.uname=t.uname,this.gname=t.gname,e&&this.#e(e),n&&this.#e(n,!0)}write(t){let e=t.length;if(e>this.blockRemain)throw new Error("writing more to entry than is appropriate");let n=this.remain,r=this.blockRemain;return this.remain=Math.max(0,n-e),this.blockRemain=Math.max(0,r-e),this.ignore?!0:n>=e?super.write(t):super.write(t.subarray(0,n))}#e(t,e=!1){t.path&&(t.path=N(t.path)),t.linkpath&&(t.linkpath=N(t.linkpath)),Object.assign(this,Object.fromEntries(Object.entries(t).filter(([n,r])=>!(r==null||n==="path"&&e))))}},Ts=(t,e,n,r={})=>{t.file&&(r.file=t.file),t.cwd&&(r.cwd=t.cwd),r.code=n instanceof Error&&n.code||e,r.tarCode=e,!t.strict&&r.recoverable!==!1?(n instanceof Error&&(r=Object.assign(n,r),n=n.message),t.emit("warn",e,n,r)):n instanceof Error?t.emit("error",Object.assign(n,r)):t.emit("error",Object.assign(new Error(`${e}: ${n}`),r))},jw=1024*1024,ya=Buffer.from([31,139]),_a=Buffer.from([40,181,47,253]),Ww=Math.max(ya.length,_a.length),Fe=Symbol("state"),rn=Symbol("writeEntry"),gt=Symbol("readEntry"),ra=Symbol("nextEntry"),Dd=Symbol("processEntry"),et=Symbol("extendedHeader"),Or=Symbol("globalExtendedHeader"),At=Symbol("meta"),Nd=Symbol("emitMeta"),j=Symbol("buffer"),mt=Symbol("queue"),xt=Symbol("ended"),ia=Symbol("emittedEnd"),sn=Symbol("emit"),Q=Symbol("unzip"),Yi=Symbol("consumeChunk"),Qi=Symbol("consumeChunkSub"),sa=Symbol("consumeBody"),Ld=Symbol("consumeMeta"),Fd=Symbol("consumeHeader"),Pr=Symbol("consuming"),oa=Symbol("bufferConcat"),es=Symbol("maybeEnd"),Mn=Symbol("writing"),Ot=Symbol("aborted"),ts=Symbol("onDone"),on=Symbol("sawValidEntry"),ns=Symbol("sawNullBlock"),rs=Symbol("sawEOF"),Md=Symbol("closeStream"),qw=()=>!0,Jr=class extends uw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[mt]=[];[j];[gt];[rn];[Fe]="begin";[At]="";[et];[Or];[xt]=!1;[Q];[Ot]=!1;[on];[ns]=!1;[rs]=!1;[Mn]=!1;[Pr]=!1;[ia]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(ts,()=>{(this[Fe]==="begin"||this[on]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(ts,t.ondone):this.on(ts,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||jw,this.filter=typeof t.filter=="function"?t.filter:qw;let e=t.file&&(t.file.endsWith(".tar.br")||t.file.endsWith(".tbr"));this.brotli=!(t.gzip||t.zstd)&&t.brotli!==void 0?t.brotli:e?void 0:!1;let n=t.file&&(t.file.endsWith(".tar.zst")||t.file.endsWith(".tzst"));this.zstd=!(t.gzip||t.brotli)&&t.zstd!==void 0?t.zstd:n?!0:void 0,this.on("end",()=>this[Md]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){Ts(this,t,e,n)}[Fd](t,e){this[on]===void 0&&(this[on]=!1);let n;try{n=new un(t,e,this[et],this[Or])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(n.nullBlock)this[ns]?(this[rs]=!0,this[Fe]==="begin"&&(this[Fe]="header"),this[sn]("eof")):(this[ns]=!0,this[sn]("nullBlock"));else if(this[ns]=!1,!n.cksumValid)this.warn("TAR_ENTRY_INVALID","checksum failure",{header:n});else if(!n.path)this.warn("TAR_ENTRY_INVALID","path is required",{header:n});else{let r=n.type;if(/^(Symbolic)?Link$/.test(r)&&!n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath required",{header:n});else if(!/^(Symbolic)?Link$/.test(r)&&!/^(Global)?ExtendedHeader$/.test(r)&&n.linkpath)this.warn("TAR_ENTRY_INVALID","linkpath forbidden",{header:n});else{let i=this[rn]=new wu(n,this[et],this[Or]);if(!this[on])if(i.remain){let s=()=>{i.invalid||(this[on]=!0)};i.on("end",s)}else this[on]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[sn]("ignoredEntry",i),this[Fe]="ignore",i.resume()):i.size>0&&(this[At]="",i.on("data",s=>this[At]+=s),this[Fe]="meta"):(this[et]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[sn]("ignoredEntry",i),this[Fe]=i.remain?"ignore":"header",i.resume()):(i.remain?this[Fe]="body":(this[Fe]="header",i.end()),this[gt]?this[mt].push(i):(this[mt].push(i),this[ra]())))}}}[Md](){queueMicrotask(()=>this.emit("close"))}[Dd](t){let e=!0;if(!t)this[gt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...r]=t;this.emit(n,...r)}else this[gt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ra]()),e=!1);return e}[ra](){do;while(this[Dd](this[mt].shift()));if(this[mt].length===0){let t=this[gt];!t||t.flowing||t.size===t.remain?this[Mn]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[sa](t,e){let n=this[rn];if(!n)throw new Error("attempt to consume body without entry??");let r=n.blockRemain??0,i=r>=t.length&&e===0?t:t.subarray(e,e+r);return n.write(i),n.blockRemain||(this[Fe]="header",this[rn]=void 0,n.end()),i.length}[Ld](t,e){let n=this[rn],r=this[sa](t,e);return!this[rn]&&n&&this[Nd](n),r}[sn](t,e,n){this[mt].length===0&&!this[gt]?this.emit(t,e,n):this[mt].push([t,e,n])}[Nd](t){switch(this[sn]("meta",this[At]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[et]=ws.parse(this[At],this[et],!1);break;case"GlobalExtendedHeader":this[Or]=ws.parse(this[At],this[Or],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[et]??Object.create(null);this[et]=e,e.path=this[At].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[et]||Object.create(null);this[et]=e,e.linkpath=this[At].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[Ot]=!0,this.emit("abort",t),this.warn("TAR_ABORT",t,{recoverable:!1})}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this[Ot])return n?.(),!1;if((this[Q]===void 0||this.brotli===void 0&&this[Q]===!1)&&t){if(this[j]&&(t=Buffer.concat([this[j],t]),this[j]=void 0),t.length<Ww)return this[j]=t,n?.(),!0;for(let o=0;this[Q]===void 0&&o<ya.length;o++)t[o]!==ya[o]&&(this[Q]=!1);let i=!1;if(this[Q]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<_a.length;o++)if(t[o]!==_a[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[Q]===!1&&s)if(t.length<512)if(this[xt])this.brotli=!0;else return this[j]=t,n?.(),!0;else try{new un(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[Q]===void 0||this[Q]===!1&&(this.brotli||i)){let o=this[xt];this[xt]=!1,this[Q]=this[Q]===void 0?new ww({}):i?new Sw({}):new _w({}),this[Q].on("data",c=>this[Yi](c)),this[Q].on("error",c=>this.abort(c)),this[Q].on("end",()=>{this[xt]=!0,this[Yi]()}),this[Mn]=!0;let a=!!this[Q][o?"end":"write"](t);return this[Mn]=!1,n?.(),a}}this[Mn]=!0,this[Q]?this[Q].write(t):this[Yi](t),this[Mn]=!1;let r=this[mt].length>0?!1:this[gt]?this[gt].flowing:!0;return!r&&this[mt].length===0&&this[gt]?.once("drain",()=>this.emit("drain")),n?.(),r}[oa](t){t&&!this[Ot]&&(this[j]=this[j]?Buffer.concat([this[j],t]):t)}[es](){if(this[xt]&&!this[ia]&&!this[Ot]&&!this[Pr]){this[ia]=!0;let t=this[rn];if(t&&t.blockRemain){let e=this[j]?this[j].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[j]&&t.write(this[j]),t.end()}this[sn](ts)}}[Yi](t){if(this[Pr]&&t)this[oa](t);else if(!t&&!this[j])this[es]();else if(t){if(this[Pr]=!0,this[j]){this[oa](t);let e=this[j];this[j]=void 0,this[Qi](e)}else this[Qi](t);for(;this[j]&&this[j]?.length>=512&&!this[Ot]&&!this[rs];){let e=this[j];this[j]=void 0,this[Qi](e)}this[Pr]=!1}(!this[j]||this[xt])&&this[es]()}[Qi](t){let e=0,n=t.length;for(;e+512<=n&&!this[Ot]&&!this[rs];)switch(this[Fe]){case"begin":case"header":this[Fd](t,e),e+=512;break;case"ignore":case"body":e+=this[sa](t,e);break;case"meta":e+=this[Ld](t,e);break;default:throw new Error("invalid state: "+this[Fe])}e<n&&(this[j]=this[j]?Buffer.concat([t.subarray(e),this[j]]):t.subarray(e))}end(t,e,n){return typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e)),n&&this.once("finish",n),this[Ot]||(this[Q]?(t&&this[Q].write(t),this[Q].end()):(this[xt]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[es]())),this}},zr=t=>{let e=t.length-1,n=-1;for(;e>-1&&t.charAt(e)==="/";)n=e,e--;return n===-1?t:t.slice(0,n)},Jw=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},yu=(t,e)=>{let n=new Map(e.map(s=>[zr(s),!0])),r=t.filter,i=(s,o="")=>{let a=o||rw(s).root||".",c;if(s===a)c=!1;else{let l=n.get(s);c=l!==void 0?l:i(nw(s),a)}return n.set(s,c),c};t.filter=r?(s,o)=>r(s,o)&&i(zr(s)):s=>i(zr(s))},Vw=t=>{let e=new Jr(t),n=t.file,r;try{r=Hn.openSync(n,"r");let i=Hn.fstatSync(r),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),a=Hn.readSync(r,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=Hn.readSync(r,a,0,s,o);if(c===0)break;o+=c,e.write(a.subarray(0,c))}e.end()}}finally{if(typeof r=="number")try{Hn.closeSync(r)}catch{}}},Zw=(t,e)=>{let n=new Jr(t),r=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{n.on("error",o),n.on("end",s),Hn.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ma(i,{readSize:r,size:c.size});l.on("error",o),l.pipe(n)}})})},Jn=Vr(Vw,Zw,t=>new Jr(t),t=>new Jr(t),(t,e)=>{e?.length&&yu(t,e),t.noResume||Jw(t)}),_u=(t,e,n)=>(t&=4095,n&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t),{isAbsolute:Xw,parse:Ud}=Kw,$a=t=>{let e="",n=Ud(t);for(;Xw(t)||n.root;){let r=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(r.length),e+=r,n=Ud(t)}return[e,t]},Rs=["|","<",">","?",":"],Ga=Rs.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),Yw=new Map(Rs.map((t,e)=>[t,Ga[e]])),Qw=new Map(Ga.map((t,e)=>[t,Rs[e]])),zd=t=>Rs.reduce((e,n)=>e.split(n).join(Yw.get(n)),t),ey=t=>Ga.reduce((e,n)=>e.split(n).join(Qw.get(n)),t),Eu=(t,e)=>e?(t=N(t).replace(/^\.(\/|$)/,""),zr(e)+"/"+t):N(t),ty=16*1024*1024,$d=Symbol("process"),Gd=Symbol("file"),Hd=Symbol("directory"),Ea=Symbol("symlink"),jd=Symbol("hardlink"),Cr=Symbol("header"),ls=Symbol("read"),Sa=Symbol("lstat"),ds=Symbol("onlstat"),Ia=Symbol("onread"),va=Symbol("onreadlink"),Ta=Symbol("openfile"),Ra=Symbol("onopenfile"),Lt=Symbol("close"),_s=Symbol("mode"),ka=Symbol("awaitDrain"),aa=Symbol("ondrain"),rt=Symbol("prefix"),Su=class extends fn{path;portable;myuid=process.getuid&&process.getuid()||0;myuser=process.env.USER||"";maxReadSize;linkCache;statCache;preservePaths;cwd;strict;mtime;noPax;noMtime;prefix;fd;blockLen=0;blockRemain=0;buf;pos=0;remain=0;length=0;offset=0;win32;absolute;header;type;linkpath;stat;onWriteEntry;#e=!1;constructor(t,e={}){let n=Ba(e);super(),this.path=N(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||ty,this.linkCache=n.linkCache||new Map,this.statCache=n.statCache||new Map,this.preservePaths=!!n.preservePaths,this.cwd=N(n.cwd||process.cwd()),this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.mtime=n.mtime,this.prefix=n.prefix?N(n.prefix):void 0,this.onWriteEntry=n.onWriteEntry,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let r=!1;if(!this.preservePaths){let[s,o]=$a(this.path);s&&typeof o=="string"&&(this.path=o,r=s)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=ey(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=N(n.absolute||Bd.resolve(this.cwd,t)),this.path===""&&(this.path="./"),r&&this.warn("TAR_ENTRY_INFO",`stripping ${r} from absolute path`,{entry:this,path:r+this.path});let i=this.statCache.get(this.absolute);i?this[ds](i):this[Sa]()}warn(t,e,n={}){return Ts(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Sa](){nt.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[ds](e)})}[ds](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=iy(t),this.emit("stat",t),this[$d]()}[$d](){switch(this.type){case"File":return this[Gd]();case"Directory":return this[Hd]();case"SymbolicLink":return this[Ea]();default:return this.end()}}[_s](t){return _u(t,this.type==="Directory",this.portable)}[rt](t){return Eu(t,this.prefix)}[Cr](){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 un({path:this[rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[rt](this.linkpath):this.linkpath,mode:this[_s](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 ws({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[rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[rt](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)}[Hd](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Cr](),this.end()}[Ea](){nt.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[va](e)})}[va](t){this.linkpath=N(t),this[Cr](),this.end()}[jd](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=N(Bd.relative(this.cwd,t)),this.stat.size=0,this[Cr](),this.end()}[Gd](){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[jd](e);this.linkCache.set(t,this.absolute)}if(this[Cr](),this.stat.size===0)return this.end();this[Ta]()}[Ta](){nt.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ra](e)})}[Ra](t){if(this.fd=t,this.#e)return this[Lt]();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[ls]()}[ls](){let{fd:t,buf:e,offset:n,length:r,pos:i}=this;if(t===void 0||e===void 0)throw new Error("cannot read file without first opening");nt.read(t,e,n,r,i,(s,o)=>{if(s)return this[Lt](()=>this.emit("error",s));this[Ia](o)})}[Lt](t=()=>{}){this.fd!==void 0&&nt.close(this.fd,t)}[Ia](t){if(t<=0&&this.remain>0){let n=Object.assign(new Error("encountered unexpected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Lt](()=>this.emit("error",n))}if(t>this.remain){let n=Object.assign(new Error("did not encounter expected EOF"),{path:this.absolute,syscall:"read",code:"EOF"});return this[Lt](()=>this.emit("error",n))}if(!this.buf)throw new Error("should have created buffer prior to reading");if(t===this.remain)for(let n=t;n<this.length&&t<this.blockRemain;n++)this.buf[n+this.offset]=0,t++,this.remain++;let e=this.offset===0&&t===this.buf.length?this.buf:this.buf.subarray(this.offset,this.offset+t);this.write(e)?this[aa]():this[ka](()=>this[aa]())}[ka](t){this.once("drain",t)}write(t,e,n){if(typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8")),this.blockRemain<t.length){let r=Object.assign(new Error("writing more data than expected"),{path:this.absolute});return this.emit("error",r)}return this.remain-=t.length,this.blockRemain-=t.length,this.pos+=t.length,this.offset+=t.length,super.write(t,null,n)}[aa](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Lt](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[ls]()}},ny=class extends Su{sync=!0;[Sa](){this[ds](nt.lstatSync(this.absolute))}[Ea](){this[va](nt.readlinkSync(this.absolute))}[Ta](){this[Ra](nt.openSync(this.absolute,"r"))}[ls](){let t=!0;try{let{fd:e,buf:n,offset:r,length:i,pos:s}=this;if(e===void 0||n===void 0)throw new Error("fd and buf must be set in READ method");let o=nt.readSync(e,n,r,i,s);this[Ia](o),t=!1}finally{if(t)try{this[Lt](()=>{})}catch{}}}[ka](t){t()}[Lt](t=()=>{}){this.fd!==void 0&&nt.closeSync(this.fd),t()}},ry=class extends fn{blockLen=0;blockRemain=0;buf=0;pos=0;remain=0;length=0;preservePaths;portable;strict;noPax;noMtime;readEntry;type;prefix;path;mode;uid;gid;uname;gname;header;mtime;atime;ctime;linkpath;size;onWriteEntry;warn(t,e,n={}){return Ts(this,t,e,n)}constructor(t,e={}){let n=Ba(e);super(),this.preservePaths=!!n.preservePaths,this.portable=!!n.portable,this.strict=!!n.strict,this.noPax=!!n.noPax,this.noMtime=!!n.noMtime,this.onWriteEntry=n.onWriteEntry,this.readEntry=t;let{type:r}=t;if(r==="Unsupported")throw new Error("writing entry that should be ignored");this.type=r,this.type==="Directory"&&this.portable&&(this.noMtime=!0),this.prefix=n.prefix,this.path=N(t.path),this.mode=t.mode!==void 0?this[_s](t.mode):void 0,this.uid=this.portable?void 0:t.uid,this.gid=this.portable?void 0:t.gid,this.uname=this.portable?void 0:t.uname,this.gname=this.portable?void 0:t.gname,this.size=t.size,this.mtime=this.noMtime?void 0:n.mtime||t.mtime,this.atime=this.portable?void 0:t.atime,this.ctime=this.portable?void 0:t.ctime,this.linkpath=t.linkpath!==void 0?N(t.linkpath):void 0,typeof n.onwarn=="function"&&this.on("warn",n.onwarn);let i=!1;if(!this.preservePaths){let[o,a]=$a(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 un({path:this[rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[rt](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 ws({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[rt](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[rt](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)}[rt](t){return Eu(t,this.prefix)}[_s](t){return _u(t,this.type==="Directory",this.portable)}write(t,e,n){typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,typeof e=="string"?e:"utf8"));let r=t.length;if(r>this.blockRemain)throw new Error("writing more to entry than is appropriate");return this.blockRemain-=r,super.write(t,n)}end(t,e,n){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),typeof t=="function"&&(n=t,e=void 0,t=void 0),typeof e=="function"&&(n=e,e=void 0),typeof t=="string"&&(t=Buffer.from(t,e??"utf8")),n&&this.once("finish",n),t?super.end(t,n):super.end(n),this}},iy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",sy=class jn{tail;head;length=0;static create(e=[]){return new jn(e)}constructor(e=[]){for(let n of e)this.push(n)}*[Symbol.iterator](){for(let e=this.head;e;e=e.next)yield e.value}removeNode(e){if(e.list!==this)throw new Error("removing node which does not belong to this list");let n=e.next,r=e.prev;return n&&(n.prev=r),r&&(r.next=n),e===this.head&&(this.head=n),e===this.tail&&(this.tail=r),this.length--,e.next=void 0,e.prev=void 0,e.list=void 0,n}unshiftNode(e){if(e===this.head)return;e.list&&e.list.removeNode(e);let n=this.head;e.list=this,e.next=n,n&&(n.prev=e),this.head=e,this.tail||(this.tail=e),this.length++}pushNode(e){if(e===this.tail)return;e.list&&e.list.removeNode(e);let n=this.tail;e.list=this,e.prev=n,n&&(n.next=e),this.tail=e,this.head||(this.head=e),this.length++}push(...e){for(let n=0,r=e.length;n<r;n++)ay(this,e[n]);return this.length}unshift(...e){for(var n=0,r=e.length;n<r;n++)cy(this,e[n]);return this.length}pop(){if(!this.tail)return;let e=this.tail.value,n=this.tail;return this.tail=this.tail.prev,this.tail?this.tail.next=void 0:this.head=void 0,n.list=void 0,this.length--,e}shift(){if(!this.head)return;let e=this.head.value,n=this.head;return this.head=this.head.next,this.head?this.head.prev=void 0:this.tail=void 0,n.list=void 0,this.length--,e}forEach(e,n){n=n||this;for(let r=this.head,i=0;r;i++)e.call(n,r.value,i,this),r=r.next}forEachReverse(e,n){n=n||this;for(let r=this.tail,i=this.length-1;r;i--)e.call(n,r.value,i,this),r=r.prev}get(e){let n=0,r=this.head;for(;r&&n<e;n++)r=r.next;if(n===e&&r)return r.value}getReverse(e){let n=0,r=this.tail;for(;r&&n<e;n++)r=r.prev;if(n===e&&r)return r.value}map(e,n){n=n||this;let r=new jn;for(let i=this.head;i;)r.push(e.call(n,i.value,this)),i=i.next;return r}mapReverse(e,n){n=n||this;var r=new jn;for(let i=this.tail;i;)r.push(e.call(n,i.value,this)),i=i.prev;return r}reduce(e,n){let r,i=this.head;if(arguments.length>1)r=n;else if(this.head)i=this.head.next,r=this.head.value;else throw new TypeError("Reduce of empty list with no initial value");for(var s=0;i;s++)r=e(r,i.value,s),i=i.next;return r}reduceReverse(e,n){let r,i=this.tail;if(arguments.length>1)r=n;else if(this.tail)i=this.tail.prev,r=this.tail.value;else throw new TypeError("Reduce of empty list with no initial value");for(let s=this.length-1;i;s--)r=e(r,i.value,s),i=i.prev;return r}toArray(){let e=new Array(this.length);for(let n=0,r=this.head;r;n++)e[n]=r.value,r=r.next;return e}toArrayReverse(){let e=new Array(this.length);for(let n=0,r=this.tail;r;n++)e[n]=r.value,r=r.prev;return e}slice(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let r=new jn;if(n<e||n<0)return r;e<0&&(e=0),n>this.length&&(n=this.length);let i=this.head,s=0;for(s=0;i&&s<e;s++)i=i.next;for(;i&&s<n;s++,i=i.next)r.push(i.value);return r}sliceReverse(e=0,n=this.length){n<0&&(n+=this.length),e<0&&(e+=this.length);let r=new jn;if(n<e||n<0)return r;e<0&&(e=0),n>this.length&&(n=this.length);let i=this.length,s=this.tail;for(;s&&i>n;i--)s=s.prev;for(;s&&i>e;i--,s=s.prev)r.push(s.value);return r}splice(e,n=0,...r){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<n;o++)s.push(i.value),i=this.removeNode(i);i?i!==this.tail&&(i=i.prev):i=this.tail;for(let o of r)i=oy(this,i,o);return s}reverse(){let e=this.head,n=this.tail;for(let r=e;r;r=r.prev){let i=r.prev;r.prev=r.next,r.next=i}return this.head=n,this.tail=e,this}};function oy(t,e,n){let r=e,i=e?e.next:t.head,s=new Ha(n,r,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function ay(t,e){t.tail=new Ha(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function cy(t,e){t.head=new Ha(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var Ha=class{list;next;prev;value;constructor(t,e,n,r){this.list=r,this.value=t,e?(e.next=this,this.prev=e):this.prev=void 0,n?(n.prev=this,this.next=n):this.next=void 0}},qd=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},Jd=Buffer.alloc(1024),us=Symbol("onStat"),Dr=Symbol("ended"),He=Symbol("queue"),Nr=Symbol("queue"),Pt=Symbol("current"),an=Symbol("process"),Lr=Symbol("processing"),is=Symbol("processJob"),je=Symbol("jobs"),ca=Symbol("jobDone"),fs=Symbol("addFSEntry"),Vd=Symbol("addTarEntry"),ba=Symbol("stat"),Aa=Symbol("readdir"),hs=Symbol("onreaddir"),ps=Symbol("pipe"),Zd=Symbol("entry"),la=Symbol("entryOpt"),gs=Symbol("writeEntryClass"),Iu=Symbol("write"),da=Symbol("ondrain"),ks=class extends fn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[gs];onWriteEntry;[He];[Nr]=new Map;[je]=0;[Lr]=!1;[Dr]=!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=N(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[gs]=Su,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 mw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new yw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Ew(t.zstd)),!this.zip)throw new Error("impossible");let e=this.zip;e.on("data",n=>super.write(n)),e.on("end",()=>super.end()),e.on("drain",()=>this[da]()),this.on("resume",()=>e.resume())}else this.on("drain",this[da]);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[He]=new sy,this[je]=0,this.jobs=Number(t.jobs)||4,this[Lr]=!1,this[Dr]=!1}[Iu](t){return super.write(t)}add(t){return this.write(t),this}end(t,e,n){return typeof t=="function"&&(n=t,t=void 0),typeof e=="function"&&(n=e,e=void 0),t&&this.add(t),this[Dr]=!0,this[an](),n&&n(),this}write(t){if(this[Dr])throw new Error("write after end");return t instanceof wu?this[Vd](t):this[fs](t),this.flowing}[Vd](t){let e=N(Wd.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new qd(t.path,e);n.entry=new ry(t,this[la](n)),n.entry.on("end",()=>this[ca](n)),this[je]+=1,this[He].push(n)}this[an]()}[fs](t){let e=N(Wd.resolve(this.cwd,t));this[He].push(new qd(t,e)),this[an]()}[ba](t){t.pending=!0,this[je]+=1;let e=this.follow?"stat":"lstat";ys[e](t.absolute,(n,r)=>{t.pending=!1,this[je]-=1,n?this.emit("error",n):this[us](t,r)})}[us](t,e){if(this.statCache.set(t.absolute,e),t.stat=e,!this.filter(t.path,e))t.ignore=!0;else if(e.isFile()&&e.nlink>1&&!this.linkCache.get(`${e.dev}:${e.ino}`)&&!this.sync)if(t===this[Pt])this[is](t);else{let n=`${e.dev}:${e.ino}`,r=this[Nr].get(n);r?r.push(t):this[Nr].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[an]()}[Aa](t){t.pending=!0,this[je]+=1,ys.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[je]-=1,e)return this.emit("error",e);this[hs](t,n)})}[hs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[an]()}[an](){if(!this[Lr]){this[Lr]=!0;for(let t=this[He].head;t&&this[je]<this.jobs;t=t.next)if(this[is](t.value),t.value.ignore){let e=t.next;this[He].removeNode(t),t.next=e}this[Lr]=!1,this[Dr]&&this[He].length===0&&this[je]===0&&(this.zip?this.zip.end(Jd):(super.write(Jd),super.end()))}}get[Pt](){return this[He]&&this[He].head&&this[He].head.value}[ca](t){this[He].shift(),this[je]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,r=this[Nr].get(n);if(r){this[Nr].delete(n);for(let i of r)i.pending=!1,this[is](i)}}this[an]()}[is](t){if(t.pending&&t.pendingLink&&t===this[Pt]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Pt]&&!t.piped&&this[ps](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[us](t,e):this[ba](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[hs](t,e):this[Aa](t),!t.readdir)return}if(t.entry=this[Zd](t),!t.entry){t.ignore=!0;return}t===this[Pt]&&!t.piped&&this[ps](t)}}}[la](t){return{onwarn:(e,n,r)=>this.warn(e,n,r),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}}[Zd](t){this[je]+=1;try{return new this[gs](t.path,this[la](t)).on("end",()=>this[ca](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[da](){this[Pt]&&this[Pt].entry&&this[Pt].entry.resume()}[ps](t){t.piped=!0,t.readdir&&t.readdir.forEach(r=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[fs](s+r)});let e=t.entry,n=this.zip;if(!e)throw new Error("cannot pipe without source");n?e.on("data",r=>{n.write(r)||e.pause()}):e.on("data",r=>{super.write(r)||e.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}warn(t,e,n={}){Ts(this,t,e,n)}},ja=class extends ks{sync=!0;constructor(t){super(t),this[gs]=ny}pause(){}resume(){}[ba](t){let e=this.follow?"statSync":"lstatSync";this[us](t,ys[e](t.absolute))}[Aa](t){this[hs](t,ys.readdirSync(t.absolute))}[ps](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[fs](s+r)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",r=>{n.write(r)}):e.on("data",r=>{super[Iu](r)})}},ly=(t,e)=>{let n=new ja(t),r=new lu(t.file,{mode:t.mode||438});n.pipe(r),vu(n,e)},dy=(t,e)=>{let n=new ks(t),r=new Is(t.file,{mode:t.mode||438});n.pipe(r);let i=new Promise((s,o)=>{r.on("error",o),r.on("close",s),n.on("error",o)});return Tu(n,e).catch(s=>n.emit("error",s)),i},vu=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Jn({file:du.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n)}),t.end()},Tu=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Jn({file:du.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:r=>{t.add(r)}}):t.add(n);t.end()},uy=(t,e)=>{let n=new ja(t);return vu(n,e),n},fy=(t,e)=>{let n=new ks(t);return Tu(n,e).catch(r=>n.emit("error",r)),n},WR=Vr(ly,dy,uy,fy,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),py=process.env.__FAKE_PLATFORM__||process.platform,Au=py==="win32",{O_CREAT:xu,O_NOFOLLOW:Kd,O_TRUNC:Ou,O_WRONLY:Pu}=bu.constants,Cu=Number(process.env.__FAKE_FS_O_FILENAME__)||bu.constants.UV_FS_O_FILEMAP||0,gy=Au&&!!Cu,my=512*1024,wy=Cu|Ou|xu|Pu,Xd=!Au&&typeof Kd=="number"?Kd|Ou|xu|Pu:null,Du=Xd!==null?()=>Xd:gy?t=>t<my?wy:"w":()=>"w",xa=(t,e,n)=>{try{return bs.lchownSync(t,e,n)}catch(r){if(r?.code!=="ENOENT")throw r}},Es=(t,e,n,r)=>{bs.lchown(t,e,n,i=>{r(i&&i?.code!=="ENOENT"?i:null)})},yy=(t,e,n,r,i)=>{if(e.isDirectory())Nu($r.resolve(t,e.name),n,r,s=>{if(s)return i(s);let o=$r.resolve(t,e.name);Es(o,n,r,i)});else{let s=$r.resolve(t,e.name);Es(s,n,r,i)}},Nu=(t,e,n,r)=>{bs.readdir(t,{withFileTypes:!0},(i,s)=>{if(i){if(i.code==="ENOENT")return r();if(i.code!=="ENOTDIR"&&i.code!=="ENOTSUP")return r(i)}if(i||!s.length)return Es(t,e,n,r);let o=s.length,a=null,c=l=>{if(!a){if(l)return r(a=l);if(--o===0)return Es(t,e,n,r)}};for(let l of s)yy(t,l,e,n,c)})},_y=(t,e,n,r)=>{e.isDirectory()&&Lu($r.resolve(t,e.name),n,r),xa($r.resolve(t,e.name),n,r)},Lu=(t,e,n)=>{let r;try{r=bs.readdirSync(t,{withFileTypes:!0})}catch(i){let s=i;if(s?.code==="ENOENT")return;if(s?.code==="ENOTDIR"||s?.code==="ENOTSUP")return xa(t,e,n);throw s}for(let i of r)_y(t,i,e,n);return xa(t,e,n)},Fu=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"}},As=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"}},Sy=(t,e)=>{Pe.stat(t,(n,r)=>{(n||!r.isDirectory())&&(n=new Fu(t,n?.code||"ENOTDIR")),e(n)})},Iy=(t,e,n)=>{t=N(t);let r=e.umask??18,i=e.mode|448,s=(i&r)!==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=N(e.cwd),m=(h,g)=>{h?n(h):g&&c?Nu(g,o,a,w=>m(w)):s?Pe.chmod(t,i,n):n()};if(t===p)return Sy(t,m);if(l)return Ey.mkdir(t,{mode:i,recursive:!0}).then(h=>m(null,h??void 0),m);let f=N(Ss.relative(p,t)).split("/");Oa(p,f,i,d,p,void 0,m)},Oa=(t,e,n,r,i,s,o)=>{if(e.length===0)return o(null,s);let a=e.shift(),c=N(Ss.resolve(t+"/"+a));Pe.mkdir(c,n,Mu(c,e,n,r,i,s,o))},Mu=(t,e,n,r,i,s,o)=>a=>{a?Pe.lstat(t,(c,l)=>{if(c)c.path=c.path&&N(c.path),o(c);else if(l.isDirectory())Oa(t,e,n,r,i,s,o);else if(r)Pe.unlink(t,d=>{if(d)return o(d);Pe.mkdir(t,n,Mu(t,e,n,r,i,s,o))});else{if(l.isSymbolicLink())return o(new As(t,t+"/"+e.join("/")));o(a)}}):(s=s||t,Oa(t,e,n,r,i,s,o))},vy=t=>{let e=!1,n;try{e=Pe.statSync(t).isDirectory()}catch(r){n=r?.code}finally{if(!e)throw new Fu(t,n??"ENOTDIR")}},Ty=(t,e)=>{t=N(t);let n=e.umask??18,r=e.mode|448,i=(r&n)!==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=N(e.cwd),p=h=>{h&&a&&Lu(h,s,o),i&&Pe.chmodSync(t,r)};if(t===d)return vy(d),p();if(c)return p(Pe.mkdirSync(t,{mode:r,recursive:!0})??void 0);let m=N(Ss.relative(d,t)).split("/"),f;for(let h=m.shift(),g=d;h&&(g+="/"+h);h=m.shift()){g=N(Ss.resolve(g));try{Pe.mkdirSync(g,r),f=f||g}catch{let w=Pe.lstatSync(g);if(w.isDirectory())continue;if(l){Pe.unlinkSync(g),Pe.mkdirSync(g,r),f=f||g;continue}else if(w.isSymbolicLink())return new As(g,g+"/"+m.join("/"))}}return p(f)},ua=Object.create(null),Yd=1e4,Bn=new Set,Ry=t=>{Bn.has(t)?Bn.delete(t):ua[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),Bn.add(t);let e=ua[t],n=Bn.size-Yd;if(n>Yd/10){for(let r of Bn)if(Bn.delete(r),delete ua[r],--n<=0)break}return e},ky=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,by=ky==="win32",Ay=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let r=e.at(-1);return r!==void 0&&(n=Bu(r,n)),e.push(n||"/"),e},[]),xy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=by?["win32 parallelization disabled"]:t.map(r=>zr(Bu(Ry(r))));let n=new Set(t.map(r=>Ay(r)).reduce((r,i)=>r.concat(i)));this.#n.set(e,{dirs:n,paths:t});for(let r of t){let i=this.#e.get(r);i?i.push(e):this.#e.set(r,[e])}for(let r of n){let i=this.#e.get(r);if(!i)this.#e.set(r,[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.#n.get(t);if(!e)throw new Error("function does not have any path reservations");return{paths:e.paths.map(n=>this.#e.get(n)),dirs:[...e.dirs].map(n=>this.#e.get(n))}}check(t){let{paths:e,dirs:n}=this.#s(t);return e.every(r=>r&&r[0]===t)&&n.every(r=>r&&r[0]instanceof Set&&r[0].has(t))}#i(t){return this.#r.has(t)||!this.check(t)?!1:(this.#r.add(t),t(()=>this.#t(t)),!0)}#t(t){if(!this.#r.has(t))return!1;let e=this.#n.get(t);if(!e)throw new Error("invalid reservation");let{paths:n,dirs:r}=e,i=new Set;for(let s of n){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 r){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.#r.delete(t),i.forEach(s=>this.#i(s)),!0}},Oy=()=>process.umask(),Qd=Symbol("onEntry"),Pa=Symbol("checkFs"),eu=Symbol("checkFs2"),Ca=Symbol("isReusable"),Me=Symbol("makeFs"),Da=Symbol("file"),Na=Symbol("directory"),ms=Symbol("link"),tu=Symbol("symlink"),nu=Symbol("hardlink"),Br=Symbol("ensureNoSymlink"),ru=Symbol("unsupported"),iu=Symbol("checkPath"),fa=Symbol("stripAbsolutePath"),Ft=Symbol("mkdir"),le=Symbol("onError"),ss=Symbol("pending"),su=Symbol("pend"),Un=Symbol("unpend"),ha=Symbol("ended"),pa=Symbol("maybeClose"),La=Symbol("skip"),Gr=Symbol("doChown"),Hr=Symbol("uid"),jr=Symbol("gid"),Wr=Symbol("checkedCwd"),Py=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,qr=Py==="win32",Cy=1024,Dy=(t,e)=>{if(!qr)return M.unlink(t,e);let n=t+".DELETE."+ku(16).toString("hex");M.rename(t,n,r=>{if(r)return e(r);M.unlink(n,e)})},Ny=t=>{if(!qr)return M.unlinkSync(t);let e=t+".DELETE."+ku(16).toString("hex");M.renameSync(t,e),M.unlinkSync(e)},ou=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,Wa=class extends Jr{[ha]=!1;[Wr]=!1;[ss]=0;reservations=new xy;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[ha]=!0,this[pa]()},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:Cy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||qr,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=N(ne.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Oy():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[Qd](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[pa](){this[ha]&&this[ss]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[fa](t,e){let n=t[e],{type:r}=t;if(!n||this.preservePaths)return!0;let[i,s]=$a(n),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||qr&&/^[a-z]:\.\.$/i.test(o[0]??"")){if(e==="path"||r==="Link")return this.warn("TAR_ENTRY_ERROR",`${e} contains '..'`,{entry:t,[e]:n}),!1;let a=ne.posix.dirname(t.path),c=ne.posix.normalize(ne.posix.join(a,o.join("/")));if(c.startsWith("../")||c==="..")return this.warn("TAR_ENTRY_ERROR",`${e} escapes extraction directory`,{entry:t,[e]:n}),!1}return i&&(t[e]=String(s),this.warn("TAR_ENTRY_INFO",`stripping ${i} from absolute ${e}`,{entry:t,[e]:n})),!0}[iu](t){let e=N(t.path),n=e.split("/");if(this.strip){if(n.length<this.strip)return!1;if(t.type==="Link"){let r=N(String(t.linkpath)).split("/");if(r.length>=this.strip)t.linkpath=r.slice(this.strip).join("/");else return!1}n.splice(0,this.strip),t.path=n.join("/")}if(isFinite(this.maxDepth)&&n.length>this.maxDepth)return this.warn("TAR_ENTRY_ERROR","path excessively deep",{entry:t,path:e,depth:n.length,maxDepth:this.maxDepth}),!1;if(!this[fa](t,"path")||!this[fa](t,"linkpath"))return!1;if(t.absolute=ne.isAbsolute(t.path)?N(ne.resolve(t.path)):N(ne.resolve(this.cwd,t.path)),!this.preservePaths&&typeof t.absolute=="string"&&t.absolute.indexOf(this.cwd+"/")!==0&&t.absolute!==this.cwd)return this.warn("TAR_ENTRY_ERROR","path escaped extraction target",{entry:t,path:N(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:r}=ne.win32.parse(String(t.absolute));t.absolute=r+zd(String(t.absolute).slice(r.length));let{root:i}=ne.win32.parse(t.path);t.path=i+zd(t.path.slice(i.length))}return!0}[Qd](t){if(!this[iu](t))return t.resume();switch(hy.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[ru](t)}}[le](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Un](),e.resume())}[Ft](t,e,n){Iy(N(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e},n)}[Gr](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}[Hr](t){return ou(this.uid,t.uid,this.processUid)}[jr](t){return ou(this.gid,t.gid,this.processGid)}[Da](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new Is(String(t.absolute),{flags:Du(t.size),mode:n,autoClose:!1});r.on("error",a=>{r.fd&&M.close(r.fd,()=>{}),r.write=()=>!0,this[le](a,t),e()});let i=1,s=a=>{if(a){r.fd&&M.close(r.fd,()=>{}),this[le](a,t),e();return}--i===0&&r.fd!==void 0&&M.close(r.fd,c=>{c?this[le](c,t):this[Un](),e()})};r.on("finish",()=>{let a=String(t.absolute),c=r.fd;if(typeof c=="number"&&t.mtime&&!this.noMtime){i++;let l=t.atime||new Date,d=t.mtime;M.futimes(c,l,d,p=>p?M.utimes(a,l,d,m=>s(m&&p)):s())}if(typeof c=="number"&&this[Gr](t)){i++;let l=this[Hr](t),d=this[jr](t);typeof l=="number"&&typeof d=="number"&&M.fchown(c,l,d,p=>p?M.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[le](a,t),e()}),t.pipe(o)),o.pipe(r)}[Na](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Ft](String(t.absolute),n,r=>{if(r){this[le](r,t),e();return}let i=1,s=()=>{--i===0&&(e(),this[Un](),t.resume())};t.mtime&&!this.noMtime&&(i++,M.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[Gr](t)&&(i++,M.chown(String(t.absolute),Number(this[Hr](t)),Number(this[jr](t)),s)),s()})}[ru](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[tu](t,e){let n=N(ne.relative(this.cwd,ne.resolve(ne.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Br](t,this.cwd,n,()=>this[ms](t,String(t.linkpath),"symlink",e),r=>{this[le](r,t),e()})}[nu](t,e){let n=N(ne.resolve(this.cwd,String(t.linkpath))),r=N(String(t.linkpath)).split("/");this[Br](t,this.cwd,r,()=>this[ms](t,n,"link",e),i=>{this[le](i,t),e()})}[Br](t,e,n,r,i){let s=n.shift();if(this.preservePaths||s===void 0)return r();let o=ne.resolve(e,s);M.lstat(o,(a,c)=>{if(a)return r();if(c?.isSymbolicLink())return i(new As(o,ne.resolve(o,n.join("/"))));this[Br](t,o,n,r,i)})}[su](){this[ss]++}[Un](){this[ss]--,this[pa]()}[La](t){this[Un](),t.resume()}[Ca](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!qr}[Pa](t){this[su]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[eu](t,n))}[eu](t,e){let n=o=>{e(o)},r=()=>{this[Ft](this.cwd,this.dmode,o=>{if(o){this[le](o,t),n();return}this[Wr]=!0,i()})},i=()=>{if(t.absolute!==this.cwd){let o=N(ne.dirname(String(t.absolute)));if(o!==this.cwd)return this[Ft](o,this.dmode,a=>{if(a){this[le](a,t),n();return}s()})}s()},s=()=>{M.lstat(String(t.absolute),(o,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[La](t),n();return}if(o||this[Ca](t,a))return this[Me](null,t,n);if(a.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,l=d=>this[Me](d??null,t,n);return c?M.chmod(String(t.absolute),Number(t.mode),l):l()}if(t.absolute!==this.cwd)return M.rmdir(String(t.absolute),c=>this[Me](c??null,t,n))}if(t.absolute===this.cwd)return this[Me](null,t,n);Dy(String(t.absolute),c=>this[Me](c??null,t,n))})};this[Wr]?i():r()}[Me](t,e,n){if(t){this[le](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[Da](e,n);case"Link":return this[nu](e,n);case"SymbolicLink":return this[tu](e,n);case"Directory":case"GNUDumpDir":return this[Na](e,n)}}[ms](t,e,n,r){M[n](e,String(t.absolute),i=>{i?this[le](i,t):(this[Un](),t.resume()),r()})}},Fr=t=>{try{return[null,t()]}catch(e){return[e,null]}},Uu=class extends Wa{sync=!0;[Me](t,e){return super[Me](t,e,()=>{})}[Pa](t){if(!this[Wr]){let i=this[Ft](this.cwd,this.dmode);if(i)return this[le](i,t);this[Wr]=!0}if(t.absolute!==this.cwd){let i=N(ne.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[Ft](i,this.dmode);if(s)return this[le](s,t)}}let[e,n]=Fr(()=>M.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[La](t);if(e||this[Ca](t,n))return this[Me](null,t);if(n.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[o]=s?Fr(()=>{M.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[Me](o,t)}let[i]=Fr(()=>M.rmdirSync(String(t.absolute)));this[Me](i,t)}let[r]=t.absolute===this.cwd?[]:Fr(()=>Ny(String(t.absolute)));this[Me](r,t)}[Da](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,r=o=>{let a;try{M.closeSync(i)}catch(c){a=c}(o||a)&&this[le](o||a,t),e()},i;try{i=M.openSync(String(t.absolute),Du(t.size),n)}catch(o){return r(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[le](o,t)),t.pipe(s)),s.on("data",o=>{try{M.writeSync(i,o,0,o.length)}catch(a){r(a)}}),s.on("end",()=>{let o=null;if(t.mtime&&!this.noMtime){let a=t.atime||new Date,c=t.mtime;try{M.futimesSync(i,a,c)}catch(l){try{M.utimesSync(String(t.absolute),a,c)}catch{o=l}}}if(this[Gr](t)){let a=this[Hr](t),c=this[jr](t);try{M.fchownSync(i,Number(a),Number(c))}catch(l){try{M.chownSync(String(t.absolute),Number(a),Number(c))}catch{o=o||l}}}r(o)})}[Na](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[Ft](String(t.absolute),n);if(r){this[le](r,t),e();return}if(t.mtime&&!this.noMtime)try{M.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Gr](t))try{M.chownSync(String(t.absolute),Number(this[Hr](t)),Number(this[jr](t)))}catch{}e(),t.resume()}[Ft](t,e){try{return Ty(N(t),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cwd:this.cwd,mode:e})}catch(n){return n}}[Br](t,e,n,r,i){if(this.preservePaths||n.length===0)return r();let s=e;for(let o of n){s=ne.resolve(s,o);let[a,c]=Fr(()=>M.lstatSync(s));if(a)return r();if(c.isSymbolicLink())return i(new As(s,ne.resolve(e,n.join("/"))))}r()}[ms](t,e,n,r){let i=`${n}Sync`;try{M[i](e,String(t.absolute)),r(),t.resume()}catch(s){return this[le](s,t)}}},Ly=t=>{let e=new Uu(t),n=t.file,r=Ru.statSync(n),i=t.maxReadSize||16*1024*1024;new tw(n,{readSize:i,size:r.size}).pipe(e)},Fy=(t,e)=>{let n=new Wa(t),r=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{n.on("error",o),n.on("close",s),Ru.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ma(i,{readSize:r,size:c.size});l.on("error",o),l.pipe(n)}})})},zu=Vr(Ly,Fy,t=>new Uu(t),t=>new Wa(t),(t,e)=>{e?.length&&yu(t,e)}),My=(t,e)=>{let n=new ja(t),r=!0,i,s;try{try{i=Oe.openSync(t.file,"r+")}catch(c){if(c?.code==="ENOENT")i=Oe.openSync(t.file,"w+");else throw c}let o=Oe.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=Oe.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 un(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)}r=!1,By(t,n,s,i,e)}finally{if(r)try{Oe.closeSync(i)}catch{}}},By=(t,e,n,r,i)=>{let s=new lu(t.file,{fd:r,start:n});e.pipe(s),zy(e,i)},Uy=(t,e)=>{e=Array.from(e);let n=new ks(t),r=(i,s,o)=>{let a=(m,f)=>{m?Oe.close(i,h=>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 Oe.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 h=new un(d);if(!h.cksumValid)return a(null,c);let g=512*Math.ceil((h.size??0)/512);if(c+g+512>s||(c+=g+512,c>=s))return a(null,c);t.mtimeCache&&h.mtime&&t.mtimeCache.set(String(h.path),h.mtime),l=0,Oe.read(i,d,0,512,c,p)};Oe.read(i,d,0,512,c,p)};return new Promise((i,s)=>{n.on("error",s);let o="r+",a=(c,l)=>{if(c&&c.code==="ENOENT"&&o==="r+")return o="w+",Oe.open(t.file,o,a);if(c||!l)return s(c);Oe.fstat(l,(d,p)=>{if(d)return Oe.close(l,()=>s(d));r(l,p.size,(m,f)=>{if(m)return s(m);let h=new Is(t.file,{fd:l,start:f});n.pipe(h),h.on("error",s),h.on("close",i),$y(n,e)})})};Oe.open(t.file,o,a)})},zy=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Jn({file:$u.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n)}),t.end()},$y=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Jn({file:$u.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n);t.end()},Mr=Vr(My,Uy,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!lw(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")}),ok=Vr(Mr.syncFile,Mr.asyncFile,Mr.syncNoFile,Mr.asyncNoFile,(t,e=[])=>{Mr.validate?.(t,e),Gy(t)}),Gy=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(n,r)=>e(n,r)&&!((t.mtimeCache?.get(n)??r.mtime??0)>(r.mtime??0)):(n,r)=>!((t.mtimeCache?.get(n)??r.mtime??0)>(r.mtime??0))};Rt();var Je={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 Zr(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function Gu(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function qa(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function Hu(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function Vn(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Ie();L();se();Ie();function _t(t,e){if(Zr(t)!=="cloud")throw new _("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function xs(t){return t.startsWith("http://")||t.startsWith("https://")}function Os(t){return t.endsWith("/")?t.slice(0,-1):t}Ie();L();var Ps="1008033",ju="1289";var Wu="pbbp2",qu="https://www.coze.cn",Ju="/api/coze_claw/resource/get_frontier_key",jy="https://www.coze.cn",Wy="wss://frontier.coze.cn";function Cs(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??jy}function Vu(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??Wy}function Zn(t){let e={},n=t?.ttEnv??process.env.COZE_BRIDGE_TT_ENV,r=t?.usePpe??process.env.COZE_BRIDGE_USE_PPE;return n&&(e["x-tt-env"]=n),r&&(e["x-use-ppe"]=r),e}function Xr(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var Kr=A("handshake");async function Ja(t){let e=Cs(t.endpoint),n=t.timeoutMs??1e4,r=`${Os(e)}${Ju}?aid=${encodeURIComponent(Ps)}`,i={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...Zn(t.ppeOverride)},s=new AbortController,o=setTimeout(()=>s.abort(),n);Kr.info("frontier key handshake",{base:e});try{let a=await fetch(r,{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 h=await a.text().catch(()=>"");throw new _("UPSTREAM_HANDSHAKE_FAILED",`handshake HTTP ${a.status} logid=${c}: ${h.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 h=JSON.stringify(d).slice(0,500);throw new _("UPSTREAM_HANDSHAKE_FAILED",`handshake response missing access_key/device_id (also tried camelCase) logid=${c}: ${h}`)}return Kr.info("handshake ok",{remoteDeviceId:f,logid:c,traceId:l}),{accessKey:m,deviceId:f}}catch(a){if(a instanceof _)throw Kr.error("handshake failed (bridge error)",{base:e,message:a.message,code:a.code}),a;if(a.name==="AbortError")throw Kr.warn("handshake timeout",{base:e,timeoutMs:n}),new _("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:a});let c=a.cause;throw Kr.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 Va=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ve="auto",Zu=2e5;function Ku(t){return{model:Za(t.model)??Ve,...t.modelToken?{modelToken:t.modelToken}:{}}}function Xu(t){return!t||t===Ve}var qy=new Set(["auto","\u81EA\u52A8"]);function Za(t){let e=t?.trim();if(e)return qy.has(e.toLowerCase())?Ve:e}function Yu(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=Va,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Ve;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else Xu(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function Qu(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Ve}"`):Xu(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="${Va}/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 n=t.modelInfo?.contextWindow??Zu;e.push("-c",`model_context_window=${n}`)}return e}function ef(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function Ka(t,e){let{ttEnv:n,usePpe:r}=Xr(t),i={};return n&&(i["x-tt-env"]=n),r&&(i["x-use-ppe"]=r),e&&(i["x-mock-scenario"]=e),i}function tf(t,e,n){if(!t.modelToken)return{};let r=Ka(e,n);return Object.keys(r).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(r).map(([s,o])=>`${s}:${o}`).join(`
|
|
84
|
+
`)}}function Xa(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function nf(t,e,n){if(!t.modelToken)return null;let r=t.model||Ve,i=Ka(e,n),s=["text"];t.modelInfo?.capabilities?.image===!0&&s.push("image");let o={baseUrl:`${Va}/v1`,api:"openai-completions",apiKey:t.modelToken,models:[{id:r,name:r,reasoning:!1,input:s,cost:{input:0,output:0,cacheRead:0,cacheWrite:0},contextWindow:t.modelInfo?.contextWindow??Zu,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(o.headers=i),o}function rf(t,e,n){if(!t.modelToken)return[];let r=Ka(e,n),i=[];for(let[s,o]of Object.entries(r))i.push("-c",`model_providers.coze.http_headers.${s}="${o}"`);return i}var re=A("agent-handlers"),sf=5*1024*1024,Yy=1,Qy=6,e_=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ds=class{constructor(e){this.opts=e}opts;async listSkills(e){_t(e._meta,"_agent/listSkills");let n=Vn(e._meta),r=await this.loadAgentCfg(n),i=r?.workspace??Re(n).workspace,s=r?.skills??[],o=[];for(let a of s){let c=st(i,a.relPath,"SKILL.md");await Zy(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(s_(a))}return{skills:o}}async addSkills(e){_t(e._meta,"_agent/addSkills");let n=Vn(e._meta),r=await this.requireAgentCfg(n),i=e.skills??[],s=[...r.skills??[]],o=new Map(s.map((c,l)=>[c.skillId,l])),a=[];for(let c of i){let l=await ic({agentId:n,workspace:r.workspace,framework:r.framework,skill:c});sc(s,o,l),a.push(c)}return await Bi(n,s),this.reloadAgentSessions(n,"skills-added"),{installedSkills:a}}async removeSkills(e){_t(e._meta,"_agent/removeSkills");let n=Vn(e._meta),r=await this.requireAgentCfg(n),i=new Set(e.skillIds??[]),s=r.skills??[],o=[];for(let a of s){if(!i.has(a.skillId)){o.push(a);continue}let c=st(r.workspace,a.relPath);await Vy(c,{recursive:!0,force:!0}),re.info("skill removed",{agentId:n,skillId:a.skillId,relPath:a.relPath})}return await Bi(n,o),this.reloadAgentSessions(n,"skills-removed"),{ok:!0}}reloadAgentSessionsPublic(e,n){this.reloadAgentSessions(e,n)}reloadAgentSessions(e,n){let r=this.opts.agents.get(e);if(r)for(let[i,s]of r.sessions){if(!s.downstream)continue;let o=s.acpSessionId;if(o&&r.activeTriggers.has(o)||this.isRuntimePendingPermission(s)){s.reloadAfterTurn=!0,re.info("downstream busy, scheduling reload after turn",{reason:n,agentId:e,framework:r.framework,cloudId:i,acpId:o});continue}let c=s.downstream;s.downstream=void 0,re.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:r.framework,cloudId:i,acpId:o}),c.stop(n).catch(l=>re.warn("downstream stop failed during reload (ignored)",{reason:n,agentId:e,cloudId:i,err:String(l)}))}}isRuntimePendingPermission(e){let n=this.opts.isRuntimePendingPermission;return!n||!e.downstream?!1:n(e.downstream)}async updateAgent(e){if(!e.cozeIdentity?.trim())return re.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,r=await fe(n);if(!r)throw new _("AGENT_NOT_FOUND",`agent not found: ${n}`);if(r.cozeIdentity===e.cozeIdentity)return re.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Pn(r.workspace,r.framework,e.cozeIdentity)}catch(i){throw re.error("_agent/update: writeInstructionFile failed, aborting update",{agentId:n,framework:r.framework,workspace:r.workspace,err:String(i)}),new _("AGENT_PROTOCOL_ERROR",`failed to write instruction file for agent ${n}: ${String(i)}`,{cause:i})}return r.cozeIdentity=e.cozeIdentity,await ke(r),re.info("_agent/update: cozeIdentity rewritten",{agentId:n,framework:r.framework}),this.reloadAgentSessions(n,"identity-changed"),{ok:!0}}async disconnectAgent(e){let n=e.agentId;if(!n)throw new _("IPC_BAD_REQUEST","_agent/disconnect: missing agentId");let r=await fe(n);return r?(r.disconnectedAt=Date.now(),r.disconnectReason=e.reason??"",await ke(r),re.info("agent disconnected",{agentId:n,reason:e.reason??"",force:e.force??!1}),this.opts.disposeAndMarkDisconnected&&await this.opts.disposeAndMarkDisconnected(n,e.reason??"disconnect"),{ok:!0}):(re.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async switchModel(e){if(_t(e._meta,"_agent/switchModel"),!e.agentId)throw new _("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=Za(e.model)??Ve,r=await fe(e.agentId);if(!r)throw new _("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);r.model=n,e.modelInfo&&(r.modelInfo=e.modelInfo),await ke(r),re.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,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=n,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: ${n}`).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:n,cloudSessions:s.length}),{ok:!0}}async resetAgent(e){if(_t(e._meta,Je.RESET),!e.agentId)throw new _("IPC_BAD_REQUEST",`${Je.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,Je.RESET),await this.runDetailSync(e.agentId,Je.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let r=this.opts.agents.get(e);if(!r){await this.clearPersistedAcpSessionIds(e),re.info("reset: agent not in memory, cleared persisted acpSessionIds only",{agentId:e});return}await r.killAllRuntimes(n);for(let s of r.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 r.sessions)i.set(s,{modelToken:o.modelToken,tokenGeneratedAt:o.tokenGeneratedAt});await Ir(e,i)}async clearPersistedAcpSessionIds(e){let n=await fe(e).catch(()=>null);if(!n?.sessions)return;let r=!1;for(let i of Object.values(n.sessions))i.acpSessionId&&(i.acpSessionId=void 0,r=!0);r&&await ke(n)}async repairAgent(e){if(_t(e._meta,Je.REPAIR),!e.agentId)throw new _("IPC_BAD_REQUEST",`${Je.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new _("IPC_BAD_REQUEST",`${Je.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(r){re.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(r)})}return await this.runDetailSync(e.agentId,Je.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,r){if(!this.opts.detailSyncer){re.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(i){re.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:r,err:String(i)})}}async getFileTree(e){_t(e._meta,"_agent/getFileTree");let n=e._meta,r=Vn(n),i=await this.resolveWorkspace(r),s=e.filePath??"",o=this.safeJoin(i,s),a=await Ya(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 Sr(o,i))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${s}`);let c=m_(e.depth);return a.isDirectory()?{tree:await g_(i,o,s,c)}:{tree:[{name:w_(s),path:ff(s||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){_t(e._meta,"_agent/getFileContent");let n=Vn(e._meta),r=await this.resolveWorkspace(n);if(!e.filePath)throw new _("IPC_BAD_REQUEST","filePath required");let i=this.safeJoin(r,e.filePath),s=await Ya(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 Sr(i,r))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(s.size>sf)throw new _("IPC_BAD_REQUEST",`file too large: ${s.size} bytes (max ${sf})`);let o=await of(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 n=this.opts.agents.get(e);return n?n.workspace:(await fe(e).catch(()=>null))?.workspace??Re(e).workspace}safeJoin(e,n){let r=tc(e,n||"."),i=rc(e,r);if(i.startsWith("..")||i===".."||i.startsWith(`..${af}`))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return r}loadAgentCfg(e){return fe(e)}async requireAgentCfg(e){let n=await this.loadAgentCfg(e);if(!n)throw new _("AGENT_NOT_FOUND",`no config for agent: ${e}`);return n}};function t_(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 n_(t){return t==="claude-code"?st(".claude","skills"):st(".agents","skills")}var r_=3e4,i_=50*1024*1024,Kn=3e4;async function ic(t){let{agentId:e,workspace:n,framework:r,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=t_(i.skillName),c=n_(r),l=st(c,a),d=st(n,l);if(await Qa(d,{recursive:!0}),s){let m=Buffer.from(i.content,"utf8");Yr(m.length),await ec(st(d,"SKILL.md"),m,"utf8")}else{let m=await o_(i.downloadUrl);c_(m)?await f_(m,d):l_(m)?await d_(m,d):await ec(st(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 sc(t,e,n){let r=e.get(n.skillId);if(r!==void 0){t[r]=n;return}e.set(n.skillId,t.length),t.push(n)}function s_(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 o_(t){if(!t)throw new _("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);Yr(e);let n=a_(t);return Yr(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await of(e);return Yr(n.length),n}if(xs(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),r_);try{let r=await fetch(t,{signal:e.signal});if(!r.ok)throw new _("IPC_BAD_REQUEST",`fetch skill failed HTTP ${r.status} ${t}`);let i=await r.arrayBuffer();return Yr(i.byteLength),Buffer.from(i)}finally{clearTimeout(n)}}throw new _("IPC_BAD_REQUEST",`unsupported downloadUrl scheme (\u8981 https/data/file): ${t.slice(0,80)}`)}function Yr(t){if(t>i_)throw new _("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function a_(t){let e=/^data:([^,;]*)(;base64)?,(.*)$/s.exec(t);if(!e)throw new _("IPC_BAD_REQUEST","bad data URL");let n=!!e[2],r=e[3]??"";return n?Buffer.from(r,"base64"):Buffer.from(decodeURIComponent(r),"utf8")}function c_(t){return t.length>=2&&t[0]===31&&t[1]===139}function l_(t){if(t.length<4||t[0]!==80||t[1]!==75)return!1;let e=t[2],n=t[3];return e===3&&n===4||e===5&&n===6}function nc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function d_(t,e){let n,r;try{n=new df.default(t),r=n.getEntries()}catch(o){throw new _("IPC_BAD_REQUEST",`zip parse failed: ${o.message}`,{cause:o})}for(let o of r){let a=o.entryName;if(!a||nc(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=u_(r),s=tc(e);for(let o of r){if(nc(o.entryName))continue;let a=o.entryName;if(i&&a.startsWith(i)&&(a=a.slice(i.length)),!a)continue;let c=tc(e,a),l=rc(s,c);if(l.startsWith("..")||l==="..")throw new _("IPC_BAD_REQUEST",`zip entry escapes destDir: ${a}`);if(o.isDirectory){await Qa(c,{recursive:!0});continue}await Qa(Ky(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 ec(c,d)}}function u_(t){let e;for(let n of t){let r=n.entryName;if(!r||nc(r))continue;let i=r.indexOf("/");if(i<=0)return;let s=r.slice(0,i+1);if(e===void 0)e=s;else if(e!==s)return}return e}async function f_(t,e){await h_(t);let n=zu({cwd:e,strip:1}),r=!1,i=setTimeout(()=>{r=!0,n.destroy(new _("IPC_BAD_REQUEST",`tar extract timeout (${Kn}ms)`))},Kn);try{await lf(cf.from(t),n)}catch(s){throw s instanceof _?s:r?new _("IPC_BAD_REQUEST",`tar extract timeout (${Kn}ms)`):new _("IPC_BAD_REQUEST",`tar extract failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}}async function h_(t){let e=[],n=Jn({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}`)}}),r=!1,i=setTimeout(()=>{r=!0,n.destroy(new _("IPC_BAD_REQUEST",`tar list timeout (${Kn}ms)`))},Kn);try{await lf(cf.from(t),n)}catch(s){throw r?new _("IPC_BAD_REQUEST",`tar list timeout (${Kn}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 p_=5e3;async function g_(t,e,n,r){return uf(t,e,n,r,{count:0})}async function uf(t,e,n,r,i){if(r<=0)return[];let s;try{s=await Jy(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let a of s){if(e_.has(a.name)||a.isSymbolicLink())continue;if(i.count>=p_){o.push({name:"...",path:"...",isDir:!1,size:0,modifiedAt:0,hasMore:!0});break}let c=st(e,a.name),l=Xy(st(n,a.name)),d=null;try{d=await Ya(c)}catch{continue}if(d.isSymbolicLink())continue;i.count++;let p={name:a.name,path:ff(rc(t,c)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&r>1&&(p.children=await uf(t,c,l,r-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 m_(t){return!t||t<=0?Yy:Math.min(t,Qy)}function w_(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function ff(t){return t.split(af).join("/")}L();import{readFileSync as mb}from"node:fs";import{dirname as yb,join as _b}from"node:path";import{fileURLToPath as Sb}from"node:url";var Xn="0.1.91-beta.1";var Ut=A("agent-health-reporter"),y_=1e4,Qr=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??y_}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()}),Ut.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Ut.info("heartbeat stopped"))}async tick(){if(this.inFlight){Ut.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Ut.debug("deviceId not available, skip tick (\u5C1A\u672A pair)");return}this.inFlight=!0;try{let n=[];for(let o of this.opts.core.agents.values()){let a=__(o);if(!a)continue;let c={agentId:o.agentId,status:a};o.patToken&&(c.patToken=o.patToken),o.accountId&&(c.accountId=o.accountId),n.push(c)}if(n.length===0)return;let r={agents:n,bridgeVersion:Xn,_meta:{cozeDeviceId:e}},i;try{i=await this.opts.core.sendRequest("_agent/health",r,5e3)}catch(o){Ut.warn("heartbeat batch send failed",{count:n.length,err:String(o)})}let s=i?.authFailures;if(s&&s.length>0&&(Ut.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){Ut.warn("onAuthFailures callback failed (ignored)",{err:String(o)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Ut.warn("onTickEnd hook failed",{err:String(n)})}}};function __(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}Rt();import{chmod as Q_,mkdir as Gs,rm as eE,stat as tE,writeFile as nE}from"node:fs/promises";import{homedir as rE}from"node:os";import{join as Cf}from"node:path";Xt();import{spawnSync as b_}from"node:child_process";function ei(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function Yn(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function Qn(t,e){return{jsonrpc:"2.0",id:t,result:e}}function zt(t,e){return{jsonrpc:"2.0",id:t,error:e}}Ie();var Ns=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)}},B={PARSE_ERROR:-32700,INVALID_REQUEST:-32600,METHOD_NOT_FOUND:-32601,INVALID_PARAMS:-32602,INTERNAL_ERROR:-32603,AGENT_NOT_FOUND:-32001,AGENT_BUSY:-32002,AGENT_TIMEOUT:-32003,AGENT_SPAWN_FAILED:-32004,OPERATION_NOT_ALLOWED_FOR_LOCAL:-32005,AGENT_DISCONNECTED:-32006,MODEL_TOKEN_GEN_FAILED:-32009,PATH_OUTSIDE_WORKSPACE:-32010,FILE_TOO_LARGE:-32011,UNSUPPORTED_MIME:-32012,UPLOAD_FAILED:-32013,UPSTREAM_NOT_READY:-32014,AGENT_FRAME_IDLE_TIMEOUT:-32016,MODEL_MODALITY_UNSUPPORTED:-32017,AGENT_DEPENDENCY_INSTALL_FAILED:-32018,AGENT_APPROVAL_TIMEOUT:-32019};function hf(t){return"method"in t&&"id"in t&&t.id!==void 0}function pf(t){return"method"in t&&!("id"in t)}function Ls(t){return!("method"in t)&&"id"in t}var E_={AGENT_NOT_FOUND:B.AGENT_NOT_FOUND,AGENT_BUSY:B.AGENT_BUSY,AGENT_DISCONNECTED:B.AGENT_DISCONNECTED,AGENT_TIMEOUT:B.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:B.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:B.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:B.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:B.INTERNAL_ERROR,BRIDGE_INTERNAL:B.INTERNAL_ERROR,IPC_AUTH_FAILED:B.INTERNAL_ERROR,IPC_BAD_REQUEST:B.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:B.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:B.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:B.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:B.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:B.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:B.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:B.FILE_TOO_LARGE,UNSUPPORTED_MIME:B.UNSUPPORTED_MIME,UPLOAD_FAILED:B.UPLOAD_FAILED,UPSTREAM_NOT_READY:B.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:B.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:B.AGENT_APPROVAL_TIMEOUT};function S_(t){if(t!=null)return t instanceof Error?{name:t.name,message:ti(t.message)}:typeof t=="string"?ti(t):typeof t=="object"?v_(t):t}var I_=[[/\/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 ti(t){let e=t;for(let[n,r]of I_)e=e.replace(n,r);return e}function v_(t){let e={};for(let[n,r]of Object.entries(t))typeof r=="string"?e[n]=ti(r):e[n]=r;return e}function ni(t){if(t instanceof _){let e=S_(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),{code:E_[t.code]??B.INTERNAL_ERROR,message:ti(t.message),data:n}}return{code:B.INTERNAL_ERROR,message:ti(t instanceof Error?t.message:String(t))}}function gf(t){let e=t.data,n=e?.bridgeCode??"AGENT_PROTOCOL_ERROR",r=!!e&&typeof e.message=="string"&&!!e.message,i=r?e?.message:t.message,s=t.data;if(r&&e){let{message:o,...a}=e;s=a}return new _(n,i,{retriable:e?.retriable??!1,cause:s})}function wf(t){return`${JSON.stringify(t)}
|
|
85
|
+
`}var mf=10*1024*1024,Fs=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>mf){let i=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${i} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${mf} bytes`)}),[]}let n=this.buffer.split(`
|
|
86
|
+
`);this.buffer=n.pop()??"";let r=[];for(let i of n){let s=i.replace(/\r$/,"").trim();if(s)try{r.push(JSON.parse(s))}catch(o){this.onError?.({line:s,error:o})}}return r}flush(){if(!this.buffer)return[];let e=this.buffer.replace(/\r$/,"").trim();if(this.buffer="",!e)return[];try{return[JSON.parse(e)]}catch(n){return this.onError?.({line:e,error:n}),[]}}};var _f={"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"},Cb=Object.fromEntries(Object.entries(_f).map(([t,e])=>[e,t])),T_={"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:[]},er=class{seq=0;next(e,n){this.seq+=1;let r=_f[e]??R_(e),i=T_[r]??[],s=[r,String(this.seq)];if(i.length>0){let o=i.map(c=>yf(n?.[c]??"")),a=k_(o).join(":");a&&s.push(a)}else n&&Object.values(n).some(o=>o)&&s.push(Object.values(n).filter(Boolean).map(o=>yf(String(o))).join(":"));return s.join("_")}reset(){this.seq=0}};function R_(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function yf(t){return t.replace(/[:_\s]+/g,"-")}function k_(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}ft();ki();Ie();L();var A_=ut("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),x_=200,O_=ut("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),P_=ut("COZE_BRIDGE_SESSION_PROMPT_FRAME_IDLE_MS",600*1e3),C_=ut("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ef=500;function D_(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ef?t:`${e.slice(0,Ef)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Sf(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),b_("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ot=class{constructor(e){this.opts=e;this.log=A(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Fs({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new er;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",n=Le(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=n,n.stdout?.setEncoding("utf8"),n.stdout?.on("data",r=>{try{for(let i of this.decoder.push(r))this.dispatch(i)}catch(i){this.log.warn("stdout dispatch threw, swallowed to keep daemon alive",{err:String(i)})}}),n.stderr?.setEncoding("utf8"),n.stderr?.on("data",r=>{let i=r.trimEnd();this.stderrRing.push(i),this.stderrRing.length>x_&&this.stderrRing.shift(),this.log.debug("stderr",{text:i})}),n.stdin?.on("error",r=>{this.log.warn("child stdin error",{err:String(r)})}),n.stdout?.on("error",r=>{this.log.warn("child stdout error",{err:String(r)})}),n.stderr?.on("error",r=>{this.log.warn("child stderr error",{err:String(r)})}),n.on("exit",(r,i)=>{this.stopped=!0,(r!==0||i!==null)&&this.stderrRing.length>0&&this.log.warn("downstream exited abnormally, recent stderr",{code:r,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 (${r}/${i})`));for(let o of this.exitHandlers)o(r,i)}),n.on("error",r=>{this.log.error("child error",{err:String(r)}),this.failAllPending(new _("AGENT_SPAWN_FAILED",String(r),{cause:r}))}),this.log.info("downstream started",{command:this.opts.command,pid:n.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 n=this.child,r=new Promise(s=>n.once("exit",()=>s()));Sf(n.pid,"SIGTERM");let i=setTimeout(()=>{n.killed||Sf(n.pid,"SIGKILL")},5e3);try{await r}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,n=O_,r=P_,i=C_){return this.call("session/prompt",e,n,r,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(Yn("session/cancel",e))}onUpdate(e){this.updateHandlers.push(e)}onAgentRequest(e){this.agentRequestHandlers.push(e)}respondAgentRequest(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(Qn(e,n))}catch(r){this.log.warn("respondAgentRequest write failed",{id:e,err:String(r)})}}respondAgentRequestError(e,n){if(this.inflightAgentRequests.delete(e),!(!this.child||this.stopped))try{this.writeFrame(zt(e,n))}catch(r){this.log.warn("respondAgentRequestError write failed",{id:e,err:String(r)})}}onExit(e){this.exitHandlers.push(e)}call(e,n,r=A_,i=0,s=0){if(!this.child||this.stopped)return Promise.reject(new _("AGENT_PROTOCOL_ERROR","downstream not started"));let o=this.idAllocator.next(e),a=ei(o,e,n),c=(()=>{if(typeof n!="object"||n===null)return;let p=n.sessionId;return typeof p=="string"?p:void 0})(),l=r>0&&Number.isFinite(r),d=i>0&&Number.isFinite(i);return new Promise((p,m)=>{let f={resolve:p,reject:m,timer:null,frameIdleTimer:null,armFrameIdle:null,method:e},h=Date.now();if(l){let w=()=>{f.timer=setTimeout(()=>{let S=Date.now()-h;if(this.inflightAgentRequests.size>0&&S<s){this.log.debug("hard cap fired but agent request inflight, extending to approval cap",{id:o,method:e,elapsed:S,approvalMaxMs:s,...c?{sessionId:c}:{}}),w();return}this.pending.delete(o),f.frameIdleTimer&&clearTimeout(f.frameIdleTimer);let v=this.inflightAgentRequests.size>0;this.log.warn("downstream call timeout",{id:o,method:e,timeoutMs:r,approvalMaxMs:s,awaitingApproval:v,...c?{sessionId:c}:{}}),m(v?new _("AGENT_APPROVAL_TIMEOUT",`${e} awaiting permission timed out after ${s}ms`):new _("AGENT_TIMEOUT",`${e} timed out after ${r}ms`))},r)};w()}let g=d?()=>{f.frameIdleTimer&&clearTimeout(f.frameIdleTimer),f.frameIdleTimer=setTimeout(()=>{if(this.inflightAgentRequests.size>0){this.log.debug("frame-idle fired but agent request inflight, re-arming",{id:o,method:e,inflight:this.inflightAgentRequests.size,...c?{sessionId:c}:{}}),g?.();return}f.timer&&clearTimeout(f.timer),this.pending.delete(o),this.log.warn("frame-idle timeout, rejecting pending call",{id:o,method:e,frameIdleMs:i,...c?{sessionId:c}:{}}),m(new _("AGENT_FRAME_IDLE_TIMEOUT",`${e} no session/update for ${i}ms (no inflight agent request)`))},i)}:null;f.armFrameIdle=g,this.pending.set(o,f),g?.();try{this.writeFrame(a)}catch(w){f.timer&&clearTimeout(f.timer),f.frameIdleTimer&&clearTimeout(f.frameIdleTimer),this.pending.delete(o),m(w)}})}writeFrame(e){if(!this.child?.stdin||this.child.stdin.destroyed)throw new _("AGENT_PROTOCOL_ERROR","downstream stdin not writable");this.child.stdin.write(wf(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Ls(e)){let n=e.id!==null?this.pending.get(e.id):void 0;if(!n){this.log.warn("orphan response",{id:e.id});return}this.pending.delete(e.id),n.timer&&clearTimeout(n.timer),n.frameIdleTimer&&clearTimeout(n.frameIdleTimer),e.error?(this.log.warn("downstream returned error frame",{id:e.id,method:n.method,code:e.error.code,message:e.error.message,data:e.error.data}),n.reject(gf(e.error))):e.result===void 0?(this.log.warn("downstream response missing both result and error",{id:e.id,method:n.method}),n.reject(new _("AGENT_PROTOCOL_ERROR",`${n.method} response missing both result and error`))):(this.log.info("downstream returned result",{id:e.id,method:n.method,result:D_(e.result)}),n.resolve(e.result));return}if(pf(e)){if(e.method==="session/update"){for(let n of this.pending.values())n.armFrameIdle?.();for(let n of this.updateHandlers)try{Promise.resolve(n(e.params)).catch(r=>this.log.warn("update handler failed (async)",{err:String(r)}))}catch(r){this.log.warn("update handler threw sync, swallowed",{err:String(r)})}}else this.log.info("unknown notification (drop, not forwarded)",{method:e.method});return}if(hf(e)){let n=e;try{this.handleAgentRequest(n).catch(r=>this.log.error("agent request handler failed (async)",{method:n.method,err:String(r)}))}catch(r){this.log.warn("handleAgentRequest threw sync, swallowed",{method:n.method,err:String(r)})}}}async handleAgentRequest(e){if(this.agentRequestHandlers.length===0){this.writeFrame(zt(e.id,{code:-32601,message:`method not handled by Bridge: ${e.method}`}));return}this.inflightAgentRequests.set(e.id,e.method);for(let n of this.agentRequestHandlers)try{await n(e)}catch(r){this.log.error("agentRequestHandler threw",{method:e.method,err:String(r)});try{this.writeFrame(zt(e.id,ni(r)))}catch{}this.inflightAgentRequests.delete(e.id)}}failAllPending(e){for(let n of this.pending.values())n.timer&&clearTimeout(n.timer),n.frameIdleTimer&&clearTimeout(n.frameIdleTimer),n.reject(e);this.pending.clear(),this.inflightAgentRequests.clear()}};function N_(t){let e={};for(let[n,r]of Object.entries(t))r!==void 0&&(n.startsWith("CLAUDE")||n==="AI_AGENT"||n==="BAGGAGE"||(e[n]=r));return e}var Ms=class extends ot{framework="claude-code";constructor(e){let n=Er("claude-code",e.command),r=e.args??[],i={command:n,args:r,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(i)}sanitizeEnv(e){return N_(e)}};Xt();import{mkdtempSync as L_,rmSync as F_}from"node:fs";import{tmpdir as M_}from"node:os";import{join as B_}from"node:path";var Bs=class extends ot{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=Er("codex",e.command),r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,s=e.isolateCodexHome?L_(B_(M_(),"coze-bridge-codex-home-")):void 0,o=s?{...e.env??{},CODEX_HOME:s}:e.env,a={command:n,args:i,cwd:e.cwd,agentId:e.agentId,...o?{env:o}:{}};super(a),this.authMethodId=e.authMethodId,this.codexHomeDir=s}async initialize(e){let n=await super.initialize(e);return this.authMethodId&&await this.call("authenticate",{methodId:this.authMethodId}),n}async stop(e){if(await super.stop(e),this.codexHomeDir)try{F_(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var U_=3e4,tr=class extends ot{framework="openclaw";agentId;sessionName;slashModelOnStart;constructor(e){let n=e.sessionName??"default",r=["acp","--session",`agent:${e.agentId}:${n}`];e.gatewayToken&&r.push("--token",e.gatewayToken);let i={command:e.command,args:r,cwd:e.cwd,agentId:e.agentId,...e.env?{env:e.env}:{}};super(i),this.agentId=e.agentId,this.sessionName=n,this.slashModelOnStart=e.slashModelOnStart}async afterSessionEstablished(e){this.slashModelOnStart&&(this.log.info("switching session to per-session provider via /model",{agentId:this.agentId,sessionName:this.sessionName,slash:this.slashModelOnStart}),await this.sessionPrompt({sessionId:e,prompt:[{type:"text",text:`/model ${this.slashModelOnStart}`}]},U_))}get acpSessionName(){return this.sessionName}};Ie();L();se();function oc(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}Xt();var $t=class{slots=[];running=!1;closed=!1;disposed=!1;enqueue(e){return this.disposed?Promise.reject(new Error("AsyncQueue disposed")):this.closed?Promise.reject(new Error("AsyncQueue closed")):new Promise((n,r)=>{this.slots.push({task:e,resolve:n,reject:r}),this.drain()})}close(){this.closed=!0}dispose(e=new Error("AsyncQueue disposed")){for(this.disposed=!0,this.closed=!0;this.slots.length>0;)this.slots.shift()?.reject(e)}get size(){return this.slots.length}get isRunning(){return this.running}get isDisposed(){return this.disposed}async drain(){if(!this.running){this.running=!0;try{for(;this.slots.length>0&&!this.disposed;){let e=this.slots.shift();if(!e)break;try{let n=await e.task();e.resolve(n)}catch(n){e.reject(n)}}}finally{this.running=!1}}}};var Us=class{agentId;framework;workspace;deployType;accountId;patToken;modelInfo;sessions=new Map;sessionQueues=new Map;activeTriggers=new Map;activeGroupIds=new Map;status="ok";model;lastActiveAt=Date.now();constructor(e){this.agentId=e.agentId,this.framework=e.framework,this.workspace=e.workspace,this.model=e.model,this.deployType=e.deployType??"local",e.accountId&&(this.accountId=e.accountId),e.patToken&&(this.patToken=e.patToken),e.modelInfo&&(this.modelInfo=e.modelInfo)}setPatToken(e){this.patToken=e}setModelInfo(e){this.modelInfo=e}getSessionQueue(e){let n=this.sessionQueues.get(e);return(!n||n.isDisposed)&&(n=new $t,this.sessionQueues.set(e,n)),n}allSessionQueues(){return this.sessionQueues.entries()}hasSessionQueue(e){let n=this.sessionQueues.get(e);return!!n&&!n.isDisposed}async dispose(e){this.status="stopped";let n=new Error(`AgentSession disposed${e?`: ${e}`:""}`);for(let r of this.sessionQueues.values())r.dispose(n);this.sessionQueues.clear(),await this.killAllRuntimes(e??"dispose")}async killAllRuntimes(e){let n=[];for(let[,r]of this.sessions)ri(r),r.downstream&&(n.push(r.downstream.stop(e).catch(()=>{})),r.downstream=void 0);await Promise.all(n),this.activeTriggers.clear(),this.activeGroupIds.clear()}};function ri(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}ft();L();import{promises as ac}from"node:fs";import{join as z_}from"node:path";var hn=A("agents.codex-sandbox-installer"),If="@openai/codex@0.135.0",vf="https://registry.npmmirror.com",cc="/usr/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex",$_="/usr/bin",Tf=["apply_patch","applypatch","codex-execve-wrapper","codex-linux-sandbox"],G_=9e4,H_=5e3,ii=null,Rf=!1;async function kf(t,e={}){if((e.platform??process.platform)!=="linux"||Rf)return;if(ii)return ii;let r=e.exec??bn,i=e.statFile??(async a=>{try{return await ac.stat(a),!0}catch{return!1}}),s=e.symlink??((a,c)=>ac.symlink(a,c)),o=e.unlink??(a=>ac.unlink(a));return ii=(async()=>{try{let a=!1;try{let{stdout:l}=await r("which",["codex"],{timeout:H_});a=l.trim().length>0}catch{a=!1}if(a)hn.info("codex already present, skip install");else{hn.info("codex not found, installing",{package:If,registry:vf});try{await r("npm",["i","-g",If,`--registry=${vf}`],{timeout:G_,maxBuffer:10*1024*1024,signal:t}),hn.info("codex install ok")}catch(l){hn.warn("codex install failed (skip symlinks)",{err:String(l)});return}}if(!await i(cc)){hn.warn("codex vendor bin not found, skip symlinks",{target:cc});return}let c=0;for(let l of Tf){let d=z_($_,l);try{await o(d).catch(()=>{}),await s(cc,d),c+=1,hn.info("codex sandbox symlink created",{link:d})}catch(p){hn.warn("codex sandbox symlink failed (ignored)",{link:d,err:String(p)})}}c===Tf.length&&(Rf=!0)}finally{ii=null}})(),ii}ft();L();import{constants as bf,access as j_}from"node:fs/promises";import{delimiter as W_,join as q_}from"node:path";var Gt=A("framework-detector"),Af={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},J_=[".exe",".cmd",".bat",".ps1"],Ht=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Le,access:e.access??j_}}async detect(e){let n=Af[e],r=await this.which(n);if(!r)return Gt.debug("framework binary not found",{framework:e,bin:n}),null;let i=e==="openclaw"?["--log-level","silent"]:[],[s,o]=await Promise.all([this.probeVersion(r,i),e==="openclaw"?this.probeOpenclawDefaultAgent(r):Promise.resolve(null)]),a={path:r,version:s};return o&&(a.defaultAgent=o),a}async detectAll(){let e=await Promise.all(Object.keys(Af).map(async r=>[r,await this.detect(r)])),n={};for(let[r,i]of e)i&&(n[r]=i);return n}async which(e){let n=this.env.pathEnv.split(W_).filter(Boolean),r=this.env.platform==="win32"?["",...J_]:[""];for(let i of n)for(let s of r){let o=q_(i,e+s);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?bf.F_OK:bf.X_OK;return await this.env.access(e,n),!0}catch{return!1}}async probeOpenclawDefaultAgent(e){let n=await this.runProbe(e,["--log-level","silent","agents","list","--json"]);if(!n)return Gt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return Gt.warn("openclaw default agent probe: non-zero exit",{path:e,code:n.code,stdoutHead:n.stdout.slice(0,200)}),null;let r=n.stdout.match(/\[\s*\{[\s\S]*\}\s*\]/);if(!r)return Gt.warn("openclaw default agent probe: regex no match (no JSON array in stdout)",{path:e,stdoutHead:n.stdout.slice(0,200)}),null;try{let i=JSON.parse(r[0]);if(!Array.isArray(i))return Gt.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?(Gt.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}:(Gt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:i.length}),null)}catch(i){return Gt.warn("openclaw default agent probe: JSON.parse failed",{path:e,err:String(i),matchHead:r[0].slice(0,200)}),null}}async probeVersion(e,n=[]){let r=await this.runProbe(e,[...n,"--version"]);return r&&(Z_(r.stdout).split(/\r?\n/)[0]??"").trim()||"unknown"}runProbe(e,n){return new Promise(r=>{let i="",s=!1,o,a=c=>{s||(s=!0,o&&clearTimeout(o),r(c))};try{let c=this.env.spawn(e,n,{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)}})}},V_=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function Z_(t){return t.replace(V_,"")}import{homedir as K_}from"node:os";import{join as X_}from"node:path";ft();Ie();Fi();L();async function Pf(){let t=X_(K_(),".openclaw/openclaw.json");return(await On(t))?.gateway?.auth?.token??""}var xf=A("openclaw.config"),Y_=[0,5e3,5e3],Of="models.providers.",zs="agents.defaults.models",$s=class{command;env;retryDelaysMs;queue=new $t;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??Y_}async withRetry(e,n){let r;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 n()}catch(o){r=o,xf.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: ${r?.message??"unknown"}`)}runCli(e){return new Promise((n,r)=>{let i=Le(this.command,e,{stdio:["ignore","pipe","pipe"],env:this.env}),s="";i.stderr?.on("data",o=>{s+=o.toString("utf8")}),i.on("error",r),i.on("close",o=>{o===0?n():r(new Error(`exit ${o}: ${s.trim().slice(0,500)}`))})})}async runCliTolerant(e,n){try{await this.runCli(e)}catch(r){let i=String(r);if(n.some(s=>i.includes(s)))return;throw r}}async bestEffortUnset(e,n){try{await this.queue.enqueue(()=>this.withRetry(e,()=>this.runCli(["config","unset",n])))}catch(r){xf.warn(`${e} failed (best-effort)`,{configPath:n,err:String(r)})}}ensureProvider(e,n){return this.queue.enqueue(()=>this.withRetry(`config set models.providers.${e}`,()=>this.runCli(["config","set",`${Of}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${Of}${e}`)}addModelToAllowlist(e,n){let r={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${zs}[${e}]`,()=>this.runCli(["config","set",zs,JSON.stringify(r),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${zs}[${e}]`,`${zs}.${e}`)}ensureAgent(e,n,r){let i=["agents","add",e,"--workspace",n,"--non-interactive"];return r&&i.push("--model",r),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 Z=A("agent-manager"),iE=(t,e,n,r,i,s,o,a,c)=>{switch(t){case"claude-code":{let l={...i?{...Yu(i),...tf(i,o,a)}:{},...c??{},IS_SANDBOX:"1"};return new Ms({cwd:n,env:l,agentId:r})}case"codex":{let d=[...i?[...Qu(i),...rf(i,o,a)]:[],"-c",'sandbox_mode="workspace-write"',"-c",'approval_policy="on-request"'],p={...i?ef(i):{},...c??{}},m=!!i;return new Bs({cwd:n,agentId:r,...d.length>0?{extraArgs:d}:{},...Object.keys(p).length>0?{env:p}:{},...m?{authMethodId:"openai-api-key",isolateCodexHome:!0}:{}})}case"openclaw":return new tr({command:e,cwd:n,agentId:r,...s?{sessionName:oc(s)}:{}})}};function lc(t){return t==="claude-code"||t==="codex"}function sE(t){let e=[],n=Object.keys(t).sort();for(let r of n){let i=t[r];i!==void 0&&(oE(i)||e.push(`${r}=${i}`))}return e.length===0?"":`${e.join(`
|
|
87
87
|
`)}
|
|
88
|
-
`}function
|
|
89
|
-
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var H_={path:"",version:"cloud-deployed"},j_={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},W_=6e4,Bs=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??z_,this.createTimeoutMs=e.createTimeoutMs??W_,this.detectorFactory=e.detectorFactory??(()=>new Gt),this.openclawConfigFactory=e.openclawConfigFactory??(r=>new Fs({command:r})),this.openclawConfigDir=e.openclawConfigDir??wh(U_(),".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=wh(e,".env");if(await M_(r).then(s=>s.isFile()).catch(()=>!1)){V.debug("openclaw .env exists, skip bootstrap",{envFile:r});return}await Ms(e,{recursive:!0});let i=$_(process.env);if(await B_(r,i,"utf8"),process.platform!=="win32")try{await L_(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=Hn(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(f=>V.warn("dispose stale agent failed (ignored)",{err:String(f)})),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 f=await ue(e.agentId,this.paths).catch(()=>null);f&&(f.patToken=e.patToken,await Te(f,this.paths))}if(n.deployType==="cloud"&&e.modelInfo){V.info("updating agent modelInfo on re-create",{agentId:e.agentId}),n.setModelInfo(e.modelInfo);let f=await ue(e.agentId,this.paths).catch(()=>null);f&&(f.modelInfo=e.modelInfo,await Te(f,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=ve(e.agentId,this.paths),o=Hn(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,h=!1;try{r&&Qa(e.framework)&&await vr(e.framework,d.signal);let f=()=>{if(d.signal.aborted)throw d.signal.reason instanceof Error?d.signal.reason:new _("AGENT_TIMEOUT","_agent/create aborted")};await Ms(s.root,{recursive:!0}),await Ms(l,{recursive:!0}),await Ms(s.logs,{recursive:!0}),f(),a||await Rr(l,e.framework,e.cozeIdentity),e.framework==="claude-code"&&await Ml(l),f();let g=await ue(e.agentId,this.paths).catch(()=>null),w=$u({model:e.model??g?.model}),E=Cu(e._meta)??g?.accountId,v=e.patToken??g?.patToken,u=o==="cloud"?e.modelInfo??g?.modelInfo:void 0;if(m=new Ns({agentId:e.agentId,framework:e.framework,workspace:l,model:w.model??qe,deployType:o,...E?{accountId:E}:{},...v?{patToken:v}:{},...u?{modelInfo:u}:{}}),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),h=!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),u&&(y.modelInfo=u),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=>Ka({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"?(Xa(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 Te(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(f){throw V.error("agent create failed, rolling back",{agentId:e.agentId,err:String(f)}),h&&m&&(await m.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await F_(s.root,{recursive:!0,force:!0}).catch(g=>V.warn("rm agent dir failed (ignored)",{err:String(g)})),f instanceof _?f:new _("AGENT_SPAWN_FAILED",String(f),{cause:f})}finally{clearTimeout(p)}}async spawnSessionDownstream(e,r,n,i,s){let a=this.config.frameworksCache?.[e.framework];if(!a)if(e.deployType==="cloud"&&Qa(e.framework))a=H_;else throw new _("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);if(Qa(e.framework)&&!fn(e.framework)){let d=xo(e.framework);V.info("spawn: ensuring acp wrapper installed",{agentId:e.agentId,framework:e.framework,reusingInFlight:!!d}),await vr(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(j_),l}catch(d){let p=l instanceof it?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=Ya(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 f=await this.detectorFactory().detect("openclaw");if(f?.defaultAgent?.id&&f?.defaultAgent?.workspace)V.info("openclaw lazy re-detect success",{agentId:f.defaultAgent.id,workspace:f.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=f,m=f.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 Vr({command:a,cwd:m.workspace,agentId:m.id,sessionName:c})}let l=await mh(),d=n?Ju(n,s,o):null,p;if(d){let m=Ha(i),f=d.models[0]?.id??qe,g=`${m}/${f}`;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 Vr({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=Ha(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 Ih}from"node:crypto";import{promises as Q_}from"node:fs";import{basename as vh}from"node:path";Ee();F();import{promises as J_}from"node:fs";import{basename as V_}from"node:path";var yh=x("file-upload"),Z_="/api/coze_claw/file/agent_upload",K_=6e4;async function _h(t,e={}){let n=`${Rs(bs(e.handshakeBase))}${Z_}`,i=e.timeoutMs??K_,s=await J_.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",...Hr(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},c=new AbortController,l=setTimeout(()=>c.abort(),i);yh.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 f=await d.text().catch(()=>"");throw new _("UPLOAD_FAILED",`upload HTTP ${d.status} logid=${p}: ${f.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 h=m.data?.file?.file_url;if(!h)throw new _("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${p}: ${JSON.stringify(m).slice(0,200)}`);return yh.info("file upload ok",{uri:h,logid:p}),{uri:h}}catch(d){throw d instanceof _?d:d.name==="AbortError"?new _("UPLOAD_FAILED",`upload timeout (${i}ms) for ${V_(t.path)}`):new _("UPLOAD_FAILED",String(d),{cause:d})}finally{clearTimeout(l)}}Ee();F();import{extname as X_}from"node:path";var Y_={".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 Eh(t){let e=X_(t).toLowerCase();return Y_[e]??"application/octet-stream"}se();var Us=x("agent-send"),Sh=50*1024*1024;function Th(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 Rh(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&&(Us.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 kh(t,e){let{session:r,runtime:n}=Th(e.core,t.agentId,t.sessionId);if(!await gn(t.path,r.workspace))throw new _("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${r.workspace}`);let i=await Q_.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>Sh)throw new _("FILE_TOO_LARGE",`${i.size} bytes > limit ${Sh}`);let s=await Eh(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??vh(t.path),a;try{a=await _h({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 Us.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:Ih(),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 Rh(e,r,n,t.sessionId,c,"agent file uploaded to cloud but sendAgentFileUpdate failed"),Us.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 bh(t,e){let{session:r,runtime:n}=Th(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??vh(t.path),s={sessionUpdate:"group_file",messageId:Ih(),content:{uri:t.path,name:i,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await Rh(e,r,n,t.sessionId,s,"agent group file sendAgentFileUpdate failed"),Us.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 Ah(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}Vt();Tt();F();var st=x("coze-cli-installer"),xh="@coze/cli@latest",eE="coze",Oh="0.1.8",tE=5e3,rE=5e3,nE=9e4,Ph=1e4,Qn=null,zs=!1;async function ec(t,e={}){if(zs)return;if(Qn)return Qn;let r=e.exec??ki;return Qn=(async()=>{try{let n=await iE(eE,r),i=!1;if(n){let o=await sE(r);if(o===void 0)st.warn("coze-cli found but version unparseable, fall through to full install",{path:n});else if(Ah(o,Oh))st.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:n,version:o,min:Oh}),i=!0;else{st.info("coze-cli already on PATH with sufficient version, skip",{path:n,version:o}),zs=!0;return}}let s=i?"upgrade-only":"full";st.info("coze-cli install start",{package:xh,mode:s});try{await r("npm",["i","-g","--prefer-online",xh],{timeout:nE,maxBuffer:10*1024*1024}),st.info("coze-cli install ok")}catch(o){st.warn("coze-cli install failed (skip subsequent steps)",{err:String(o)});return}if(i){zs=!0;return}if(t.env)try{await r("coze",["config","set","xTTEnv",t.env],{timeout:Ph}),st.info("coze config set xTTEnv ok",{env:t.env})}catch(o){st.warn("coze config set failed (continue to auth login)",{err:String(o)})}try{await r("coze",["auth","login","--token",t.patToken],{timeout:Ph}),st.info("coze auth login ok")}catch(o){st.warn("coze auth login failed",{err:String(o)});return}zs=!0}finally{Qn=null}})(),Qn}async function iE(t,e){let r=process.platform==="win32"?"where":"which";try{let{stdout:n}=await e(r,[t],{timeout:tE});return xi(n)}catch{return}}async function sE(t){try{let{stdout:e,stderr:r}=await t("coze",["--version"],{timeout:rE});return(e||r).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Pi();se();var oE=10*6e4;function Ch(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?oE:e}function $s(t){return Tr(t??N().configFile)}function Kr(t,e){return Oi(e??N().configFile,t)}import{randomBytes as kE}from"node:crypto";Ei();Ee();F();import{createReadStream as aE}from"node:fs";import{mkdir as cE,readFile as lE,realpath as dE,stat as uE,writeFile as hE}from"node:fs/promises";import{basename as fE,dirname as tc,isAbsolute as pE,join as gE,relative as mE,resolve as Dh,sep as wE}from"node:path";import{createInterface as yE}from"node:readline";var Lh=x("fs-rpc"),ei=vt("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Fh(t,e){let r=Buffer.byteLength(t.content,"utf8");if(r>ei)throw new _("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${r} bytes > limit ${ei} bytes`);let n=await Bh(t.path,e);return await cE(tc(n),{recursive:!0}),await hE(n,t.content,"utf8"),Lh.info("fs/write_text_file ok",{path:n,size:t.content.length}),null}async function Mh(t,e){let r=await Bh(t.path,e),n=await uE(r),i=typeof t.line=="number"||typeof t.limit=="number";if(n.size>ei&&!i)throw new _("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${n.size} bytes > ${ei} bytes`);let s;if(i&&n.size>ei)s=await _E(r,t.line??1,t.limit);else{let o=await lE(r,"utf8");if(i){let a=o.split(`
|
|
88
|
+
`}function oE(t){if(t.includes(`
|
|
89
|
+
`)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var aE={path:"",version:"cloud-deployed"},cE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},lE=6e4,Hs=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??iE,this.createTimeoutMs=e.createTimeoutMs??lE,this.detectorFactory=e.detectorFactory??(()=>new Ht),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new $s({command:n})),this.openclawConfigDir=e.openclawConfigDir??Cf(rE(),".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=>{Z.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=Cf(e,".env");if(await tE(n).then(s=>s.isFile()).catch(()=>!1)){Z.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}await Gs(e,{recursive:!0});let i=sE(process.env);if(await nE(n,i,"utf8"),process.platform!=="win32")try{await Q_(n,384)}catch(s){Z.warn("chmod ~/.openclaw/.env to 0600 failed (ignored)",{err:String(s)})}Z.info("openclaw .env bootstrapped",{envFile:n,bytes:i.length}),await this.getOpenclawConfig().restartGateway(),Z.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 n=Zr(e._meta)==="cloud";this.registry.reviveIfDisconnected?.(e.agentId);let r=this.registry.get(e.agentId);if(r){if(r.framework!==e.framework)throw new _("AGENT_BUSY",`agent ${e.agentId} exists with different framework (${r.framework})`);if(r.status==="error")Z.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await r.dispose("rebuild after error").catch(h=>Z.warn("dispose stale agent failed (ignored)",{err:String(h)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==r.patToken){Z.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),r.setPatToken(e.patToken);let h=await fe(e.agentId,this.paths).catch(()=>null);h&&(h.patToken=e.patToken,await ke(h,this.paths))}if(r.deployType==="cloud"&&e.modelInfo){Z.info("updating agent modelInfo on re-create",{agentId:e.agentId}),r.setModelInfo(e.modelInfo);let h=await fe(e.agentId,this.paths).catch(()=>null);h&&(h.modelInfo=e.modelInfo,await ke(h,this.paths))}return Z.info("agent already exists, return current",{agentId:e.agentId}),{ok:!0,agentId:r.agentId,workspace:r.workspace,framework:r.framework}}}if(!n&&!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=Re(e.agentId,this.paths),o=Zr(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{n&&lc(e.framework)&&(e.framework==="codex"?await Promise.all([Kt("codex",d.signal),kf(d.signal)]):await Kt(e.framework,d.signal));let h=()=>{if(d.signal.aborted)throw d.signal.reason instanceof Error?d.signal.reason:new _("AGENT_TIMEOUT","_agent/create aborted")};await Gs(s.root,{recursive:!0}),await Gs(l,{recursive:!0}),await Gs(s.logs,{recursive:!0}),h(),a||await Pn(l,e.framework,e.cozeIdentity),e.framework==="claude-code"&&await Jl(l),h();let g=await fe(e.agentId,this.paths).catch(()=>null),w=Ku({model:e.model??g?.model}),S=Gu(e._meta)??g?.accountId,v=e.patToken??g?.patToken,u=o==="cloud"?e.modelInfo??g?.modelInfo:void 0;if(m=new Us({agentId:e.agentId,framework:e.framework,workspace:l,model:w.model??Ve,deployType:o,...S?{accountId:S}:{},...v?{patToken:v}:{},...u?{modelInfo:u}:{}}),m.status="ok",g?.sessions){for(let[T,D]of Object.entries(g.sessions))m.sessions.set(T,{acpSessionId:D.acpSessionId,modelToken:D.modelToken,tokenGeneratedAt:D.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let R=Object.keys(g.sessions).length;R>0&&Z.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:R})}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"),S&&(y.accountId=S),v&&(y.patToken=v),u&&(y.modelInfo=u),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)):Z.warn("openclaw binary not on this machine, skip agents add (will fail at session/prompt)",{agentId:e.agentId}));let E=e.initialSkills??[];if(E.length>0){let R=[...y.skills??[]],T=new Map(R.map((U,I)=>[U.skillId,I])),D=await Promise.allSettled(E.map(U=>ic({agentId:e.agentId,workspace:l,framework:e.framework,skill:U}))),C=0;for(let[U,I]of D.entries()){let b=E[U];b&&(I.status==="fulfilled"?(sc(R,T,I.value),C++):Z.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:b.skillId,skillName:b.skillName,err:String(I.reason)}))}C>0&&(y.skills=R,Z.info("initialSkills installed",{agentId:e.agentId,installed:C,requested:E.length}))}return await ke(y,this.paths),Z.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(h){throw Z.error("agent create failed, rolling back",{agentId:e.agentId,err:String(h)}),f&&m&&(await m.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await eE(s.root,{recursive:!0,force:!0}).catch(g=>Z.warn("rm agent dir failed (ignored)",{err:String(g)})),h instanceof _?h:new _("AGENT_SPAWN_FAILED",String(h),{cause:h})}finally{clearTimeout(p)}}async spawnSessionDownstream(e,n,r,i,s){let a=this.config.frameworksCache?.[e.framework];if(!a)if(e.deployType==="cloud"&&lc(e.framework))a=aE;else throw new _("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);if(lc(e.framework)&&!_r(e.framework)){let d=Fo(e.framework);Z.info("spawn: ensuring acp wrapper installed",{agentId:e.agentId,framework:e.framework,reusingInFlight:!!d}),await Kt(e.framework)}let c=e.deployType==="cloud"?{model:e.model,modelToken:n,...e.modelInfo?{modelInfo:e.modelInfo}:{}}:void 0,l;e.framework==="openclaw"?l=await this.buildOpenclawDownstream({session:e,modelConfig:c,cloudSessionId:r,cozeEnv:i,mockScenario:s,command:a.path}):l=this.factory(e.framework,a.path,e.workspace,e.agentId,c,r,i,s,this.buildBinShimPathEnv());try{return await l.start(),await l.initialize(cE),l}catch(d){let p=l instanceof ot?l.getStderrTail():[];throw p.length>0&&Z.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:n,modelConfig:r,cloudSessionId:i,cozeEnv:s,mockScenario:o,command:a}=e,c=oc(i);if(n.deployType==="local"){let m=this.config.frameworksCache?.openclaw?.defaultAgent;if(!m?.id||!m.workspace){Z.warn("openclaw default agent stale or missing, attempting lazy re-detect");let h=await this.detectorFactory().detect("openclaw");if(h?.defaultAgent?.id&&h?.defaultAgent?.workspace)Z.info("openclaw lazy re-detect success",{agentId:h.defaultAgent.id,workspace:h.defaultAgent.workspace}),this.config.frameworksCache||(this.config.frameworksCache={}),this.config.frameworksCache.openclaw=h,m=h.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 tr({command:a,cwd:m.workspace,agentId:m.id,sessionName:c})}let l=await Pf(),d=r?nf(r,s,o):null,p;if(d){let m=Xa(i),h=d.models[0]?.id??Ve,g=`${m}/${h}`;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 tr({command:a,cwd:n.workspace,agentId:n.agentId,sessionName:c,...l?{gatewayToken:l}:{},...p?{slashModelOnStart:p}:{}})}async openclawRepair(e,n){let r=this.getOpenclawConfig();await r.deleteAgent(e),await r.ensureAgent(e,n)}async cleanupOpenclawSessionProviders(e){if(e.framework!=="openclaw"||!this.openclawConfigCache)return;let n=this.openclawConfigCache;for(let r of e.sessions.keys()){let i=Xa(r),s=`${i}/${e.model}`,o=!0;try{await n.removeProvider(i)}catch(a){o=!1,Z.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:i,err:String(a)})}try{await n.removeModelFromAllowlist(s)}catch(a){o=!1,Z.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:s,err:String(a)})}o&&this.ensuredProviders.delete(s)}}};import{randomUUID as Mf}from"node:crypto";import{promises as wE}from"node:fs";import{basename as Bf}from"node:path";Ie();L();import{promises as uE}from"node:fs";import{basename as fE}from"node:path";var Df=A("file-upload"),hE="/api/coze_claw/file/agent_upload",pE=6e4;async function Nf(t,e={}){let r=`${Os(Cs(e.handshakeBase))}${hE}`,i=e.timeoutMs??pE,s=await uE.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",...Zn(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},c=new AbortController,l=setTimeout(()=>c.abort(),i);Df.info("file upload start",{url:r,agentId:t.agentId,sessionId:t.sessionId,name:t.name,bytes:t.sizeBytes,mime:t.mimeType});try{let d=await fetch(r,{method:"POST",headers:a,body:o,signal:c.signal}),p=d.headers.get("x-tt-logid")??"";if(!d.ok){let h=await d.text().catch(()=>"");throw new _("UPLOAD_FAILED",`upload HTTP ${d.status} logid=${p}: ${h.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 Df.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 ${fE(t.path)}`):new _("UPLOAD_FAILED",String(d),{cause:d})}finally{clearTimeout(l)}}Ie();L();import{extname as gE}from"node:path";var mE={".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 Lf(t){let e=gE(t).toLowerCase();return mE[e]??"application/octet-stream"}se();var js=A("agent-send"),Ff=50*1024*1024;function Uf(t,e,n){let r=t.get(e);if(!r)throw new _("AGENT_NOT_FOUND",`agent=${e}`);if(t.disconnectedAgents.has(e))throw new _("AGENT_DISCONNECTED",`agent=${e} was disconnected by cloud`);let i=r.sessions.get(n);if(!i)throw new _("AGENT_NOT_FOUND",`session=${n} not active in agent=${e}`);return{session:r,runtime:i}}async function zf(t,e,n,r,i,s){let a;for(let c=0;c<=2;c++)try{await t.core.sendAgentFileUpdate(e,n,r,i);return}catch(l){a=l,c<2&&(js.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 $f(t,e){let{session:n,runtime:r}=Uf(e.core,t.agentId,t.sessionId);if(!await Sr(t.path,n.workspace))throw new _("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let i=await wE.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>Ff)throw new _("FILE_TOO_LARGE",`${i.size} bytes > limit ${Ff}`);let s=await Lf(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??Bf(t.path),a;try{a=await Nf({patToken:n.patToken??e.patToken,agentId:t.agentId,sessionId:t.sessionId,path:t.path,mimeType:s,name:o,sizeBytes:i.size,...n.accountId?{accountId:n.accountId}:{}},{handshakeBase:e.handshakeBase,ppeOverride:e.ppeOverride})}catch(l){throw js.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:Mf(),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 zf(e,n,r,t.sessionId,c,"agent file uploaded to cloud but sendAgentFileUpdate failed"),js.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 Gf(t,e){let{session:n,runtime:r}=Uf(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??Bf(t.path),s={sessionUpdate:"group_file",messageId:Mf(),content:{uri:t.path,name:i,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await zf(e,n,r,t.sessionId,s,"agent group file sendAgentFileUpdate failed"),js.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 Hf(t,e){let n=t.split(".").map(Number),r=e.split(".").map(Number),i=Math.max(n.length,r.length);for(let s=0;s<i;s++){let o=n[s]??0,a=r[s]??0;if(o<a)return!0;if(o>a)return!1}return!1}Xt();ft();L();var at=A("coze-cli-installer"),jf="@coze/cli@latest",yE="coze",Wf="0.1.8",_E=5e3,EE=5e3,SE=9e4,qf=1e4,si=null,Ws=!1;async function dc(t,e={}){if(Ws)return;if(si)return si;let n=e.exec??bn;return si=(async()=>{try{let r=await IE(yE,n),i=!1;if(r){let o=await vE(n);if(o===void 0)at.warn("coze-cli found but version unparseable, fall through to full install",{path:r});else if(Hf(o,Wf))at.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:r,version:o,min:Wf}),i=!0;else{at.info("coze-cli already on PATH with sufficient version, skip",{path:r,version:o}),Ws=!0;return}}let s=i?"upgrade-only":"full";at.info("coze-cli install start",{package:jf,mode:s});try{await n("npm",["i","-g","--prefer-online",jf],{timeout:SE,maxBuffer:10*1024*1024}),at.info("coze-cli install ok")}catch(o){at.warn("coze-cli install failed (skip subsequent steps)",{err:String(o)});return}if(i){Ws=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:qf}),at.info("coze config set xTTEnv ok",{env:t.env})}catch(o){at.warn("coze config set failed (continue to auth login)",{err:String(o)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:qf}),at.info("coze auth login ok")}catch(o){at.warn("coze auth login failed",{err:String(o)});return}Ws=!0}finally{si=null}})(),si}async function IE(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:r}=await e(n,[t],{timeout:_E});return Ni(r)}catch{return}}async function vE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:EE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Fi();se();var TE=10*6e4;function Jf(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?TE:e}function qs(t){return On(t??F().configFile)}function nr(t,e){return Li(e??F().configFile,t)}import{randomBytes as jE}from"node:crypto";ki();Ie();L();import{createReadStream as RE}from"node:fs";import{mkdir as kE,readFile as bE,realpath as AE,stat as xE,writeFile as OE}from"node:fs/promises";import{basename as PE,dirname as uc,isAbsolute as CE,join as DE,relative as NE,resolve as Vf,sep as LE}from"node:path";import{createInterface as FE}from"node:readline";var Kf=A("fs-rpc"),oi=ut("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function Xf(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>oi)throw new _("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${oi} bytes`);let r=await Qf(t.path,e);return await kE(uc(r),{recursive:!0}),await OE(r,t.content,"utf8"),Kf.info("fs/write_text_file ok",{path:r,size:t.content.length}),null}async function Yf(t,e){let n=await Qf(t.path,e),r=await xE(n),i=typeof t.line=="number"||typeof t.limit=="number";if(r.size>oi&&!i)throw new _("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${r.size} bytes > ${oi} bytes`);let s;if(i&&r.size>oi)s=await ME(n,t.line??1,t.limit);else{let o=await bE(n,"utf8");if(i){let a=o.split(`
|
|
90
90
|
`),c=Math.max(0,(t.line??1)-1),l=typeof t.limit=="number"?c+t.limit:void 0;s=a.slice(c,l).join(`
|
|
91
|
-
`)}else s=o}return
|
|
92
|
-
`)}async function Bh(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([Nh(Dh(e)),Nh(Dh(t))]),i=mE(r,n);if(EE(i,wE,pE(i)))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return n}function EE(t,e,r){return t===""?!1:r?!0:t===".."||t.startsWith(`..${e}`)}async function Nh(t){let e=[],r=t;for(;r!==tc(r);)try{let n=await dE(r);return e.length?gE(n,...e.reverse()):n}catch{e.push(fE(r)),r=tc(r)}return t}F();var Uh=x("prompt-multimodal"),zh=10*1024*1024,SE=15e3,IE=6;async function $h(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 vE(o))}}let i=Array.from({length:Math.min(IE,t.length)},()=>n());return await Promise.all(i),e}function Gh(t){return t.some(e=>e.type==="image")}async function vE(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!Ts(e.uri))return t;try{let{buf:r,contentType:n}=await RE(e.uri),i=e.mimeType||TE(n)||"application/octet-stream";return Uh.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 Uh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(r)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function TE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function RE(t){let e=new AbortController,r=setTimeout(()=>e.abort(),SE);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>zh)throw new Error(`image too large: ${i.byteLength} bytes (max ${zh})`);return{buf:Buffer.from(i),contentType:n.headers.get("content-type")??void 0}}finally{clearTimeout(r)}}Rt();Ee();F();var C=x("core"),bE=3e4,AE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,xE=3e4,Gs=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new Jr;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=Ch(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}),Yn(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(zt(i,{code:M.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:M.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:M.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(Os(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&&AE.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,M.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(qr(r,s));return}if(e.method.startsWith("session/")){let i=await this.routeSessionMethod(e);r!==null&&await this.upstream.send(qr(r,i));return}if(e.method==="initialize"){r!==null&&await this.upstream.send(qr(r,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}r!==null?await this.sendError(r,M.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(zt(r,Xn(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}=Nu(n);switch(r){case"session/new":{let s=OE();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=Du(n._meta);if(l?e.activeGroupIds.set(a.acpSessionId,l):e.activeGroupIds.delete(a.acpSessionId),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&Gh(s.prompt))throw new _("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let d=await $h(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(We.GEN_MODEL_TOKEN,n,xE);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(Yn(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(Yn(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(Zn("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(CE(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(Zn("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:M.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 Fh(s,i);r.respondAgentRequest(n.id,o)}else{let s=n.params??{},o=await Mh(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,Xn(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(h=>({optionId:h.optionId,kind:h.kind,name:h.name}))}),this.upstream.send(Vn(i,"session/request_permission",m)).catch(h=>{this.pendingUpstream.delete(i),C.error("forward permission request failed",{agentId:e.agentId,err:String(h)}),r.respondAgentRequestError(n.id,{code:M.INTERNAL_ERROR,message:`upstream send failed: ${String(h)}`})})}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"&&PE(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 xs(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=bE){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(Vn(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 mn(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(zt(e,{code:r,message:n,data:{bridgeVersion:Wr}}))}};function OE(){return kE(16).toString("hex")}function PE(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 CE(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();se();import{randomBytes as DE}from"node:crypto";import{chmod as NE,mkdir as LE,writeFile as Hh}from"node:fs/promises";import{createServer as FE}from"node:http";import{dirname as ME}from"node:path";var BE=1e6,rc=x("ipc"),Hs=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??N()}async start(){this.token=DE(32).toString("hex");let e=FE((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(),rc.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 LE(ME(this.paths.portFile),{recursive:!0}),await Hh(this.paths.portFile,String(this.port),"utf8"),await Hh(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await NE(this.paths.tokenFile,384)}catch(e){rc.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,r){if(e.headers.authorization!==`Bearer ${this.token}`){ti(r,401,{error:"unauthorized"});return}let i=`${e.method} ${(e.url??"").split("?")[0]}`,s=this.routes.get(i);if(!s){ti(r,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await UE(e)}catch(a){ti(r,400,{error:"invalid json",detail:String(a)});return}try{let a=await s.handler(o,e);ti(r,200,a??{ok:!0})}catch(a){rc.error("IPC handler failed",{key:i,err:String(a)}),ti(r,500,{error:a instanceof Error?a.message:String(a)})}}};function ti(t,e,r){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(r))}async function UE(t){let e=[],r=0;for await(let i of t){let s=i;if(r+=s.length,r>BE)throw new Error("body too large");e.push(s)}let n=Buffer.concat(e).toString("utf8");return n?JSON.parse(n):null}var Yh="";function XE(t=""){let r=`${Date.now()}`,n=Yh||(Yh=t0(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 QE(t){return(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8)}function Qh(t){return(Array(4).join("0")+parseInt(t,2).toString(16)).slice(-4)}function e0(t){let e=t.split(/\./).map(i=>QE(i)),r=[];return r[0]=Qh(e[0]+e[1]),r[1]=Qh(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",r[0],r[1]].join("")}function t0(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?e0(t):r?r0(t):"00000000000000000000000000000000"}function r0(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 f=o.substring(0,4-p[m].length).concat(p[m]);r.push(f)}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 n0(t,e){let r=t.key;r!==void 0&&(fe(e,10),ur(e,r));let n=t.value;n!==void 0&&(fe(e,18),ur(e,n))}function i0(t){let e={};e:for(;!pf(t);){let r=Ie(t);switch(r>>>3){case 0:break e;case 1:e.key=dr(t,Ie(t));break;case 2:e.value=dr(t,Ie(t));break;default:uf(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 df(t){let e=ff();return s0(t,e),u0(e)}function s0(t,e){let r=t.SeqID;r!==void 0&&(fe(e,8),ni(e,r));let n=t.LogID;n!==void 0&&(fe(e,16),ni(e,n));let i=t.service;i!==void 0&&(fe(e,24),ni(e,lc(i)));let s=t.method;s!==void 0&&(fe(e,32),ni(e,lc(s)));let o=t.headers;if(o!==void 0)for(let f of o){fe(e,42);let g=ff();n0(f,g),fe(e,g.limit),p0(e,g),l0(g)}let a=t.payloadEncoding;a!==void 0&&(fe(e,50),ur(e,a));let c=t.payloadType;c!==void 0&&(fe(e,58),ur(e,c));let l=t.payload;l!==void 0&&(fe(e,66),fe(e,l.length),f0(e,l));let d=t.LogIDNew;d!==void 0&&(fe(e,74),ur(e,d));let p=t.serverTiming;p!==void 0&&(fe(e,82),ur(e,p));let m=t.msgID;m!==void 0&&(fe(e,90),ur(e,m));let h=t.frameType;h!==void 0&&(fe(e,96),ni(e,lc(h)))}function o0(t){return a0(d0(t))}function a0(t){let e={};e:for(;!pf(t);){let r=Ie(t);switch(r>>>3){case 0:break e;case 1:e.SeqID=tf(t,!0);break;case 2:e.LogID=tf(t,!0);break;case 3:e.service=Ie(t);break;case 4:e.method=Ie(t);break;case 5:{let n=c0(t);(e.headers||(e.headers=[])).push(i0(t)),t.limit=n;break}case 6:e.payloadEncoding=dr(t,Ie(t));break;case 7:e.payloadType=dr(t,Ie(t));break;case 8:e.payload=h0(t,Ie(t));break;case 9:e.LogIDNew=dr(t,Ie(t));break;case 10:e.serverTiming=dr(t,Ie(t));break;case 11:e.msgID=dr(t,Ie(t));break;case 12:e.frameType=Ie(t);break;default:uf(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 c0(t){let e=Ie(t),r=t.limit;return t.limit=t.offset+e,r}function uf(t,e){switch(e){case 0:for(;128&Me(t););break;case 2:dc(t,Ie(t));break;case 5:dc(t,4);break;case 1:dc(t,8);break;default:throw new Error("Unimplemented type: "+e)}}function lc(t){return t|=0,{low:t,high:t>>31,unsigned:t>=0}}var hf=[];function ff(){let t=hf.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function l0(t){hf.push(t)}function d0(t){return{bytes:t,offset:0,limit:t.length}}function u0(t){let e=t.bytes,r=t.limit;return e.length===r?e:e.subarray(0,r)}function dc(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function pf(t){return t.offset>=t.limit}function oi(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 Ac(t,e){let r=t.offset;if(r+e>t.limit)throw new Error("Read past limit");return t.offset+=e,r}function h0(t,e){let r=Ac(t,e);return t.bytes.subarray(r,r+e)}function f0(t,e){let r=oi(t,e.length);t.bytes.set(e,r)}function dr(t,e){let r=Ac(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 ur(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}fe(t,n);let i=oi(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 p0(t,e){let r=oi(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 Me(t){return t.bytes[Ac(t,1)]}function ef(t,e){let r=oi(t,1);t.bytes[r]=e}function Ie(t){let e=0,r=0,n;do n=Me(t),e<32&&(r|=(127&n)<<e),e+=7;while(128&n);return r}function fe(t,e){for(e>>>=0;e>=128;)ef(t,127&e|128),e>>>=7;ef(t,e)}function tf(t,e){let r=0,n=0,i=0,s;return s=Me(t),r=127&s,128&s&&(s=Me(t),r|=(127&s)<<7,128&s&&(s=Me(t),r|=(127&s)<<14,128&s&&(s=Me(t),r|=(127&s)<<21,128&s&&(s=Me(t),n=127&s,128&s&&(s=Me(t),n|=(127&s)<<7,128&s&&(s=Me(t),n|=(127&s)<<14,128&s&&(s=Me(t),n|=(127&s)<<21,128&s&&(s=Me(t),i=127&s,128&s&&(s=Me(t),i|=(127&s)<<7))))))))),{low:r|n<<28,high:n>>>4|i<<24,unsigned:e}}function ni(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=oi(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 g0(t){return o0(t)}function rf(t){return df(t)}var nf=65536,m0="\0\0\0\0\0\0\0\0",Xr=nf*nf,gf=Xr*Xr,sf=gf/2,Ht=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===m0?of:new t((Ht.call(e,0)|Ht.call(e,1)<<8|Ht.call(e,2)<<16|Ht.call(e,3)<<24)>>>0,(Ht.call(e,4)|Ht.call(e,5)<<8|Ht.call(e,6)<<16|Ht.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?w0:of;if(r){if(e>=gf)return _0}else{if(e<=-sf)return E0;if(e+1>=sf)return y0}return t.fromBits(e%Xr|0,e/Xr|0,r)}toNumber(){return this.unsigned?(this.high>>>0)*Xr+(this.low>>>0):this.high*Xr+(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,h=0;return h+=s+l,m+=h>>>16,h&=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|h,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]}},of=new Oe(0,0,!1),w0=new Oe(0,0,!0),y0=Oe.fromBits(-1,2147483647,!1),_0=Oe.fromBits(-1,-1,!0),E0=Oe.fromBits(0,-2147483648,!1),lr=(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})({}),hr=class{constructor(e){this.type=e,this.target=null}},hc=class extends hr{constructor(e,r){super(e),this.message=r&&r.message||null}},fc=class extends hr{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}},pc=class extends hr{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}},gc=class extends hr{constructor(e,r){super(e),this.data=r&&r.data||null}},mc=class extends gc{constructor(e,r){super(e),this.data=r&&r.data||null,this.message=r&&r.message||null}},wc=class extends hr{constructor(e,r){super(e),this.data=r&&r.data||null}};function Je(t,{message:e,code:r,error:n}){return new fc(t,{message:e,code:r,error:n})}function ot(t,{code:e,reason:r,wasClean:n,willReconnect:i}){return new pc(t,{code:e,reason:r,wasClean:n,willReconnect:i})}function S0(t,{data:e,message:r}){return new mc(t,{data:e,message:r})}function I0(t,{data:e}){return new wc(t,{data:e})}function af(t,{message:e}){return new hc(t,{message:e})}var js=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()}},Qr=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",fr=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",ai=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",ii=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",v0=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,si=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}},yc=class extends si{_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,ai&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:r,header:n,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),fr&&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=ot("close",{reason:this._formatErrorMessage(e)});this.emit("close",n)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",I0("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",ot("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",S0("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 T0(t,e){if(e)return new e(t.url,t.protocol);if(ai||fr)return new yc(t.url,t.protocol,t.headers);if((Qr||ii)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(t.url,t.protocols)}function R0(t){return!!(t||ai&&wx.connectSocket||fr&&tt.connectSocket||(Qr||ii)&&typeof WebSocket<"u"&&WebSocket)}function cf(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 mf(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 wf(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 _c(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 yf(t){if(typeof t=="string"){let e=new Uint8Array(mf(t));return _c(t,e,0),e}return t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function k0(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 b0=(t,e)=>{switch(t){case"boe":case"ppe":return{[`x-use-${t}`]:1,"x-tt-env":e};default:return{}}},Ec=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 A0(t){return new Promise(e=>{if(!Qr)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 jt(t,e,r){return!!t?.find(n=>n.key===e&&n.value===r)}function Yr(t,e){return t?.find(r=>r.key===e)?.value}var uc=null;async function x0(){return uc||(uc=Promise.resolve().then(()=>(Xh(),Kh))),uc}var Sc=class extends si{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 x0();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}}},Ic=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}},vc=class{constructor(e,r){this._DBName=e,this._pathKey=r,this._qosDB=fr?tt:ai?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 _f(t,e){if(fr||fr)return new vc(t,e);if((Qr||ii)&&typeof indexedDB<"u")return new Sc(t,e);if((Qr||ii)&&typeof localStorage<"u")return new Ic(t,e);throw new Error("init QoSDB failed")}var Tc=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=_f("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 xc(t){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let r=jt(t.message.headers,"x_frontier_qos","2"),n=r&&jt(t.message.headers,"x_frontier_qos_ack","1"),i=r&&jt(t.message.headers,"x_frontier_is_ack","1"),s=i?Yr(t.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:r,isQoSAck:n,isAckCleanupMessage:i,ackMsgIds:s}}async function Ef(){return this._QoSManager||(this._QoSManager=new Tc),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function O0(t,e){let{enableAutoAck:r}=this._options,n=jt(t.message.headers,"need_ack","1"),i=jt(t.message.headers,"is_ack","1"),s=xc.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 P0(t,e){this._debug("received",t.message),e()}async function C0(t,e){let r=g0(await yf(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=wf(r.payload,0,r.payload.byteLength):r.textPayload=""}else r.textPayload=""}catch(n){r.textPayload="",console.log(n)}t.message=r,e()}function D0(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 N0=4294967295;function L0(t,e,r){if(r>N0)throw new Error("integer too large");let n=3;for(;n>=0;){let i=255&r;kc(i,t,e+n),r>>>=8,n--}return e+4}function F0(t,e){let r=0,n=e,i=e+4;for(;n<i;){let{value:s,offset:o}=Rc(t,n);n=o,r=r<<8>>>0,r+=s}return{value:r,offset:i}}function M0(t,e,r){return t?t.length<40?_c(t,e,r)+r:e.utf8Write?e.utf8Write(t,r)+r:e.write?e.write(t,r)+r:_c(t,e,r)+r:r}function B0(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 U0(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 Rc(t,e){return t.readUInt8?{value:t.readUInt8(e),offset:e+1}:{value:255&t[e],offset:e+1}}function kc(t,e,r){return e.writeUint8?e.writeUint8(t,r):e[r]=255&t,r+1}var z0=function(t){return new Uint8Array(t)},$0=typeof Buffer<"u"?Buffer.allocUnsafe:D0(z0,Uint8Array.prototype.subarray),G0=16,Oc=32;function H0(t){let e=0,r={};for(let n=0;n<t.length;n++)r[t[n].cursor_name]=mf(t[n].cursor_name),e+=14+r[t[n].cursor_name];return[e,r]}function lf(t,e,r){let[n,i]=H0(t),s=$0(n),o=0;return t.forEach(a=>{console.log("cursor.service",a,a.service),o=kc(0,s,o),console.log("header",o),o=L0(s,o,a.service||0),console.log("service",o),o=kc(i[a.cursor_name],s,o),console.log("service-name",o),o=M0(a.cursor_name,s,o),console.log("name",o),o=U0(Oe.fromNumber(a.cursor||e),s,o),console.log("curvalue",o)}),{frameType:Oc,headers:[{key:"cursor_file_name",value:r}],payload:s}}function j0(t){let e=0,r=[];for(;e<t.byteLength;){let{offset:n}=Rc(t,e);e=n;let i={cursor_name:"",cursor:0,service:0},{value:s,offset:o}=F0(t,e);i.service=s,e=o;let{value:a,offset:c}=Rc(t,e);e=c,i.cursor_name=wf(t,e,e+a),e+=a;let{value:l,offset:d}=B0(t,e);i.cursor=l.toNumber(),e=d,r.push(i)}return r}function W0(){return{frameType:Oc,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var bc=class{constructor(e,r,n){this._cursorNameSpace=e,this._cursorFileName=r,this._messageStrategy=n,this._qosDB=_f(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?lf(r,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return r&&r.length?lf(r,0,this._cursorFileName):W0()}}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=j0(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}},q0="__x_msg_qos__";async function Sf(t){if(!this._options.enableQoS)return null;let{aID:e,fpID:r,messageStrategy:n}=this._options,i=t||q0;try{return this._cursorManager?t&&this._cursorManager.updateCursorFileName(t):this._cursorManager=new bc(`${r}_${e}_${i}`,i,n),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function J0(t,e){let r=jt(t.message.headers,"code","-1"),n=jt(t.message.headers,"is_ack","1"),i=Yr(t.message.headers,"x_frontier_msgid"),s=Number(Yr(t.message.headers,"x_frontier_ttl"))||0,o=xc.call(this,t),a=jt(t.message.headers,"x-msg-qos","2"),c=Yr(t.message.headers,"x-msg-cursor_name"),l=Number(Yr(t.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await Ef.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 Sf.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 V0(t,e){let r=xc.call(this,t);if(!r.isQoSMessage)return e();let n=await Ef.call(this);if(r.isAckCleanupMessage&&r.ackMsgIds.length)for(let i of r.ackMsgIds)await n.del(i);e()}async function Z0(t,e){let r=t.message.frameType===G0,n=t.message.frameType===Oc;if(!r&&!n)return e();let i=Yr(t.message.headers,"cursor_file_name");if(!i)return e();let s=await Sf.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=df(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(n){let o=t.message.payload;o&&s.setCursors(o)}}var K0=async function(t,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},X0=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()},Ws=class extends si{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=Qr,this._isNode=v0,this._isMiniTT=fr,this._isMiniWX=ai,this._isWorker=ii,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{cf(this,s,[K0,Y0,X0])}catch(o){let a=Je("error",{message:o.message,code:lr.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{cf(this,s,[C0,O0,V0,Z0,J0,P0])}catch(c){let l=Je("error",{message:c.message,code:lr.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:lr.MAX_RETRIES_ERROR,error:s}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Je("error",{message:s.message,code:lr.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(ot("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(ot("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 A0(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(ot("close",{code:s.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(Je("error",{message:l,code:lr.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&!s.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(ot("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(!R0(n))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new js(i,this._options.maxRetries),this._pingLossCounter=new Ec(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=af("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,h,f,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(h=location&&location.protocol=="https:"?"wss://":"ws://",f=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${h}${f}`):(h="wss://",f=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(f)?f:`${h}${f}`);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,u=m?b0(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,...u},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:lr.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:lr.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=af("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=T0({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=rf(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(ot("close",{code:1006,reason:`connect ${s} timeout, max retries reached`,wasClean:!0}))}else{let s=this._options.reconnectInterceptor(e,r);this._dispatchCloseEvent(ot("close",{code:e,reason:r,wasClean:!0,willReconnect:s})),s&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(ot("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(ot("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 yf(e),i=k0(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?XE(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},h=rf(m);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(h),this._debug("sent",m)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(h),this._debug("enqueue",m)):(this._messageQueue.shift(),this._messageQueue.push(h)),{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 js(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 yI=dt(mp(),1),_I=dt(eo(),1),EI=dt(rn(),1),SI=dt($c(),1),II=dt(jc(),1),vI=dt(Kc(),1),Rp=dt(io(),1),TI=dt(Tp(),1);var kp=Rp.default;Ee();F();var ie=x("upstream.frontier"),Ap="application/json",xp="none",kI=15e3,gi=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){ie.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:Mu,...Hr(this.opts.ppeOverride)};class r extends kp{constructor(f){super(f,Fu,{headers:e})}send(f,...g){if(wl("debug"))try{let w;typeof f=="string"?w=Buffer.from(f,"utf8"):f instanceof Buffer?w=f:f instanceof ArrayBuffer?w=new Uint8Array(f):ArrayBuffer.isView(f)?w=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):w=new Uint8Array(0);let E=Buffer.from(w.slice(0,128)).toString("hex");ie.debug("WS raw frame out",{bytes:w.byteLength,headHex:E})}catch(w){ie.warn("WS raw frame dump failed",{err:String(w)})}super.send(f,...g)}}let n=Uu(this.opts.urlOverride),i={url:n,ws:r,fpID:Lu,aID:ks,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Ap,force:!0},payloadEncoding:{encoding:xp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},s=new Ws(i),o=!1,a=null,c,l,d=new Promise((h,f)=>{c=h,l=f}),p=h=>{o||(o=!0,a&&(clearTimeout(a),a=null),h?l(h):c())};s.onopen=()=>{this.opened=!0,this.openCount+=1;let h=this.openCount===1;ie.info("frontier opened",{url:n,remoteDeviceId:this.opts.handshake.deviceId,initial:h,openCount:this.openCount}),h&&p();for(let f of this.connectHandlers)Promise.resolve(f({initial:h})).catch(g=>ie.warn("onConnect handler threw (ignored)",{err:String(g)}))},s.onclose=h=>{this.opened=!1,ie.info("frontier closed",{code:h.code,reason:h.reason,willReconnect:h.willReconnect})},s.onerror=h=>{ie.warn("frontier error",{code:h.code,msg:h.message}),p(new _("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${h.code} msg=${h.message??""}`))},s.onmessage=h=>this.handleMessage(h),this.fws=s;let m=this.opts.openTimeoutMs??kI;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(h){try{s.close(1e3,"open failed")}catch(f){ie.warn("fws close during start failure threw (ignored)",{err:String(f)})}throw this.fws=null,this.opened=!1,h}}async stop(e){let r=this.fws;if(r){this.fws=null,this.opened=!1;try{r.close(1e3,e??"bridge shutdown")}catch(n){ie.warn("frontier close threw (ignored)",{err:String(n)})}}}async send(e){let r=this.fws,n=e.method;if(!r)throw ie.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?(ie.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;Op(s)||ie.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:i.length});try{await r.send(i,{service:33555712,method:1,payloadType:Ap,payloadEncoding:xp})}catch(a){throw ie.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){ie.debug("drop non-adapter frontier frame",{service:r});return}let n=xI(e);if(!n){ie.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ie.debug("frame received but no onFrame handler",{size:n.length});return}let i;try{i=JSON.parse(n)}catch(o){ie.warn("frontier message JSON parse failed",{err:String(o),head:n.slice(0,80)});return}let s=i;Op(s)||ie.info("frontier frame in",{logid:AI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id,method:s.method,body:bI(n)}),Promise.resolve(this.handler(i)).catch(o=>ie.warn("frontier frame handler threw",{err:String(o)}))}};function Op(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Pp=2e3;function bI(t){return t.length<=Pp?t:`${t.slice(0,Pp)}...<truncated, total ${t.length} chars>`}function AI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function xI(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 Yc=x("upstream.switchable"),oo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,r){if(this.inner===e)return;Yc.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 Yc.error("swap target start failed, reverting",{err:String(i)}),this.inner=n,i}await n.stop(r??"swapped").catch(i=>Yc.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 Qc=x("upstream"),ln=class{handler=null;async start(){Qc.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Qc.info("NoopUpstream stopped",{reason:e})}async send(e){Qc.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)}};Ee();F();F();se();import{promises as el}from"node:fs";import{dirname as OI}from"node:path";var PI=x("pat-token-store");async function Cp(t=N()){try{let r=(await el.readFile(t.patTokenFile,"utf8")).trim();return r.length>0?r:null}catch(e){let r=e?.code;return r!=="ENOENT"&&PI.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:r,message:e.message}),null}}async function mi(t,e=N()){if(!t)throw new Error("writePatToken: empty patToken");await el.mkdir(OI(e.patTokenFile),{recursive:!0}),await el.writeFile(e.patTokenFile,t,{encoding:"utf8",mode:384})}se();se();import{promises as ao}from"node:fs";import{join as CI}from"node:path";function DI(t,e){return`#!/bin/sh
|
|
91
|
+
`)}else s=o}return Kf.info("fs/read_text_file ok",{path:n,size:s.length}),{content:s}}async function ME(t,e,n){let r=FE({input:RE(t,{encoding:"utf8"}),crlfDelay:Number.POSITIVE_INFINITY}),i=Math.max(0,e-1),s=typeof n=="number"?i+n:Number.POSITIVE_INFINITY,o=[],a=0;try{for await(let c of r)if(a>=i&&a<s&&o.push(c),a++,a>=s)break}finally{r.close()}return o.join(`
|
|
92
|
+
`)}async function Qf(t,e){if(typeof t!="string"||t.length===0)throw new _("IPC_BAD_REQUEST","path must be a non-empty string");let[n,r]=await Promise.all([Zf(Vf(e)),Zf(Vf(t))]),i=NE(n,r);if(BE(i,LE,CE(i)))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return r}function BE(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function Zf(t){let e=[],n=t;for(;n!==uc(n);)try{let r=await AE(n);return e.length?DE(r,...e.reverse()):r}catch{e.push(PE(n)),n=uc(n)}return t}L();var eh=A("prompt-multimodal"),th=10*1024*1024,UE=15e3,zE=6;async function nh(t){let e=new Array(t.length),n=0;async function r(){for(;n<t.length;){let s=n++,o=t[s];o!==void 0&&(e[s]=await $E(o))}}let i=Array.from({length:Math.min(zE,t.length)},()=>r());return await Promise.all(i),e}function rh(t){return t.some(e=>e.type==="image")}async function $E(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!xs(e.uri))return t;try{let{buf:n,contentType:r}=await HE(e.uri),i=e.mimeType||GE(r)||"application/octet-stream";return eh.info("image uri fetched and inlined",{uri:e.uri,bytes:n.length,mimeType:i}),{type:"image",data:n.toString("base64"),mimeType:i}}catch(n){return eh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function GE(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function HE(t){let e=new AbortController,n=setTimeout(()=>e.abort(),UE);try{let r=await fetch(t,{signal:e.signal});if(!r.ok)throw new Error(`HTTP ${r.status} ${r.statusText}`);let i=await r.arrayBuffer();if(i.byteLength>th)throw new Error(`image too large: ${i.byteLength} bytes (max ${th})`);return{buf:Buffer.from(i),contentType:r.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}Rt();Ie();L();var P=A("core"),WE=3e4,qE=/^(boe|ppe)_[A-Za-z0-9_-]+$/,JE="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",VE="\u5BA1\u6279\u5DF2\u8D85\u65F6",ZE=3e4,Js=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new er;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=Jf(e.bridgeConfig)}registerExtension(e,n){this.extensions[e]=n}getCozeEnv(){return this.currentCozeEnv}getMockScenario(){return this.currentMockScenario}setMockScenario(e){this.currentMockScenario=e&&e.length>0?e:void 0}async start(){this.upstream.onFrame(e=>this.handleFrame(e)),this.upstream.onConnect?.(({initial:e})=>{e||this.rejectAllPendingOnReconnect()}),await this.upstream.start(),P.info("Core started",{extensions:Object.keys(this.extensions)})}async stop(e){P.info("Core stopping",{reason:e}),await Promise.all([...this.agents.values()].map(n=>n.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),P.info("agent registered",{agentId:e.agentId,framework:e.framework});for(let n of this.registerHandlers)try{n(e.agentId)}catch(r){P.warn("onAgentRegister handler threw (ignored)",{agentId:e.agentId,err:String(r)})}}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)&&P.info("agent revived from disconnect",{agentId:e})}attachRuntimeHooks(e,n,r){let i=r.downstream;i&&(i.onUpdate(s=>{r.loadingSession||this.forwardUpdate(e,s)}),i.onAgentRequest(s=>{this.handleAgentRequest(e,i,s)}),i.onExit((s,o)=>{P.info("session runtime exited",{agentId:e.agentId,cloudId:n,code:s,signal:o}),ri(r),r.downstream=void 0,r.replySeq=0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId),this.rejectPendingForDownstream(i,"downstream exited")}))}hasPendingPermissionFor(e){for(let n of this.pendingUpstream.values())if(n.downstream===e)return!0;return!1}rejectPendingForDownstream(e,n){let r=[];for(let[i,s]of this.pendingUpstream)s.downstream===e&&r.push(i);if(r.length!==0){P.info("reject pendingUpstream entries (downstream gone)",{reason:n,count:r.length});for(let i of r){let s=this.pendingUpstream.get(i);if(s){this.pendingUpstream.delete(i),this.upstream.send(zt(i,{code:B.INTERNAL_ERROR,message:`bridge downstream gone: ${n}`})).catch(o=>P.debug("send error response to upstream failed (ignored)",{err:String(o)}));try{s.downstream.respondAgentRequestError(s.agentRequestId,{code:B.INTERNAL_ERROR,message:`bridge: ${n}`})}catch{}}}}}rejectAllPendingOnReconnect(){let e=this.pendingUpstream.size,n=this.pendingBridge.size;if(!(e===0&&n===0)){P.warn("upstream reconnected, rejecting stale pending requests",{pendingUpstream:e,pendingBridge:n});for(let[,r]of this.pendingUpstream){try{r.downstream.respondAgentRequestError(r.agentRequestId,{code:B.INTERNAL_ERROR,message:"upstream reconnected; please retry"})}catch{}this.clearPendingPermissionFor(r)}this.pendingUpstream.clear();for(let[,r]of this.pendingBridge)clearTimeout(r.timer),r.reject(new _("UPSTREAM_DISCONNECTED",`${r.method} aborted: upstream reconnected`));this.pendingBridge.clear()}}async handleFrame(e){if(Ls(e)){this.handleUpstreamResponse(e);return}if(!("method"in e)||typeof e.method!="string")return;let n="id"in e&&e.id!==void 0?e.id:null,r=e.params?._meta?.cozeEnv;r&&qE.test(r)?this.currentCozeEnv=r:r&&P.warn("rejecting cozeEnv with invalid shape, keeping previous",{rejected:r});try{if(e.method.startsWith("_agent/")){let i=this.extensions[e.method];if(!i){n!==null?await this.sendError(n,B.METHOD_NOT_FOUND,`extension not registered: ${e.method}`):P.warn("drop notification: extension not registered",{method:e.method});return}let s=await i(e,this);n!==null&&await this.upstream.send(Qn(n,s));return}if(e.method.startsWith("session/")){let i=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(Qn(n,i));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(Qn(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,B.METHOD_NOT_FOUND,`method not implemented: ${e.method}`):P.warn("drop unknown notification",{method:e.method})}catch(i){P.error("handleFrame failed",{method:e.method,err:String(i)}),n!==null&&await this.upstream.send(zt(n,ni(i)))}}async routeSessionMethod(e){if(!e.params||typeof e.params!="object")throw new _("IPC_BAD_REQUEST",`${e.method} requires params`);let n=e.params,r=n._meta?.cozeAgentId;if(!r)throw new _("IPC_BAD_REQUEST",`${e.method}: missing _meta.cozeAgentId`);let i=this.agents.get(r);if(!i)throw this.disconnectedAgents.has(r)?new _("AGENT_DISCONNECTED",`agent ${r} has been disconnected; cloud must _agent/create to revive`):new _("AGENT_NOT_FOUND",`agent not found: ${r}`);let s=typeof n.sessionId=="string"?n.sessionId:void 0;if(e.method==="session/cancel"||e.method==="session/new"||!s)return this.dispatchSessionCall(i,e.method,n);if(e.method==="session/prompt"){let c=i.sessions.get(s);if(c?.pendingPermission){let l=n._meta?.cozeTriggerMsgId,d=qa(n._meta);return P.info("session in pendingPermission, bouncing new prompt",{agentId:i.agentId,cloudSessionId:s}),this.synthesizePromptReply(i,c,s,JE,l,d)}}let o=Date.now(),a=!1;try{let c=await i.getSessionQueue(s).enqueue(()=>this.dispatchSessionCall(i,e.method,n));return a=!0,c}finally{P.info("session call done",{agentId:i.agentId,method:e.method,durationMs:Date.now()-o,ok:a})}}async dispatchSessionCall(e,n,r){e.lastActiveAt=Date.now();let{stripped:i}=Hu(r);switch(n){case"session/new":{let s=KE();return P.info("session/new ack (lazy spawn)",{agentId:e.agentId,cloudId:s}),{sessionId:s}}case"session/load":{let s=i;return P.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=r._meta?.cozeTriggerMsgId;c?e.activeTriggers.set(a.acpSessionId,c):e.activeTriggers.delete(a.acpSessionId);let l=qa(r._meta);if(l?e.activeGroupIds.set(a.acpSessionId,l):e.activeGroupIds.delete(a.acpSessionId),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&rh(s.prompt))throw new _("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let d=await nh(s.prompt);try{let p=await a.downstream.sessionPrompt({...s,sessionId:a.acpSessionId,prompt:d});return a.lastActiveAt=Date.now(),p}catch(p){if(p instanceof _&&p.code==="AGENT_APPROVAL_TIMEOUT"){let m=a.pendingPermission;m&&(m.downstream.respondAgentRequest(m.agentRequestId,{outcome:{outcome:"cancelled"}}),this.pendingUpstream.delete(m.upstreamId),a.pendingPermission=void 0);let f=a.acpSessionId,h=f?e.activeTriggers.get(f):void 0,g=f?e.activeGroupIds.get(f):void 0;return P.warn("approval timed out, synthesizing \u5BA1\u6279\u5DF2\u8D85\u65F6 reply + recovering session",{agentId:e.agentId,cloudId:o}),await this.synthesizePromptReply(e,a,o,VE,h,g)}throw p}finally{if(e.activeTriggers.delete(a.acpSessionId),e.activeGroupIds.delete(a.acpSessionId),a.pendingPermission=void 0,a.reloadAfterTurn){a.reloadAfterTurn=!1;let p=a.downstream;p&&(a.downstream=void 0,P.info("reloadAfterTurn: stopping downstream",{agentId:e.agentId,cloudId:o,acpId:a.acpSessionId}),p.stop("reload-after-turn").catch(m=>P.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&&(P.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: ${n}`)}}async ensureRuntime(e,n){let r=e.sessions.get(n);if(r)return r;let s={modelToken:e.deployType==="cloud"?await this.requestSessionToken(e.agentId,n):"",tokenGeneratedAt:Date.now(),lastActiveAt:Date.now(),loadingSession:!1,replySeq:0};return e.sessions.set(n,s),await this.persistSessionMapping(e),s}async requestSessionToken(e,n){let r={sessionId:n,_meta:{cozeAgentId:e}};try{let i=await this.sendRequest(Je.GEN_MODEL_TOKEN,r,ZE);if(!i?.modelToken)throw new _("MODEL_TOKEN_GEN_FAILED",`cloud returned empty modelToken (agentId=${e}, cloudSessionId=${n})`);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,n,r){if(ri(r),r.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=r.spawnFailCount??0,a=r.spawnFailedAt??0;if(o>=i&&Date.now()-a<s)throw new _("AGENT_SPAWN_FAILED",`agent ${e.agentId} session ${n} 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,r.modelToken,n,this.currentCozeEnv,this.currentMockScenario)}catch(l){throw r.spawnFailCount=o+1,r.spawnFailedAt=Date.now(),r.spawnFailCount>=i&&r.acpSessionId&&(P.warn("clearing stale acpSessionId after repeated spawn failures",{agentId:e.agentId,cloudId:n,staleAcpId:r.acpSessionId}),r.acpSessionId=void 0),l}if(r.spawnFailCount=0,r.spawnFailedAt=void 0,r.downstream=c,this.attachRuntimeHooks(e,n,r),r.acpSessionId){r.loadingSession=!0;try{await c.sessionLoad({sessionId:r.acpSessionId,cwd:e.workspace}),P.info("session restored via session/load",{agentId:e.agentId,cloudId:n,acpId:r.acpSessionId})}catch(l){P.warn("session/load failed, fallback to session/new",{agentId:e.agentId,cloudId:n,acpId:r.acpSessionId,err:String(l)}),r.acpSessionId=void 0;let d=await c.sessionNew({cwd:e.workspace});r.acpSessionId=d.sessionId,await this.persistSessionMapping(e)}finally{r.loadingSession=!1}}else{let l=await c.sessionNew({cwd:e.workspace});r.acpSessionId=l.sessionId,await this.persistSessionMapping(e)}c.afterSessionEstablished&&r.acpSessionId&&await c.afterSessionEstablished(r.acpSessionId)}armIdleTimer(e,n,r){if(ri(r),this.isRuntimeBusy(e,r)){P.debug("skip idle timer: runtime busy (in-flight turn / pending permission)",{agentId:e.agentId,cloudId:n});return}r.idleTimer=setTimeout(()=>{if(r.idleTimer=void 0,this.isRuntimeBusy(e,r)){P.info("idle reaper fired but runtime busy, re-arming",{agentId:e.agentId,cloudId:n}),this.armIdleTimer(e,n,r);return}P.info("session runtime idle timeout, killing downstream",{agentId:e.agentId,cloudId:n});let i=r.downstream;r.downstream=void 0,r.acpSessionId&&e.activeTriggers.delete(r.acpSessionId),i&&i.stop("idle timeout").catch(s=>P.warn("idle stop failed (ignored)",{agentId:e.agentId,cloudId:n,err:String(s)}))},this.sessionIdleTimeoutMs),r.idleTimer.unref?.()}isRuntimeBusy(e,n){if(n.acpSessionId&&e.activeTriggers.has(n.acpSessionId))return!0;let r=n.downstream;if(!r)return!1;for(let i of this.pendingUpstream.values())if(i.downstream===r)return!0;return!1}async sendAgentFileUpdate(e,n,r,i){let s={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};if(n.acpSessionId){let o=e.activeTriggers.get(n.acpSessionId);o&&(s.cozeTriggerMsgId=o);let a=e.activeGroupIds.get(n.acpSessionId);a&&(s.cozeGroupId=a)}await this.upstream.send(Yn("session/update",{sessionId:r,update:i,_meta:s}))}async synthesizePromptReply(e,n,r,i,s,o){let a={cozeAgentId:e.agentId,cozeReplySeqID:++n.replySeq};return s&&(a.cozeTriggerMsgId=s),o&&(a.cozeGroupId=o),await this.upstream.send(Yn("session/update",{sessionId:r,update:{sessionUpdate:"agent_message_chunk",content:{type:"text",text:i}},_meta:a})).catch(c=>P.warn("synthesizePromptReply update send failed (ignored)",{err:String(c)})),{stopReason:"end_turn"}}forwardUpdate(e,n){let r=n.sessionId,i=this.reverseSessionId(e,r);if(!i){P.debug("drop update for unknown session",{agentId:e.agentId,acpId:r});return}let s=e.sessions.get(i);if(!s){P.debug("drop update: runtime gone",{agentId:e.agentId,cloudId:i});return}if(YE(n)){P.debug("drop codex metadata-warn chunk",{agentId:e.agentId,acpId:r});return}let o={cozeAgentId:e.agentId,cozeReplySeqID:++s.replySeq},a=e.activeTriggers.get(r);a&&(o.cozeTriggerMsgId=a);let c=e.activeGroupIds.get(r);c&&(o.cozeGroupId=c),this.upstream.send(Yn("session/update",{...n,sessionId:i,_meta:o})).catch(l=>P.warn("forward update failed",{agentId:e.agentId,err:String(l)}))}handleAgentRequest(e,n,r){if(r.method==="session/request_permission"){this.forwardPermissionRequest(e,n,r);return}if(r.method==="fs/write_text_file"||r.method==="fs/read_text_file"){this.handleFsRpcRequest(e,n,r);return}P.warn("unhandled agent request,returning method_not_found",{agentId:e.agentId,method:r.method}),n.respondAgentRequestError(r.id,{code:B.METHOD_NOT_FOUND,message:`method not handled by Bridge: ${r.method}`})}async handleFsRpcRequest(e,n,r){try{let i=e.workspace;if(r.method==="fs/write_text_file"){let s=r.params??{},o=await Xf(s,i);n.respondAgentRequest(r.id,o)}else{let s=r.params??{},o=await Yf(s,i);n.respondAgentRequest(r.id,o)}}catch(i){P.warn("fs rpc handler failed",{agentId:e.agentId,method:r.method,err:String(i)}),n.respondAgentRequestError(r.id,ni(i))}}clearPendingPermissionFor(e){if(e.method!=="session/request_permission"||!e.cloudSessionId)return;let n=this.agents.get(e.agentId)?.sessions.get(e.cloudSessionId);n&&(n.pendingPermission=void 0)}forwardPermissionRequest(e,n,r){let i=this.upstreamIds.next("session/request_permission"),s=r.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=p?e.sessions.get(p):void 0;m&&(m.pendingPermission={downstream:n,agentRequestId:r.id,upstreamId:i});let f={...s,...p?{sessionId:p}:{},_meta:l};this.pendingUpstream.set(i,{agentRequestId:r.id,agentId:e.agentId,downstream:n,method:r.method,cloudSessionId:p}),P.info("forward permission_request \u2192 upstream",{agentId:e.agentId,upstreamId:i,acpSessionId:a,cloudSessionId:p,toolCallId:s.toolCall?.toolCallId,options:s.options?.map(h=>({optionId:h.optionId,kind:h.kind,name:h.name}))}),this.upstream.send(ei(i,"session/request_permission",f)).catch(h=>{this.pendingUpstream.delete(i),P.error("forward permission request failed",{agentId:e.agentId,err:String(h)}),n.respondAgentRequestError(r.id,{code:B.INTERNAL_ERROR,message:`upstream send failed: ${String(h)}`})})}handleUpstreamResponse(e){if(e.id===null)return;let n=this.lookupPending(this.pendingUpstream,e.id,"upstream");if(n){this.pendingUpstream.delete(n.key);let i=n.value;this.clearPendingPermissionFor(i),e.error?(P.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"&&XE(e.result,i),P.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 r=this.lookupPending(this.pendingBridge,e.id,"bridge");if(r){this.pendingBridge.delete(r.key),clearTimeout(r.value.timer),e.error?r.value.reject(new Ns(e.error)):r.value.resolve(e.result);return}P.debug("orphan upstream response (no pending)",{id:e.id})}lookupPending(e,n,r){let i=e.get(n);if(i)return{value:i,key:n};if(typeof n=="number"){let s=String(n),o=e.get(s);if(o)return P.warn(`${r} id type mismatch: number received but Bridge expected string`,{rawId:n,normalizedId:s}),{value:o,key:s}}}sendRequest(e,n,r=WE){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 ${r}ms`))},r);this.pendingBridge.set(i,{method:e,resolve:s,reject:o,timer:a}),this.upstream.send(ei(i,e,n)).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 n=new Map;for(let[r,i]of e.sessions){let s={modelToken:i.modelToken,tokenGeneratedAt:i.tokenGeneratedAt};i.acpSessionId&&(s.acpSessionId=i.acpSessionId),n.set(r,s)}await Ir(e.agentId,n,this.paths)}catch(n){P.warn("persist session mapping failed",{agentId:e.agentId,err:String(n)})}}reverseSessionId(e,n){for(let[r,i]of e.sessions.entries())if(i.acpSessionId===n)return r}sendError(e,n,r){return this.upstream.send(zt(e,{code:n,message:r,data:{bridgeVersion:Xn}}))}};function KE(){return jE(16).toString("hex")}function XE(t,e){if(!t||typeof t!="object"){P.warn("permission response: result not an object (suspicious)",{agentId:e.agentId,result:t});return}let n=t;if("kind"in n&&!("outcome"in n)){P.warn('permission response: top-level "kind" field (D66 historical bug shape)',{agentId:e.agentId,result:t});return}let r=n.outcome;if(!r||typeof r!="object"){P.warn("permission response: missing or non-object outcome field",{agentId:e.agentId,result:t});return}let s=r.outcome;(typeof s!="string"||s!=="selected"&&s!=="cancelled")&&P.warn("permission response: unknown outcome discriminant",{agentId:e.agentId,outcomeValue:s,result:t})}function YE(t){let e=t.update;if(e?.sessionUpdate!=="agent_message_chunk")return!1;let n=e.content;if(!n||typeof n!="object")return!1;let r=n;return r.type!=="text"||typeof r.text!="string"?!1:r.text.startsWith("Model metadata for `")}L();se();import{randomBytes as QE}from"node:crypto";import{chmod as e0,mkdir as t0,writeFile as ih}from"node:fs/promises";import{createServer as n0}from"node:http";import{dirname as r0}from"node:path";var i0=1e6,fc=A("ipc"),Vs=class{server=null;port=0;token="";routes;paths;constructor(e){this.routes=new Map(e.routes.map(n=>[`${n.method} ${n.path}`,n])),this.paths=e.paths??F()}async start(){this.token=QE(32).toString("hex");let e=n0((r,i)=>{this.dispatch(r,i)});this.server=e,await new Promise((r,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>r())});let n=e.address();if(!n||typeof n!="object")throw new Error("failed to obtain IPC port");return this.port=n.port,await this.persistAuthFiles(),fc.info("IPC listening",{port:this.port}),{port:this.port,token:this.token}}async stop(){let e=this.server;e&&(await new Promise((n,r)=>{e.close(i=>i?r(i):n())}),this.server=null)}async persistAuthFiles(){await t0(r0(this.paths.portFile),{recursive:!0}),await ih(this.paths.portFile,String(this.port),"utf8"),await ih(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await e0(this.paths.tokenFile,384)}catch(e){fc.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){ai(n,401,{error:"unauthorized"});return}let i=`${e.method} ${(e.url??"").split("?")[0]}`,s=this.routes.get(i);if(!s){ai(n,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await s0(e)}catch(a){ai(n,400,{error:"invalid json",detail:String(a)});return}try{let a=await s.handler(o,e);ai(n,200,a??{ok:!0})}catch(a){fc.error("IPC handler failed",{key:i,err:String(a)}),ai(n,500,{error:a instanceof Error?a.message:String(a)})}}};function ai(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function s0(t){let e=[],n=0;for await(let i of t){let s=i;if(n+=s.length,n>i0)throw new Error("body too large");e.push(s)}let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):null}var hh="";function w0(t=""){let n=`${Date.now()}`,r=hh||(hh=S0(t)),i=Math.random().toString(16).slice(-6);return"02"+n+r+i}function y0(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function _0(t){return(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8)}function ph(t){return(Array(4).join("0")+parseInt(t,2).toString(16)).slice(-4)}function E0(t){let e=t.split(/\./).map(i=>_0(i)),n=[];return n[0]=ph(e[0]+e[1]),n[1]=ph(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",n[0],n[1]].join("")}function S0(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),n=/(([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?E0(t):n?I0(t):"00000000000000000000000000000000"}function I0(t){let e="",n=[],r=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&&(r=p.length),i+=p.length;for(let m=0;m<p.length;m++)if(p[m].length!==4){let h=o.substring(0,4-p[m].length).concat(p[m]);n.push(h)}else n.push(p[m]);s=!1}else{if(d.length!==4){let m=o.substring(0,4-d.length).concat(d);n.push(m)}else n.push(d);s&&(r+=1),i+=1,s=!1}}let c="";for(let l=0;l<8-i;l++)c=c.concat(o);for(let l=0;l<n.length;l++)l===r&&(e=e.concat(c)),e=e.concat(n[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 v0(t,e){let n=t.key;n!==void 0&&(pe(e,10),mn(e,n));let r=t.value;r!==void 0&&(pe(e,18),mn(e,r))}function T0(t){let e={};e:for(;!Ah(t);){let n=Te(t);switch(n>>>3){case 0:break e;case 1:e.key=gn(t,Te(t));break;case 2:e.value=gn(t,Te(t));break;default:Rh(t,7&n)}}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 Th(t){let e=bh();return R0(t,e),P0(e)}function R0(t,e){let n=t.SeqID;n!==void 0&&(pe(e,8),li(e,n));let r=t.LogID;r!==void 0&&(pe(e,16),li(e,r));let i=t.service;i!==void 0&&(pe(e,24),li(e,_c(i)));let s=t.method;s!==void 0&&(pe(e,32),li(e,_c(s)));let o=t.headers;if(o!==void 0)for(let h of o){pe(e,42);let g=bh();v0(h,g),pe(e,g.limit),N0(e,g),x0(g)}let a=t.payloadEncoding;a!==void 0&&(pe(e,50),mn(e,a));let c=t.payloadType;c!==void 0&&(pe(e,58),mn(e,c));let l=t.payload;l!==void 0&&(pe(e,66),pe(e,l.length),D0(e,l));let d=t.LogIDNew;d!==void 0&&(pe(e,74),mn(e,d));let p=t.serverTiming;p!==void 0&&(pe(e,82),mn(e,p));let m=t.msgID;m!==void 0&&(pe(e,90),mn(e,m));let f=t.frameType;f!==void 0&&(pe(e,96),li(e,_c(f)))}function k0(t){return b0(O0(t))}function b0(t){let e={};e:for(;!Ah(t);){let n=Te(t);switch(n>>>3){case 0:break e;case 1:e.SeqID=mh(t,!0);break;case 2:e.LogID=mh(t,!0);break;case 3:e.service=Te(t);break;case 4:e.method=Te(t);break;case 5:{let r=A0(t);(e.headers||(e.headers=[])).push(T0(t)),t.limit=r;break}case 6:e.payloadEncoding=gn(t,Te(t));break;case 7:e.payloadType=gn(t,Te(t));break;case 8:e.payload=C0(t,Te(t));break;case 9:e.LogIDNew=gn(t,Te(t));break;case 10:e.serverTiming=gn(t,Te(t));break;case 11:e.msgID=gn(t,Te(t));break;case 12:e.frameType=Te(t);break;default:Rh(t,7&n)}}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 A0(t){let e=Te(t),n=t.limit;return t.limit=t.offset+e,n}function Rh(t,e){switch(e){case 0:for(;128&Ue(t););break;case 2:Ec(t,Te(t));break;case 5:Ec(t,4);break;case 1:Ec(t,8);break;default:throw new Error("Unimplemented type: "+e)}}function _c(t){return t|=0,{low:t,high:t>>31,unsigned:t>=0}}var kh=[];function bh(){let t=kh.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function x0(t){kh.push(t)}function O0(t){return{bytes:t,offset:0,limit:t.length}}function P0(t){let e=t.bytes,n=t.limit;return e.length===n?e:e.subarray(0,n)}function Ec(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function Ah(t){return t.offset>=t.limit}function fi(t,e){let n=t.bytes,r=t.offset,i=t.limit,s=r+e;if(s>n.length){let o=new Uint8Array(2*s);o.set(n),t.bytes=o}return t.offset=s,s>i&&(t.limit=s),r}function Bc(t,e){let n=t.offset;if(n+e>t.limit)throw new Error("Read past limit");return t.offset+=e,n}function C0(t,e){let n=Bc(t,e);return t.bytes.subarray(n,n+e)}function D0(t,e){let n=fi(t,e.length);t.bytes.set(e,n)}function gn(t,e){let n=Bc(t,e),r=String.fromCharCode,i=t.bytes,s="\uFFFD",o="";for(let a=0;a<e;a++){let c=i[a+n],l,d,p,m;(128&c)===0?o+=r(c):(224&c)===192?a+1>=e?o+=s:(l=i[a+n+1],(192&l)!==128?o+=s:(m=(31&c)<<6|63&l,m<128?o+=s:(o+=r(m),a++))):(240&c)==224?a+2>=e?o+=s:(l=i[a+n+1],d=i[a+n+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+=r(m),a+=2))):(248&c)==240?a+3>=e?o+=s:(l=i[a+n+1],d=i[a+n+2],p=i[a+n+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+=r((m>>10)+55296,(1023&m)+56320),a+=3))):o+=s}return o}function mn(t,e){let n=e.length,r=0;for(let o=0;o<n;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<n&&(a=(a<<10)+e.charCodeAt(++o)-56613888),r+=a<128?1:a<2048?2:a<65536?3:4}pe(t,r);let i=fi(t,r),s=t.bytes;for(let o=0;o<n;o++){let a=e.charCodeAt(o);a>=55296&&a<=56319&&o+1<n&&(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 N0(t,e){let n=fi(t,e.limit),r=t.bytes,i=e.bytes;for(let s=0,o=e.limit;s<o;s++)r[s+n]=i[s]}function Ue(t){return t.bytes[Bc(t,1)]}function gh(t,e){let n=fi(t,1);t.bytes[n]=e}function Te(t){let e=0,n=0,r;do r=Ue(t),e<32&&(n|=(127&r)<<e),e+=7;while(128&r);return n}function pe(t,e){for(e>>>=0;e>=128;)gh(t,127&e|128),e>>>=7;gh(t,e)}function mh(t,e){let n=0,r=0,i=0,s;return s=Ue(t),n=127&s,128&s&&(s=Ue(t),n|=(127&s)<<7,128&s&&(s=Ue(t),n|=(127&s)<<14,128&s&&(s=Ue(t),n|=(127&s)<<21,128&s&&(s=Ue(t),r=127&s,128&s&&(s=Ue(t),r|=(127&s)<<7,128&s&&(s=Ue(t),r|=(127&s)<<14,128&s&&(s=Ue(t),r|=(127&s)<<21,128&s&&(s=Ue(t),i=127&s,128&s&&(s=Ue(t),i|=(127&s)<<7))))))))),{low:n|r<<28,high:r>>>4|i<<24,unsigned:e}}function li(t,e){let n=e.low>>>0,r=(e.low>>>28|e.high<<4)>>>0,i=e.high>>>24,s=i===0?r===0?n<16384?n<128?1:2:n<2097152?3:4:r<16384?r<128?5:6:r<2097152?7:8:i<128?9:10,o=fi(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?r>>>21|128:r>>>21&127;case 7:a[o+6]=s!==7?r>>>14|128:r>>>14&127;case 6:a[o+5]=s!==6?r>>>7|128:r>>>7&127;case 5:a[o+4]=s!==5?128|r:127&r;case 4:a[o+3]=s!==4?n>>>21|128:n>>>21&127;case 3:a[o+2]=s!==3?n>>>14|128:n>>>14&127;case 2:a[o+1]=s!==2?n>>>7|128:n>>>7&127;case 1:a[o]=s!==1?128|n:127&n}}function L0(t){return k0(t)}function wh(t){return Th(t)}var yh=65536,F0="\0\0\0\0\0\0\0\0",rr=yh*yh,xh=rr*rr,_h=xh/2,jt=String.prototype.charCodeAt,Ce=class t{constructor(e,n,r){this.isLong=!0,this.low=0|e,this.high=0|n,this.unsigned=!!r}static isLong(e){return e&&e.isLong===!0}static fromBits(e,n,r){return new t(e,n,r)}static fromBytes(e,n,r){return r?t.fromBytesLE(e,n):t.fromBytesBE(e,n)}static fromBytesLE(e,n){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,n)}static fromBytesBE(e,n){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],n)}static fromHash(e){return e===F0?Eh:new t((jt.call(e,0)|jt.call(e,1)<<8|jt.call(e,2)<<16|jt.call(e,3)<<24)>>>0,(jt.call(e,4)|jt.call(e,5)<<8|jt.call(e,6)<<16|jt.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,n=!0){if(isNaN(e))return n?M0:Eh;if(n){if(e>=xh)return U0}else{if(e<=-_h)return z0;if(e+1>=_h)return B0}return t.fromBits(e%rr|0,e/rr|0,n)}toNumber(){return this.unsigned?(this.high>>>0)*rr+(this.low>>>0):this.high*rr+(this.low>>>0)}isZero(){return this.high===0&&this.low===0}add(e){t.isLong(e)||(e=t.fromNumber(e));let n=this.high>>>16,r=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+=r+a,d+=p>>>16,p&=65535,d+=n+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,n=this.low;return[255&n,n>>>8&255,n>>>16&255,n>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]}toBytesBE(){let e=this.high,n=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,n>>>24,n>>>16&255,n>>>8&255,255&n]}},Eh=new Ce(0,0,!1),M0=new Ce(0,0,!0),B0=Ce.fromBits(-1,2147483647,!1),U0=Ce.fromBits(-1,-1,!0),z0=Ce.fromBits(0,-2147483648,!1),pn=(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})({}),wn=class{constructor(e){this.type=e,this.target=null}},Ic=class extends wn{constructor(e,n){super(e),this.message=n&&n.message||null}},vc=class extends wn{constructor(e,n){super(e),this.error=n&&n.error||null,this.colno=n&&n.colno||0,this.filename=n&&n.filename||"",this.lineno=n&&n.lineno||0,this.message=n&&n.message||"",this.code=n&&n.code||5001}},Tc=class extends wn{constructor(e,n){super(e),this.code=n&&n.code||0,this.reason=n&&n.reason||"",this.wasClean=n&&n.wasClean||!1,this.willReconnect=n&&n.willReconnect||!1}},Rc=class extends wn{constructor(e,n){super(e),this.data=n&&n.data||null}},kc=class extends Rc{constructor(e,n){super(e),this.data=n&&n.data||null,this.message=n&&n.message||null}},bc=class extends wn{constructor(e,n){super(e),this.data=n&&n.data||null}};function Ze(t,{message:e,code:n,error:r}){return new vc(t,{message:e,code:n,error:r})}function ct(t,{code:e,reason:n,wasClean:r,willReconnect:i}){return new Tc(t,{code:e,reason:n,wasClean:r,willReconnect:i})}function $0(t,{data:e,message:n}){return new kc(t,{data:e,message:n})}function G0(t,{data:e}){return new bc(t,{data:e})}function Sh(t,{message:e}){return new Ic(t,{message:e})}var Zs=class{constructor(e,n){this.endpoints=e,this.maxRetries=n,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()}},sr=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",yn=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",hi=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",di=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",H0=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,ui=class{constructor(){this._listeners={}}emit(e,...n){let r=this._listeners[e];if(r)r.slice().forEach(i=>i.fn.apply(i.ctx,n));else if(e==="error"&&!this.onerror){let i=n.length&&n[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,n){if(e===void 0)this._listeners={};else if(n===void 0)this._listeners[e]=null;else{let r=this._listeners[e];if(r)for(let i=0;i<r.length;)r[i].fn===n?r.splice(i,1):++i}return this}on(e,n,r){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:n,ctx:r||this}),this}},Ac=class extends ui{_formatErrorMessage(e){return e.errMsg||e.errNo?`message: ${e.errMsg||""} code: ${e.errNo||""}`.trim():JSON.stringify(e)}constructor(e,n,r){super(),this._socket=null,hi&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:n,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),yn&&tt.connectSocket&&(this._socket=tt.connectSocket({url:e,protocols:n,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)}))}_createSocketSuccessHandler(){Promise.resolve().then(()=>{this._addWsListeners()})}_createSocketFailHandler(e){Promise.resolve().then(()=>{let n=Ze("error",{message:this._formatErrorMessage(e)});this.emit("error",n);let r=ct("close",{reason:this._formatErrorMessage(e)});this.emit("close",r)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",G0("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",ct("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",$0("message",{...e}))}),this._socket.onError(e=>{this.emit("error",Ze("error",{...e,message:e.errMsg||""}))})}send(e){if(e instanceof Uint8Array){let n=e.buffer.slice(e.byteOffset,e.byteLength+e.byteOffset);this._socket&&this._socket.send({data:n,fail:r=>{this.emit("error",Ze("error",{message:this._formatErrorMessage(r)}))}})}else this._socket&&this._socket.send({data:e,fail:n=>{this.emit("error",Ze("error",{message:this._formatErrorMessage(n)}))}})}close(e,n){this._socket&&this._socket.close({code:e,reason:n})}addEventListener(e,n){this.on(e,n)}removeEventListener(e,n){this.off(e,n)}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 j0(t,e){if(e)return new e(t.url,t.protocol);if(hi||yn)return new Ac(t.url,t.protocol,t.headers);if((sr||di)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(t.url,t.protocols)}function W0(t){return!!(t||hi&&wx.connectSocket||yn&&tt.connectSocket||(sr||di)&&typeof WebSocket<"u"&&WebSocket)}function Ih(t,e,n){let r=-1;async function i(s){return s<=r?Promise.reject(new Error("next() called multiple times in process")):(r=s,s===n.length?Promise.resolve():n[s].bind(t)(e,i.bind(null,s+1)))}i(0)}function Oh(t){let e=0,n=0;for(let r=0;r<t.length;++r)n=t.charCodeAt(r),n<128?e+=1:n<2048?e+=2:(64512&n)===55296&&(64512&t.charCodeAt(r+1))===56320?(++r,e+=4):e+=3;return e}function Ph(t,e,n){if(n-e<1)return"";let r="";for(let i=e;i<n;){let s=t[i++];if(s<=127)r+=String.fromCharCode(s);else if(s>=192&&s<224)r+=String.fromCharCode((31&s)<<6|63&t[i++]);else if(s>=224&&s<240)r+=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;r+=String.fromCharCode(55296+(o>>10)),r+=String.fromCharCode(56320+(1023&o))}}return r}function xc(t,e,n){let r=n,i,s;for(let o=0;o<t.length;++o)i=t.charCodeAt(o),i<128?e[n++]=i:i<2048?(e[n++]=i>>6|192,e[n++]=63&i|128):(64512&i)===55296&&(64512&(s=t.charCodeAt(o+1)))===56320?(i=65536+((1023&i)<<10)+(1023&s),++o,e[n++]=i>>18|240,e[n++]=i>>12&63|128,e[n++]=i>>6&63|128,e[n++]=63&i|128):(e[n++]=i>>12|224,e[n++]=i>>6&63|128,e[n++]=63&i|128);return n-r}async function Ch(t){if(typeof t=="string"){let e=new Uint8Array(Oh(t));return xc(t,e,0),e}return t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function q0(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 J0=(t,e)=>{switch(t){case"boe":case"ppe":return{[`x-use-${t}`]:1,"x-tt-env":e};default:return{}}},Oc=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 V0(t){return new Promise(e=>{if(!sr)return e("unknown reason");try{let n=document.createElement("script");window.frontierJSONP=r=>{document.body.removeChild(n),window.frontierJSONP=void 0,e(r&&r.msg||"unknown reason")},n.type="text/javascript",n.src=t.replace(/^ws/,"http")+"&jscallback=frontierJSONP";try{document.body.appendChild(n)}catch{document.body.removeChild(n)}}catch{window.frontierJSONP=void 0,e("unknown reason")}})}function Wt(t,e,n){return!!t?.find(r=>r.key===e&&r.value===n)}function ir(t,e){return t?.find(n=>n.key===e)?.value}var Sc=null;async function Z0(){return Sc||(Sc=Promise.resolve().then(()=>(fh(),uh))),Sc}var Pc=class extends ui{constructor(e,n){super(),this._dbName=e,this._keyPath=n,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,n=this._keyPath;this._initPromise=(async()=>{let{openDB:r}=await Z0();this._qosDB=await r(`frontier_${e}`,1,{upgrade(i){i.createObjectStore(e,{keyPath:n})}})})(),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(n){console.log(n)}}async set(e,n){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(n){console.log(n)}}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}}},Cc=class{constructor(e,n){this._DBName=e,this._pathKey=n,this._qosDB=localStorage}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let n=this._qosDB.getItem(this._prefix);return JSON.parse(n||"{}")[e]}async set(e,n){let r=this._qosDB.getItem(this._prefix),i=JSON.parse(r||"{}");return i[n||e[this._pathKey]]=e,this._qosDB.setItem(this._prefix,JSON.stringify(i)),n||e[this._pathKey]}async del(e){let n=this._qosDB.getItem(this._prefix),r=JSON.parse(n||"{}");return r[e]=void 0,this._qosDB.setItem(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clear()}async keys(){let e=this._qosDB.getItem(this._prefix),n=JSON.parse(e||"{}");return Object.keys(n)}async getAll(){let e=this._qosDB.getItem(this._prefix),n=JSON.parse(e||"{}");return Object.values(n)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}},Dc=class{constructor(e,n){this._DBName=e,this._pathKey=n,this._qosDB=yn?tt:hi?wx:null}async openDB(){}get _prefix(){return`frontier_${this._DBName}`}async get(e){let n=this._qosDB.getStorageSync(this._prefix);return JSON.parse(n||"{}")[e]}async set(e,n){let r=this._qosDB.getStorageSync(this._prefix),i=JSON.parse(r||"{}");return i[n||e[this._pathKey]]=e,this._qosDB.setStorageSync(this._prefix,JSON.stringify(i)),n||e[this._pathKey]}async del(e){let n=this._qosDB.getStorageSync(this._prefix),r=JSON.parse(n||"{}");return r[e]=void 0,this._qosDB.setStorageSync(this._prefix,JSON.stringify(r))}async clear(){return this._qosDB.clearStorageSync()}async keys(){let e=this._qosDB.getStorageInfoSync(this._prefix),n=JSON.parse(e||"{}");return Object.keys(n)}async getAll(){let e=this._qosDB.getStorageInfoSync(this._prefix),n=JSON.parse(e||"{}");return Object.values(n)}closeDB(){return Promise.resolve()}get isReady(){return!!this._qosDB}};function Dh(t,e){if(yn||yn)return new Dc(t,e);if((sr||di)&&typeof indexedDB<"u")return new Pc(t,e);if((sr||di)&&typeof localStorage<"u")return new Cc(t,e);throw new Error("init QoSDB failed")}var Nc=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Dh("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:r})=>r<Date.now()).forEach(r=>{this._qosDB?.del(r.message_id)})}async del(e){return this._qosDB?.del(e)}async set(e,n){return this._qosDB?.set({message_id:e,timestamp:n})}async get(e){return this._qosDB?.get(e)}async closeDB(){clearInterval(this._intervalTimeoutId),await this._qosDB?.closeDB()}get isReady(){return this._qosDB?.isReady}};function Uc(t){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let n=Wt(t.message.headers,"x_frontier_qos","2"),r=n&&Wt(t.message.headers,"x_frontier_qos_ack","1"),i=n&&Wt(t.message.headers,"x_frontier_is_ack","1"),s=i?ir(t.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:n,isQoSAck:r,isAckCleanupMessage:i,ackMsgIds:s}}async function Nh(){return this._QoSManager||(this._QoSManager=new Nc),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function K0(t,e){let{enableAutoAck:n}=this._options,r=Wt(t.message.headers,"need_ack","1"),i=Wt(t.message.headers,"is_ack","1"),s=Uc.call(this,t);if(n&&r){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 X0(t,e){this._debug("received",t.message),e()}async function Y0(t,e){let n=L0(await Ch(t.data));try{if(n.payload instanceof Uint8Array){let r=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=n.payloadEncoding?n.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=n.payloadType?n.payloadType.replace(/\s/g,"").toLowerCase():"",a=s.force?s.type:o||s.type,c=r.force?r.encoding:i||r.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))?n.textPayload=Ph(n.payload,0,n.payload.byteLength):n.textPayload=""}else n.textPayload=""}catch(r){n.textPayload="",console.log(r)}t.message=n,e()}function Q0(t,e,n){let r=n||8192,i=r>>>1,s=null,o=r;return function(a){if(a<1||a>i)return t(a);o+a>r&&(s=t(r),o=0);let c=e.call(s,o,o+=a);return 7&o&&(o=(7|o)+1),c}}var eS=4294967295;function tS(t,e,n){if(n>eS)throw new Error("integer too large");let r=3;for(;r>=0;){let i=255&n;Fc(i,t,e+r),n>>>=8,r--}return e+4}function nS(t,e){let n=0,r=e,i=e+4;for(;r<i;){let{value:s,offset:o}=Lc(t,r);r=o,n=n<<8>>>0,n+=s}return{value:n,offset:i}}function rS(t,e,n){return t?t.length<40?xc(t,e,n)+n:e.utf8Write?e.utf8Write(t,n)+n:e.write?e.write(t,n)+n:xc(t,e,n)+n:n}function iS(t,e){let n=new Ce(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:n,offset:e+8}}function sS(t,e,n){let r=t.low,i=t.high;return e[n]=i>>>24,e[n+1]=i>>>16&255,e[n+2]=i>>>8&255,e[n+3]=255&i,e[n+4]=r>>>24,e[n+5]=r>>>16&255,e[n+6]=r>>>8&255,e[n+7]=255&r,n+=8,n}function Lc(t,e){return t.readUInt8?{value:t.readUInt8(e),offset:e+1}:{value:255&t[e],offset:e+1}}function Fc(t,e,n){return e.writeUint8?e.writeUint8(t,n):e[n]=255&t,n+1}var oS=function(t){return new Uint8Array(t)},aS=typeof Buffer<"u"?Buffer.allocUnsafe:Q0(oS,Uint8Array.prototype.subarray),cS=16,zc=32;function lS(t){let e=0,n={};for(let r=0;r<t.length;r++)n[t[r].cursor_name]=Oh(t[r].cursor_name),e+=14+n[t[r].cursor_name];return[e,n]}function vh(t,e,n){let[r,i]=lS(t),s=aS(r),o=0;return t.forEach(a=>{console.log("cursor.service",a,a.service),o=Fc(0,s,o),console.log("header",o),o=tS(s,o,a.service||0),console.log("service",o),o=Fc(i[a.cursor_name],s,o),console.log("service-name",o),o=rS(a.cursor_name,s,o),console.log("name",o),o=sS(Ce.fromNumber(a.cursor||e),s,o),console.log("curvalue",o)}),{frameType:zc,headers:[{key:"cursor_file_name",value:n}],payload:s}}function dS(t){let e=0,n=[];for(;e<t.byteLength;){let{offset:r}=Lc(t,e);e=r;let i={cursor_name:"",cursor:0,service:0},{value:s,offset:o}=nS(t,e);i.service=s,e=o;let{value:a,offset:c}=Lc(t,e);e=c,i.cursor_name=Ph(t,e,e+a),e+=a;let{value:l,offset:d}=iS(t,e);i.cursor=l.toNumber(),e=d,n.push(i)}return n}function uS(){return{frameType:zc,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var Mc=class{constructor(e,n,r){this._cursorNameSpace=e,this._cursorFileName=n,this._messageStrategy=r,this._qosDB=Dh(this._cursorNameSpace,"cursor_name")}async openDB(){await this._qosDB.openDB()}async getCursors(){if(!this._qosDB.isReady)return;let e=this._messageStrategy,n=await this._qosDB.getAll();switch(console.log("allCursorValues",n),e){case"ALL":return n&&n.length?vh(n,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return n&&n.length?vh(n,0,this._cursorFileName):uS()}}async set(e,n,r){return console.log("setdb",e,n,r),this._qosDB.set({cursor_name:e,cursor:n,service:r})}async setCursors(e){let n=dS(e);for(let r of n)console.log("setcursor",n),await this._qosDB.set(r)}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}},fS="__x_msg_qos__";async function Lh(t){if(!this._options.enableQoS)return null;let{aID:e,fpID:n,messageStrategy:r}=this._options,i=t||fS;try{return this._cursorManager?t&&this._cursorManager.updateCursorFileName(t):this._cursorManager=new Mc(`${n}_${e}_${i}`,i,r),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function hS(t,e){let n=Wt(t.message.headers,"code","-1"),r=Wt(t.message.headers,"is_ack","1"),i=ir(t.message.headers,"x_frontier_msgid"),s=Number(ir(t.message.headers,"x_frontier_ttl"))||0,o=Uc.call(this,t),a=Wt(t.message.headers,"x-msg-qos","2"),c=ir(t.message.headers,"x-msg-cursor_name"),l=Number(ir(t.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await Nh.call(this):null;if(t.message.service>0&&r&&!n||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 Lh.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 pS(t,e){let n=Uc.call(this,t);if(!n.isQoSMessage)return e();let r=await Nh.call(this);if(n.isAckCleanupMessage&&n.ackMsgIds.length)for(let i of n.ackMsgIds)await r.del(i);e()}async function gS(t,e){let n=t.message.frameType===cS,r=t.message.frameType===zc;if(!n&&!r)return e();let i=ir(t.message.headers,"cursor_file_name");if(!i)return e();let s=await Lh.call(this,i);if(!s)return e();if(n){let o=await s.getCursors(),a={frameType:o?.frameType,SeqID:Ce.fromNumber(this._seqId++),LogID:Ce.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=Th(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(r){let o=t.message.payload;o&&s.setCursors(o)}}var mS=async function(t,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},wS=async function(t,e){let n=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${n}`),e()},yS=async function(t,e){if(!this._ws||this._ws.readyState!==this.OPEN)return e();let{pingInterval:n}=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(),n),this._dispatchOpenEvent(t),this._isBrowser&&this._ws&&(this._ws.binaryType=this._binaryType);let r=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${r} success`),e()},Ks=class extends ui{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=sr,this._isNode=H0,this._isMiniTT=yn,this._isMiniWX=hi,this._isWorker=di,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{Ih(this,s,[mS,yS,wS])}catch(o){let a=Ze("error",{message:o.message,code:pn.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{Ih(this,s,[Y0,K0,pS,gS,hS,X0])}catch(c){let l=Ze("error",{message:c.message,code:pn.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(Ze("error",{message:c,code:pn.MAX_RETRIES_ERROR,error:s}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Ze("error",{message:s.message,code:pn.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(ct("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(ct("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 V0(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(ct("close",{code:s.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(Ze("error",{message:l,code:pn.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&!s.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(ct("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:y0,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:n,ws:r}=e,i=Array.isArray(n)?n:typeof n=="string"?[n]:[];if(!i||i.length===0)throw new Error("please provide valid url");if(!W0(r))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new Zs(i,this._options.maxRetries),this._pingLossCounter=new Oc(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=Sh("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:n,deviceID:r,bddID:i,ttwID:s,accessKey:o,aID:a,customParams:c={},enableAutoAck:l,enableQoS:d,QoSLevel:p,env:m}=this._options,f,h,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(f=location&&location.protocol=="https:"?"wss://":"ws://",h=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${f}${h}`):(f="wss://",h=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(h)?h:`${f}${h}`);let w=i?"bd_did":s?"ttwid":"device_id",S=i||s||r;if(!S||!w)throw new Error("please provide bddID, deviceID or ttwID");let v=typeof c=="function"?await c():c,u=m?J0(m.xUseEnv,m.xTTEnv):{},y=Object.assign({device_platform:"web",version_code:"fws_1.0.0",access_key:o,fpid:n,aid:a,[w]:S,xsack:l?1:0,xaack:l?1:0,xsqos:d?1:0,qos_level:d?p:void 0,qos_sdk_version:2,...u},v),E=Object.keys(y).reduce((R,T)=>y[T]!==void 0?`${R}${R?"&":"?"}${T}=${y[T]}`:R,"");return`${g}/ws/v2${E}`}async _connect(){if(!(this._connectLock||this._readyClosed)){this._connectLock=!0;try{let e=this._endpointManager?.checkCurrentEndpointReachedMaxRetries(),{timeoutInterval:n}=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=Ze("error",{message:a,code:pn.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(Ze("error",{message:a,code:pn.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=Sh("reconnect",{message:"start"});this.onStartReconnect&&this.onStartReconnect(i)}let r=this._endpointManager?.getCurrentEndpointTriesCount()||0;r>1&&await this._wait(r-1),this._debug(`connecting url: ${this._url} protocols: ${this._protocols}`),this._ws=j0({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),n)}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:n,maxReconnectInterval:r,reconnectIntervalGrowFactor:i}=this._options,s=n*Math.pow(i,e-1);return s>r?r: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(n=>{setTimeout(n,this._getIntervalValue(e))})}_disconnect(e=1e3,n="",r=!1){this._ws&&this._destroyWebSocket(e,n,r)}_onTimeout(){let e=this._endpointManager?.getCurrentEndpoint();this._debug(`connect ${e} timeout`),this._disconnect(1001,"timeout, try reconnecting",!0)}_sendAck(e){let n=wh(e);this._ws&&this._ws.readyState===this.OPEN&&(this._ws&&this._ws.send(n),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,n=""){try{this._ws&&this._ws.close(e,n)}catch{}}_destroyWebSocket(e=1e3,n="",r=!1){if(this._clearPingTimer(),this._clearTimer(),this._removeWsListeners(),this._wsInstanceClose(1e3,n),this._connectLock=!1,r&&this._navigatorOnline()&&!this._readyClosed){if(this._endpointManager?.checkReachMaxTries()){let s=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(ct("close",{code:1006,reason:`connect ${s} timeout, max retries reached`,wasClean:!0}))}else{let s=this._options.reconnectInterceptor(e,n);this._dispatchCloseEvent(ct("close",{code:e,reason:n,wasClean:!0,willReconnect:s})),s&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(ct("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(ct("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((n,r)=>(n+=r&&r.byteLength||0,n),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,n){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,n)}async send(e,n){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 r=await Ch(e),i=q0(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?w0(this._options.logIDNewConfig.userIp):""}=n||{};if(!o)throw new Error("please provide a valid service");let m={SeqID:Ce.fromNumber(this._seqId++),LogID:Ce.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:r,LogIDNew:p},f=wh(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:n}=e||{},r=Array.isArray(n)?n:typeof n=="string"?[n]:[];e&&Object.assign(this._options,e),r&&r.length?this._endpointManager=new Zs(r,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,n){this.on(e,n)}dispatchEvent(e){let{type:n}=e;this.emit(n,e)}removeEventListener(e,n){this.off(e,n)}pingOnce(){return new Promise((e,n)=>{this._clearPingTimer(),this._pingPongTimeoutId=setTimeout(this._ping.bind(this),this._options.pingInterval);let r=()=>{e("success"),this.off("ping_once_success",r),this.off("ping_once_timeout",i)},i=()=>{n("timeout"),this.off("ping_once_success",r),this.off("ping_once_timeout",i)};this.on("ping_once_success",r),this.on("ping_once_timeout",i),this._ping()})}};var BI=dt(Op(),1),UI=dt(so(),1),zI=dt(cr(),1),$I=dt(Xc(),1),GI=dt(el(),1),HI=dt(ol(),1),Up=dt(lo(),1),jI=dt(Bp(),1);var zp=Up.default;Ie();L();var ie=A("upstream.frontier"),Gp="application/json",Hp="none",qI=15e3,Si=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){ie.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:qu,...Zn(this.opts.ppeOverride)};class n extends zp{constructor(h){super(h,Wu,{headers:e})}send(h,...g){if(bl("debug"))try{let w;typeof h=="string"?w=Buffer.from(h,"utf8"):h instanceof Buffer?w=h:h instanceof ArrayBuffer?w=new Uint8Array(h):ArrayBuffer.isView(h)?w=new Uint8Array(h.buffer,h.byteOffset,h.byteLength):w=new Uint8Array(0);let S=Buffer.from(w.slice(0,128)).toString("hex");ie.debug("WS raw frame out",{bytes:w.byteLength,headHex:S})}catch(w){ie.warn("WS raw frame dump failed",{err:String(w)})}super.send(h,...g)}}let r=Vu(this.opts.urlOverride),i={url:r,ws:n,fpID:ju,aID:Ps,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:Gp,force:!0},payloadEncoding:{encoding:Hp,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},s=new Ks(i),o=!1,a=null,c,l,d=new Promise((f,h)=>{c=f,l=h}),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;ie.info("frontier opened",{url:r,remoteDeviceId:this.opts.handshake.deviceId,initial:f,openCount:this.openCount}),f&&p();for(let h of this.connectHandlers)Promise.resolve(h({initial:f})).catch(g=>ie.warn("onConnect handler threw (ignored)",{err:String(g)}))},s.onclose=f=>{this.opened=!1,ie.info("frontier closed",{code:f.code,reason:f.reason,willReconnect:f.willReconnect})},s.onerror=f=>{ie.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??qI;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(h){ie.warn("fws close during start failure threw (ignored)",{err:String(h)})}throw this.fws=null,this.opened=!1,f}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(r){ie.warn("frontier close threw (ignored)",{err:String(r)})}}}async send(e){let n=this.fws,r=e.method;if(!n)throw ie.warn("frontier send refused: upstream not started",{method:r}),new _("UPSTREAM_DISCONNECTED","frontier upstream not started");if(!this.isConnected()){let a=Date.now();throw a-this.lastSendRefusedLogAt>1e3?(ie.warn("frontier send refused: ws not open",{method:r,opened:this.opened,readyState:n.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=${n.readyState}); refusing to silently buffer`)}this.injectAgentPatToken(e);let i=JSON.stringify(e),s=e;jp(s)||ie.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:i.length});try{await n.send(i,{service:33555712,method:1,payloadType:Gp,payloadEncoding:Hp})}catch(a){throw ie.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 n=this.opts.getPatTokenForAgent;if(!n)return;let r=e.params?._meta;if(!r?.cozeAgentId)return;let i=n(r.cozeAgentId);i&&(r.cozePatToken=i)}handleMessage(e){let n=e.message?.service;if(n!==33555712){ie.debug("drop non-adapter frontier frame",{service:n});return}let r=ZI(e);if(!r){ie.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ie.debug("frame received but no onFrame handler",{size:r.length});return}let i;try{i=JSON.parse(r)}catch(o){ie.warn("frontier message JSON parse failed",{err:String(o),head:r.slice(0,80)});return}let s=i;jp(s)||ie.info("frontier frame in",{logid:VI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id,method:s.method,body:JI(r)}),Promise.resolve(this.handler(i)).catch(o=>ie.warn("frontier frame handler threw",{err:String(o)}))}};function jp(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var Wp=2e3;function JI(t){return t.length<=Wp?t:`${t.slice(0,Wp)}...<truncated, total ${t.length} chars>`}function VI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function ZI(t){let e=t.message;if(e?.textPayload)return e.textPayload;let n=e?.payload;if(!n)return null;try{return Buffer.from(n).toString("utf8")}catch{return null}}L();var cl=A("upstream.switchable"),fo=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;cl.info("swap upstream",{reason:n});let r=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 cl.error("swap target start failed, reverting",{err:String(i)}),this.inner=r,i}await r.stop(n??"swapped").catch(i=>cl.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()}};L();var ll=A("upstream"),pr=class{handler=null;async start(){ll.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){ll.info("NoopUpstream stopped",{reason:e})}async send(e){ll.debug("NoopUpstream.send (dropped)",{method:"method"in e?e.method:void 0})}onFrame(e){this.handler=e}isConnected(){return!1}async injectFrame(e){this.handler&&await this.handler(e)}};Ie();L();L();se();import{promises as dl}from"node:fs";import{dirname as KI}from"node:path";var XI=A("pat-token-store");async function ho(t=F()){try{let n=(await dl.readFile(t.patTokenFile,"utf8")).trim();return n.length>0?n:null}catch(e){let n=e?.code;return n!=="ENOENT"&&XI.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function Ii(t,e=F()){if(!t)throw new Error("writePatToken: empty patToken");await dl.mkdir(KI(e.patTokenFile),{recursive:!0}),await dl.writeFile(e.patTokenFile,t,{encoding:"utf8",mode:384})}se();se();import{promises as po}from"node:fs";import{join as YI}from"node:path";function QI(t,e){return`#!/bin/sh
|
|
93
93
|
exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
|
|
94
|
-
`}function
|
|
94
|
+
`}function ev(t,e){return`@echo off\r
|
|
95
95
|
"${e}" "${t}" %*\r
|
|
96
|
-
`}async function Dp(t,e=N()){let r=e.binDir;await ao.mkdir(r,{recursive:!0});let n=CI(r,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),i=process.execPath,s=process.platform==="win32"?NI(t,i):DI(t,i);return await ao.readFile(n,"utf8").catch(()=>null)===s||(await ao.writeFile(n,s,"utf8"),process.platform!=="win32"&&await ao.chmod(n,493)),r}F();se();import{execSync as Lp}from"node:child_process";import{readFileSync as Fp,unlinkSync as LI}from"node:fs";import{mkdir as FI,readFile as Mp,unlink as Bp,writeFile as MI}from"node:fs/promises";import{dirname as BI}from"node:path";function Np(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var UI=x("single-instance"),co=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??N().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&&(UI.warn("removing stale pid file",{stalePid:e}),await Bp(this.pidFile).catch(()=>{})),await FI(BI(this.pidFile),{recursive:!0}),await MI(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Mp(this.pidFile,"utf8")).trim()===String(process.pid)&&await Bp(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Mp(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 Np(e)?this.matchesDaemonTitle(e):!1}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let r=Fp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(r.includes("coze-bridge-daemon")||r.includes("lib/index.js"))}catch{}try{let r=Lp(`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=Lp(`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{Fp(this.pidFile,"utf8").trim()===String(process.pid)&&LI(this.pidFile)}catch{}})}};var O=x("daemon"),zI="coze-bridge-daemon";async function zp(){let t=N();process.env.COZE_BRIDGE_LOG_MODE!=="legacy"&&gl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:I=>ve(I,t).logs,listAgentIds:()=>Dl(t)});let e=new co({processTitle:zI}),r=await e.acquire();if(r.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${r.pid})`);let n=await $s(),i=n??{};Ri({pid:process.pid}),O.info(n?"loaded bridge config":"initialized bridge config");try{let I=new Gt;i.frameworksCache=await I.detectAll(),O.info("refreshed frameworks_cache",{detected:Object.keys(i.frameworksCache)})}catch(I){O.warn("framework detection failed",{err:String(I)})}await Kr(i);let s=new oo(new ln),o=null,a=new Gs({upstream:s,paths:t,bridgeConfig:i,sessionSpawner:async(I,T,A,P)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(I,T,A,P)}});await GI(t,a);let c=new Bs({paths:t,config:i,registry:a});o=c;let l,d,p=null,m={},h,f=null;a.registerExtension("_agent/create",async I=>c.createAgent(I.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let g={},w=new As({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 Li({paths:t,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)})}}))};s.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 u=new Hs({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let I=a.getMockScenario();return{running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:p??"",frameworksCache:i.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=Wn(T.env),X=T.handshake_url,Ce=T.frontier_url,ct=Up(T.env,X,Ce),lt=!!l&&l!==A,dn=d!==void 0&&d!==ct,un=lt||dn,yi=await Ua({privatecode:A,...X?{endpoint:X}:{},ppeOverride:G});if(un){O.warn("pair config switched, resetting agents",{pcChanged:lt,envChanged:dn,previousPc:l?lo(l):"",nextPc:lo(A),previousEnvKey:d??"",nextEnvKey:ct});for(let _e of[...a.agents.values()])await _e.dispose("pair config switch").catch(()=>{}),a.agents.delete(_e.agentId);a.disconnectedAgents.size>0&&(O.info("clearing disconnectedAgents set on pair config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await s.swap(new ln,"pair switch").catch(()=>{})}p=yi.deviceId,Ri({deviceId:p,pid:process.pid}),ec({patToken:A,env:T.env}).catch(_e=>O.warn("coze-cli setup error (ignored)",{err:String(_e)}));let ge=new gi({handshake:yi,privatecode:A,...Ce?{urlOverride:Ce}:{},ppeOverride:G,getPatTokenForAgent:_e=>a.agents.get(_e)?.patToken});await s.swap(ge,"pair");try{let _e=new Gt;i.frameworksCache=await _e.detectAll(),await Kr(i),O.info("frameworks_cache refreshed before pair",{detected:Object.keys(i.frameworksCache)})}catch(_e){O.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(_e)})}let So=Object.keys(i.frameworksCache??{});try{let _e=await a.sendRequest("_agent/pair",{pairCode:P,patToken:A,frameworks:So,_meta:{cozeDeviceId:p}});O.info("_agent/pair ok",{pairResult:_e}),l=A,d=ct,m=G,h=X,T.mock_scenario!==void 0&&(a.setMockScenario(T.mock_scenario),O.info("mock scenario set",{scenario:T.mock_scenario})),mi(A,t).catch(Ze=>O.warn("writePatToken after /pair failed (ignored)",{err:String(Ze)})),f||(f=new Jn({core:a,getDeviceId:()=>p??"",onTickEnd:()=>E.retryPending().catch(Ze=>O.warn("detailSync.retryPending failed (ignored)",{err:String(Ze)})),onAuthFailures:v})),f.start(),un&&uo(t,c).catch(Ze=>O.warn("post-pair-switch auto-revive error (ignored)",{err:String(Ze)}));let Io;return T.agent_id&&(Io=await HI(T.agent_id,t,c,Ze=>a.sendRequest("_agent/detail",Ze),A).catch(Ze=>(O.error("--agent-id ensureAgent failed",{agentId:T.agent_id,err:String(Ze)}),{ok:!1,agentId:T.agent_id??"",note:String(Ze)}))),{ok:!0,note:"paired with cloud",...Io?{agent:Io}:{}}}catch(_e){return O.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 _("IPC_BAD_REQUEST","/connect requires privatecode");let P=Wn(T.env),G=T.handshake_url,X=T.frontier_url,Ce=Up(T.env,G,X);if(l===A&&d===Ce){let ge=await $I(t);return a.agents.size===0&&ge?(O.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),uo(t,c).catch(So=>O.warn("connect-noop auto-revive error (ignored)",{err:String(So)}))):O.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let ct=!!l&&l!==A,lt=d!==void 0&&d!==Ce,dn=ct||lt,un=await Ua({privatecode:A,...G?{endpoint:G}:{},ppeOverride:P});if(dn){O.warn("connect config switched, resetting agents",{pcChanged:ct,envChanged:lt,previousPc:l?lo(l):"",nextPc:lo(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 s.swap(new ln,"connect switch").catch(()=>{})}p=un.deviceId,Ri({deviceId:p,pid:process.pid}),ec({patToken:A,env:T.env}).catch(ge=>O.warn("coze-cli setup error (ignored)",{err:String(ge)}));let yi=new gi({handshake:un,privatecode:A,...X?{urlOverride:X}:{},ppeOverride:P,getPatTokenForAgent:ge=>a.agents.get(ge)?.patToken});return await s.swap(yi,"connect"),l=A,d=Ce,m=P,h=G,T.mock_scenario!==void 0&&(a.setMockScenario(T.mock_scenario),O.info("mock scenario set",{scenario:T.mock_scenario})),f||(f=new Jn({core:a,getDeviceId:()=>p??"",onTickEnd:()=>E.retryPending().catch(ge=>O.warn("detailSync.retryPending failed (ignored)",{err:String(ge)})),onAuthFailures:v})),f.start(),dn&&uo(t,c).catch(ge=>O.warn("post-connect-switch auto-revive error (ignored)",{err:String(ge)})),mi(A,t).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?bh:kh)(A,{core:a,patToken:l,handshakeBase:h,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 Gt;return i.frameworksCache=await I.detectAll(),await Kr(i),{ok:!0,frameworks:i.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(O.info("IPC /shutdown received"),setImmediate(()=>{R.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:y,token:S}=await u.start();try{await Dp(t.libEntry,t)}catch(I){O.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(I)})}await a.start(),uo(t,c).catch(I=>O.warn("auto-revive top-level error (ignored)",{err:String(I)})),Al().then(async()=>{let{probeAcpVersion:I}=await Promise.resolve().then(()=>(Vt(),kl));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:u,shutdown(I){return k||(O.info("daemon shutdown",{reason:I}),k=(async()=>{f?.stop(),await a.stop(I),await u.stop(),await e.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(i.frameworksCache??{}),libVersion:i.libVersion??"dev"}),R}async function $I(t){let{readdir:e}=await import("node:fs/promises");try{return(await e(t.agentsRoot)).length>0}catch{return!1}}function lo(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Up(t,e,r){return`${t??""}|${e??""}|${r??""}`}async function GI(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(()=>(Rt(),Ni));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 HI(t,e,r,n,i){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(Rt(),Ni)),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 uo(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(()=>(Rt(),Ni));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=jI(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 jI(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}nl();se();import{readFile as $p}from"node:fs/promises";var It=class{paths;constructor(e){this.paths=e??N()}async probe(e=1e3){let r=await ho(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:QI(n)}}}async request(e){let r=await ho(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:YI(c)}}finally{clearTimeout(o)}}};async function ho(t){try{let[e,r]=await Promise.all([$p(t.portFile,"utf8"),$p(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 YI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function QI(t){return t instanceof Error?t.message:String(t)}Tt();F();se();function Jt(t,...e){let r=[],n;for(let i=0;i<t.length;i++){let s=t[i],o=!1;for(let a of e){if(s===a){n=t[i+1],i+=1,o=!0;break}if(s.startsWith(`${a}=`)){n=s.slice(a.length+1),o=!0;break}}o||r.push(s)}return{value:n,rest:r}}import{copyFile as Gp,mkdir as ev,readFile as il,writeFile as tv}from"node:fs/promises";import{homedir as oP}from"node:os";import{dirname as rv,resolve as sl,sep as fo}from"node:path";import{fileURLToPath as nv}from"node:url";F();se();var Hp=x("dist-install");function iv(t){let e=nv(t),r=rv(e),n=`${fo}src${fo}`;if(r.includes(n)||r.endsWith(`${fo}src${fo}cli`))return null;let i=sl(r,"index.js"),s=sl(r,"..","package.json");return{dist:i,pkgJson:s}}async function ol(t={}){let e=t.paths??N(),r=iv(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 il(i,"utf8")).version??"unknown"}catch(p){return Hp.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 $s(e.configFile)??{},a=o.libVersion;if(a===s)try{return await il(e.libEntry),{kind:"already-current",libVersion:s}}catch{}await ev(e.libDir,{recursive:!0}),await Gp(n,e.libEntry),await Gp(`${n}.map`,`${e.libEntry}.map`).catch(()=>{});let c=sl(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
|
|
97
|
-
`;return await
|
|
98
|
-
`).filter(o=>o.length>0).filter(o=>
|
|
99
|
-
`)}async function
|
|
96
|
+
`}async function qp(t,e=F()){let n=e.binDir;await po.mkdir(n,{recursive:!0});let r=YI(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),i=process.execPath,s=process.platform==="win32"?ev(t,i):QI(t,i);return await po.readFile(r,"utf8").catch(()=>null)===s||(await po.writeFile(r,s,"utf8"),process.platform!=="win32"&&await po.chmod(r,493)),n}L();se();import{execSync as Vp}from"node:child_process";import{readFileSync as Zp,unlinkSync as tv}from"node:fs";import{mkdir as nv,readFile as Kp,unlink as Xp,writeFile as rv}from"node:fs/promises";import{dirname as iv}from"node:path";function Jp(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var sv=A("single-instance"),go=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??F().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&&(sv.warn("removing stale pid file",{stalePid:e}),await Xp(this.pidFile).catch(()=>{})),await nv(iv(this.pidFile),{recursive:!0}),await rv(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await Kp(this.pidFile,"utf8")).trim()===String(process.pid)&&await Xp(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await Kp(this.pidFile,"utf8"),n=Number.parseInt(e.trim(),10);return Number.isFinite(n)&&n>0?n:null}catch(e){if(e.code==="ENOENT")return null;throw e}}isAlive(e){return Jp(e)?this.matchesDaemonTitle(e):!1}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=Zp(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes("coze-bridge-daemon")||n.includes("lib/index.js"))}catch{}try{let n=Vp(`ps -o command= -p ${e}`,{stdio:["ignore","pipe","ignore"],timeout:1e3}).toString();return n.trim()?n.includes("coze-bridge-daemon")||n.includes("lib/index.js"):!1}catch{return!0}}matchesDaemonTitleWindows(e){try{let r=Vp(`tasklist /FI "PID eq ${e}" /FO CSV /NH`,{stdio:["ignore","pipe","ignore"],timeout:2e3}).toString().trim();if(!r||/^(INFO|信息)[::]/.test(r))return!1;let i=r.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{Zp(this.pidFile,"utf8").trim()===String(process.pid)&&tv(this.pidFile)}catch{}})}};mo();var O=A("daemon"),hv="coze-bridge-daemon";async function Qp(){let t=F();process.env.COZE_BRIDGE_LOG_MODE!=="legacy"&&Rl({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:I=>Re(I,t).logs,listAgentIds:()=>Hl(t)});let e=new go({processTitle:hv}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let r=await qs(),i=r??{};Pi({pid:process.pid}),O.info(r?"loaded bridge config":"initialized bridge config");try{let I=new Ht;i.frameworksCache=await I.detectAll(),O.info("refreshed frameworks_cache",{detected:Object.keys(i.frameworksCache)})}catch(I){O.warn("framework detection failed",{err:String(I)})}await nr(i);let s=new fo(new pr),o=null,a=new Js({upstream:s,paths:t,bridgeConfig:i,sessionSpawner:async(I,b,x,ue)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(I,b,x,ue)}});await gv(t,a);let c=new Hs({paths:t,config:i,registry:a});o=c;let l,d,p=null,m={},f,h=null,g=new $t;function w(I){return g.enqueue(()=>S(I))}async function S(I){let b=I,x=b?.privatecode;if(!x)throw new _("IPC_BAD_REQUEST","/connect requires privatecode");let ue=Xr(b.env),Ee=b.handshake_url,Ne=b.frontier_url,Zt=Yp(b.env,Ee,Ne);if(l===x&&d===Zt){let me=await pv(t);return a.agents.size===0&&me?(O.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),yo(t,c).catch(Ao=>O.warn("connect-noop auto-revive error (ignored)",{err:String(Ao)}))):O.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Tn=!!l&&l!==x,gr=d!==void 0&&d!==Zt,mr=Tn||gr,wr=await Ja({privatecode:x,...Ee?{endpoint:Ee}:{},ppeOverride:ue});if(mr){O.warn("connect config switched, resetting agents",{pcChanged:Tn,envChanged:gr,previousPc:l?wo(l):"",nextPc:wo(x)});for(let me of[...a.agents.values()])await me.dispose("connect config switch").catch(()=>{}),a.agents.delete(me.agentId);a.disconnectedAgents.size>0&&(O.info("clearing disconnectedAgents set on connect config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await s.swap(new pr,"connect switch").catch(()=>{})}p=wr.deviceId,Pi({deviceId:p,pid:process.pid}),dc({patToken:x,env:b.env}).catch(me=>O.warn("coze-cli setup error (ignored)",{err:String(me)}));let Ti=new Si({handshake:wr,privatecode:x,...Ne?{urlOverride:Ne}:{},ppeOverride:ue,getPatTokenForAgent:me=>a.agents.get(me)?.patToken});return await s.swap(Ti,"connect"),l=x,d=Zt,m=ue,f=Ee,b.mock_scenario!==void 0&&(a.setMockScenario(b.mock_scenario),O.info("mock scenario set",{scenario:b.mock_scenario})),h||(h=new Qr({core:a,getDeviceId:()=>p??"",onTickEnd:()=>y.retryPending().catch(me=>O.warn("detailSync.retryPending failed (ignored)",{err:String(me)})),onAuthFailures:E})),h.start(),mr&&yo(t,c).catch(me=>O.warn("post-connect-switch auto-revive error (ignored)",{err:String(me)})),Ii(x,t).catch(me=>O.warn("writePatToken after /connect failed (ignored)",{err:String(me)})),O.info("/connect: WS established",{deviceId:p}),{ok:!0,note:"connected"}}a.registerExtension("_agent/create",async I=>c.createAgent(I.params)),a.registerExtension("_agent/health",async()=>({ok:!0}));let v={},u=new Ds({agents:a.agents,disposeAndMarkDisconnected:async(I,b)=>{let x=a.agents.get(I);if(x){await c.cleanupOpenclawSessionProviders(x).catch(Ee=>O.warn("cleanup openclaw providers failed (ignored)",{agentId:I,err:String(Ee)}));let ue=!0;try{await x.dispose(`disconnect: ${b}`)}catch(Ee){ue=!1,O.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:I,err:String(Ee)}),x.status="error"}ue&&(x.status="disconnected",a.unregister(I),a.disconnectedAgents.add(I))}else a.disconnectedAgents.add(I)},detailSyncer:async I=>{if(!v.ref)throw new Error("agent-detail-sync not initialized yet");await v.ref.syncOne(I)},cleanupOpenclawProviders:async I=>{await c.cleanupOpenclawSessionProviders(I)},openclawRepair:async(I,b)=>{await c.openclawRepair(I,b)},isRuntimePendingPermission:I=>a.hasPendingPermissionFor(I)});a.registerExtension("_agent/listSkills",I=>u.listSkills(I.params)),a.registerExtension("_agent/addSkills",I=>u.addSkills(I.params)),a.registerExtension("_agent/removeSkills",I=>u.removeSkills(I.params)),a.registerExtension("_agent/getFileTree",I=>u.getFileTree(I.params)),a.registerExtension("_agent/getFileContent",I=>u.getFileContent(I.params)),a.registerExtension("_agent/update",I=>u.updateAgent(I.params)),a.registerExtension("_agent/disconnect",I=>u.disconnectAgent(I.params)),a.registerExtension("_agent/switchModel",I=>u.switchModel(I.params)),a.registerExtension("_agent/reset",I=>u.resetAgent(I.params)),a.registerExtension("_agent/repair",I=>u.repairAgent(I.params));let y=new zi({paths:t,handlers:u,sendDetail:I=>a.sendRequest("_agent/detail",I)});v.ref=y;let E=async I=>{await Promise.allSettled(I.map(async b=>{try{await u.disconnectAgent({agentId:b.agentId,reason:`auth_failure: code=${b.code} ${b.message}`}),O.info("agent disconnected due to auth failure from heartbeat response",{agentId:b.agentId,code:b.code,message:b.message})}catch(x){O.warn("disconnect during authFailure handling failed (ignored)",{agentId:b.agentId,err:String(x)})}}))};s.onConnect(({initial:I})=>{O.info("frontier upstream connected, triggering detail sync",{initial:I}),y.syncAll(I?"initial-connect":"reconnect").catch(b=>O.warn("detail sync top-level error (ignored)",{err:String(b)}))});let R=new Vs({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let I=a.getMockScenario();return{running:!0,pid:process.pid,agents:[...a.agents.keys()],deviceId:p??"",frameworksCache:i.frameworksCache??{},...I?{mockScenario:I}:{}}}},{method:"POST",path:"/pair",handler:async I=>{let b=I,x=b?.privatecode,ue=b?.pairing_code;if(!x||!ue)throw new _("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let Ee=Xr(b.env),Ne=b.handshake_url,Zt=b.frontier_url,Tn=Yp(b.env,Ne,Zt),gr=!!l&&l!==x,mr=d!==void 0&&d!==Tn,wr=gr||mr,Ti=await Ja({privatecode:x,...Ne?{endpoint:Ne}:{},ppeOverride:Ee});if(wr){O.warn("pair config switched, resetting agents",{pcChanged:gr,envChanged:mr,previousPc:l?wo(l):"",nextPc:wo(x),previousEnvKey:d??"",nextEnvKey:Tn});for(let Se of[...a.agents.values()])await Se.dispose("pair config switch").catch(()=>{}),a.agents.delete(Se.agentId);a.disconnectedAgents.size>0&&(O.info("clearing disconnectedAgents set on pair config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await s.swap(new pr,"pair switch").catch(()=>{})}p=Ti.deviceId,Pi({deviceId:p,pid:process.pid}),dc({patToken:x,env:b.env}).catch(Se=>O.warn("coze-cli setup error (ignored)",{err:String(Se)}));let me=new Si({handshake:Ti,privatecode:x,...Zt?{urlOverride:Zt}:{},ppeOverride:Ee,getPatTokenForAgent:Se=>a.agents.get(Se)?.patToken});await s.swap(me,"pair");try{let Se=new Ht;i.frameworksCache=await Se.detectAll(),await nr(i),O.info("frameworks_cache refreshed before pair",{detected:Object.keys(i.frameworksCache)})}catch(Se){O.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(Se)})}let Ao=Object.keys(i.frameworksCache??{});try{let Se=await a.sendRequest("_agent/pair",{pairCode:ue,patToken:x,frameworks:Ao,_meta:{cozeDeviceId:p}});O.info("_agent/pair ok",{pairResult:Se}),l=x,d=Tn,m=Ee,f=Ne,b.mock_scenario!==void 0&&(a.setMockScenario(b.mock_scenario),O.info("mock scenario set",{scenario:b.mock_scenario})),Ii(x,t).catch(Xe=>O.warn("writePatToken after /pair failed (ignored)",{err:String(Xe)})),h||(h=new Qr({core:a,getDeviceId:()=>p??"",onTickEnd:()=>y.retryPending().catch(Xe=>O.warn("detailSync.retryPending failed (ignored)",{err:String(Xe)})),onAuthFailures:E})),h.start(),wr&&yo(t,c).catch(Xe=>O.warn("post-pair-switch auto-revive error (ignored)",{err:String(Xe)}));let xo;return b.agent_id&&(xo=await mv(b.agent_id,t,c,Xe=>a.sendRequest("_agent/detail",Xe),x).catch(Xe=>(O.error("--agent-id ensureAgent failed",{agentId:b.agent_id,err:String(Xe)}),{ok:!1,agentId:b.agent_id??"",note:String(Xe)}))),{ok:!0,note:"paired with cloud",...xo?{agent:xo}:{}}}catch(Se){return O.error("_agent/pair failed",{err:String(Se)}),{ok:!1,note:`pair failed: ${String(Se)}`}}}},{method:"POST",path:"/connect",handler:I=>w(I)},{method:"POST",path:"/_agent/create",handler:async I=>{let b=I;return{ok:!0,result:await c.createAgent(b)}}},{method:"POST",path:"/agent/send",handler:async I=>{let b=I;if(!b?.agentId||!b?.sessionId||!b?.kind||!b?.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 x=b;return await(x.groupFile?Gf:$f)(x,{core:a,patToken:l,handshakeBase:f,ppeOverride:m})}catch(x){if(x instanceof _)return{ok:!1,code:x.code,message:x.message};throw x}}},{method:"POST",path:"/refresh",handler:async()=>{O.info("IPC /refresh: re-detecting frameworks");let I=new Ht;return i.frameworksCache=await I.detectAll(),await nr(i),{ok:!0,frameworks:i.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(O.info("IPC /shutdown received"),setImmediate(()=>{U.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:T,token:D}=await R.start();try{await qp(t.libEntry,t)}catch(I){O.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(I)})}await a.start(),yo(t,c).catch(I=>O.warn("auto-revive top-level error (ignored)",{err:String(I)})),Bl().then(async()=>{let{probeAcpVersion:I}=await Promise.resolve().then(()=>(Xt(),Fl));for(let b of["claude-code","codex"]){let x=await I(b);x&&O.info("acp wrapper version",{framework:b,version:x})}}).catch(I=>O.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(I)}));let C=null,U={port:T,token:D,core:a,ipc:R,shutdown(I){return C||(O.info("daemon shutdown",{reason:I}),C=(async()=>{h?.stop(),await a.stop(I),await R.stop(),await e.release()})(),C)}};for(let I of["SIGTERM","SIGINT"])process.on(I,()=>{U.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:T,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(i.frameworksCache??{}),libVersion:i.libVersion??"dev"}),wv({cliSpawned:process.env[ul]==="1",readPatToken:()=>ho(t),connect:w}).catch(I=>O.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(I)})),U}async function pv(t){let{readdir:e}=await import("node:fs/promises");try{return(await e(t.agentsRoot)).length>0}catch{return!1}}function wo(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function Yp(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function gv(t,e){let{readdir:n}=await import("node:fs/promises"),r;try{r=await n(t.agentsRoot)}catch{return}let{loadAgentConfig:i,enforceAgentConfigMode:s}=await Promise.resolve().then(()=>(Rt(),Ui));for(let o of r){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 mv(t,e,n,r,i){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(Rt(),Ui)),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 n.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 r({_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 n.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 yo(t,e){let{readdir:n}=await import("node:fs/promises"),r;try{r=await n(t.agentsRoot)}catch{return{revived:0,skipped:0,total:0}}if(r.length===0)return{revived:0,skipped:0,total:0};let{loadAgentConfig:i}=await Promise.resolve().then(()=>(Rt(),Ui));O.info("auto-revive: scanning local agents on startup",{count:r.length});let s=0,o=0;for(let a of r){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=yv(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:r.length}),{revived:s,skipped:o,total:r.length}}async function wv(t){let e=t.logger??O;if(t.cliSpawned)return"skipped-cli";let n=await t.readPatToken();return n?(e.info("supervisor-spawned daemon, auto-connecting with stored PAT"),t.connect({privatecode:n}).catch(r=>e.warn("startup auto-connect failed (staying idle)",{err:String(r)})),"connecting"):(e.info("no stored PAT, skip startup auto-connect"),"skipped-no-pat")}function yv(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}mo();se();import{readFile as eg}from"node:fs/promises";var Tt=class{paths;constructor(e){this.paths=e??F()}async probe(e=1e3){let n=await _o(this.paths);if(!n)return{kind:"not-running"};try{let r=await this.fetch(n,{method:"GET",path:"/status",timeoutMs:e});return r.status===200?{kind:"connected",...n}:{kind:"stale",reason:`unexpected status ${r.status}`}}catch(r){return{kind:"stale",reason:Ev(r)}}}async request(e){let n=await _o(this.paths);if(!n)throw new Error("coze-bridge daemon not running (no port/token files)");return this.fetch(n,e)}async fetch(e,n){let r=n.body!==void 0,i={Authorization:`Bearer ${e.token}`};r&&(i["content-type"]="application/json");let s=new AbortController,o=setTimeout(()=>s.abort(),n.timeoutMs??5e3);try{let a=await fetch(`http://127.0.0.1:${e.port}${n.path}`,{method:n.method,headers:i,body:r?JSON.stringify(n.body):void 0,signal:s.signal}),c=await a.text();return{status:a.status,body:_v(c)}}finally{clearTimeout(o)}}};async function _o(t){try{let[e,n]=await Promise.all([eg(t.portFile,"utf8"),eg(t.tokenFile,"utf8")]),r=Number.parseInt(e.trim(),10),i=n.trim();return!Number.isFinite(r)||r<=0||!i?null:{port:r,token:i}}catch(e){if(e.code==="ENOENT")return null;throw e}}function _v(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function Ev(t){return t instanceof Error?t.message:String(t)}ft();L();se();function Vt(t,...e){let n=[],r;for(let i=0;i<t.length;i++){let s=t[i],o=!1;for(let a of e){if(s===a){r=t[i+1],i+=1,o=!0;break}if(s.startsWith(`${a}=`)){r=s.slice(a.length+1),o=!0;break}}o||n.push(s)}return{value:r,rest:n}}import{copyFile as tg,mkdir as Sv,readFile as pl,writeFile as Iv}from"node:fs/promises";import{homedir as LP}from"node:os";import{dirname as vv,resolve as gl,sep as Eo}from"node:path";import{fileURLToPath as Tv}from"node:url";L();se();var ng=A("dist-install");function Rv(t){let e=Tv(t),n=vv(e),r=`${Eo}src${Eo}`;if(n.includes(r)||n.endsWith(`${Eo}src${Eo}cli`))return null;let i=gl(n,"index.js"),s=gl(n,"..","package.json");return{dist:i,pkgJson:s}}async function ml(t={}){let e=t.paths??F(),n=Rv(import.meta.url),r=t.sourceDist??n?.dist,i=t.sourcePackageJson??n?.pkgJson;if(!r||!i)return{kind:"dev-mode-skip",reason:"running from src/(tsx loader);no dist/ to install"};if(r===e.libEntry)return{kind:"dev-mode-skip",reason:"running from installed lib path; no re-install needed"};let s;try{s=JSON.parse(await pl(i,"utf8")).version??"unknown"}catch(p){return ng.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 qs(e.configFile)??{},a=o.libVersion;if(a===s)try{return await pl(e.libEntry),{kind:"already-current",libVersion:s}}catch{}await Sv(e.libDir,{recursive:!0}),await tg(r,e.libEntry),await tg(`${r}.map`,`${e.libEntry}.map`).catch(()=>{});let c=gl(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
|
|
97
|
+
`;return await pl(c,"utf8").catch(()=>null)!==l&&await Iv(c,l),o.libVersion=s,await nr(o,e.configFile),ng.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}}Co();L();se();import{closeSync as ig,fstatSync as sg,openSync as og,readFileSync as kv,readSync as bv,readdirSync as Av,statSync as xv}from"node:fs";import{join as So}from"node:path";var Ov=new Set(["debug","info","warn","error"]);function ag(t){let e=t,n=Vt(e,"--agent-id");e=n.rest;let r=Vt(e,"--date");e=r.rest;let i=Vt(e,"-n","--lines");e=i.rest;let s=Vt(e,"--level");e=s.rest;let o=Vt(e,"--grep");e=o.rest;let a=i.value===void 0?200:Number(i.value),c=Number.isInteger(a)&&a>=0?a:200,l=s.value&&Ov.has(s.value)?s.value:void 0,d={lines:c,follow:e.includes("-f")||e.includes("--follow"),raw:e.includes("--raw"),list:e.includes("--list")};return n.value&&(d.agentId=n.value),r.value&&(d.date=r.value),l&&(d.level=l),o.value&&(d.grep=o.value),d}function Pv(t,e){return t.agentId?So(Re(t.agentId,e).logs,bi("agent",t.date)):So(e.bridgeLogsDir,bi("bridge",t.date))}function Cv(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function Dv(t,e){let n;try{n=Av(t)}catch{return[]}let r=[];for(let i of n){let s=Po(i,e);if(!s)continue;let o=0;try{o=xv(So(t,i)).size}catch{}r.push({file:So(t,i),date:s,size:o})}return r.sort((i,s)=>s.date.localeCompare(i.date)),r}function cg(t,e){if(e.grep&&!t.includes(e.grep))return!1;if(e.level){let n;try{n=JSON.parse(t).level}catch{return!0}if(typeof n=="string"&&!Al(n,e.level))return!1}return!0}var rg={debug:"90",info:"36",warn:"33",error:"31"},Nv=new Set(["ts","level","module","msg"]);function Lv(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function lg(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let r=Lv(n.ts),i=typeof n.level=="string"?n.level:"",s=i.toUpperCase().padEnd(5);e.color&&rg[i]&&(s=`\x1B[${rg[i]}m${s}\x1B[0m`);let o=typeof n.module=="string"?n.module:"",a=typeof n.msg=="string"?n.msg:"",c=Object.entries(n).filter(([l])=>!Nv.has(l)).map(([l,d])=>` ${l}=${typeof d=="string"?d:JSON.stringify(d)}`).join("");return`${r} ${s} ${o} ${a}${c}`}function Fv(t,e,n){let s=kv(t,"utf8").split(`
|
|
98
|
+
`).filter(o=>o.length>0).filter(o=>cg(o,{level:e.level,grep:e.grep}));for(let o of Cv(s,e.lines))process.stdout.write(`${lg(o,{raw:e.raw,color:n})}
|
|
99
|
+
`)}async function dg(t,e){let n=e.paths??F(),r=process.stdout.isTTY===!0;if(t.list){let o=t.agentId?Re(t.agentId,n).logs:n.bridgeLogsDir,a=t.agentId?"agent":"bridge",c=Dv(o,a);if(c.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${o}
|
|
100
100
|
`),1;for(let l of c)process.stdout.write(`${l.date} ${(l.size/1024).toFixed(1)}KB ${l.file}
|
|
101
|
-
`);return 0}let i=t.date??
|
|
101
|
+
`);return 0}let i=t.date??Rn(new Date),s=Pv({agentId:t.agentId,date:i},n);try{Fv(s,t,r)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${s}
|
|
102
102
|
\u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
|
|
103
|
-
(legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${
|
|
104
|
-
`),1}return t.follow&&await
|
|
105
|
-
`);i=c.pop()??"";for(let l of c)l.length>0&&
|
|
106
|
-
`)}await new Promise(c=>setTimeout(c,
|
|
103
|
+
(legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
|
|
104
|
+
`),1}return t.follow&&await Uv(s,t,r),0}var Mv=500;function Bv(t){try{let e=og(t,"r");try{return sg(e).size}finally{ig(e)}}catch{return 0}}async function Uv(t,e,n){let r=Bv(t),i="",s=!1,o=()=>{s=!0};process.on("SIGINT",o);try{for(;!s;){let a="";try{let c=og(t,"r");try{let l=sg(c).size;if(l>r){let d=Buffer.allocUnsafe(l-r),p=bv(c,d,0,d.length,r);a=d.subarray(0,p).toString("utf8"),r+=p}}finally{ig(c)}}catch{}if(a){let c=(i+a).split(`
|
|
105
|
+
`);i=c.pop()??"";for(let l of c)l.length>0&&cg(l,{level:e.level,grep:e.grep})&&process.stdout.write(`${lg(l,{raw:e.raw,color:n})}
|
|
106
|
+
`)}await new Promise(c=>setTimeout(c,Mv))}}finally{process.off("SIGINT",o)}}import{basename as zv,resolve as $v}from"node:path";se();var Gv=9e4,Hv={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,AGENT_APPROVAL_TIMEOUT:1};function jv(t){return Hv[t]??1}async function ug(t,e={}){let n=e.paths??F();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>
|
|
107
107
|
`),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.
|
|
108
|
-
`),3;let
|
|
109
|
-
`),4;let i={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path
|
|
108
|
+
`),3;let r=await _o(n).catch(()=>null);if(!r)return process.stderr.write(`Error: coze-bridge daemon not running (cannot read ${n.portFile} / ${n.tokenFile}). Make sure you are inside an agent session spawned by the daemon.
|
|
109
|
+
`),4;let i={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:$v(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 Wv(r,"/agent/send",i,Gv)}catch(o){return process.stderr.write(`Error: daemon IPC failed: ${o instanceof Error?o.message:String(o)}
|
|
110
110
|
`),4}if(!s.ok)return process.stderr.write(`Error: ${s.code}: ${s.message}
|
|
111
|
-
`),
|
|
112
|
-
`);else{let o=t.name??
|
|
113
|
-
`)}else process.stdout.write(`Sent ${t.kind} ${o} (${
|
|
114
|
-
`)}return 0}async function
|
|
115
|
-
`)}function
|
|
111
|
+
`),jv(s.code);if(t.json)process.stdout.write(`${JSON.stringify(s)}
|
|
112
|
+
`);else{let o=t.name??zv(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})
|
|
113
|
+
`)}else process.stdout.write(`Sent ${t.kind} ${o} (${qv(s.bytes)})
|
|
114
|
+
`)}return 0}async function Wv(t,e,n,r){let i=new AbortController,s=setTimeout(()=>i.abort(),r);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(n),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 qv(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var _g=A("cli");function ge(t,e){let{value:n,rest:r}=Vt(t,e);return{value:n,rest:r}}function vi(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
|
|
115
|
+
`)}function uT(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 fT(e.slice(1));if(e[0]==="log")return{mode:"log",...ag(e.slice(1))};if(e[0]==="connect")return hT(e.slice(1));if(e.includes("--status"))return vi("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return vi("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--refresh"))return vi("--refresh","coze-bridge refresh"),{mode:"refresh"};if(e.includes("--uninstall"))return vi("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return vi("--install-service","coze-bridge service install"),{mode:"service-install"};if(e.includes("--help")||e.includes("-h")||e.length===0)return{mode:"help"};let n=e,{value:r,rest:i}=ge(n,"--pat-token");n=i;let{value:s,rest:o}=ge(n,"--pair-code");n=o;let{value:a,rest:c}=ge(n,"--env");n=c;let{value:l,rest:d}=ge(n,"--handshake-url");n=d;let{value:p,rest:m}=ge(n,"--frontier-url");n=m;let{value:f,rest:h}=ge(n,"--mock-scenario");n=h;let{value:g}=ge(n,"--agent-id");if(!r||!s)return{mode:"help"};let w={mode:"pair",privatecode:r,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 fT(t){let e=t[0],n=t[1];if(e!=="image"&&e!=="file")return{mode:"help"};if(!n||n.startsWith("--"))return{mode:"help"};let r=t.slice(2),{value:i,rest:s}=ge(r,"--caption");r=s;let{value:o,rest:a}=ge(r,"--name");r=a;let{value:c,rest:l}=ge(r,"--agent-id");r=l;let{value:d,rest:p}=ge(r,"--session-id");r=p;let{value:m,rest:f}=ge(r,"--mime");r=f;let h=r.includes("--group-file");r=r.filter(S=>S!=="--group-file");let g=r.includes("--json"),w={mode:"send",kind:e,path:n,json:g};return i&&(w.caption=i),o&&(w.name=o),c&&(w.agentId=c),d&&(w.sessionId=d),h&&(w.groupFile=!0),m&&(w.mimeType=m),w}function hT(t){let e=t,{value:n,rest:r}=ge(e,"--pat-token");e=r;let{value:i,rest:s}=ge(e,"--env");e=s;let{value:o,rest:a}=ge(e,"--handshake-url");e=a;let{value:c,rest:l}=ge(e,"--frontier-url");e=l;let{value:d,rest:p}=ge(e,"--mock-scenario");e=p;let m={mode:"connect"};return n&&(m.privatecode=n),i&&(m.env=i),o&&(m.handshakeUrl=o),c&&(m.frontierUrl=c),d&&(m.mockScenario=d),m}var pT=`
|
|
116
116
|
coze-bridge - local bridge daemon for cloud Agent Service
|
|
117
117
|
|
|
118
118
|
Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
|
|
@@ -191,47 +191,47 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
|
|
|
191
191
|
|
|
192
192
|
Internal:
|
|
193
193
|
<node> <entry> --daemon daemon mode (OS supervisor only)
|
|
194
|
-
`.trimStart();async function
|
|
195
|
-
`),0;case"daemon":{try{await
|
|
196
|
-
`),1;if(
|
|
197
|
-
`),1;let i=await
|
|
194
|
+
`.trimStart();async function Eg(t=process.argv,e={}){let n=uT(t);switch(n.mode){case"help":return process.stdout.write(pT),0;case"version":return process.stdout.write(`${Xn}
|
|
195
|
+
`),0;case"daemon":{try{await Qp()}catch(r){return _g.error("daemon start failed",{err:String(r)}),1}return new Promise(()=>{})}case"status":return gT(e);case"stop":return Ig(e);case"refresh":return yT(e);case"log":return dg(n,e);case"update":return mT(e);case"purge":return _T(e);case"service-install":return ET(e);case"service-uninstall":return ST(e);case"pair":{let r={};return n.env&&(r.env=n.env),n.handshakeUrl&&(r.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(r.frontierUrl=n.frontierUrl),n.mockScenario&&(r.mockScenario=n.mockScenario),IT(n.privatecode,n.pairingCode,e,r,n.agentId)}case"connect":{let r={};return n.env&&(r.env=n.env),n.handshakeUrl&&(r.handshakeUrl=n.handshakeUrl),n.frontierUrl&&(r.frontierUrl=n.frontierUrl),n.mockScenario&&(r.mockScenario=n.mockScenario),vT(n.privatecode,e,r)}case"send":return ug({kind:n.kind,path:n.path,...n.agentId?{agentId:n.agentId}:{},...n.sessionId?{sessionId:n.sessionId}:{},...n.caption?{caption:n.caption}:{},...n.name?{name:n.name}:{},...n.groupFile?{groupFile:!0}:{},...n.mimeType?{mimeType:n.mimeType}:{},json:n.json},e)}}async function Sg(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 gT(t){let e=t.paths??F(),n=new Tt(e),r=await n.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
196
|
+
`),1;if(r.kind==="stale")return await Sg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
197
|
+
`),1;let i=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
|
|
198
198
|
${JSON.stringify(i.body,null,2)}
|
|
199
|
-
`),0}async function
|
|
200
|
-
`),0;if(
|
|
201
|
-
`),0;try{return await
|
|
199
|
+
`),0}async function Ig(t){let e=t.paths??F(),n=new Tt(e),r=await n.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
|
|
200
|
+
`),0;if(r.kind==="stale")return await Sg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
|
|
201
|
+
`),0;try{return await n.request({method:"POST",path:"/shutdown"}),process.stdout.write(`coze-bridge: stopped
|
|
202
202
|
`),0}catch(i){return process.stdout.write(`coze-bridge: stop failed: ${String(i)}
|
|
203
|
-
`),1}}async function
|
|
204
|
-
`),e(1)})})}async function
|
|
205
|
-
`),1;try{let
|
|
206
|
-
${JSON.stringify(
|
|
207
|
-
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(
|
|
208
|
-
`),1)}catch(
|
|
209
|
-
`),1}}async function
|
|
203
|
+
`),1}}async function mT(t){return await Ig(t),(t.spawnNpx??wT)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function wT(t){return new Promise(e=>{let n=Le("npx",t,{stdio:"inherit"});n.on("exit",r=>e(r??1)),n.on("error",r=>{process.stderr.write(`coze-bridge: spawn npx failed: ${String(r)}
|
|
204
|
+
`),e(1)})})}async function yT(t){let e=new Tt(t.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
|
|
205
|
+
`),1;try{let r=await e.request({method:"POST",path:"/refresh",timeoutMs:35e3});return r.status===200?(process.stdout.write(`coze-bridge: refreshed
|
|
206
|
+
${JSON.stringify(r.body,null,2)}
|
|
207
|
+
`),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(r.body)}
|
|
208
|
+
`),1)}catch(r){return process.stderr.write(`coze-bridge: refresh failed: ${String(r)}
|
|
209
|
+
`),1}}async function Il(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:n}=await Promise.resolve().then(()=>(yg(),wg)),r=e(),i=n();return{platform:r.platform,install:()=>r.install(i),uninstall:()=>r.uninstall(i)}}async function _T(t){let e=new Tt(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
|
|
210
210
|
`);try{await e.request({method:"POST",path:"/shutdown"})}catch(o){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(o)}
|
|
211
|
-
`)}await new Promise(o=>setTimeout(o,500))}let
|
|
211
|
+
`)}await new Promise(o=>setTimeout(o,500))}let r=await Il(t);if(r)try{await r.uninstall(),process.stdout.write(`coze-bridge: ${r.platform} supervisor unregistered
|
|
212
212
|
`)}catch(o){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(o)}
|
|
213
|
-
`)}let i=t.paths??
|
|
213
|
+
`)}let i=t.paths??F(),{rm:s}=await import("node:fs/promises");try{await s(i.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${i.bridgeRoot}
|
|
214
214
|
`)}catch(o){return process.stderr.write(`coze-bridge: remove failed: ${String(o)}
|
|
215
215
|
`),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
|
|
216
|
-
`),0}async function
|
|
216
|
+
`),0}async function ET(t){let e=await Il(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
|
|
217
217
|
`),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
|
|
218
|
-
`),0}catch(
|
|
219
|
-
`),1}}async function
|
|
220
|
-
`),0}catch(
|
|
221
|
-
`),1}}async function
|
|
218
|
+
`),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
|
|
219
|
+
`),1}}async function ST(t){let e=await Il(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
|
|
220
|
+
`),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
|
|
221
|
+
`),1}}async function IT(t,e,n,r={},i){let s=new Tt(n.paths),o=n.spawnDaemon??hl;if(!n.skipDistInstall){let l=await ml({paths:n.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
|
|
222
222
|
`),(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}
|
|
223
223
|
`)}let a=await s.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
|
|
224
|
-
`),await o({paths:
|
|
225
|
-
`),1;let c={privatecode:t,pairing_code:e};
|
|
224
|
+
`),await o({paths:n.paths}),a=await vg(s,n.waitTimeoutMs??1e4,n.sleep??Tg),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
|
|
225
|
+
`),1;let c={privatecode:t,pairing_code:e};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),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}
|
|
226
226
|
`),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"
|
|
227
227
|
`),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(l.body)}
|
|
228
228
|
`),1}catch(l){return process.stderr.write(`coze-bridge: pair failed: ${String(l)}
|
|
229
|
-
`),1}}async function
|
|
229
|
+
`),1}}async function vT(t,e,n={}){let r=e.paths??F(),i=t??await ho(r);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 Tt(e.paths),o=e.spawnDaemon??hl;if(!e.skipDistInstall){let l=await ml({paths:e.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
|
|
230
230
|
`),(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}
|
|
231
231
|
`)}let a=await s.probe();if(a.kind!=="connected"&&(process.stdout.write(`coze-bridge: starting daemon...
|
|
232
|
-
`),await o({paths:e.paths}),a=await
|
|
233
|
-
`),1;let c={privatecode:i};
|
|
234
|
-
`),await
|
|
232
|
+
`),await o({paths:e.paths}),a=await vg(s,e.waitTimeoutMs??1e4,e.sleep??Tg),a.kind!=="connected"))return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
|
|
233
|
+
`),1;let c={privatecode:i};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);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"})
|
|
234
|
+
`),await Ii(i,r).catch(d=>_g.warn("writePatToken after connect failed (ignored)",{err:String(d)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(l.body)}
|
|
235
235
|
`),1)}catch(l){return process.stderr.write(`coze-bridge: connect failed: ${String(l)}
|
|
236
|
-
`),1}}async function
|
|
236
|
+
`),1}}async function vg(t,e,n){let r=Date.now()+e;for(;Date.now()<r;){let i=await t.probe(500);if(i.kind==="connected")return i;await n(200)}return t.probe(500)}function Tg(t){return new Promise(e=>setTimeout(e,t))}L();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&kl("warn");Eg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
|
|
237
237
|
`),process.exit(1)});
|