coze-bridge 0.1.93-beta.1 → 0.1.93-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +47 -47
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,25 +5,25 @@ 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 $g=Object.create;var Ho=Object.defineProperty;var Gg=Object.getOwnPropertyDescriptor;var Hg=Object.getOwnPropertyNames;var jg=Object.getPrototypeOf,Wg=Object.prototype.hasOwnProperty;var j=(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 ve=(t,e)=>()=>(t&&(e=t(t=0)),e);var H=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ui=(t,e)=>{for(var n in e)Ho(t,n,{get:e[n],enumerable:!0})},qg=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Hg(e))!Wg.call(t,i)&&i!==n&&Ho(t,i,{get:()=>e[i],enumerable:!(r=Gg(e,i))||r.enumerable});return t};var ht=(t,e,n)=>(n=t!=null?$g(jg(t)):{},qg(e||!t||!t.__esModule?Ho(n,"default",{value:t,enumerable:!0}):n,t));function pt(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var zi=ve(()=>{"use strict"});import{createWriteStream as Jg,mkdirSync as Vg,readdirSync as Zg,unlinkSync as Kg}from"node:fs";import{join as Ll}from"node:path";function en(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function On(t,e){return`${t}-${e}.log`}function jo(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Xg(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 $i(t,e,n,r){let i;try{i=Zg(t)}catch{return}for(let s of i){let o=jo(s,e);if(o&&Xg(o,n,r))try{Kg(Ll(t,s))}catch{}}}var Ar,Wo=ve(()=>{"use strict";Ar=class{constructor(e,n,r){this.dir=e;this.prefix=n;this.opts=r;this.clock=r.clock??(()=>en(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{Vg(this.dir,{recursive:!0});let n=Jg(Ll(this.dir,On(this.prefix,e)),{flags:"a"});n.on("error",r=>process.stderr.write(`[log-sink] stream error: ${String(r)}
8
+ var $g=Object.create;var Ho=Object.defineProperty;var Gg=Object.getOwnPropertyDescriptor;var Hg=Object.getOwnPropertyNames;var jg=Object.getPrototypeOf,Wg=Object.prototype.hasOwnProperty;var j=(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 ve=(t,e)=>()=>(t&&(e=t(t=0)),e);var H=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Bi=(t,e)=>{for(var n in e)Ho(t,n,{get:e[n],enumerable:!0})},qg=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Hg(e))!Wg.call(t,i)&&i!==n&&Ho(t,i,{get:()=>e[i],enumerable:!(r=Gg(e,i))||r.enumerable});return t};var ht=(t,e,n)=>(n=t!=null?$g(jg(t)):{},qg(e||!t||!t.__esModule?Ho(n,"default",{value:t,enumerable:!0}):n,t));function pt(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var Ui=ve(()=>{"use strict"});import{createWriteStream as Jg,mkdirSync as Vg,readdirSync as Zg,unlinkSync as Kg}from"node:fs";import{join as Ll}from"node:path";function Qt(t){let e=n=>String(n).padStart(2,"0");return`${t.getFullYear()}-${e(t.getMonth()+1)}-${e(t.getDate())}`}function On(t,e){return`${t}-${e}.log`}function jo(t,e){let n=t.match(/^(.+)-(\d{4}-\d{2}-\d{2})\.log$/);return!n||n[1]!==e?null:n[2]??null}function Xg(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 zi(t,e,n,r){let i;try{i=Zg(t)}catch{return}for(let s of i){let o=jo(s,e);if(o&&Xg(o,n,r))try{Kg(Ll(t,s))}catch{}}}var br,Wo=ve(()=>{"use strict";br=class{constructor(e,n,r){this.dir=e;this.prefix=n;this.opts=r;this.clock=r.clock??(()=>Qt(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{Vg(this.dir,{recursive:!0});let n=Jg(Ll(this.dir,On(this.prefix,e)),{flags:"a"});n.on("error",r=>process.stderr.write(`[log-sink] stream error: ${String(r)}
9
9
  `)),this.stream=n}catch(n){process.stderr.write(`[log-sink] rotate failed: ${String(n)}
10
- `),this.stream=void 0;return}this.currentDate!==void 0&&$i(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Yg,mkdirSync as Qg}from"node:fs";import{join as em}from"node:path";function Ml(t){let e=t.retentionDays??rm,n=t.clock??(()=>en(new Date));Hi={bridgeSink:new Ar(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:i=>new Ar(t.agentLogsDir(i),"agent",{retentionDays:e,clock:n})};let r=n();$i(t.bridgeLogsDir,"bridge",r,e);for(let i of t.listAgentIds?.()??[])$i(t.agentLogsDir(i),"agent",r,e)}function im(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Bl(t){qo=t}function Ul(t){return Pn[qo]<=Pn[t]}function zl(t,e){let n=Pn[t];return n===void 0?!0:n>=Pn[e]}function ji(t){Fl={...t}}function $l(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`${en(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${r}${s}:${o}`}function xr(t,e,n,r,i){try{let s=`${JSON.stringify({ts:$l(new Date),level:e,module:n,msg:r,...i})}
11
- `;Qg(t,{recursive:!0}),Yg(em(t,On("bridge",en(new Date))),s)}catch{}}function sm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function Gi(t,e,n,r,i){if(Pn[t]<Pn[qo])return;let s=`${JSON.stringify({ts:$l(new Date),level:t,module:e,msg:n,...Fl,...r})}
12
- `;if(Hi){let o=sm(i,r),a=o?im(Hi,o):Hi.bridgeSink;try{a.write(s)}catch{process.stderr.write(s)}return}t==="error"||t==="warn"?nm.write(s):tm.write(s)}function b(t,e){return{debug:(n,r)=>Gi("debug",t,n,r,e),info:(n,r)=>Gi("info",t,n,r,e),warn:(n,r)=>Gi("warn",t,n,r,e),error:(n,r)=>Gi("error",t,n,r,e),child:n=>b(`${t}.${n}`,e),forAgent:n=>b(t,n)}}var Pn,qo,tm,nm,Fl,rm,Hi,F=ve(()=>{"use strict";zi();Wo();Pn={debug:10,info:20,warn:30,error:40},qo=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),tm=process.stdout,nm=process.stderr,Fl={},rm=pt("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Hi=null});import{execFile as om,spawn as am,spawnSync as uR}from"node:child_process";import{promisify as cm}from"node:util";function dm(t){if(process.platform!=="win32")return!1;if(Gl.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(Gl,"").toLowerCase();return lm.has(n)}function Hl(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return dm(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function Fe(t,e=[],n={}){return am(t,e,Hl(t,n))}function Cn(t,e=[],n={}){return um(t,e,Hl(t,n))}var lm,Gl,um,gt=ve(()=>{"use strict";lm=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Gl=/\.(cmd|bat|ps1)$/i;um=cm(om)});var _,Te=ve(()=>{"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 Yl={};Ui(Yl,{_resetAcpInstallerForTests:()=>Em,_resetInstallTimeoutsForTests:()=>_m,_setBinaryPathCacheForTests:()=>vm,_setInFlightForTests:()=>Sm,_setInstallTimeoutsForTests:()=>ym,buildInstallFailureMessage:()=>Xl,ensureAcpInstalled:()=>tn,formatExecError:()=>ql,getAcpBinaryPath:()=>Or,getAcpPackageSpec:()=>mm,getInFlightInstall:()=>Zo,npmInstallGlobal:()=>Kl,parseVersionTriple:()=>Vl,pickWhichLine:()=>Ji,probeAcpVersion:()=>Jl,resolveAcpCommand:()=>Pr,versionSatisfiesSpec:()=>Zl});import{readFile as fm,realpath as hm,stat as pm}from"node:fs/promises";import{dirname as Jo,join as gm}from"node:path";function mm(t){let e=Vo[t];if(e)return`${e.npmPackage}@${e.versionSpec}`}function ym(t,e){Wi=t,qi=e}function _m(){Wi=5e4,qi=5e3}function ql(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 jl(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:n}=await Cn(e,[t],{timeout:wm});return Ji(n)}catch{return}}function Ji(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 Jl(t,e){let n=Vo[t];if(!n)return;let r=e??Or(t);if(!r){le.warn("acp wrapper probe: binary path cache empty",{framework:t,binary:n.binary,hint:"ensureAcpInstalled \u6CA1\u8DD1\u8FC7 / \u88C5\u5931\u8D25 / \u4E4B\u524D negative cache 5min \u5185"});return}let i;try{i=await hm(r)}catch(o){le.warn("acp wrapper probe: realpath failed (symlink target \u4E0D\u5B58\u5728?)",{framework:t,binaryPath:r,err:String(o)});return}let s=Jo(i);for(let o=0;o<Wl;o++){let a=gm(s,"package.json");try{if(!(await pm(a)).isFile()){s=Jo(s);continue}let d=await fm(a,"utf8"),p=JSON.parse(d);if(p.name===n.npmPackage){if(typeof p.version=="string"&&p.version.length>0)return p.version;le.warn("acp wrapper probe: package.json \u627E\u5230\u4F46 version \u5B57\u6BB5\u7F3A",{framework:t,packageJsonPath:a});return}}catch(l){let d=l;d.code!=="ENOENT"&&le.warn("acp wrapper probe: package.json \u8BFB\u53D6\u5F02\u5E38",{framework:t,candidate:a,errCode:d?.code,err:String(l)})}let c=Jo(s);if(c===s)break;s=c}le.warn("acp wrapper probe: \u627E\u4E0D\u5230\u5339\u914D name \u7684 package.json (\u4E0A\u6EAF\u5230 max depth)",{framework:t,binaryPath:r,realBinary:i,expectedName:n.npmPackage,maxDepth:Wl})}function Vl(t){let e=/^\s*(\d+)\.(\d+)\.(\d+)/.exec(t);return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Zl(t,e){let n=Vl(t);if(!n)return!0;let r=/^\^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(e.trim());if(!r)return!0;let[i,s,o]=n,a=Number(r[1]),c=Number(r[2]),l=r[3]!==void 0?Number(r[3]):0;return i>a||i===a&&(s>c||s===c&&o>=l)?a>=1?i===a:c>=1?i===0&&s===c:i===0&&s===0&&o===l:!1}async function Kl(t,e,n){let r=`${t}@${e}`;le.info("npm install -g start",{npmPackage:t,versionSpec:e});let i=Date.now(),s=process.platform==="win32";return new Promise((o,a)=>{let c=Fe("npm",["install","-g",r],{stdio:["ignore","pipe","pipe"],...s?{}:{detached:!0}});if(!c.pid){c.once("error",y=>{le.warn("npm spawn failed (no pid, error swallowed)",{npmPackage:t,err:String(y)})}),a(new Error(`failed to spawn npm: no pid (npmPackage=${t})`));return}let l=c.pid,d=10*1024*1024,p=[],m=[],u=0,h=0;c.stdout?.on("data",y=>{u+=y.length,u<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 le.warn("npm install: kill failed (process already dead?)",{npmPackage:t,pid:l,sig:y,err:String(E)}),!1}},v=setTimeout(()=>{g="terminating",le.warn("npm install timeout, sending SIGTERM to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,timeoutMs:Wi,graceMs:qi,stdoutBytes:u,stderrBytes:h}),S("SIGTERM"),w=setTimeout(()=>{g="killing",le.warn("npm install SIGTERM grace expired, escalating to SIGKILL",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,stdoutBytes:u,stderrBytes:h}),S("SIGKILL")},qi)},Wi),f=()=>{g="aborted",le.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?f():n.addEventListener("abort",f,{once:!0})),c.on("error",y=>{clearTimeout(v),w&&clearTimeout(w),n?.removeEventListener("abort",f),le.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",f);let T=Buffer.concat(p).toString("utf8"),R=Buffer.concat(m).toString("utf8"),D=Date.now()-i;if(y===0&&g==="running"){le.info("npm install -g done",{npmPackage:t,versionSpec:e,elapsedMs:D}),o();return}le.warn("npm install -g exited non-success",{npmPackage:t,versionSpec:e,pid:l,phase:g,exitCode:y,signal:E,elapsedMs:D,stdoutBytes:u,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:R,stdout:T});a(C)})})}function Xl(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(`
13
- `)}async function tn(t,e){let n=Vo[t];if(!n)throw new _("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let r=Dn.get(t);if(r)return r;let i=Nn.get(t);if(i)return i;let s=`npm install -g ${n.npmPackage}@${n.versionSpec}`,o=(c,l,d)=>new _("AGENT_DEPENDENCY_INSTALL_FAILED",Xl({framework:t,npmPackage:n.npmPackage,versionSpec:n.versionSpec,command:s,reason:c,elapsedMs:l}),d!==void 0?{cause:d}:{}),a=(async()=>{let c=await jl(n.binary);if(c){let p=process.env.COZE_BRIDGE_ACP_NO_AUTO_UPGRADE==="1",m=p?void 0:await Jl(t,c);if(p||Zl(m??"",n.versionSpec))return Dn.set(t,c),le.info("acp wrapper found on PATH",{binary:n.binary,path:c,version:m??(p?"unchecked (auto-upgrade off)":"unknown"),spec:n.versionSpec}),c;le.info("acp wrapper on PATH but version out of spec \u2014 reinstalling to locked range",{binary:n.binary,path:c,installed:m,spec:n.versionSpec})}let l=Date.now();try{await Kl(n.npmPackage,n.versionSpec,e)}catch(p){let m=ql(p);throw le.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 jl(n.binary);if(!d)throw le.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 Dn.set(t,d),d})().finally(()=>{Nn.delete(t)});return Nn.set(t,a),a}function Or(t){return Dn.get(t)}function Pr(t,e){if(e)return e;let n=Or(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 Zo(t){return Nn.get(t)}function Em(){Dn.clear(),Nn.clear()}function Sm(t,e){Nn.set(t,e)}function vm(t,e){Dn.set(t,e)}var le,Vo,Wi,qi,wm,Dn,Nn,Wl,nn=ve(()=>{"use strict";gt();Te();F();le=b("agents.acp-installer"),Vo={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp",versionSpec:"^0.39"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp",versionSpec:"^0.15"}};Wi=5e4,qi=5e3,wm=5e3;Dn=new Map,Nn=new Map;Wl=6});import{chmod as Tm,mkdir as Rm,readFile as km,rename as td,writeFile as nd}from"node:fs/promises";import{dirname as bm}from"node:path";async function Ln(t){try{let e=await km(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Fn(t,e,n){await Rm(bm(t),{recursive:!0});let r=`${JSON.stringify(e,null,2)}
14
- `,i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{n?.mode!==void 0?await nd(i,r,{encoding:"utf8",mode:n.mode}):await nd(i,r,"utf8"),await td(i,t),n?.mode!==void 0&&await Tm(t,n.mode)}catch(s){await td(i,i).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(i,{force:!0}).catch(()=>{}),s}}var Cr=ve(()=>{"use strict"});import{promises as rd,readdirSync as Am}from"node:fs";import{homedir as xm}from"node:os";import{sep as Om,join as ee,resolve as id}from"node:path";function L(t){let e=t??xm(),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"),agentEnvFile:ee(r,"agent-env.json"),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 be(t,e=L()){let n=ee(e.agentsRoot,t);return{root:n,config:ee(n,"config.json"),workspace:ee(n,"workspace"),logs:ee(n,"logs")}}function Vi(t=L()){try{return Am(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function Dr(t,e){let n=await rd.realpath(id(t)).catch(()=>null);if(!n)return!1;let r=await rd.realpath(id(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+Om)}var re=ve(()=>{"use strict"});var Xi={};Ui(Xi,{AGENT_CONFIG_FILE_MODE:()=>Zi,enforceAgentConfigMode:()=>Dm,loadAgentConfig:()=>me,persistAgentSessions:()=>Nr,persistAgentSkills:()=>Ki,saveAgentConfig:()=>Ae});import{chmod as Pm,stat as Cm}from"node:fs/promises";function me(t,e){return Ln(be(t,e).config)}function Ae(t,e){return Fn(be(t.agentId,e).config,t,{mode:Zi})}async function Dm(t,e){if(process.platform==="win32")return;let n=be(t,e).config;try{let r=await Cm(n);if(!r.isFile())return;let i=r.mode&511;i!==Zi&&(await Pm(n,Zi),sd.warn("agent config mode auto-corrected to 0600",{path:n,from:i.toString(8)}))}catch(r){if(r.code==="ENOENT")return;sd.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(r)})}}async function Nr(t,e,n){let r=await me(t,n);r&&(r.sessions=Object.fromEntries(e),await Ae(r,n))}async function Ki(t,e,n){let r=await me(t,n);r&&(r.skills=e,await Ae(r,n))}var sd,Zi,At=ve(()=>{"use strict";Cr();F();re();sd=b("agent-config"),Zi=384});var Xo=H((GR,ld)=>{ld.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 Qi=H(ud=>{var dd={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 Bm(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(dd))ud[t]=Bm(dd[t])});var md=H((jR,gd)=>{var Um=j("fs"),ie=j("path"),fd=Xo(),zm=Qi(),$m=typeof process=="object"&&process.platform==="win32",hd=t=>typeof t=="object"&&t!==null,pd=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 X(t){this.sep=ie.sep,this.fs=Um,hd(t)&&hd(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}gd.exports=X;X.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 zm.FILE_IN_THE_WAY(`"${i}"`)}})}n(t)};X.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=ie.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};X.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=ie.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(u,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)})})})})})};X.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=ie.join(r,a),l=e.fs.statSync(c);(!i||i.test(c))&&o.push(ie.normalize(c)+(l.isDirectory()?e.sep:"")),l.isDirectory()&&s&&(o=o.concat(n(c,i,s)))}),o}return n(t,void 0,!0)};X.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=ie.join(t,a),n.fs.stat(a,function(c,l){if(c)return e(c);l&&(r.push(ie.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))})})})};X.prototype.getAttributes=function(){};X.prototype.setAttributes=function(){};X.crc32update=function(t,e){return pd[(t^e)&255]^t>>>8};X.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let r=0;r<e;)n=X.crc32update(n,t[r++]);return~n>>>0};X.methodToString=function(t){switch(t){case fd.STORED:return"STORED ("+t+")";case fd.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};X.canonical=function(t){if(!t)return"";let e=ie.posix.normalize("/"+t.split("\\").join("/"));return ie.join(".",e)};X.zipnamefix=function(t){if(!t)return"";let e=ie.posix.normalize("/"+t.split("\\").join("/"));return ie.posix.join(".",e)};X.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]};X.sanitize=function(t,e){t=ie.resolve(ie.normalize(t));for(var n=e.split("/"),r=0,i=n.length;r<i;r++){var s=ie.normalize(ie.join(t,n.slice(r,i).join(ie.sep)));if(s.indexOf(t)===0)return s}return ie.normalize(ie.join(t,ie.basename(e)))};X.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};X.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};X.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)};X.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};X.isWin=$m;X.crcTable=pd});var yd=H((WR,wd)=>{var Gm=j("path");wd.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=Gm.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 Ed=H((qR,_d)=>{_d.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Un=H((JR,Bn)=>{Bn.exports=md();Bn.exports.Constants=Xo();Bn.exports.Errors=Qi();Bn.exports.FileAttr=yd();Bn.exports.decoder=Ed()});var vd=H((VR,Sd)=>{var xt=Un(),k=xt.Constants;Sd.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,u=0,h=0;t|=xt.isWin?2560:768,n|=k.FLG_EFS;let g={extraLen:0},w=f=>Math.max(0,f)>>>0,S=f=>Math.max(0,f)&65535,v=f=>Math.max(0,f)&255;return i=xt.fromDate2DOS(new Date),{get made(){return t},set made(f){t=f},get version(){return e},set version(f){e=f},get flags(){return n},set flags(f){n=f},get flags_efs(){return(n&k.FLG_EFS)>0},set flags_efs(f){f?n|=k.FLG_EFS:n&=~k.FLG_EFS},get flags_desc(){return(n&k.FLG_DESC)>0},set flags_desc(f){f?n|=k.FLG_DESC:n&=~k.FLG_DESC},get method(){return r},set method(f){switch(f){case k.STORED:this.version=10;case k.DEFLATED:default:this.version=20}r=f},get time(){return xt.fromDOS2Date(this.timeval)},set time(f){f=new Date(f),this.timeval=xt.fromDate2DOS(f)},get timeval(){return i},set timeval(f){i=w(f)},get timeHighByte(){return v(i>>>8)},get crc(){return s},set crc(f){s=w(f)},get compressedSize(){return o},set compressedSize(f){o=w(f)},get size(){return a},set size(f){a=w(f)},get fileNameLength(){return c},set fileNameLength(f){c=f},get extraLength(){return l},set extraLength(f){l=f},get extraLocalLength(){return g.extraLen},set extraLocalLength(f){g.extraLen=f},get commentLength(){return d},set commentLength(f){d=f},get diskNumStart(){return p},set diskNumStart(f){p=w(f)},get inAttr(){return m},set inAttr(f){m=w(f)},get attr(){return u},set attr(f){u=w(f)},get fileAttr(){return(u||0)>>16&4095},get offset(){return h},set offset(f){h=w(f)},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(f){var y=f.slice(h,h+k.LOCHDR);if(y.readUInt32LE(0)!==k.LOCSIG)throw xt.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,T=E+g.extraLen;return f.slice(E,T)},loadFromBinary:function(f){if(f.length!==k.CENHDR||f.readUInt32LE(0)!==k.CENSIG)throw xt.Errors.INVALID_CEN();t=f.readUInt16LE(k.CENVEM),e=f.readUInt16LE(k.CENVER),n=f.readUInt16LE(k.CENFLG),r=f.readUInt16LE(k.CENHOW),i=f.readUInt32LE(k.CENTIM),s=f.readUInt32LE(k.CENCRC),o=f.readUInt32LE(k.CENSIZ),a=f.readUInt32LE(k.CENLEN),c=f.readUInt16LE(k.CENNAM),l=f.readUInt16LE(k.CENEXT),d=f.readUInt16LE(k.CENCOM),p=f.readUInt16LE(k.CENDSK),m=f.readUInt16LE(k.CENATT),u=f.readUInt32LE(k.CENATX),h=f.readUInt32LE(k.CENOFF)},localHeaderToBinary:function(){var f=Buffer.alloc(k.LOCHDR);return f.writeUInt32LE(k.LOCSIG,0),f.writeUInt16LE(e,k.LOCVER),f.writeUInt16LE(n,k.LOCFLG),f.writeUInt16LE(r,k.LOCHOW),f.writeUInt32LE(i,k.LOCTIM),f.writeUInt32LE(s,k.LOCCRC),f.writeUInt32LE(o,k.LOCSIZ),f.writeUInt32LE(a,k.LOCLEN),f.writeUInt16LE(c,k.LOCNAM),f.writeUInt16LE(g.extraLen,k.LOCEXT),f},centralHeaderToBinary:function(){var f=Buffer.alloc(k.CENHDR+c+l+d);return f.writeUInt32LE(k.CENSIG,0),f.writeUInt16LE(t,k.CENVEM),f.writeUInt16LE(e,k.CENVER),f.writeUInt16LE(n,k.CENFLG),f.writeUInt16LE(r,k.CENHOW),f.writeUInt32LE(i,k.CENTIM),f.writeUInt32LE(s,k.CENCRC),f.writeUInt32LE(o,k.CENSIZ),f.writeUInt32LE(a,k.CENLEN),f.writeUInt16LE(c,k.CENNAM),f.writeUInt16LE(l,k.CENEXT),f.writeUInt16LE(d,k.CENCOM),f.writeUInt16LE(p,k.CENDSK),f.writeUInt16LE(m,k.CENATT),f.writeUInt32LE(u,k.CENATX),f.writeUInt32LE(h,k.CENOFF),f},toJSON:function(){let f=function(y){return y+" bytes"};return{made:t,version:e,flags:n,method:xt.methodToString(r),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:f(o),size:f(a),fileNameLength:f(c),extraLength:f(l),commentLength:f(d),diskNumStart:p,inAttr:m,attr:u,offset:h,centralHeaderSize:f(k.CENHDR+c+l+d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Td=H((ZR,Id)=>{var zn=Un(),J=zn.Constants;Id.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 J.ENDHDR+i},loadFromBinary:function(s){if((s.length!==J.ENDHDR||s.readUInt32LE(0)!==J.ENDSIG)&&(s.length<J.ZIP64HDR||s.readUInt32LE(0)!==J.ZIP64SIG))throw zn.Errors.INVALID_END();s.readUInt32LE(0)===J.ENDSIG?(t=s.readUInt16LE(J.ENDSUB),e=s.readUInt16LE(J.ENDTOT),n=s.readUInt32LE(J.ENDSIZ),r=s.readUInt32LE(J.ENDOFF),i=s.readUInt16LE(J.ENDCOM)):(t=zn.readBigUInt64LE(s,J.ZIP64SUB),e=zn.readBigUInt64LE(s,J.ZIP64TOT),n=zn.readBigUInt64LE(s,J.ZIP64SIZE),r=zn.readBigUInt64LE(s,J.ZIP64OFF),i=0)},toBinary:function(){var s=Buffer.alloc(J.ENDHDR+i);return s.writeUInt32LE(J.ENDSIG,0),s.writeUInt32LE(0,4),s.writeUInt16LE(t,J.ENDSUB),s.writeUInt16LE(e,J.ENDTOT),s.writeUInt32LE(n,J.ENDSIZ),s.writeUInt32LE(r,J.ENDOFF),s.writeUInt16LE(i,J.ENDCOM),s.fill(" ",J.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 Qo=H(Yo=>{Yo.EntryHeader=vd();Yo.MainHeader=Td()});var kd=H((XR,Rd)=>{Rd.exports=function(t){var e=j("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 Ad=H((YR,bd)=>{var Hm=+(process.versions?process.versions.node:"").split(".")[0]||0;bd.exports=function(t,e){var n=j("zlib");let r=Hm>=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 Dd=H((QR,Cd)=>{"use strict";var{randomFillSync:xd}=j("crypto"),jm=Qi(),Wm=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}),Pd=(t,e)=>Math.imul(t,e)>>>0,Od=(t,e)=>Wm[(t^e)&255]^t>>>8,Lr=()=>typeof xd=="function"?xd(Buffer.alloc(12)):Lr.node();Lr.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 es={genSalt:Lr};function ts(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])}ts.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Od(e[0],t),e[1]+=e[0]&255,e[1]=Pd(e[1],134775813)+1,e[2]=Od(e[2],e[1]>>>24),t};ts.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Pd(t,t^1)>>8&255};function qm(t){let e=new ts(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 Jm(t){let e=new ts(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 Vm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let r=qm(n),i=r(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw jm.WRONG_PASSWORD();return r(t.slice(12))}function Zm(t){Buffer.isBuffer(t)&&t.length>=12?es.genSalt=function(){return t.slice(0,12)}:t==="node"?es.genSalt=Lr.node:es.genSalt=Lr}function Km(t,e,n,r=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=Jm(n),s=es.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)}Cd.exports={decrypt:Vm,encrypt:Km,_salter:Zm}});var Nd=H(ns=>{ns.Deflater=kd();ns.Inflater=Ad();ns.ZipCrypto=Dd()});var ta=H((tk,Ld)=>{var z=Un(),Xm=Qo(),Y=z.Constants,ea=Nd();Ld.exports=function(t,e){var n=new Xm.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 u(f){if(!n.flags_desc&&!n.localHeader.flags_desc){if(z.crc32(f)!==n.localHeader.crc)return!1}else{let y={},E=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(E)==Y.LOCSIG||e.readUInt32LE(E)==Y.CENSIG)throw z.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(E)==Y.EXTSIG)y.crc=e.readUInt32LE(E+Y.EXTCRC),y.compressedSize=e.readUInt32LE(E+Y.EXTSIZ),y.size=e.readUInt32LE(E+Y.EXTLEN);else if(e.readUInt16LE(E+12)===19280)y.crc=e.readUInt32LE(E+Y.EXTCRC-4),y.compressedSize=e.readUInt32LE(E+Y.EXTSIZ-4),y.size=e.readUInt32LE(E+Y.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(f)!==y.crc)return!1}return!0}function h(f,y,E){if(typeof y>"u"&&typeof f=="string"&&(E=f,f=void 0),s)return f&&y&&y(Buffer.alloc(0),z.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var T=m();if(T.length===0)return f&&y&&y(T),T;if(n.encrypted){if(typeof E!="string"&&!Buffer.isBuffer(E))throw z.Errors.INVALID_PASS_PARAM();T=ea.ZipCrypto.decrypt(T,n,E)}var R=Buffer.alloc(n.size);switch(n.method){case z.Constants.STORED:if(T.copy(R),u(R))return f&&y&&y(R),R;throw f&&y&&y(R,z.Errors.BAD_CRC()),z.Errors.BAD_CRC();case z.Constants.DEFLATED:var D=new ea.Inflater(T,n.size);if(f)D.inflateAsync(function(C){C.copy(C,0),y&&(u(C)?y(C):y(C,z.Errors.BAD_CRC()))});else{if(D.inflate(R).copy(R,0),!u(R))throw z.Errors.BAD_CRC(`"${p.decode(r)}"`);return R}break;default:throw f&&y&&y(Buffer.alloc(0),z.Errors.UNKNOWN_METHOD()),z.Errors.UNKNOWN_METHOD()}}function g(f,y){if((!o||!o.length)&&Buffer.isBuffer(e))return f&&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),f&&y&&y(E),E;default:case z.Constants.DEFLATED:var T=new ea.Deflater(o);if(f)T.deflateAsync(function(D){E=Buffer.alloc(D.length),n.compressedSize=D.length,D.copy(E),y&&y(E)});else{var R=T.deflate();return n.compressedSize=R.length,R}T=null;break}}else if(f&&y)y(Buffer.alloc(0));else return Buffer.alloc(0)}function w(f,y){return z.readBigUInt64LE(f,y)}function S(f){try{for(var y=0,E,T,R;y+4<f.length;)E=f.readUInt16LE(y),y+=2,T=f.readUInt16LE(y),y+=2,R=f.slice(y,y+T),y+=T,Y.ID_ZIP64===E&&v(R)}catch{throw z.Errors.EXTRA_FIELD_PARSE_ERROR()}}function v(f){var y,E,T,R;f.length>=Y.EF_ZIP64_SCOMP&&(y=w(f,Y.EF_ZIP64_SUNCOMP),n.size===Y.EF_ZIP64_OR_32&&(n.size=y)),f.length>=Y.EF_ZIP64_RHO&&(E=w(f,Y.EF_ZIP64_SCOMP),n.compressedSize===Y.EF_ZIP64_OR_32&&(n.compressedSize=E)),f.length>=Y.EF_ZIP64_DSN&&(T=w(f,Y.EF_ZIP64_RHO),n.offset===Y.EF_ZIP64_OR_32&&(n.offset=T)),f.length>=Y.EF_ZIP64_DSN+4&&(R=f.readUInt32LE(Y.EF_ZIP64_DSN),n.diskNumStart===Y.EF_ZIP64_OR_16&&(n.diskNumStart=R))}return{get entryName(){return p.decode(r)},get rawEntryName(){return r},set entryName(f){r=z.toBuffer(f,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(f){a=f,n.extraLength=f.length,S(f)},get comment(){return p.decode(i)},set comment(f){if(i=z.toBuffer(f,p.encode),n.commentLength=i.length,i.length>65535)throw z.Errors.COMMENT_TOO_LONG()},get name(){var f=p.decode(r);return s?f.substr(f.length-1).split("/").pop():f.split("/").pop()},get isDirectory(){return s},getCompressedData:function(){return g(!1,null)},getCompressedDataAsync:function(f){g(!0,f)},setData:function(f){o=z.toBuffer(f,z.decoder.encode),!s&&o.length?(n.size=o.length,n.method=z.Constants.DEFLATED,n.crc=z.crc32(f),n.changed=!0):n.method=z.Constants.STORED},getData:function(f){return n.changed?o:h(!1,null,f)},getDataAsync:function(f,y){n.changed?f(o):h(!0,f,y)},set attr(f){n.attr=f},get attr(){return n.attr},set header(f){n.loadFromBinary(f)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=a.length;var f=n.centralHeaderToBinary(),y=z.Constants.CENHDR;return r.copy(f,y),y+=r.length,a.copy(f,y),y+=n.extraLength,i.copy(f,y),f},packLocalHeader:function(){let f=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,f),f+=y.length,r.copy(E,f),f+=r.length,c.copy(E,f),f+=c.length,E},toJSON:function(){let f=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:f(e),data:f(o)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Bd=H((nk,Md)=>{var Fd=ta(),Ym=Qo(),we=Un();Md.exports=function(t,e){var n=[],r={},i=Buffer.alloc(0),s=new Ym.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 f=0;f<v.length;f++){let y=v.slice(0,f+1).join("/")+"/";w.add(y)}}for(let S of w)if(!(S in r)){let v=new Fd(l);v.entryName=S,v.attr=16,v.temporary=!0,n.push(v),r[v.entryName]=v,c.add(v)}}function u(){if(o=!0,r={},s.diskEntries>(t.length-s.offset)/we.Constants.CENHDR)throw we.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(s.diskEntries);for(var w=s.offset,S=0;S<n.length;S++){var v=w,f=new Fd(l,t);f.header=t.slice(v,v+=we.Constants.CENHDR),f.entryName=t.slice(v,v+=f.header.fileNameLength),f.header.extraLength&&(f.extra=t.slice(v,v+=f.header.extraLength)),f.header.commentLength&&(f.comment=t.slice(v,v+f.header.commentLength)),w+=f.header.centralHeaderSize,n[S]=f,r[f.entryName]=f}c.clear(),m()}function h(w){var S=t.length-we.Constants.ENDHDR,v=Math.max(0,S-65535),f=v,y=t.length,E=-1,T=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(v=0),S;S>=f;S--)if(t[S]===80){if(t.readUInt32LE(S)===we.Constants.ENDSIG){E=S,T=S,y=S+we.Constants.ENDHDR,f=S-we.Constants.END64HDR;continue}if(t.readUInt32LE(S)===we.Constants.END64SIG){f=v;continue}if(t.readUInt32LE(S)===we.Constants.ZIP64SIG){E=S,y=S+we.readBigUInt64LE(t,S+we.Constants.ZIP64SIZE)+we.Constants.ZIP64LEAD;break}}if(E==-1)throw we.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(E,y)),s.commentLength&&(i=t.slice(T+we.Constants.ENDHDR)),w&&u()}function g(){n.length>1&&!d&&n.sort((w,S)=>w.entryName.toLowerCase().localeCompare(S.entryName.toLowerCase()))}return{get entries(){return o||u(),n.filter(w=>!c.has(w))},get comment(){return p.decode(i)},set comment(w){i=we.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||u(),r[w]||null},setEntry:function(w){o||u(),n.push(w),r[w.entryName]=w,s.totalEntries=n.length},deleteFile:function(w,S=!0){o||u();let v=r[w];this.getEntryChildren(v,S).map(y=>y.entryName).forEach(this.deleteEntry)},deleteEntry:function(w){o||u();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||u(),typeof w=="object")if(w.isDirectory&&S){let v=[],f=w.entryName;for(let y of n)y.entryName.startsWith(f)&&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||u(),g();let w=[],S=[],v=0,f=0;s.size=0,s.offset=0;let y=0;for(let R of this.entries){let D=R.getCompressedData();R.header.offset=f;let C=R.packLocalHeader(),G=C.length+D.length;f+=G,w.push(C),w.push(D);let M=R.packCentralHeader();S.push(M),s.size+=M.length,v+=G+M.length,y++}v+=s.mainHeaderSize,s.offset=f,s.totalEntries=y,f=0;let E=Buffer.alloc(v);for(let R of w)R.copy(E,f),f+=R.length;for(let R of S)R.copy(E,f),f+=R.length;let T=s.toBinary();return i&&i.copy(T,we.Constants.ENDHDR),T.copy(E,f),t=E,o=!1,E},toAsyncBuffer:function(w,S,v,f){try{o||u(),g();let y=[],E=[],T=0,R=0,D=0;s.size=0,s.offset=0;let C=function(G){if(G.length>0){let M=G.shift(),ae=M.entryName+M.extra.toString();v&&v(ae),M.getCompressedDataAsync(function(Ee){f&&f(ae),M.header.offset=R;let I=M.packLocalHeader(),x=I.length+Ee.length;R+=x,y.push(I),y.push(Ee);let O=M.packCentralHeader();E.push(O),s.size+=O.length,T+=x+O.length,D++,C(G)})}else{T+=s.mainHeaderSize,s.offset=R,s.totalEntries=D,R=0;let M=Buffer.alloc(T);y.forEach(function(Ee){Ee.copy(M,R),R+=Ee.length}),E.forEach(function(Ee){Ee.copy(M,R),R+=Ee.length});let ae=s.toBinary();i&&i.copy(ae,we.Constants.ENDHDR),ae.copy(M,R),t=M,o=!1,w(M)}};C(Array.from(this.entries))}catch(y){S(y)}}}}});var $d=H((rk,zd)=>{var Z=Un(),V=j("path"),Qm=ta(),ew=Bd(),rn=(...t)=>Z.findLast(t,e=>typeof e=="boolean"),Ud=(...t)=>Z.findLast(t,e=>typeof e=="string"),tw=(...t)=>Z.findLast(t,e=>typeof e=="function"),nw={noSort:!1,readEntries:!1,method:Z.Constants.NONE,fs:null};zd.exports=function(t,e){let n=null,r=Object.assign(Object.create(null),nw);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=Z.Constants.BUFFER,t=void 0)),Object.assign(r,e);let i=new Z(r);if((typeof r.decoder!="object"||typeof r.decoder.encode!="function"||typeof r.decoder.decode!="function")&&(r.decoder=Z.decoder),t&&typeof t=="string")if(i.fs.existsSync(t))r.method=Z.Constants.FILE,r.filename=t,n=i.fs.readFileSync(t);else throw Z.Errors.INVALID_FILENAME();let s=new ew(n,r),{canonical:o,sanitize:a,zipnamefix:c}=Z;function l(u){if(u&&s){var h;if(typeof u=="string"&&(h=s.getEntry(V.posix.normalize(u))),typeof u=="object"&&typeof u.entryName<"u"&&typeof u.header<"u"&&(h=s.getEntry(u.entryName)),h)return h}return null}function d(u){let{join:h,normalize:g,sep:w}=V.posix;return h(V.isAbsolute(u)?"/":".",g(w+u.split("\\").join(w)+w))}function p(u){return u instanceof RegExp?(function(h){return function(g){return h.test(g)}})(u):typeof u!="function"?()=>!0:u}let m=(u,h)=>{let g=h.slice(-1);return g=g===i.sep?i.sep:"",V.relative(u,h)+g};return{readFile:function(u,h){var g=l(u);return g&&g.getData(h)||null},childCount:function(u){let h=l(u);if(h)return s.getChildCount(h)},readFileAsync:function(u,h){var g=l(u);g?g.getDataAsync(h):h(null,"getEntry failed for:"+u)},readAsText:function(u,h){var g=l(u);if(g){var w=g.getData();if(w&&w.length)return w.toString(h||"utf8")}return""},readAsTextAsync:function(u,h,g){var w=l(u);w?w.getDataAsync(function(S,v){if(v){h(S,v);return}S&&S.length?h(S.toString(g||"utf8")):h("")}):h("")},deleteFile:function(u,h=!0){var g=l(u);g&&s.deleteFile(g.entryName,h)},deleteEntry:function(u){var h=l(u);h&&s.deleteEntry(h.entryName)},addZipComment:function(u){s.comment=u},getZipComment:function(){return s.comment||""},addZipEntryComment:function(u,h){var g=l(u);g&&(g.comment=h)},getZipEntryComment:function(u){var h=l(u);return h&&h.comment||""},updateFile:function(u,h){var g=l(u);g&&g.setData(h)},addLocalFile:function(u,h,g,w){if(i.fs.existsSync(u)){h=h?d(h):"";let S=V.win32.basename(V.win32.normalize(u));h+=g||S;let v=i.fs.statSync(u),f=v.isFile()?i.fs.readFileSync(u):Buffer.alloc(0);v.isDirectory()&&(h+=i.sep),this.addFile(h,f,w,v)}else throw Z.Errors.FILE_NOT_FOUND(u)},addLocalFileAsync:function(u,h){u=typeof u=="object"?u:{localPath:u};let g=V.resolve(u.localPath),{comment:w}=u,{zipPath:S,zipName:v}=u,f=this;i.fs.stat(g,function(y,E){if(y)return h(y,!1);S=S?d(S):"";let T=V.win32.basename(V.win32.normalize(g));if(S+=v||T,E.isFile())i.fs.readFile(g,function(R,D){return R?h(R,!1):(f.addFile(S,D,w,E),setImmediate(h,void 0,!0))});else if(E.isDirectory())return S+=i.sep,f.addFile(S,Buffer.alloc(0),w,E),setImmediate(h,void 0,!0)})},addLocalFolder:function(u,h,g){if(g=p(g),h=h?d(h):"",u=V.normalize(u),i.fs.existsSync(u)){let w=i.findFiles(u),S=this;if(w.length)for(let v of w){let f=V.join(h,m(u,v));g(f)&&S.addLocalFile(v,V.dirname(f))}}else throw Z.Errors.FILE_NOT_FOUND(u)},addLocalFolderAsync:function(u,h,g,w){w=p(w),g=g?d(g):"",u=V.normalize(u);var S=this;i.fs.open(u,"r",function(v){if(v&&v.code==="ENOENT")h(void 0,Z.Errors.FILE_NOT_FOUND(u));else if(v)h(void 0,v);else{var f=i.findFiles(u),y=-1,E=function(){if(y+=1,y<f.length){var T=f[y],R=m(u,T).split("\\").join("/");R=R.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),w(R)?i.fs.stat(T,function(D,C){D&&h(void 0,D),C.isFile()?i.fs.readFile(T,function(G,M){G?h(void 0,G):(S.addFile(g+R,M,"",C),E())}):(S.addFile(g+R+"/",Buffer.alloc(0),"",C),E())}):process.nextTick(()=>{E()})}else h(!0,void 0)};E()}})},addLocalFolderAsync2:function(u,h){let g=this;u=typeof u=="object"?u:{localPath:u},localPath=V.resolve(d(u.localPath));let{zipPath:w,filter:S,namefix:v}=u;S instanceof RegExp?S=(function(E){return function(T){return E.test(T)}})(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 f=E=>V.join(w,v(m(localPath,E))),y=E=>V.win32.basename(V.win32.normalize(v(E)));i.fs.open(localPath,"r",function(E){E&&E.code==="ENOENT"?h(void 0,Z.Errors.FILE_NOT_FOUND(localPath)):E?h(void 0,E):i.findFilesAsync(localPath,function(T,R){if(T)return h(T);R=R.filter(D=>S(f(D))),R.length||h(void 0,!1),setImmediate(R.reverse().reduce(function(D,C){return function(G,M){if(G||M===!1)return setImmediate(D,G,!1);g.addLocalFileAsync({localPath:C,zipPath:V.dirname(f(C)),zipName:y(C)},D)}},h))})})},addLocalFolderPromise:function(u,h){return new Promise((g,w)=>{this.addLocalFolderAsync2(Object.assign({localPath:u},h),(S,v)=>{S&&w(S),v&&g(this)})})},addFile:function(u,h,g,w){u=c(u);let S=l(u),v=S!=null;v||(S=new Qm(r),S.entryName=u),S.comment=g||"";let f=typeof w=="object"&&w instanceof i.fs.Stats;f&&(S.header.time=w.mtime);var y=S.isDirectory?16:0;let E=S.isDirectory?16384:32768;return f?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(u){return s.password=u,s?s.entries:[]},getEntry:function(u){return l(u)},getEntryCount:function(){return s.getEntryCount()},forEach:function(u){return s.forEach(u)},extractEntryTo:function(u,h,g,w,S,v){w=rn(!1,w),S=rn(!1,S),g=rn(!0,g),v=Ud(S,v);var f=l(u);if(!f)throw Z.Errors.NO_ENTRY();var y=o(f.entryName),E=a(h,v&&!f.isDirectory?v:g?y:V.basename(y));if(f.isDirectory){var T=s.getEntryChildren(f);return T.forEach(function(C){if(C.isDirectory)return;var G=C.getData();if(!G)throw Z.Errors.CANT_EXTRACT_FILE();var M=o(C.entryName),ae=a(h,g?M:V.basename(M));let Ee=S?C.header.fileAttr:void 0;i.writeFileTo(ae,G,w,Ee)}),!0}var R=f.getData(s.password);if(!R)throw Z.Errors.CANT_EXTRACT_FILE();if(i.fs.existsSync(E)&&!w)throw Z.Errors.CANT_OVERRIDE();let D=S?u.header.fileAttr:void 0;return i.writeFileTo(E,R,w,D),!0},test:function(u){if(!s)return!1;for(var h in s.entries)try{if(h.isDirectory)continue;var g=s.entries[h].getData(u);if(!g)return!1}catch{return!1}return!0},extractAllTo:function(u,h,g,w){if(g=rn(!1,g),w=Ud(g,w),h=rn(!1,h),!s)throw Z.Errors.NO_ZIP();s.entries.forEach(function(S){var v=a(u,o(S.entryName));if(S.isDirectory){i.makeDir(v);return}var f=S.getData(w);if(!f)throw Z.Errors.CANT_EXTRACT_FILE();let y=g?S.header.fileAttr:void 0;i.writeFileTo(v,f,h,y);try{i.fs.utimesSync(v,S.header.time,S.header.time)}catch{throw Z.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(u,h,g,w){if(w=tw(h,g,w),g=rn(!1,g),h=rn(!1,h),!w)return new Promise((E,T)=>{this.extractAllToAsync(u,h,g,function(R){R?T(R):E(this)})});if(!s){w(Z.Errors.NO_ZIP());return}u=V.resolve(u);let S=E=>a(u,V.normalize(o(E.entryName))),v=(E,T)=>new Error(E+': "'+T+'"'),f=[],y=[];s.entries.forEach(E=>{E.isDirectory?f.push(E):y.push(E)});for(let E of f){let T=S(E),R=g?E.header.fileAttr:void 0;try{i.makeDir(T),R&&i.fs.chmodSync(T,R),i.fs.utimesSync(T,E.header.time,E.header.time)}catch{w(v("Unable to create folder",T))}}y.reverse().reduce(function(E,T){return function(R){if(R)E(R);else{let D=V.normalize(o(T.entryName)),C=a(u,D);T.getDataAsync(function(G,M){if(M)E(M);else if(!G)E(Z.Errors.CANT_EXTRACT_FILE());else{let ae=g?T.header.fileAttr:void 0;i.writeFileToAsync(C,G,h,ae,function(Ee){Ee||E(v("Unable to write file",C)),i.fs.utimes(C,T.header.time,T.header.time,function(I){I?E(v("Unable to set times",C)):E()})})}})}}},w)()},writeZip:function(u,h){if(arguments.length===1&&typeof u=="function"&&(h=u,u=""),!u&&r.filename&&(u=r.filename),!!u){var g=s.compressToBuffer();if(g){var w=i.writeFileTo(u,g,!0);typeof h=="function"&&h(w?null:new Error("failed"),"")}}},writeZipPromise:function(u,h){let{overwrite:g,perm:w}=Object.assign({overwrite:!0},h);return new Promise((S,v)=>{!u&&r.filename&&(u=r.filename),u||v("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(f=>{let y=E=>E?S(E):v("ADM-ZIP: Wasn't able to write zip file");i.writeFileToAsync(u,f,g,w,y)},v)})},toBufferPromise:function(){return new Promise((u,h)=>{s.toAsyncBuffer(u,h)})},toBuffer:function(u,h,g,w){return typeof u=="function"?(s.toAsyncBuffer(u,h,g,w),null):s.compressToBuffer()}}}});function kS(){return Sh||(Sh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bS(){return vh||(vh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function AS(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{n(Ue(t.result)),i()},o=()=>{r(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(n=>{n instanceof IDBCursor&&Ih.set(n,t)}).catch(()=>{}),Pc.set(e,t),e}function xS(t){if(xc.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)});xc.set(t,e)}function Rh(t){Oc=t(Oc)}function OS(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(Ei(this),e,...n);return Th.set(r,e.sort?e.sort():[e]),Ue(r)}:bS().includes(t)?function(...e){return t.apply(Ei(this),e),Ue(Ih.get(this))}:function(...e){return Ue(t.apply(Ei(this),e))}}function PS(t){return typeof t=="function"?OS(t):(t instanceof IDBTransaction&&xS(t),RS(t,kS())?new Proxy(t,Oc):t)}function Ue(t){if(t instanceof IDBRequest)return AS(t);if(Ac.has(t))return Ac.get(t);let e=PS(t);return e!==t&&(Ac.set(t,e),Pc.set(e,t)),e}var RS,Sh,vh,Ih,xc,Th,Ac,Pc,Oc,Ei,Cc=ve(()=>{RS=(t,e)=>e.some(n=>t instanceof n);Ih=new WeakMap,xc=new WeakMap,Th=new WeakMap,Ac=new WeakMap,Pc=new WeakMap;Oc={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return xc.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Th.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Ue(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}};Ei=t=>Pc.get(t)});var bh={};Ui(bh,{deleteDB:()=>DS,openDB:()=>CS,unwrap:()=>Ei,wrap:()=>Ue});function CS(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=Ue(o);return r&&o.addEventListener("upgradeneeded",c=>{r(Ue(o.result),c.oldVersion,c.newVersion,Ue(o.transaction))}),n&&o.addEventListener("blocked",()=>n()),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",()=>i())}).catch(()=>{}),a}function DS(t,{blocked:e}={}){let n=indexedDB.deleteDatabase(t);return e&&n.addEventListener("blocked",()=>e()),Ue(n).then(()=>{})}function kh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Dc.get(e))return Dc.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=LS.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||NS.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 Dc.set(e,s),s}var NS,LS,Dc,Ah=ve(()=>{Cc();Cc();NS=["get","getKey","getAll","getAllKeys","count"],LS=["put","add","delete","clear"],Dc=new Map;Rh(t=>({...t,get:(e,n,r)=>kh(e,n)||t.get(e,n,r),has:(e,n)=>!!kh(e,n)||t.has(e,n)}))});var It=H((GO,ep)=>{"use strict";var Yh=["nodebuffer","arraybuffer","fragments"],Qh=typeof Blob<"u";Qh&&Yh.push("blob");ep.exports={BINARY_TYPES:Yh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Qh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ki=H((HO,lo)=>{"use strict";var{EMPTY_BUFFER:B0}=It(),nl=Buffer[Symbol.species];function U0(t,e){if(t.length===0)return B0;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 nl(n.buffer,n.byteOffset,r):n}function tp(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function np(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function z0(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function rl(t){if(rl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new nl(t):ArrayBuffer.isView(t)?e=new nl(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),rl.readOnly=!1),e}lo.exports={concat:U0,mask:tp,toArrayBuffer:z0,toBuffer:rl,unmask:np};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=j("bufferutil");lo.exports.mask=function(e,n,r,i,s){s<48?tp(e,n,r,i,s):t.mask(e,n,r,i,s)},lo.exports.unmask=function(e,n){e.length<32?np(e,n):t.unmask(e,n)}}catch{}});var sp=H((jO,ip)=>{"use strict";var rp=Symbol("kDone"),il=Symbol("kRun"),sl=class{constructor(e){this[rp]=()=>{this.pending--,this[il]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[il]()}[il](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[rp])}}};ip.exports=sl});var pr=H((WO,lp)=>{"use strict";var bi=j("zlib"),op=ki(),$0=sp(),{kStatusCode:ap}=It(),G0=Buffer[Symbol.species],H0=Buffer.from([0,0,255,255]),fo=Symbol("permessage-deflate"),Tt=Symbol("total-length"),fr=Symbol("callback"),Zt=Symbol("buffers"),hr=Symbol("error"),uo,ol=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,!uo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;uo=new $0(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[fr];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){uo.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){uo.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"?bi.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=bi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[fo]=this,this._inflate[Tt]=0,this._inflate[Zt]=[],this._inflate.on("error",W0),this._inflate.on("data",cp)}this._inflate[fr]=r,this._inflate.write(e),n&&this._inflate.write(H0),this._inflate.flush(()=>{let s=this._inflate[hr];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=op.concat(this._inflate[Zt],this._inflate[Tt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Tt]=0,this._inflate[Zt]=[],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"?bi.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=bi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Tt]=0,this._deflate[Zt]=[],this._deflate.on("data",j0)}this._deflate[fr]=r,this._deflate.write(e),this._deflate.flush(bi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=op.concat(this._deflate[Zt],this._deflate[Tt]);n&&(s=new G0(s.buffer,s.byteOffset,s.length-4)),this._deflate[fr]=null,this._deflate[Tt]=0,this._deflate[Zt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};lp.exports=ol;function j0(t){this[Zt].push(t),this[Tt]+=t.length}function cp(t){if(this[Tt]+=t.length,this[fo]._maxPayload<1||this[Tt]<=this[fo]._maxPayload){this[Zt].push(t);return}this[hr]=new RangeError("Max payload size exceeded"),this[hr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[hr][ap]=1009,this.removeListener("data",cp),this.reset()}function W0(t){if(this[fo]._inflate=null,this[hr]){this[fr](this[hr]);return}t[ap]=1007,this[fr](t)}});var gr=H((qO,ho)=>{"use strict";var{isUtf8:dp}=j("buffer"),{hasBlob:q0}=It(),J0=[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 V0(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function al(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 Z0(t){return q0&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}ho.exports={isBlob:Z0,isValidStatusCode:V0,isValidUTF8:al,tokenChars:J0};if(dp)ho.exports.isValidUTF8=function(t){return t.length<24?al(t):dp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=j("utf-8-validate");ho.exports.isValidUTF8=function(e){return e.length<32?al(e):t(e)}}catch{}});var fl=H((JO,wp)=>{"use strict";var{Writable:K0}=j("stream"),up=pr(),{BINARY_TYPES:X0,EMPTY_BUFFER:fp,kStatusCode:Y0,kWebSocket:Q0}=It(),{concat:cl,toArrayBuffer:ev,unmask:tv}=ki(),{isValidStatusCode:nv,isValidUTF8:hp}=gr(),po=Buffer[Symbol.species],$e=0,pp=1,gp=2,mp=3,ll=4,dl=5,go=6,ul=class extends K0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||X0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Q0]=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=$e}_write(e,n,r){if(this._opcode===8&&this._state==$e)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 po(r.buffer,r.byteOffset+e,r.length-e),new po(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 po(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 $e:this.getInfo(e);break;case pp:this.getPayloadLength16(e);break;case gp:this.getPayloadLength64(e);break;case mp:this.getMask();break;case ll:this.getData(e);break;case dl:case go: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[up.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=pp:this._payloadLength===127?this._state=gp: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=mp:this._state=ll}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ll}getData(e){let n=fp;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&&tv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=dl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[up.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===$e&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=$e;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=cl(r,n):this._binaryType==="arraybuffer"?i=ev(cl(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=$e):(this._state=go,setImmediate(()=>{this.emit("message",i,!0),this._state=$e,this.startLoop(e)}))}else{let i=cl(r,n);if(!this._skipUTF8Validation&&!hp(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===dl||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=$e):(this._state=go,setImmediate(()=>{this.emit("message",i,!1),this._state=$e,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fp),this.end();else{let r=e.readUInt16BE(0);if(!nv(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new po(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!hp(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=$e;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=$e):(this._state=go,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=$e,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[Y0]=i,o}};wp.exports=ul});var gl=H((ZO,Ep)=>{"use strict";var{Duplex:VO}=j("stream"),{randomFillSync:rv}=j("crypto"),yp=pr(),{EMPTY_BUFFER:iv,kWebSocket:sv,NOOP:ov}=It(),{isBlob:mr,isValidStatusCode:av}=gr(),{mask:_p,toBuffer:Tn}=ki(),Ge=Symbol("kByteLength"),cv=Buffer.alloc(4),mo=8*1024,Rn,wr=mo,Ye=0,lv=1,dv=2,hl=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=Ye,this.onerror=ov,this[sv]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||cv,n.generateMask?n.generateMask(r):(wr===mo&&(Rn===void 0&&(Rn=Buffer.alloc(mo)),rv(Rn,0,mo),wr=0),r[0]=Rn[wr++],r[1]=Rn[wr++],r[2]=Rn[wr++],r[3]=Rn[wr++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[Ge]!==void 0?a=n[Ge]:(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?(_p(e,r,l,s,a),[l]):(_p(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,i){let s;if(e===void 0)s=iv;else{if(typeof e!="number"||!av(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={[Ge]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ye?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):mr(e)?(i=e.size,s=!1):(e=Tn(e),i=e.length,s=Tn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};mr(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ye?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):mr(e)?(i=e.size,s=!1):(e=Tn(e),i=e.length,s=Tn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};mr(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ye?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[yp.extensionName],s=n.binary?2:1,o=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):mr(e)?(a=e.size,c=!1):(e=Tn(e),a=e.length,c=Tn.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={[Ge]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};mr(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ye?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[Ge],this._state=dv,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(pl,this,a,i);return}this._bufferedBytes-=r[Ge];let o=Tn(s);n?this.dispatch(o,n,r,i):(this._state=Ye,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(uv,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[yp.extensionName];this._bufferedBytes+=r[Ge],this._state=lv,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");pl(this,c,i);return}this._bufferedBytes-=r[Ge],this._state=Ye,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===Ye&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ge],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ge],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Ep.exports=hl;function pl(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 uv(t,e,n){pl(t,e,n),t.onerror(e)}});var xp=H((KO,Ap)=>{"use strict";var{kForOnEventAttribute:Ai,kListener:ml}=It(),Sp=Symbol("kCode"),vp=Symbol("kData"),Ip=Symbol("kError"),Tp=Symbol("kMessage"),Rp=Symbol("kReason"),yr=Symbol("kTarget"),kp=Symbol("kType"),bp=Symbol("kWasClean"),Rt=class{constructor(e){this[yr]=null,this[kp]=e}get target(){return this[yr]}get type(){return this[kp]}};Object.defineProperty(Rt.prototype,"target",{enumerable:!0});Object.defineProperty(Rt.prototype,"type",{enumerable:!0});var kn=class extends Rt{constructor(e,n={}){super(e),this[Sp]=n.code===void 0?0:n.code,this[Rp]=n.reason===void 0?"":n.reason,this[bp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Sp]}get reason(){return this[Rp]}get wasClean(){return this[bp]}};Object.defineProperty(kn.prototype,"code",{enumerable:!0});Object.defineProperty(kn.prototype,"reason",{enumerable:!0});Object.defineProperty(kn.prototype,"wasClean",{enumerable:!0});var _r=class extends Rt{constructor(e,n={}){super(e),this[Ip]=n.error===void 0?null:n.error,this[Tp]=n.message===void 0?"":n.message}get error(){return this[Ip]}get message(){return this[Tp]}};Object.defineProperty(_r.prototype,"error",{enumerable:!0});Object.defineProperty(_r.prototype,"message",{enumerable:!0});var xi=class extends Rt{constructor(e,n={}){super(e),this[vp]=n.data===void 0?null:n.data}get data(){return this[vp]}};Object.defineProperty(xi.prototype,"data",{enumerable:!0});var fv={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[Ai]&&i[ml]===e&&!i[Ai])return;let r;if(t==="message")r=function(s,o){let a=new xi("message",{data:o?s:s.toString()});a[yr]=this,wo(e,this,a)};else if(t==="close")r=function(s,o){let a=new kn("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[yr]=this,wo(e,this,a)};else if(t==="error")r=function(s){let o=new _r("error",{error:s,message:s.message});o[yr]=this,wo(e,this,o)};else if(t==="open")r=function(){let s=new Rt("open");s[yr]=this,wo(e,this,s)};else return;r[Ai]=!!n[Ai],r[ml]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ml]===e&&!n[Ai]){this.removeListener(t,n);break}}};Ap.exports={CloseEvent:kn,ErrorEvent:_r,Event:Rt,EventTarget:fv,MessageEvent:xi};function wo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var yo=H((XO,Op)=>{"use strict";var{tokenChars:Oi}=gr();function ut(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function hv(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&&Oi[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 u=t.slice(c,d);l===44?(ut(e,u,n),n=Object.create(null)):o=u,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Oi[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),ut(n,t.slice(c,d),!0),l===44&&(ut(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(Oi[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:r||(r=!0),i=!1}else if(s)if(Oi[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&&Oi[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 u=t.slice(c,d);r&&(u=u.replace(/\\/g,""),r=!1),ut(n,a,u),l===44&&(ut(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?ut(e,m,n):(a===void 0?ut(n,m,!0):r?ut(n,a,m.replace(/\\/g,"")):ut(n,a,m),ut(e,o,n)),e}function pv(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(", ")}Op.exports={format:pv,parse:hv}});var vo=H((eP,Gp)=>{"use strict";var gv=j("events"),mv=j("https"),wv=j("http"),Dp=j("net"),yv=j("tls"),{randomBytes:_v,createHash:Ev}=j("crypto"),{Duplex:YO,Readable:QO}=j("stream"),{URL:wl}=j("url"),Kt=pr(),Sv=fl(),vv=gl(),{isBlob:Iv}=gr(),{BINARY_TYPES:Pp,CLOSE_TIMEOUT:Tv,EMPTY_BUFFER:_o,GUID:Rv,kForOnEventAttribute:yl,kListener:kv,kStatusCode:bv,kWebSocket:pe,NOOP:Np}=It(),{EventTarget:{addEventListener:Av,removeEventListener:xv}}=xp(),{format:Ov,parse:Pv}=yo(),{toBuffer:Cv}=ki(),Lp=Symbol("kAborted"),_l=[8,13],kt=["CONNECTING","OPEN","CLOSING","CLOSED"],Dv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,q=class t extends gv{constructor(e,n,r){super(),this._binaryType=Pp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=_o,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]),Fp(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Pp.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 Sv({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new vv(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[pe]=this,s[pe]=this,e[pe]=this,i.on("conclude",Fv),i.on("drain",Mv),i.on("error",Bv),i.on("message",Uv),i.on("ping",zv),i.on("pong",$v),s.onerror=Gv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Up),e.on("data",So),e.on("end",zp),e.on("error",$p),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Kt.extensionName]&&this._extensions[Kt.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){Le(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())}),Bp(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){El(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||_o,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){El(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||_o,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){El(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Kt.extensionName]||(i.compress=!1),this._sender.send(e||_o,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Le(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(q,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(q.prototype,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(q,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(q.prototype,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(q,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(q.prototype,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(q,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});Object.defineProperty(q.prototype,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(q.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(q.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[yl])return e[kv];return null},set(e){for(let n of this.listeners(t))if(n[yl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[yl]:!0})}})});q.prototype.addEventListener=Av;q.prototype.removeEventListener=xv;Gp.exports=q;function Fp(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Tv,protocolVersion:_l[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,!_l.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${_l.join(", ")})`);let s;if(e instanceof wl)s=e;else try{s=new wl(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;Eo(t,g);return}let l=o?443:80,d=_v(16).toString("base64"),p=o?mv.request:wv.request,m=new Set,u;if(i.createConnection=i.createConnection||(o?Lv:Nv),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&&(u=new Kt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Ov({[Kt.extensionName]:u.offer()})),n.length){for(let g of n){if(typeof g!="string"||!Dv.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",()=>{Le(t,h,"Opening handshake has timed out")}),h.on("error",g=>{h===null||h[Lp]||(h=t._req=null,Eo(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){Le(t,h,"Maximum redirects exceeded");return}h.abort();let v;try{v=new wl(w,e)}catch{let y=new SyntaxError(`Invalid URL: ${w}`);Eo(t,y);return}Fp(t,v,n,r)}else t.emit("unexpected-response",h,g)||Le(t,h,`Unexpected server response: ${g.statusCode}`)}),h.on("upgrade",(g,w,S)=>{if(t.emit("upgrade",g),t.readyState!==q.CONNECTING)return;h=t._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Le(t,w,"Invalid Upgrade header");return}let f=Ev("sha1").update(d+Rv).digest("base64");if(g.headers["sec-websocket-accept"]!==f){Le(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){Le(t,w,E);return}y&&(t._protocol=y);let T=g.headers["sec-websocket-extensions"];if(T!==void 0){if(!u){Le(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=Pv(T)}catch{Le(t,w,"Invalid Sec-WebSocket-Extensions header");return}let D=Object.keys(R);if(D.length!==1||D[0]!==Kt.extensionName){Le(t,w,"Server indicated an extension that was not requested");return}try{u.accept(R[Kt.extensionName])}catch{Le(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Kt.extensionName]=u}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 Eo(t,e){t._readyState=q.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Nv(t){return t.path=t.socketPath,Dp.connect(t)}function Lv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Dp.isIP(t.host)?"":t.host),yv.connect(t)}function Le(t,e,n){t._readyState=q.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Le),e.setHeader?(e[Lp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Eo,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function El(t,e,n){if(e){let r=Iv(e)?e.size:Cv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${kt[t.readyState]})`);process.nextTick(n,r)}}function Fv(t,e){let n=this[pe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[pe]!==void 0&&(n._socket.removeListener("data",So),process.nextTick(Mp,n._socket),t===1005?n.close():n.close(t,e))}function Mv(){let t=this[pe];t.isPaused||t._socket.resume()}function Bv(t){let e=this[pe];e._socket[pe]!==void 0&&(e._socket.removeListener("data",So),process.nextTick(Mp,e._socket),e.close(t[bv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Cp(){this[pe].emitClose()}function Uv(t,e){this[pe].emit("message",t,e)}function zv(t){let e=this[pe];e._autoPong&&e.pong(t,!this._isServer,Np),e.emit("ping",t)}function $v(t){this[pe].emit("pong",t)}function Mp(t){t.resume()}function Gv(t){let e=this[pe];e.readyState!==q.CLOSED&&(e.readyState===q.OPEN&&(e._readyState=q.CLOSING,Bp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Bp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Up(){let t=this[pe];if(this.removeListener("close",Up),this.removeListener("data",So),this.removeListener("end",zp),t._readyState=q.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[pe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Cp),t._receiver.on("finish",Cp))}function So(t){this[pe]._receiver.write(t)||this.pause()}function zp(){let t=this[pe];t._readyState=q.CLOSING,t._receiver.end(),this.end()}function $p(){let t=this[pe];this.removeListener("error",$p),this.on("error",Np),t&&(t._readyState=q.CLOSING,this.destroy())}});var qp=H((nP,Wp)=>{"use strict";var tP=vo(),{Duplex:Hv}=j("stream");function Hp(t){t.emit("close")}function jv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function jp(t){this.removeListener("error",jp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Wv(t,e){let n=!0,r=new Hv({...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(Hp,r);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(Hp,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",jv),r.on("error",jp),r}Wp.exports=Wv});var Sl=H((rP,Jp)=>{"use strict";var{tokenChars:qv}=gr();function Jv(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&&qv[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}Jp.exports={parse:Jv}});var eg=H((sP,Qp)=>{"use strict";var Vv=j("events"),Io=j("http"),{Duplex:iP}=j("stream"),{createHash:Zv}=j("crypto"),Vp=yo(),bn=pr(),Kv=Sl(),Xv=vo(),{CLOSE_TIMEOUT:Yv,GUID:Qv,kWebSocket:eI}=It(),tI=/^[+/0-9A-Za-z]{22}==$/,Zp=0,Kp=1,Yp=2,vl=class extends Vv{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Yv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Xv,...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=Io.createServer((r,i)=>{let s=Io.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=nI(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=Zp}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===Yp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Pi,this);return}if(e&&this.once("close",e),this._state!==Kp)if(this._state=Kp,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(Pi,this):process.nextTick(Pi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Pi(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",Xp);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){An(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){An(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!tI.test(s)){An(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){An(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ci(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Kv.parse(c)}catch{An(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 bn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let u=Vp.parse(d);u[bn.extensionName]&&(m.accept(u[bn.extensionName]),p[bn.extensionName]=m)}catch{An(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,(u,h,g,w)=>{if(!u)return Ci(n,h||401,g,w);this.completeUpgrade(p,s,l,e,n,r,i)});return}if(!this.options.verifyClient(m))return Ci(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[eI])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Zp)return Ci(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Zv("sha1").update(n+Qv).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[bn.extensionName]){let p=e[bn.extensionName].params,m=Vp.format({[bn.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
10
+ `),this.stream=void 0;return}this.currentDate!==void 0&&zi(this.dir,this.prefix,e,this.opts.retentionDays),this.currentDate=e}close(){this.stream?.end(),this.stream=void 0,this.currentDate=void 0}}});import{appendFileSync as Yg,mkdirSync as Qg}from"node:fs";import{join as em}from"node:path";function Ml(t){let e=t.retentionDays??rm,n=t.clock??(()=>Qt(new Date));Gi={bridgeSink:new br(t.bridgeLogsDir,"bridge",{retentionDays:e,clock:n}),agentSinks:new Map,makeAgentSink:i=>new br(t.agentLogsDir(i),"agent",{retentionDays:e,clock:n})};let r=n();zi(t.bridgeLogsDir,"bridge",r,e);for(let i of t.listAgentIds?.()??[])zi(t.agentLogsDir(i),"agent",r,e)}function im(t,e){let n=t.agentSinks.get(e);return n||(n=t.makeAgentSink(e),t.agentSinks.set(e,n)),n}function Bl(t){qo=t}function Ul(t){return Pn[qo]<=Pn[t]}function zl(t,e){let n=Pn[t];return n===void 0?!0:n>=Pn[e]}function Hi(t){Fl={...t}}function $l(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`${Qt(t)}T${e(t.getHours())}:${e(t.getMinutes())}:${e(t.getSeconds())}.${e(t.getMilliseconds(),3)}${r}${s}:${o}`}function Ar(t,e,n,r,i){try{let s=`${JSON.stringify({ts:$l(new Date),level:e,module:n,msg:r,...i})}
11
+ `;Qg(t,{recursive:!0}),Yg(em(t,On("bridge",Qt(new Date))),s)}catch{}}function sm(t,e){if(t)return t;let n=e?.agentId;return typeof n=="string"&&n.length>0?n:void 0}function $i(t,e,n,r,i){if(Pn[t]<Pn[qo])return;let s=`${JSON.stringify({ts:$l(new Date),level:t,module:e,msg:n,...Fl,...r})}
12
+ `;if(Gi){let o=sm(i,r),a=o?im(Gi,o):Gi.bridgeSink;try{a.write(s)}catch{process.stderr.write(s)}return}t==="error"||t==="warn"?nm.write(s):tm.write(s)}function b(t,e){return{debug:(n,r)=>$i("debug",t,n,r,e),info:(n,r)=>$i("info",t,n,r,e),warn:(n,r)=>$i("warn",t,n,r,e),error:(n,r)=>$i("error",t,n,r,e),child:n=>b(`${t}.${n}`,e),forAgent:n=>b(t,n)}}var Pn,qo,tm,nm,Fl,rm,Gi,F=ve(()=>{"use strict";Ui();Wo();Pn={debug:10,info:20,warn:30,error:40},qo=(()=>{let t=process.env.COZE_BRIDGE_LOG_LEVEL;return t==="debug"||t==="info"||t==="warn"||t==="error"?t:"info"})(),tm=process.stdout,nm=process.stderr,Fl={},rm=pt("COZE_BRIDGE_LOG_RETENTION_DAYS",30),Gi=null});import{execFile as om,spawn as am,spawnSync as uR}from"node:child_process";import{promisify as cm}from"node:util";function dm(t){if(process.platform!=="win32")return!1;if(Gl.test(t))return!0;let n=(t.split(/[/\\]/).pop()??t).replace(Gl,"").toLowerCase();return lm.has(n)}function Hl(t,e){if(process.platform!=="win32")return e??{};let n={...e??{}};return dm(t)&&n.shell===void 0&&(n.shell=!0),n.windowsHide===void 0&&(n.windowsHide=!0),n}function Fe(t,e=[],n={}){return am(t,e,Hl(t,n))}function Cn(t,e=[],n={}){return um(t,e,Hl(t,n))}var lm,Gl,um,gt=ve(()=>{"use strict";lm=new Set(["npm","npx","yarn","pnpm","coze","tsx","claude-agent-acp","codex-acp","openclaw"]),Gl=/\.(cmd|bat|ps1)$/i;um=cm(om)});var _,Te=ve(()=>{"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 Yl={};Bi(Yl,{_resetAcpInstallerForTests:()=>Em,_resetInstallTimeoutsForTests:()=>_m,_setBinaryPathCacheForTests:()=>vm,_setInFlightForTests:()=>Sm,_setInstallTimeoutsForTests:()=>ym,buildInstallFailureMessage:()=>Xl,ensureAcpInstalled:()=>en,formatExecError:()=>ql,getAcpBinaryPath:()=>xr,getAcpPackageSpec:()=>mm,getInFlightInstall:()=>Zo,npmInstallGlobal:()=>Kl,parseVersionTriple:()=>Vl,pickWhichLine:()=>qi,probeAcpVersion:()=>Jl,resolveAcpCommand:()=>Or,versionSatisfiesSpec:()=>Zl});import{readFile as fm,realpath as hm,stat as pm}from"node:fs/promises";import{dirname as Jo,join as gm}from"node:path";function mm(t){let e=Vo[t];if(e)return`${e.npmPackage}@${e.versionSpec}`}function ym(t,e){ji=t,Wi=e}function _m(){ji=5e4,Wi=5e3}function ql(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 jl(t){let e=process.platform==="win32"?"where":"which";try{let{stdout:n}=await Cn(e,[t],{timeout:wm});return qi(n)}catch{return}}function qi(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 Jl(t,e){let n=Vo[t];if(!n)return;let r=e??xr(t);if(!r){le.warn("acp wrapper probe: binary path cache empty",{framework:t,binary:n.binary,hint:"ensureAcpInstalled \u6CA1\u8DD1\u8FC7 / \u88C5\u5931\u8D25 / \u4E4B\u524D negative cache 5min \u5185"});return}let i;try{i=await hm(r)}catch(o){le.warn("acp wrapper probe: realpath failed (symlink target \u4E0D\u5B58\u5728?)",{framework:t,binaryPath:r,err:String(o)});return}let s=Jo(i);for(let o=0;o<Wl;o++){let a=gm(s,"package.json");try{if(!(await pm(a)).isFile()){s=Jo(s);continue}let d=await fm(a,"utf8"),p=JSON.parse(d);if(p.name===n.npmPackage){if(typeof p.version=="string"&&p.version.length>0)return p.version;le.warn("acp wrapper probe: package.json \u627E\u5230\u4F46 version \u5B57\u6BB5\u7F3A",{framework:t,packageJsonPath:a});return}}catch(l){let d=l;d.code!=="ENOENT"&&le.warn("acp wrapper probe: package.json \u8BFB\u53D6\u5F02\u5E38",{framework:t,candidate:a,errCode:d?.code,err:String(l)})}let c=Jo(s);if(c===s)break;s=c}le.warn("acp wrapper probe: \u627E\u4E0D\u5230\u5339\u914D name \u7684 package.json (\u4E0A\u6EAF\u5230 max depth)",{framework:t,binaryPath:r,realBinary:i,expectedName:n.npmPackage,maxDepth:Wl})}function Vl(t){let e=/^\s*(\d+)\.(\d+)\.(\d+)/.exec(t);return e?[Number(e[1]),Number(e[2]),Number(e[3])]:null}function Zl(t,e){let n=Vl(t);if(!n)return!0;let r=/^\^(\d+)\.(\d+)(?:\.(\d+))?$/.exec(e.trim());if(!r)return!0;let[i,s,o]=n,a=Number(r[1]),c=Number(r[2]),l=r[3]!==void 0?Number(r[3]):0;return i>a||i===a&&(s>c||s===c&&o>=l)?a>=1?i===a:c>=1?i===0&&s===c:i===0&&s===0&&o===l:!1}async function Kl(t,e,n){let r=`${t}@${e}`;le.info("npm install -g start",{npmPackage:t,versionSpec:e});let i=Date.now(),s=process.platform==="win32";return new Promise((o,a)=>{let c=Fe("npm",["install","-g",r],{stdio:["ignore","pipe","pipe"],...s?{}:{detached:!0}});if(!c.pid){c.once("error",y=>{le.warn("npm spawn failed (no pid, error swallowed)",{npmPackage:t,err:String(y)})}),a(new Error(`failed to spawn npm: no pid (npmPackage=${t})`));return}let l=c.pid,d=10*1024*1024,p=[],m=[],u=0,h=0;c.stdout?.on("data",y=>{u+=y.length,u<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 le.warn("npm install: kill failed (process already dead?)",{npmPackage:t,pid:l,sig:y,err:String(E)}),!1}},v=setTimeout(()=>{g="terminating",le.warn("npm install timeout, sending SIGTERM to process group",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,timeoutMs:ji,graceMs:Wi,stdoutBytes:u,stderrBytes:h}),S("SIGTERM"),w=setTimeout(()=>{g="killing",le.warn("npm install SIGTERM grace expired, escalating to SIGKILL",{npmPackage:t,versionSpec:e,pid:l,elapsedMs:Date.now()-i,stdoutBytes:u,stderrBytes:h}),S("SIGKILL")},Wi)},ji),f=()=>{g="aborted",le.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?f():n.addEventListener("abort",f,{once:!0})),c.on("error",y=>{clearTimeout(v),w&&clearTimeout(w),n?.removeEventListener("abort",f),le.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",f);let T=Buffer.concat(p).toString("utf8"),R=Buffer.concat(m).toString("utf8"),D=Date.now()-i;if(y===0&&g==="running"){le.info("npm install -g done",{npmPackage:t,versionSpec:e,elapsedMs:D}),o();return}le.warn("npm install -g exited non-success",{npmPackage:t,versionSpec:e,pid:l,phase:g,exitCode:y,signal:E,elapsedMs:D,stdoutBytes:u,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:R,stdout:T});a(C)})})}function Xl(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(`
13
+ `)}async function en(t,e){let n=Vo[t];if(!n)throw new _("BRIDGE_INTERNAL",`ensureAcpInstalled called for non-npm framework: ${t}`);let r=Dn.get(t);if(r)return r;let i=Nn.get(t);if(i)return i;let s=`npm install -g ${n.npmPackage}@${n.versionSpec}`,o=(c,l,d)=>new _("AGENT_DEPENDENCY_INSTALL_FAILED",Xl({framework:t,npmPackage:n.npmPackage,versionSpec:n.versionSpec,command:s,reason:c,elapsedMs:l}),d!==void 0?{cause:d}:{}),a=(async()=>{let c=await jl(n.binary);if(c){let p=process.env.COZE_BRIDGE_ACP_NO_AUTO_UPGRADE==="1",m=p?void 0:await Jl(t,c);if(p||Zl(m??"",n.versionSpec))return Dn.set(t,c),le.info("acp wrapper found on PATH",{binary:n.binary,path:c,version:m??(p?"unchecked (auto-upgrade off)":"unknown"),spec:n.versionSpec}),c;le.info("acp wrapper on PATH but version out of spec \u2014 reinstalling to locked range",{binary:n.binary,path:c,installed:m,spec:n.versionSpec})}let l=Date.now();try{await Kl(n.npmPackage,n.versionSpec,e)}catch(p){let m=ql(p);throw le.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 jl(n.binary);if(!d)throw le.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 Dn.set(t,d),d})().finally(()=>{Nn.delete(t)});return Nn.set(t,a),a}function xr(t){return Dn.get(t)}function Or(t,e){if(e)return e;let n=xr(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 Zo(t){return Nn.get(t)}function Em(){Dn.clear(),Nn.clear()}function Sm(t,e){Nn.set(t,e)}function vm(t,e){Dn.set(t,e)}var le,Vo,ji,Wi,wm,Dn,Nn,Wl,tn=ve(()=>{"use strict";gt();Te();F();le=b("agents.acp-installer"),Vo={"claude-code":{npmPackage:"@agentclientprotocol/claude-agent-acp",binary:"claude-agent-acp",versionSpec:"^0.39"},codex:{npmPackage:"@zed-industries/codex-acp",binary:"codex-acp",versionSpec:"^0.15"}};ji=5e4,Wi=5e3,wm=5e3;Dn=new Map,Nn=new Map;Wl=6});import{chmod as Tm,mkdir as Rm,readFile as km,rename as td,writeFile as nd}from"node:fs/promises";import{dirname as bm}from"node:path";async function Ln(t){try{let e=await km(t,"utf8");return JSON.parse(e)}catch(e){if(e.code==="ENOENT")return null;throw e}}async function Fn(t,e,n){await Rm(bm(t),{recursive:!0});let r=`${JSON.stringify(e,null,2)}
14
+ `,i=`${t}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{n?.mode!==void 0?await nd(i,r,{encoding:"utf8",mode:n.mode}):await nd(i,r,"utf8"),await td(i,t),n?.mode!==void 0&&await Tm(t,n.mode)}catch(s){await td(i,i).catch(()=>{});let{rm:o}=await import("node:fs/promises");throw await o(i,{force:!0}).catch(()=>{}),s}}var Pr=ve(()=>{"use strict"});import{promises as rd,readdirSync as Am}from"node:fs";import{homedir as xm}from"node:os";import{sep as Om,join as ee,resolve as id}from"node:path";function L(t){let e=t??xm(),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"),agentEnvFile:ee(r,"agent-env.json"),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 be(t,e=L()){let n=ee(e.agentsRoot,t);return{root:n,config:ee(n,"config.json"),workspace:ee(n,"workspace"),logs:ee(n,"logs")}}function Ji(t=L()){try{return Am(t.agentsRoot,{withFileTypes:!0}).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function Cr(t,e){let n=await rd.realpath(id(t)).catch(()=>null);if(!n)return!1;let r=await rd.realpath(id(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+Om)}var re=ve(()=>{"use strict"});var Ki={};Bi(Ki,{AGENT_CONFIG_FILE_MODE:()=>Vi,enforceAgentConfigMode:()=>Dm,loadAgentConfig:()=>we,persistAgentSessions:()=>Dr,persistAgentSkills:()=>Zi,saveAgentConfig:()=>Ae});import{chmod as Pm,stat as Cm}from"node:fs/promises";function we(t,e){return Ln(be(t,e).config)}function Ae(t,e){return Fn(be(t.agentId,e).config,t,{mode:Vi})}async function Dm(t,e){if(process.platform==="win32")return;let n=be(t,e).config;try{let r=await Cm(n);if(!r.isFile())return;let i=r.mode&511;i!==Vi&&(await Pm(n,Vi),sd.warn("agent config mode auto-corrected to 0600",{path:n,from:i.toString(8)}))}catch(r){if(r.code==="ENOENT")return;sd.warn("enforceAgentConfigMode: chmod failed (ignored)",{path:n,err:String(r)})}}async function Dr(t,e,n){let r=await we(t,n);r&&(r.sessions=Object.fromEntries(e),await Ae(r,n))}async function Zi(t,e,n){let r=await we(t,n);r&&(r.skills=e,await Ae(r,n))}var sd,Vi,At=ve(()=>{"use strict";Pr();F();re();sd=b("agent-config"),Vi=384});var Xo=H((GR,ld)=>{ld.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 Yi=H(ud=>{var dd={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 Bm(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(dd))ud[t]=Bm(dd[t])});var md=H((jR,gd)=>{var Um=j("fs"),ie=j("path"),fd=Xo(),zm=Yi(),$m=typeof process=="object"&&process.platform==="win32",hd=t=>typeof t=="object"&&t!==null,pd=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 X(t){this.sep=ie.sep,this.fs=Um,hd(t)&&hd(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}gd.exports=X;X.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 zm.FILE_IN_THE_WAY(`"${i}"`)}})}n(t)};X.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=ie.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};X.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=ie.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(u,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)})})})})})};X.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=ie.join(r,a),l=e.fs.statSync(c);(!i||i.test(c))&&o.push(ie.normalize(c)+(l.isDirectory()?e.sep:"")),l.isDirectory()&&s&&(o=o.concat(n(c,i,s)))}),o}return n(t,void 0,!0)};X.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=ie.join(t,a),n.fs.stat(a,function(c,l){if(c)return e(c);l&&(r.push(ie.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))})})})};X.prototype.getAttributes=function(){};X.prototype.setAttributes=function(){};X.crc32update=function(t,e){return pd[(t^e)&255]^t>>>8};X.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,n=-1;for(let r=0;r<e;)n=X.crc32update(n,t[r++]);return~n>>>0};X.methodToString=function(t){switch(t){case fd.STORED:return"STORED ("+t+")";case fd.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};X.canonical=function(t){if(!t)return"";let e=ie.posix.normalize("/"+t.split("\\").join("/"));return ie.join(".",e)};X.zipnamefix=function(t){if(!t)return"";let e=ie.posix.normalize("/"+t.split("\\").join("/"));return ie.posix.join(".",e)};X.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]};X.sanitize=function(t,e){t=ie.resolve(ie.normalize(t));for(var n=e.split("/"),r=0,i=n.length;r<i;r++){var s=ie.normalize(ie.join(t,n.slice(r,i).join(ie.sep)));if(s.indexOf(t)===0)return s}return ie.normalize(ie.join(t,ie.basename(e)))};X.toBuffer=function(e,n){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?n(e):Buffer.alloc(0)};X.readBigUInt64LE=function(t,e){let n=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+n};X.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)};X.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};X.isWin=$m;X.crcTable=pd});var yd=H((WR,wd)=>{var Gm=j("path");wd.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=Gm.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 Ed=H((qR,_d)=>{_d.exports={efs:!0,encode:t=>Buffer.from(t,"utf8"),decode:t=>t.toString("utf8")}});var Un=H((JR,Bn)=>{Bn.exports=md();Bn.exports.Constants=Xo();Bn.exports.Errors=Yi();Bn.exports.FileAttr=yd();Bn.exports.decoder=Ed()});var vd=H((VR,Sd)=>{var xt=Un(),k=xt.Constants;Sd.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,u=0,h=0;t|=xt.isWin?2560:768,n|=k.FLG_EFS;let g={extraLen:0},w=f=>Math.max(0,f)>>>0,S=f=>Math.max(0,f)&65535,v=f=>Math.max(0,f)&255;return i=xt.fromDate2DOS(new Date),{get made(){return t},set made(f){t=f},get version(){return e},set version(f){e=f},get flags(){return n},set flags(f){n=f},get flags_efs(){return(n&k.FLG_EFS)>0},set flags_efs(f){f?n|=k.FLG_EFS:n&=~k.FLG_EFS},get flags_desc(){return(n&k.FLG_DESC)>0},set flags_desc(f){f?n|=k.FLG_DESC:n&=~k.FLG_DESC},get method(){return r},set method(f){switch(f){case k.STORED:this.version=10;case k.DEFLATED:default:this.version=20}r=f},get time(){return xt.fromDOS2Date(this.timeval)},set time(f){f=new Date(f),this.timeval=xt.fromDate2DOS(f)},get timeval(){return i},set timeval(f){i=w(f)},get timeHighByte(){return v(i>>>8)},get crc(){return s},set crc(f){s=w(f)},get compressedSize(){return o},set compressedSize(f){o=w(f)},get size(){return a},set size(f){a=w(f)},get fileNameLength(){return c},set fileNameLength(f){c=f},get extraLength(){return l},set extraLength(f){l=f},get extraLocalLength(){return g.extraLen},set extraLocalLength(f){g.extraLen=f},get commentLength(){return d},set commentLength(f){d=f},get diskNumStart(){return p},set diskNumStart(f){p=w(f)},get inAttr(){return m},set inAttr(f){m=w(f)},get attr(){return u},set attr(f){u=w(f)},get fileAttr(){return(u||0)>>16&4095},get offset(){return h},set offset(f){h=w(f)},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(f){var y=f.slice(h,h+k.LOCHDR);if(y.readUInt32LE(0)!==k.LOCSIG)throw xt.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,T=E+g.extraLen;return f.slice(E,T)},loadFromBinary:function(f){if(f.length!==k.CENHDR||f.readUInt32LE(0)!==k.CENSIG)throw xt.Errors.INVALID_CEN();t=f.readUInt16LE(k.CENVEM),e=f.readUInt16LE(k.CENVER),n=f.readUInt16LE(k.CENFLG),r=f.readUInt16LE(k.CENHOW),i=f.readUInt32LE(k.CENTIM),s=f.readUInt32LE(k.CENCRC),o=f.readUInt32LE(k.CENSIZ),a=f.readUInt32LE(k.CENLEN),c=f.readUInt16LE(k.CENNAM),l=f.readUInt16LE(k.CENEXT),d=f.readUInt16LE(k.CENCOM),p=f.readUInt16LE(k.CENDSK),m=f.readUInt16LE(k.CENATT),u=f.readUInt32LE(k.CENATX),h=f.readUInt32LE(k.CENOFF)},localHeaderToBinary:function(){var f=Buffer.alloc(k.LOCHDR);return f.writeUInt32LE(k.LOCSIG,0),f.writeUInt16LE(e,k.LOCVER),f.writeUInt16LE(n,k.LOCFLG),f.writeUInt16LE(r,k.LOCHOW),f.writeUInt32LE(i,k.LOCTIM),f.writeUInt32LE(s,k.LOCCRC),f.writeUInt32LE(o,k.LOCSIZ),f.writeUInt32LE(a,k.LOCLEN),f.writeUInt16LE(c,k.LOCNAM),f.writeUInt16LE(g.extraLen,k.LOCEXT),f},centralHeaderToBinary:function(){var f=Buffer.alloc(k.CENHDR+c+l+d);return f.writeUInt32LE(k.CENSIG,0),f.writeUInt16LE(t,k.CENVEM),f.writeUInt16LE(e,k.CENVER),f.writeUInt16LE(n,k.CENFLG),f.writeUInt16LE(r,k.CENHOW),f.writeUInt32LE(i,k.CENTIM),f.writeUInt32LE(s,k.CENCRC),f.writeUInt32LE(o,k.CENSIZ),f.writeUInt32LE(a,k.CENLEN),f.writeUInt16LE(c,k.CENNAM),f.writeUInt16LE(l,k.CENEXT),f.writeUInt16LE(d,k.CENCOM),f.writeUInt16LE(p,k.CENDSK),f.writeUInt16LE(m,k.CENATT),f.writeUInt32LE(u,k.CENATX),f.writeUInt32LE(h,k.CENOFF),f},toJSON:function(){let f=function(y){return y+" bytes"};return{made:t,version:e,flags:n,method:xt.methodToString(r),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:f(o),size:f(a),fileNameLength:f(c),extraLength:f(l),commentLength:f(d),diskNumStart:p,inAttr:m,attr:u,offset:h,centralHeaderSize:f(k.CENHDR+c+l+d)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Td=H((ZR,Id)=>{var zn=Un(),J=zn.Constants;Id.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 J.ENDHDR+i},loadFromBinary:function(s){if((s.length!==J.ENDHDR||s.readUInt32LE(0)!==J.ENDSIG)&&(s.length<J.ZIP64HDR||s.readUInt32LE(0)!==J.ZIP64SIG))throw zn.Errors.INVALID_END();s.readUInt32LE(0)===J.ENDSIG?(t=s.readUInt16LE(J.ENDSUB),e=s.readUInt16LE(J.ENDTOT),n=s.readUInt32LE(J.ENDSIZ),r=s.readUInt32LE(J.ENDOFF),i=s.readUInt16LE(J.ENDCOM)):(t=zn.readBigUInt64LE(s,J.ZIP64SUB),e=zn.readBigUInt64LE(s,J.ZIP64TOT),n=zn.readBigUInt64LE(s,J.ZIP64SIZE),r=zn.readBigUInt64LE(s,J.ZIP64OFF),i=0)},toBinary:function(){var s=Buffer.alloc(J.ENDHDR+i);return s.writeUInt32LE(J.ENDSIG,0),s.writeUInt32LE(0,4),s.writeUInt16LE(t,J.ENDSUB),s.writeUInt16LE(e,J.ENDTOT),s.writeUInt32LE(n,J.ENDSIZ),s.writeUInt32LE(r,J.ENDOFF),s.writeUInt16LE(i,J.ENDCOM),s.fill(" ",J.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 Qo=H(Yo=>{Yo.EntryHeader=vd();Yo.MainHeader=Td()});var kd=H((XR,Rd)=>{Rd.exports=function(t){var e=j("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 Ad=H((YR,bd)=>{var Hm=+(process.versions?process.versions.node:"").split(".")[0]||0;bd.exports=function(t,e){var n=j("zlib");let r=Hm>=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 Dd=H((QR,Cd)=>{"use strict";var{randomFillSync:xd}=j("crypto"),jm=Yi(),Wm=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}),Pd=(t,e)=>Math.imul(t,e)>>>0,Od=(t,e)=>Wm[(t^e)&255]^t>>>8,Nr=()=>typeof xd=="function"?xd(Buffer.alloc(12)):Nr.node();Nr.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 Qi={genSalt:Nr};function es(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])}es.prototype.updateKeys=function(t){let e=this.keys;return e[0]=Od(e[0],t),e[1]+=e[0]&255,e[1]=Pd(e[1],134775813)+1,e[2]=Od(e[2],e[1]>>>24),t};es.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Pd(t,t^1)>>8&255};function qm(t){let e=new es(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 Jm(t){let e=new es(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 Vm(t,e,n){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let r=qm(n),i=r(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw jm.WRONG_PASSWORD();return r(t.slice(12))}function Zm(t){Buffer.isBuffer(t)&&t.length>=12?Qi.genSalt=function(){return t.slice(0,12)}:t==="node"?Qi.genSalt=Nr.node:Qi.genSalt=Nr}function Km(t,e,n,r=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=Jm(n),s=Qi.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)}Cd.exports={decrypt:Vm,encrypt:Km,_salter:Zm}});var Nd=H(ts=>{ts.Deflater=kd();ts.Inflater=Ad();ts.ZipCrypto=Dd()});var ta=H((tk,Ld)=>{var z=Un(),Xm=Qo(),Y=z.Constants,ea=Nd();Ld.exports=function(t,e){var n=new Xm.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 u(f){if(!n.flags_desc&&!n.localHeader.flags_desc){if(z.crc32(f)!==n.localHeader.crc)return!1}else{let y={},E=n.realDataOffset+n.compressedSize;if(e.readUInt32LE(E)==Y.LOCSIG||e.readUInt32LE(E)==Y.CENSIG)throw z.Errors.DESCRIPTOR_NOT_EXIST();if(e.readUInt32LE(E)==Y.EXTSIG)y.crc=e.readUInt32LE(E+Y.EXTCRC),y.compressedSize=e.readUInt32LE(E+Y.EXTSIZ),y.size=e.readUInt32LE(E+Y.EXTLEN);else if(e.readUInt16LE(E+12)===19280)y.crc=e.readUInt32LE(E+Y.EXTCRC-4),y.compressedSize=e.readUInt32LE(E+Y.EXTSIZ-4),y.size=e.readUInt32LE(E+Y.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(f)!==y.crc)return!1}return!0}function h(f,y,E){if(typeof y>"u"&&typeof f=="string"&&(E=f,f=void 0),s)return f&&y&&y(Buffer.alloc(0),z.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var T=m();if(T.length===0)return f&&y&&y(T),T;if(n.encrypted){if(typeof E!="string"&&!Buffer.isBuffer(E))throw z.Errors.INVALID_PASS_PARAM();T=ea.ZipCrypto.decrypt(T,n,E)}var R=Buffer.alloc(n.size);switch(n.method){case z.Constants.STORED:if(T.copy(R),u(R))return f&&y&&y(R),R;throw f&&y&&y(R,z.Errors.BAD_CRC()),z.Errors.BAD_CRC();case z.Constants.DEFLATED:var D=new ea.Inflater(T,n.size);if(f)D.inflateAsync(function(C){C.copy(C,0),y&&(u(C)?y(C):y(C,z.Errors.BAD_CRC()))});else{if(D.inflate(R).copy(R,0),!u(R))throw z.Errors.BAD_CRC(`"${p.decode(r)}"`);return R}break;default:throw f&&y&&y(Buffer.alloc(0),z.Errors.UNKNOWN_METHOD()),z.Errors.UNKNOWN_METHOD()}}function g(f,y){if((!o||!o.length)&&Buffer.isBuffer(e))return f&&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),f&&y&&y(E),E;default:case z.Constants.DEFLATED:var T=new ea.Deflater(o);if(f)T.deflateAsync(function(D){E=Buffer.alloc(D.length),n.compressedSize=D.length,D.copy(E),y&&y(E)});else{var R=T.deflate();return n.compressedSize=R.length,R}T=null;break}}else if(f&&y)y(Buffer.alloc(0));else return Buffer.alloc(0)}function w(f,y){return z.readBigUInt64LE(f,y)}function S(f){try{for(var y=0,E,T,R;y+4<f.length;)E=f.readUInt16LE(y),y+=2,T=f.readUInt16LE(y),y+=2,R=f.slice(y,y+T),y+=T,Y.ID_ZIP64===E&&v(R)}catch{throw z.Errors.EXTRA_FIELD_PARSE_ERROR()}}function v(f){var y,E,T,R;f.length>=Y.EF_ZIP64_SCOMP&&(y=w(f,Y.EF_ZIP64_SUNCOMP),n.size===Y.EF_ZIP64_OR_32&&(n.size=y)),f.length>=Y.EF_ZIP64_RHO&&(E=w(f,Y.EF_ZIP64_SCOMP),n.compressedSize===Y.EF_ZIP64_OR_32&&(n.compressedSize=E)),f.length>=Y.EF_ZIP64_DSN&&(T=w(f,Y.EF_ZIP64_RHO),n.offset===Y.EF_ZIP64_OR_32&&(n.offset=T)),f.length>=Y.EF_ZIP64_DSN+4&&(R=f.readUInt32LE(Y.EF_ZIP64_DSN),n.diskNumStart===Y.EF_ZIP64_OR_16&&(n.diskNumStart=R))}return{get entryName(){return p.decode(r)},get rawEntryName(){return r},set entryName(f){r=z.toBuffer(f,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(f){a=f,n.extraLength=f.length,S(f)},get comment(){return p.decode(i)},set comment(f){if(i=z.toBuffer(f,p.encode),n.commentLength=i.length,i.length>65535)throw z.Errors.COMMENT_TOO_LONG()},get name(){var f=p.decode(r);return s?f.substr(f.length-1).split("/").pop():f.split("/").pop()},get isDirectory(){return s},getCompressedData:function(){return g(!1,null)},getCompressedDataAsync:function(f){g(!0,f)},setData:function(f){o=z.toBuffer(f,z.decoder.encode),!s&&o.length?(n.size=o.length,n.method=z.Constants.DEFLATED,n.crc=z.crc32(f),n.changed=!0):n.method=z.Constants.STORED},getData:function(f){return n.changed?o:h(!1,null,f)},getDataAsync:function(f,y){n.changed?f(o):h(!0,f,y)},set attr(f){n.attr=f},get attr(){return n.attr},set header(f){n.loadFromBinary(f)},get header(){return n},packCentralHeader:function(){n.flags_efs=this.efs,n.extraLength=a.length;var f=n.centralHeaderToBinary(),y=z.Constants.CENHDR;return r.copy(f,y),y+=r.length,a.copy(f,y),y+=n.extraLength,i.copy(f,y),f},packLocalHeader:function(){let f=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,f),f+=y.length,r.copy(E,f),f+=r.length,c.copy(E,f),f+=c.length,E},toJSON:function(){let f=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:f(e),data:f(o)}},toString:function(){return JSON.stringify(this.toJSON(),null," ")}}}});var Bd=H((nk,Md)=>{var Fd=ta(),Ym=Qo(),ye=Un();Md.exports=function(t,e){var n=[],r={},i=Buffer.alloc(0),s=new Ym.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 f=0;f<v.length;f++){let y=v.slice(0,f+1).join("/")+"/";w.add(y)}}for(let S of w)if(!(S in r)){let v=new Fd(l);v.entryName=S,v.attr=16,v.temporary=!0,n.push(v),r[v.entryName]=v,c.add(v)}}function u(){if(o=!0,r={},s.diskEntries>(t.length-s.offset)/ye.Constants.CENHDR)throw ye.Errors.DISK_ENTRY_TOO_LARGE();n=new Array(s.diskEntries);for(var w=s.offset,S=0;S<n.length;S++){var v=w,f=new Fd(l,t);f.header=t.slice(v,v+=ye.Constants.CENHDR),f.entryName=t.slice(v,v+=f.header.fileNameLength),f.header.extraLength&&(f.extra=t.slice(v,v+=f.header.extraLength)),f.header.commentLength&&(f.comment=t.slice(v,v+f.header.commentLength)),w+=f.header.centralHeaderSize,n[S]=f,r[f.entryName]=f}c.clear(),m()}function h(w){var S=t.length-ye.Constants.ENDHDR,v=Math.max(0,S-65535),f=v,y=t.length,E=-1,T=0;for(typeof l.trailingSpace=="boolean"&&l.trailingSpace&&(v=0),S;S>=f;S--)if(t[S]===80){if(t.readUInt32LE(S)===ye.Constants.ENDSIG){E=S,T=S,y=S+ye.Constants.ENDHDR,f=S-ye.Constants.END64HDR;continue}if(t.readUInt32LE(S)===ye.Constants.END64SIG){f=v;continue}if(t.readUInt32LE(S)===ye.Constants.ZIP64SIG){E=S,y=S+ye.readBigUInt64LE(t,S+ye.Constants.ZIP64SIZE)+ye.Constants.ZIP64LEAD;break}}if(E==-1)throw ye.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(E,y)),s.commentLength&&(i=t.slice(T+ye.Constants.ENDHDR)),w&&u()}function g(){n.length>1&&!d&&n.sort((w,S)=>w.entryName.toLowerCase().localeCompare(S.entryName.toLowerCase()))}return{get entries(){return o||u(),n.filter(w=>!c.has(w))},get comment(){return p.decode(i)},set comment(w){i=ye.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||u(),r[w]||null},setEntry:function(w){o||u(),n.push(w),r[w.entryName]=w,s.totalEntries=n.length},deleteFile:function(w,S=!0){o||u();let v=r[w];this.getEntryChildren(v,S).map(y=>y.entryName).forEach(this.deleteEntry)},deleteEntry:function(w){o||u();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||u(),typeof w=="object")if(w.isDirectory&&S){let v=[],f=w.entryName;for(let y of n)y.entryName.startsWith(f)&&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||u(),g();let w=[],S=[],v=0,f=0;s.size=0,s.offset=0;let y=0;for(let R of this.entries){let D=R.getCompressedData();R.header.offset=f;let C=R.packLocalHeader(),G=C.length+D.length;f+=G,w.push(C),w.push(D);let M=R.packCentralHeader();S.push(M),s.size+=M.length,v+=G+M.length,y++}v+=s.mainHeaderSize,s.offset=f,s.totalEntries=y,f=0;let E=Buffer.alloc(v);for(let R of w)R.copy(E,f),f+=R.length;for(let R of S)R.copy(E,f),f+=R.length;let T=s.toBinary();return i&&i.copy(T,ye.Constants.ENDHDR),T.copy(E,f),t=E,o=!1,E},toAsyncBuffer:function(w,S,v,f){try{o||u(),g();let y=[],E=[],T=0,R=0,D=0;s.size=0,s.offset=0;let C=function(G){if(G.length>0){let M=G.shift(),ae=M.entryName+M.extra.toString();v&&v(ae),M.getCompressedDataAsync(function(Ee){f&&f(ae),M.header.offset=R;let I=M.packLocalHeader(),x=I.length+Ee.length;R+=x,y.push(I),y.push(Ee);let O=M.packCentralHeader();E.push(O),s.size+=O.length,T+=x+O.length,D++,C(G)})}else{T+=s.mainHeaderSize,s.offset=R,s.totalEntries=D,R=0;let M=Buffer.alloc(T);y.forEach(function(Ee){Ee.copy(M,R),R+=Ee.length}),E.forEach(function(Ee){Ee.copy(M,R),R+=Ee.length});let ae=s.toBinary();i&&i.copy(ae,ye.Constants.ENDHDR),ae.copy(M,R),t=M,o=!1,w(M)}};C(Array.from(this.entries))}catch(y){S(y)}}}}});var $d=H((rk,zd)=>{var Z=Un(),V=j("path"),Qm=ta(),ew=Bd(),nn=(...t)=>Z.findLast(t,e=>typeof e=="boolean"),Ud=(...t)=>Z.findLast(t,e=>typeof e=="string"),tw=(...t)=>Z.findLast(t,e=>typeof e=="function"),nw={noSort:!1,readEntries:!1,method:Z.Constants.NONE,fs:null};zd.exports=function(t,e){let n=null,r=Object.assign(Object.create(null),nw);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=Z.Constants.BUFFER,t=void 0)),Object.assign(r,e);let i=new Z(r);if((typeof r.decoder!="object"||typeof r.decoder.encode!="function"||typeof r.decoder.decode!="function")&&(r.decoder=Z.decoder),t&&typeof t=="string")if(i.fs.existsSync(t))r.method=Z.Constants.FILE,r.filename=t,n=i.fs.readFileSync(t);else throw Z.Errors.INVALID_FILENAME();let s=new ew(n,r),{canonical:o,sanitize:a,zipnamefix:c}=Z;function l(u){if(u&&s){var h;if(typeof u=="string"&&(h=s.getEntry(V.posix.normalize(u))),typeof u=="object"&&typeof u.entryName<"u"&&typeof u.header<"u"&&(h=s.getEntry(u.entryName)),h)return h}return null}function d(u){let{join:h,normalize:g,sep:w}=V.posix;return h(V.isAbsolute(u)?"/":".",g(w+u.split("\\").join(w)+w))}function p(u){return u instanceof RegExp?(function(h){return function(g){return h.test(g)}})(u):typeof u!="function"?()=>!0:u}let m=(u,h)=>{let g=h.slice(-1);return g=g===i.sep?i.sep:"",V.relative(u,h)+g};return{readFile:function(u,h){var g=l(u);return g&&g.getData(h)||null},childCount:function(u){let h=l(u);if(h)return s.getChildCount(h)},readFileAsync:function(u,h){var g=l(u);g?g.getDataAsync(h):h(null,"getEntry failed for:"+u)},readAsText:function(u,h){var g=l(u);if(g){var w=g.getData();if(w&&w.length)return w.toString(h||"utf8")}return""},readAsTextAsync:function(u,h,g){var w=l(u);w?w.getDataAsync(function(S,v){if(v){h(S,v);return}S&&S.length?h(S.toString(g||"utf8")):h("")}):h("")},deleteFile:function(u,h=!0){var g=l(u);g&&s.deleteFile(g.entryName,h)},deleteEntry:function(u){var h=l(u);h&&s.deleteEntry(h.entryName)},addZipComment:function(u){s.comment=u},getZipComment:function(){return s.comment||""},addZipEntryComment:function(u,h){var g=l(u);g&&(g.comment=h)},getZipEntryComment:function(u){var h=l(u);return h&&h.comment||""},updateFile:function(u,h){var g=l(u);g&&g.setData(h)},addLocalFile:function(u,h,g,w){if(i.fs.existsSync(u)){h=h?d(h):"";let S=V.win32.basename(V.win32.normalize(u));h+=g||S;let v=i.fs.statSync(u),f=v.isFile()?i.fs.readFileSync(u):Buffer.alloc(0);v.isDirectory()&&(h+=i.sep),this.addFile(h,f,w,v)}else throw Z.Errors.FILE_NOT_FOUND(u)},addLocalFileAsync:function(u,h){u=typeof u=="object"?u:{localPath:u};let g=V.resolve(u.localPath),{comment:w}=u,{zipPath:S,zipName:v}=u,f=this;i.fs.stat(g,function(y,E){if(y)return h(y,!1);S=S?d(S):"";let T=V.win32.basename(V.win32.normalize(g));if(S+=v||T,E.isFile())i.fs.readFile(g,function(R,D){return R?h(R,!1):(f.addFile(S,D,w,E),setImmediate(h,void 0,!0))});else if(E.isDirectory())return S+=i.sep,f.addFile(S,Buffer.alloc(0),w,E),setImmediate(h,void 0,!0)})},addLocalFolder:function(u,h,g){if(g=p(g),h=h?d(h):"",u=V.normalize(u),i.fs.existsSync(u)){let w=i.findFiles(u),S=this;if(w.length)for(let v of w){let f=V.join(h,m(u,v));g(f)&&S.addLocalFile(v,V.dirname(f))}}else throw Z.Errors.FILE_NOT_FOUND(u)},addLocalFolderAsync:function(u,h,g,w){w=p(w),g=g?d(g):"",u=V.normalize(u);var S=this;i.fs.open(u,"r",function(v){if(v&&v.code==="ENOENT")h(void 0,Z.Errors.FILE_NOT_FOUND(u));else if(v)h(void 0,v);else{var f=i.findFiles(u),y=-1,E=function(){if(y+=1,y<f.length){var T=f[y],R=m(u,T).split("\\").join("/");R=R.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),w(R)?i.fs.stat(T,function(D,C){D&&h(void 0,D),C.isFile()?i.fs.readFile(T,function(G,M){G?h(void 0,G):(S.addFile(g+R,M,"",C),E())}):(S.addFile(g+R+"/",Buffer.alloc(0),"",C),E())}):process.nextTick(()=>{E()})}else h(!0,void 0)};E()}})},addLocalFolderAsync2:function(u,h){let g=this;u=typeof u=="object"?u:{localPath:u},localPath=V.resolve(d(u.localPath));let{zipPath:w,filter:S,namefix:v}=u;S instanceof RegExp?S=(function(E){return function(T){return E.test(T)}})(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 f=E=>V.join(w,v(m(localPath,E))),y=E=>V.win32.basename(V.win32.normalize(v(E)));i.fs.open(localPath,"r",function(E){E&&E.code==="ENOENT"?h(void 0,Z.Errors.FILE_NOT_FOUND(localPath)):E?h(void 0,E):i.findFilesAsync(localPath,function(T,R){if(T)return h(T);R=R.filter(D=>S(f(D))),R.length||h(void 0,!1),setImmediate(R.reverse().reduce(function(D,C){return function(G,M){if(G||M===!1)return setImmediate(D,G,!1);g.addLocalFileAsync({localPath:C,zipPath:V.dirname(f(C)),zipName:y(C)},D)}},h))})})},addLocalFolderPromise:function(u,h){return new Promise((g,w)=>{this.addLocalFolderAsync2(Object.assign({localPath:u},h),(S,v)=>{S&&w(S),v&&g(this)})})},addFile:function(u,h,g,w){u=c(u);let S=l(u),v=S!=null;v||(S=new Qm(r),S.entryName=u),S.comment=g||"";let f=typeof w=="object"&&w instanceof i.fs.Stats;f&&(S.header.time=w.mtime);var y=S.isDirectory?16:0;let E=S.isDirectory?16384:32768;return f?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(u){return s.password=u,s?s.entries:[]},getEntry:function(u){return l(u)},getEntryCount:function(){return s.getEntryCount()},forEach:function(u){return s.forEach(u)},extractEntryTo:function(u,h,g,w,S,v){w=nn(!1,w),S=nn(!1,S),g=nn(!0,g),v=Ud(S,v);var f=l(u);if(!f)throw Z.Errors.NO_ENTRY();var y=o(f.entryName),E=a(h,v&&!f.isDirectory?v:g?y:V.basename(y));if(f.isDirectory){var T=s.getEntryChildren(f);return T.forEach(function(C){if(C.isDirectory)return;var G=C.getData();if(!G)throw Z.Errors.CANT_EXTRACT_FILE();var M=o(C.entryName),ae=a(h,g?M:V.basename(M));let Ee=S?C.header.fileAttr:void 0;i.writeFileTo(ae,G,w,Ee)}),!0}var R=f.getData(s.password);if(!R)throw Z.Errors.CANT_EXTRACT_FILE();if(i.fs.existsSync(E)&&!w)throw Z.Errors.CANT_OVERRIDE();let D=S?u.header.fileAttr:void 0;return i.writeFileTo(E,R,w,D),!0},test:function(u){if(!s)return!1;for(var h in s.entries)try{if(h.isDirectory)continue;var g=s.entries[h].getData(u);if(!g)return!1}catch{return!1}return!0},extractAllTo:function(u,h,g,w){if(g=nn(!1,g),w=Ud(g,w),h=nn(!1,h),!s)throw Z.Errors.NO_ZIP();s.entries.forEach(function(S){var v=a(u,o(S.entryName));if(S.isDirectory){i.makeDir(v);return}var f=S.getData(w);if(!f)throw Z.Errors.CANT_EXTRACT_FILE();let y=g?S.header.fileAttr:void 0;i.writeFileTo(v,f,h,y);try{i.fs.utimesSync(v,S.header.time,S.header.time)}catch{throw Z.Errors.CANT_EXTRACT_FILE()}})},extractAllToAsync:function(u,h,g,w){if(w=tw(h,g,w),g=nn(!1,g),h=nn(!1,h),!w)return new Promise((E,T)=>{this.extractAllToAsync(u,h,g,function(R){R?T(R):E(this)})});if(!s){w(Z.Errors.NO_ZIP());return}u=V.resolve(u);let S=E=>a(u,V.normalize(o(E.entryName))),v=(E,T)=>new Error(E+': "'+T+'"'),f=[],y=[];s.entries.forEach(E=>{E.isDirectory?f.push(E):y.push(E)});for(let E of f){let T=S(E),R=g?E.header.fileAttr:void 0;try{i.makeDir(T),R&&i.fs.chmodSync(T,R),i.fs.utimesSync(T,E.header.time,E.header.time)}catch{w(v("Unable to create folder",T))}}y.reverse().reduce(function(E,T){return function(R){if(R)E(R);else{let D=V.normalize(o(T.entryName)),C=a(u,D);T.getDataAsync(function(G,M){if(M)E(M);else if(!G)E(Z.Errors.CANT_EXTRACT_FILE());else{let ae=g?T.header.fileAttr:void 0;i.writeFileToAsync(C,G,h,ae,function(Ee){Ee||E(v("Unable to write file",C)),i.fs.utimes(C,T.header.time,T.header.time,function(I){I?E(v("Unable to set times",C)):E()})})}})}}},w)()},writeZip:function(u,h){if(arguments.length===1&&typeof u=="function"&&(h=u,u=""),!u&&r.filename&&(u=r.filename),!!u){var g=s.compressToBuffer();if(g){var w=i.writeFileTo(u,g,!0);typeof h=="function"&&h(w?null:new Error("failed"),"")}}},writeZipPromise:function(u,h){let{overwrite:g,perm:w}=Object.assign({overwrite:!0},h);return new Promise((S,v)=>{!u&&r.filename&&(u=r.filename),u||v("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(f=>{let y=E=>E?S(E):v("ADM-ZIP: Wasn't able to write zip file");i.writeFileToAsync(u,f,g,w,y)},v)})},toBufferPromise:function(){return new Promise((u,h)=>{s.toAsyncBuffer(u,h)})},toBuffer:function(u,h,g,w){return typeof u=="function"?(s.toAsyncBuffer(u,h,g,w),null):s.compressToBuffer()}}}});function kS(){return Sh||(Sh=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function bS(){return vh||(vh=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function AS(t){let e=new Promise((n,r)=>{let i=()=>{t.removeEventListener("success",s),t.removeEventListener("error",o)},s=()=>{n(Ue(t.result)),i()},o=()=>{r(t.error),i()};t.addEventListener("success",s),t.addEventListener("error",o)});return e.then(n=>{n instanceof IDBCursor&&Ih.set(n,t)}).catch(()=>{}),Pc.set(e,t),e}function xS(t){if(xc.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)});xc.set(t,e)}function Rh(t){Oc=t(Oc)}function OS(t){return t===IDBDatabase.prototype.transaction&&!("objectStoreNames"in IDBTransaction.prototype)?function(e,...n){let r=t.call(Ei(this),e,...n);return Th.set(r,e.sort?e.sort():[e]),Ue(r)}:bS().includes(t)?function(...e){return t.apply(Ei(this),e),Ue(Ih.get(this))}:function(...e){return Ue(t.apply(Ei(this),e))}}function PS(t){return typeof t=="function"?OS(t):(t instanceof IDBTransaction&&xS(t),RS(t,kS())?new Proxy(t,Oc):t)}function Ue(t){if(t instanceof IDBRequest)return AS(t);if(Ac.has(t))return Ac.get(t);let e=PS(t);return e!==t&&(Ac.set(t,e),Pc.set(e,t)),e}var RS,Sh,vh,Ih,xc,Th,Ac,Pc,Oc,Ei,Cc=ve(()=>{RS=(t,e)=>e.some(n=>t instanceof n);Ih=new WeakMap,xc=new WeakMap,Th=new WeakMap,Ac=new WeakMap,Pc=new WeakMap;Oc={get(t,e,n){if(t instanceof IDBTransaction){if(e==="done")return xc.get(t);if(e==="objectStoreNames")return t.objectStoreNames||Th.get(t);if(e==="store")return n.objectStoreNames[1]?void 0:n.objectStore(n.objectStoreNames[0])}return Ue(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}};Ei=t=>Pc.get(t)});var bh={};Bi(bh,{deleteDB:()=>DS,openDB:()=>CS,unwrap:()=>Ei,wrap:()=>Ue});function CS(t,e,{blocked:n,upgrade:r,blocking:i,terminated:s}={}){let o=indexedDB.open(t,e),a=Ue(o);return r&&o.addEventListener("upgradeneeded",c=>{r(Ue(o.result),c.oldVersion,c.newVersion,Ue(o.transaction))}),n&&o.addEventListener("blocked",()=>n()),a.then(c=>{s&&c.addEventListener("close",()=>s()),i&&c.addEventListener("versionchange",()=>i())}).catch(()=>{}),a}function DS(t,{blocked:e}={}){let n=indexedDB.deleteDatabase(t);return e&&n.addEventListener("blocked",()=>e()),Ue(n).then(()=>{})}function kh(t,e){if(!(t instanceof IDBDatabase&&!(e in t)&&typeof e=="string"))return;if(Dc.get(e))return Dc.get(e);let n=e.replace(/FromIndex$/,""),r=e!==n,i=LS.includes(n);if(!(n in(r?IDBIndex:IDBObjectStore).prototype)||!(i||NS.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 Dc.set(e,s),s}var NS,LS,Dc,Ah=ve(()=>{Cc();Cc();NS=["get","getKey","getAll","getAllKeys","count"],LS=["put","add","delete","clear"],Dc=new Map;Rh(t=>({...t,get:(e,n,r)=>kh(e,n)||t.get(e,n,r),has:(e,n)=>!!kh(e,n)||t.has(e,n)}))});var It=H((GO,ep)=>{"use strict";var Yh=["nodebuffer","arraybuffer","fragments"],Qh=typeof Blob<"u";Qh&&Yh.push("blob");ep.exports={BINARY_TYPES:Yh,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Qh,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ki=H((HO,co)=>{"use strict";var{EMPTY_BUFFER:B0}=It(),nl=Buffer[Symbol.species];function U0(t,e){if(t.length===0)return B0;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 nl(n.buffer,n.byteOffset,r):n}function tp(t,e,n,r,i){for(let s=0;s<i;s++)n[r+s]=t[s]^e[s&3]}function np(t,e){for(let n=0;n<t.length;n++)t[n]^=e[n&3]}function z0(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function rl(t){if(rl.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new nl(t):ArrayBuffer.isView(t)?e=new nl(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),rl.readOnly=!1),e}co.exports={concat:U0,mask:tp,toArrayBuffer:z0,toBuffer:rl,unmask:np};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=j("bufferutil");co.exports.mask=function(e,n,r,i,s){s<48?tp(e,n,r,i,s):t.mask(e,n,r,i,s)},co.exports.unmask=function(e,n){e.length<32?np(e,n):t.unmask(e,n)}}catch{}});var sp=H((jO,ip)=>{"use strict";var rp=Symbol("kDone"),il=Symbol("kRun"),sl=class{constructor(e){this[rp]=()=>{this.pending--,this[il]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[il]()}[il](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[rp])}}};ip.exports=sl});var hr=H((WO,lp)=>{"use strict";var bi=j("zlib"),op=ki(),$0=sp(),{kStatusCode:ap}=It(),G0=Buffer[Symbol.species],H0=Buffer.from([0,0,255,255]),uo=Symbol("permessage-deflate"),Tt=Symbol("total-length"),ur=Symbol("callback"),Vt=Symbol("buffers"),fr=Symbol("error"),lo,ol=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,!lo){let n=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;lo=new $0(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[ur];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){lo.add(i=>{this._decompress(e,n,(s,o)=>{i(),r(s,o)})})}compress(e,n,r){lo.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"?bi.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=bi.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[uo]=this,this._inflate[Tt]=0,this._inflate[Vt]=[],this._inflate.on("error",W0),this._inflate.on("data",cp)}this._inflate[ur]=r,this._inflate.write(e),n&&this._inflate.write(H0),this._inflate.flush(()=>{let s=this._inflate[fr];if(s){this._inflate.close(),this._inflate=null,r(s);return}let o=op.concat(this._inflate[Vt],this._inflate[Tt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Tt]=0,this._inflate[Vt]=[],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"?bi.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=bi.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Tt]=0,this._deflate[Vt]=[],this._deflate.on("data",j0)}this._deflate[ur]=r,this._deflate.write(e),this._deflate.flush(bi.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=op.concat(this._deflate[Vt],this._deflate[Tt]);n&&(s=new G0(s.buffer,s.byteOffset,s.length-4)),this._deflate[ur]=null,this._deflate[Tt]=0,this._deflate[Vt]=[],n&&this.params[`${i}_no_context_takeover`]&&this._deflate.reset(),r(null,s)})}};lp.exports=ol;function j0(t){this[Vt].push(t),this[Tt]+=t.length}function cp(t){if(this[Tt]+=t.length,this[uo]._maxPayload<1||this[Tt]<=this[uo]._maxPayload){this[Vt].push(t);return}this[fr]=new RangeError("Max payload size exceeded"),this[fr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[fr][ap]=1009,this.removeListener("data",cp),this.reset()}function W0(t){if(this[uo]._inflate=null,this[fr]){this[ur](this[fr]);return}t[ap]=1007,this[ur](t)}});var pr=H((qO,fo)=>{"use strict";var{isUtf8:dp}=j("buffer"),{hasBlob:q0}=It(),J0=[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 V0(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function al(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 Z0(t){return q0&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}fo.exports={isBlob:Z0,isValidStatusCode:V0,isValidUTF8:al,tokenChars:J0};if(dp)fo.exports.isValidUTF8=function(t){return t.length<24?al(t):dp(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=j("utf-8-validate");fo.exports.isValidUTF8=function(e){return e.length<32?al(e):t(e)}}catch{}});var fl=H((JO,wp)=>{"use strict";var{Writable:K0}=j("stream"),up=hr(),{BINARY_TYPES:X0,EMPTY_BUFFER:fp,kStatusCode:Y0,kWebSocket:Q0}=It(),{concat:cl,toArrayBuffer:ev,unmask:tv}=ki(),{isValidStatusCode:nv,isValidUTF8:hp}=pr(),ho=Buffer[Symbol.species],$e=0,pp=1,gp=2,mp=3,ll=4,dl=5,po=6,ul=class extends K0{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||X0[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Q0]=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=$e}_write(e,n,r){if(this._opcode===8&&this._state==$e)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 ho(r.buffer,r.byteOffset+e,r.length-e),new ho(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 ho(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 $e:this.getInfo(e);break;case pp:this.getPayloadLength16(e);break;case gp:this.getPayloadLength64(e);break;case mp:this.getMask();break;case ll:this.getData(e);break;case dl:case po: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[up.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=pp:this._payloadLength===127?this._state=gp: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=mp:this._state=ll}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ll}getData(e){let n=fp;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&&tv(n,this._mask)}if(this._opcode>7){this.controlMessage(n,e);return}if(this._compressed){this._state=dl,this.decompress(n,e);return}n.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(n)),this.dataMessage(e)}decompress(e,n){this._extensions[up.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===$e&&this.startLoop(n)})}dataMessage(e){if(!this._fin){this._state=$e;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=cl(r,n):this._binaryType==="arraybuffer"?i=ev(cl(r,n)):this._binaryType==="blob"?i=new Blob(r):i=r,this._allowSynchronousEvents?(this.emit("message",i,!0),this._state=$e):(this._state=po,setImmediate(()=>{this.emit("message",i,!0),this._state=$e,this.startLoop(e)}))}else{let i=cl(r,n);if(!this._skipUTF8Validation&&!hp(i)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===dl||this._allowSynchronousEvents?(this.emit("message",i,!1),this._state=$e):(this._state=po,setImmediate(()=>{this.emit("message",i,!1),this._state=$e,this.startLoop(e)}))}}controlMessage(e,n){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,fp),this.end();else{let r=e.readUInt16BE(0);if(!nv(r)){let s=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");n(s);return}let i=new ho(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!hp(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=$e;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=$e):(this._state=po,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=$e,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[Y0]=i,o}};wp.exports=ul});var gl=H((ZO,Ep)=>{"use strict";var{Duplex:VO}=j("stream"),{randomFillSync:rv}=j("crypto"),yp=hr(),{EMPTY_BUFFER:iv,kWebSocket:sv,NOOP:ov}=It(),{isBlob:gr,isValidStatusCode:av}=pr(),{mask:_p,toBuffer:Tn}=ki(),Ge=Symbol("kByteLength"),cv=Buffer.alloc(4),go=8*1024,Rn,mr=go,Ye=0,lv=1,dv=2,hl=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=Ye,this.onerror=ov,this[sv]=void 0}static frame(e,n){let r,i=!1,s=2,o=!1;n.mask&&(r=n.maskBuffer||cv,n.generateMask?n.generateMask(r):(mr===go&&(Rn===void 0&&(Rn=Buffer.alloc(go)),rv(Rn,0,go),mr=0),r[0]=Rn[mr++],r[1]=Rn[mr++],r[2]=Rn[mr++],r[3]=Rn[mr++]),o=(r[0]|r[1]|r[2]|r[3])===0,s=6);let a;typeof e=="string"?(!n.mask||o)&&n[Ge]!==void 0?a=n[Ge]:(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?(_p(e,r,l,s,a),[l]):(_p(e,r,e,0,a),[l,e])):[l,e]}close(e,n,r,i){let s;if(e===void 0)s=iv;else{if(typeof e!="number"||!av(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={[Ge]:s.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ye?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):gr(e)?(i=e.size,s=!1):(e=Tn(e),i=e.length,s=Tn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};gr(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ye?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):gr(e)?(i=e.size,s=!1):(e=Tn(e),i=e.length,s=Tn.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:i,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};gr(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ye?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(t.frame(e,o),r)}send(e,n,r){let i=this._extensions[yp.extensionName],s=n.binary?2:1,o=n.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):gr(e)?(a=e.size,c=!1):(e=Tn(e),a=e.length,c=Tn.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={[Ge]:a,fin:n.fin,generateMask:this._generateMask,mask:n.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:o};gr(e)?this._state!==Ye?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ye?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,n,r,i){this._bufferedBytes+=r[Ge],this._state=dv,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(pl,this,a,i);return}this._bufferedBytes-=r[Ge];let o=Tn(s);n?this.dispatch(o,n,r,i):(this._state=Ye,this.sendFrame(t.frame(o,r),i),this.dequeue())}).catch(s=>{process.nextTick(uv,this,s,i)})}dispatch(e,n,r,i){if(!n){this.sendFrame(t.frame(e,r),i);return}let s=this._extensions[yp.extensionName];this._bufferedBytes+=r[Ge],this._state=lv,s.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");pl(this,c,i);return}this._bufferedBytes-=r[Ge],this._state=Ye,r.readOnly=!1,this.sendFrame(t.frame(a,r),i),this.dequeue()})}dequeue(){for(;this._state===Ye&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ge],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ge],this._queue.push(e)}sendFrame(e,n){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],n),this._socket.uncork()):this._socket.write(e[0],n)}};Ep.exports=hl;function pl(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 uv(t,e,n){pl(t,e,n),t.onerror(e)}});var xp=H((KO,Ap)=>{"use strict";var{kForOnEventAttribute:Ai,kListener:ml}=It(),Sp=Symbol("kCode"),vp=Symbol("kData"),Ip=Symbol("kError"),Tp=Symbol("kMessage"),Rp=Symbol("kReason"),wr=Symbol("kTarget"),kp=Symbol("kType"),bp=Symbol("kWasClean"),Rt=class{constructor(e){this[wr]=null,this[kp]=e}get target(){return this[wr]}get type(){return this[kp]}};Object.defineProperty(Rt.prototype,"target",{enumerable:!0});Object.defineProperty(Rt.prototype,"type",{enumerable:!0});var kn=class extends Rt{constructor(e,n={}){super(e),this[Sp]=n.code===void 0?0:n.code,this[Rp]=n.reason===void 0?"":n.reason,this[bp]=n.wasClean===void 0?!1:n.wasClean}get code(){return this[Sp]}get reason(){return this[Rp]}get wasClean(){return this[bp]}};Object.defineProperty(kn.prototype,"code",{enumerable:!0});Object.defineProperty(kn.prototype,"reason",{enumerable:!0});Object.defineProperty(kn.prototype,"wasClean",{enumerable:!0});var yr=class extends Rt{constructor(e,n={}){super(e),this[Ip]=n.error===void 0?null:n.error,this[Tp]=n.message===void 0?"":n.message}get error(){return this[Ip]}get message(){return this[Tp]}};Object.defineProperty(yr.prototype,"error",{enumerable:!0});Object.defineProperty(yr.prototype,"message",{enumerable:!0});var xi=class extends Rt{constructor(e,n={}){super(e),this[vp]=n.data===void 0?null:n.data}get data(){return this[vp]}};Object.defineProperty(xi.prototype,"data",{enumerable:!0});var fv={addEventListener(t,e,n={}){for(let i of this.listeners(t))if(!n[Ai]&&i[ml]===e&&!i[Ai])return;let r;if(t==="message")r=function(s,o){let a=new xi("message",{data:o?s:s.toString()});a[wr]=this,mo(e,this,a)};else if(t==="close")r=function(s,o){let a=new kn("close",{code:s,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[wr]=this,mo(e,this,a)};else if(t==="error")r=function(s){let o=new yr("error",{error:s,message:s.message});o[wr]=this,mo(e,this,o)};else if(t==="open")r=function(){let s=new Rt("open");s[wr]=this,mo(e,this,s)};else return;r[Ai]=!!n[Ai],r[ml]=e,n.once?this.once(t,r):this.on(t,r)},removeEventListener(t,e){for(let n of this.listeners(t))if(n[ml]===e&&!n[Ai]){this.removeListener(t,n);break}}};Ap.exports={CloseEvent:kn,ErrorEvent:yr,Event:Rt,EventTarget:fv,MessageEvent:xi};function mo(t,e,n){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,n):t.call(e,n)}});var wo=H((XO,Op)=>{"use strict";var{tokenChars:Oi}=pr();function ut(t,e,n){t[e]===void 0?t[e]=[n]:t[e].push(n)}function hv(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&&Oi[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 u=t.slice(c,d);l===44?(ut(e,u,n),n=Object.create(null)):o=u,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(d===-1&&Oi[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),ut(n,t.slice(c,d),!0),l===44&&(ut(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(Oi[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:r||(r=!0),i=!1}else if(s)if(Oi[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&&Oi[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 u=t.slice(c,d);r&&(u=u.replace(/\\/g,""),r=!1),ut(n,a,u),l===44&&(ut(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?ut(e,m,n):(a===void 0?ut(n,m,!0):r?ut(n,a,m.replace(/\\/g,"")):ut(n,a,m),ut(e,o,n)),e}function pv(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(", ")}Op.exports={format:pv,parse:hv}});var So=H((eP,Gp)=>{"use strict";var gv=j("events"),mv=j("https"),wv=j("http"),Dp=j("net"),yv=j("tls"),{randomBytes:_v,createHash:Ev}=j("crypto"),{Duplex:YO,Readable:QO}=j("stream"),{URL:wl}=j("url"),Zt=hr(),Sv=fl(),vv=gl(),{isBlob:Iv}=pr(),{BINARY_TYPES:Pp,CLOSE_TIMEOUT:Tv,EMPTY_BUFFER:yo,GUID:Rv,kForOnEventAttribute:yl,kListener:kv,kStatusCode:bv,kWebSocket:pe,NOOP:Np}=It(),{EventTarget:{addEventListener:Av,removeEventListener:xv}}=xp(),{format:Ov,parse:Pv}=wo(),{toBuffer:Cv}=ki(),Lp=Symbol("kAborted"),_l=[8,13],kt=["CONNECTING","OPEN","CLOSING","CLOSED"],Dv=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,q=class t extends gv{constructor(e,n,r){super(),this._binaryType=Pp[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=yo,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]),Fp(this,e,n,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Pp.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 Sv({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),s=new vv(e,this._extensions,r.generateMask);this._receiver=i,this._sender=s,this._socket=e,i[pe]=this,s[pe]=this,e[pe]=this,i.on("conclude",Fv),i.on("drain",Mv),i.on("error",Bv),i.on("message",Uv),i.on("ping",zv),i.on("pong",$v),s.onerror=Gv,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),n.length>0&&e.unshift(n),e.on("close",Up),e.on("data",Eo),e.on("end",zp),e.on("error",$p),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Zt.extensionName]&&this._extensions[Zt.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){Le(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())}),Bp(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){El(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.ping(e||yo,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){El(this,e,r);return}n===void 0&&(n=!this._isServer),this._sender.pong(e||yo,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){El(this,e,r);return}let i={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...n};this._extensions[Zt.extensionName]||(i.compress=!1),this._sender.send(e||yo,i,r)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){Le(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(q,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(q.prototype,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(q,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(q.prototype,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(q,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(q.prototype,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(q,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});Object.defineProperty(q.prototype,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(q.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(q.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[yl])return e[kv];return null},set(e){for(let n of this.listeners(t))if(n[yl]){this.removeListener(t,n);break}typeof e=="function"&&this.addEventListener(t,e,{[yl]:!0})}})});q.prototype.addEventListener=Av;q.prototype.removeEventListener=xv;Gp.exports=q;function Fp(t,e,n,r){let i={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Tv,protocolVersion:_l[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,!_l.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${_l.join(", ")})`);let s;if(e instanceof wl)s=e;else try{s=new wl(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;_o(t,g);return}let l=o?443:80,d=_v(16).toString("base64"),p=o?mv.request:wv.request,m=new Set,u;if(i.createConnection=i.createConnection||(o?Lv:Nv),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&&(u=new Zt({...i.perMessageDeflate,isServer:!1,maxPayload:i.maxPayload}),i.headers["Sec-WebSocket-Extensions"]=Ov({[Zt.extensionName]:u.offer()})),n.length){for(let g of n){if(typeof g!="string"||!Dv.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",()=>{Le(t,h,"Opening handshake has timed out")}),h.on("error",g=>{h===null||h[Lp]||(h=t._req=null,_o(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){Le(t,h,"Maximum redirects exceeded");return}h.abort();let v;try{v=new wl(w,e)}catch{let y=new SyntaxError(`Invalid URL: ${w}`);_o(t,y);return}Fp(t,v,n,r)}else t.emit("unexpected-response",h,g)||Le(t,h,`Unexpected server response: ${g.statusCode}`)}),h.on("upgrade",(g,w,S)=>{if(t.emit("upgrade",g),t.readyState!==q.CONNECTING)return;h=t._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Le(t,w,"Invalid Upgrade header");return}let f=Ev("sha1").update(d+Rv).digest("base64");if(g.headers["sec-websocket-accept"]!==f){Le(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){Le(t,w,E);return}y&&(t._protocol=y);let T=g.headers["sec-websocket-extensions"];if(T!==void 0){if(!u){Le(t,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let R;try{R=Pv(T)}catch{Le(t,w,"Invalid Sec-WebSocket-Extensions header");return}let D=Object.keys(R);if(D.length!==1||D[0]!==Zt.extensionName){Le(t,w,"Server indicated an extension that was not requested");return}try{u.accept(R[Zt.extensionName])}catch{Le(t,w,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[Zt.extensionName]=u}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 _o(t,e){t._readyState=q.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function Nv(t){return t.path=t.socketPath,Dp.connect(t)}function Lv(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=Dp.isIP(t.host)?"":t.host),yv.connect(t)}function Le(t,e,n){t._readyState=q.CLOSING;let r=new Error(n);Error.captureStackTrace(r,Le),e.setHeader?(e[Lp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(_o,t,r)):(e.destroy(r),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function El(t,e,n){if(e){let r=Iv(e)?e.size:Cv(e).length;t._socket?t._sender._bufferedBytes+=r:t._bufferedAmount+=r}if(n){let r=new Error(`WebSocket is not open: readyState ${t.readyState} (${kt[t.readyState]})`);process.nextTick(n,r)}}function Fv(t,e){let n=this[pe];n._closeFrameReceived=!0,n._closeMessage=e,n._closeCode=t,n._socket[pe]!==void 0&&(n._socket.removeListener("data",Eo),process.nextTick(Mp,n._socket),t===1005?n.close():n.close(t,e))}function Mv(){let t=this[pe];t.isPaused||t._socket.resume()}function Bv(t){let e=this[pe];e._socket[pe]!==void 0&&(e._socket.removeListener("data",Eo),process.nextTick(Mp,e._socket),e.close(t[bv])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function Cp(){this[pe].emitClose()}function Uv(t,e){this[pe].emit("message",t,e)}function zv(t){let e=this[pe];e._autoPong&&e.pong(t,!this._isServer,Np),e.emit("ping",t)}function $v(t){this[pe].emit("pong",t)}function Mp(t){t.resume()}function Gv(t){let e=this[pe];e.readyState!==q.CLOSED&&(e.readyState===q.OPEN&&(e._readyState=q.CLOSING,Bp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function Bp(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function Up(){let t=this[pe];if(this.removeListener("close",Up),this.removeListener("data",Eo),this.removeListener("end",zp),t._readyState=q.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[pe]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",Cp),t._receiver.on("finish",Cp))}function Eo(t){this[pe]._receiver.write(t)||this.pause()}function zp(){let t=this[pe];t._readyState=q.CLOSING,t._receiver.end(),this.end()}function $p(){let t=this[pe];this.removeListener("error",$p),this.on("error",Np),t&&(t._readyState=q.CLOSING,this.destroy())}});var qp=H((nP,Wp)=>{"use strict";var tP=So(),{Duplex:Hv}=j("stream");function Hp(t){t.emit("close")}function jv(){!this.destroyed&&this._writableState.finished&&this.destroy()}function jp(t){this.removeListener("error",jp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function Wv(t,e){let n=!0,r=new Hv({...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(Hp,r);return}let o=!1;t.once("error",function(c){o=!0,s(c)}),t.once("close",function(){o||s(i),process.nextTick(Hp,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",jv),r.on("error",jp),r}Wp.exports=Wv});var Sl=H((rP,Jp)=>{"use strict";var{tokenChars:qv}=pr();function Jv(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&&qv[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}Jp.exports={parse:Jv}});var eg=H((sP,Qp)=>{"use strict";var Vv=j("events"),vo=j("http"),{Duplex:iP}=j("stream"),{createHash:Zv}=j("crypto"),Vp=wo(),bn=hr(),Kv=Sl(),Xv=So(),{CLOSE_TIMEOUT:Yv,GUID:Qv,kWebSocket:eI}=It(),tI=/^[+/0-9A-Za-z]{22}==$/,Zp=0,Kp=1,Yp=2,vl=class extends Vv{constructor(e,n){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Yv,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Xv,...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=vo.createServer((r,i)=>{let s=vo.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=nI(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=Zp}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===Yp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Pi,this);return}if(e&&this.once("close",e),this._state!==Kp)if(this._state=Kp,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(Pi,this):process.nextTick(Pi,this);else{let n=this._server;this._removeListeners(),this._removeListeners=this._server=null,n.close(()=>{Pi(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",Xp);let s=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){An(this,e,n,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){An(this,e,n,400,"Invalid Upgrade header");return}if(s===void 0||!tI.test(s)){An(this,e,n,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){An(this,e,n,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Ci(n,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Kv.parse(c)}catch{An(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 bn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let u=Vp.parse(d);u[bn.extensionName]&&(m.accept(u[bn.extensionName]),p[bn.extensionName]=m)}catch{An(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,(u,h,g,w)=>{if(!u)return Ci(n,h||401,g,w);this.completeUpgrade(p,s,l,e,n,r,i)});return}if(!this.options.verifyClient(m))return Ci(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[eI])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Zp)return Ci(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Zv("sha1").update(n+Qv).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[bn.extensionName]){let p=e[bn.extensionName].params,m=Vp.format({[bn.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,i),s.write(l.concat(`\r
15
15
  `).join(`\r
16
- `)),s.removeListener("error",Xp),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(Pi,this)})),a(d,i)}};Qp.exports=vl;function nI(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 Pi(t){t._state=Yp,t.emit("close")}function Xp(){this.destroy()}function Ci(t,e,n,r){n=n||Io.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} ${Io.STATUS_CODES[e]}\r
16
+ `)),s.removeListener("error",Xp),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(Pi,this)})),a(d,i)}};Qp.exports=vl;function nI(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 Pi(t){t._state=Yp,t.emit("close")}function Xp(){this.destroy()}function Ci(t,e,n,r){n=n||vo.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} ${vo.STATUS_CODES[e]}\r
17
17
  `+Object.keys(r).map(i=>`${i}: ${r[i]}`).join(`\r
18
18
  `)+`\r
19
19
  \r
20
- `+n)}function An(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,An),t.emit("wsClientError",o,n,e)}else Ci(n,r,i,s)}});import{existsSync as kI,openSync as bI}from"node:fs";import{mkdir as AI}from"node:fs/promises";import{dirname as xI}from"node:path";import{fileURLToPath as OI}from"node:url";function CI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function kl(t=L()){return kI(t.libEntry)?t.libEntry:OI(new URL("../index.ts",import.meta.url))}async function hg(t={}){let e=t.paths??L(),n=t.entryOverride??kl(e),r=CI(e,process.env.COZE_BRIDGE_LOG_MODE);await AI(xI(r),{recursive:!0});let i=bI(r,"a"),o=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],a=Fe(process.execPath,o,{detached:!0,stdio:["ignore",i,i],env:{...process.env,[Li]:"1"}});if(a.unref(),typeof a.pid!="number")throw new Error("failed to spawn daemon (no pid)");return PI.info("daemon spawned",{pid:a.pid,entry:n}),{pid:a.pid,entry:n}}var PI,Li,xo=ve(()=>{"use strict";gt();F();re();PI=b("spawn-daemon"),Li="COZE_BRIDGE_DAEMON"});import{spawn as mT}from"node:child_process";import{mkdir as wT,unlink as yT,writeFile as _T}from"node:fs/promises";import{dirname as ET,join as ST}from"node:path";function vr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function vT(t){if(!t)return"";let e=Object.entries(t).map(([n,r])=>` <key>${vr(n)}</key>
21
- <string>${vr(r)}</string>`).join(`
20
+ `+n)}function An(t,e,n,r,i,s){if(t.listenerCount("wsClientError")){let o=new Error(i);Error.captureStackTrace(o,An),t.emit("wsClientError",o,n,e)}else Ci(n,r,i,s)}});import{existsSync as kI,openSync as bI}from"node:fs";import{mkdir as AI}from"node:fs/promises";import{dirname as xI}from"node:path";import{fileURLToPath as OI}from"node:url";function CI(t,e){return e==="legacy"?t.logFile:t.daemonStdioLog}function kl(t=L()){return kI(t.libEntry)?t.libEntry:OI(new URL("../index.ts",import.meta.url))}async function hg(t={}){let e=t.paths??L(),n=t.entryOverride??kl(e),r=CI(e,process.env.COZE_BRIDGE_LOG_MODE);await AI(xI(r),{recursive:!0});let i=bI(r,"a"),o=n.endsWith(".ts")?["--import","tsx/esm",n,"--daemon"]:[n,"--daemon"],a=Fe(process.execPath,o,{detached:!0,stdio:["ignore",i,i],env:{...process.env,[Li]:"1"}});if(a.unref(),typeof a.pid!="number")throw new Error("failed to spawn daemon (no pid)");return PI.info("daemon spawned",{pid:a.pid,entry:n}),{pid:a.pid,entry:n}}var PI,Li,Ao=ve(()=>{"use strict";gt();F();re();PI=b("spawn-daemon"),Li="COZE_BRIDGE_DAEMON"});import{spawn as mT}from"node:child_process";import{mkdir as wT,unlink as yT,writeFile as _T}from"node:fs/promises";import{dirname as ET,join as ST}from"node:path";function Sr(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function vT(t){if(!t)return"";let e=Object.entries(t).map(([n,r])=>` <key>${Sr(n)}</key>
21
+ <string>${Sr(r)}</string>`).join(`
22
22
  `);return e?`
23
23
  <key>EnvironmentVariables</key>
24
24
  <dict>
25
25
  ${e}
26
- </dict>`:""}function IT(t,e){return new Promise((n,r)=>{let i=mT(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 Sr,Fi,Fo,Pl,Ag=ve(()=>{"use strict";F();Sr=b("supervisor.launchd"),Fi="ai.coze.bridge",Fo=IT,Pl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
26
+ </dict>`:""}function IT(t,e){return new Promise((n,r)=>{let i=mT(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 Er,Fi,Lo,Pl,Ag=ve(()=>{"use strict";F();Er=b("supervisor.launchd"),Fi="ai.coze.bridge",Lo=IT,Pl={platform:"darwin",renderConfig(t){return`<?xml version="1.0" encoding="UTF-8"?>
27
27
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
28
28
  <plist version="1.0">
29
29
  <dict>
@@ -31,8 +31,8 @@ ${e}
31
31
  <string>${Fi}</string>
32
32
  <key>ProgramArguments</key>
33
33
  <array>
34
- <string>${vr(t.nodeBin)}</string>
35
- <string>${vr(t.entry)}</string>
34
+ <string>${Sr(t.nodeBin)}</string>
35
+ <string>${Sr(t.entry)}</string>
36
36
  <string>--daemon</string>
37
37
  </array>
38
38
  <key>RunAtLoad</key>
@@ -42,13 +42,13 @@ ${e}
42
42
  <key>ThrottleInterval</key>
43
43
  <integer>10</integer>
44
44
  <key>StandardOutPath</key>
45
- <string>${vr(t.logFile)}</string>
45
+ <string>${Sr(t.logFile)}</string>
46
46
  <key>StandardErrorPath</key>
47
- <string>${vr(t.logFile)}</string>${vT(t.env)}
47
+ <string>${Sr(t.logFile)}</string>${vT(t.env)}
48
48
  </dict>
49
49
  </plist>
50
- `},configPath(t){return ST(t.homeDir,"Library","LaunchAgents",`${Fi}.plist`)},async install(t,e){let n=e?.activate!==!1,r=this.configPath(t);if(await wT(ET(r),{recursive:!0}),await _T(r,this.renderConfig(t),"utf8"),Sr.info("plist written",{plistPath:r,activate:n}),!n)return;await Fo("launchctl",["unload","-w",r]).catch(s=>Sr.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(s)})),await Fo("launchctl",["load","-w",r]),Sr.info("launchd job loaded",{label:Fi});let i=process.getuid?.()??0;await Fo("launchctl",["kickstart","-k",`gui/${i}/${Fi}`]),Sr.info("launchd job kickstarted",{label:Fi,uid:i})},async uninstall(t){let e=this.configPath(t);await Fo("launchctl",["unload","-w",e]).catch(n=>Sr.warn("launchctl unload failed (ignored)",{err:String(n)})),await yT(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Sr.info("launchd job removed",{plistPath:e})}}});import{spawn as TT}from"node:child_process";import{mkdir as RT,unlink as kT,writeFile as bT}from"node:fs/promises";import{dirname as AT,join as xg}from"node:path";function Bo(t,e){return t.isRoot?e:["--user",...e]}function OT(t){return t?Object.entries(t).map(([e,n])=>{let r=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${r}"`}).join(`
51
- `):""}function Uo(t,e){return new Promise((n,r)=>{let i=TT(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 Mo,Ir,xT,Cl,Og=ve(()=>{"use strict";F();Mo=b("supervisor.systemd"),Ir="coze-bridge.service",xT="/etc/systemd/system";Cl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
50
+ `},configPath(t){return ST(t.homeDir,"Library","LaunchAgents",`${Fi}.plist`)},async install(t,e){let n=e?.activate!==!1,r=this.configPath(t);if(await wT(ET(r),{recursive:!0}),await _T(r,this.renderConfig(t),"utf8"),Er.info("plist written",{plistPath:r,activate:n}),!n)return;await Lo("launchctl",["unload","-w",r]).catch(s=>Er.info("launchctl unload before load (ignored, likely not loaded yet)",{err:String(s)})),await Lo("launchctl",["load","-w",r]),Er.info("launchd job loaded",{label:Fi});let i=process.getuid?.()??0;await Lo("launchctl",["kickstart","-k",`gui/${i}/${Fi}`]),Er.info("launchd job kickstarted",{label:Fi,uid:i})},async uninstall(t){let e=this.configPath(t);await Lo("launchctl",["unload","-w",e]).catch(n=>Er.warn("launchctl unload failed (ignored)",{err:String(n)})),await yT(e).catch(n=>{if(n.code!=="ENOENT")throw n}),Er.info("launchd job removed",{plistPath:e})}}});import{spawn as TT}from"node:child_process";import{mkdir as RT,unlink as kT,writeFile as bT}from"node:fs/promises";import{dirname as AT,join as xg}from"node:path";function Mo(t,e){return t.isRoot?e:["--user",...e]}function OT(t){return t?Object.entries(t).map(([e,n])=>{let r=n.replace(/\\/g,"\\\\").replace(/"/g,'\\"');return`Environment="${e}=${r}"`}).join(`
51
+ `):""}function Bo(t,e){return new Promise((n,r)=>{let i=TT(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 Fo,vr,xT,Cl,Og=ve(()=>{"use strict";F();Fo=b("supervisor.systemd"),vr="coze-bridge.service",xT="/etc/systemd/system";Cl={platform:"linux",renderConfig(t){let e=t.isRoot?"multi-user.target":"default.target";return`[Unit]
52
52
  Description=Coze Bridge daemon
53
53
  After=network.target
54
54
 
@@ -62,7 +62,7 @@ StandardError=append:${t.logFile}
62
62
  ${OT(t.env)}
63
63
  [Install]
64
64
  WantedBy=${e}
65
- `},configPath(t){return t.isRoot?xg(xT,Ir):xg(t.homeDir,".config","systemd","user",Ir)},async install(t,e){let n=e?.activate!==!1,r=this.configPath(t),i=t.isRoot?"system":"user";await RT(AT(r),{recursive:!0}),await bT(r,this.renderConfig(t),"utf8"),Mo.info("systemd unit written",{unitPath:r,mode:i,activate:n}),await Uo("systemctl",Bo(t,["daemon-reload"])),await Uo("systemctl",Bo(t,n?["enable","--now",Ir]:["enable",Ir])),Mo.info("systemd unit enabled",{unitName:Ir,mode:i,activate:n})},async uninstall(t){let e=this.configPath(t);await Uo("systemctl",Bo(t,["disable","--now",Ir])).catch(n=>Mo.warn("systemctl disable failed (ignored)",{err:String(n)})),await kT(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Uo("systemctl",Bo(t,["daemon-reload"])).catch(()=>{}),Mo.info("systemd unit removed",{unitPath:e})}}});import{spawn as PT}from"node:child_process";import{join as CT}from"node:path";function Pg(t,e){return new Promise((n,r)=>{let i=PT(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 Dl,zo,Nl,Cg=ve(()=>{"use strict";F();Dl=b("supervisor.taskscheduler"),zo="CozeBridge",Nl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
65
+ `},configPath(t){return t.isRoot?xg(xT,vr):xg(t.homeDir,".config","systemd","user",vr)},async install(t,e){let n=e?.activate!==!1,r=this.configPath(t),i=t.isRoot?"system":"user";await RT(AT(r),{recursive:!0}),await bT(r,this.renderConfig(t),"utf8"),Fo.info("systemd unit written",{unitPath:r,mode:i,activate:n}),await Bo("systemctl",Mo(t,["daemon-reload"])),await Bo("systemctl",Mo(t,n?["enable","--now",vr]:["enable",vr])),Fo.info("systemd unit enabled",{unitName:vr,mode:i,activate:n})},async uninstall(t){let e=this.configPath(t);await Bo("systemctl",Mo(t,["disable","--now",vr])).catch(n=>Fo.warn("systemctl disable failed (ignored)",{err:String(n)})),await kT(e).catch(n=>{if(n.code!=="ENOENT")throw n}),await Bo("systemctl",Mo(t,["daemon-reload"])).catch(()=>{}),Fo.info("systemd unit removed",{unitPath:e})}}});import{spawn as PT}from"node:child_process";import{join as CT}from"node:path";function Pg(t,e){return new Promise((n,r)=>{let i=PT(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 Dl,Uo,Nl,Cg=ve(()=>{"use strict";F();Dl=b("supervisor.taskscheduler"),Uo="CozeBridge",Nl={platform:"win32",renderConfig(t){return`<?xml version="1.0" encoding="UTF-16"?>
66
66
  <Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
67
67
  <RegistrationInfo>
68
68
  <Description>Coze Bridge daemon</Description>
@@ -86,42 +86,42 @@ WantedBy=${e}
86
86
  </Exec>
87
87
  </Actions>
88
88
  </Task>
89
- `},configPath(t){return CT(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await Pg("schtasks",["/Create","/SC","ONLOGON","/TN",zo,"/TR",n,"/RU",t.userName,"/F"]),Dl.info("task scheduler entry created",{task:zo,logFile:t.logFile})},async uninstall(t){await Pg("schtasks",["/Delete","/TN",zo,"/F"]).catch(e=>Dl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Dl.info("task scheduler entry removed",{task:zo})}}});var Dg={};Ui(Dg,{buildContext:()=>BT,getSupervisor:()=>LT,launchdSupervisor:()=>Pl,systemdSupervisor:()=>Cl,taskSchedulerSupervisor:()=>Nl});import{homedir as DT,userInfo as NT}from"node:os";function LT(t=process.platform){switch(t){case"darwin":return Pl;case"linux":return Cl;case"win32":return Nl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function MT(){let t={};for(let e of FT){let n=process.env[e];n&&(t[e]=n)}return t}function BT(){let t=L();return{nodeBin:process.execPath,entry:kl(t),logFile:t.logFile,homeDir:DT(),userName:NT().username,isRoot:process.getuid?.()===0,env:MT()}}var FT,Ng=ve(()=>{"use strict";re();xo();Ag();Og();Cg();FT=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});F();nn();var Ql=b("acp-installer-warmup"),Im=["claude-code","codex"];async function ed(t={}){let e=t.ensure??tn,r=(await Promise.allSettled(Im.map(async i=>{let s=await e(i);Ql.info("acp wrapper warmup ok",{framework:i,path:s})}))).filter(i=>i.status==="rejected");r.length>0&&Ql.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))})}At();F();import{readdir as Lm}from"node:fs/promises";import{mkdir as od,writeFile as ad}from"node:fs/promises";import{join as Ko}from"node:path";var Nm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Mn(t,e,n){await od(t,{recursive:!0});let r=Nm[e],i=Ko(t,r);return await ad(i,n??"","utf8"),i}async function cd(t){let e=Ko(t,".claude");await od(e,{recursive:!0});let n=Ko(e,"settings.local.json"),r=JSON.stringify({permissions:{defaultMode:"bypassPermissions"}},null,2);return await ad(n,r,"utf8"),n}var Oe=b("agent-detail-sync"),Fm=6e4,Mm=5*6e4,Yi=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,r;try{r=await Lm(n)}catch(i){Oe.info("agents dir not found, skip detail sync",{root:n,err:String(i)});return}Oe.info("starting detail sync",{reason:e,count:r.length}),await Promise.allSettled(r.map(async i=>{let s=await me(i,this.opts.paths).catch(()=>null);if(s){if(s.disconnectedAt){Oe.debug("detail sync: skip disconnected agent",{agentId:i});return}try{await this.syncOne(i,s)}catch(o){Oe.warn("detail sync failed for agent, skipping",{agentId:i,err:String(o)})}}})),Oe.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){Oe.info("retrying pending detail syncs",{count:n.length});for(let r of n)try{await this.syncOne(r)}catch(i){Oe.debug("detail sync retry still failing, will try again",{agentId:r,err:String(i)})}}}async syncOne(e,n){let r=n??await me(e,this.opts.paths);if(!r){Oe.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){Oe.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,Mm):Fm;this.retryQueue.set(e,{dueAt:Date.now()+l,currentDelay:l});return}if(i.agentId&&i.agentId!==e){Oe.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&&Oe.info("detail.deployType",{agentId:e,deployType:i.deployType}),!s){Oe.debug("detail sync: no diff",{agentId:e});return}await Ae(r,this.opts.paths),Oe.info("detail sync: config updated",{agentId:e,identityChanged:o,agentName:r.agentName}),o&&(await Mn(r.workspace,r.framework,r.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Rf=ht($d(),1);import{lstat as uc,mkdir as fc,readFile as Sf,readdir as d_,rm as u_,stat as f_,writeFile as hc}from"node:fs/promises";import{dirname as h_,join as at,normalize as p_,relative as mc,resolve as pc,sep as vf}from"node:path";import{Readable as If}from"node:stream";import{pipeline as Tf}from"node:stream/promises";import sw from"events";import xe from"fs";import{EventEmitter as Za}from"node:events";import vu from"node:stream";import{StringDecoder as ow}from"node:string_decoder";import Ru from"node:path";import Zn from"node:fs";import{dirname as _w,parse as Ew}from"path";import{EventEmitter as Aw}from"events";import Oa from"assert";import{Buffer as pn}from"buffer";import*as qd from"zlib";import xw from"zlib";import{posix as Gn}from"node:path";import{basename as ny}from"node:path";import Os from"fs";import it from"fs";import Qd from"path";import{win32 as hy}from"node:path";import ou from"path";import zu from"node:fs";import Oy from"node:assert";import{randomBytes as $u}from"node:crypto";import B from"node:fs";import se from"node:path";import Gu from"fs";import Us from"node:fs";import Qr from"node:path";import De from"node:fs";import My from"node:fs/promises";import Ds from"node:path";import{join as Qu}from"node:path";import Ce from"node:fs";import nf from"node:path";var rw=Object.defineProperty,iw=(t,e)=>{for(var n in e)rw(t,n,{get:e[n],enumerable:!0})},Gd=typeof process=="object"&&process?process:{stdout:null,stderr:null},aw=t=>!!t&&typeof t=="object"&&(t instanceof wn||t instanceof vu||cw(t)||lw(t)),cw=t=>!!t&&typeof t=="object"&&t instanceof Za&&typeof t.pipe=="function"&&t.pipe!==vu.Writable.prototype.pipe,lw=t=>!!t&&typeof t=="object"&&t instanceof Za&&typeof t.write=="function"&&typeof t.end=="function",mt=Symbol("EOF"),wt=Symbol("maybeEmitEnd"),Ot=Symbol("emittedEnd"),rs=Symbol("emittingEnd"),Fr=Symbol("emittedError"),is=Symbol("closed"),Hd=Symbol("read"),ss=Symbol("flush"),jd=Symbol("flushChunk"),je=Symbol("encoding"),$n=Symbol("decoder"),de=Symbol("flowing"),Mr=Symbol("paused"),qn=Symbol("resume"),ue=Symbol("buffer"),Re=Symbol("pipes"),fe=Symbol("bufferLength"),na=Symbol("bufferPush"),os=Symbol("bufferShift"),Ie=Symbol("objectMode"),Q=Symbol("destroyed"),ra=Symbol("error"),ia=Symbol("emitData"),Wd=Symbol("emitEnd"),sa=Symbol("emitEnd2"),et=Symbol("async"),oa=Symbol("abort"),as=Symbol("aborted"),Br=Symbol("signal"),sn=Symbol("dataListeners"),Pe=Symbol("discarded"),Ur=t=>Promise.resolve().then(t),dw=t=>t(),uw=t=>t==="end"||t==="finish"||t==="prefinish",fw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,hw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Iu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[qn](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},pw=class extends Iu{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)}},gw=t=>!!t.objectMode,mw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",wn=class extends Za{[de]=!1;[Mr]=!1;[Re]=[];[ue]=[];[Ie];[je];[et];[$n];[mt]=!1;[Ot]=!1;[rs]=!1;[is]=!1;[Fr]=null;[fe]=0;[Q]=!1;[Br];[as]=!1;[sn]=0;[Pe]=!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");gw(e)?(this[Ie]=!0,this[je]=null):mw(e)?(this[je]=e.encoding,this[Ie]=!1):(this[Ie]=!1,this[je]=null),this[et]=!!e.async,this[$n]=this[je]?new ow(this[je]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[ue]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Re]});let{signal:n}=e;n&&(this[Br]=n,n.aborted?this[oa]():n.addEventListener("abort",()=>this[oa]()))}get bufferLength(){return this[fe]}get encoding(){return this[je]}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[Ie]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[et]}set async(t){this[et]=this[et]||!!t}[oa](){this[as]=!0,this.emit("abort",this[Br]?.reason),this.destroy(this[Br]?.reason)}get aborted(){return this[as]}set aborted(t){}write(t,e,n){if(this[as])return!1;if(this[mt])throw new Error("write after end");if(this[Q])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let r=this[et]?Ur:dw;if(!this[Ie]&&!Buffer.isBuffer(t)){if(hw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ie]?(this[de]&&this[fe]!==0&&this[ss](!0),this[de]?this.emit("data",t):this[na](t),this[fe]!==0&&this.emit("readable"),n&&r(n),this[de]):t.length?(typeof t=="string"&&!(e===this[je]&&!this[$n]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[je]&&(t=this[$n].write(t)),this[de]&&this[fe]!==0&&this[ss](!0),this[de]?this.emit("data",t):this[na](t),this[fe]!==0&&this.emit("readable"),n&&r(n),this[de]):(this[fe]!==0&&this.emit("readable"),n&&r(n),this[de])}read(t){if(this[Q])return null;if(this[Pe]=!1,this[fe]===0||t===0||t&&t>this[fe])return this[wt](),null;this[Ie]&&(t=null),this[ue].length>1&&!this[Ie]&&(this[ue]=[this[je]?this[ue].join(""):Buffer.concat(this[ue],this[fe])]);let e=this[Hd](t||null,this[ue][0]);return this[wt](),e}[Hd](t,e){if(this[Ie])this[os]();else{let n=e;t===n.length||t===null?this[os]():typeof n=="string"?(this[ue][0]=n.slice(t),e=n.slice(0,t),this[fe]-=t):(this[ue][0]=n.subarray(t),e=n.subarray(0,t),this[fe]-=t)}return this.emit("data",e),!this[ue].length&&!this[mt]&&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[mt]=!0,this.writable=!1,(this[de]||!this[Mr])&&this[wt](),this}[qn](){this[Q]||(!this[sn]&&!this[Re].length&&(this[Pe]=!0),this[Mr]=!1,this[de]=!0,this.emit("resume"),this[ue].length?this[ss]():this[mt]?this[wt]():this.emit("drain"))}resume(){return this[qn]()}pause(){this[de]=!1,this[Mr]=!0,this[Pe]=!1}get destroyed(){return this[Q]}get flowing(){return this[de]}get paused(){return this[Mr]}[na](t){this[Ie]?this[fe]+=1:this[fe]+=t.length,this[ue].push(t)}[os](){return this[Ie]?this[fe]-=1:this[fe]-=this[ue][0].length,this[ue].shift()}[ss](t=!1){do;while(this[jd](this[os]())&&this[ue].length);!t&&!this[ue].length&&!this[mt]&&this.emit("drain")}[jd](t){return this.emit("data",t),this[de]}pipe(t,e){if(this[Q])return t;this[Pe]=!1;let n=this[Ot];return e=e||{},t===Gd.stdout||t===Gd.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[Re].push(e.proxyErrors?new pw(this,t,e):new Iu(this,t,e)),this[et]?Ur(()=>this[qn]()):this[qn]()),t}unpipe(t){let e=this[Re].find(n=>n.dest===t);e&&(this[Re].length===1?(this[de]&&this[sn]===0&&(this[de]=!1),this[Re]=[]):this[Re].splice(this[Re].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[Pe]=!1,this[sn]++,!this[Re].length&&!this[de]&&this[qn]();else if(t==="readable"&&this[fe]!==0)super.emit("readable");else if(uw(t)&&this[Ot])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Fr]){let r=e;this[et]?Ur(()=>r.call(this,this[Fr])):r.call(this,this[Fr])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[sn]=this.listeners("data").length,this[sn]===0&&!this[Pe]&&!this[Re].length&&(this[de]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[sn]=0,!this[Pe]&&!this[Re].length&&(this[de]=!1)),e}get emittedEnd(){return this[Ot]}[wt](){!this[rs]&&!this[Ot]&&!this[Q]&&this[ue].length===0&&this[mt]&&(this[rs]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[is]&&this.emit("close"),this[rs]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Q&&this[Q])return!1;if(t==="data")return!this[Ie]&&!n?!1:this[et]?(Ur(()=>this[ia](n)),!0):this[ia](n);if(t==="end")return this[Wd]();if(t==="close"){if(this[is]=!0,!this[Ot]&&!this[Q])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Fr]=n,super.emit(ra,n);let i=!this[Br]||this.listeners("error").length?super.emit("error",n):!1;return this[wt](),i}else if(t==="resume"){let i=super.emit("resume");return this[wt](),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[wt](),r}[ia](t){for(let n of this[Re])n.dest.write(t)===!1&&this.pause();let e=this[Pe]?!1:super.emit("data",t);return this[wt](),e}[Wd](){return this[Ot]?!1:(this[Ot]=!0,this.readable=!1,this[et]?(Ur(()=>this[sa]()),!0):this[sa]())}[sa](){if(this[$n]){let e=this[$n].end();if(e){for(let n of this[Re])n.dest.write(e);this[Pe]||super.emit("data",e)}}for(let e of this[Re])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ie]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Ie]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Ie])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[je]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Q,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[Pe]=!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[mt])return e();let r,i,s=l=>{this.off("data",o),this.off("end",a),this.off(Q,c),e(),i(l)},o=l=>{this.off("error",s),this.off("end",a),this.off(Q,c),this.pause(),r({value:l,done:!!this[mt]})},a=()=>{this.off("error",s),this.off("data",o),this.off(Q,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(Q,c),this.once("error",s),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[Pe]=!1;let t=!1,e=()=>(this.pause(),this.off(ra,e),this.off(Q,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(ra,e),this.once(Q,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Q])return t?this.emit("error",t):this.emit(Q),this;this[Q]=!0,this[Pe]=!0,this[ue].length=0,this[fe]=0;let e=this;return typeof e.close=="function"&&!this[is]&&e.close(),t?this.emit("error",t):this.emit(Q),this}static get isStream(){return aw}},ww=xe.writev,zt=Symbol("_autoClose"),Ve=Symbol("_close"),zr=Symbol("_ended"),$=Symbol("_fd"),aa=Symbol("_finished"),St=Symbol("_flags"),ca=Symbol("_flush"),Aa=Symbol("_handleChunk"),xa=Symbol("_makeBuf"),Xr=Symbol("_mode"),cs=Symbol("_needDrain"),Xn=Symbol("_onerror"),Yn=Symbol("_onopen"),la=Symbol("_onread"),Jn=Symbol("_onwrite"),$t=Symbol("_open"),Je=Symbol("_path"),Lt=Symbol("_pos"),nt=Symbol("_queue"),Vn=Symbol("_read"),da=Symbol("_readSize"),Et=Symbol("_reading"),$r=Symbol("_remain"),ua=Symbol("_size"),ys=Symbol("_write"),on=Symbol("_writing"),_s=Symbol("_defaultFlag"),hn=Symbol("_errored"),Ka=class extends wn{[hn]=!1;[$];[Je];[da];[Et]=!1;[ua];[$r];[zt];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[hn]=!1,this[$]=typeof e.fd=="number"?e.fd:void 0,this[Je]=t,this[da]=e.readSize||16*1024*1024,this[Et]=!1,this[ua]=typeof e.size=="number"?e.size:1/0,this[$r]=this[ua],this[zt]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[$]=="number"?this[Vn]():this[$t]()}get fd(){return this[$]}get path(){return this[Je]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[$t](){xe.open(this[Je],"r",(t,e)=>this[Yn](t,e))}[Yn](t,e){t?this[Xn](t):(this[$]=e,this.emit("open",e),this[Vn]())}[xa](){return Buffer.allocUnsafe(Math.min(this[da],this[$r]))}[Vn](){if(!this[Et]){this[Et]=!0;let t=this[xa]();if(t.length===0)return process.nextTick(()=>this[la](null,0,t));xe.read(this[$],t,0,t.length,null,(e,n,r)=>this[la](e,n,r))}}[la](t,e,n){this[Et]=!1,t?this[Xn](t):this[Aa](e,n)&&this[Vn]()}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Xn](t){this[Et]=!0,this[Ve](),this.emit("error",t)}[Aa](t,e){let n=!1;return this[$r]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[$r]<=0)&&(n=!1,this[Ve](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[$]=="number"&&this[Vn](),!1;case"error":return this[hn]?!1:(this[hn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},yw=class extends Ka{[$t](){let t=!0;try{this[Yn](null,xe.openSync(this[Je],"r")),t=!1}finally{t&&this[Ve]()}}[Vn](){let t=!0;try{if(!this[Et]){this[Et]=!0;do{let e=this[xa](),n=e.length===0?0:xe.readSync(this[$],e,0,e.length,null);if(!this[Aa](n,e))break}while(!0);this[Et]=!1}t=!1}finally{t&&this[Ve]()}}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.closeSync(t),this.emit("close")}}},Ns=class extends sw{readable=!1;writable=!0;[hn]=!1;[on]=!1;[zr]=!1;[nt]=[];[cs]=!1;[Je];[Xr];[zt];[$];[_s];[St];[aa]=!1;[Lt];constructor(t,e){e=e||{},super(e),this[Je]=t,this[$]=typeof e.fd=="number"?e.fd:void 0,this[Xr]=e.mode===void 0?438:e.mode,this[Lt]=typeof e.start=="number"?e.start:void 0,this[zt]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Lt]!==void 0?"r+":"w";this[_s]=e.flags===void 0,this[St]=e.flags===void 0?n:e.flags,this[$]===void 0&&this[$t]()}emit(t,...e){if(t==="error"){if(this[hn])return!1;this[hn]=!0}return super.emit(t,...e)}get fd(){return this[$]}get path(){return this[Je]}[Xn](t){this[Ve](),this[on]=!0,this.emit("error",t)}[$t](){xe.open(this[Je],this[St],this[Xr],(t,e)=>this[Yn](t,e))}[Yn](t,e){this[_s]&&this[St]==="r+"&&t&&t.code==="ENOENT"?(this[St]="w",this[$t]()):t?this[Xn](t):(this[$]=e,this.emit("open",e),this[on]||this[ca]())}end(t,e){return t&&this.write(t,e),this[zr]=!0,!this[on]&&!this[nt].length&&typeof this[$]=="number"&&this[Jn](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[zr]?(this.emit("error",new Error("write() after end()")),!1):this[$]===void 0||this[on]||this[nt].length?(this[nt].push(t),this[cs]=!0,!1):(this[on]=!0,this[ys](t),!0)}[ys](t){xe.write(this[$],t,0,t.length,this[Lt],(e,n)=>this[Jn](e,n))}[Jn](t,e){t?this[Xn](t):(this[Lt]!==void 0&&typeof e=="number"&&(this[Lt]+=e),this[nt].length?this[ca]():(this[on]=!1,this[zr]&&!this[aa]?(this[aa]=!0,this[Ve](),this.emit("finish")):this[cs]&&(this[cs]=!1,this.emit("drain"))))}[ca](){if(this[nt].length===0)this[zr]&&this[Jn](null,0);else if(this[nt].length===1)this[ys](this[nt].pop());else{let t=this[nt];this[nt]=[],ww(this[$],t,this[Lt],(e,n)=>this[Jn](e,n))}}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Tu=class extends Ns{[$t](){let t;if(this[_s]&&this[St]==="r+")try{t=xe.openSync(this[Je],this[St],this[Xr])}catch(e){if(e?.code==="ENOENT")return this[St]="w",this[$t]();throw e}else t=xe.openSync(this[Je],this[St],this[Xr]);this[Yn](null,t)}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.closeSync(t),this.emit("close")}}[ys](t){let e=!0;try{this[Jn](null,xe.writeSync(this[$],t,0,t.length,this[Lt])),e=!1}finally{if(e)try{this[Ve]()}catch{}}}},Sw=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"]]),vw=t=>!!t.sync&&!!t.file,Iw=t=>!t.sync&&!!t.file,Tw=t=>!!t.sync&&!t.file,Rw=t=>!t.sync&&!t.file,kw=t=>!!t.file,bw=t=>Sw.get(t)||t,Xa=(t={})=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){let i=bw(n);e[i]=r}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},oi=(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=Xa(s);if(i?.(c,o),vw(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return t(c,o)}else if(Iw(c)){let l=e(c,o);return a?l.then(()=>a(),a):l}else if(Tw(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return n(c,o)}else if(Rw(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}),Ow=xw.constants||{ZLIB_VERNUM:4736},ot=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},Ow)),Pw=pn.concat,Jd=Object.getOwnPropertyDescriptor(pn,"concat"),Cw=t=>t,fa=Jd?.writable===!0||Jd?.set!==void 0?t=>{pn.concat=t?Cw:Pw}:t=>{},gn=Symbol("_superWrite"),ls=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"}},ha=Symbol("flushFlag"),Ya=class extends wn{#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 qd[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new qd[e](t)}catch(n){throw new ls(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 ls(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Oa(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(pn.alloc(0),{[ha]: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}[gn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=pn.from(t,e)),this.#e)return;Oa(this.#t,"zlib binding closed");let r=this.#t._handle,i=r.close;r.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},fa(!0);let o;try{let c=typeof t[ha]=="number"?t[ha]:this.#r;o=this.#t._processChunk(t,c),fa(!1)}catch(c){fa(!1),this.#o(new ls(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 ls(c,this.write)));let a;if(o)if(Array.isArray(o)&&o.length>0){let c=o[0];a=this[gn](pn.from(c));for(let l=1;l<o.length;l++)a=this[gn](o[l])}else a=this[gn](pn.from(o));return n&&n(),a}},ku=class extends Ya{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||ot.Z_FINISH,t.fullFlushFlag=ot.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(ot.Z_SYNC_FLUSH),Oa(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)}}}},Dw=class extends ku{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[gn](t){return this.#e?(this.#e=!1,t[9]=255,super[gn](t)):super[gn](t)}},Nw=class extends ku{constructor(t){super(t,"Unzip")}},bu=class extends Ya{constructor(t,e){t=t||{},t.flush=t.flush||ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=ot.BROTLI_OPERATION_FLUSH,super(t,e)}},Lw=class extends bu{constructor(t){super(t,"BrotliCompress")}},Fw=class extends bu{constructor(t){super(t,"BrotliDecompress")}},Au=class extends Ya{constructor(t,e){t=t||{},t.flush=t.flush||ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||ot.ZSTD_e_end,t.fullFlushFlag=ot.ZSTD_e_flush,super(t,e)}},Mw=class extends Au{constructor(t){super(t,"ZstdCompress")}},Bw=class extends Au{constructor(t){super(t,"ZstdDecompress")}},Uw=(t,e)=>{if(Number.isSafeInteger(t))t<0?$w(t,e):zw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},zw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},$w=(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]=xu(i):i===0?e[r-1]=0:(n=!0,e[r-1]=Ou(i))}},Gw=t=>{let e=t[0],n=e===128?jw(t.subarray(1,t.length)):e===255?Hw(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},Hw=t=>{for(var e=t.length,n=0,r=!1,i=e-1;i>-1;i--){var s=Number(t[i]),o;r?o=xu(s):s===0?o=s:(r=!0,o=Ou(s)),o!==0&&(n-=o*Math.pow(256,e-i-1))}return n},jw=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},xu=t=>(255^t)&255,Ou=t=>(255^t)+1&255,Ww={};iw(Ww,{code:()=>Qa,isCode:()=>Es,isName:()=>qw,name:()=>Ls});var Es=t=>Ls.has(t),qw=t=>Qa.has(t),Ls=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"]]),Qa=new Map(Array.from(Ls).map(t=>[t[1],t[0]])),mn=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??an(t,e,100),this.mode=n?.mode??r?.mode??Ft(t,e+100,8),this.uid=n?.uid??r?.uid??Ft(t,e+108,8),this.gid=n?.gid??r?.gid??Ft(t,e+116,8),this.size=n?.size??r?.size??Ft(t,e+124,12),this.mtime=n?.mtime??r?.mtime??pa(t,e+136,12),this.cksum=Ft(t,e+148,12),r&&this.#n(r,!0),n&&this.#n(n);let i=an(t,e+156,1);if(Es(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=an(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=n?.uname??r?.uname??an(t,e+265,32),this.gname=n?.gname??r?.gname??an(t,e+297,32),this.devmaj=n?.devmaj??r?.devmaj??Ft(t,e+329,8)??0,this.devmin=n?.devmin??r?.devmin??Ft(t,e+337,8)??0,t[e+475]!==0){let o=an(t,e+345,155);this.path=o+"/"+this.path}else{let o=an(t,e+345,130);o&&(this.path=o+"/"+this.path),this.atime=n?.atime??r?.atime??pa(t,e+476,12),this.ctime=n?.ctime??r?.ctime??pa(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=Jw(this.path||"",n),i=r[0],s=r[1];this.needPax=!!r[2],this.needPax=cn(t,e,100,i)||this.needPax,this.needPax=Mt(t,e+100,8,this.mode)||this.needPax,this.needPax=Mt(t,e+108,8,this.uid)||this.needPax,this.needPax=Mt(t,e+116,8,this.gid)||this.needPax,this.needPax=Mt(t,e+124,12,this.size)||this.needPax,this.needPax=ga(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=cn(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=cn(t,e+265,32,this.uname)||this.needPax,this.needPax=cn(t,e+297,32,this.gname)||this.needPax,this.needPax=Mt(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Mt(t,e+337,8,this.devmin)||this.needPax,this.needPax=cn(t,e+345,n,s)||this.needPax,t[e+475]!==0?this.needPax=cn(t,e+345,155,s)||this.needPax:(this.needPax=cn(t,e+345,130,s)||this.needPax,this.needPax=ga(t,e+476,12,this.atime)||this.needPax,this.needPax=ga(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,Mt(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Ls.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Qa.get(t));if(Es(e)||e==="Unsupported")this.#e=e;else if(Es(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Jw=(t,e)=>{let n=t,r="",i,s=Gn.parse(t).root||".";if(Buffer.byteLength(n)<100)i=[n,r,!1];else{r=Gn.dirname(n),n=Gn.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=Gn.join(Gn.basename(r),n),r=Gn.dirname(r));while(r!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},an=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),pa=(t,e,n)=>Vw(Ft(t,e,n)),Vw=t=>t===void 0?void 0:new Date(t*1e3),Ft=(t,e,n)=>Number(t[e])&128?Gw(t.subarray(e,e+n)):Kw(t,e,n),Zw=t=>isNaN(t)?void 0:t,Kw=(t,e,n)=>Zw(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Xw={12:8589934591,8:2097151},Mt=(t,e,n,r)=>r===void 0?!1:r>Xw[n]||r<0?(Uw(r,t.subarray(e,e+n)),!0):(Yw(t,e,n,r),!1),Yw=(t,e,n,r)=>t.write(Qw(r,n),e,n,"ascii"),Qw=(t,e)=>ey(Math.floor(t).toString(8),e),ey=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",ga=(t,e,n,r)=>r===void 0?!1:Mt(t,e,n,r.getTime()/1e3),ty=new Array(156).join("\0"),cn=(t,e,n,r)=>r===void 0?!1:(t.write(r+ty,e,n,"utf8"),r.length!==Buffer.byteLength(r)||r.length>n),xs=class Pu{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 mn({path:("PaxHeader/"+ny(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+`
89
+ `},configPath(t){return CT(t.homeDir,".coze","bridge","task.xml")},async install(t){let n=`cmd.exe /c ${[`^"${t.nodeBin}^"`,`^"${t.entry}^"`,"--daemon",`>> ^"${t.logFile}^" 2>&1`].join(" ")}`;await Pg("schtasks",["/Create","/SC","ONLOGON","/TN",Uo,"/TR",n,"/RU",t.userName,"/F"]),Dl.info("task scheduler entry created",{task:Uo,logFile:t.logFile})},async uninstall(t){await Pg("schtasks",["/Delete","/TN",Uo,"/F"]).catch(e=>Dl.warn("schtasks /Delete failed (ignored)",{err:String(e)})),Dl.info("task scheduler entry removed",{task:Uo})}}});var Dg={};Bi(Dg,{buildContext:()=>BT,getSupervisor:()=>LT,launchdSupervisor:()=>Pl,systemdSupervisor:()=>Cl,taskSchedulerSupervisor:()=>Nl});import{homedir as DT,userInfo as NT}from"node:os";function LT(t=process.platform){switch(t){case"darwin":return Pl;case"linux":return Cl;case"win32":return Nl;default:throw new Error(`unsupported platform for OS supervisor: ${t}`)}}function MT(){let t={};for(let e of FT){let n=process.env[e];n&&(t[e]=n)}return t}function BT(){let t=L();return{nodeBin:process.execPath,entry:kl(t),logFile:t.logFile,homeDir:DT(),userName:NT().username,isRoot:process.getuid?.()===0,env:MT()}}var FT,Ng=ve(()=>{"use strict";re();Ao();Ag();Og();Cg();FT=["PATH","HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","ALL_PROXY","http_proxy","https_proxy","no_proxy","all_proxy","NODE_EXTRA_CA_CERTS"]});F();tn();var Ql=b("acp-installer-warmup"),Im=["claude-code","codex"];async function ed(t={}){let e=t.ensure??en,r=(await Promise.allSettled(Im.map(async i=>{let s=await e(i);Ql.info("acp wrapper warmup ok",{framework:i,path:s})}))).filter(i=>i.status==="rejected");r.length>0&&Ql.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))})}At();F();import{readdir as Lm}from"node:fs/promises";import{mkdir as od,writeFile as ad}from"node:fs/promises";import{join as Ko}from"node:path";var Nm={"claude-code":"CLAUDE.md",codex:"AGENTS.md",openclaw:"SOUL.md"};async function Mn(t,e,n){await od(t,{recursive:!0});let r=Nm[e],i=Ko(t,r);return await ad(i,n??"","utf8"),i}async function cd(t){let e=Ko(t,".claude");await od(e,{recursive:!0});let n=Ko(e,"settings.local.json"),r=JSON.stringify({permissions:{defaultMode:"bypassPermissions"}},null,2);return await ad(n,r,"utf8"),n}var Oe=b("agent-detail-sync"),Fm=6e4,Mm=5*6e4,Xi=class{constructor(e){this.opts=e}opts;retryQueue=new Map;async syncAll(e){let n=this.opts.paths.agentsRoot,r;try{r=await Lm(n)}catch(i){Oe.info("agents dir not found, skip detail sync",{root:n,err:String(i)});return}Oe.info("starting detail sync",{reason:e,count:r.length}),await Promise.allSettled(r.map(async i=>{let s=await we(i,this.opts.paths).catch(()=>null);if(s){if(s.disconnectedAt){Oe.debug("detail sync: skip disconnected agent",{agentId:i});return}try{await this.syncOne(i,s)}catch(o){Oe.warn("detail sync failed for agent, skipping",{agentId:i,err:String(o)})}}})),Oe.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){Oe.info("retrying pending detail syncs",{count:n.length});for(let r of n)try{await this.syncOne(r)}catch(i){Oe.debug("detail sync retry still failing, will try again",{agentId:r,err:String(i)})}}}async syncOne(e,n){let r=n??await we(e,this.opts.paths);if(!r){Oe.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){Oe.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,Mm):Fm;this.retryQueue.set(e,{dueAt:Date.now()+l,currentDelay:l});return}if(i.agentId&&i.agentId!==e){Oe.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&&Oe.info("detail.deployType",{agentId:e,deployType:i.deployType}),!s){Oe.debug("detail sync: no diff",{agentId:e});return}await Ae(r,this.opts.paths),Oe.info("detail sync: config updated",{agentId:e,identityChanged:o,agentName:r.agentName}),o&&(await Mn(r.workspace,r.framework,r.cozeIdentity),this.opts.handlers.reloadAgentSessionsPublic(e,"detail-sync"))}};var Rf=ht($d(),1);import{lstat as uc,mkdir as fc,readFile as Sf,readdir as d_,rm as u_,stat as f_,writeFile as hc}from"node:fs/promises";import{dirname as h_,join as at,normalize as p_,relative as mc,resolve as pc,sep as vf}from"node:path";import{Readable as If}from"node:stream";import{pipeline as Tf}from"node:stream/promises";import sw from"events";import xe from"fs";import{EventEmitter as Za}from"node:events";import vu from"node:stream";import{StringDecoder as ow}from"node:string_decoder";import Ru from"node:path";import Zn from"node:fs";import{dirname as _w,parse as Ew}from"path";import{EventEmitter as Aw}from"events";import Oa from"assert";import{Buffer as hn}from"buffer";import*as qd from"zlib";import xw from"zlib";import{posix as Gn}from"node:path";import{basename as ny}from"node:path";import xs from"fs";import it from"fs";import Qd from"path";import{win32 as hy}from"node:path";import ou from"path";import zu from"node:fs";import Oy from"node:assert";import{randomBytes as $u}from"node:crypto";import B from"node:fs";import se from"node:path";import Gu from"fs";import Bs from"node:fs";import Yr from"node:path";import De from"node:fs";import My from"node:fs/promises";import Cs from"node:path";import{join as Qu}from"node:path";import Ce from"node:fs";import nf from"node:path";var rw=Object.defineProperty,iw=(t,e)=>{for(var n in e)rw(t,n,{get:e[n],enumerable:!0})},Gd=typeof process=="object"&&process?process:{stdout:null,stderr:null},aw=t=>!!t&&typeof t=="object"&&(t instanceof mn||t instanceof vu||cw(t)||lw(t)),cw=t=>!!t&&typeof t=="object"&&t instanceof Za&&typeof t.pipe=="function"&&t.pipe!==vu.Writable.prototype.pipe,lw=t=>!!t&&typeof t=="object"&&t instanceof Za&&typeof t.write=="function"&&typeof t.end=="function",mt=Symbol("EOF"),wt=Symbol("maybeEmitEnd"),Ot=Symbol("emittedEnd"),ns=Symbol("emittingEnd"),Lr=Symbol("emittedError"),rs=Symbol("closed"),Hd=Symbol("read"),is=Symbol("flush"),jd=Symbol("flushChunk"),je=Symbol("encoding"),$n=Symbol("decoder"),de=Symbol("flowing"),Fr=Symbol("paused"),qn=Symbol("resume"),ue=Symbol("buffer"),Re=Symbol("pipes"),fe=Symbol("bufferLength"),na=Symbol("bufferPush"),ss=Symbol("bufferShift"),Ie=Symbol("objectMode"),Q=Symbol("destroyed"),ra=Symbol("error"),ia=Symbol("emitData"),Wd=Symbol("emitEnd"),sa=Symbol("emitEnd2"),et=Symbol("async"),oa=Symbol("abort"),os=Symbol("aborted"),Mr=Symbol("signal"),rn=Symbol("dataListeners"),Pe=Symbol("discarded"),Br=t=>Promise.resolve().then(t),dw=t=>t(),uw=t=>t==="end"||t==="finish"||t==="prefinish",fw=t=>t instanceof ArrayBuffer||!!t&&typeof t=="object"&&t.constructor&&t.constructor.name==="ArrayBuffer"&&t.byteLength>=0,hw=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),Iu=class{src;dest;opts;ondrain;constructor(t,e,n){this.src=t,this.dest=e,this.opts=n,this.ondrain=()=>t[qn](),this.dest.on("drain",this.ondrain)}unpipe(){this.dest.removeListener("drain",this.ondrain)}proxyErrors(t){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},pw=class extends Iu{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)}},gw=t=>!!t.objectMode,mw=t=>!t.objectMode&&!!t.encoding&&t.encoding!=="buffer",mn=class extends Za{[de]=!1;[Fr]=!1;[Re]=[];[ue]=[];[Ie];[je];[et];[$n];[mt]=!1;[Ot]=!1;[ns]=!1;[rs]=!1;[Lr]=null;[fe]=0;[Q]=!1;[Mr];[os]=!1;[rn]=0;[Pe]=!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");gw(e)?(this[Ie]=!0,this[je]=null):mw(e)?(this[je]=e.encoding,this[Ie]=!1):(this[Ie]=!1,this[je]=null),this[et]=!!e.async,this[$n]=this[je]?new ow(this[je]):null,e&&e.debugExposeBuffer===!0&&Object.defineProperty(this,"buffer",{get:()=>this[ue]}),e&&e.debugExposePipes===!0&&Object.defineProperty(this,"pipes",{get:()=>this[Re]});let{signal:n}=e;n&&(this[Mr]=n,n.aborted?this[oa]():n.addEventListener("abort",()=>this[oa]()))}get bufferLength(){return this[fe]}get encoding(){return this[je]}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[Ie]}set objectMode(t){throw new Error("objectMode must be set at instantiation time")}get async(){return this[et]}set async(t){this[et]=this[et]||!!t}[oa](){this[os]=!0,this.emit("abort",this[Mr]?.reason),this.destroy(this[Mr]?.reason)}get aborted(){return this[os]}set aborted(t){}write(t,e,n){if(this[os])return!1;if(this[mt])throw new Error("write after end");if(this[Q])return this.emit("error",Object.assign(new Error("Cannot call write after a stream was destroyed"),{code:"ERR_STREAM_DESTROYED"})),!0;typeof e=="function"&&(n=e,e="utf8"),e||(e="utf8");let r=this[et]?Br:dw;if(!this[Ie]&&!Buffer.isBuffer(t)){if(hw(t))t=Buffer.from(t.buffer,t.byteOffset,t.byteLength);else if(fw(t))t=Buffer.from(t);else if(typeof t!="string")throw new Error("Non-contiguous data written to non-objectMode stream")}return this[Ie]?(this[de]&&this[fe]!==0&&this[is](!0),this[de]?this.emit("data",t):this[na](t),this[fe]!==0&&this.emit("readable"),n&&r(n),this[de]):t.length?(typeof t=="string"&&!(e===this[je]&&!this[$n]?.lastNeed)&&(t=Buffer.from(t,e)),Buffer.isBuffer(t)&&this[je]&&(t=this[$n].write(t)),this[de]&&this[fe]!==0&&this[is](!0),this[de]?this.emit("data",t):this[na](t),this[fe]!==0&&this.emit("readable"),n&&r(n),this[de]):(this[fe]!==0&&this.emit("readable"),n&&r(n),this[de])}read(t){if(this[Q])return null;if(this[Pe]=!1,this[fe]===0||t===0||t&&t>this[fe])return this[wt](),null;this[Ie]&&(t=null),this[ue].length>1&&!this[Ie]&&(this[ue]=[this[je]?this[ue].join(""):Buffer.concat(this[ue],this[fe])]);let e=this[Hd](t||null,this[ue][0]);return this[wt](),e}[Hd](t,e){if(this[Ie])this[ss]();else{let n=e;t===n.length||t===null?this[ss]():typeof n=="string"?(this[ue][0]=n.slice(t),e=n.slice(0,t),this[fe]-=t):(this[ue][0]=n.subarray(t),e=n.subarray(0,t),this[fe]-=t)}return this.emit("data",e),!this[ue].length&&!this[mt]&&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[mt]=!0,this.writable=!1,(this[de]||!this[Fr])&&this[wt](),this}[qn](){this[Q]||(!this[rn]&&!this[Re].length&&(this[Pe]=!0),this[Fr]=!1,this[de]=!0,this.emit("resume"),this[ue].length?this[is]():this[mt]?this[wt]():this.emit("drain"))}resume(){return this[qn]()}pause(){this[de]=!1,this[Fr]=!0,this[Pe]=!1}get destroyed(){return this[Q]}get flowing(){return this[de]}get paused(){return this[Fr]}[na](t){this[Ie]?this[fe]+=1:this[fe]+=t.length,this[ue].push(t)}[ss](){return this[Ie]?this[fe]-=1:this[fe]-=this[ue][0].length,this[ue].shift()}[is](t=!1){do;while(this[jd](this[ss]())&&this[ue].length);!t&&!this[ue].length&&!this[mt]&&this.emit("drain")}[jd](t){return this.emit("data",t),this[de]}pipe(t,e){if(this[Q])return t;this[Pe]=!1;let n=this[Ot];return e=e||{},t===Gd.stdout||t===Gd.stderr?e.end=!1:e.end=e.end!==!1,e.proxyErrors=!!e.proxyErrors,n?e.end&&t.end():(this[Re].push(e.proxyErrors?new pw(this,t,e):new Iu(this,t,e)),this[et]?Br(()=>this[qn]()):this[qn]()),t}unpipe(t){let e=this[Re].find(n=>n.dest===t);e&&(this[Re].length===1?(this[de]&&this[rn]===0&&(this[de]=!1),this[Re]=[]):this[Re].splice(this[Re].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[Pe]=!1,this[rn]++,!this[Re].length&&!this[de]&&this[qn]();else if(t==="readable"&&this[fe]!==0)super.emit("readable");else if(uw(t)&&this[Ot])super.emit(t),this.removeAllListeners(t);else if(t==="error"&&this[Lr]){let r=e;this[et]?Br(()=>r.call(this,this[Lr])):r.call(this,this[Lr])}return n}removeListener(t,e){return this.off(t,e)}off(t,e){let n=super.off(t,e);return t==="data"&&(this[rn]=this.listeners("data").length,this[rn]===0&&!this[Pe]&&!this[Re].length&&(this[de]=!1)),n}removeAllListeners(t){let e=super.removeAllListeners(t);return(t==="data"||t===void 0)&&(this[rn]=0,!this[Pe]&&!this[Re].length&&(this[de]=!1)),e}get emittedEnd(){return this[Ot]}[wt](){!this[ns]&&!this[Ot]&&!this[Q]&&this[ue].length===0&&this[mt]&&(this[ns]=!0,this.emit("end"),this.emit("prefinish"),this.emit("finish"),this[rs]&&this.emit("close"),this[ns]=!1)}emit(t,...e){let n=e[0];if(t!=="error"&&t!=="close"&&t!==Q&&this[Q])return!1;if(t==="data")return!this[Ie]&&!n?!1:this[et]?(Br(()=>this[ia](n)),!0):this[ia](n);if(t==="end")return this[Wd]();if(t==="close"){if(this[rs]=!0,!this[Ot]&&!this[Q])return!1;let i=super.emit("close");return this.removeAllListeners("close"),i}else if(t==="error"){this[Lr]=n,super.emit(ra,n);let i=!this[Mr]||this.listeners("error").length?super.emit("error",n):!1;return this[wt](),i}else if(t==="resume"){let i=super.emit("resume");return this[wt](),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[wt](),r}[ia](t){for(let n of this[Re])n.dest.write(t)===!1&&this.pause();let e=this[Pe]?!1:super.emit("data",t);return this[wt](),e}[Wd](){return this[Ot]?!1:(this[Ot]=!0,this.readable=!1,this[et]?(Br(()=>this[sa]()),!0):this[sa]())}[sa](){if(this[$n]){let e=this[$n].end();if(e){for(let n of this[Re])n.dest.write(e);this[Pe]||super.emit("data",e)}}for(let e of this[Re])e.end();let t=super.emit("end");return this.removeAllListeners("end"),t}async collect(){let t=Object.assign([],{dataLength:0});this[Ie]||(t.dataLength=0);let e=this.promise();return this.on("data",n=>{t.push(n),this[Ie]||(t.dataLength+=n.length)}),await e,t}async concat(){if(this[Ie])throw new Error("cannot concat in objectMode");let t=await this.collect();return this[je]?t.join(""):Buffer.concat(t,t.dataLength)}async promise(){return new Promise((t,e)=>{this.on(Q,()=>e(new Error("stream destroyed"))),this.on("error",n=>e(n)),this.on("end",()=>t())})}[Symbol.asyncIterator](){this[Pe]=!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[mt])return e();let r,i,s=l=>{this.off("data",o),this.off("end",a),this.off(Q,c),e(),i(l)},o=l=>{this.off("error",s),this.off("end",a),this.off(Q,c),this.pause(),r({value:l,done:!!this[mt]})},a=()=>{this.off("error",s),this.off("data",o),this.off(Q,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(Q,c),this.once("error",s),this.once("end",a),this.once("data",o)})},throw:e,return:e,[Symbol.asyncIterator](){return this},[Symbol.asyncDispose]:async()=>{}}}[Symbol.iterator](){this[Pe]=!1;let t=!1,e=()=>(this.pause(),this.off(ra,e),this.off(Q,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(ra,e),this.once(Q,e),{next:n,throw:e,return:e,[Symbol.iterator](){return this},[Symbol.dispose]:()=>{}}}destroy(t){if(this[Q])return t?this.emit("error",t):this.emit(Q),this;this[Q]=!0,this[Pe]=!0,this[ue].length=0,this[fe]=0;let e=this;return typeof e.close=="function"&&!this[rs]&&e.close(),t?this.emit("error",t):this.emit(Q),this}static get isStream(){return aw}},ww=xe.writev,zt=Symbol("_autoClose"),Ve=Symbol("_close"),Ur=Symbol("_ended"),$=Symbol("_fd"),aa=Symbol("_finished"),St=Symbol("_flags"),ca=Symbol("_flush"),Aa=Symbol("_handleChunk"),xa=Symbol("_makeBuf"),Kr=Symbol("_mode"),as=Symbol("_needDrain"),Xn=Symbol("_onerror"),Yn=Symbol("_onopen"),la=Symbol("_onread"),Jn=Symbol("_onwrite"),$t=Symbol("_open"),Je=Symbol("_path"),Lt=Symbol("_pos"),nt=Symbol("_queue"),Vn=Symbol("_read"),da=Symbol("_readSize"),Et=Symbol("_reading"),zr=Symbol("_remain"),ua=Symbol("_size"),ws=Symbol("_write"),sn=Symbol("_writing"),ys=Symbol("_defaultFlag"),fn=Symbol("_errored"),Ka=class extends mn{[fn]=!1;[$];[Je];[da];[Et]=!1;[ua];[zr];[zt];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[fn]=!1,this[$]=typeof e.fd=="number"?e.fd:void 0,this[Je]=t,this[da]=e.readSize||16*1024*1024,this[Et]=!1,this[ua]=typeof e.size=="number"?e.size:1/0,this[zr]=this[ua],this[zt]=typeof e.autoClose=="boolean"?e.autoClose:!0,typeof this[$]=="number"?this[Vn]():this[$t]()}get fd(){return this[$]}get path(){return this[Je]}write(){throw new TypeError("this is a readable stream")}end(){throw new TypeError("this is a readable stream")}[$t](){xe.open(this[Je],"r",(t,e)=>this[Yn](t,e))}[Yn](t,e){t?this[Xn](t):(this[$]=e,this.emit("open",e),this[Vn]())}[xa](){return Buffer.allocUnsafe(Math.min(this[da],this[zr]))}[Vn](){if(!this[Et]){this[Et]=!0;let t=this[xa]();if(t.length===0)return process.nextTick(()=>this[la](null,0,t));xe.read(this[$],t,0,t.length,null,(e,n,r)=>this[la](e,n,r))}}[la](t,e,n){this[Et]=!1,t?this[Xn](t):this[Aa](e,n)&&this[Vn]()}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}[Xn](t){this[Et]=!0,this[Ve](),this.emit("error",t)}[Aa](t,e){let n=!1;return this[zr]-=t,t>0&&(n=super.write(t<e.length?e.subarray(0,t):e)),(t===0||this[zr]<=0)&&(n=!1,this[Ve](),super.end()),n}emit(t,...e){switch(t){case"prefinish":case"finish":return!1;case"drain":return typeof this[$]=="number"&&this[Vn](),!1;case"error":return this[fn]?!1:(this[fn]=!0,super.emit(t,...e));default:return super.emit(t,...e)}}},yw=class extends Ka{[$t](){let t=!0;try{this[Yn](null,xe.openSync(this[Je],"r")),t=!1}finally{t&&this[Ve]()}}[Vn](){let t=!0;try{if(!this[Et]){this[Et]=!0;do{let e=this[xa](),n=e.length===0?0:xe.readSync(this[$],e,0,e.length,null);if(!this[Aa](n,e))break}while(!0);this[Et]=!1}t=!1}finally{t&&this[Ve]()}}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.closeSync(t),this.emit("close")}}},Ds=class extends sw{readable=!1;writable=!0;[fn]=!1;[sn]=!1;[Ur]=!1;[nt]=[];[as]=!1;[Je];[Kr];[zt];[$];[ys];[St];[aa]=!1;[Lt];constructor(t,e){e=e||{},super(e),this[Je]=t,this[$]=typeof e.fd=="number"?e.fd:void 0,this[Kr]=e.mode===void 0?438:e.mode,this[Lt]=typeof e.start=="number"?e.start:void 0,this[zt]=typeof e.autoClose=="boolean"?e.autoClose:!0;let n=this[Lt]!==void 0?"r+":"w";this[ys]=e.flags===void 0,this[St]=e.flags===void 0?n:e.flags,this[$]===void 0&&this[$t]()}emit(t,...e){if(t==="error"){if(this[fn])return!1;this[fn]=!0}return super.emit(t,...e)}get fd(){return this[$]}get path(){return this[Je]}[Xn](t){this[Ve](),this[sn]=!0,this.emit("error",t)}[$t](){xe.open(this[Je],this[St],this[Kr],(t,e)=>this[Yn](t,e))}[Yn](t,e){this[ys]&&this[St]==="r+"&&t&&t.code==="ENOENT"?(this[St]="w",this[$t]()):t?this[Xn](t):(this[$]=e,this.emit("open",e),this[sn]||this[ca]())}end(t,e){return t&&this.write(t,e),this[Ur]=!0,!this[sn]&&!this[nt].length&&typeof this[$]=="number"&&this[Jn](null,0),this}write(t,e){return typeof t=="string"&&(t=Buffer.from(t,e)),this[Ur]?(this.emit("error",new Error("write() after end()")),!1):this[$]===void 0||this[sn]||this[nt].length?(this[nt].push(t),this[as]=!0,!1):(this[sn]=!0,this[ws](t),!0)}[ws](t){xe.write(this[$],t,0,t.length,this[Lt],(e,n)=>this[Jn](e,n))}[Jn](t,e){t?this[Xn](t):(this[Lt]!==void 0&&typeof e=="number"&&(this[Lt]+=e),this[nt].length?this[ca]():(this[sn]=!1,this[Ur]&&!this[aa]?(this[aa]=!0,this[Ve](),this.emit("finish")):this[as]&&(this[as]=!1,this.emit("drain"))))}[ca](){if(this[nt].length===0)this[Ur]&&this[Jn](null,0);else if(this[nt].length===1)this[ws](this[nt].pop());else{let t=this[nt];this[nt]=[],ww(this[$],t,this[Lt],(e,n)=>this[Jn](e,n))}}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.close(t,e=>e?this.emit("error",e):this.emit("close"))}}},Tu=class extends Ds{[$t](){let t;if(this[ys]&&this[St]==="r+")try{t=xe.openSync(this[Je],this[St],this[Kr])}catch(e){if(e?.code==="ENOENT")return this[St]="w",this[$t]();throw e}else t=xe.openSync(this[Je],this[St],this[Kr]);this[Yn](null,t)}[Ve](){if(this[zt]&&typeof this[$]=="number"){let t=this[$];this[$]=void 0,xe.closeSync(t),this.emit("close")}}[ws](t){let e=!0;try{this[Jn](null,xe.writeSync(this[$],t,0,t.length,this[Lt])),e=!1}finally{if(e)try{this[Ve]()}catch{}}}},Sw=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"]]),vw=t=>!!t.sync&&!!t.file,Iw=t=>!t.sync&&!!t.file,Tw=t=>!!t.sync&&!t.file,Rw=t=>!t.sync&&!t.file,kw=t=>!!t.file,bw=t=>Sw.get(t)||t,Xa=(t={})=>{if(!t)return{};let e={};for(let[n,r]of Object.entries(t)){let i=bw(n);e[i]=r}return e.chmod===void 0&&e.noChmod===!1&&(e.chmod=!0),delete e.noChmod,e},si=(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=Xa(s);if(i?.(c,o),vw(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return t(c,o)}else if(Iw(c)){let l=e(c,o);return a?l.then(()=>a(),a):l}else if(Tw(c)){if(typeof a=="function")throw new TypeError("callback not supported for sync tar functions");return n(c,o)}else if(Rw(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}),Ow=xw.constants||{ZLIB_VERNUM:4736},ot=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},Ow)),Pw=hn.concat,Jd=Object.getOwnPropertyDescriptor(hn,"concat"),Cw=t=>t,fa=Jd?.writable===!0||Jd?.set!==void 0?t=>{hn.concat=t?Cw:Pw}:t=>{},pn=Symbol("_superWrite"),cs=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"}},ha=Symbol("flushFlag"),Ya=class extends mn{#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 qd[e]!="function")throw new TypeError("Compression method not supported: "+e);try{this.#t=new qd[e](t)}catch(n){throw new cs(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 cs(n))),this.once("end",()=>this.close)}close(){this.#t&&(this.#t.close(),this.#t=void 0,this.emit("close"))}reset(){if(!this.#e)return Oa(this.#t,"zlib binding closed"),this.#t.reset?.()}flush(t){this.ended||(typeof t!="number"&&(t=this.#i),this.write(Object.assign(hn.alloc(0),{[ha]: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}[pn](t){return super.write(t)}write(t,e,n){if(typeof e=="function"&&(n=e,e="utf8"),typeof t=="string"&&(t=hn.from(t,e)),this.#e)return;Oa(this.#t,"zlib binding closed");let r=this.#t._handle,i=r.close;r.close=()=>{};let s=this.#t.close;this.#t.close=()=>{},fa(!0);let o;try{let c=typeof t[ha]=="number"?t[ha]:this.#r;o=this.#t._processChunk(t,c),fa(!1)}catch(c){fa(!1),this.#o(new cs(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 cs(c,this.write)));let a;if(o)if(Array.isArray(o)&&o.length>0){let c=o[0];a=this[pn](hn.from(c));for(let l=1;l<o.length;l++)a=this[pn](o[l])}else a=this[pn](hn.from(o));return n&&n(),a}},ku=class extends Ya{#e;#n;constructor(t,e){t=t||{},t.flush=t.flush||ot.Z_NO_FLUSH,t.finishFlush=t.finishFlush||ot.Z_FINISH,t.fullFlushFlag=ot.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(ot.Z_SYNC_FLUSH),Oa(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)}}}},Dw=class extends ku{#e;constructor(t){super(t,"Gzip"),this.#e=t&&!!t.portable}[pn](t){return this.#e?(this.#e=!1,t[9]=255,super[pn](t)):super[pn](t)}},Nw=class extends ku{constructor(t){super(t,"Unzip")}},bu=class extends Ya{constructor(t,e){t=t||{},t.flush=t.flush||ot.BROTLI_OPERATION_PROCESS,t.finishFlush=t.finishFlush||ot.BROTLI_OPERATION_FINISH,t.fullFlushFlag=ot.BROTLI_OPERATION_FLUSH,super(t,e)}},Lw=class extends bu{constructor(t){super(t,"BrotliCompress")}},Fw=class extends bu{constructor(t){super(t,"BrotliDecompress")}},Au=class extends Ya{constructor(t,e){t=t||{},t.flush=t.flush||ot.ZSTD_e_continue,t.finishFlush=t.finishFlush||ot.ZSTD_e_end,t.fullFlushFlag=ot.ZSTD_e_flush,super(t,e)}},Mw=class extends Au{constructor(t){super(t,"ZstdCompress")}},Bw=class extends Au{constructor(t){super(t,"ZstdDecompress")}},Uw=(t,e)=>{if(Number.isSafeInteger(t))t<0?$w(t,e):zw(t,e);else throw Error("cannot encode number outside of javascript safe integer range");return e},zw=(t,e)=>{e[0]=128;for(var n=e.length;n>1;n--)e[n-1]=t&255,t=Math.floor(t/256)},$w=(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]=xu(i):i===0?e[r-1]=0:(n=!0,e[r-1]=Ou(i))}},Gw=t=>{let e=t[0],n=e===128?jw(t.subarray(1,t.length)):e===255?Hw(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},Hw=t=>{for(var e=t.length,n=0,r=!1,i=e-1;i>-1;i--){var s=Number(t[i]),o;r?o=xu(s):s===0?o=s:(r=!0,o=Ou(s)),o!==0&&(n-=o*Math.pow(256,e-i-1))}return n},jw=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},xu=t=>(255^t)&255,Ou=t=>(255^t)+1&255,Ww={};iw(Ww,{code:()=>Qa,isCode:()=>_s,isName:()=>qw,name:()=>Ns});var _s=t=>Ns.has(t),qw=t=>Qa.has(t),Ns=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"]]),Qa=new Map(Array.from(Ns).map(t=>[t[1],t[0]])),gn=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??on(t,e,100),this.mode=n?.mode??r?.mode??Ft(t,e+100,8),this.uid=n?.uid??r?.uid??Ft(t,e+108,8),this.gid=n?.gid??r?.gid??Ft(t,e+116,8),this.size=n?.size??r?.size??Ft(t,e+124,12),this.mtime=n?.mtime??r?.mtime??pa(t,e+136,12),this.cksum=Ft(t,e+148,12),r&&this.#n(r,!0),n&&this.#n(n);let i=on(t,e+156,1);if(_s(i)&&(this.#e=i||"0"),this.#e==="0"&&this.path.slice(-1)==="/"&&(this.#e="5"),this.#e==="5"&&(this.size=0),this.linkpath=on(t,e+157,100),t.subarray(e+257,e+265).toString()==="ustar\x0000")if(this.uname=n?.uname??r?.uname??on(t,e+265,32),this.gname=n?.gname??r?.gname??on(t,e+297,32),this.devmaj=n?.devmaj??r?.devmaj??Ft(t,e+329,8)??0,this.devmin=n?.devmin??r?.devmin??Ft(t,e+337,8)??0,t[e+475]!==0){let o=on(t,e+345,155);this.path=o+"/"+this.path}else{let o=on(t,e+345,130);o&&(this.path=o+"/"+this.path),this.atime=n?.atime??r?.atime??pa(t,e+476,12),this.ctime=n?.ctime??r?.ctime??pa(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=Jw(this.path||"",n),i=r[0],s=r[1];this.needPax=!!r[2],this.needPax=an(t,e,100,i)||this.needPax,this.needPax=Mt(t,e+100,8,this.mode)||this.needPax,this.needPax=Mt(t,e+108,8,this.uid)||this.needPax,this.needPax=Mt(t,e+116,8,this.gid)||this.needPax,this.needPax=Mt(t,e+124,12,this.size)||this.needPax,this.needPax=ga(t,e+136,12,this.mtime)||this.needPax,t[e+156]=Number(this.#e.codePointAt(0)),this.needPax=an(t,e+157,100,this.linkpath)||this.needPax,t.write("ustar\x0000",e+257,8),this.needPax=an(t,e+265,32,this.uname)||this.needPax,this.needPax=an(t,e+297,32,this.gname)||this.needPax,this.needPax=Mt(t,e+329,8,this.devmaj)||this.needPax,this.needPax=Mt(t,e+337,8,this.devmin)||this.needPax,this.needPax=an(t,e+345,n,s)||this.needPax,t[e+475]!==0?this.needPax=an(t,e+345,155,s)||this.needPax:(this.needPax=an(t,e+345,130,s)||this.needPax,this.needPax=ga(t,e+476,12,this.atime)||this.needPax,this.needPax=ga(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,Mt(t,e+148,8,this.cksum),this.cksumValid=!0,this.needPax}get type(){return this.#e==="Unsupported"?this.#e:Ns.get(this.#e)}get typeKey(){return this.#e}set type(t){let e=String(Qa.get(t));if(_s(e)||e==="Unsupported")this.#e=e;else if(_s(t))this.#e=t;else throw new TypeError("invalid entry type: "+t)}},Jw=(t,e)=>{let n=t,r="",i,s=Gn.parse(t).root||".";if(Buffer.byteLength(n)<100)i=[n,r,!1];else{r=Gn.dirname(n),n=Gn.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=Gn.join(Gn.basename(r),n),r=Gn.dirname(r));while(r!==s&&i===void 0);i||(i=[t.slice(0,99),"",!0])}return i},on=(t,e,n)=>t.subarray(e,e+n).toString("utf8").replace(/\0.*/,""),pa=(t,e,n)=>Vw(Ft(t,e,n)),Vw=t=>t===void 0?void 0:new Date(t*1e3),Ft=(t,e,n)=>Number(t[e])&128?Gw(t.subarray(e,e+n)):Kw(t,e,n),Zw=t=>isNaN(t)?void 0:t,Kw=(t,e,n)=>Zw(parseInt(t.subarray(e,e+n).toString("utf8").replace(/\0.*$/,"").trim(),8)),Xw={12:8589934591,8:2097151},Mt=(t,e,n,r)=>r===void 0?!1:r>Xw[n]||r<0?(Uw(r,t.subarray(e,e+n)),!0):(Yw(t,e,n,r),!1),Yw=(t,e,n,r)=>t.write(Qw(r,n),e,n,"ascii"),Qw=(t,e)=>ey(Math.floor(t).toString(8),e),ey=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join("0")+t+" ")+"\0",ga=(t,e,n,r)=>r===void 0?!1:Mt(t,e,n,r.getTime()/1e3),ty=new Array(156).join("\0"),an=(t,e,n,r)=>r===void 0?!1:(t.write(r+ty,e,n,"utf8"),r.length!==Buffer.byteLength(r)||r.length>n),As=class Pu{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 gn({path:("PaxHeader/"+ny(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+`
90
90
  `,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 Pu(ry(iy(e),n),r)}},ry=(t,e)=>e?Object.assign({},e,t):t,iy=t=>t.replace(/\n$/,"").split(`
91
- `).reduce(sy,Object.create(null)),sy=(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},oy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,N=oy!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Cu=class extends wn{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))))}},Fs=(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))},ay=1024*1024,Pa=Buffer.from([31,139]),Ca=Buffer.from([40,181,47,253]),cy=Math.max(Pa.length,Ca.length),Me=Symbol("state"),ln=Symbol("writeEntry"),yt=Symbol("readEntry"),ma=Symbol("nextEntry"),Vd=Symbol("processEntry"),rt=Symbol("extendedHeader"),Gr=Symbol("globalExtendedHeader"),Pt=Symbol("meta"),Zd=Symbol("emitMeta"),W=Symbol("buffer"),_t=Symbol("queue"),Ct=Symbol("ended"),wa=Symbol("emittedEnd"),dn=Symbol("emit"),te=Symbol("unzip"),ds=Symbol("consumeChunk"),us=Symbol("consumeChunkSub"),ya=Symbol("consumeBody"),Kd=Symbol("consumeMeta"),Xd=Symbol("consumeHeader"),Hr=Symbol("consuming"),_a=Symbol("bufferConcat"),fs=Symbol("maybeEnd"),Hn=Symbol("writing"),Dt=Symbol("aborted"),hs=Symbol("onDone"),un=Symbol("sawValidEntry"),ps=Symbol("sawNullBlock"),gs=Symbol("sawEOF"),Yd=Symbol("closeStream"),ly=()=>!0,si=class extends Aw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[_t]=[];[W];[yt];[ln];[Me]="begin";[Pt]="";[rt];[Gr];[Ct]=!1;[te];[Dt]=!1;[un];[ps]=!1;[gs]=!1;[Hn]=!1;[Hr]=!1;[wa]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(hs,()=>{(this[Me]==="begin"||this[un]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(hs,t.ondone):this.on(hs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||ay,this.filter=typeof t.filter=="function"?t.filter:ly;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[Yd]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){Fs(this,t,e,n)}[Xd](t,e){this[un]===void 0&&(this[un]=!1);let n;try{n=new mn(t,e,this[rt],this[Gr])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(n.nullBlock)this[ps]?(this[gs]=!0,this[Me]==="begin"&&(this[Me]="header"),this[dn]("eof")):(this[ps]=!0,this[dn]("nullBlock"));else if(this[ps]=!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[ln]=new Cu(n,this[rt],this[Gr]);if(!this[un])if(i.remain){let s=()=>{i.invalid||(this[un]=!0)};i.on("end",s)}else this[un]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[dn]("ignoredEntry",i),this[Me]="ignore",i.resume()):i.size>0&&(this[Pt]="",i.on("data",s=>this[Pt]+=s),this[Me]="meta"):(this[rt]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[dn]("ignoredEntry",i),this[Me]=i.remain?"ignore":"header",i.resume()):(i.remain?this[Me]="body":(this[Me]="header",i.end()),this[yt]?this[_t].push(i):(this[_t].push(i),this[ma]())))}}}[Yd](){queueMicrotask(()=>this.emit("close"))}[Vd](t){let e=!0;if(!t)this[yt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...r]=t;this.emit(n,...r)}else this[yt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ma]()),e=!1);return e}[ma](){do;while(this[Vd](this[_t].shift()));if(this[_t].length===0){let t=this[yt];!t||t.flowing||t.size===t.remain?this[Hn]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[ya](t,e){let n=this[ln];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[Me]="header",this[ln]=void 0,n.end()),i.length}[Kd](t,e){let n=this[ln],r=this[ya](t,e);return!this[ln]&&n&&this[Zd](n),r}[dn](t,e,n){this[_t].length===0&&!this[yt]?this.emit(t,e,n):this[_t].push([t,e,n])}[Zd](t){switch(this[dn]("meta",this[Pt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[rt]=xs.parse(this[Pt],this[rt],!1);break;case"GlobalExtendedHeader":this[Gr]=xs.parse(this[Pt],this[Gr],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[rt]??Object.create(null);this[rt]=e,e.path=this[Pt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[rt]||Object.create(null);this[rt]=e,e.linkpath=this[Pt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[Dt]=!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[Dt])return n?.(),!1;if((this[te]===void 0||this.brotli===void 0&&this[te]===!1)&&t){if(this[W]&&(t=Buffer.concat([this[W],t]),this[W]=void 0),t.length<cy)return this[W]=t,n?.(),!0;for(let o=0;this[te]===void 0&&o<Pa.length;o++)t[o]!==Pa[o]&&(this[te]=!1);let i=!1;if(this[te]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<Ca.length;o++)if(t[o]!==Ca[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[te]===!1&&s)if(t.length<512)if(this[Ct])this.brotli=!0;else return this[W]=t,n?.(),!0;else try{new mn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[te]===void 0||this[te]===!1&&(this.brotli||i)){let o=this[Ct];this[Ct]=!1,this[te]=this[te]===void 0?new Nw({}):i?new Bw({}):new Fw({}),this[te].on("data",c=>this[ds](c)),this[te].on("error",c=>this.abort(c)),this[te].on("end",()=>{this[Ct]=!0,this[ds]()}),this[Hn]=!0;let a=!!this[te][o?"end":"write"](t);return this[Hn]=!1,n?.(),a}}this[Hn]=!0,this[te]?this[te].write(t):this[ds](t),this[Hn]=!1;let r=this[_t].length>0?!1:this[yt]?this[yt].flowing:!0;return!r&&this[_t].length===0&&this[yt]?.once("drain",()=>this.emit("drain")),n?.(),r}[_a](t){t&&!this[Dt]&&(this[W]=this[W]?Buffer.concat([this[W],t]):t)}[fs](){if(this[Ct]&&!this[wa]&&!this[Dt]&&!this[Hr]){this[wa]=!0;let t=this[ln];if(t&&t.blockRemain){let e=this[W]?this[W].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[W]&&t.write(this[W]),t.end()}this[dn](hs)}}[ds](t){if(this[Hr]&&t)this[_a](t);else if(!t&&!this[W])this[fs]();else if(t){if(this[Hr]=!0,this[W]){this[_a](t);let e=this[W];this[W]=void 0,this[us](e)}else this[us](t);for(;this[W]&&this[W]?.length>=512&&!this[Dt]&&!this[gs];){let e=this[W];this[W]=void 0,this[us](e)}this[Hr]=!1}(!this[W]||this[Ct])&&this[fs]()}[us](t){let e=0,n=t.length;for(;e+512<=n&&!this[Dt]&&!this[gs];)switch(this[Me]){case"begin":case"header":this[Xd](t,e),e+=512;break;case"ignore":case"body":e+=this[ya](t,e);break;case"meta":e+=this[Kd](t,e);break;default:throw new Error("invalid state: "+this[Me])}e<n&&(this[W]=this[W]?Buffer.concat([t.subarray(e),this[W]]):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[Dt]||(this[te]?(t&&this[te].write(t),this[te].end()):(this[Ct]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[fs]())),this}},Yr=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)},dy=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Du=(t,e)=>{let n=new Map(e.map(s=>[Yr(s),!0])),r=t.filter,i=(s,o="")=>{let a=o||Ew(s).root||".",c;if(s===a)c=!1;else{let l=n.get(s);c=l!==void 0?l:i(_w(s),a)}return n.set(s,c),c};t.filter=r?(s,o)=>r(s,o)&&i(Yr(s)):s=>i(Yr(s))},uy=t=>{let e=new si(t),n=t.file,r;try{r=Zn.openSync(n,"r");let i=Zn.fstatSync(r),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),a=Zn.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=Zn.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{Zn.closeSync(r)}catch{}}},fy=(t,e)=>{let n=new si(t),r=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{n.on("error",o),n.on("end",s),Zn.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ka(i,{readSize:r,size:c.size});l.on("error",o),l.pipe(n)}})})},Qn=oi(uy,fy,t=>new si(t),t=>new si(t),(t,e)=>{e?.length&&Du(t,e),t.noResume||dy(t)}),Nu=(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:py,parse:eu}=hy,ec=t=>{let e="",n=eu(t);for(;py(t)||n.root;){let r=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(r.length),e+=r,n=eu(t)}return[e,t]},Ms=["|","<",">","?",":"],tc=Ms.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),gy=new Map(Ms.map((t,e)=>[t,tc[e]])),my=new Map(tc.map((t,e)=>[t,Ms[e]])),tu=t=>Ms.reduce((e,n)=>e.split(n).join(gy.get(n)),t),wy=t=>tc.reduce((e,n)=>e.split(n).join(my.get(n)),t),Lu=(t,e)=>e?(t=N(t).replace(/^\.(\/|$)/,""),Yr(e)+"/"+t):N(t),yy=16*1024*1024,nu=Symbol("process"),ru=Symbol("file"),iu=Symbol("directory"),Da=Symbol("symlink"),su=Symbol("hardlink"),jr=Symbol("header"),Ss=Symbol("read"),Na=Symbol("lstat"),vs=Symbol("onlstat"),La=Symbol("onread"),Fa=Symbol("onreadlink"),Ma=Symbol("openfile"),Ba=Symbol("onopenfile"),Bt=Symbol("close"),Ps=Symbol("mode"),Ua=Symbol("awaitDrain"),Ea=Symbol("ondrain"),st=Symbol("prefix"),Fu=class extends wn{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=Xa(e);super(),this.path=N(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||yy,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]=ec(this.path);s&&typeof o=="string"&&(this.path=o,r=s)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=wy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=N(n.absolute||Qd.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[vs](i):this[Na]()}warn(t,e,n={}){return Fs(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Na](){it.lstat(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[vs](e)})}[vs](t){this.statCache.set(this.absolute,t),this.stat=t,t.isFile()||(t.size=0),this.type=Sy(t),this.emit("stat",t),this[nu]()}[nu](){switch(this.type){case"File":return this[ru]();case"Directory":return this[iu]();case"SymbolicLink":return this[Da]();default:return this.end()}}[Ps](t){return Nu(t,this.type==="Directory",this.portable)}[st](t){return Lu(t,this.prefix)}[jr](){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 mn({path:this[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](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 xs({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[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](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)}[iu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[jr](),this.end()}[Da](){it.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Fa](e)})}[Fa](t){this.linkpath=N(t),this[jr](),this.end()}[su](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=N(Qd.relative(this.cwd,t)),this.stat.size=0,this[jr](),this.end()}[ru](){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[su](e);this.linkCache.set(t,this.absolute)}if(this[jr](),this.stat.size===0)return this.end();this[Ma]()}[Ma](){it.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ba](e)})}[Ba](t){if(this.fd=t,this.#e)return this[Bt]();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[Ss]()}[Ss](){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");it.read(t,e,n,r,i,(s,o)=>{if(s)return this[Bt](()=>this.emit("error",s));this[La](o)})}[Bt](t=()=>{}){this.fd!==void 0&&it.close(this.fd,t)}[La](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[Bt](()=>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[Bt](()=>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[Ea]():this[Ua](()=>this[Ea]())}[Ua](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)}[Ea](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Bt](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[Ss]()}},_y=class extends Fu{sync=!0;[Na](){this[vs](it.lstatSync(this.absolute))}[Da](){this[Fa](it.readlinkSync(this.absolute))}[Ma](){this[Ba](it.openSync(this.absolute,"r"))}[Ss](){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=it.readSync(e,n,r,i,s);this[La](o),t=!1}finally{if(t)try{this[Bt](()=>{})}catch{}}}[Ua](t){t()}[Bt](t=()=>{}){this.fd!==void 0&&it.closeSync(this.fd),t()}},Ey=class extends wn{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 Fs(this,t,e,n)}constructor(t,e={}){let n=Xa(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[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: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]=ec(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 mn({path:this[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](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 xs({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[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](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)}[st](t){return Lu(t,this.prefix)}[Ps](t){return Nu(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}},Sy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",vy=class Kn{tail;head;length=0;static create(e=[]){return new Kn(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++)Ty(this,e[n]);return this.length}unshift(...e){for(var n=0,r=e.length;n<r;n++)Ry(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 Kn;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 Kn;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 Kn;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 Kn;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=Iy(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 Iy(t,e,n){let r=e,i=e?e.next:t.head,s=new nc(n,r,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function Ty(t,e){t.tail=new nc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Ry(t,e){t.head=new nc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var nc=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}},au=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},cu=Buffer.alloc(1024),Is=Symbol("onStat"),Wr=Symbol("ended"),We=Symbol("queue"),qr=Symbol("queue"),Nt=Symbol("current"),fn=Symbol("process"),Jr=Symbol("processing"),ms=Symbol("processJob"),qe=Symbol("jobs"),Sa=Symbol("jobDone"),Ts=Symbol("addFSEntry"),lu=Symbol("addTarEntry"),za=Symbol("stat"),$a=Symbol("readdir"),Rs=Symbol("onreaddir"),ks=Symbol("pipe"),du=Symbol("entry"),va=Symbol("entryOpt"),bs=Symbol("writeEntryClass"),Mu=Symbol("write"),Ia=Symbol("ondrain"),Bs=class extends wn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[bs];onWriteEntry;[We];[qr]=new Map;[qe]=0;[Jr]=!1;[Wr]=!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[bs]=Fu,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 Dw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Lw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Mw(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[Ia]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Ia]);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[We]=new vy,this[qe]=0,this.jobs=Number(t.jobs)||4,this[Jr]=!1,this[Wr]=!1}[Mu](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[Wr]=!0,this[fn](),n&&n(),this}write(t){if(this[Wr])throw new Error("write after end");return t instanceof Cu?this[lu](t):this[Ts](t),this.flowing}[lu](t){let e=N(ou.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new au(t.path,e);n.entry=new Ey(t,this[va](n)),n.entry.on("end",()=>this[Sa](n)),this[qe]+=1,this[We].push(n)}this[fn]()}[Ts](t){let e=N(ou.resolve(this.cwd,t));this[We].push(new au(t,e)),this[fn]()}[za](t){t.pending=!0,this[qe]+=1;let e=this.follow?"stat":"lstat";Os[e](t.absolute,(n,r)=>{t.pending=!1,this[qe]-=1,n?this.emit("error",n):this[Is](t,r)})}[Is](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[Nt])this[ms](t);else{let n=`${e.dev}:${e.ino}`,r=this[qr].get(n);r?r.push(t):this[qr].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[fn]()}[$a](t){t.pending=!0,this[qe]+=1,Os.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[qe]-=1,e)return this.emit("error",e);this[Rs](t,n)})}[Rs](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[fn]()}[fn](){if(!this[Jr]){this[Jr]=!0;for(let t=this[We].head;t&&this[qe]<this.jobs;t=t.next)if(this[ms](t.value),t.value.ignore){let e=t.next;this[We].removeNode(t),t.next=e}this[Jr]=!1,this[Wr]&&this[We].length===0&&this[qe]===0&&(this.zip?this.zip.end(cu):(super.write(cu),super.end()))}}get[Nt](){return this[We]&&this[We].head&&this[We].head.value}[Sa](t){this[We].shift(),this[qe]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,r=this[qr].get(n);if(r){this[qr].delete(n);for(let i of r)i.pending=!1,this[ms](i)}}this[fn]()}[ms](t){if(t.pending&&t.pendingLink&&t===this[Nt]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Nt]&&!t.piped&&this[ks](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[Is](t,e):this[za](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Rs](t,e):this[$a](t),!t.readdir)return}if(t.entry=this[du](t),!t.entry){t.ignore=!0;return}t===this[Nt]&&!t.piped&&this[ks](t)}}}[va](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}}[du](t){this[qe]+=1;try{return new this[bs](t.path,this[va](t)).on("end",()=>this[Sa](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Ia](){this[Nt]&&this[Nt].entry&&this[Nt].entry.resume()}[ks](t){t.piped=!0,t.readdir&&t.readdir.forEach(r=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[Ts](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={}){Fs(this,t,e,n)}},rc=class extends Bs{sync=!0;constructor(t){super(t),this[bs]=_y}pause(){}resume(){}[za](t){let e=this.follow?"statSync":"lstatSync";this[Is](t,Os[e](t.absolute))}[$a](t){this[Rs](t,Os.readdirSync(t.absolute))}[ks](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[Ts](s+r)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",r=>{n.write(r)}):e.on("data",r=>{super[Mu](r)})}},ky=(t,e)=>{let n=new rc(t),r=new Tu(t.file,{mode:t.mode||438});n.pipe(r),Bu(n,e)},by=(t,e)=>{let n=new Bs(t),r=new Ns(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 Uu(n,e).catch(s=>n.emit("error",s)),i},Bu=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Qn({file:Ru.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n)}),t.end()},Uu=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Qn({file:Ru.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:r=>{t.add(r)}}):t.add(n);t.end()},Ay=(t,e)=>{let n=new rc(t);return Bu(n,e),n},xy=(t,e)=>{let n=new Bs(t);return Uu(n,e).catch(r=>n.emit("error",r)),n},Ik=oi(ky,by,Ay,xy,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),Py=process.env.__FAKE_PLATFORM__||process.platform,Hu=Py==="win32",{O_CREAT:ju,O_NOFOLLOW:uu,O_TRUNC:Wu,O_WRONLY:qu}=Gu.constants,Ju=Number(process.env.__FAKE_FS_O_FILENAME__)||Gu.constants.UV_FS_O_FILEMAP||0,Cy=Hu&&!!Ju,Dy=512*1024,Ny=Ju|Wu|ju|qu,fu=!Hu&&typeof uu=="number"?uu|Wu|ju|qu:null,Vu=fu!==null?()=>fu:Cy?t=>t<Dy?Ny:"w":()=>"w",Ga=(t,e,n)=>{try{return Us.lchownSync(t,e,n)}catch(r){if(r?.code!=="ENOENT")throw r}},Cs=(t,e,n,r)=>{Us.lchown(t,e,n,i=>{r(i&&i?.code!=="ENOENT"?i:null)})},Ly=(t,e,n,r,i)=>{if(e.isDirectory())Zu(Qr.resolve(t,e.name),n,r,s=>{if(s)return i(s);let o=Qr.resolve(t,e.name);Cs(o,n,r,i)});else{let s=Qr.resolve(t,e.name);Cs(s,n,r,i)}},Zu=(t,e,n,r)=>{Us.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 Cs(t,e,n,r);let o=s.length,a=null,c=l=>{if(!a){if(l)return r(a=l);if(--o===0)return Cs(t,e,n,r)}};for(let l of s)Ly(t,l,e,n,c)})},Fy=(t,e,n,r)=>{e.isDirectory()&&Ku(Qr.resolve(t,e.name),n,r),Ga(Qr.resolve(t,e.name),n,r)},Ku=(t,e,n)=>{let r;try{r=Us.readdirSync(t,{withFileTypes:!0})}catch(i){let s=i;if(s?.code==="ENOENT")return;if(s?.code==="ENOTDIR"||s?.code==="ENOTSUP")return Ga(t,e,n);throw s}for(let i of r)Fy(t,i,e,n);return Ga(t,e,n)},Xu=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"}},zs=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"}},By=(t,e)=>{De.stat(t,(n,r)=>{(n||!r.isDirectory())&&(n=new Xu(t,n?.code||"ENOTDIR")),e(n)})},Uy=(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?Zu(g,o,a,w=>m(w)):s?De.chmod(t,i,n):n()};if(t===p)return By(t,m);if(l)return My.mkdir(t,{mode:i,recursive:!0}).then(h=>m(null,h??void 0),m);let u=N(Ds.relative(p,t)).split("/");Ha(p,u,i,d,p,void 0,m)},Ha=(t,e,n,r,i,s,o)=>{if(e.length===0)return o(null,s);let a=e.shift(),c=N(Ds.resolve(t+"/"+a));De.mkdir(c,n,Yu(c,e,n,r,i,s,o))},Yu=(t,e,n,r,i,s,o)=>a=>{a?De.lstat(t,(c,l)=>{if(c)c.path=c.path&&N(c.path),o(c);else if(l.isDirectory())Ha(t,e,n,r,i,s,o);else if(r)De.unlink(t,d=>{if(d)return o(d);De.mkdir(t,n,Yu(t,e,n,r,i,s,o))});else{if(l.isSymbolicLink())return o(new zs(t,t+"/"+e.join("/")));o(a)}}):(s=s||t,Ha(t,e,n,r,i,s,o))},zy=t=>{let e=!1,n;try{e=De.statSync(t).isDirectory()}catch(r){n=r?.code}finally{if(!e)throw new Xu(t,n??"ENOTDIR")}},$y=(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&&Ku(h,s,o),i&&De.chmodSync(t,r)};if(t===d)return zy(d),p();if(c)return p(De.mkdirSync(t,{mode:r,recursive:!0})??void 0);let m=N(Ds.relative(d,t)).split("/"),u;for(let h=m.shift(),g=d;h&&(g+="/"+h);h=m.shift()){g=N(Ds.resolve(g));try{De.mkdirSync(g,r),u=u||g}catch{let w=De.lstatSync(g);if(w.isDirectory())continue;if(l){De.unlinkSync(g),De.mkdirSync(g,r),u=u||g;continue}else if(w.isSymbolicLink())return new zs(g,g+"/"+m.join("/"))}}return p(u)},Ta=Object.create(null),hu=1e4,jn=new Set,Gy=t=>{jn.has(t)?jn.delete(t):Ta[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),jn.add(t);let e=Ta[t],n=jn.size-hu;if(n>hu/10){for(let r of jn)if(jn.delete(r),delete Ta[r],--n<=0)break}return e},Hy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,jy=Hy==="win32",Wy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let r=e.at(-1);return r!==void 0&&(n=Qu(r,n)),e.push(n||"/"),e},[]),qy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=jy?["win32 parallelization disabled"]:t.map(r=>Yr(Qu(Gy(r))));let n=new Set(t.map(r=>Wy(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}},Jy=()=>process.umask(),pu=Symbol("onEntry"),ja=Symbol("checkFs"),gu=Symbol("checkFs2"),Wa=Symbol("isReusable"),Be=Symbol("makeFs"),qa=Symbol("file"),Ja=Symbol("directory"),As=Symbol("link"),mu=Symbol("symlink"),wu=Symbol("hardlink"),Kr=Symbol("ensureNoSymlink"),yu=Symbol("unsupported"),_u=Symbol("checkPath"),Ra=Symbol("stripAbsolutePath"),Ut=Symbol("mkdir"),he=Symbol("onError"),ws=Symbol("pending"),Eu=Symbol("pend"),Wn=Symbol("unpend"),ka=Symbol("ended"),ba=Symbol("maybeClose"),Va=Symbol("skip"),ei=Symbol("doChown"),ti=Symbol("uid"),ni=Symbol("gid"),ri=Symbol("checkedCwd"),Vy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ii=Vy==="win32",Zy=1024,Ky=(t,e)=>{if(!ii)return B.unlink(t,e);let n=t+".DELETE."+$u(16).toString("hex");B.rename(t,n,r=>{if(r)return e(r);B.unlink(n,e)})},Xy=t=>{if(!ii)return B.unlinkSync(t);let e=t+".DELETE."+$u(16).toString("hex");B.renameSync(t,e),B.unlinkSync(e)},Su=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,ic=class extends si{[ka]=!1;[ri]=!1;[ws]=0;reservations=new qy;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[ka]=!0,this[ba]()},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:Zy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||ii,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=N(se.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Jy():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[pu](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[ba](){this[ka]&&this[ws]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Ra](t,e){let n=t[e],{type:r}=t;if(!n||this.preservePaths)return!0;let[i,s]=ec(n),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||ii&&/^[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=se.posix.dirname(t.path),c=se.posix.normalize(se.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}[_u](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[Ra](t,"path")||!this[Ra](t,"linkpath"))return!1;if(t.absolute=se.isAbsolute(t.path)?N(se.resolve(t.path)):N(se.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}=se.win32.parse(String(t.absolute));t.absolute=r+tu(String(t.absolute).slice(r.length));let{root:i}=se.win32.parse(t.path);t.path=i+tu(t.path.slice(i.length))}return!0}[pu](t){if(!this[_u](t))return t.resume();switch(Oy.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[ja](t);default:return this[yu](t)}}[he](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Wn](),e.resume())}[Ut](t,e,n){Uy(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)}[ei](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}[ti](t){return Su(this.uid,t.uid,this.processUid)}[ni](t){return Su(this.gid,t.gid,this.processGid)}[qa](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new Ns(String(t.absolute),{flags:Vu(t.size),mode:n,autoClose:!1});r.on("error",a=>{r.fd&&B.close(r.fd,()=>{}),r.write=()=>!0,this[he](a,t),e()});let i=1,s=a=>{if(a){r.fd&&B.close(r.fd,()=>{}),this[he](a,t),e();return}--i===0&&r.fd!==void 0&&B.close(r.fd,c=>{c?this[he](c,t):this[Wn](),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;B.futimes(c,l,d,p=>p?B.utimes(a,l,d,m=>s(m&&p)):s())}if(typeof c=="number"&&this[ei](t)){i++;let l=this[ti](t),d=this[ni](t);typeof l=="number"&&typeof d=="number"&&B.fchown(c,l,d,p=>p?B.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[he](a,t),e()}),t.pipe(o)),o.pipe(r)}[Ja](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Ut](String(t.absolute),n,r=>{if(r){this[he](r,t),e();return}let i=1,s=()=>{--i===0&&(e(),this[Wn](),t.resume())};t.mtime&&!this.noMtime&&(i++,B.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[ei](t)&&(i++,B.chown(String(t.absolute),Number(this[ti](t)),Number(this[ni](t)),s)),s()})}[yu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[mu](t,e){let n=N(se.relative(this.cwd,se.resolve(se.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Kr](t,this.cwd,n,()=>this[As](t,String(t.linkpath),"symlink",e),r=>{this[he](r,t),e()})}[wu](t,e){let n=N(se.resolve(this.cwd,String(t.linkpath))),r=N(String(t.linkpath)).split("/");this[Kr](t,this.cwd,r,()=>this[As](t,n,"link",e),i=>{this[he](i,t),e()})}[Kr](t,e,n,r,i){let s=n.shift();if(this.preservePaths||s===void 0)return r();let o=se.resolve(e,s);B.lstat(o,(a,c)=>{if(a)return r();if(c?.isSymbolicLink())return i(new zs(o,se.resolve(o,n.join("/"))));this[Kr](t,o,n,r,i)})}[Eu](){this[ws]++}[Wn](){this[ws]--,this[ba]()}[Va](t){this[Wn](),t.resume()}[Wa](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!ii}[ja](t){this[Eu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[gu](t,n))}[gu](t,e){let n=o=>{e(o)},r=()=>{this[Ut](this.cwd,this.dmode,o=>{if(o){this[he](o,t),n();return}this[ri]=!0,i()})},i=()=>{if(t.absolute!==this.cwd){let o=N(se.dirname(String(t.absolute)));if(o!==this.cwd)return this[Ut](o,this.dmode,a=>{if(a){this[he](a,t),n();return}s()})}s()},s=()=>{B.lstat(String(t.absolute),(o,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[Va](t),n();return}if(o||this[Wa](t,a))return this[Be](null,t,n);if(a.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,l=d=>this[Be](d??null,t,n);return c?B.chmod(String(t.absolute),Number(t.mode),l):l()}if(t.absolute!==this.cwd)return B.rmdir(String(t.absolute),c=>this[Be](c??null,t,n))}if(t.absolute===this.cwd)return this[Be](null,t,n);Ky(String(t.absolute),c=>this[Be](c??null,t,n))})};this[ri]?i():r()}[Be](t,e,n){if(t){this[he](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[qa](e,n);case"Link":return this[wu](e,n);case"SymbolicLink":return this[mu](e,n);case"Directory":case"GNUDumpDir":return this[Ja](e,n)}}[As](t,e,n,r){B[n](e,String(t.absolute),i=>{i?this[he](i,t):(this[Wn](),t.resume()),r()})}},Vr=t=>{try{return[null,t()]}catch(e){return[e,null]}},ef=class extends ic{sync=!0;[Be](t,e){return super[Be](t,e,()=>{})}[ja](t){if(!this[ri]){let i=this[Ut](this.cwd,this.dmode);if(i)return this[he](i,t);this[ri]=!0}if(t.absolute!==this.cwd){let i=N(se.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[Ut](i,this.dmode);if(s)return this[he](s,t)}}let[e,n]=Vr(()=>B.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Va](t);if(e||this[Wa](t,n))return this[Be](null,t);if(n.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[o]=s?Vr(()=>{B.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[Be](o,t)}let[i]=Vr(()=>B.rmdirSync(String(t.absolute)));this[Be](i,t)}let[r]=t.absolute===this.cwd?[]:Vr(()=>Xy(String(t.absolute)));this[Be](r,t)}[qa](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,r=o=>{let a;try{B.closeSync(i)}catch(c){a=c}(o||a)&&this[he](o||a,t),e()},i;try{i=B.openSync(String(t.absolute),Vu(t.size),n)}catch(o){return r(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[he](o,t)),t.pipe(s)),s.on("data",o=>{try{B.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{B.futimesSync(i,a,c)}catch(l){try{B.utimesSync(String(t.absolute),a,c)}catch{o=l}}}if(this[ei](t)){let a=this[ti](t),c=this[ni](t);try{B.fchownSync(i,Number(a),Number(c))}catch(l){try{B.chownSync(String(t.absolute),Number(a),Number(c))}catch{o=o||l}}}r(o)})}[Ja](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[Ut](String(t.absolute),n);if(r){this[he](r,t),e();return}if(t.mtime&&!this.noMtime)try{B.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[ei](t))try{B.chownSync(String(t.absolute),Number(this[ti](t)),Number(this[ni](t)))}catch{}e(),t.resume()}[Ut](t,e){try{return $y(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}}[Kr](t,e,n,r,i){if(this.preservePaths||n.length===0)return r();let s=e;for(let o of n){s=se.resolve(s,o);let[a,c]=Vr(()=>B.lstatSync(s));if(a)return r();if(c.isSymbolicLink())return i(new zs(s,se.resolve(e,n.join("/"))))}r()}[As](t,e,n,r){let i=`${n}Sync`;try{B[i](e,String(t.absolute)),r(),t.resume()}catch(s){return this[he](s,t)}}},Yy=t=>{let e=new ef(t),n=t.file,r=zu.statSync(n),i=t.maxReadSize||16*1024*1024;new yw(n,{readSize:i,size:r.size}).pipe(e)},Qy=(t,e)=>{let n=new ic(t),r=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{n.on("error",o),n.on("close",s),zu.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ka(i,{readSize:r,size:c.size});l.on("error",o),l.pipe(n)}})})},tf=oi(Yy,Qy,t=>new ef(t),t=>new ic(t),(t,e)=>{e?.length&&Du(t,e)}),e_=(t,e)=>{let n=new rc(t),r=!0,i,s;try{try{i=Ce.openSync(t.file,"r+")}catch(c){if(c?.code==="ENOENT")i=Ce.openSync(t.file,"w+");else throw c}let o=Ce.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=Ce.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 mn(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,t_(t,n,s,i,e)}finally{if(r)try{Ce.closeSync(i)}catch{}}},t_=(t,e,n,r,i)=>{let s=new Tu(t.file,{fd:r,start:n});e.pipe(s),r_(e,i)},n_=(t,e)=>{e=Array.from(e);let n=new Bs(t),r=(i,s,o)=>{let a=(m,u)=>{m?Ce.close(i,h=>o(m)):o(null,u)},c=0;if(s===0)return a(null,0);let l=0,d=Buffer.alloc(512),p=(m,u)=>{if(m||u===void 0)return a(m);if(l+=u,l<512&&u)return Ce.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 mn(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,Ce.read(i,d,0,512,c,p)};Ce.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+",Ce.open(t.file,o,a);if(c||!l)return s(c);Ce.fstat(l,(d,p)=>{if(d)return Ce.close(l,()=>s(d));r(l,p.size,(m,u)=>{if(m)return s(m);let h=new Ns(t.file,{fd:l,start:u});n.pipe(h),h.on("error",s),h.on("close",i),i_(n,e)})})};Ce.open(t.file,o,a)})},r_=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Qn({file:nf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n)}),t.end()},i_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Qn({file:nf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n);t.end()},Zr=oi(e_,n_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!kw(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")}),Bk=oi(Zr.syncFile,Zr.asyncFile,Zr.syncNoFile,Zr.asyncNoFile,(t,e=[])=>{Zr.validate?.(t,e),s_(t)}),s_=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))};At();var Ze={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 ai(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function rf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function sc(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function sf(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function er(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Te();F();re();Te();function vt(t,e){if(ai(t)!=="cloud")throw new _("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function $s(t){return t.startsWith("http://")||t.startsWith("https://")}function Gs(t){return t.endsWith("/")?t.slice(0,-1):t}Te();F();var Hs="1008033",of="1289";var af="pbbp2",cf="https://www.coze.cn",lf="/api/coze_claw/resource/get_frontier_key",a_="https://www.coze.cn",c_="wss://frontier.coze.cn";function js(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??a_}function df(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??c_}function tr(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 li(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var ci=b("handshake");async function oc(t){let e=js(t.endpoint),n=t.timeoutMs??1e4,r=`${Gs(e)}${lf}?aid=${encodeURIComponent(Hs)}`,i={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...tr(t.ppeOverride)},s=new AbortController,o=setTimeout(()=>s.abort(),n);ci.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,u=typeof p.device_id=="string"&&p.device_id||typeof p.deviceId=="string"&&p.deviceId||void 0;if(!m||!u){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 ci.info("handshake ok",{remoteDeviceId:u,logid:c,traceId:l}),{accessKey:m,deviceId:u}}catch(a){if(a instanceof _)throw ci.error("handshake failed (bridge error)",{base:e,message:a.message,code:a.code}),a;if(a.name==="AbortError")throw ci.warn("handshake timeout",{base:e,timeoutMs:n}),new _("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:a});let c=a.cause;throw ci.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 ac=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ke="auto",uf=2e5;function ff(t){return{model:cc(t.model)??Ke,...t.modelToken?{modelToken:t.modelToken}:{}}}function hf(t){return!t||t===Ke}var l_=new Set(["auto","\u81EA\u52A8"]);function cc(t){let e=t?.trim();if(e)return l_.has(e.toLowerCase())?Ke:e}function pf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=ac,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Ke;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else hf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function gf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Ke}"`):hf(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="${ac}/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??uf;e.push("-c",`model_context_window=${n}`)}return e}function mf(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function lc(t,e){let{ttEnv:n,usePpe:r}=li(t),i={};return n&&(i["x-tt-env"]=n),r&&(i["x-use-ppe"]=r),e&&(i["x-mock-scenario"]=e),i}function wf(t,e,n){if(!t.modelToken)return{};let r=lc(e,n);return Object.keys(r).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(r).map(([s,o])=>`${s}:${o}`).join(`
92
- `)}}function dc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function yf(t,e,n){if(!t.modelToken)return null;let r=t.model||Ke,i=lc(e,n),s=["text"];t.modelInfo?.capabilities?.image===!0&&s.push("image");let o={baseUrl:`${ac}/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??uf,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(o.headers=i),o}function _f(t,e,n){if(!t.modelToken)return[];let r=lc(e,n),i=[];for(let[s,o]of Object.entries(r))i.push("-c",`model_providers.coze.http_headers.${s}="${o}"`);return i}var oe=b("agent-handlers"),Ef=5*1024*1024,g_=1,m_=6,w_=new Set(["node_modules",".git",".coze","dist","build",".next"]),Ws=class{constructor(e){this.opts=e}opts;async listSkills(e){vt(e._meta,"_agent/listSkills");let n=er(e._meta),r=await this.loadAgentCfg(n),i=r?.workspace??be(n).workspace,s=r?.skills??[],o=[];for(let a of s){let c=at(i,a.relPath,"SKILL.md");await f_(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(v_(a))}return{skills:o}}async addSkills(e){vt(e._meta,"_agent/addSkills");let n=er(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 wc({agentId:n,workspace:r.workspace,framework:r.framework,skill:c});yc(s,o,l),a.push(c)}return await Ki(n,s),this.reloadAgentSessions(n,"skills-added"),{installedSkills:a}}async removeSkills(e){vt(e._meta,"_agent/removeSkills");let n=er(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=at(r.workspace,a.relPath);await u_(c,{recursive:!0,force:!0}),oe.info("skill removed",{agentId:n,skillId:a.skillId,relPath:a.relPath})}return await Ki(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,oe.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,oe.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:r.framework,cloudId:i,acpId:o}),c.stop(n).catch(l=>oe.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 oe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,r=await me(n);if(!r)throw new _("AGENT_NOT_FOUND",`agent not found: ${n}`);if(r.cozeIdentity===e.cozeIdentity)return oe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Mn(r.workspace,r.framework,e.cozeIdentity)}catch(i){throw oe.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 Ae(r),oe.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 me(n);return r?(r.disconnectedAt=Date.now(),r.disconnectReason=e.reason??"",await Ae(r),oe.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}):(oe.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async switchModel(e){if(vt(e._meta,"_agent/switchModel"),!e.agentId)throw new _("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=cc(e.model)??Ke,r=await me(e.agentId);if(!r)throw new _("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);r.model=n,e.modelInfo&&(r.modelInfo=e.modelInfo),await Ae(r),oe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let i=this.opts.agents.get(e.agentId);if(!i)return oe.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=>oe.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),oe.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(vt(e._meta,Ze.RESET),!e.agentId)throw new _("IPC_BAD_REQUEST",`${Ze.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,Ze.RESET),await this.runDetailSync(e.agentId,Ze.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let r=this.opts.agents.get(e);if(!r){await this.clearPersistedAcpSessionIds(e),oe.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 Nr(e,i)}async clearPersistedAcpSessionIds(e){let n=await me(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 Ae(n)}async repairAgent(e){if(vt(e._meta,Ze.REPAIR),!e.agentId)throw new _("IPC_BAD_REQUEST",`${Ze.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new _("IPC_BAD_REQUEST",`${Ze.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(r){oe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(r)})}return await this.runDetailSync(e.agentId,Ze.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,r){if(!this.opts.detailSyncer){oe.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(i){oe.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:r,err:String(i)})}}async getFileTree(e){vt(e._meta,"_agent/getFileTree");let n=e._meta,r=er(n),i=await this.resolveWorkspace(r),s=e.filePath??"",o=this.safeJoin(i,s),a=await uc(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 Dr(o,i))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${s}`);let c=D_(e.depth);return a.isDirectory()?{tree:await C_(i,o,s,c)}:{tree:[{name:N_(s),path:bf(s||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){vt(e._meta,"_agent/getFileContent");let n=er(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 uc(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 Dr(i,r))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(s.size>Ef)throw new _("IPC_BAD_REQUEST",`file too large: ${s.size} bytes (max ${Ef})`);let o=await Sf(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 me(e).catch(()=>null))?.workspace??be(e).workspace}safeJoin(e,n){let r=pc(e,n||"."),i=mc(e,r);if(i.startsWith("..")||i===".."||i.startsWith(`..${vf}`))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return r}loadAgentCfg(e){return me(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 y_(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 __(t){return t==="claude-code"?at(".claude","skills"):at(".agents","skills")}var E_=3e4,S_=50*1024*1024,nr=3e4;async function wc(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=y_(i.skillName),c=__(r),l=at(c,a),d=at(n,l);if(await fc(d,{recursive:!0}),s){let m=Buffer.from(i.content,"utf8");di(m.length),await hc(at(d,"SKILL.md"),m,"utf8")}else{let m=await I_(i.downloadUrl);R_(m)?await x_(m,d):k_(m)?await b_(m,d):await hc(at(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 oe.info("skill installed",{agentId:e,skillId:i.skillId,skillName:i.skillName,relPath:l,source:s?"content":"downloadUrl"}),p}function yc(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 v_(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 I_(t){if(!t)throw new _("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);di(e);let n=T_(t);return di(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Sf(e);return di(n.length),n}if($s(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),E_);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 di(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 di(t){if(t>S_)throw new _("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function T_(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 R_(t){return t.length>=2&&t[0]===31&&t[1]===139}function k_(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 gc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function b_(t,e){let n,r;try{n=new Rf.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||gc(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=A_(r),s=pc(e);for(let o of r){if(gc(o.entryName))continue;let a=o.entryName;if(i&&a.startsWith(i)&&(a=a.slice(i.length)),!a)continue;let c=pc(e,a),l=mc(s,c);if(l.startsWith("..")||l==="..")throw new _("IPC_BAD_REQUEST",`zip entry escapes destDir: ${a}`);if(o.isDirectory){await fc(c,{recursive:!0});continue}await fc(h_(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 hc(c,d)}}function A_(t){let e;for(let n of t){let r=n.entryName;if(!r||gc(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 x_(t,e){await O_(t);let n=tf({cwd:e,strip:1}),r=!1,i=setTimeout(()=>{r=!0,n.destroy(new _("IPC_BAD_REQUEST",`tar extract timeout (${nr}ms)`))},nr);try{await Tf(If.from(t),n)}catch(s){throw s instanceof _?s:r?new _("IPC_BAD_REQUEST",`tar extract timeout (${nr}ms)`):new _("IPC_BAD_REQUEST",`tar extract failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}}async function O_(t){let e=[],n=Qn({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 (${nr}ms)`))},nr);try{await Tf(If.from(t),n)}catch(s){throw r?new _("IPC_BAD_REQUEST",`tar list timeout (${nr}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 C_(t,e,n,r){return kf(t,e,n,r,{count:0})}async function kf(t,e,n,r,i){if(r<=0)return[];let s;try{s=await d_(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let a of s){if(w_.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=at(e,a.name),l=p_(at(n,a.name)),d=null;try{d=await uc(c)}catch{continue}if(d.isSymbolicLink())continue;i.count++;let p={name:a.name,path:bf(mc(t,c)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&r>1&&(p.children=await kf(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 D_(t){return!t||t<=0?g_:Math.min(t,m_)}function N_(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function bf(t){return t.split(vf).join("/")}F();import{readFileSync as Vb}from"node:fs";import{dirname as Kb,join as Xb}from"node:path";import{fileURLToPath as Qb}from"node:url";var rr="0.1.93-beta.1";var Gt=b("agent-health-reporter"),L_=1e4,ui=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??L_}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()}),Gt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Gt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Gt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Gt.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=F_(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:rr,_meta:{cozeDeviceId:e}},i;try{i=await this.opts.core.sendRequest("_agent/health",r,5e3)}catch(o){Gt.warn("heartbeat batch send failed",{count:n.length,err:String(o)})}let s=i?.authFailures;if(s&&s.length>0&&(Gt.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){Gt.warn("onAuthFailures callback failed (ignored)",{err:String(o)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Gt.warn("onTickEnd hook failed",{err:String(n)})}}};function F_(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}At();import{chmod as yE,mkdir as eo,rm as _E,stat as EE,writeFile as SE}from"node:fs/promises";import{homedir as vE}from"node:os";import{join as Vf}from"node:path";nn();import{spawnSync as q_}from"node:child_process";function fi(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function ir(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function sr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Ht(t,e){return{jsonrpc:"2.0",id:t,error:e}}Te();var qs=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)}},U={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 Af(t){return"method"in t&&"id"in t&&t.id!==void 0}function xf(t){return"method"in t&&!("id"in t)}function Js(t){return!("method"in t)&&"id"in t}var M_={AGENT_NOT_FOUND:U.AGENT_NOT_FOUND,AGENT_BUSY:U.AGENT_BUSY,AGENT_DISCONNECTED:U.AGENT_DISCONNECTED,AGENT_TIMEOUT:U.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:U.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:U.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:U.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:U.INTERNAL_ERROR,BRIDGE_INTERNAL:U.INTERNAL_ERROR,IPC_AUTH_FAILED:U.INTERNAL_ERROR,IPC_BAD_REQUEST:U.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:U.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:U.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:U.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:U.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:U.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:U.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:U.FILE_TOO_LARGE,UNSUPPORTED_MIME:U.UNSUPPORTED_MIME,UPLOAD_FAILED:U.UPLOAD_FAILED,UPSTREAM_NOT_READY:U.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:U.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:U.AGENT_APPROVAL_TIMEOUT};function B_(t){if(t!=null)return t instanceof Error?{name:t.name,message:hi(t.message)}:typeof t=="string"?hi(t):typeof t=="object"?z_(t):t}var U_=[[/\/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 hi(t){let e=t;for(let[n,r]of U_)e=e.replace(n,r);return e}function z_(t){let e={};for(let[n,r]of Object.entries(t))typeof r=="string"?e[n]=hi(r):e[n]=r;return e}function pi(t){if(t instanceof _){let e=B_(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),{code:M_[t.code]??U.INTERNAL_ERROR,message:hi(t.message),data:n}}return{code:U.INTERNAL_ERROR,message:hi(t instanceof Error?t.message:String(t))}}function Of(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 Cf(t){return`${JSON.stringify(t)}
93
- `}var Pf=10*1024*1024,Vs=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>Pf){let i=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${i} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${Pf} bytes`)}),[]}let n=this.buffer.split(`
94
- `);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 Nf={"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"},dA=Object.fromEntries(Object.entries(Nf).map(([t,e])=>[e,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:[]},or=class{seq=0;next(e,n){this.seq+=1;let r=Nf[e]??G_(e),i=$_[r]??[],s=[r,String(this.seq)];if(i.length>0){let o=i.map(c=>Df(n?.[c]??"")),a=H_(o).join(":");a&&s.push(a)}else n&&Object.values(n).some(o=>o)&&s.push(Object.values(n).filter(Boolean).map(o=>Df(String(o))).join(":"));return s.join("_")}reset(){this.seq=0}};function G_(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Df(t){return t.replace(/[:_\s]+/g,"-")}function H_(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Cr();import{readFileSync as j_}from"node:fs";var W_=384;async function _c(t,e=process.env){let n={};for(let[r,i]of Object.entries(e))typeof i=="string"&&(n[r]=i);await Fn(t.agentEnvFile,n,{mode:W_})}function Ec(t){try{let e=JSON.parse(j_(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Lf(t,e,n={},r=i=>i){return{...r({...t,...Ec(e)}),...n}}gt();zi();Te();F();re();var J_=pt("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),V_=200,Z_=pt("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),K_=pt("COZE_BRIDGE_SESSION_PROMPT_FRAME_IDLE_MS",600*1e3),X_=pt("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ff=500;function Y_(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ff?t:`${e.slice(0,Ff)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Mf(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),q_("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ct=class{constructor(e){this.opts=e;this.log=b(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Vs({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new or;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=Fe(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:Lf(process.env,this.opts.agentEnvFile??L().agentEnvFile,this.opts.env,r=>this.sanitizeEnv(r)),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>V_&&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()));Mf(n.pid,"SIGTERM");let i=setTimeout(()=>{n.killed||Mf(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=Z_,r=K_,i=X_){return this.call("session/prompt",e,n,r,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(ir("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(sr(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(Ht(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=J_,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=fi(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 u={resolve:p,reject:m,timer:null,frameIdleTimer:null,armFrameIdle:null,method:e},h=Date.now();if(l){let w=()=>{u.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),u.frameIdleTimer&&clearTimeout(u.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?()=>{u.frameIdleTimer&&clearTimeout(u.frameIdleTimer),u.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}u.timer&&clearTimeout(u.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;u.armFrameIdle=g,this.pending.set(o,u),g?.();try{this.writeFrame(a)}catch(w){u.timer&&clearTimeout(u.timer),u.frameIdleTimer&&clearTimeout(u.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(Cf(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(Js(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(Of(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:Y_(e.result)}),n.resolve(e.result));return}if(xf(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(Af(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(Ht(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(Ht(e.id,pi(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 Q_(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 Zs=class extends ct{framework="claude-code";constructor(e){let n=Pr("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 Q_(e)}};nn();import{mkdtempSync as eE,rmSync as tE}from"node:fs";import{tmpdir as nE}from"node:os";import{join as rE}from"node:path";var Ks=class extends ct{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=Pr("codex",e.command),r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,s=e.isolateCodexHome?eE(rE(nE(),"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{tE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var iE=3e4,ar=class extends ct{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}`}]},iE))}get acpSessionName(){return this.sessionName}};Te();F();re();function Sc(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}nn();var jt=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 Xs=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 jt,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)gi(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 gi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}gt();F();import{promises as vc}from"node:fs";import{join as sE}from"node:path";var yn=b("agents.codex-sandbox-installer"),Bf="@openai/codex@0.135.0",Uf="https://registry.npmmirror.com",Ic="/usr/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex",oE="/usr/bin",zf=["apply_patch","applypatch","codex-execve-wrapper","codex-linux-sandbox"],aE=9e4,cE=5e3,mi=null,$f=!1;async function Gf(t,e={}){if((e.platform??process.platform)!=="linux"||$f)return;if(mi)return mi;let r=e.exec??Cn,i=e.statFile??(async a=>{try{return await vc.stat(a),!0}catch{return!1}}),s=e.symlink??((a,c)=>vc.symlink(a,c)),o=e.unlink??(a=>vc.unlink(a));return mi=(async()=>{try{let a=!1;try{let{stdout:l}=await r("which",["codex"],{timeout:cE});a=l.trim().length>0}catch{a=!1}if(a)yn.info("codex already present, skip install");else{yn.info("codex not found, installing",{package:Bf,registry:Uf});try{await r("npm",["i","-g",Bf,`--registry=${Uf}`],{timeout:aE,maxBuffer:10*1024*1024,signal:t}),yn.info("codex install ok")}catch(l){yn.warn("codex install failed (skip symlinks)",{err:String(l)});return}}if(!await i(Ic)){yn.warn("codex vendor bin not found, skip symlinks",{target:Ic});return}let c=0;for(let l of zf){let d=sE(oE,l);try{await o(d).catch(()=>{}),await s(Ic,d),c+=1,yn.info("codex sandbox symlink created",{link:d})}catch(p){yn.warn("codex sandbox symlink failed (ignored)",{link:d,err:String(p)})}}c===zf.length&&($f=!0)}finally{mi=null}})(),mi}gt();F();import{constants as Hf,access as lE}from"node:fs/promises";import{delimiter as dE,join as uE}from"node:path";var Wt=b("framework-detector"),jf={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},fE=[".exe",".cmd",".bat",".ps1"],qt=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Fe,access:e.access??lE}}async detect(e){let n=jf[e],r=await this.which(n);if(!r)return Wt.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(jf).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(dE).filter(Boolean),r=this.env.platform==="win32"?["",...fE]:[""];for(let i of n)for(let s of r){let o=uE(i,e+s);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Hf.F_OK:Hf.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 Wt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return Wt.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 Wt.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 Wt.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?(Wt.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}:(Wt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:i.length}),null)}catch(i){return Wt.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&&(pE(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)}})}},hE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function pE(t){return t.replace(hE,"")}import{homedir as gE}from"node:os";import{join as mE}from"node:path";gt();Te();Cr();F();async function Jf(){let t=mE(gE(),".openclaw/openclaw.json");return(await Ln(t))?.gateway?.auth?.token??""}var Wf=b("openclaw.config"),wE=[0,5e3,5e3],qf="models.providers.",Ys="agents.defaults.models",Qs=class{command;env;retryDelaysMs;queue=new jt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??wE}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,Wf.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=Fe(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){Wf.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",`${qf}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${qf}${e}`)}addModelToAllowlist(e,n){let r={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Ys}[${e}]`,()=>this.runCli(["config","set",Ys,JSON.stringify(r),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Ys}[${e}]`,`${Ys}.${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 K=b("agent-manager"),IE=(t,e,n,r,i,s,o,a,c)=>{switch(t){case"claude-code":{let l={...i?{...pf(i),...wf(i,o,a)}:{},...c??{},IS_SANDBOX:"1"};return new Zs({cwd:n,env:l,agentId:r})}case"codex":{let d=[...i?[...gf(i),..._f(i,o,a)]:[],"-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"'],p={...i?mf(i):{},...c??{}},m=!!i;return new Ks({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 ar({command:e,cwd:n,agentId:r,...s?{sessionName:Sc(s)}:{}})}};function Tc(t){return t==="claude-code"||t==="codex"}function TE(t){let e=[],n=Object.keys(t).sort();for(let r of n){let i=t[r];i!==void 0&&(RE(i)||e.push(`${r}=${i}`))}return e.length===0?"":`${e.join(`
91
+ `).reduce(sy,Object.create(null)),sy=(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},oy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,N=oy!=="win32"?t=>t:t=>t&&t.replaceAll(/\\/g,"/"),Cu=class extends mn{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))))}},Ls=(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))},ay=1024*1024,Pa=Buffer.from([31,139]),Ca=Buffer.from([40,181,47,253]),cy=Math.max(Pa.length,Ca.length),Me=Symbol("state"),cn=Symbol("writeEntry"),yt=Symbol("readEntry"),ma=Symbol("nextEntry"),Vd=Symbol("processEntry"),rt=Symbol("extendedHeader"),$r=Symbol("globalExtendedHeader"),Pt=Symbol("meta"),Zd=Symbol("emitMeta"),W=Symbol("buffer"),_t=Symbol("queue"),Ct=Symbol("ended"),wa=Symbol("emittedEnd"),ln=Symbol("emit"),te=Symbol("unzip"),ls=Symbol("consumeChunk"),ds=Symbol("consumeChunkSub"),ya=Symbol("consumeBody"),Kd=Symbol("consumeMeta"),Xd=Symbol("consumeHeader"),Gr=Symbol("consuming"),_a=Symbol("bufferConcat"),us=Symbol("maybeEnd"),Hn=Symbol("writing"),Dt=Symbol("aborted"),fs=Symbol("onDone"),dn=Symbol("sawValidEntry"),hs=Symbol("sawNullBlock"),ps=Symbol("sawEOF"),Yd=Symbol("closeStream"),ly=()=>!0,ii=class extends Aw{file;strict;maxMetaEntrySize;filter;brotli;zstd;writable=!0;readable=!1;[_t]=[];[W];[yt];[cn];[Me]="begin";[Pt]="";[rt];[$r];[Ct]=!1;[te];[Dt]=!1;[dn];[hs]=!1;[ps]=!1;[Hn]=!1;[Gr]=!1;[wa]=!1;constructor(t={}){super(),this.file=t.file||"",this.on(fs,()=>{(this[Me]==="begin"||this[dn]===!1)&&this.warn("TAR_BAD_ARCHIVE","Unrecognized archive format")}),t.ondone?this.on(fs,t.ondone):this.on(fs,()=>{this.emit("prefinish"),this.emit("finish"),this.emit("end")}),this.strict=!!t.strict,this.maxMetaEntrySize=t.maxMetaEntrySize||ay,this.filter=typeof t.filter=="function"?t.filter:ly;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[Yd]()),typeof t.onwarn=="function"&&this.on("warn",t.onwarn),typeof t.onReadEntry=="function"&&this.on("entry",t.onReadEntry)}warn(t,e,n={}){Ls(this,t,e,n)}[Xd](t,e){this[dn]===void 0&&(this[dn]=!1);let n;try{n=new gn(t,e,this[rt],this[$r])}catch(r){return this.warn("TAR_ENTRY_INVALID",r)}if(n.nullBlock)this[hs]?(this[ps]=!0,this[Me]==="begin"&&(this[Me]="header"),this[ln]("eof")):(this[hs]=!0,this[ln]("nullBlock"));else if(this[hs]=!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[cn]=new Cu(n,this[rt],this[$r]);if(!this[dn])if(i.remain){let s=()=>{i.invalid||(this[dn]=!0)};i.on("end",s)}else this[dn]=!0;i.meta?i.size>this.maxMetaEntrySize?(i.ignore=!0,this[ln]("ignoredEntry",i),this[Me]="ignore",i.resume()):i.size>0&&(this[Pt]="",i.on("data",s=>this[Pt]+=s),this[Me]="meta"):(this[rt]=void 0,i.ignore=i.ignore||!this.filter(i.path,i),i.ignore?(this[ln]("ignoredEntry",i),this[Me]=i.remain?"ignore":"header",i.resume()):(i.remain?this[Me]="body":(this[Me]="header",i.end()),this[yt]?this[_t].push(i):(this[_t].push(i),this[ma]())))}}}[Yd](){queueMicrotask(()=>this.emit("close"))}[Vd](t){let e=!0;if(!t)this[yt]=void 0,e=!1;else if(Array.isArray(t)){let[n,...r]=t;this.emit(n,...r)}else this[yt]=t,this.emit("entry",t),t.emittedEnd||(t.on("end",()=>this[ma]()),e=!1);return e}[ma](){do;while(this[Vd](this[_t].shift()));if(this[_t].length===0){let t=this[yt];!t||t.flowing||t.size===t.remain?this[Hn]||this.emit("drain"):t.once("drain",()=>this.emit("drain"))}}[ya](t,e){let n=this[cn];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[Me]="header",this[cn]=void 0,n.end()),i.length}[Kd](t,e){let n=this[cn],r=this[ya](t,e);return!this[cn]&&n&&this[Zd](n),r}[ln](t,e,n){this[_t].length===0&&!this[yt]?this.emit(t,e,n):this[_t].push([t,e,n])}[Zd](t){switch(this[ln]("meta",this[Pt]),t.type){case"ExtendedHeader":case"OldExtendedHeader":this[rt]=As.parse(this[Pt],this[rt],!1);break;case"GlobalExtendedHeader":this[$r]=As.parse(this[Pt],this[$r],!0);break;case"NextFileHasLongPath":case"OldGnuLongPath":{let e=this[rt]??Object.create(null);this[rt]=e,e.path=this[Pt].replace(/\0.*/,"");break}case"NextFileHasLongLinkpath":{let e=this[rt]||Object.create(null);this[rt]=e,e.linkpath=this[Pt].replace(/\0.*/,"");break}default:throw new Error("unknown meta: "+t.type)}}abort(t){this[Dt]=!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[Dt])return n?.(),!1;if((this[te]===void 0||this.brotli===void 0&&this[te]===!1)&&t){if(this[W]&&(t=Buffer.concat([this[W],t]),this[W]=void 0),t.length<cy)return this[W]=t,n?.(),!0;for(let o=0;this[te]===void 0&&o<Pa.length;o++)t[o]!==Pa[o]&&(this[te]=!1);let i=!1;if(this[te]===!1&&this.zstd!==!1){i=!0;for(let o=0;o<Ca.length;o++)if(t[o]!==Ca[o]){i=!1;break}}let s=this.brotli===void 0&&!i;if(this[te]===!1&&s)if(t.length<512)if(this[Ct])this.brotli=!0;else return this[W]=t,n?.(),!0;else try{new gn(t.subarray(0,512)),this.brotli=!1}catch{this.brotli=!0}if(this[te]===void 0||this[te]===!1&&(this.brotli||i)){let o=this[Ct];this[Ct]=!1,this[te]=this[te]===void 0?new Nw({}):i?new Bw({}):new Fw({}),this[te].on("data",c=>this[ls](c)),this[te].on("error",c=>this.abort(c)),this[te].on("end",()=>{this[Ct]=!0,this[ls]()}),this[Hn]=!0;let a=!!this[te][o?"end":"write"](t);return this[Hn]=!1,n?.(),a}}this[Hn]=!0,this[te]?this[te].write(t):this[ls](t),this[Hn]=!1;let r=this[_t].length>0?!1:this[yt]?this[yt].flowing:!0;return!r&&this[_t].length===0&&this[yt]?.once("drain",()=>this.emit("drain")),n?.(),r}[_a](t){t&&!this[Dt]&&(this[W]=this[W]?Buffer.concat([this[W],t]):t)}[us](){if(this[Ct]&&!this[wa]&&!this[Dt]&&!this[Gr]){this[wa]=!0;let t=this[cn];if(t&&t.blockRemain){let e=this[W]?this[W].length:0;this.warn("TAR_BAD_ARCHIVE",`Truncated input (needed ${t.blockRemain} more bytes, only ${e} available)`,{entry:t}),this[W]&&t.write(this[W]),t.end()}this[ln](fs)}}[ls](t){if(this[Gr]&&t)this[_a](t);else if(!t&&!this[W])this[us]();else if(t){if(this[Gr]=!0,this[W]){this[_a](t);let e=this[W];this[W]=void 0,this[ds](e)}else this[ds](t);for(;this[W]&&this[W]?.length>=512&&!this[Dt]&&!this[ps];){let e=this[W];this[W]=void 0,this[ds](e)}this[Gr]=!1}(!this[W]||this[Ct])&&this[us]()}[ds](t){let e=0,n=t.length;for(;e+512<=n&&!this[Dt]&&!this[ps];)switch(this[Me]){case"begin":case"header":this[Xd](t,e),e+=512;break;case"ignore":case"body":e+=this[ya](t,e);break;case"meta":e+=this[Kd](t,e);break;default:throw new Error("invalid state: "+this[Me])}e<n&&(this[W]=this[W]?Buffer.concat([t.subarray(e),this[W]]):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[Dt]||(this[te]?(t&&this[te].write(t),this[te].end()):(this[Ct]=!0,(this.brotli===void 0||this.zstd===void 0)&&(t=t||Buffer.alloc(0)),t&&this.write(t),this[us]())),this}},Xr=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)},dy=t=>{let e=t.onReadEntry;t.onReadEntry=e?n=>{e(n),n.resume()}:n=>n.resume()},Du=(t,e)=>{let n=new Map(e.map(s=>[Xr(s),!0])),r=t.filter,i=(s,o="")=>{let a=o||Ew(s).root||".",c;if(s===a)c=!1;else{let l=n.get(s);c=l!==void 0?l:i(_w(s),a)}return n.set(s,c),c};t.filter=r?(s,o)=>r(s,o)&&i(Xr(s)):s=>i(Xr(s))},uy=t=>{let e=new ii(t),n=t.file,r;try{r=Zn.openSync(n,"r");let i=Zn.fstatSync(r),s=t.maxReadSize||16*1024*1024;if(i.size<s){let o=Buffer.allocUnsafe(i.size),a=Zn.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=Zn.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{Zn.closeSync(r)}catch{}}},fy=(t,e)=>{let n=new ii(t),r=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{n.on("error",o),n.on("end",s),Zn.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ka(i,{readSize:r,size:c.size});l.on("error",o),l.pipe(n)}})})},Qn=si(uy,fy,t=>new ii(t),t=>new ii(t),(t,e)=>{e?.length&&Du(t,e),t.noResume||dy(t)}),Nu=(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:py,parse:eu}=hy,ec=t=>{let e="",n=eu(t);for(;py(t)||n.root;){let r=t.charAt(0)==="/"&&t.slice(0,4)!=="//?/"?"/":n.root;t=t.slice(r.length),e+=r,n=eu(t)}return[e,t]},Fs=["|","<",">","?",":"],tc=Fs.map(t=>String.fromCodePoint(61440+Number(t.codePointAt(0)))),gy=new Map(Fs.map((t,e)=>[t,tc[e]])),my=new Map(tc.map((t,e)=>[t,Fs[e]])),tu=t=>Fs.reduce((e,n)=>e.split(n).join(gy.get(n)),t),wy=t=>tc.reduce((e,n)=>e.split(n).join(my.get(n)),t),Lu=(t,e)=>e?(t=N(t).replace(/^\.(\/|$)/,""),Xr(e)+"/"+t):N(t),yy=16*1024*1024,nu=Symbol("process"),ru=Symbol("file"),iu=Symbol("directory"),Da=Symbol("symlink"),su=Symbol("hardlink"),Hr=Symbol("header"),Es=Symbol("read"),Na=Symbol("lstat"),Ss=Symbol("onlstat"),La=Symbol("onread"),Fa=Symbol("onreadlink"),Ma=Symbol("openfile"),Ba=Symbol("onopenfile"),Bt=Symbol("close"),Os=Symbol("mode"),Ua=Symbol("awaitDrain"),Ea=Symbol("ondrain"),st=Symbol("prefix"),Fu=class extends mn{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=Xa(e);super(),this.path=N(t),this.portable=!!n.portable,this.maxReadSize=n.maxReadSize||yy,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]=ec(this.path);s&&typeof o=="string"&&(this.path=o,r=s)}this.win32=!!n.win32||process.platform==="win32",this.win32&&(this.path=wy(this.path.replaceAll(/\\/g,"/")),t=t.replaceAll(/\\/g,"/")),this.absolute=N(n.absolute||Qd.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[Ss](i):this[Na]()}warn(t,e,n={}){return Ls(this,t,e,n)}emit(t,...e){return t==="error"&&(this.#e=!0),super.emit(t,...e)}[Na](){it.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=Sy(t),this.emit("stat",t),this[nu]()}[nu](){switch(this.type){case"File":return this[ru]();case"Directory":return this[iu]();case"SymbolicLink":return this[Da]();default:return this.end()}}[Os](t){return Nu(t,this.type==="Directory",this.portable)}[st](t){return Lu(t,this.prefix)}[Hr](){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 gn({path:this[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](this.linkpath):this.linkpath,mode:this[Os](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 As({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[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](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)}[iu](){if(!this.stat)throw new Error("cannot create directory entry without stat");this.path.slice(-1)!=="/"&&(this.path+="/"),this.stat.size=0,this[Hr](),this.end()}[Da](){it.readlink(this.absolute,(t,e)=>{if(t)return this.emit("error",t);this[Fa](e)})}[Fa](t){this.linkpath=N(t),this[Hr](),this.end()}[su](t){if(!this.stat)throw new Error("cannot create link entry without stat");this.type="Link",this.linkpath=N(Qd.relative(this.cwd,t)),this.stat.size=0,this[Hr](),this.end()}[ru](){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[su](e);this.linkCache.set(t,this.absolute)}if(this[Hr](),this.stat.size===0)return this.end();this[Ma]()}[Ma](){it.open(this.absolute,"r",(t,e)=>{if(t)return this.emit("error",t);this[Ba](e)})}[Ba](t){if(this.fd=t,this.#e)return this[Bt]();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[Es]()}[Es](){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");it.read(t,e,n,r,i,(s,o)=>{if(s)return this[Bt](()=>this.emit("error",s));this[La](o)})}[Bt](t=()=>{}){this.fd!==void 0&&it.close(this.fd,t)}[La](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[Bt](()=>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[Bt](()=>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[Ea]():this[Ua](()=>this[Ea]())}[Ua](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)}[Ea](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[Bt](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[Es]()}},_y=class extends Fu{sync=!0;[Na](){this[Ss](it.lstatSync(this.absolute))}[Da](){this[Fa](it.readlinkSync(this.absolute))}[Ma](){this[Ba](it.openSync(this.absolute,"r"))}[Es](){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=it.readSync(e,n,r,i,s);this[La](o),t=!1}finally{if(t)try{this[Bt](()=>{})}catch{}}}[Ua](t){t()}[Bt](t=()=>{}){this.fd!==void 0&&it.closeSync(this.fd),t()}},Ey=class extends mn{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 Ls(this,t,e,n)}constructor(t,e={}){let n=Xa(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[Os](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]=ec(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 gn({path:this[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](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 As({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[st](this.path),linkpath:this.type==="Link"&&this.linkpath!==void 0?this[st](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)}[st](t){return Lu(t,this.prefix)}[Os](t){return Nu(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}},Sy=t=>t.isFile()?"File":t.isDirectory()?"Directory":t.isSymbolicLink()?"SymbolicLink":"Unsupported",vy=class Kn{tail;head;length=0;static create(e=[]){return new Kn(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++)Ty(this,e[n]);return this.length}unshift(...e){for(var n=0,r=e.length;n<r;n++)Ry(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 Kn;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 Kn;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 Kn;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 Kn;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=Iy(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 Iy(t,e,n){let r=e,i=e?e.next:t.head,s=new nc(n,r,i,t);return s.next===void 0&&(t.tail=s),s.prev===void 0&&(t.head=s),t.length++,s}function Ty(t,e){t.tail=new nc(e,t.tail,void 0,t),t.head||(t.head=t.tail),t.length++}function Ry(t,e){t.head=new nc(e,void 0,t.head,t),t.tail||(t.tail=t.head),t.length++}var nc=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}},au=class{path;absolute;entry;stat;readdir;pending=!1;pendingLink=!1;ignore=!1;piped=!1;constructor(t,e){this.path=t||"./",this.absolute=e}},cu=Buffer.alloc(1024),vs=Symbol("onStat"),jr=Symbol("ended"),We=Symbol("queue"),Wr=Symbol("queue"),Nt=Symbol("current"),un=Symbol("process"),qr=Symbol("processing"),gs=Symbol("processJob"),qe=Symbol("jobs"),Sa=Symbol("jobDone"),Is=Symbol("addFSEntry"),lu=Symbol("addTarEntry"),za=Symbol("stat"),$a=Symbol("readdir"),Ts=Symbol("onreaddir"),Rs=Symbol("pipe"),du=Symbol("entry"),va=Symbol("entryOpt"),ks=Symbol("writeEntryClass"),Mu=Symbol("write"),Ia=Symbol("ondrain"),Ms=class extends mn{sync=!1;opt;cwd;maxReadSize;preservePaths;strict;noPax;prefix;linkCache;statCache;file;portable;zip;readdirCache;noDirRecurse;follow;noMtime;mtime;filter;jobs;[ks];onWriteEntry;[We];[Wr]=new Map;[qe]=0;[qr]=!1;[jr]=!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[ks]=Fu,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 Dw(t.gzip)),t.brotli&&(typeof t.brotli!="object"&&(t.brotli={}),this.zip=new Lw(t.brotli)),t.zstd&&(typeof t.zstd!="object"&&(t.zstd={}),this.zip=new Mw(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[Ia]()),this.on("resume",()=>e.resume())}else this.on("drain",this[Ia]);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[We]=new vy,this[qe]=0,this.jobs=Number(t.jobs)||4,this[qr]=!1,this[jr]=!1}[Mu](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[jr]=!0,this[un](),n&&n(),this}write(t){if(this[jr])throw new Error("write after end");return t instanceof Cu?this[lu](t):this[Is](t),this.flowing}[lu](t){let e=N(ou.resolve(this.cwd,t.path));if(!this.filter(t.path,t))t.resume();else{let n=new au(t.path,e);n.entry=new Ey(t,this[va](n)),n.entry.on("end",()=>this[Sa](n)),this[qe]+=1,this[We].push(n)}this[un]()}[Is](t){let e=N(ou.resolve(this.cwd,t));this[We].push(new au(t,e)),this[un]()}[za](t){t.pending=!0,this[qe]+=1;let e=this.follow?"stat":"lstat";xs[e](t.absolute,(n,r)=>{t.pending=!1,this[qe]-=1,n?this.emit("error",n):this[vs](t,r)})}[vs](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[Nt])this[gs](t);else{let n=`${e.dev}:${e.ino}`,r=this[Wr].get(n);r?r.push(t):this[Wr].set(n,[t]),t.pendingLink=!0,t.pending=!0}this[un]()}[$a](t){t.pending=!0,this[qe]+=1,xs.readdir(t.absolute,(e,n)=>{if(t.pending=!1,this[qe]-=1,e)return this.emit("error",e);this[Ts](t,n)})}[Ts](t,e){this.readdirCache.set(t.absolute,e),t.readdir=e,this[un]()}[un](){if(!this[qr]){this[qr]=!0;for(let t=this[We].head;t&&this[qe]<this.jobs;t=t.next)if(this[gs](t.value),t.value.ignore){let e=t.next;this[We].removeNode(t),t.next=e}this[qr]=!1,this[jr]&&this[We].length===0&&this[qe]===0&&(this.zip?this.zip.end(cu):(super.write(cu),super.end()))}}get[Nt](){return this[We]&&this[We].head&&this[We].head.value}[Sa](t){this[We].shift(),this[qe]-=1;let{stat:e}=t;if(e&&e.isFile()&&e.nlink>1){let n=`${e.dev}:${e.ino}`,r=this[Wr].get(n);if(r){this[Wr].delete(n);for(let i of r)i.pending=!1,this[gs](i)}}this[un]()}[gs](t){if(t.pending&&t.pendingLink&&t===this[Nt]&&(t.pending=!1,t.pendingLink=!1),!t.pending){if(t.entry){t===this[Nt]&&!t.piped&&this[Rs](t);return}if(!t.stat){let e=this.statCache.get(t.absolute);e?this[vs](t,e):this[za](t)}if(t.stat&&!t.ignore){if(!this.noDirRecurse&&t.stat.isDirectory()&&!t.readdir){let e=this.readdirCache.get(t.absolute);if(e?this[Ts](t,e):this[$a](t),!t.readdir)return}if(t.entry=this[du](t),!t.entry){t.ignore=!0;return}t===this[Nt]&&!t.piped&&this[Rs](t)}}}[va](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}}[du](t){this[qe]+=1;try{return new this[ks](t.path,this[va](t)).on("end",()=>this[Sa](t)).on("error",e=>this.emit("error",e))}catch(e){this.emit("error",e)}}[Ia](){this[Nt]&&this[Nt].entry&&this[Nt].entry.resume()}[Rs](t){t.piped=!0,t.readdir&&t.readdir.forEach(r=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[Is](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={}){Ls(this,t,e,n)}},rc=class extends Ms{sync=!0;constructor(t){super(t),this[ks]=_y}pause(){}resume(){}[za](t){let e=this.follow?"statSync":"lstatSync";this[vs](t,xs[e](t.absolute))}[$a](t){this[Ts](t,xs.readdirSync(t.absolute))}[Rs](t){let e=t.entry,n=this.zip;if(t.readdir&&t.readdir.forEach(r=>{let i=t.path,s=i==="./"?"":i.replace(/\/*$/,"/");this[Is](s+r)}),!e)throw new Error("Cannot pipe without source");n?e.on("data",r=>{n.write(r)}):e.on("data",r=>{super[Mu](r)})}},ky=(t,e)=>{let n=new rc(t),r=new Tu(t.file,{mode:t.mode||438});n.pipe(r),Bu(n,e)},by=(t,e)=>{let n=new Ms(t),r=new Ds(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 Uu(n,e).catch(s=>n.emit("error",s)),i},Bu=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Qn({file:Ru.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n)}),t.end()},Uu=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Qn({file:Ru.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:r=>{t.add(r)}}):t.add(n);t.end()},Ay=(t,e)=>{let n=new rc(t);return Bu(n,e),n},xy=(t,e)=>{let n=new Ms(t);return Uu(n,e).catch(r=>n.emit("error",r)),n},Ik=si(ky,by,Ay,xy,(t,e)=>{if(!e?.length)throw new TypeError("no paths specified to add to archive")}),Py=process.env.__FAKE_PLATFORM__||process.platform,Hu=Py==="win32",{O_CREAT:ju,O_NOFOLLOW:uu,O_TRUNC:Wu,O_WRONLY:qu}=Gu.constants,Ju=Number(process.env.__FAKE_FS_O_FILENAME__)||Gu.constants.UV_FS_O_FILEMAP||0,Cy=Hu&&!!Ju,Dy=512*1024,Ny=Ju|Wu|ju|qu,fu=!Hu&&typeof uu=="number"?uu|Wu|ju|qu:null,Vu=fu!==null?()=>fu:Cy?t=>t<Dy?Ny:"w":()=>"w",Ga=(t,e,n)=>{try{return Bs.lchownSync(t,e,n)}catch(r){if(r?.code!=="ENOENT")throw r}},Ps=(t,e,n,r)=>{Bs.lchown(t,e,n,i=>{r(i&&i?.code!=="ENOENT"?i:null)})},Ly=(t,e,n,r,i)=>{if(e.isDirectory())Zu(Yr.resolve(t,e.name),n,r,s=>{if(s)return i(s);let o=Yr.resolve(t,e.name);Ps(o,n,r,i)});else{let s=Yr.resolve(t,e.name);Ps(s,n,r,i)}},Zu=(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 Ps(t,e,n,r);let o=s.length,a=null,c=l=>{if(!a){if(l)return r(a=l);if(--o===0)return Ps(t,e,n,r)}};for(let l of s)Ly(t,l,e,n,c)})},Fy=(t,e,n,r)=>{e.isDirectory()&&Ku(Yr.resolve(t,e.name),n,r),Ga(Yr.resolve(t,e.name),n,r)},Ku=(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 Ga(t,e,n);throw s}for(let i of r)Fy(t,i,e,n);return Ga(t,e,n)},Xu=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"}},Us=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"}},By=(t,e)=>{De.stat(t,(n,r)=>{(n||!r.isDirectory())&&(n=new Xu(t,n?.code||"ENOTDIR")),e(n)})},Uy=(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?Zu(g,o,a,w=>m(w)):s?De.chmod(t,i,n):n()};if(t===p)return By(t,m);if(l)return My.mkdir(t,{mode:i,recursive:!0}).then(h=>m(null,h??void 0),m);let u=N(Cs.relative(p,t)).split("/");Ha(p,u,i,d,p,void 0,m)},Ha=(t,e,n,r,i,s,o)=>{if(e.length===0)return o(null,s);let a=e.shift(),c=N(Cs.resolve(t+"/"+a));De.mkdir(c,n,Yu(c,e,n,r,i,s,o))},Yu=(t,e,n,r,i,s,o)=>a=>{a?De.lstat(t,(c,l)=>{if(c)c.path=c.path&&N(c.path),o(c);else if(l.isDirectory())Ha(t,e,n,r,i,s,o);else if(r)De.unlink(t,d=>{if(d)return o(d);De.mkdir(t,n,Yu(t,e,n,r,i,s,o))});else{if(l.isSymbolicLink())return o(new Us(t,t+"/"+e.join("/")));o(a)}}):(s=s||t,Ha(t,e,n,r,i,s,o))},zy=t=>{let e=!1,n;try{e=De.statSync(t).isDirectory()}catch(r){n=r?.code}finally{if(!e)throw new Xu(t,n??"ENOTDIR")}},$y=(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&&Ku(h,s,o),i&&De.chmodSync(t,r)};if(t===d)return zy(d),p();if(c)return p(De.mkdirSync(t,{mode:r,recursive:!0})??void 0);let m=N(Cs.relative(d,t)).split("/"),u;for(let h=m.shift(),g=d;h&&(g+="/"+h);h=m.shift()){g=N(Cs.resolve(g));try{De.mkdirSync(g,r),u=u||g}catch{let w=De.lstatSync(g);if(w.isDirectory())continue;if(l){De.unlinkSync(g),De.mkdirSync(g,r),u=u||g;continue}else if(w.isSymbolicLink())return new Us(g,g+"/"+m.join("/"))}}return p(u)},Ta=Object.create(null),hu=1e4,jn=new Set,Gy=t=>{jn.has(t)?jn.delete(t):Ta[t]=t.normalize("NFD").toLocaleLowerCase("en").toLocaleUpperCase("en"),jn.add(t);let e=Ta[t],n=jn.size-hu;if(n>hu/10){for(let r of jn)if(jn.delete(r),delete Ta[r],--n<=0)break}return e},Hy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,jy=Hy==="win32",Wy=t=>t.split("/").slice(0,-1).reduce((e,n)=>{let r=e.at(-1);return r!==void 0&&(n=Qu(r,n)),e.push(n||"/"),e},[]),qy=class{#e=new Map;#n=new Map;#r=new Set;reserve(t,e){t=jy?["win32 parallelization disabled"]:t.map(r=>Xr(Qu(Gy(r))));let n=new Set(t.map(r=>Wy(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}},Jy=()=>process.umask(),pu=Symbol("onEntry"),ja=Symbol("checkFs"),gu=Symbol("checkFs2"),Wa=Symbol("isReusable"),Be=Symbol("makeFs"),qa=Symbol("file"),Ja=Symbol("directory"),bs=Symbol("link"),mu=Symbol("symlink"),wu=Symbol("hardlink"),Zr=Symbol("ensureNoSymlink"),yu=Symbol("unsupported"),_u=Symbol("checkPath"),Ra=Symbol("stripAbsolutePath"),Ut=Symbol("mkdir"),he=Symbol("onError"),ms=Symbol("pending"),Eu=Symbol("pend"),Wn=Symbol("unpend"),ka=Symbol("ended"),ba=Symbol("maybeClose"),Va=Symbol("skip"),Qr=Symbol("doChown"),ei=Symbol("uid"),ti=Symbol("gid"),ni=Symbol("checkedCwd"),Vy=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,ri=Vy==="win32",Zy=1024,Ky=(t,e)=>{if(!ri)return B.unlink(t,e);let n=t+".DELETE."+$u(16).toString("hex");B.rename(t,n,r=>{if(r)return e(r);B.unlink(n,e)})},Xy=t=>{if(!ri)return B.unlinkSync(t);let e=t+".DELETE."+$u(16).toString("hex");B.renameSync(t,e),B.unlinkSync(e)},Su=(t,e,n)=>t!==void 0&&t===t>>>0?t:e!==void 0&&e===e>>>0?e:n,ic=class extends ii{[ka]=!1;[ni]=!1;[ms]=0;reservations=new qy;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[ka]=!0,this[ba]()},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:Zy,this.forceChown=t.forceChown===!0,this.win32=!!t.win32||ri,this.newer=!!t.newer,this.keep=!!t.keep,this.noMtime=!!t.noMtime,this.preservePaths=!!t.preservePaths,this.unlink=!!t.unlink,this.cwd=N(se.resolve(t.cwd||process.cwd())),this.strip=Number(t.strip)||0,this.processUmask=this.chmod?typeof t.processUmask=="number"?t.processUmask:Jy():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[pu](e))}warn(t,e,n={}){return(t==="TAR_BAD_ARCHIVE"||t==="TAR_ABORT")&&(n.recoverable=!1),super.warn(t,e,n)}[ba](){this[ka]&&this[ms]===0&&(this.emit("prefinish"),this.emit("finish"),this.emit("end"))}[Ra](t,e){let n=t[e],{type:r}=t;if(!n||this.preservePaths)return!0;let[i,s]=ec(n),o=s.replaceAll(/\\/g,"/").split("/");if(o.includes("..")||ri&&/^[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=se.posix.dirname(t.path),c=se.posix.normalize(se.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}[_u](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[Ra](t,"path")||!this[Ra](t,"linkpath"))return!1;if(t.absolute=se.isAbsolute(t.path)?N(se.resolve(t.path)):N(se.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}=se.win32.parse(String(t.absolute));t.absolute=r+tu(String(t.absolute).slice(r.length));let{root:i}=se.win32.parse(t.path);t.path=i+tu(t.path.slice(i.length))}return!0}[pu](t){if(!this[_u](t))return t.resume();switch(Oy.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[ja](t);default:return this[yu](t)}}[he](t,e){t.name==="CwdError"?this.emit("error",t):(this.warn("TAR_ENTRY_ERROR",t,{entry:e}),this[Wn](),e.resume())}[Ut](t,e,n){Uy(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)}[Qr](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}[ei](t){return Su(this.uid,t.uid,this.processUid)}[ti](t){return Su(this.gid,t.gid,this.processGid)}[qa](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,r=new Ds(String(t.absolute),{flags:Vu(t.size),mode:n,autoClose:!1});r.on("error",a=>{r.fd&&B.close(r.fd,()=>{}),r.write=()=>!0,this[he](a,t),e()});let i=1,s=a=>{if(a){r.fd&&B.close(r.fd,()=>{}),this[he](a,t),e();return}--i===0&&r.fd!==void 0&&B.close(r.fd,c=>{c?this[he](c,t):this[Wn](),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;B.futimes(c,l,d,p=>p?B.utimes(a,l,d,m=>s(m&&p)):s())}if(typeof c=="number"&&this[Qr](t)){i++;let l=this[ei](t),d=this[ti](t);typeof l=="number"&&typeof d=="number"&&B.fchown(c,l,d,p=>p?B.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[he](a,t),e()}),t.pipe(o)),o.pipe(r)}[Ja](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode;this[Ut](String(t.absolute),n,r=>{if(r){this[he](r,t),e();return}let i=1,s=()=>{--i===0&&(e(),this[Wn](),t.resume())};t.mtime&&!this.noMtime&&(i++,B.utimes(String(t.absolute),t.atime||new Date,t.mtime,s)),this[Qr](t)&&(i++,B.chown(String(t.absolute),Number(this[ei](t)),Number(this[ti](t)),s)),s()})}[yu](t){t.unsupported=!0,this.warn("TAR_ENTRY_UNSUPPORTED",`unsupported entry type: ${t.type}`,{entry:t}),t.resume()}[mu](t,e){let n=N(se.relative(this.cwd,se.resolve(se.dirname(String(t.absolute)),String(t.linkpath)))).split("/");this[Zr](t,this.cwd,n,()=>this[bs](t,String(t.linkpath),"symlink",e),r=>{this[he](r,t),e()})}[wu](t,e){let n=N(se.resolve(this.cwd,String(t.linkpath))),r=N(String(t.linkpath)).split("/");this[Zr](t,this.cwd,r,()=>this[bs](t,n,"link",e),i=>{this[he](i,t),e()})}[Zr](t,e,n,r,i){let s=n.shift();if(this.preservePaths||s===void 0)return r();let o=se.resolve(e,s);B.lstat(o,(a,c)=>{if(a)return r();if(c?.isSymbolicLink())return i(new Us(o,se.resolve(o,n.join("/"))));this[Zr](t,o,n,r,i)})}[Eu](){this[ms]++}[Wn](){this[ms]--,this[ba]()}[Va](t){this[Wn](),t.resume()}[Wa](t,e){return t.type==="File"&&!this.unlink&&e.isFile()&&e.nlink<=1&&!ri}[ja](t){this[Eu]();let e=[t.path];t.linkpath&&e.push(t.linkpath),this.reservations.reserve(e,n=>this[gu](t,n))}[gu](t,e){let n=o=>{e(o)},r=()=>{this[Ut](this.cwd,this.dmode,o=>{if(o){this[he](o,t),n();return}this[ni]=!0,i()})},i=()=>{if(t.absolute!==this.cwd){let o=N(se.dirname(String(t.absolute)));if(o!==this.cwd)return this[Ut](o,this.dmode,a=>{if(a){this[he](a,t),n();return}s()})}s()},s=()=>{B.lstat(String(t.absolute),(o,a)=>{if(a&&(this.keep||this.newer&&a.mtime>(t.mtime??a.mtime))){this[Va](t),n();return}if(o||this[Wa](t,a))return this[Be](null,t,n);if(a.isDirectory()){if(t.type==="Directory"){let c=this.chmod&&t.mode&&(a.mode&4095)!==t.mode,l=d=>this[Be](d??null,t,n);return c?B.chmod(String(t.absolute),Number(t.mode),l):l()}if(t.absolute!==this.cwd)return B.rmdir(String(t.absolute),c=>this[Be](c??null,t,n))}if(t.absolute===this.cwd)return this[Be](null,t,n);Ky(String(t.absolute),c=>this[Be](c??null,t,n))})};this[ni]?i():r()}[Be](t,e,n){if(t){this[he](t,e),n();return}switch(e.type){case"File":case"OldFile":case"ContiguousFile":return this[qa](e,n);case"Link":return this[wu](e,n);case"SymbolicLink":return this[mu](e,n);case"Directory":case"GNUDumpDir":return this[Ja](e,n)}}[bs](t,e,n,r){B[n](e,String(t.absolute),i=>{i?this[he](i,t):(this[Wn](),t.resume()),r()})}},Jr=t=>{try{return[null,t()]}catch(e){return[e,null]}},ef=class extends ic{sync=!0;[Be](t,e){return super[Be](t,e,()=>{})}[ja](t){if(!this[ni]){let i=this[Ut](this.cwd,this.dmode);if(i)return this[he](i,t);this[ni]=!0}if(t.absolute!==this.cwd){let i=N(se.dirname(String(t.absolute)));if(i!==this.cwd){let s=this[Ut](i,this.dmode);if(s)return this[he](s,t)}}let[e,n]=Jr(()=>B.lstatSync(String(t.absolute)));if(n&&(this.keep||this.newer&&n.mtime>(t.mtime??n.mtime)))return this[Va](t);if(e||this[Wa](t,n))return this[Be](null,t);if(n.isDirectory()){if(t.type==="Directory"){let s=this.chmod&&t.mode&&(n.mode&4095)!==t.mode,[o]=s?Jr(()=>{B.chmodSync(String(t.absolute),Number(t.mode))}):[];return this[Be](o,t)}let[i]=Jr(()=>B.rmdirSync(String(t.absolute)));this[Be](i,t)}let[r]=t.absolute===this.cwd?[]:Jr(()=>Xy(String(t.absolute)));this[Be](r,t)}[qa](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.fmode,r=o=>{let a;try{B.closeSync(i)}catch(c){a=c}(o||a)&&this[he](o||a,t),e()},i;try{i=B.openSync(String(t.absolute),Vu(t.size),n)}catch(o){return r(o)}let s=this.transform&&this.transform(t)||t;s!==t&&(s.on("error",o=>this[he](o,t)),t.pipe(s)),s.on("data",o=>{try{B.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{B.futimesSync(i,a,c)}catch(l){try{B.utimesSync(String(t.absolute),a,c)}catch{o=l}}}if(this[Qr](t)){let a=this[ei](t),c=this[ti](t);try{B.fchownSync(i,Number(a),Number(c))}catch(l){try{B.chownSync(String(t.absolute),Number(a),Number(c))}catch{o=o||l}}}r(o)})}[Ja](t,e){let n=typeof t.mode=="number"?t.mode&4095:this.dmode,r=this[Ut](String(t.absolute),n);if(r){this[he](r,t),e();return}if(t.mtime&&!this.noMtime)try{B.utimesSync(String(t.absolute),t.atime||new Date,t.mtime)}catch{}if(this[Qr](t))try{B.chownSync(String(t.absolute),Number(this[ei](t)),Number(this[ti](t)))}catch{}e(),t.resume()}[Ut](t,e){try{return $y(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}}[Zr](t,e,n,r,i){if(this.preservePaths||n.length===0)return r();let s=e;for(let o of n){s=se.resolve(s,o);let[a,c]=Jr(()=>B.lstatSync(s));if(a)return r();if(c.isSymbolicLink())return i(new Us(s,se.resolve(e,n.join("/"))))}r()}[bs](t,e,n,r){let i=`${n}Sync`;try{B[i](e,String(t.absolute)),r(),t.resume()}catch(s){return this[he](s,t)}}},Yy=t=>{let e=new ef(t),n=t.file,r=zu.statSync(n),i=t.maxReadSize||16*1024*1024;new yw(n,{readSize:i,size:r.size}).pipe(e)},Qy=(t,e)=>{let n=new ic(t),r=t.maxReadSize||16*1024*1024,i=t.file;return new Promise((s,o)=>{n.on("error",o),n.on("close",s),zu.stat(i,(a,c)=>{if(a)o(a);else{let l=new Ka(i,{readSize:r,size:c.size});l.on("error",o),l.pipe(n)}})})},tf=si(Yy,Qy,t=>new ef(t),t=>new ic(t),(t,e)=>{e?.length&&Du(t,e)}),e_=(t,e)=>{let n=new rc(t),r=!0,i,s;try{try{i=Ce.openSync(t.file,"r+")}catch(c){if(c?.code==="ENOENT")i=Ce.openSync(t.file,"w+");else throw c}let o=Ce.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=Ce.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 gn(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,t_(t,n,s,i,e)}finally{if(r)try{Ce.closeSync(i)}catch{}}},t_=(t,e,n,r,i)=>{let s=new Tu(t.file,{fd:r,start:n});e.pipe(s),r_(e,i)},n_=(t,e)=>{e=Array.from(e);let n=new Ms(t),r=(i,s,o)=>{let a=(m,u)=>{m?Ce.close(i,h=>o(m)):o(null,u)},c=0;if(s===0)return a(null,0);let l=0,d=Buffer.alloc(512),p=(m,u)=>{if(m||u===void 0)return a(m);if(l+=u,l<512&&u)return Ce.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 gn(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,Ce.read(i,d,0,512,c,p)};Ce.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+",Ce.open(t.file,o,a);if(c||!l)return s(c);Ce.fstat(l,(d,p)=>{if(d)return Ce.close(l,()=>s(d));r(l,p.size,(m,u)=>{if(m)return s(m);let h=new Ds(t.file,{fd:l,start:u});n.pipe(h),h.on("error",s),h.on("close",i),i_(n,e)})})};Ce.open(t.file,o,a)})},r_=(t,e)=>{e.forEach(n=>{n.charAt(0)==="@"?Qn({file:nf.resolve(t.cwd,n.slice(1)),sync:!0,noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n)}),t.end()},i_=async(t,e)=>{for(let n of e)n.charAt(0)==="@"?await Qn({file:nf.resolve(String(t.cwd),n.slice(1)),noResume:!0,onReadEntry:r=>t.add(r)}):t.add(n);t.end()},Vr=si(e_,n_,()=>{throw new TypeError("file is required")},()=>{throw new TypeError("file is required")},(t,e)=>{if(!kw(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")}),Bk=si(Vr.syncFile,Vr.asyncFile,Vr.syncNoFile,Vr.asyncNoFile,(t,e=[])=>{Vr.validate?.(t,e),s_(t)}),s_=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))};At();var Ze={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 oi(t){return t?.cozeDeployType==="cloud"?"cloud":"local"}function rf(t){let e=t?.cozeAccountId?.trim();if(!(!e||e==="0"))return e}function sc(t){let e=t?.cozeGroupId?.trim();if(!(!e||e==="0"))return e}function sf(t){let{_meta:e,...n}=t;return{stripped:n,meta:e}}function er(t){if(!t?.cozeAgentId)throw new Error("missing _meta.cozeAgentId");return t.cozeAgentId}Te();F();re();Te();function vt(t,e){if(oi(t)!=="cloud")throw new _("OPERATION_NOT_ALLOWED_FOR_LOCAL",`${e} is not allowed for local agent`)}function zs(t){return t.startsWith("http://")||t.startsWith("https://")}function $s(t){return t.endsWith("/")?t.slice(0,-1):t}Te();F();var Gs="1008033",of="1289";var af="pbbp2",cf="https://www.coze.cn",lf="/api/coze_claw/resource/get_frontier_key",a_="https://www.coze.cn",c_="wss://frontier.coze.cn";function Hs(t){return t??process.env.COZE_BRIDGE_HANDSHAKE_URL??a_}function df(t){return t??process.env.COZE_BRIDGE_FRONTIER_URL??c_}function tr(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 ci(t){return t?t.startsWith("boe_")?{ttEnv:t}:{ttEnv:t,usePpe:"1"}:{}}var ai=b("handshake");async function oc(t){let e=Hs(t.endpoint),n=t.timeoutMs??1e4,r=`${$s(e)}${lf}?aid=${encodeURIComponent(Gs)}`,i={Authorization:`Bearer ${t.privatecode}`,Accept:"application/json",...tr(t.ppeOverride)},s=new AbortController,o=setTimeout(()=>s.abort(),n);ai.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,u=typeof p.device_id=="string"&&p.device_id||typeof p.deviceId=="string"&&p.deviceId||void 0;if(!m||!u){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 ai.info("handshake ok",{remoteDeviceId:u,logid:c,traceId:l}),{accessKey:m,deviceId:u}}catch(a){if(a instanceof _)throw ai.error("handshake failed (bridge error)",{base:e,message:a.message,code:a.code}),a;if(a.name==="AbortError")throw ai.warn("handshake timeout",{base:e,timeoutMs:n}),new _("UPSTREAM_HANDSHAKE_FAILED",`handshake timeout (${n}ms)`,{cause:a});let c=a.cause;throw ai.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 ac=process.env.COZE_BRIDGE_LLM_GATEWAY_URL?.trim()||"https://llm-gateway.coze.cn",Ke="auto",uf=2e5;function ff(t){return{model:cc(t.model)??Ke,...t.modelToken?{modelToken:t.modelToken}:{}}}function hf(t){return!t||t===Ke}var l_=new Set(["auto","\u81EA\u52A8"]);function cc(t){let e=t?.trim();if(e)return l_.has(e.toLowerCase())?Ke:e}function pf(t){let e={};if(t.modelToken){e.ANTHROPIC_BASE_URL=ac,e.ANTHROPIC_AUTH_TOKEN=t.modelToken;let n=t.model||Ke;e.ANTHROPIC_MODEL=n,e.ANTHROPIC_SMALL_FAST_MODEL=n,t.modelInfo?.contextWindow&&(e.CLAUDE_CODE_MAX_CONTEXT_TOKENS=String(t.modelInfo.contextWindow))}else hf(t.model)||(e.ANTHROPIC_MODEL=t.model);return e}function gf(t){let e=[];if(t.modelToken?e.push("-c",`model="${t.model||Ke}"`):hf(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="${ac}/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??uf;e.push("-c",`model_context_window=${n}`)}return e}function mf(t){return t.modelToken?{OPENAI_API_KEY:t.modelToken}:{}}function lc(t,e){let{ttEnv:n,usePpe:r}=ci(t),i={};return n&&(i["x-tt-env"]=n),r&&(i["x-use-ppe"]=r),e&&(i["x-mock-scenario"]=e),i}function wf(t,e,n){if(!t.modelToken)return{};let r=lc(e,n);return Object.keys(r).length===0?{}:{ANTHROPIC_CUSTOM_HEADERS:Object.entries(r).map(([s,o])=>`${s}:${o}`).join(`
92
+ `)}}function dc(t){return`coze-session-${t.replace(/[^A-Za-z0-9_-]+/g,"-")}`}function yf(t,e,n){if(!t.modelToken)return null;let r=t.model||Ke,i=lc(e,n),s=["text"];t.modelInfo?.capabilities?.image===!0&&s.push("image");let o={baseUrl:`${ac}/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??uf,maxTokens:8192,api:"openai-completions"}]};return Object.keys(i).length>0&&(o.headers=i),o}function _f(t,e,n){if(!t.modelToken)return[];let r=lc(e,n),i=[];for(let[s,o]of Object.entries(r))i.push("-c",`model_providers.coze.http_headers.${s}="${o}"`);return i}var oe=b("agent-handlers"),Ef=5*1024*1024,g_=1,m_=6,w_=new Set(["node_modules",".git",".coze","dist","build",".next"]),js=class{constructor(e){this.opts=e}opts;async listSkills(e){vt(e._meta,"_agent/listSkills");let n=er(e._meta),r=await this.loadAgentCfg(n),i=r?.workspace??be(n).workspace,s=r?.skills??[],o=[];for(let a of s){let c=at(i,a.relPath,"SKILL.md");await f_(c).then(d=>d.isFile()).catch(()=>!1)&&o.push(v_(a))}return{skills:o}}async addSkills(e){vt(e._meta,"_agent/addSkills");let n=er(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 wc({agentId:n,workspace:r.workspace,framework:r.framework,skill:c});yc(s,o,l),a.push(c)}return await Zi(n,s),this.reloadAgentSessions(n,"skills-added"),{installedSkills:a}}async removeSkills(e){vt(e._meta,"_agent/removeSkills");let n=er(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=at(r.workspace,a.relPath);await u_(c,{recursive:!0,force:!0}),oe.info("skill removed",{agentId:n,skillId:a.skillId,relPath:a.relPath})}return await Zi(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,oe.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,oe.info("killing downstream for workspace reload (idle)",{reason:n,agentId:e,framework:r.framework,cloudId:i,acpId:o}),c.stop(n).catch(l=>oe.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 oe.info("_agent/update: empty cozeIdentity, noop",{agentId:e.agentId}),{ok:!0};let n=e.agentId,r=await we(n);if(!r)throw new _("AGENT_NOT_FOUND",`agent not found: ${n}`);if(r.cozeIdentity===e.cozeIdentity)return oe.info("_agent/update: cozeIdentity unchanged, noop",{agentId:n}),{ok:!0};try{await Mn(r.workspace,r.framework,e.cozeIdentity)}catch(i){throw oe.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 Ae(r),oe.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 we(n);return r?(r.disconnectedAt=Date.now(),r.disconnectReason=e.reason??"",await Ae(r),oe.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}):(oe.warn("_agent/disconnect: agent not found, ignoring",{agentId:n}),{ok:!0})}async switchModel(e){if(vt(e._meta,"_agent/switchModel"),!e.agentId)throw new _("IPC_BAD_REQUEST","_agent/switchModel: missing agentId");let n=cc(e.model)??Ke,r=await we(e.agentId);if(!r)throw new _("AGENT_NOT_FOUND",`agent not found: ${e.agentId}`);r.model=n,e.modelInfo&&(r.modelInfo=e.modelInfo),await Ae(r),oe.info("_agent/switchModel: model persisted",{agentId:e.agentId,model:n,reason:e.reason??""});let i=this.opts.agents.get(e.agentId);if(!i)return oe.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=>oe.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),oe.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(vt(e._meta,Ze.RESET),!e.agentId)throw new _("IPC_BAD_REQUEST",`${Ze.RESET}: missing agentId`);return await this.clearSessionMappings(e.agentId,Ze.RESET),await this.runDetailSync(e.agentId,Ze.RESET,e.reason),{ok:!0}}async clearSessionMappings(e,n){let r=this.opts.agents.get(e);if(!r){await this.clearPersistedAcpSessionIds(e),oe.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 Dr(e,i)}async clearPersistedAcpSessionIds(e){let n=await we(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 Ae(n)}async repairAgent(e){if(vt(e._meta,Ze.REPAIR),!e.agentId)throw new _("IPC_BAD_REQUEST",`${Ze.REPAIR}: missing agentId`);let n=await this.loadAgentCfg(e.agentId);if(n&&n.framework!=="openclaw")throw new _("IPC_BAD_REQUEST",`${Ze.REPAIR} only allowed for openclaw, got ${n.framework}`);if(n&&this.opts.openclawRepair)try{await this.opts.openclawRepair(e.agentId,n.workspace)}catch(r){oe.warn("openclaw repair (delete+add) failed (ignored)",{agentId:e.agentId,reason:e.reason,err:String(r)})}return await this.runDetailSync(e.agentId,Ze.REPAIR,e.reason),{ok:!0}}async runDetailSync(e,n,r){if(!this.opts.detailSyncer){oe.warn("detailSyncer not wired, skipping sync",{method:n,agentId:e});return}try{await this.opts.detailSyncer(e)}catch(i){oe.warn("detail sync failed (ignored)",{method:n,agentId:e,reason:r,err:String(i)})}}async getFileTree(e){vt(e._meta,"_agent/getFileTree");let n=e._meta,r=er(n),i=await this.resolveWorkspace(r),s=e.filePath??"",o=this.safeJoin(i,s),a=await uc(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 Cr(o,i))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${s}`);let c=D_(e.depth);return a.isDirectory()?{tree:await C_(i,o,s,c)}:{tree:[{name:N_(s),path:bf(s||"."),isDir:!1,size:a.size,modifiedAt:Math.floor(a.mtimeMs)}]}}async getFileContent(e){vt(e._meta,"_agent/getFileContent");let n=er(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 uc(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 Cr(i,r))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${e.filePath}`);if(s.size>Ef)throw new _("IPC_BAD_REQUEST",`file too large: ${s.size} bytes (max ${Ef})`);let o=await Sf(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 we(e).catch(()=>null))?.workspace??be(e).workspace}safeJoin(e,n){let r=pc(e,n||"."),i=mc(e,r);if(i.startsWith("..")||i===".."||i.startsWith(`..${vf}`))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${n}`);return r}loadAgentCfg(e){return we(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 y_(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 __(t){return t==="claude-code"?at(".claude","skills"):at(".agents","skills")}var E_=3e4,S_=50*1024*1024,nr=3e4;async function wc(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=y_(i.skillName),c=__(r),l=at(c,a),d=at(n,l);if(await fc(d,{recursive:!0}),s){let m=Buffer.from(i.content,"utf8");li(m.length),await hc(at(d,"SKILL.md"),m,"utf8")}else{let m=await I_(i.downloadUrl);R_(m)?await x_(m,d):k_(m)?await b_(m,d):await hc(at(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 oe.info("skill installed",{agentId:e,skillId:i.skillId,skillName:i.skillName,relPath:l,source:s?"content":"downloadUrl"}),p}function yc(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 v_(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 I_(t){if(!t)throw new _("IPC_BAD_REQUEST","skill missing downloadUrl");if(t.startsWith("data:")){let e=Math.floor(t.length*3/4);li(e);let n=T_(t);return li(n.length),n}if(t.startsWith("file:")){let e=new URL(t).pathname,n=await Sf(e);return li(n.length),n}if(zs(t)){let e=new AbortController,n=setTimeout(()=>e.abort(),E_);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 li(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 li(t){if(t>S_)throw new _("IPC_BAD_REQUEST",`skill too large: ${t} bytes`)}function T_(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 R_(t){return t.length>=2&&t[0]===31&&t[1]===139}function k_(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 gc(t){return t==="__MACOSX"||t.startsWith("__MACOSX/")}async function b_(t,e){let n,r;try{n=new Rf.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||gc(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=A_(r),s=pc(e);for(let o of r){if(gc(o.entryName))continue;let a=o.entryName;if(i&&a.startsWith(i)&&(a=a.slice(i.length)),!a)continue;let c=pc(e,a),l=mc(s,c);if(l.startsWith("..")||l==="..")throw new _("IPC_BAD_REQUEST",`zip entry escapes destDir: ${a}`);if(o.isDirectory){await fc(c,{recursive:!0});continue}await fc(h_(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 hc(c,d)}}function A_(t){let e;for(let n of t){let r=n.entryName;if(!r||gc(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 x_(t,e){await O_(t);let n=tf({cwd:e,strip:1}),r=!1,i=setTimeout(()=>{r=!0,n.destroy(new _("IPC_BAD_REQUEST",`tar extract timeout (${nr}ms)`))},nr);try{await Tf(If.from(t),n)}catch(s){throw s instanceof _?s:r?new _("IPC_BAD_REQUEST",`tar extract timeout (${nr}ms)`):new _("IPC_BAD_REQUEST",`tar extract failed: ${s.message??String(s)}`,{cause:s})}finally{clearTimeout(i)}}async function O_(t){let e=[],n=Qn({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 (${nr}ms)`))},nr);try{await Tf(If.from(t),n)}catch(s){throw r?new _("IPC_BAD_REQUEST",`tar list timeout (${nr}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 C_(t,e,n,r){return kf(t,e,n,r,{count:0})}async function kf(t,e,n,r,i){if(r<=0)return[];let s;try{s=await d_(e,{withFileTypes:!0})}catch{return[]}let o=[];for(let a of s){if(w_.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=at(e,a.name),l=p_(at(n,a.name)),d=null;try{d=await uc(c)}catch{continue}if(d.isSymbolicLink())continue;i.count++;let p={name:a.name,path:bf(mc(t,c)),isDir:d.isDirectory(),size:d.size,modifiedAt:Math.floor(d.mtimeMs)};d.isDirectory()&&r>1&&(p.children=await kf(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 D_(t){return!t||t<=0?g_:Math.min(t,m_)}function N_(t){if(!t||t==="."||t==="/")return".";let e=t.split(/[/\\]/);return e[e.length-1]||"."}function bf(t){return t.split(vf).join("/")}F();import{readFileSync as Vb}from"node:fs";import{dirname as Kb,join as Xb}from"node:path";import{fileURLToPath as Qb}from"node:url";var rr="0.1.93-beta.2";var Gt=b("agent-health-reporter"),L_=1e4,di=class{constructor(e){this.opts=e;this.intervalMs=e.intervalMs??L_}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()}),Gt.info("heartbeat started",{intervalMs:this.intervalMs}),this.tick())}stop(){this.timer&&(clearInterval(this.timer),this.timer=null,this.unsubscribeRegister&&(this.unsubscribeRegister(),this.unsubscribeRegister=null),Gt.info("heartbeat stopped"))}async tick(){if(this.inFlight){Gt.debug("previous tick still in-flight, skip");return}let e=this.opts.getDeviceId();if(!e){Gt.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=F_(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:rr,_meta:{cozeDeviceId:e}},i;try{i=await this.opts.core.sendRequest("_agent/health",r,5e3)}catch(o){Gt.warn("heartbeat batch send failed",{count:n.length,err:String(o)})}let s=i?.authFailures;if(s&&s.length>0&&(Gt.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){Gt.warn("onAuthFailures callback failed (ignored)",{err:String(o)})}}finally{this.inFlight=!1}if(this.opts.onTickEnd)try{await this.opts.onTickEnd()}catch(n){Gt.warn("onTickEnd hook failed",{err:String(n)})}}};function F_(t){return t.status==="error"?"error":t.activeTriggers.size>0?"busy":t.status==="ok"?"online":null}At();import{chmod as yE,mkdir as Qs,rm as _E,stat as EE,writeFile as SE}from"node:fs/promises";import{homedir as vE}from"node:os";import{join as Vf}from"node:path";tn();import{spawnSync as q_}from"node:child_process";function ui(t,e,n){return n===void 0?{jsonrpc:"2.0",id:t,method:e}:{jsonrpc:"2.0",id:t,method:e,params:n}}function ir(t,e){return e===void 0?{jsonrpc:"2.0",method:t}:{jsonrpc:"2.0",method:t,params:e}}function sr(t,e){return{jsonrpc:"2.0",id:t,result:e}}function Ht(t,e){return{jsonrpc:"2.0",id:t,error:e}}Te();var Ws=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)}},U={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 Af(t){return"method"in t&&"id"in t&&t.id!==void 0}function xf(t){return"method"in t&&!("id"in t)}function qs(t){return!("method"in t)&&"id"in t}var M_={AGENT_NOT_FOUND:U.AGENT_NOT_FOUND,AGENT_BUSY:U.AGENT_BUSY,AGENT_DISCONNECTED:U.AGENT_DISCONNECTED,AGENT_TIMEOUT:U.AGENT_TIMEOUT,AGENT_FRAME_IDLE_TIMEOUT:U.AGENT_FRAME_IDLE_TIMEOUT,AGENT_SPAWN_FAILED:U.AGENT_SPAWN_FAILED,AGENT_PROTOCOL_ERROR:U.INTERNAL_ERROR,BRIDGE_CONFIG_INVALID:U.INTERNAL_ERROR,BRIDGE_INTERNAL:U.INTERNAL_ERROR,IPC_AUTH_FAILED:U.INTERNAL_ERROR,IPC_BAD_REQUEST:U.INVALID_REQUEST,MODEL_TOKEN_GEN_FAILED:U.MODEL_TOKEN_GEN_FAILED,MODEL_MODALITY_UNSUPPORTED:U.MODEL_MODALITY_UNSUPPORTED,OPERATION_NOT_ALLOWED_FOR_LOCAL:U.OPERATION_NOT_ALLOWED_FOR_LOCAL,UPSTREAM_DISCONNECTED:U.INTERNAL_ERROR,UPSTREAM_HANDSHAKE_FAILED:U.INTERNAL_ERROR,PATH_OUTSIDE_WORKSPACE:U.PATH_OUTSIDE_WORKSPACE,FILE_TOO_LARGE:U.FILE_TOO_LARGE,UNSUPPORTED_MIME:U.UNSUPPORTED_MIME,UPLOAD_FAILED:U.UPLOAD_FAILED,UPSTREAM_NOT_READY:U.UPSTREAM_NOT_READY,AGENT_DEPENDENCY_INSTALL_FAILED:U.AGENT_DEPENDENCY_INSTALL_FAILED,AGENT_APPROVAL_TIMEOUT:U.AGENT_APPROVAL_TIMEOUT};function B_(t){if(t!=null)return t instanceof Error?{name:t.name,message:fi(t.message)}:typeof t=="string"?fi(t):typeof t=="object"?z_(t):t}var U_=[[/\/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 fi(t){let e=t;for(let[n,r]of U_)e=e.replace(n,r);return e}function z_(t){let e={};for(let[n,r]of Object.entries(t))typeof r=="string"?e[n]=fi(r):e[n]=r;return e}function hi(t){if(t instanceof _){let e=B_(t.cause),n={bridgeCode:t.code,retriable:t.retriable};return e!==void 0&&(n.cause=e),{code:M_[t.code]??U.INTERNAL_ERROR,message:fi(t.message),data:n}}return{code:U.INTERNAL_ERROR,message:fi(t instanceof Error?t.message:String(t))}}function Of(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 Cf(t){return`${JSON.stringify(t)}
93
+ `}var Pf=10*1024*1024,Js=class{buffer="";onError;constructor(e={}){this.onError=e.onError}push(e){if(this.buffer+=typeof e=="string"?e:e.toString("utf8"),this.buffer.length>Pf){let i=this.buffer.length;return this.buffer="",this.onError?.({line:`<buffer overflow: ${i} bytes, dropped>`,error:new Error(`LdjsonDecoder buffer exceeded ${Pf} bytes`)}),[]}let n=this.buffer.split(`
94
+ `);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 Nf={"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"},dA=Object.fromEntries(Object.entries(Nf).map(([t,e])=>[e,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:[]},or=class{seq=0;next(e,n){this.seq+=1;let r=Nf[e]??G_(e),i=$_[r]??[],s=[r,String(this.seq)];if(i.length>0){let o=i.map(c=>Df(n?.[c]??"")),a=H_(o).join(":");a&&s.push(a)}else n&&Object.values(n).some(o=>o)&&s.push(Object.values(n).filter(Boolean).map(o=>Df(String(o))).join(":"));return s.join("_")}reset(){this.seq=0}};function G_(t){return t.replace(/[\s/]+/g,".").replace(/_+/g,"-")}function Df(t){return t.replace(/[:_\s]+/g,"-")}function H_(t){let e=t.length;for(;e>0&&!t[e-1];)e-=1;return t.slice(0,e)}Pr();import{readFileSync as j_}from"node:fs";var W_=384;async function _c(t,e=process.env){let n={};for(let[r,i]of Object.entries(e))typeof i=="string"&&(n[r]=i);await Fn(t.agentEnvFile,n,{mode:W_})}function Ec(t){try{let e=JSON.parse(j_(t,"utf8"));return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function Lf(t,e,n={},r=i=>i){return{...r({...t,...Ec(e)}),...n}}gt();Ui();Te();F();re();var J_=pt("COZE_BRIDGE_INITIALIZE_TIMEOUT_MS",3e4),V_=200,Z_=pt("COZE_BRIDGE_SESSION_PROMPT_MAX_MS",3600*1e3),K_=pt("COZE_BRIDGE_SESSION_PROMPT_FRAME_IDLE_MS",600*1e3),X_=pt("COZE_BRIDGE_SESSION_PROMPT_APPROVAL_MAX_MS",1440*60*1e3),Ff=500;function Y_(t){try{let e=JSON.stringify(t);return e===void 0||e.length<=Ff?t:`${e.slice(0,Ff)}...<truncated, total ${e.length} chars>`}catch{return"<unserializable>"}}function Mf(t,e){if(!(typeof t!="number"||t<=0))try{if(process.platform==="win32"){let n=["/PID",String(t),"/T"];e==="SIGKILL"&&n.push("/F"),q_("taskkill",n,{stdio:"ignore",windowsHide:!0})}else process.kill(-t,e)}catch{}}var ct=class{constructor(e){this.opts=e;this.log=b(`downstream.${this.constructor.name}`,this.opts.agentId),this.decoder=new Js({onError:n=>this.log.warn("decode line failed",{line:n.line})})}opts;child;decoder;pending=new Map;inflightAgentRequests=new Map;idAllocator=new or;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=Fe(this.opts.command,this.opts.args,{cwd:this.opts.cwd,env:Lf(process.env,this.opts.agentEnvFile??L().agentEnvFile,this.opts.env,r=>this.sanitizeEnv(r)),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>V_&&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()));Mf(n.pid,"SIGTERM");let i=setTimeout(()=>{n.killed||Mf(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=Z_,r=K_,i=X_){return this.call("session/prompt",e,n,r,i)}async sessionCancel(e){!this.child||this.stopped||this.writeFrame(ir("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(sr(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(Ht(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=J_,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=ui(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 u={resolve:p,reject:m,timer:null,frameIdleTimer:null,armFrameIdle:null,method:e},h=Date.now();if(l){let w=()=>{u.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),u.frameIdleTimer&&clearTimeout(u.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?()=>{u.frameIdleTimer&&clearTimeout(u.frameIdleTimer),u.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}u.timer&&clearTimeout(u.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;u.armFrameIdle=g,this.pending.set(o,u),g?.();try{this.writeFrame(a)}catch(w){u.timer&&clearTimeout(u.timer),u.frameIdleTimer&&clearTimeout(u.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(Cf(e),n=>{n&&this.log.warn("stdin write callback err",{err:String(n)})})}dispatch(e){if(qs(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(Of(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:Y_(e.result)}),n.resolve(e.result));return}if(xf(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(Af(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(Ht(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(Ht(e.id,hi(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 Q_(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 Vs=class extends ct{framework="claude-code";constructor(e){let n=Or("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 Q_(e)}};tn();import{mkdtempSync as eE,rmSync as tE}from"node:fs";import{tmpdir as nE}from"node:os";import{join as rE}from"node:path";var Zs=class extends ct{framework="codex";authMethodId;codexHomeDir;constructor(e){let n=Or("codex",e.command),r=e.args??[],i=e.extraArgs?[...r,...e.extraArgs]:r,s=e.isolateCodexHome?eE(rE(nE(),"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{tE(this.codexHomeDir,{recursive:!0,force:!0})}catch{}}};var iE=3e4,ar=class extends ct{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}`}]},iE))}get acpSessionName(){return this.sessionName}};Te();F();re();function Sc(t){return t.replace(/[^A-Za-z0-9._-]+/g,"-")}tn();var jt=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 Ks=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 jt,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)pi(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 pi(t){t.idleTimer&&(clearTimeout(t.idleTimer),t.idleTimer=void 0)}gt();F();import{promises as vc}from"node:fs";import{join as sE}from"node:path";var wn=b("agents.codex-sandbox-installer"),Bf="@openai/codex@0.135.0",Uf="https://registry.npmmirror.com",Ic="/usr/lib/node_modules/@openai/codex/node_modules/@openai/codex-linux-x64/vendor/x86_64-unknown-linux-musl/bin/codex",oE="/usr/bin",zf=["apply_patch","applypatch","codex-execve-wrapper","codex-linux-sandbox"],aE=9e4,cE=5e3,gi=null,$f=!1;async function Gf(t,e={}){if((e.platform??process.platform)!=="linux"||$f)return;if(gi)return gi;let r=e.exec??Cn,i=e.statFile??(async a=>{try{return await vc.stat(a),!0}catch{return!1}}),s=e.symlink??((a,c)=>vc.symlink(a,c)),o=e.unlink??(a=>vc.unlink(a));return gi=(async()=>{try{let a=!1;try{let{stdout:l}=await r("which",["codex"],{timeout:cE});a=l.trim().length>0}catch{a=!1}if(a)wn.info("codex already present, skip install");else{wn.info("codex not found, installing",{package:Bf,registry:Uf});try{await r("npm",["i","-g",Bf,`--registry=${Uf}`],{timeout:aE,maxBuffer:10*1024*1024,signal:t}),wn.info("codex install ok")}catch(l){wn.warn("codex install failed (skip symlinks)",{err:String(l)});return}}if(!await i(Ic)){wn.warn("codex vendor bin not found, skip symlinks",{target:Ic});return}let c=0;for(let l of zf){let d=sE(oE,l);try{await o(d).catch(()=>{}),await s(Ic,d),c+=1,wn.info("codex sandbox symlink created",{link:d})}catch(p){wn.warn("codex sandbox symlink failed (ignored)",{link:d,err:String(p)})}}c===zf.length&&($f=!0)}finally{gi=null}})(),gi}gt();F();import{constants as Hf,access as lE}from"node:fs/promises";import{delimiter as dE,join as uE}from"node:path";var Wt=b("framework-detector"),jf={"claude-code":"claude",codex:"codex",openclaw:"openclaw"},fE=[".exe",".cmd",".bat",".ps1"],yn=class{env;constructor(e={}){this.env={pathEnv:e.pathEnv??process.env.PATH??"",platform:e.platform??process.platform,spawn:e.spawn??Fe,access:e.access??lE}}async detect(e){let n=jf[e],r=await this.which(n);if(!r)return Wt.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(jf).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(dE).filter(Boolean),r=this.env.platform==="win32"?["",...fE]:[""];for(let i of n)for(let s of r){let o=uE(i,e+s);if(await this.isExecutable(o))return o}return null}async isExecutable(e){try{let n=this.env.platform==="win32"?Hf.F_OK:Hf.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 Wt.warn("openclaw default agent probe: runProbe returned null (spawn err / timeout)",{path:e}),null;if(n.code!==0)return Wt.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 Wt.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 Wt.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?(Wt.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}:(Wt.info("openclaw default agent probe: no agent has isDefault=true",{path:e,agentCount:i.length}),null)}catch(i){return Wt.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&&(pE(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)}})}},hE=new RegExp("\x1B\\[[0-9;]*[A-Za-z]","g");function pE(t){return t.replace(hE,"")}import{homedir as gE}from"node:os";import{join as mE}from"node:path";gt();Te();Pr();F();async function Jf(){let t=mE(gE(),".openclaw/openclaw.json");return(await Ln(t))?.gateway?.auth?.token??""}var Wf=b("openclaw.config"),wE=[0,5e3,5e3],qf="models.providers.",Xs="agents.defaults.models",Ys=class{command;env;retryDelaysMs;queue=new jt;constructor(e){this.command=e.command,this.env=e.env??process.env,this.retryDelaysMs=e.retryDelaysMs??wE}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,Wf.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=Fe(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){Wf.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",`${qf}${e}`,JSON.stringify(n),"--strict-json","--merge"])))}removeProvider(e){return this.bestEffortUnset(`config unset models.providers.${e}`,`${qf}${e}`)}addModelToAllowlist(e,n){let r={[e]:n?{alias:n}:{}};return this.queue.enqueue(()=>this.withRetry(`config set ${Xs}[${e}]`,()=>this.runCli(["config","set",Xs,JSON.stringify(r),"--strict-json","--merge"])))}removeModelFromAllowlist(e){return this.bestEffortUnset(`config unset ${Xs}[${e}]`,`${Xs}.${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 K=b("agent-manager"),IE=(t,e,n,r,i,s,o,a,c)=>{switch(t){case"claude-code":{let l={...i?{...pf(i),...wf(i,o,a)}:{},...c??{},IS_SANDBOX:"1"};return new Vs({cwd:n,env:l,agentId:r})}case"codex":{let d=[...i?[...gf(i),..._f(i,o,a)]:[],"-c",'sandbox_mode="danger-full-access"',"-c",'approval_policy="never"'],p={...i?mf(i):{},...c??{}},m=!!i;return new Zs({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 ar({command:e,cwd:n,agentId:r,...s?{sessionName:Sc(s)}:{}})}};function Tc(t){return t==="claude-code"||t==="codex"}function TE(t){let e=[],n=Object.keys(t).sort();for(let r of n){let i=t[r];i!==void 0&&(RE(i)||e.push(`${r}=${i}`))}return e.length===0?"":`${e.join(`
95
95
  `)}
96
96
  `}function RE(t){if(t.includes(`
97
- `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var kE={path:"",version:"cloud-deployed"},bE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},AE=6e4,to=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??AE,this.detectorFactory=e.detectorFactory??(()=>new qt),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Qs({command:n})),this.openclawConfigDir=e.openclawConfigDir??Vf(vE(),".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=>{K.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=Vf(e,".env");if(await EE(n).then(s=>s.isFile()).catch(()=>!1)){K.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}await eo(e,{recursive:!0});let i=TE({...process.env,...Ec(this.paths.agentEnvFile)});if(await SE(n,i,"utf8"),process.platform!=="win32")try{await yE(n,384)}catch(s){K.warn("chmod ~/.openclaw/.env to 0600 failed (ignored)",{err:String(s)})}K.info("openclaw .env bootstrapped",{envFile:n,bytes:i.length}),await this.getOpenclawConfig().restartGateway(),K.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=ai(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")K.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await r.dispose("rebuild after error").catch(h=>K.warn("dispose stale agent failed (ignored)",{err:String(h)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==r.patToken){K.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),r.setPatToken(e.patToken);let h=await me(e.agentId,this.paths).catch(()=>null);h&&(h.patToken=e.patToken,await Ae(h,this.paths))}if(r.deployType==="cloud"&&e.modelInfo){K.info("updating agent modelInfo on re-create",{agentId:e.agentId}),r.setModelInfo(e.modelInfo);let h=await me(e.agentId,this.paths).catch(()=>null);h&&(h.modelInfo=e.modelInfo,await Ae(h,this.paths))}return K.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=be(e.agentId,this.paths),o=ai(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,u=!1;try{n&&Tc(e.framework)&&(e.framework==="codex"?await Promise.all([tn("codex",d.signal),Gf(d.signal)]):await tn(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 eo(s.root,{recursive:!0}),await eo(l,{recursive:!0}),await eo(s.logs,{recursive:!0}),h(),a||await Mn(l,e.framework,e.cozeIdentity),e.framework==="claude-code"&&await cd(l),h();let g=await me(e.agentId,this.paths).catch(()=>null),w=ff({model:e.model??g?.model}),S=rf(e._meta)??g?.accountId,v=e.patToken??g?.patToken,f=o==="cloud"?e.modelInfo??g?.modelInfo:void 0;if(m=new Xs({agentId:e.agentId,framework:e.framework,workspace:l,model:w.model??Ke,deployType:o,...S?{accountId:S}:{},...v?{patToken:v}:{},...f?{modelInfo:f}:{}}),m.status="ok",g?.sessions){for(let[R,D]of Object.entries(g.sessions))m.sessions.set(R,{acpSessionId:D.acpSessionId,modelToken:D.modelToken,tokenGeneratedAt:D.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let T=Object.keys(g.sessions).length;T>0&&K.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:T})}this.registry.register(m),u=!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),f&&(y.modelInfo=f),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)):K.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 T=[...y.skills??[]],R=new Map(T.map((G,M)=>[G.skillId,M])),D=await Promise.allSettled(E.map(G=>wc({agentId:e.agentId,workspace:l,framework:e.framework,skill:G}))),C=0;for(let[G,M]of D.entries()){let ae=E[G];ae&&(M.status==="fulfilled"?(yc(T,R,M.value),C++):K.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:ae.skillId,skillName:ae.skillName,err:String(M.reason)}))}C>0&&(y.skills=T,K.info("initialSkills installed",{agentId:e.agentId,installed:C,requested:E.length}))}return await Ae(y,this.paths),K.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 K.error("agent create failed, rolling back",{agentId:e.agentId,err:String(h)}),u&&m&&(await m.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await _E(s.root,{recursive:!0,force:!0}).catch(g=>K.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"&&Tc(e.framework))a=kE;else throw new _("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);if(Tc(e.framework)&&!Or(e.framework)){let d=Zo(e.framework);K.info("spawn: ensuring acp wrapper installed",{agentId:e.agentId,framework:e.framework,reusingInFlight:!!d}),await tn(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(bE),l}catch(d){let p=l instanceof ct?l.getStderrTail():[];throw p.length>0&&K.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=Sc(i);if(n.deployType==="local"){let m=this.config.frameworksCache?.openclaw?.defaultAgent;if(!m?.id||!m.workspace){K.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)K.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 ar({command:a,cwd:m.workspace,agentId:m.id,sessionName:c})}let l=await Jf(),d=r?yf(r,s,o):null,p;if(d){let m=dc(i),h=d.models[0]?.id??Ke,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 ar({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=dc(r),s=`${i}/${e.model}`,o=!0;try{await n.removeProvider(i)}catch(a){o=!1,K.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:i,err:String(a)})}try{await n.removeModelFromAllowlist(s)}catch(a){o=!1,K.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:s,err:String(a)})}o&&this.ensuredProviders.delete(s)}}};import{randomUUID as Qf}from"node:crypto";import{promises as FE}from"node:fs";import{basename as eh}from"node:path";Te();F();import{promises as OE}from"node:fs";import{basename as PE}from"node:path";var Zf=b("file-upload"),CE="/api/coze_claw/file/agent_upload",DE=6e4;async function Kf(t,e={}){let r=`${Gs(js(e.handshakeBase))}${CE}`,i=e.timeoutMs??DE,s=await OE.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",...tr(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},c=new AbortController,l=setTimeout(()=>c.abort(),i);Zf.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 u=m.data?.file?.file_url;if(!u)throw new _("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${p}: ${JSON.stringify(m).slice(0,200)}`);return Zf.info("file upload ok",{uri:u,logid:p}),{uri:u}}catch(d){throw d instanceof _?d:d.name==="AbortError"?new _("UPLOAD_FAILED",`upload timeout (${i}ms) for ${PE(t.path)}`):new _("UPLOAD_FAILED",String(d),{cause:d})}finally{clearTimeout(l)}}Te();F();import{extname as NE}from"node:path";var LE={".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 Xf(t){let e=NE(t).toLowerCase();return LE[e]??"application/octet-stream"}re();var no=b("agent-send"),Yf=50*1024*1024;function th(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 nh(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&&(no.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 rh(t,e){let{session:n,runtime:r}=th(e.core,t.agentId,t.sessionId);if(!await Dr(t.path,n.workspace))throw new _("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let i=await FE.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>Yf)throw new _("FILE_TOO_LARGE",`${i.size} bytes > limit ${Yf}`);let s=await Xf(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??eh(t.path),a;try{a=await Kf({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 no.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:Qf(),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 nh(e,n,r,t.sessionId,c,"agent file uploaded to cloud but sendAgentFileUpdate failed"),no.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 ih(t,e){let{session:n,runtime:r}=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??eh(t.path),s={sessionUpdate:"group_file",messageId:Qf(),content:{uri:t.path,name:i,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await nh(e,n,r,t.sessionId,s,"agent group file sendAgentFileUpdate failed"),no.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 sh(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}nn();gt();F();var lt=b("coze-cli-installer"),oh="@coze/cli@latest",ME="coze",ah="0.1.8",BE=5e3,UE=5e3,zE=9e4,ch=1e4,wi=null,ro=!1;async function Rc(t,e={}){if(ro)return;if(wi)return wi;let n=e.exec??Cn;return wi=(async()=>{try{let r=await $E(ME,n),i=!1;if(r){let o=await GE(n);if(o===void 0)lt.warn("coze-cli found but version unparseable, fall through to full install",{path:r});else if(sh(o,ah))lt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:r,version:o,min:ah}),i=!0;else{lt.info("coze-cli already on PATH with sufficient version, skip",{path:r,version:o}),ro=!0;return}}let s=i?"upgrade-only":"full";lt.info("coze-cli install start",{package:oh,mode:s});try{await n("npm",["i","-g","--prefer-online",oh],{timeout:zE,maxBuffer:10*1024*1024}),lt.info("coze-cli install ok")}catch(o){lt.warn("coze-cli install failed (skip subsequent steps)",{err:String(o)});return}if(i){ro=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:ch}),lt.info("coze config set xTTEnv ok",{env:t.env})}catch(o){lt.warn("coze config set failed (continue to auth login)",{err:String(o)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:ch}),lt.info("coze auth login ok")}catch(o){lt.warn("coze auth login failed",{err:String(o)});return}ro=!0}finally{wi=null}})(),wi}async function $E(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:r}=await e(n,[t],{timeout:BE});return Ji(r)}catch{return}}async function GE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:UE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Cr();re();var HE=10*6e4;function lh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?HE:e}function io(t){return Ln(t??L().configFile)}function cr(t,e){return Fn(e??L().configFile,t)}import{randomBytes as lS}from"node:crypto";zi();Te();F();import{createReadStream as jE}from"node:fs";import{mkdir as WE,readFile as qE,realpath as JE,stat as VE,writeFile as ZE}from"node:fs/promises";import{basename as KE,dirname as kc,isAbsolute as XE,join as YE,relative as QE,resolve as dh,sep as eS}from"node:path";import{createInterface as tS}from"node:readline";var fh=b("fs-rpc"),yi=pt("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function hh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>yi)throw new _("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${yi} bytes`);let r=await gh(t.path,e);return await WE(kc(r),{recursive:!0}),await ZE(r,t.content,"utf8"),fh.info("fs/write_text_file ok",{path:r,size:t.content.length}),null}async function ph(t,e){let n=await gh(t.path,e),r=await VE(n),i=typeof t.line=="number"||typeof t.limit=="number";if(r.size>yi&&!i)throw new _("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${r.size} bytes > ${yi} bytes`);let s;if(i&&r.size>yi)s=await nS(n,t.line??1,t.limit);else{let o=await qE(n,"utf8");if(i){let a=o.split(`
97
+ `)||t.includes("\r")||t.includes("$")||t.includes("#"))return!0;let e=t[0];return e==="'"||e==='"'}var kE={path:"",version:"cloud-deployed"},bE={protocolVersion:1,clientCapabilities:{fs:{readTextFile:!0,writeTextFile:!0}}},AE=6e4,eo=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??AE,this.detectorFactory=e.detectorFactory??(()=>new yn),this.openclawConfigFactory=e.openclawConfigFactory??(n=>new Ys({command:n})),this.openclawConfigDir=e.openclawConfigDir??Vf(vE(),".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=>{K.warn("openclaw env bootstrap failed (ignored)",{err:String(e)}),this.openclawEnvBootstrapPromise=void 0}),this.openclawEnvBootstrapPromise)}async doBootstrapOpenclawEnv(){let e=this.openclawConfigDir,n=Vf(e,".env");if(await EE(n).then(s=>s.isFile()).catch(()=>!1)){K.debug("openclaw .env exists, skip bootstrap",{envFile:n});return}await Qs(e,{recursive:!0});let i=TE({...process.env,...Ec(this.paths.agentEnvFile)});if(await SE(n,i,"utf8"),process.platform!=="win32")try{await yE(n,384)}catch(s){K.warn("chmod ~/.openclaw/.env to 0600 failed (ignored)",{err:String(s)})}K.info("openclaw .env bootstrapped",{envFile:n,bytes:i.length}),await this.getOpenclawConfig().restartGateway(),K.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=oi(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")K.warn("existing agent in error state, rebuilding",{agentId:e.agentId}),await r.dispose("rebuild after error").catch(h=>K.warn("dispose stale agent failed (ignored)",{err:String(h)})),this.registry.unregister(e.agentId);else{if(e.patToken&&e.patToken!==r.patToken){K.info("updating agent patToken on re-create (reconnect with new PAT)",{agentId:e.agentId}),r.setPatToken(e.patToken);let h=await we(e.agentId,this.paths).catch(()=>null);h&&(h.patToken=e.patToken,await Ae(h,this.paths))}if(r.deployType==="cloud"&&e.modelInfo){K.info("updating agent modelInfo on re-create",{agentId:e.agentId}),r.setModelInfo(e.modelInfo);let h=await we(e.agentId,this.paths).catch(()=>null);h&&(h.modelInfo=e.modelInfo,await Ae(h,this.paths))}return K.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=be(e.agentId,this.paths),o=oi(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,u=!1;try{n&&Tc(e.framework)&&(e.framework==="codex"?await Promise.all([en("codex",d.signal),Gf(d.signal)]):await en(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 Qs(s.root,{recursive:!0}),await Qs(l,{recursive:!0}),await Qs(s.logs,{recursive:!0}),h(),a||await Mn(l,e.framework,e.cozeIdentity),e.framework==="claude-code"&&await cd(l),h();let g=await we(e.agentId,this.paths).catch(()=>null),w=ff({model:e.model??g?.model}),S=rf(e._meta)??g?.accountId,v=e.patToken??g?.patToken,f=o==="cloud"?e.modelInfo??g?.modelInfo:void 0;if(m=new Ks({agentId:e.agentId,framework:e.framework,workspace:l,model:w.model??Ke,deployType:o,...S?{accountId:S}:{},...v?{patToken:v}:{},...f?{modelInfo:f}:{}}),m.status="ok",g?.sessions){for(let[R,D]of Object.entries(g.sessions))m.sessions.set(R,{acpSessionId:D.acpSessionId,modelToken:D.modelToken,tokenGeneratedAt:D.tokenGeneratedAt,lastActiveAt:Date.now(),loadingSession:!1,replySeq:0});let T=Object.keys(g.sessions).length;T>0&&K.info("restored persisted session records (no spawn)",{agentId:e.agentId,count:T})}this.registry.register(m),u=!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),f&&(y.modelInfo=f),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)):K.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 T=[...y.skills??[]],R=new Map(T.map((G,M)=>[G.skillId,M])),D=await Promise.allSettled(E.map(G=>wc({agentId:e.agentId,workspace:l,framework:e.framework,skill:G}))),C=0;for(let[G,M]of D.entries()){let ae=E[G];ae&&(M.status==="fulfilled"?(yc(T,R,M.value),C++):K.warn("initialSkill install failed (skipping)",{agentId:e.agentId,skillId:ae.skillId,skillName:ae.skillName,err:String(M.reason)}))}C>0&&(y.skills=T,K.info("initialSkills installed",{agentId:e.agentId,installed:C,requested:E.length}))}return await Ae(y,this.paths),K.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 K.error("agent create failed, rolling back",{agentId:e.agentId,err:String(h)}),u&&m&&(await m.dispose("rollback").catch(()=>{}),this.registry.unregister(e.agentId)),await _E(s.root,{recursive:!0,force:!0}).catch(g=>K.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"&&Tc(e.framework))a=kE;else throw new _("AGENT_SPAWN_FAILED",`framework ${e.framework} not detected on this machine`);if(Tc(e.framework)&&!xr(e.framework)){let d=Zo(e.framework);K.info("spawn: ensuring acp wrapper installed",{agentId:e.agentId,framework:e.framework,reusingInFlight:!!d}),await en(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(bE),l}catch(d){let p=l instanceof ct?l.getStderrTail():[];throw p.length>0&&K.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=Sc(i);if(n.deployType==="local"){let m=this.config.frameworksCache?.openclaw?.defaultAgent;if(!m?.id||!m.workspace){K.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)K.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 ar({command:a,cwd:m.workspace,agentId:m.id,sessionName:c})}let l=await Jf(),d=r?yf(r,s,o):null,p;if(d){let m=dc(i),h=d.models[0]?.id??Ke,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 ar({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=dc(r),s=`${i}/${e.model}`,o=!0;try{await n.removeProvider(i)}catch(a){o=!1,K.warn("removeProvider failed, keeping ensuredProviders entry",{providerId:i,err:String(a)})}try{await n.removeModelFromAllowlist(s)}catch(a){o=!1,K.warn("removeModelFromAllowlist failed, keeping ensuredProviders entry",{fullModelId:s,err:String(a)})}o&&this.ensuredProviders.delete(s)}}};import{randomUUID as Qf}from"node:crypto";import{promises as FE}from"node:fs";import{basename as eh}from"node:path";Te();F();import{promises as OE}from"node:fs";import{basename as PE}from"node:path";var Zf=b("file-upload"),CE="/api/coze_claw/file/agent_upload",DE=6e4;async function Kf(t,e={}){let r=`${$s(Hs(e.handshakeBase))}${CE}`,i=e.timeoutMs??DE,s=await OE.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",...tr(e.ppeOverride),...t.accountId?{"x-coze-account":t.accountId}:{}},c=new AbortController,l=setTimeout(()=>c.abort(),i);Zf.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 u=m.data?.file?.file_url;if(!u)throw new _("UPLOAD_FAILED",`upload response missing data.file.file_url logid=${p}: ${JSON.stringify(m).slice(0,200)}`);return Zf.info("file upload ok",{uri:u,logid:p}),{uri:u}}catch(d){throw d instanceof _?d:d.name==="AbortError"?new _("UPLOAD_FAILED",`upload timeout (${i}ms) for ${PE(t.path)}`):new _("UPLOAD_FAILED",String(d),{cause:d})}finally{clearTimeout(l)}}Te();F();import{extname as NE}from"node:path";var LE={".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 Xf(t){let e=NE(t).toLowerCase();return LE[e]??"application/octet-stream"}re();var to=b("agent-send"),Yf=50*1024*1024;function th(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 nh(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&&(to.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 rh(t,e){let{session:n,runtime:r}=th(e.core,t.agentId,t.sessionId);if(!await Cr(t.path,n.workspace))throw new _("PATH_OUTSIDE_WORKSPACE",`path=${t.path} not under workspace=${n.workspace}`);let i=await FE.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>Yf)throw new _("FILE_TOO_LARGE",`${i.size} bytes > limit ${Yf}`);let s=await Xf(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??eh(t.path),a;try{a=await Kf({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 to.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:Qf(),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 nh(e,n,r,t.sessionId,c,"agent file uploaded to cloud but sendAgentFileUpdate failed"),to.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 ih(t,e){let{session:n,runtime:r}=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??eh(t.path),s={sessionUpdate:"group_file",messageId:Qf(),content:{uri:t.path,name:i,mimeType:t.mimeType,...t.caption!==void 0?{caption:t.caption}:{}}};return await nh(e,n,r,t.sessionId,s,"agent group file sendAgentFileUpdate failed"),to.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 sh(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}tn();gt();F();var lt=b("coze-cli-installer"),oh="@coze/cli@latest",ME="coze",ah="0.1.8",BE=5e3,UE=5e3,zE=9e4,ch=1e4,mi=null,no=!1;async function Rc(t,e={}){if(no)return;if(mi)return mi;let n=e.exec??Cn;return mi=(async()=>{try{let r=await $E(ME,n),i=!1;if(r){let o=await GE(n);if(o===void 0)lt.warn("coze-cli found but version unparseable, fall through to full install",{path:r});else if(sh(o,ah))lt.info("coze-cli version too old, upgrade-only (preserve user config + auth)",{path:r,version:o,min:ah}),i=!0;else{lt.info("coze-cli already on PATH with sufficient version, skip",{path:r,version:o}),no=!0;return}}let s=i?"upgrade-only":"full";lt.info("coze-cli install start",{package:oh,mode:s});try{await n("npm",["i","-g","--prefer-online",oh],{timeout:zE,maxBuffer:10*1024*1024}),lt.info("coze-cli install ok")}catch(o){lt.warn("coze-cli install failed (skip subsequent steps)",{err:String(o)});return}if(i){no=!0;return}if(t.env)try{await n("coze",["config","set","xTTEnv",t.env],{timeout:ch}),lt.info("coze config set xTTEnv ok",{env:t.env})}catch(o){lt.warn("coze config set failed (continue to auth login)",{err:String(o)})}try{await n("coze",["auth","login","--token",t.patToken],{timeout:ch}),lt.info("coze auth login ok")}catch(o){lt.warn("coze auth login failed",{err:String(o)});return}no=!0}finally{mi=null}})(),mi}async function $E(t,e){let n=process.platform==="win32"?"where":"which";try{let{stdout:r}=await e(n,[t],{timeout:BE});return qi(r)}catch{return}}async function GE(t){try{let{stdout:e,stderr:n}=await t("coze",["--version"],{timeout:UE});return(e||n).match(/(\d+\.\d+\.\d+)/)?.[1]}catch{return}}Pr();re();var HE=10*6e4;function lh(t){let e=t?.sessionIdleTimeoutMs;return typeof e!="number"||!Number.isFinite(e)||e<=0?HE:e}function ro(t){return Ln(t??L().configFile)}function wi(t,e){return Fn(e??L().configFile,t)}import{randomBytes as lS}from"node:crypto";Ui();Te();F();import{createReadStream as jE}from"node:fs";import{mkdir as WE,readFile as qE,realpath as JE,stat as VE,writeFile as ZE}from"node:fs/promises";import{basename as KE,dirname as kc,isAbsolute as XE,join as YE,relative as QE,resolve as dh,sep as eS}from"node:path";import{createInterface as tS}from"node:readline";var fh=b("fs-rpc"),yi=pt("COZE_BRIDGE_FS_RPC_MAX_BYTES",20*1024*1024);async function hh(t,e){let n=Buffer.byteLength(t.content,"utf8");if(n>yi)throw new _("IPC_BAD_REQUEST",`fs/write_text_file content too large: ${n} bytes > limit ${yi} bytes`);let r=await gh(t.path,e);return await WE(kc(r),{recursive:!0}),await ZE(r,t.content,"utf8"),fh.info("fs/write_text_file ok",{path:r,size:t.content.length}),null}async function ph(t,e){let n=await gh(t.path,e),r=await VE(n),i=typeof t.line=="number"||typeof t.limit=="number";if(r.size>yi&&!i)throw new _("IPC_BAD_REQUEST",`fs/read_text_file too large without line/limit slicing: ${r.size} bytes > ${yi} bytes`);let s;if(i&&r.size>yi)s=await nS(n,t.line??1,t.limit);else{let o=await qE(n,"utf8");if(i){let a=o.split(`
98
98
  `),c=Math.max(0,(t.line??1)-1),l=typeof t.limit=="number"?c+t.limit:void 0;s=a.slice(c,l).join(`
99
99
  `)}else s=o}return fh.info("fs/read_text_file ok",{path:n,size:s.length}),{content:s}}async function nS(t,e,n){let r=tS({input:jE(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(`
100
- `)}async function gh(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([uh(dh(e)),uh(dh(t))]),i=QE(n,r);if(rS(i,eS,XE(i)))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return r}function rS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function uh(t){let e=[],n=t;for(;n!==kc(n);)try{let r=await JE(n);return e.length?YE(r,...e.reverse()):r}catch{e.push(KE(n)),n=kc(n)}return t}F();var mh=b("prompt-multimodal"),wh=10*1024*1024,iS=15e3,sS=6;async function yh(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 oS(o))}}let i=Array.from({length:Math.min(sS,t.length)},()=>r());return await Promise.all(i),e}function _h(t){return t.some(e=>e.type==="image")}async function oS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!$s(e.uri))return t;try{let{buf:n,contentType:r}=await cS(e.uri),i=e.mimeType||aS(r)||"application/octet-stream";return mh.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 mh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function aS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function cS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),iS);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>wh)throw new Error(`image too large: ${i.byteLength} bytes (max ${wh})`);return{buf:Buffer.from(i),contentType:r.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}At();Te();F();var P=b("core"),dS=3e4,uS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,fS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",hS="\u5BA1\u6279\u5DF2\u8D85\u65F6",pS=3e4,so=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new or;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=lh(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}),gi(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(Ht(i,{code:U.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:U.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:U.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(Js(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&&uS.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,U.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(sr(n,s));return}if(e.method.startsWith("session/")){let i=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(sr(n,i));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(sr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,U.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(Ht(n,pi(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=sc(n._meta);return P.info("session in pendingPermission, bouncing new prompt",{agentId:i.agentId,cloudSessionId:s}),this.synthesizePromptReply(i,c,s,fS,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}=sf(r);switch(n){case"session/new":{let s=gS();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=sc(r._meta);if(l?e.activeGroupIds.set(a.acpSessionId,l):e.activeGroupIds.delete(a.acpSessionId),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&_h(s.prompt))throw new _("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let d=await yh(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 u=a.acpSessionId,h=u?e.activeTriggers.get(u):void 0,g=u?e.activeGroupIds.get(u):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,hS,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(Ze.GEN_MODEL_TOKEN,r,pS);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(gi(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(gi(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(ir("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(ir("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(wS(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(ir("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:U.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 hh(s,i);n.respondAgentRequest(r.id,o)}else{let s=r.params??{},o=await ph(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,pi(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 u={...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(fi(i,"session/request_permission",u)).catch(h=>{this.pendingUpstream.delete(i),P.error("forward permission request failed",{agentId:e.agentId,err:String(h)}),n.respondAgentRequestError(r.id,{code:U.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"&&mS(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 qs(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=dS){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(fi(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 Nr(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(Ht(e,{code:n,message:r,data:{bridgeVersion:rr}}))}};function gS(){return lS(16).toString("hex")}function mS(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 wS(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 `")}F();re();import{randomBytes as yS}from"node:crypto";import{chmod as _S,mkdir as ES,writeFile as Eh}from"node:fs/promises";import{createServer as SS}from"node:http";import{dirname as vS}from"node:path";var IS=1e6,bc=b("ipc"),oo=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??L()}async start(){this.token=yS(32).toString("hex");let e=SS((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(),bc.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 ES(vS(this.paths.portFile),{recursive:!0}),await Eh(this.paths.portFile,String(this.port),"utf8"),await Eh(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await _S(this.paths.tokenFile,384)}catch(e){bc.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){_i(n,401,{error:"unauthorized"});return}let i=`${e.method} ${(e.url??"").split("?")[0]}`,s=this.routes.get(i);if(!s){_i(n,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await TS(e)}catch(a){_i(n,400,{error:"invalid json",detail:String(a)});return}try{let a=await s.handler(o,e);_i(n,200,a??{ok:!0})}catch(a){bc.error("IPC handler failed",{key:i,err:String(a)}),_i(n,500,{error:a instanceof Error?a.message:String(a)})}}};function _i(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function TS(t){let e=[],n=0;for await(let i of t){let s=i;if(n+=s.length,n>IS)throw new Error("body too large");e.push(s)}let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):null}var xh="";function FS(t=""){let n=`${Date.now()}`,r=xh||(xh=zS(t)),i=Math.random().toString(16).slice(-6);return"02"+n+r+i}function MS(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function BS(t){return(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8)}function Oh(t){return(Array(4).join("0")+parseInt(t,2).toString(16)).slice(-4)}function US(t){let e=t.split(/\./).map(i=>BS(i)),n=[];return n[0]=Oh(e[0]+e[1]),n[1]=Oh(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",n[0],n[1]].join("")}function zS(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?US(t):n?$S(t):"00000000000000000000000000000000"}function $S(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 GS(t,e){let n=t.key;n!==void 0&&(ye(e,10),Sn(e,n));let r=t.value;r!==void 0&&(ye(e,18),Sn(e,r))}function HS(t){let e={};e:for(;!jh(t);){let n=ke(t);switch(n>>>3){case 0:break e;case 1:e.key=En(t,ke(t));break;case 2:e.value=En(t,ke(t));break;default:$h(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 zh(t){let e=Hh();return jS(t,e),KS(e)}function jS(t,e){let n=t.SeqID;n!==void 0&&(ye(e,8),Si(e,n));let r=t.LogID;r!==void 0&&(ye(e,16),Si(e,r));let i=t.service;i!==void 0&&(ye(e,24),Si(e,Nc(i)));let s=t.method;s!==void 0&&(ye(e,32),Si(e,Nc(s)));let o=t.headers;if(o!==void 0)for(let h of o){ye(e,42);let g=Hh();GS(h,g),ye(e,g.limit),QS(e,g),VS(g)}let a=t.payloadEncoding;a!==void 0&&(ye(e,50),Sn(e,a));let c=t.payloadType;c!==void 0&&(ye(e,58),Sn(e,c));let l=t.payload;l!==void 0&&(ye(e,66),ye(e,l.length),YS(e,l));let d=t.LogIDNew;d!==void 0&&(ye(e,74),Sn(e,d));let p=t.serverTiming;p!==void 0&&(ye(e,82),Sn(e,p));let m=t.msgID;m!==void 0&&(ye(e,90),Sn(e,m));let u=t.frameType;u!==void 0&&(ye(e,96),Si(e,Nc(u)))}function WS(t){return qS(ZS(t))}function qS(t){let e={};e:for(;!jh(t);){let n=ke(t);switch(n>>>3){case 0:break e;case 1:e.SeqID=Ch(t,!0);break;case 2:e.LogID=Ch(t,!0);break;case 3:e.service=ke(t);break;case 4:e.method=ke(t);break;case 5:{let r=JS(t);(e.headers||(e.headers=[])).push(HS(t)),t.limit=r;break}case 6:e.payloadEncoding=En(t,ke(t));break;case 7:e.payloadType=En(t,ke(t));break;case 8:e.payload=XS(t,ke(t));break;case 9:e.LogIDNew=En(t,ke(t));break;case 10:e.serverTiming=En(t,ke(t));break;case 11:e.msgID=En(t,ke(t));break;case 12:e.frameType=ke(t);break;default:$h(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 JS(t){let e=ke(t),n=t.limit;return t.limit=t.offset+e,n}function $h(t,e){switch(e){case 0:for(;128&ze(t););break;case 2:Lc(t,ke(t));break;case 5:Lc(t,4);break;case 1:Lc(t,8);break;default:throw new Error("Unimplemented type: "+e)}}function Nc(t){return t|=0,{low:t,high:t>>31,unsigned:t>=0}}var Gh=[];function Hh(){let t=Gh.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function VS(t){Gh.push(t)}function ZS(t){return{bytes:t,offset:0,limit:t.length}}function KS(t){let e=t.bytes,n=t.limit;return e.length===n?e:e.subarray(0,n)}function Lc(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function jh(t){return t.offset>=t.limit}function Ti(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 Qc(t,e){let n=t.offset;if(n+e>t.limit)throw new Error("Read past limit");return t.offset+=e,n}function XS(t,e){let n=Qc(t,e);return t.bytes.subarray(n,n+e)}function YS(t,e){let n=Ti(t,e.length);t.bytes.set(e,n)}function En(t,e){let n=Qc(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 Sn(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}ye(t,r);let i=Ti(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 QS(t,e){let n=Ti(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 ze(t){return t.bytes[Qc(t,1)]}function Ph(t,e){let n=Ti(t,1);t.bytes[n]=e}function ke(t){let e=0,n=0,r;do r=ze(t),e<32&&(n|=(127&r)<<e),e+=7;while(128&r);return n}function ye(t,e){for(e>>>=0;e>=128;)Ph(t,127&e|128),e>>>=7;Ph(t,e)}function Ch(t,e){let n=0,r=0,i=0,s;return s=ze(t),n=127&s,128&s&&(s=ze(t),n|=(127&s)<<7,128&s&&(s=ze(t),n|=(127&s)<<14,128&s&&(s=ze(t),n|=(127&s)<<21,128&s&&(s=ze(t),r=127&s,128&s&&(s=ze(t),r|=(127&s)<<7,128&s&&(s=ze(t),r|=(127&s)<<14,128&s&&(s=ze(t),r|=(127&s)<<21,128&s&&(s=ze(t),i=127&s,128&s&&(s=ze(t),i|=(127&s)<<7))))))))),{low:n|r<<28,high:r>>>4|i<<24,unsigned:e}}function Si(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=Ti(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 e0(t){return WS(t)}function Dh(t){return zh(t)}var Nh=65536,t0="\0\0\0\0\0\0\0\0",lr=Nh*Nh,Wh=lr*lr,Lh=Wh/2,Jt=String.prototype.charCodeAt,Ne=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===t0?Fh: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?n0:Fh;if(n){if(e>=Wh)return i0}else{if(e<=-Lh)return s0;if(e+1>=Lh)return r0}return t.fromBits(e%lr|0,e/lr|0,n)}toNumber(){return this.unsigned?(this.high>>>0)*lr+(this.low>>>0):this.high*lr+(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,u=0;return u+=s+l,m+=u>>>16,u&=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|u,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]}},Fh=new Ne(0,0,!1),n0=new Ne(0,0,!0),r0=Ne.fromBits(-1,2147483647,!1),i0=Ne.fromBits(-1,-1,!0),s0=Ne.fromBits(0,-2147483648,!1),_n=(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})({}),vn=class{constructor(e){this.type=e,this.target=null}},Mc=class extends vn{constructor(e,n){super(e),this.message=n&&n.message||null}},Bc=class extends vn{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}},Uc=class extends vn{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}},zc=class extends vn{constructor(e,n){super(e),this.data=n&&n.data||null}},$c=class extends zc{constructor(e,n){super(e),this.data=n&&n.data||null,this.message=n&&n.message||null}},Gc=class extends vn{constructor(e,n){super(e),this.data=n&&n.data||null}};function Xe(t,{message:e,code:n,error:r}){return new Bc(t,{message:e,code:n,error:r})}function dt(t,{code:e,reason:n,wasClean:r,willReconnect:i}){return new Uc(t,{code:e,reason:n,wasClean:r,willReconnect:i})}function o0(t,{data:e,message:n}){return new $c(t,{data:e,message:n})}function a0(t,{data:e}){return new Gc(t,{data:e})}function Mh(t,{message:e}){return new Mc(t,{message:e})}var ao=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()}},ur=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",In=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",Ri=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",vi=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",c0=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,Ii=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}},Hc=class extends Ii{_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,Ri&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:n,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),In&&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=Xe("error",{message:this._formatErrorMessage(e)});this.emit("error",n);let r=dt("close",{reason:this._formatErrorMessage(e)});this.emit("close",r)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",a0("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",dt("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",o0("message",{...e}))}),this._socket.onError(e=>{this.emit("error",Xe("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",Xe("error",{message:this._formatErrorMessage(r)}))}})}else this._socket&&this._socket.send({data:e,fail:n=>{this.emit("error",Xe("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 l0(t,e){if(e)return new e(t.url,t.protocol);if(Ri||In)return new Hc(t.url,t.protocol,t.headers);if((ur||vi)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(t.url,t.protocols)}function d0(t){return!!(t||Ri&&wx.connectSocket||In&&tt.connectSocket||(ur||vi)&&typeof WebSocket<"u"&&WebSocket)}function Bh(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 qh(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 Jh(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 jc(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 Vh(t){if(typeof t=="string"){let e=new Uint8Array(qh(t));return jc(t,e,0),e}return t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function u0(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 f0=(t,e)=>{switch(t){case"boe":case"ppe":return{[`x-use-${t}`]:1,"x-tt-env":e};default:return{}}},Wc=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 h0(t){return new Promise(e=>{if(!ur)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 Vt(t,e,n){return!!t?.find(r=>r.key===e&&r.value===n)}function dr(t,e){return t?.find(n=>n.key===e)?.value}var Fc=null;async function p0(){return Fc||(Fc=Promise.resolve().then(()=>(Ah(),bh))),Fc}var qc=class extends Ii{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 p0();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}}},Jc=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}},Vc=class{constructor(e,n){this._DBName=e,this._pathKey=n,this._qosDB=In?tt:Ri?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 Zh(t,e){if(In||In)return new Vc(t,e);if((ur||vi)&&typeof indexedDB<"u")return new qc(t,e);if((ur||vi)&&typeof localStorage<"u")return new Jc(t,e);throw new Error("init QoSDB failed")}var Zc=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Zh("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 el(t){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let n=Vt(t.message.headers,"x_frontier_qos","2"),r=n&&Vt(t.message.headers,"x_frontier_qos_ack","1"),i=n&&Vt(t.message.headers,"x_frontier_is_ack","1"),s=i?dr(t.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:n,isQoSAck:r,isAckCleanupMessage:i,ackMsgIds:s}}async function Kh(){return this._QoSManager||(this._QoSManager=new Zc),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function g0(t,e){let{enableAutoAck:n}=this._options,r=Vt(t.message.headers,"need_ack","1"),i=Vt(t.message.headers,"is_ack","1"),s=el.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 m0(t,e){this._debug("received",t.message),e()}async function w0(t,e){let n=e0(await Vh(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=Jh(n.payload,0,n.payload.byteLength):n.textPayload=""}else n.textPayload=""}catch(r){n.textPayload="",console.log(r)}t.message=n,e()}function y0(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 _0=4294967295;function E0(t,e,n){if(n>_0)throw new Error("integer too large");let r=3;for(;r>=0;){let i=255&n;Xc(i,t,e+r),n>>>=8,r--}return e+4}function S0(t,e){let n=0,r=e,i=e+4;for(;r<i;){let{value:s,offset:o}=Kc(t,r);r=o,n=n<<8>>>0,n+=s}return{value:n,offset:i}}function v0(t,e,n){return t?t.length<40?jc(t,e,n)+n:e.utf8Write?e.utf8Write(t,n)+n:e.write?e.write(t,n)+n:jc(t,e,n)+n:n}function I0(t,e){let n=new Ne(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 T0(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 Kc(t,e){return t.readUInt8?{value:t.readUInt8(e),offset:e+1}:{value:255&t[e],offset:e+1}}function Xc(t,e,n){return e.writeUint8?e.writeUint8(t,n):e[n]=255&t,n+1}var R0=function(t){return new Uint8Array(t)},k0=typeof Buffer<"u"?Buffer.allocUnsafe:y0(R0,Uint8Array.prototype.subarray),b0=16,tl=32;function A0(t){let e=0,n={};for(let r=0;r<t.length;r++)n[t[r].cursor_name]=qh(t[r].cursor_name),e+=14+n[t[r].cursor_name];return[e,n]}function Uh(t,e,n){let[r,i]=A0(t),s=k0(r),o=0;return t.forEach(a=>{console.log("cursor.service",a,a.service),o=Xc(0,s,o),console.log("header",o),o=E0(s,o,a.service||0),console.log("service",o),o=Xc(i[a.cursor_name],s,o),console.log("service-name",o),o=v0(a.cursor_name,s,o),console.log("name",o),o=T0(Ne.fromNumber(a.cursor||e),s,o),console.log("curvalue",o)}),{frameType:tl,headers:[{key:"cursor_file_name",value:n}],payload:s}}function x0(t){let e=0,n=[];for(;e<t.byteLength;){let{offset:r}=Kc(t,e);e=r;let i={cursor_name:"",cursor:0,service:0},{value:s,offset:o}=S0(t,e);i.service=s,e=o;let{value:a,offset:c}=Kc(t,e);e=c,i.cursor_name=Jh(t,e,e+a),e+=a;let{value:l,offset:d}=I0(t,e);i.cursor=l.toNumber(),e=d,n.push(i)}return n}function O0(){return{frameType:tl,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var Yc=class{constructor(e,n,r){this._cursorNameSpace=e,this._cursorFileName=n,this._messageStrategy=r,this._qosDB=Zh(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?Uh(n,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return n&&n.length?Uh(n,0,this._cursorFileName):O0()}}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=x0(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}},P0="__x_msg_qos__";async function Xh(t){if(!this._options.enableQoS)return null;let{aID:e,fpID:n,messageStrategy:r}=this._options,i=t||P0;try{return this._cursorManager?t&&this._cursorManager.updateCursorFileName(t):this._cursorManager=new Yc(`${n}_${e}_${i}`,i,r),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function C0(t,e){let n=Vt(t.message.headers,"code","-1"),r=Vt(t.message.headers,"is_ack","1"),i=dr(t.message.headers,"x_frontier_msgid"),s=Number(dr(t.message.headers,"x_frontier_ttl"))||0,o=el.call(this,t),a=Vt(t.message.headers,"x-msg-qos","2"),c=dr(t.message.headers,"x-msg-cursor_name"),l=Number(dr(t.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await Kh.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 Xh.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 D0(t,e){let n=el.call(this,t);if(!n.isQoSMessage)return e();let r=await Kh.call(this);if(n.isAckCleanupMessage&&n.ackMsgIds.length)for(let i of n.ackMsgIds)await r.del(i);e()}async function N0(t,e){let n=t.message.frameType===b0,r=t.message.frameType===tl;if(!n&&!r)return e();let i=dr(t.message.headers,"cursor_file_name");if(!i)return e();let s=await Xh.call(this,i);if(!s)return e();if(n){let o=await s.getCursors(),a={frameType:o?.frameType,SeqID:Ne.fromNumber(this._seqId++),LogID:Ne.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=zh(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(r){let o=t.message.payload;o&&s.setCursors(o)}}var L0=async function(t,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},F0=async function(t,e){let n=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${n}`),e()},M0=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()},co=class extends Ii{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=ur,this._isNode=c0,this._isMiniTT=In,this._isMiniWX=Ri,this._isWorker=vi,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{Bh(this,s,[L0,M0,F0])}catch(o){let a=Xe("error",{message:o.message,code:_n.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{Bh(this,s,[w0,g0,D0,N0,C0,m0])}catch(c){let l=Xe("error",{message:c.message,code:_n.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(Xe("error",{message:c,code:_n.MAX_RETRIES_ERROR,error:s}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Xe("error",{message:s.message,code:_n.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(dt("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(dt("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 h0(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(dt("close",{code:s.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(Xe("error",{message:l,code:_n.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&!s.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(dt("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:MS,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(!d0(r))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new ao(i,this._options.maxRetries),this._pingLossCounter=new Wc(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=Mh("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,u,h,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(u=location&&location.protocol=="https:"?"wss://":"ws://",h=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${u}${h}`):(u="wss://",h=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(h)?h:`${u}${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,f=m?f0(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,...f},v),E=Object.keys(y).reduce((T,R)=>y[R]!==void 0?`${T}${T?"&":"?"}${R}=${y[R]}`:T,"");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=Xe("error",{message:a,code:_n.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(Xe("error",{message:a,code:_n.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=Mh("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=l0({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=Dh(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(dt("close",{code:1006,reason:`connect ${s} timeout, max retries reached`,wasClean:!0}))}else{let s=this._options.reconnectInterceptor(e,n);this._dispatchCloseEvent(dt("close",{code:e,reason:n,wasClean:!0,willReconnect:s})),s&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(dt("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(dt("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 Vh(e),i=u0(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?FS(this._options.logIDNewConfig.userIp):""}=n||{};if(!o)throw new Error("please provide a valid service");let m={SeqID:Ne.fromNumber(this._seqId++),LogID:Ne.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},u=Dh(m);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(u),this._debug("sent",m)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(u),this._debug("enqueue",m)):(this._messageQueue.shift(),this._messageQueue.push(u)),{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 ao(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 rI=ht(qp(),1),iI=ht(yo(),1),sI=ht(pr(),1),oI=ht(fl(),1),aI=ht(gl(),1),cI=ht(Sl(),1),tg=ht(vo(),1),lI=ht(eg(),1);var ng=tg.default;Te();F();var ne=b("upstream.frontier"),ig="application/json",sg="none",uI=15e3;function fI(t){class e extends ng{constructor(r){super(r,af,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",r=>ne.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:r instanceof Error?r.message:String(r)}))}close(r,i){this.guardTeardown(),super.close(r,i)}terminate(){this.guardTeardown(),super.terminate()}send(r,...i){if(Ul("debug"))try{let s;typeof r=="string"?s=Buffer.from(r,"utf8"):r instanceof Buffer?s=r:r instanceof ArrayBuffer?s=new Uint8Array(r):ArrayBuffer.isView(r)?s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength):s=new Uint8Array(0);let o=Buffer.from(s.slice(0,128)).toString("hex");ne.debug("WS raw frame out",{bytes:s.byteLength,headHex:o})}catch(s){ne.warn("WS raw frame dump failed",{err:String(s)})}super.send(r,...i)}}return e}var Di=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:cf,...tr(this.opts.ppeOverride)},n=fI(e),r=df(this.opts.urlOverride),i={url:r,ws:n,fpID:of,aID:Hs,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:ig,force:!0},payloadEncoding:{encoding:sg,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},s=new co(i),o=!1,a=null,c,l,d=new Promise((u,h)=>{c=u,l=h}),p=u=>{o||(o=!0,a&&(clearTimeout(a),a=null),u?l(u):c())};s.onopen=()=>{this.opened=!0,this.openCount+=1;let u=this.openCount===1;ne.info("frontier opened",{url:r,remoteDeviceId:this.opts.handshake.deviceId,initial:u,openCount:this.openCount}),u&&p();for(let h of this.connectHandlers)Promise.resolve(h({initial:u})).catch(g=>ne.warn("onConnect handler threw (ignored)",{err:String(g)}))},s.onclose=u=>{this.opened=!1,ne.info("frontier closed",{code:u.code,reason:u.reason,willReconnect:u.willReconnect})},s.onerror=u=>{ne.warn("frontier error",{code:u.code,msg:u.message}),p(new _("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${u.code} msg=${u.message??""}`))},s.onmessage=u=>this.handleMessage(u),this.fws=s;let m=this.opts.openTimeoutMs??uI;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(u){try{s.close(1e3,"open failed")}catch(h){ne.warn("fws close during start failure threw (ignored)",{err:String(h)})}throw this.fws=null,this.opened=!1,u}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(r){ne.warn("frontier close threw (ignored)",{err:String(r)})}}}async send(e){let n=this.fws,r=e.method;if(!n)throw ne.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?(ne.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;og(s)||ne.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:i.length});try{await n.send(i,{service:33555712,method:1,payloadType:ig,payloadEncoding:sg})}catch(a){throw ne.warn("frontier frame send failed",{method:s.method,jsonrpcId:s.id,err:String(a)}),new _("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(a)}`,{cause:a})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let 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){ne.debug("drop non-adapter frontier frame",{service:n});return}let r=gI(e);if(!r){ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ne.debug("frame received but no onFrame handler",{size:r.length});return}let i;try{i=JSON.parse(r)}catch(o){ne.warn("frontier message JSON parse failed",{err:String(o),head:r.slice(0,80)});return}let s=i;og(s)||ne.info("frontier frame in",{logid:pI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id,method:s.method,body:hI(r)}),Promise.resolve(this.handler(i)).catch(o=>ne.warn("frontier frame handler threw",{err:String(o)}))}};function og(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var ag=2e3;function hI(t){return t.length<=ag?t:`${t.slice(0,ag)}...<truncated, total ${t.length} chars>`}function pI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function gI(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}}F();var Il=b("upstream.switchable"),To=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Il.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 Il.error("swap target start failed, reverting",{err:String(i)}),this.inner=r,i}await r.stop(n??"swapped").catch(i=>Il.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 Tl=b("upstream"),Er=class{handler=null;async start(){Tl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Tl.info("NoopUpstream stopped",{reason:e})}async send(e){Tl.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)}};Te();F();F();re();import{promises as Rl}from"node:fs";import{dirname as mI}from"node:path";var wI=b("pat-token-store");async function Ro(t=L()){try{let n=(await Rl.readFile(t.patTokenFile,"utf8")).trim();return n.length>0?n:null}catch(e){let n=e?.code;return n!=="ENOENT"&&wI.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function Ni(t,e=L()){if(!t)throw new Error("writePatToken: empty patToken");await Rl.mkdir(mI(e.patTokenFile),{recursive:!0}),await Rl.writeFile(e.patTokenFile,t,{encoding:"utf8",mode:384})}re();re();import{promises as ko}from"node:fs";import{join as yI}from"node:path";function _I(t,e){return`#!/bin/sh
100
+ `)}async function gh(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([uh(dh(e)),uh(dh(t))]),i=QE(n,r);if(rS(i,eS,XE(i)))throw new _("IPC_BAD_REQUEST",`path escapes workspace: ${t}`);return r}function rS(t,e,n){return t===""?!1:n?!0:t===".."||t.startsWith(`..${e}`)}async function uh(t){let e=[],n=t;for(;n!==kc(n);)try{let r=await JE(n);return e.length?YE(r,...e.reverse()):r}catch{e.push(KE(n)),n=kc(n)}return t}F();var mh=b("prompt-multimodal"),wh=10*1024*1024,iS=15e3,sS=6;async function yh(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 oS(o))}}let i=Array.from({length:Math.min(sS,t.length)},()=>r());return await Promise.all(i),e}function _h(t){return t.some(e=>e.type==="image")}async function oS(t){if(t.type!=="image")return t;let e=t;if(e.data||!e.uri||!zs(e.uri))return t;try{let{buf:n,contentType:r}=await cS(e.uri),i=e.mimeType||aS(r)||"application/octet-stream";return mh.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 mh.warn("image fetch failed, degrading to text block",{uri:e.uri,err:String(n)}),{type:"text",text:`[image load failed: ${e.uri}]`}}}function aS(t){if(!t)return;let e=t.indexOf(";");return(e===-1?t:t.slice(0,e)).trim()||void 0}async function cS(t){let e=new AbortController,n=setTimeout(()=>e.abort(),iS);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>wh)throw new Error(`image too large: ${i.byteLength} bytes (max ${wh})`);return{buf:Buffer.from(i),contentType:r.headers.get("content-type")??void 0}}finally{clearTimeout(n)}}At();Te();F();var P=b("core"),dS=3e4,uS=/^(boe|ppe)_[A-Za-z0-9_-]+$/,fS="\u6211\u6B63\u5728\u7B49\u5F85\u5BA1\u6279\uFF0C\u8BF7\u7A0D\u540E\u518D\u8054\u7CFB\u6211",hS="\u5BA1\u6279\u5DF2\u8D85\u65F6",pS=3e4,io=class{upstream;agents=new Map;disconnectedAgents=new Set;extensions;paths;sessionSpawner;sessionIdleTimeoutMs;upstreamIds=new or;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=lh(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)}async reloadAgents(e){let n=e?this.agents.has(e)?[e]:[]:[...this.agents.keys()];for(let r of n)await this.agents.get(r)?.killAllRuntimes("reload");return n}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}),pi(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(Ht(i,{code:U.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:U.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:U.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(qs(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&&uS.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,U.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(sr(n,s));return}if(e.method.startsWith("session/")){let i=await this.routeSessionMethod(e);n!==null&&await this.upstream.send(sr(n,i));return}if(e.method==="initialize"){n!==null&&await this.upstream.send(sr(n,{protocolVersion:1,agentCapabilities:{loadSession:!0}}));return}n!==null?await this.sendError(n,U.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(Ht(n,hi(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=sc(n._meta);return P.info("session in pendingPermission, bouncing new prompt",{agentId:i.agentId,cloudSessionId:s}),this.synthesizePromptReply(i,c,s,fS,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}=sf(r);switch(n){case"session/new":{let s=gS();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=sc(r._meta);if(l?e.activeGroupIds.set(a.acpSessionId,l):e.activeGroupIds.delete(a.acpSessionId),e.deployType==="cloud"&&e.modelInfo?.capabilities?.image===!1&&_h(s.prompt))throw new _("MODEL_MODALITY_UNSUPPORTED",`model=${e.modelInfo.id??e.model} does not support image input`);let d=await yh(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 u=a.acpSessionId,h=u?e.activeTriggers.get(u):void 0,g=u?e.activeGroupIds.get(u):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,hS,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(Ze.GEN_MODEL_TOKEN,r,pS);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(pi(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(pi(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(ir("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(ir("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(wS(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(ir("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:U.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 hh(s,i);n.respondAgentRequest(r.id,o)}else{let s=r.params??{},o=await ph(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,hi(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 u={...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(ui(i,"session/request_permission",u)).catch(h=>{this.pendingUpstream.delete(i),P.error("forward permission request failed",{agentId:e.agentId,err:String(h)}),n.respondAgentRequestError(r.id,{code:U.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"&&mS(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 Ws(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=dS){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(ui(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 Dr(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(Ht(e,{code:n,message:r,data:{bridgeVersion:rr}}))}};function gS(){return lS(16).toString("hex")}function mS(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 wS(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 `")}F();re();import{randomBytes as yS}from"node:crypto";import{chmod as _S,mkdir as ES,writeFile as Eh}from"node:fs/promises";import{createServer as SS}from"node:http";import{dirname as vS}from"node:path";var IS=1e6,bc=b("ipc"),so=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??L()}async start(){this.token=yS(32).toString("hex");let e=SS((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(),bc.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 ES(vS(this.paths.portFile),{recursive:!0}),await Eh(this.paths.portFile,String(this.port),"utf8"),await Eh(this.paths.tokenFile,this.token,{encoding:"utf8",mode:384});try{await _S(this.paths.tokenFile,384)}catch(e){bc.warn("chmod token file failed (non-POSIX?)",{err:String(e)})}}async dispatch(e,n){if(e.headers.authorization!==`Bearer ${this.token}`){_i(n,401,{error:"unauthorized"});return}let i=`${e.method} ${(e.url??"").split("?")[0]}`,s=this.routes.get(i);if(!s){_i(n,404,{error:"not found"});return}let o=null;if(e.method==="POST")try{o=await TS(e)}catch(a){_i(n,400,{error:"invalid json",detail:String(a)});return}try{let a=await s.handler(o,e);_i(n,200,a??{ok:!0})}catch(a){bc.error("IPC handler failed",{key:i,err:String(a)}),_i(n,500,{error:a instanceof Error?a.message:String(a)})}}};function _i(t,e,n){t.statusCode=e,t.setHeader("content-type","application/json"),t.end(JSON.stringify(n))}async function TS(t){let e=[],n=0;for await(let i of t){let s=i;if(n+=s.length,n>IS)throw new Error("body too large");e.push(s)}let r=Buffer.concat(e).toString("utf8");return r?JSON.parse(r):null}var xh="";function FS(t=""){let n=`${Date.now()}`,r=xh||(xh=zS(t)),i=Math.random().toString(16).slice(-6);return"02"+n+r+i}function MS(){return 1e4*Date.now()+Math.floor(1e4*Math.random())}function BS(t){return(Array(8).join("0")+parseInt(t,10).toString(2)).slice(-8)}function Oh(t){return(Array(4).join("0")+parseInt(t,2).toString(16)).slice(-4)}function US(t){let e=t.split(/\./).map(i=>BS(i)),n=[];return n[0]=Oh(e[0]+e[1]),n[1]=Oh(e[2]+e[3]),["0000","0000","0000","0000","0000","ffff",n[0],n[1]].join("")}function zS(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?US(t):n?$S(t):"00000000000000000000000000000000"}function $S(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 GS(t,e){let n=t.key;n!==void 0&&(_e(e,10),Sn(e,n));let r=t.value;r!==void 0&&(_e(e,18),Sn(e,r))}function HS(t){let e={};e:for(;!jh(t);){let n=ke(t);switch(n>>>3){case 0:break e;case 1:e.key=En(t,ke(t));break;case 2:e.value=En(t,ke(t));break;default:$h(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 zh(t){let e=Hh();return jS(t,e),KS(e)}function jS(t,e){let n=t.SeqID;n!==void 0&&(_e(e,8),Si(e,n));let r=t.LogID;r!==void 0&&(_e(e,16),Si(e,r));let i=t.service;i!==void 0&&(_e(e,24),Si(e,Nc(i)));let s=t.method;s!==void 0&&(_e(e,32),Si(e,Nc(s)));let o=t.headers;if(o!==void 0)for(let h of o){_e(e,42);let g=Hh();GS(h,g),_e(e,g.limit),QS(e,g),VS(g)}let a=t.payloadEncoding;a!==void 0&&(_e(e,50),Sn(e,a));let c=t.payloadType;c!==void 0&&(_e(e,58),Sn(e,c));let l=t.payload;l!==void 0&&(_e(e,66),_e(e,l.length),YS(e,l));let d=t.LogIDNew;d!==void 0&&(_e(e,74),Sn(e,d));let p=t.serverTiming;p!==void 0&&(_e(e,82),Sn(e,p));let m=t.msgID;m!==void 0&&(_e(e,90),Sn(e,m));let u=t.frameType;u!==void 0&&(_e(e,96),Si(e,Nc(u)))}function WS(t){return qS(ZS(t))}function qS(t){let e={};e:for(;!jh(t);){let n=ke(t);switch(n>>>3){case 0:break e;case 1:e.SeqID=Ch(t,!0);break;case 2:e.LogID=Ch(t,!0);break;case 3:e.service=ke(t);break;case 4:e.method=ke(t);break;case 5:{let r=JS(t);(e.headers||(e.headers=[])).push(HS(t)),t.limit=r;break}case 6:e.payloadEncoding=En(t,ke(t));break;case 7:e.payloadType=En(t,ke(t));break;case 8:e.payload=XS(t,ke(t));break;case 9:e.LogIDNew=En(t,ke(t));break;case 10:e.serverTiming=En(t,ke(t));break;case 11:e.msgID=En(t,ke(t));break;case 12:e.frameType=ke(t);break;default:$h(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 JS(t){let e=ke(t),n=t.limit;return t.limit=t.offset+e,n}function $h(t,e){switch(e){case 0:for(;128&ze(t););break;case 2:Lc(t,ke(t));break;case 5:Lc(t,4);break;case 1:Lc(t,8);break;default:throw new Error("Unimplemented type: "+e)}}function Nc(t){return t|=0,{low:t,high:t>>31,unsigned:t>=0}}var Gh=[];function Hh(){let t=Gh.pop();return t?(t.offset=t.limit=0,t):{bytes:new Uint8Array(64),offset:0,limit:0}}function VS(t){Gh.push(t)}function ZS(t){return{bytes:t,offset:0,limit:t.length}}function KS(t){let e=t.bytes,n=t.limit;return e.length===n?e:e.subarray(0,n)}function Lc(t,e){if(t.offset+e>t.limit)throw new Error("Skip past limit");t.offset+=e}function jh(t){return t.offset>=t.limit}function Ti(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 Qc(t,e){let n=t.offset;if(n+e>t.limit)throw new Error("Read past limit");return t.offset+=e,n}function XS(t,e){let n=Qc(t,e);return t.bytes.subarray(n,n+e)}function YS(t,e){let n=Ti(t,e.length);t.bytes.set(e,n)}function En(t,e){let n=Qc(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 Sn(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}_e(t,r);let i=Ti(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 QS(t,e){let n=Ti(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 ze(t){return t.bytes[Qc(t,1)]}function Ph(t,e){let n=Ti(t,1);t.bytes[n]=e}function ke(t){let e=0,n=0,r;do r=ze(t),e<32&&(n|=(127&r)<<e),e+=7;while(128&r);return n}function _e(t,e){for(e>>>=0;e>=128;)Ph(t,127&e|128),e>>>=7;Ph(t,e)}function Ch(t,e){let n=0,r=0,i=0,s;return s=ze(t),n=127&s,128&s&&(s=ze(t),n|=(127&s)<<7,128&s&&(s=ze(t),n|=(127&s)<<14,128&s&&(s=ze(t),n|=(127&s)<<21,128&s&&(s=ze(t),r=127&s,128&s&&(s=ze(t),r|=(127&s)<<7,128&s&&(s=ze(t),r|=(127&s)<<14,128&s&&(s=ze(t),r|=(127&s)<<21,128&s&&(s=ze(t),i=127&s,128&s&&(s=ze(t),i|=(127&s)<<7))))))))),{low:n|r<<28,high:r>>>4|i<<24,unsigned:e}}function Si(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=Ti(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 e0(t){return WS(t)}function Dh(t){return zh(t)}var Nh=65536,t0="\0\0\0\0\0\0\0\0",cr=Nh*Nh,Wh=cr*cr,Lh=Wh/2,qt=String.prototype.charCodeAt,Ne=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===t0?Fh:new t((qt.call(e,0)|qt.call(e,1)<<8|qt.call(e,2)<<16|qt.call(e,3)<<24)>>>0,(qt.call(e,4)|qt.call(e,5)<<8|qt.call(e,6)<<16|qt.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?n0:Fh;if(n){if(e>=Wh)return i0}else{if(e<=-Lh)return s0;if(e+1>=Lh)return r0}return t.fromBits(e%cr|0,e/cr|0,n)}toNumber(){return this.unsigned?(this.high>>>0)*cr+(this.low>>>0):this.high*cr+(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,u=0;return u+=s+l,m+=u>>>16,u&=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|u,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]}},Fh=new Ne(0,0,!1),n0=new Ne(0,0,!0),r0=Ne.fromBits(-1,2147483647,!1),i0=Ne.fromBits(-1,-1,!0),s0=Ne.fromBits(0,-2147483648,!1),_n=(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})({}),vn=class{constructor(e){this.type=e,this.target=null}},Mc=class extends vn{constructor(e,n){super(e),this.message=n&&n.message||null}},Bc=class extends vn{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}},Uc=class extends vn{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}},zc=class extends vn{constructor(e,n){super(e),this.data=n&&n.data||null}},$c=class extends zc{constructor(e,n){super(e),this.data=n&&n.data||null,this.message=n&&n.message||null}},Gc=class extends vn{constructor(e,n){super(e),this.data=n&&n.data||null}};function Xe(t,{message:e,code:n,error:r}){return new Bc(t,{message:e,code:n,error:r})}function dt(t,{code:e,reason:n,wasClean:r,willReconnect:i}){return new Uc(t,{code:e,reason:n,wasClean:r,willReconnect:i})}function o0(t,{data:e,message:n}){return new $c(t,{data:e,message:n})}function a0(t,{data:e}){return new Gc(t,{data:e})}function Mh(t,{message:e}){return new Mc(t,{message:e})}var oo=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()}},dr=(typeof globalThis<"u"&&globalThis.constructor.name==="Window"||typeof window<"u"&&window.constructor.name==="Window")&&typeof document<"u",In=typeof globalThis<"u"&&(globalThis.constructor.name==="Object"||globalThis.constructor.name==="DedicatedWorkerGlobalScope")&&typeof tt<"u",Ri=(typeof globalThis<"u"&&globalThis.constructor.name==="Object"||typeof globalThis>"u"||typeof globalThis<"u"&&!!globalThis.WeixinJSBridge)&&typeof wx<"u",vi=typeof globalThis<"u"&&(globalThis.constructor.name==="DedicatedWorkerGlobalScope"||globalThis.constructor.name==="SharedWorkerGlobalScope"||globalThis.constructor.name==="ServiceWorkerGlobalScope")&&typeof self<"u",c0=typeof globalThis<"u"&&globalThis.constructor.name==="Object"&&typeof global<"u"&&global.constructor.name==="Object"&&typeof process<"u"&&!!process.version,Ii=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}},Hc=class extends Ii{_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,Ri&&wx.connectSocket&&(this._socket=wx.connectSocket({url:e,protocols:n,header:r,fail:this._createSocketFailHandler.bind(this),success:this._createSocketSuccessHandler.bind(this)})),In&&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=Xe("error",{message:this._formatErrorMessage(e)});this.emit("error",n);let r=dt("close",{reason:this._formatErrorMessage(e)});this.emit("close",r)})}_addWsListeners(){this._socket.onOpen(e=>{this.emit("open",a0("open",{...e,data:e.errMsg||""}))}),this._socket.onClose(e=>{this.emit("close",dt("close",{...e}))}),this._socket.onMessage(e=>{this.emit("message",o0("message",{...e}))}),this._socket.onError(e=>{this.emit("error",Xe("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",Xe("error",{message:this._formatErrorMessage(r)}))}})}else this._socket&&this._socket.send({data:e,fail:n=>{this.emit("error",Xe("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 l0(t,e){if(e)return new e(t.url,t.protocol);if(Ri||In)return new Hc(t.url,t.protocol,t.headers);if((dr||vi)&&typeof WebSocket<"u"&&WebSocket)return new WebSocket(t.url,t.protocols)}function d0(t){return!!(t||Ri&&wx.connectSocket||In&&tt.connectSocket||(dr||vi)&&typeof WebSocket<"u"&&WebSocket)}function Bh(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 qh(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 Jh(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 jc(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 Vh(t){if(typeof t=="string"){let e=new Uint8Array(qh(t));return jc(t,e,0),e}return t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength)}function u0(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 f0=(t,e)=>{switch(t){case"boe":case"ppe":return{[`x-use-${t}`]:1,"x-tt-env":e};default:return{}}},Wc=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 h0(t){return new Promise(e=>{if(!dr)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 Jt(t,e,n){return!!t?.find(r=>r.key===e&&r.value===n)}function lr(t,e){return t?.find(n=>n.key===e)?.value}var Fc=null;async function p0(){return Fc||(Fc=Promise.resolve().then(()=>(Ah(),bh))),Fc}var qc=class extends Ii{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 p0();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}}},Jc=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}},Vc=class{constructor(e,n){this._DBName=e,this._pathKey=n,this._qosDB=In?tt:Ri?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 Zh(t,e){if(In||In)return new Vc(t,e);if((dr||vi)&&typeof indexedDB<"u")return new qc(t,e);if((dr||vi)&&typeof localStorage<"u")return new Jc(t,e);throw new Error("init QoSDB failed")}var Zc=class{constructor(){this._intervalTimeoutId=null,this._interval=36e5,this._qosDB=Zh("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 el(t){let e=!!this._options.enableQoS;if(!e)return{enabled:e,isQoSMessage:!1,isQoSAck:!1,isAckCleanupMessage:!1,ackMsgIds:[]};let n=Jt(t.message.headers,"x_frontier_qos","2"),r=n&&Jt(t.message.headers,"x_frontier_qos_ack","1"),i=n&&Jt(t.message.headers,"x_frontier_is_ack","1"),s=i?lr(t.message.headers,"x_frontier_ack_msgid")?.split(",").filter(Boolean)||[]:[];return{enabled:e,isQoSMessage:n,isQoSAck:r,isAckCleanupMessage:i,ackMsgIds:s}}async function Kh(){return this._QoSManager||(this._QoSManager=new Zc),this._QoSManager.isReady||await this._QoSManager.openDB(),this._QoSManager}async function g0(t,e){let{enableAutoAck:n}=this._options,r=Jt(t.message.headers,"need_ack","1"),i=Jt(t.message.headers,"is_ack","1"),s=el.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 m0(t,e){this._debug("received",t.message),e()}async function w0(t,e){let n=e0(await Vh(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=Jh(n.payload,0,n.payload.byteLength):n.textPayload=""}else n.textPayload=""}catch(r){n.textPayload="",console.log(r)}t.message=n,e()}function y0(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 _0=4294967295;function E0(t,e,n){if(n>_0)throw new Error("integer too large");let r=3;for(;r>=0;){let i=255&n;Xc(i,t,e+r),n>>>=8,r--}return e+4}function S0(t,e){let n=0,r=e,i=e+4;for(;r<i;){let{value:s,offset:o}=Kc(t,r);r=o,n=n<<8>>>0,n+=s}return{value:n,offset:i}}function v0(t,e,n){return t?t.length<40?jc(t,e,n)+n:e.utf8Write?e.utf8Write(t,n)+n:e.write?e.write(t,n)+n:jc(t,e,n)+n:n}function I0(t,e){let n=new Ne(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 T0(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 Kc(t,e){return t.readUInt8?{value:t.readUInt8(e),offset:e+1}:{value:255&t[e],offset:e+1}}function Xc(t,e,n){return e.writeUint8?e.writeUint8(t,n):e[n]=255&t,n+1}var R0=function(t){return new Uint8Array(t)},k0=typeof Buffer<"u"?Buffer.allocUnsafe:y0(R0,Uint8Array.prototype.subarray),b0=16,tl=32;function A0(t){let e=0,n={};for(let r=0;r<t.length;r++)n[t[r].cursor_name]=qh(t[r].cursor_name),e+=14+n[t[r].cursor_name];return[e,n]}function Uh(t,e,n){let[r,i]=A0(t),s=k0(r),o=0;return t.forEach(a=>{console.log("cursor.service",a,a.service),o=Xc(0,s,o),console.log("header",o),o=E0(s,o,a.service||0),console.log("service",o),o=Xc(i[a.cursor_name],s,o),console.log("service-name",o),o=v0(a.cursor_name,s,o),console.log("name",o),o=T0(Ne.fromNumber(a.cursor||e),s,o),console.log("curvalue",o)}),{frameType:tl,headers:[{key:"cursor_file_name",value:n}],payload:s}}function x0(t){let e=0,n=[];for(;e<t.byteLength;){let{offset:r}=Kc(t,e);e=r;let i={cursor_name:"",cursor:0,service:0},{value:s,offset:o}=S0(t,e);i.service=s,e=o;let{value:a,offset:c}=Kc(t,e);e=c,i.cursor_name=Jh(t,e,e+a),e+=a;let{value:l,offset:d}=I0(t,e);i.cursor=l.toNumber(),e=d,n.push(i)}return n}function O0(){return{frameType:tl,headers:[{key:"cursor_file_name",value:"FILE_NOT_EXIST"}],payload:void 0}}var Yc=class{constructor(e,n,r){this._cursorNameSpace=e,this._cursorFileName=n,this._messageStrategy=r,this._qosDB=Zh(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?Uh(n,0,this._cursorFileName):void 0;case"INSTANT":return;case"CONTINUE":return n&&n.length?Uh(n,0,this._cursorFileName):O0()}}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=x0(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}},P0="__x_msg_qos__";async function Xh(t){if(!this._options.enableQoS)return null;let{aID:e,fpID:n,messageStrategy:r}=this._options,i=t||P0;try{return this._cursorManager?t&&this._cursorManager.updateCursorFileName(t):this._cursorManager=new Yc(`${n}_${e}_${i}`,i,r),this._cursorManager.isReady||await this._cursorManager.openDB(),this._cursorManager}catch{return null}}async function C0(t,e){let n=Jt(t.message.headers,"code","-1"),r=Jt(t.message.headers,"is_ack","1"),i=lr(t.message.headers,"x_frontier_msgid"),s=Number(lr(t.message.headers,"x_frontier_ttl"))||0,o=el.call(this,t),a=Jt(t.message.headers,"x-msg-qos","2"),c=lr(t.message.headers,"x-msg-cursor_name"),l=Number(lr(t.message.headers,"x-msg-cursor_value"));if(o.isQoSAck)return e();let d=o.isQoSMessage?await Kh.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 Xh.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 D0(t,e){let n=el.call(this,t);if(!n.isQoSMessage)return e();let r=await Kh.call(this);if(n.isAckCleanupMessage&&n.ackMsgIds.length)for(let i of n.ackMsgIds)await r.del(i);e()}async function N0(t,e){let n=t.message.frameType===b0,r=t.message.frameType===tl;if(!n&&!r)return e();let i=lr(t.message.headers,"cursor_file_name");if(!i)return e();let s=await Xh.call(this,i);if(!s)return e();if(n){let o=await s.getCursors(),a={frameType:o?.frameType,SeqID:Ne.fromNumber(this._seqId++),LogID:Ne.fromNumber(this._options.logIDGenerator()),service:9e3,method:5,headers:o?.headers,payload:o?.payload},c=zh(a);this._ws&&this._ws.readyState&&this._ws.send(c)}if(r){let o=t.message.payload;o&&s.setCursors(o)}}var L0=async function(t,e){this._isInit=!1,clearTimeout(this._connectionTimeoutId),e()},F0=async function(t,e){let n=this._endpointManager?.getCurrentEndpoint();this._debug(`open ${n}`),e()},M0=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()},ao=class extends Ii{constructor(e){super(),this._miniNavigatorOnline=!0,this._isBrowser=dr,this._isNode=c0,this._isMiniTT=In,this._isMiniWX=Ri,this._isWorker=vi,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{Bh(this,s,[L0,M0,F0])}catch(o){let a=Xe("error",{message:o.message,code:_n.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{Bh(this,s,[w0,g0,D0,N0,C0,m0])}catch(c){let l=Xe("error",{message:c.message,code:_n.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(Xe("error",{message:c,code:_n.MAX_RETRIES_ERROR,error:s}));return}this._ws&&this._ws.readyState===this.OPEN&&this._disconnect(),this._dispatchErrorEvent(Xe("error",{message:s.message,code:_n.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(dt("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(dt("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 h0(this._url)),c=`connecting failed, ${c}, hostname: ${a}, max retries reached`,this._dispatchCloseEvent(dt("close",{code:s.code,reason:c}));let l=`connect ${a} fail, max retries reached`;this._dispatchErrorEvent(Xe("error",{message:l,code:_n.MAX_RETRIES_ERROR})),this._endpointManager?.resetEndpointConfig(),this._pingLossCounter?.resetCounter();return}if(s.code!==1e3&&!s.reason){let a=this._endpointManager?.getCurrentEndpoint();this._dispatchCloseEvent(dt("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:MS,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(!d0(r))throw new Error("please provide ws params, WebSocket constructor is undefined");Object.assign(this._options,e),this._endpointManager=new oo(i,this._options.maxRetries),this._pingLossCounter=new Wc(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=Mh("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,u,h,g;this._isBrowser||this._isMiniWX||this._isMiniTT?(u=location&&location.protocol=="https:"?"wss://":"ws://",h=e.replace(/((^ws)|(^http))((?:[s]*:\/\/))/,""),g=/^wss(.*:\/\/)/.test(e)?e:`${u}${h}`):(u="wss://",h=e.replace(/(^http)((?:[s]*:\/\/))/,""),g=/(^ws)((?:[s]*:\/\/))/.test(h)?h:`${u}${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,f=m?f0(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,...f},v),E=Object.keys(y).reduce((T,R)=>y[R]!==void 0?`${T}${T?"&":"?"}${R}=${y[R]}`:T,"");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=Xe("error",{message:a,code:_n.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(Xe("error",{message:a,code:_n.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=Mh("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=l0({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=Dh(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(dt("close",{code:1006,reason:`connect ${s} timeout, max retries reached`,wasClean:!0}))}else{let s=this._options.reconnectInterceptor(e,n);this._dispatchCloseEvent(dt("close",{code:e,reason:n,wasClean:!0,willReconnect:s})),s&&this._connect()}return}this._navigatorOnline()||this._readyClosed?this._dispatchCloseEvent(dt("close",{code:e,reason:"bye"})):this._dispatchCloseEvent(dt("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 Vh(e),i=u0(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?FS(this._options.logIDNewConfig.userIp):""}=n||{};if(!o)throw new Error("please provide a valid service");let m={SeqID:Ne.fromNumber(this._seqId++),LogID:Ne.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},u=Dh(m);return this._ws&&this._ws.readyState===this.OPEN?(this._ws&&this._ws.send(u),this._debug("sent",m)):this._messageQueue.length<this._options.maxMessageQueueLength?(this._messageQueue.push(u),this._debug("enqueue",m)):(this._messageQueue.shift(),this._messageQueue.push(u)),{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 oo(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 rI=ht(qp(),1),iI=ht(wo(),1),sI=ht(hr(),1),oI=ht(fl(),1),aI=ht(gl(),1),cI=ht(Sl(),1),tg=ht(So(),1),lI=ht(eg(),1);var ng=tg.default;Te();F();var ne=b("upstream.frontier"),ig="application/json",sg="none",uI=15e3;function fI(t){class e extends ng{constructor(r){super(r,af,{headers:t})}guardTeardown(){this.listenerCount("error")===0&&this.on("error",r=>ne.warn("frontier ws error during teardown (handled, prevents daemon crash)",{err:r instanceof Error?r.message:String(r)}))}close(r,i){this.guardTeardown(),super.close(r,i)}terminate(){this.guardTeardown(),super.terminate()}send(r,...i){if(Ul("debug"))try{let s;typeof r=="string"?s=Buffer.from(r,"utf8"):r instanceof Buffer?s=r:r instanceof ArrayBuffer?s=new Uint8Array(r):ArrayBuffer.isView(r)?s=new Uint8Array(r.buffer,r.byteOffset,r.byteLength):s=new Uint8Array(0);let o=Buffer.from(s.slice(0,128)).toString("hex");ne.debug("WS raw frame out",{bytes:s.byteLength,headHex:o})}catch(s){ne.warn("WS raw frame dump failed",{err:String(s)})}super.send(r,...i)}}return e}var Di=class{constructor(e){this.opts=e}opts;fws=null;handler=null;connectHandlers=[];opened=!1;lastSendRefusedLogAt=0;sendRefusedSuppressed=0;openCount=0;async start(){if(this.fws){ne.warn("start called on already-started FrontierUpstream; noop");return}let e={Authorization:`Bearer ${this.opts.privatecode}`,Origin:cf,...tr(this.opts.ppeOverride)},n=fI(e),r=df(this.opts.urlOverride),i={url:r,ws:n,fpID:of,aID:Gs,accessKey:this.opts.handshake.accessKey,deviceID:this.opts.handshake.deviceId,payloadType:{type:ig,force:!0},payloadEncoding:{encoding:sg,force:!0},enableTransformTextPayload:!0,enableQoS:!1,enableAutoAck:!1,automaticOpen:!1,maxRetries:Number.POSITIVE_INFINITY,debug:this.opts.debug??!1},s=new ao(i),o=!1,a=null,c,l,d=new Promise((u,h)=>{c=u,l=h}),p=u=>{o||(o=!0,a&&(clearTimeout(a),a=null),u?l(u):c())};s.onopen=()=>{this.opened=!0,this.openCount+=1;let u=this.openCount===1;ne.info("frontier opened",{url:r,remoteDeviceId:this.opts.handshake.deviceId,initial:u,openCount:this.openCount}),u&&p();for(let h of this.connectHandlers)Promise.resolve(h({initial:u})).catch(g=>ne.warn("onConnect handler threw (ignored)",{err:String(g)}))},s.onclose=u=>{this.opened=!1,ne.info("frontier closed",{code:u.code,reason:u.reason,willReconnect:u.willReconnect})},s.onerror=u=>{ne.warn("frontier error",{code:u.code,msg:u.message}),p(new _("UPSTREAM_DISCONNECTED",`frontier connect error before open: code=${u.code} msg=${u.message??""}`))},s.onmessage=u=>this.handleMessage(u),this.fws=s;let m=this.opts.openTimeoutMs??uI;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(u){try{s.close(1e3,"open failed")}catch(h){ne.warn("fws close during start failure threw (ignored)",{err:String(h)})}throw this.fws=null,this.opened=!1,u}}async stop(e){let n=this.fws;if(n){this.fws=null,this.opened=!1;try{n.close(1e3,e??"bridge shutdown")}catch(r){ne.warn("frontier close threw (ignored)",{err:String(r)})}}}async send(e){let n=this.fws,r=e.method;if(!n)throw ne.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?(ne.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;og(s)||ne.info("frontier frame out",{method:s.method,jsonrpcId:s.id,size:i.length});try{await n.send(i,{service:33555712,method:1,payloadType:ig,payloadEncoding:sg})}catch(a){throw ne.warn("frontier frame send failed",{method:s.method,jsonrpcId:s.id,err:String(a)}),new _("UPSTREAM_DISCONNECTED",`frontier send failed: ${String(a)}`,{cause:a})}}onFrame(e){this.handler=e}onConnect(e){this.connectHandlers.push(e)}isConnected(){return this.opened&&this.fws?.readyState===1}injectAgentPatToken(e){let 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){ne.debug("drop non-adapter frontier frame",{service:n});return}let r=gI(e);if(!r){ne.debug("frontier message without text payload, drop",{payloadType:e.message?.payloadType});return}if(!this.handler){ne.debug("frame received but no onFrame handler",{size:r.length});return}let i;try{i=JSON.parse(r)}catch(o){ne.warn("frontier message JSON parse failed",{err:String(o),head:r.slice(0,80)});return}let s=i;og(s)||ne.info("frontier frame in",{logid:pI(e.message?.LogID),logidNew:e.message?.LogIDNew,msgId:e.message?.msgID,jsonrpcId:s.id,method:s.method,body:hI(r)}),Promise.resolve(this.handler(i)).catch(o=>ne.warn("frontier frame handler threw",{err:String(o)}))}};function og(t){return t.method==="_agent/health"?!0:typeof t.id=="string"&&t.id.startsWith("agent.health_")}var ag=2e3;function hI(t){return t.length<=ag?t:`${t.slice(0,ag)}...<truncated, total ${t.length} chars>`}function pI(t){return t?t.high===0?String(t.low>>>0):`${t.high.toString(16)}${(t.low>>>0).toString(16).padStart(8,"0")}`:""}function gI(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}}F();var Il=b("upstream.switchable"),Io=class{inner;handler=null;connectHandlers=[];constructor(e){this.inner=e}async swap(e,n){if(this.inner===e)return;Il.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 Il.error("swap target start failed, reverting",{err:String(i)}),this.inner=r,i}await r.stop(n??"swapped").catch(i=>Il.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 Tl=b("upstream"),_r=class{handler=null;async start(){Tl.info("NoopUpstream started (M1 skeleton; real Frontier wired in M4)")}async stop(e){Tl.info("NoopUpstream stopped",{reason:e})}async send(e){Tl.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)}};Te();F();F();re();import{promises as Rl}from"node:fs";import{dirname as mI}from"node:path";var wI=b("pat-token-store");async function To(t=L()){try{let n=(await Rl.readFile(t.patTokenFile,"utf8")).trim();return n.length>0?n:null}catch(e){let n=e?.code;return n!=="ENOENT"&&wI.warn("read pat-token failed (treating as missing)",{path:t.patTokenFile,code:n,message:e.message}),null}}async function Ni(t,e=L()){if(!t)throw new Error("writePatToken: empty patToken");await Rl.mkdir(mI(e.patTokenFile),{recursive:!0}),await Rl.writeFile(e.patTokenFile,t,{encoding:"utf8",mode:384})}re();re();import{promises as Ro}from"node:fs";import{join as yI}from"node:path";function _I(t,e){return`#!/bin/sh
101
101
  exec ${JSON.stringify(e)} ${JSON.stringify(t)} "$@"
102
102
  `}function EI(t,e){return`@echo off\r
103
103
  "${e}" "${t}" %*\r
104
- `}async function cg(t,e=L()){let n=e.binDir;await ko.mkdir(n,{recursive:!0});let r=yI(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),i=process.execPath,s=process.platform==="win32"?EI(t,i):_I(t,i);return await ko.readFile(r,"utf8").catch(()=>null)===s||(await ko.writeFile(r,s,"utf8"),process.platform!=="win32"&&await ko.chmod(r,493)),n}F();re();import{execSync as lg}from"node:child_process";import{readFileSync as dg,unlinkSync as SI}from"node:fs";import{mkdir as vI,readFile as ug,unlink as fg,writeFile as II}from"node:fs/promises";import{dirname as TI}from"node:path";function bo(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var RI=b("single-instance"),Ao=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??L().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&&(RI.warn("removing stale pid file",{stalePid:e}),await fg(this.pidFile).catch(()=>{})),await vI(TI(this.pidFile),{recursive:!0}),await II(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await ug(this.pidFile,"utf8")).trim()===String(process.pid)&&await fg(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await ug(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 bo(e)?this.matchesDaemonTitle(e):!1}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=dg(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes("coze-bridge-daemon")||n.includes("lib/index.js"))}catch{}try{let n=lg(`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=lg(`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{dg(this.pidFile,"utf8").trim()===String(process.pid)&&SI(this.pidFile)}catch{}})}};xo();F();var xn=b("daemon.upstream-watchdog"),DI=12e4,NI=9e5,LI=3e4;function bl(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var Oo=class{constructor(e){this.opts=e;this.softMs=e.softMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",DI),this.hardMs=e.hardMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",NI),this.intervalMs=e.intervalMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",LI),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),xn.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&xn.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&xn.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,xn.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){xn.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,xn.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(r=>xn.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(r)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var A=b("daemon"),FI="coze-bridge-daemon";async function gg(){let t=L();process.env.COZE_BRIDGE_LOG_MODE!=="legacy"&&Ml({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:I=>be(I,t).logs,listAgentIds:()=>Vi(t)});let e=new Ao({processTitle:FI}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let r=await io(),i=r??{};ji({pid:process.pid}),A.info(r?"loaded bridge config":"initialized bridge config");try{let I=new qt;i.frameworksCache=await I.detectAll(),A.info("refreshed frameworks_cache",{detected:Object.keys(i.frameworksCache)})}catch(I){A.warn("framework detection failed",{err:String(I)})}await cr(i);let s=new To(new Er),o=null,a=new so({upstream:s,paths:t,bridgeConfig:i,sessionSpawner:async(I,x,O,ce)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(I,x,O,ce)}});await BI(t,a);let c=new to({paths:t,config:i,registry:a});o=c;let l,d,p=null,m={},u,h=null,g=null,w=null,S=new jt;function v(I,x){return S.enqueue(()=>y(I,x))}function f(){g||(g=new Oo({isConnected:()=>s.isConnected(),forceReconnect:()=>w?v(w,{force:!0}):void 0,onFatal:I=>{if(process.env[Li]==="1"){A.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:I});return}A.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:I}),process.exit(1)}})),g.start()}async function y(I,x){let O=I,ce=O?.privatecode;if(!ce)throw new _("IPC_BAD_REQUEST","/connect requires privatecode");let He=li(O.env),ft=O.handshake_url,Yt=O.frontier_url,Qt=pg(O.env,ft,Yt);if(w=O,!x?.force&&l===ce&&d===Qt){let Se=await MI(t);return a.agents.size===0&&Se?(A.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Co(t,c).catch(ge=>A.warn("connect-noop auto-revive error (ignored)",{err:String(ge)}))):A.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Tr=!!l&&l!==ce,Rr=d!==void 0&&d!==Qt,kr=Tr||Rr,br=await oc({privatecode:ce,...ft?{endpoint:ft}:{},ppeOverride:He});if(kr){A.warn("connect config switched, resetting agents",{pcChanged:Tr,envChanged:Rr,previousPc:l?Po(l):"",nextPc:Po(ce)});for(let Se of[...a.agents.values()])await Se.dispose("connect config switch").catch(()=>{}),a.agents.delete(Se.agentId);a.disconnectedAgents.size>0&&(A.info("clearing disconnectedAgents set on connect config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await s.swap(new Er,"connect switch").catch(()=>{})}p=br.deviceId,ji({deviceId:p,pid:process.pid}),Rc({patToken:ce,env:O.env}).catch(Se=>A.warn("coze-cli setup error (ignored)",{err:String(Se)}));let $o=new Di({handshake:br,privatecode:ce,...Yt?{urlOverride:Yt}:{},ppeOverride:He,getPatTokenForAgent:Se=>a.agents.get(Se)?.patToken});return await s.swap($o,"connect"),l=ce,d=Qt,m=He,u=ft,O.mock_scenario!==void 0&&(a.setMockScenario(O.mock_scenario),A.info("mock scenario set",{scenario:O.mock_scenario})),h||(h=new ui({core:a,getDeviceId:()=>p??"",onTickEnd:()=>R.retryPending().catch(Se=>A.warn("detailSync.retryPending failed (ignored)",{err:String(Se)})),onAuthFailures:D})),h.start(),f(),kr&&Co(t,c).catch(Se=>A.warn("post-connect-switch auto-revive error (ignored)",{err:String(Se)})),Ni(ce,t).catch(Se=>A.warn("writePatToken after /connect failed (ignored)",{err:String(Se)})),A.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 E={},T=new Ws({agents:a.agents,disposeAndMarkDisconnected:async(I,x)=>{let O=a.agents.get(I);if(O){await c.cleanupOpenclawSessionProviders(O).catch(He=>A.warn("cleanup openclaw providers failed (ignored)",{agentId:I,err:String(He)}));let ce=!0;try{await O.dispose(`disconnect: ${x}`)}catch(He){ce=!1,A.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:I,err:String(He)}),O.status="error"}ce&&(O.status="disconnected",a.unregister(I),a.disconnectedAgents.add(I))}else a.disconnectedAgents.add(I)},detailSyncer:async I=>{if(!E.ref)throw new Error("agent-detail-sync not initialized yet");await E.ref.syncOne(I)},cleanupOpenclawProviders:async I=>{await c.cleanupOpenclawSessionProviders(I)},openclawRepair:async(I,x)=>{await c.openclawRepair(I,x)},isRuntimePendingPermission:I=>a.hasPendingPermissionFor(I)});a.registerExtension("_agent/listSkills",I=>T.listSkills(I.params)),a.registerExtension("_agent/addSkills",I=>T.addSkills(I.params)),a.registerExtension("_agent/removeSkills",I=>T.removeSkills(I.params)),a.registerExtension("_agent/getFileTree",I=>T.getFileTree(I.params)),a.registerExtension("_agent/getFileContent",I=>T.getFileContent(I.params)),a.registerExtension("_agent/update",I=>T.updateAgent(I.params)),a.registerExtension("_agent/disconnect",I=>T.disconnectAgent(I.params)),a.registerExtension("_agent/switchModel",I=>T.switchModel(I.params)),a.registerExtension("_agent/reset",I=>T.resetAgent(I.params)),a.registerExtension("_agent/repair",I=>T.repairAgent(I.params));let R=new Yi({paths:t,handlers:T,sendDetail:I=>a.sendRequest("_agent/detail",I)});E.ref=R;let D=async I=>{await Promise.allSettled(I.map(async x=>{try{await T.disconnectAgent({agentId:x.agentId,reason:`auth_failure: code=${x.code} ${x.message}`}),A.info("agent disconnected due to auth failure from heartbeat response",{agentId:x.agentId,code:x.code,message:x.message})}catch(O){A.warn("disconnect during authFailure handling failed (ignored)",{agentId:x.agentId,err:String(O)})}}))};s.onConnect(({initial:I})=>{A.info("frontier upstream connected, triggering detail sync",{initial:I}),R.syncAll(I?"initial-connect":"reconnect").catch(x=>A.warn("detail sync top-level error (ignored)",{err:String(x)}))});let C=new oo({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let I=a.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[Li]==="1"?"manual":"supervisor",agents:[...a.agents.keys()],deviceId:p??"",frameworksCache:i.frameworksCache??{},...I?{mockScenario:I}:{}}}},{method:"POST",path:"/pair",handler:async I=>{let x=I,O=x?.privatecode,ce=x?.pairing_code;if(!O||!ce)throw new _("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let He=li(x.env),ft=x.handshake_url,Yt=x.frontier_url,Qt=pg(x.env,ft,Yt),Tr=!!l&&l!==O,Rr=d!==void 0&&d!==Qt,kr=Tr||Rr,br=await oc({privatecode:O,...ft?{endpoint:ft}:{},ppeOverride:He});if(kr){A.warn("pair config switched, resetting agents",{pcChanged:Tr,envChanged:Rr,previousPc:l?Po(l):"",nextPc:Po(O),previousEnvKey:d??"",nextEnvKey:Qt});for(let ge of[...a.agents.values()])await ge.dispose("pair config switch").catch(()=>{}),a.agents.delete(ge.agentId);a.disconnectedAgents.size>0&&(A.info("clearing disconnectedAgents set on pair config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await s.swap(new Er,"pair switch").catch(()=>{})}p=br.deviceId,ji({deviceId:p,pid:process.pid}),Rc({patToken:O,env:x.env}).catch(ge=>A.warn("coze-cli setup error (ignored)",{err:String(ge)}));let $o=new Di({handshake:br,privatecode:O,...Yt?{urlOverride:Yt}:{},ppeOverride:He,getPatTokenForAgent:ge=>a.agents.get(ge)?.patToken});await s.swap($o,"pair");try{let ge=new qt;i.frameworksCache=await ge.detectAll(),await cr(i),A.info("frameworks_cache refreshed before pair",{detected:Object.keys(i.frameworksCache)})}catch(ge){A.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(ge)})}let Se=Object.keys(i.frameworksCache??{});try{let ge=await a.sendRequest("_agent/pair",{pairCode:ce,patToken:O,frameworks:Se,_meta:{cozeDeviceId:p}});A.info("_agent/pair ok",{pairResult:ge}),l=O,d=Qt,m=He,u=ft,x.mock_scenario!==void 0&&(a.setMockScenario(x.mock_scenario),A.info("mock scenario set",{scenario:x.mock_scenario})),Ni(O,t).catch(Qe=>A.warn("writePatToken after /pair failed (ignored)",{err:String(Qe)})),h||(h=new ui({core:a,getDeviceId:()=>p??"",onTickEnd:()=>R.retryPending().catch(Qe=>A.warn("detailSync.retryPending failed (ignored)",{err:String(Qe)})),onAuthFailures:D})),h.start(),f(),kr&&Co(t,c).catch(Qe=>A.warn("post-pair-switch auto-revive error (ignored)",{err:String(Qe)}));let Go;return x.agent_id&&(Go=await UI(x.agent_id,t,c,Qe=>a.sendRequest("_agent/detail",Qe),O).catch(Qe=>(A.error("--agent-id ensureAgent failed",{agentId:x.agent_id,err:String(Qe)}),{ok:!1,agentId:x.agent_id??"",note:String(Qe)}))),{ok:!0,note:"paired with cloud",...Go?{agent:Go}:{}}}catch(ge){return A.error("_agent/pair failed",{err:String(ge)}),{ok:!1,note:`pair failed: ${String(ge)}`}}}},{method:"POST",path:"/connect",handler:I=>v(I)},{method:"POST",path:"/_agent/create",handler:async I=>{let x=I;return{ok:!0,result:await c.createAgent(x)}}},{method:"POST",path:"/agent/send",handler:async I=>{let x=I;if(!x?.agentId||!x?.sessionId||!x?.kind||!x?.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 O=x;return await(O.groupFile?ih:rh)(O,{core:a,patToken:l,handshakeBase:u,ppeOverride:m})}catch(O){if(O instanceof _)return{ok:!1,code:O.code,message:O.message};throw O}}},{method:"POST",path:"/refresh",handler:async()=>{A.info("IPC /refresh: re-detecting frameworks");let I=new qt;return i.frameworksCache=await I.detectAll(),await cr(i),{ok:!0,frameworks:i.frameworksCache}}},{method:"POST",path:"/shutdown",handler:async()=>(A.info("IPC /shutdown received"),setImmediate(()=>{Ee.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:G,token:M}=await C.start();try{await cg(t.libEntry,t)}catch(I){A.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(I)})}await a.start(),Co(t,c).catch(I=>A.warn("auto-revive top-level error (ignored)",{err:String(I)})),ed().then(async()=>{let{probeAcpVersion:I}=await Promise.resolve().then(()=>(nn(),Yl));for(let x of["claude-code","codex"]){let O=await I(x);O&&A.info("acp wrapper version",{framework:x,version:O})}}).catch(I=>A.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(I)}));let ae=null,Ee={port:G,token:M,core:a,ipc:C,shutdown(I){return ae||(A.info("daemon shutdown",{reason:I}),ae=(async()=>{h?.stop(),g?.stop(),await a.stop(I),await C.stop(),await e.release()})(),ae)}};for(let I of["SIGTERM","SIGINT"])process.on(I,()=>{Ee.shutdown(I).then(()=>process.exit(0))});return process.on("unhandledRejection",I=>{A.error("unhandledRejection",{reason:I instanceof Error?I.message:String(I),stack:I instanceof Error?I.stack:void 0})}),process.on("uncaughtException",I=>{A.error("uncaughtException (will exit, supervisor will restart)",{message:I.message,stack:I.stack,name:I.name});try{process.stderr.write(`FATAL uncaughtException: ${I.stack??I.message}
105
- `)}catch{}process.exit(1)}),A.info("daemon ready",{port:G,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(i.frameworksCache??{}),libVersion:i.libVersion??"dev"}),zI({cliSpawned:process.env[Li]==="1",readPatToken:()=>Ro(t),connect:v}).catch(I=>A.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(I)})),Ee}async function MI(t){return Vi(t).length>0}function Po(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function pg(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function BI(t,e){let n=Vi(t);if(n.length===0)return;let{loadAgentConfig:r,enforceAgentConfigMode:i}=await Promise.resolve().then(()=>(At(),Xi));for(let s of n){await i(s,t).catch(o=>A.warn("enforceAgentConfigMode failed (ignored)",{agentId:s,err:String(o)}));try{let o=await r(s,t);o?.disconnectedAt&&(e.disconnectedAgents.add(s),A.info("agent marked disconnected on startup",{agentId:s,disconnectedAt:o.disconnectedAt,reason:o.disconnectReason??""}))}catch(o){A.warn("failed to load agent config on startup, skipping",{agentId:s,err:String(o)})}}}async function UI(t,e,n,r,i){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(At(),Xi)),o=await s(t,e);if(o){A.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"}}A.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 Co(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(()=>(At(),Xi));A.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){A.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(l)}),o+=1;continue}if(!c){o+=1;continue}if(c.disconnectedAt){A.info("auto-revive: skip disconnected agent",{agentId:a,disconnectedAt:c.disconnectedAt}),o+=1;continue}try{A.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:a,framework:c.framework});let l=$I(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){A.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(l)}),o+=1}}return A.info("auto-revive: done",{revived:s,skipped:o,total:r.length}),{revived:s,skipped:o,total:r.length}}async function zI(t){let e=t.logger??A;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 $I(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}xo();re();import{readFile as mg}from"node:fs/promises";var bt=class{paths;constructor(e){this.paths=e??L()}async probe(e=1e3){let n=await Do(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:HI(r)}}}async request(e){let n=await Do(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:GI(c)}}finally{clearTimeout(o)}}};async function Do(t){try{let[e,n]=await Promise.all([mg(t.portFile,"utf8"),mg(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 GI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function HI(t){return t instanceof Error?t.message:String(t)}gt();F();re();function Xt(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 wg,mkdir as jI,readFile as Al,writeFile as WI}from"node:fs/promises";import{homedir as vC}from"node:os";import{dirname as qI,resolve as xl,sep as No}from"node:path";import{fileURLToPath as JI}from"node:url";F();re();var yg=b("dist-install");function VI(t){let e=JI(t),n=qI(e),r=`${No}src${No}`;if(n.includes(r)||n.endsWith(`${No}src${No}cli`))return null;let i=xl(n,"index.js"),s=xl(n,"..","package.json");return{dist:i,pkgJson:s}}async function Ol(t={}){let e=t.paths??L(),n=VI(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 Al(i,"utf8")).version??"unknown"}catch(p){return yg.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 io(e.configFile)??{},a=o.libVersion;if(a===s)try{return await Al(e.libEntry),{kind:"already-current",libVersion:s}}catch{}await jI(e.libDir,{recursive:!0}),await wg(r,e.libEntry),await wg(`${r}.map`,`${e.libEntry}.map`).catch(()=>{});let c=xl(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
106
- `;return await Al(c,"utf8").catch(()=>null)!==l&&await WI(c,l),o.libVersion=s,await cr(o,e.configFile),yg.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}}Wo();F();re();import{closeSync as Eg,fstatSync as Sg,openSync as vg,readFileSync as ZI,readSync as KI,readdirSync as XI,statSync as YI}from"node:fs";import{join as Lo}from"node:path";var QI=new Set(["debug","info","warn","error"]);function Ig(t){let e=t,n=Xt(e,"--agent-id");e=n.rest;let r=Xt(e,"--date");e=r.rest;let i=Xt(e,"-n","--lines");e=i.rest;let s=Xt(e,"--level");e=s.rest;let o=Xt(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&&QI.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 eT(t,e){return t.agentId?Lo(be(t.agentId,e).logs,On("agent",t.date)):Lo(e.bridgeLogsDir,On("bridge",t.date))}function tT(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function nT(t,e){let n;try{n=XI(t)}catch{return[]}let r=[];for(let i of n){let s=jo(i,e);if(!s)continue;let o=0;try{o=YI(Lo(t,i)).size}catch{}r.push({file:Lo(t,i),date:s,size:o})}return r.sort((i,s)=>s.date.localeCompare(i.date)),r}function Tg(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"&&!zl(n,e.level))return!1}return!0}var _g={debug:"90",info:"36",warn:"33",error:"31"},rT=new Set(["ts","level","module","msg"]);function iT(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Rg(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let r=iT(n.ts),i=typeof n.level=="string"?n.level:"",s=i.toUpperCase().padEnd(5);e.color&&_g[i]&&(s=`\x1B[${_g[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])=>!rT.has(l)).map(([l,d])=>` ${l}=${typeof d=="string"?d:JSON.stringify(d)}`).join("");return`${r} ${s} ${o} ${a}${c}`}function sT(t,e,n){let s=ZI(t,"utf8").split(`
104
+ `}async function cg(t,e=L()){let n=e.binDir;await Ro.mkdir(n,{recursive:!0});let r=yI(n,process.platform==="win32"?"coze-bridge.cmd":"coze-bridge"),i=process.execPath,s=process.platform==="win32"?EI(t,i):_I(t,i);return await Ro.readFile(r,"utf8").catch(()=>null)===s||(await Ro.writeFile(r,s,"utf8"),process.platform!=="win32"&&await Ro.chmod(r,493)),n}F();re();import{execSync as lg}from"node:child_process";import{readFileSync as dg,unlinkSync as SI}from"node:fs";import{mkdir as vI,readFile as ug,unlink as fg,writeFile as II}from"node:fs/promises";import{dirname as TI}from"node:path";function ko(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}var RI=b("single-instance"),bo=class{pidFile;acquired=!1;constructor(e={}){this.pidFile=e.pidFile??L().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&&(RI.warn("removing stale pid file",{stalePid:e}),await fg(this.pidFile).catch(()=>{})),await vI(TI(this.pidFile),{recursive:!0}),await II(this.pidFile,String(process.pid),"utf8"),this.acquired=!0,this.installCleanupHooks(),{kind:"acquired"})}async release(){if(this.acquired){try{(await ug(this.pidFile,"utf8")).trim()===String(process.pid)&&await fg(this.pidFile)}catch{}this.acquired=!1}}async readExistingPid(){try{let e=await ug(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 ko(e)?this.matchesDaemonTitle(e):!1}matchesDaemonTitle(e){if(process.platform==="win32")return this.matchesDaemonTitleWindows(e);try{let n=dg(`/proc/${e}/cmdline`,"utf8").replace(/\0/g," ");return!!(n.includes("coze-bridge-daemon")||n.includes("lib/index.js"))}catch{}try{let n=lg(`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=lg(`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{dg(this.pidFile,"utf8").trim()===String(process.pid)&&SI(this.pidFile)}catch{}})}};Ao();F();var xn=b("daemon.upstream-watchdog"),DI=12e4,NI=9e5,LI=3e4;function bl(t,e){let n=process.env[t];if(!n)return e;let r=Number(n);return Number.isFinite(r)&&r>0?r:e}var xo=class{constructor(e){this.opts=e;this.softMs=e.softMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_SOFT_MS",DI),this.hardMs=e.hardMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_HARD_MS",NI),this.intervalMs=e.intervalMs??bl("COZE_BRIDGE_UPSTREAM_WATCHDOG_INTERVAL_MS",LI),this.now=e.now??Date.now}opts;softMs;hardMs;intervalMs;now;timer=null;downSince=null;forcedAt=null;forcing=!1;lastTickAt=null;start(){this.timer||(this.timer=setInterval(()=>this.tick(),this.intervalMs),this.timer.unref?.(),xn.info("upstream watchdog started",{softMs:this.softMs,hardMs:this.hardMs,intervalMs:this.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),this.downSince=null,this.forcedAt=null,this.lastTickAt=null}tick(){let e=this.now();if(this.lastTickAt!==null&&e-this.lastTickAt>this.intervalMs*3&&(this.downSince!==null&&xn.warn("upstream watchdog: large tick gap (likely sleep/suspend), resetting downSince",{gapMs:e-this.lastTickAt}),this.downSince=null,this.forcedAt=null),this.lastTickAt=e,this.opts.isConnected()){this.downSince!==null&&xn.info("upstream watchdog: reconnected, reset",{downMs:this.now()-this.downSince}),this.downSince=null,this.forcedAt=null;return}if(this.downSince===null){this.downSince=e,xn.warn("upstream watchdog: disconnect detected, arming",{softMs:this.softMs,hardMs:this.hardMs});return}let n=e-this.downSince;if(n>=this.hardMs){xn.error("upstream watchdog: disconnected too long, exiting for supervisor restart",{downMs:n,hardMs:this.hardMs}),this.opts.onFatal(n);return}n>=this.softMs&&this.shouldForceNow(e)&&(this.forcedAt=e,this.forcing=!0,xn.warn("upstream watchdog: forcing reconnect",{downMs:n,softMs:this.softMs}),Promise.resolve().then(()=>this.opts.forceReconnect()).catch(r=>xn.warn("upstream watchdog: forceReconnect error (ignored)",{err:String(r)})).finally(()=>{this.forcing=!1}))}shouldForceNow(e){return!(this.forcing||this.forcedAt!==null&&e-this.forcedAt<this.softMs)}};var A=b("daemon"),FI="coze-bridge-daemon";async function gg(){let t=L();process.env.COZE_BRIDGE_LOG_MODE!=="legacy"&&Ml({bridgeLogsDir:t.bridgeLogsDir,agentLogsDir:I=>be(I,t).logs,listAgentIds:()=>Ji(t)});let e=new bo({processTitle:FI}),n=await e.acquire();if(n.kind==="already-running")throw new Error(`coze-bridge daemon already running (pid=${n.pid})`);let r=await ro(),i=r??{};Hi({pid:process.pid}),A.info(r?"loaded bridge config":"initialized bridge config");try{let I=new yn;i.frameworksCache=await I.detectAll(),A.info("refreshed frameworks_cache",{detected:Object.keys(i.frameworksCache)})}catch(I){A.warn("framework detection failed",{err:String(I)})}await wi(i);let s=new Io(new _r),o=null,a=new io({upstream:s,paths:t,bridgeConfig:i,sessionSpawner:async(I,x,O,ce)=>{if(!o)throw new Error("agentManager not ready");return o.spawnSessionDownstream(I,x,O,ce)}});await BI(t,a);let c=new eo({paths:t,config:i,registry:a});o=c;let l,d,p=null,m={},u,h=null,g=null,w=null,S=new jt;function v(I,x){return S.enqueue(()=>y(I,x))}function f(){g||(g=new xo({isConnected:()=>s.isConnected(),forceReconnect:()=>w?v(w,{force:!0}):void 0,onFatal:I=>{if(process.env[Li]==="1"){A.error("upstream watchdog fatal, but daemon is unmanaged (CLI-spawned) \u2014 staying alive for soft-reconnect instead of exiting",{downMs:I});return}A.error("upstream watchdog fatal: exiting for supervisor restart",{downMs:I}),process.exit(1)}})),g.start()}async function y(I,x){let O=I,ce=O?.privatecode;if(!ce)throw new _("IPC_BAD_REQUEST","/connect requires privatecode");let He=ci(O.env),ft=O.handshake_url,Xt=O.frontier_url,Yt=pg(O.env,ft,Xt);if(w=O,!x?.force&&l===ce&&d===Yt){let Se=await MI(t);return a.agents.size===0&&Se?(A.warn("/connect noop but core.agents empty with configs on disk; re-running auto-revive"),Po(t,c).catch(me=>A.warn("connect-noop auto-revive error (ignored)",{err:String(me)}))):A.info("/connect: already connected with same PAT + env, noop"),{ok:!0,note:"already connected"}}let Ir=!!l&&l!==ce,Tr=d!==void 0&&d!==Yt,Rr=Ir||Tr,kr=await oc({privatecode:ce,...ft?{endpoint:ft}:{},ppeOverride:He});if(Rr){A.warn("connect config switched, resetting agents",{pcChanged:Ir,envChanged:Tr,previousPc:l?Oo(l):"",nextPc:Oo(ce)});for(let Se of[...a.agents.values()])await Se.dispose("connect config switch").catch(()=>{}),a.agents.delete(Se.agentId);a.disconnectedAgents.size>0&&(A.info("clearing disconnectedAgents set on connect config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await s.swap(new _r,"connect switch").catch(()=>{})}p=kr.deviceId,Hi({deviceId:p,pid:process.pid}),Rc({patToken:ce,env:O.env}).catch(Se=>A.warn("coze-cli setup error (ignored)",{err:String(Se)}));let $o=new Di({handshake:kr,privatecode:ce,...Xt?{urlOverride:Xt}:{},ppeOverride:He,getPatTokenForAgent:Se=>a.agents.get(Se)?.patToken});return await s.swap($o,"connect"),l=ce,d=Yt,m=He,u=ft,O.mock_scenario!==void 0&&(a.setMockScenario(O.mock_scenario),A.info("mock scenario set",{scenario:O.mock_scenario})),h||(h=new di({core:a,getDeviceId:()=>p??"",onTickEnd:()=>R.retryPending().catch(Se=>A.warn("detailSync.retryPending failed (ignored)",{err:String(Se)})),onAuthFailures:D})),h.start(),f(),Rr&&Po(t,c).catch(Se=>A.warn("post-connect-switch auto-revive error (ignored)",{err:String(Se)})),Ni(ce,t).catch(Se=>A.warn("writePatToken after /connect failed (ignored)",{err:String(Se)})),A.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 E={},T=new js({agents:a.agents,disposeAndMarkDisconnected:async(I,x)=>{let O=a.agents.get(I);if(O){await c.cleanupOpenclawSessionProviders(O).catch(He=>A.warn("cleanup openclaw providers failed (ignored)",{agentId:I,err:String(He)}));let ce=!0;try{await O.dispose(`disconnect: ${x}`)}catch(He){ce=!1,A.error("dispose during disconnect FAILED, leaving agent in error state",{agentId:I,err:String(He)}),O.status="error"}ce&&(O.status="disconnected",a.unregister(I),a.disconnectedAgents.add(I))}else a.disconnectedAgents.add(I)},detailSyncer:async I=>{if(!E.ref)throw new Error("agent-detail-sync not initialized yet");await E.ref.syncOne(I)},cleanupOpenclawProviders:async I=>{await c.cleanupOpenclawSessionProviders(I)},openclawRepair:async(I,x)=>{await c.openclawRepair(I,x)},isRuntimePendingPermission:I=>a.hasPendingPermissionFor(I)});a.registerExtension("_agent/listSkills",I=>T.listSkills(I.params)),a.registerExtension("_agent/addSkills",I=>T.addSkills(I.params)),a.registerExtension("_agent/removeSkills",I=>T.removeSkills(I.params)),a.registerExtension("_agent/getFileTree",I=>T.getFileTree(I.params)),a.registerExtension("_agent/getFileContent",I=>T.getFileContent(I.params)),a.registerExtension("_agent/update",I=>T.updateAgent(I.params)),a.registerExtension("_agent/disconnect",I=>T.disconnectAgent(I.params)),a.registerExtension("_agent/switchModel",I=>T.switchModel(I.params)),a.registerExtension("_agent/reset",I=>T.resetAgent(I.params)),a.registerExtension("_agent/repair",I=>T.repairAgent(I.params));let R=new Xi({paths:t,handlers:T,sendDetail:I=>a.sendRequest("_agent/detail",I)});E.ref=R;let D=async I=>{await Promise.allSettled(I.map(async x=>{try{await T.disconnectAgent({agentId:x.agentId,reason:`auth_failure: code=${x.code} ${x.message}`}),A.info("agent disconnected due to auth failure from heartbeat response",{agentId:x.agentId,code:x.code,message:x.message})}catch(O){A.warn("disconnect during authFailure handling failed (ignored)",{agentId:x.agentId,err:String(O)})}}))};s.onConnect(({initial:I})=>{A.info("frontier upstream connected, triggering detail sync",{initial:I}),R.syncAll(I?"initial-connect":"reconnect").catch(x=>A.warn("detail sync top-level error (ignored)",{err:String(x)}))});let C=new so({paths:t,routes:[{method:"GET",path:"/status",handler:async()=>{let I=a.getMockScenario();return{running:!0,pid:process.pid,spawnedBy:process.env[Li]==="1"?"manual":"supervisor",agents:[...a.agents.keys()],deviceId:p??"",frameworksCache:i.frameworksCache??{},...I?{mockScenario:I}:{}}}},{method:"POST",path:"/pair",handler:async I=>{let x=I,O=x?.privatecode,ce=x?.pairing_code;if(!O||!ce)throw new _("IPC_BAD_REQUEST","/pair requires privatecode + pairing_code");let He=ci(x.env),ft=x.handshake_url,Xt=x.frontier_url,Yt=pg(x.env,ft,Xt),Ir=!!l&&l!==O,Tr=d!==void 0&&d!==Yt,Rr=Ir||Tr,kr=await oc({privatecode:O,...ft?{endpoint:ft}:{},ppeOverride:He});if(Rr){A.warn("pair config switched, resetting agents",{pcChanged:Ir,envChanged:Tr,previousPc:l?Oo(l):"",nextPc:Oo(O),previousEnvKey:d??"",nextEnvKey:Yt});for(let me of[...a.agents.values()])await me.dispose("pair config switch").catch(()=>{}),a.agents.delete(me.agentId);a.disconnectedAgents.size>0&&(A.info("clearing disconnectedAgents set on pair config switch",{count:a.disconnectedAgents.size}),a.disconnectedAgents.clear()),await s.swap(new _r,"pair switch").catch(()=>{})}p=kr.deviceId,Hi({deviceId:p,pid:process.pid}),Rc({patToken:O,env:x.env}).catch(me=>A.warn("coze-cli setup error (ignored)",{err:String(me)}));let $o=new Di({handshake:kr,privatecode:O,...Xt?{urlOverride:Xt}:{},ppeOverride:He,getPatTokenForAgent:me=>a.agents.get(me)?.patToken});await s.swap($o,"pair");try{let me=new yn;i.frameworksCache=await me.detectAll(),await wi(i),A.info("frameworks_cache refreshed before pair",{detected:Object.keys(i.frameworksCache)})}catch(me){A.warn("frameworks_cache refresh failed (ignored, using cached)",{err:String(me)})}let Se=Object.keys(i.frameworksCache??{});try{let me=await a.sendRequest("_agent/pair",{pairCode:ce,patToken:O,frameworks:Se,_meta:{cozeDeviceId:p}});A.info("_agent/pair ok",{pairResult:me}),l=O,d=Yt,m=He,u=ft,x.mock_scenario!==void 0&&(a.setMockScenario(x.mock_scenario),A.info("mock scenario set",{scenario:x.mock_scenario})),Ni(O,t).catch(Qe=>A.warn("writePatToken after /pair failed (ignored)",{err:String(Qe)})),h||(h=new di({core:a,getDeviceId:()=>p??"",onTickEnd:()=>R.retryPending().catch(Qe=>A.warn("detailSync.retryPending failed (ignored)",{err:String(Qe)})),onAuthFailures:D})),h.start(),f(),Rr&&Po(t,c).catch(Qe=>A.warn("post-pair-switch auto-revive error (ignored)",{err:String(Qe)}));let Go;return x.agent_id&&(Go=await UI(x.agent_id,t,c,Qe=>a.sendRequest("_agent/detail",Qe),O).catch(Qe=>(A.error("--agent-id ensureAgent failed",{agentId:x.agent_id,err:String(Qe)}),{ok:!1,agentId:x.agent_id??"",note:String(Qe)}))),{ok:!0,note:"paired with cloud",...Go?{agent:Go}:{}}}catch(me){return A.error("_agent/pair failed",{err:String(me)}),{ok:!1,note:`pair failed: ${String(me)}`}}}},{method:"POST",path:"/connect",handler:I=>v(I)},{method:"POST",path:"/_agent/create",handler:async I=>{let x=I;return{ok:!0,result:await c.createAgent(x)}}},{method:"POST",path:"/agent/send",handler:async I=>{let x=I;if(!x?.agentId||!x?.sessionId||!x?.kind||!x?.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 O=x;return await(O.groupFile?ih:rh)(O,{core:a,patToken:l,handshakeBase:u,ppeOverride:m})}catch(O){if(O instanceof _)return{ok:!1,code:O.code,message:O.message};throw O}}},{method:"POST",path:"/reload",handler:async I=>{let x=I?.agent_id,O=await a.reloadAgents(x);return A.info("IPC /reload: recycled agent subprocesses",{agentId:x??"(all)",recycled:O}),{ok:!0,recycled:O}}},{method:"POST",path:"/shutdown",handler:async()=>(A.info("IPC /shutdown received"),setImmediate(()=>{Ee.shutdown("ipc /shutdown")}),{ok:!0})}]}),{port:G,token:M}=await C.start();try{await cg(t.libEntry,t)}catch(I){A.warn("bin shim install failed (D72 send \u547D\u4EE4\u53EF\u80FD\u4E0D\u53EF\u7528)",{err:String(I)})}await a.start(),Po(t,c).catch(I=>A.warn("auto-revive top-level error (ignored)",{err:String(I)})),ed().then(async()=>{let{probeAcpVersion:I}=await Promise.resolve().then(()=>(tn(),Yl));for(let x of["claude-code","codex"]){let O=await I(x);O&&A.info("acp wrapper version",{framework:x,version:O})}}).catch(I=>A.warn("acp wrapper warmup / probe top-level error (ignored)",{err:String(I)}));let ae=null,Ee={port:G,token:M,core:a,ipc:C,shutdown(I){return ae||(A.info("daemon shutdown",{reason:I}),ae=(async()=>{h?.stop(),g?.stop(),await a.stop(I),await C.stop(),await e.release()})(),ae)}};for(let I of["SIGTERM","SIGINT"])process.on(I,()=>{Ee.shutdown(I).then(()=>process.exit(0))});return process.on("unhandledRejection",I=>{A.error("unhandledRejection",{reason:I instanceof Error?I.message:String(I),stack:I instanceof Error?I.stack:void 0})}),process.on("uncaughtException",I=>{A.error("uncaughtException (will exit, supervisor will restart)",{message:I.message,stack:I.stack,name:I.name});try{process.stderr.write(`FATAL uncaughtException: ${I.stack??I.message}
105
+ `)}catch{}process.exit(1)}),A.info("daemon ready",{port:G,pid:process.pid,nodeVersion:process.version,platform:process.platform,frameworks:Object.keys(i.frameworksCache??{}),libVersion:i.libVersion??"dev"}),zI({cliSpawned:process.env[Li]==="1",readPatToken:()=>To(t),connect:v}).catch(I=>A.warn("maybeAutoConnectOnStartup error (ignored)",{err:String(I)})),Ee}async function MI(t){return Ji(t).length>0}function Oo(t){return t.length<=8?"***":`${t.slice(0,4)}***${t.slice(-4)}`}function pg(t,e,n){return`${t??""}|${e??""}|${n??""}`}async function BI(t,e){let n=Ji(t);if(n.length===0)return;let{loadAgentConfig:r,enforceAgentConfigMode:i}=await Promise.resolve().then(()=>(At(),Ki));for(let s of n){await i(s,t).catch(o=>A.warn("enforceAgentConfigMode failed (ignored)",{agentId:s,err:String(o)}));try{let o=await r(s,t);o?.disconnectedAt&&(e.disconnectedAgents.add(s),A.info("agent marked disconnected on startup",{agentId:s,disconnectedAt:o.disconnectedAt,reason:o.disconnectReason??""}))}catch(o){A.warn("failed to load agent config on startup, skipping",{agentId:s,err:String(o)})}}}async function UI(t,e,n,r,i){let{loadAgentConfig:s}=await Promise.resolve().then(()=>(At(),Ki)),o=await s(t,e);if(o){A.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"}}A.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 Po(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(()=>(At(),Ki));A.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){A.warn("auto-revive: load config failed (skipping)",{agentId:a,err:String(l)}),o+=1;continue}if(!c){o+=1;continue}if(c.disconnectedAt){A.info("auto-revive: skip disconnected agent",{agentId:a,disconnectedAt:c.disconnectedAt}),o+=1;continue}try{A.info("auto-revive: re-registering agent (D44 no spawn)",{agentId:a,framework:c.framework});let l=$I(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){A.warn("auto-revive: createAgent failed (skipping)",{agentId:a,framework:c.framework,err:String(l)}),o+=1}}return A.info("auto-revive: done",{revived:s,skipped:o,total:r.length}),{revived:s,skipped:o,total:r.length}}async function zI(t){let e=t.logger??A;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 $I(t){let e={};return t.deployType&&(e.cozeDeployType=t.deployType),t.accountId&&(e.cozeAccountId=t.accountId),Object.keys(e).length>0?e:void 0}Ao();re();import{readFile as mg}from"node:fs/promises";var bt=class{paths;constructor(e){this.paths=e??L()}async probe(e=1e3){let n=await Co(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:HI(r)}}}async request(e){let n=await Co(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:GI(c)}}finally{clearTimeout(o)}}};async function Co(t){try{let[e,n]=await Promise.all([mg(t.portFile,"utf8"),mg(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 GI(t){if(!t)return null;try{return JSON.parse(t)}catch{return t}}function HI(t){return t instanceof Error?t.message:String(t)}gt();F();re();function Kt(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 wg,mkdir as jI,readFile as Al,writeFile as WI}from"node:fs/promises";import{homedir as vC}from"node:os";import{dirname as qI,resolve as xl,sep as Do}from"node:path";import{fileURLToPath as JI}from"node:url";F();re();var yg=b("dist-install");function VI(t){let e=JI(t),n=qI(e),r=`${Do}src${Do}`;if(n.includes(r)||n.endsWith(`${Do}src${Do}cli`))return null;let i=xl(n,"index.js"),s=xl(n,"..","package.json");return{dist:i,pkgJson:s}}async function Ol(t={}){let e=t.paths??L(),n=VI(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 Al(i,"utf8")).version??"unknown"}catch(p){return yg.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 ro(e.configFile)??{},a=o.libVersion;if(a===s)try{return await Al(e.libEntry),{kind:"already-current",libVersion:s}}catch{}await jI(e.libDir,{recursive:!0}),await wg(r,e.libEntry),await wg(`${r}.map`,`${e.libEntry}.map`).catch(()=>{});let c=xl(e.libDir,"package.json"),l=`${JSON.stringify({type:"module"},null,2)}
106
+ `;return await Al(c,"utf8").catch(()=>null)!==l&&await WI(c,l),o.libVersion=s,await wi(o,e.configFile),yg.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}}Wo();F();re();import{closeSync as Eg,fstatSync as Sg,openSync as vg,readFileSync as ZI,readSync as KI,readdirSync as XI,statSync as YI}from"node:fs";import{join as No}from"node:path";var QI=new Set(["debug","info","warn","error"]);function Ig(t){let e=t,n=Kt(e,"--agent-id");e=n.rest;let r=Kt(e,"--date");e=r.rest;let i=Kt(e,"-n","--lines");e=i.rest;let s=Kt(e,"--level");e=s.rest;let o=Kt(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&&QI.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 eT(t,e){return t.agentId?No(be(t.agentId,e).logs,On("agent",t.date)):No(e.bridgeLogsDir,On("bridge",t.date))}function tT(t,e){return e<=0||e>=t.length?t:t.slice(t.length-e)}function nT(t,e){let n;try{n=XI(t)}catch{return[]}let r=[];for(let i of n){let s=jo(i,e);if(!s)continue;let o=0;try{o=YI(No(t,i)).size}catch{}r.push({file:No(t,i),date:s,size:o})}return r.sort((i,s)=>s.date.localeCompare(i.date)),r}function Tg(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"&&!zl(n,e.level))return!1}return!0}var _g={debug:"90",info:"36",warn:"33",error:"31"},rT=new Set(["ts","level","module","msg"]);function iT(t){if(typeof t!="string")return"";let e=t.split("T")[1];return e?e.slice(0,12):""}function Rg(t,e){if(e.raw)return t;let n;try{n=JSON.parse(t)}catch{return t}let r=iT(n.ts),i=typeof n.level=="string"?n.level:"",s=i.toUpperCase().padEnd(5);e.color&&_g[i]&&(s=`\x1B[${_g[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])=>!rT.has(l)).map(([l,d])=>` ${l}=${typeof d=="string"?d:JSON.stringify(d)}`).join("");return`${r} ${s} ${o} ${a}${c}`}function sT(t,e,n){let s=ZI(t,"utf8").split(`
107
107
  `).filter(o=>o.length>0).filter(o=>Tg(o,{level:e.level,grep:e.grep}));for(let o of tT(s,e.lines))process.stdout.write(`${Rg(o,{raw:e.raw,color:n})}
108
108
  `)}async function kg(t,e){let n=e.paths??L(),r=process.stdout.isTTY===!0;if(t.list){let o=t.agentId?be(t.agentId,n).logs:n.bridgeLogsDir,a=t.agentId?"agent":"bridge",c=nT(o,a);if(c.length===0)return process.stderr.write(`coze-bridge log: \u65E0\u65E5\u5FD7\u6587\u4EF6\u4E8E ${o}
109
109
  `),1;for(let l of c)process.stdout.write(`${l.date} ${(l.size/1024).toFixed(1)}KB ${l.file}
110
- `);return 0}let i=t.date??en(new Date),s=eT({agentId:t.agentId,date:i},n);try{sT(s,t,r)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${s}
110
+ `);return 0}let i=t.date??Qt(new Date),s=eT({agentId:t.agentId,date:i},n);try{sT(s,t,r)}catch{return process.stderr.write(`coze-bridge log: \u627E\u4E0D\u5230\u65E5\u5FD7 ${s}
111
111
  \u7528 'coze-bridge log${t.agentId?` --agent-id ${t.agentId}`:""} --list' \u770B\u6709\u54EA\u4E9B\u65E5\u671F\u3002
112
112
  (legacy \u6A21\u5F0F\u65E0 dated \u6587\u4EF6, \u89C1 ${n.logFile})
113
113
  `),1}return t.follow&&await cT(s,t,r),0}var oT=500;function aT(t){try{let e=vg(t,"r");try{return Sg(e).size}finally{Eg(e)}}catch{return 0}}async function cT(t,e,n){let r=aT(t),i="",s=!1,o=()=>{s=!0};process.on("SIGINT",o);try{for(;!s;){let a="";try{let c=vg(t,"r");try{let l=Sg(c).size;if(l>r){let d=Buffer.allocUnsafe(l-r),p=KI(c,d,0,d.length,r);a=d.subarray(0,p).toString("utf8"),r+=p}}finally{Eg(c)}}catch{}if(a){let c=(i+a).split(`
114
114
  `);i=c.pop()??"";for(let l of c)l.length>0&&Tg(l,{level:e.level,grep:e.grep})&&process.stdout.write(`${Rg(l,{raw:e.raw,color:n})}
115
115
  `)}await new Promise(c=>setTimeout(c,oT))}}finally{process.off("SIGINT",o)}}import{basename as lT,resolve as dT}from"node:path";re();var uT=9e4,fT={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 hT(t){return fT[t]??1}async function bg(t,e={}){let n=e.paths??L();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>
116
116
  `),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.
117
- `),3;let r=await Do(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.
117
+ `),3;let r=await Co(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.
118
118
  `),4;let i={agentId:t.agentId,sessionId:t.sessionId,kind:t.kind,path:t.groupFile?t.path:dT(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 pT(r,"/agent/send",i,uT)}catch(o){return process.stderr.write(`Error: daemon IPC failed: ${o instanceof Error?o.message:String(o)}
119
119
  `),4}if(!s.ok)return process.stderr.write(`Error: ${s.code}: ${s.message}
120
120
  `),hT(s.code);if(t.json)process.stdout.write(`${JSON.stringify(s)}
121
121
  `);else{let o=t.name??lT(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})
122
122
  `)}else process.stdout.write(`Sent ${t.kind} ${o} (${gT(s.bytes)})
123
- `)}return 0}async function pT(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 gT(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Fg=b("cli");function _e(t,e){let{value:n,rest:r}=Xt(t,e);return{value:n,rest:r}}function Mi(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
124
- `)}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 zT(e.slice(1));if(e[0]==="log")return{mode:"log",...Ig(e.slice(1))};if(e[0]==="connect")return $T(e.slice(1));if(e.includes("--status"))return Mi("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return Mi("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--refresh"))return Mi("--refresh","coze-bridge refresh"),{mode:"refresh"};if(e.includes("--uninstall"))return Mi("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return Mi("--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}=_e(n,"--pat-token");n=i;let{value:s,rest:o}=_e(n,"--pair-code");n=o;let{value:a,rest:c}=_e(n,"--env");n=c;let{value:l,rest:d}=_e(n,"--handshake-url");n=d;let{value:p,rest:m}=_e(n,"--frontier-url");n=m;let{value:u,rest:h}=_e(n,"--mock-scenario");n=h;let{value:g}=_e(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),u&&(w.mockScenario=u),g&&(w.agentId=g),w}function zT(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}=_e(r,"--caption");r=s;let{value:o,rest:a}=_e(r,"--name");r=a;let{value:c,rest:l}=_e(r,"--agent-id");r=l;let{value:d,rest:p}=_e(r,"--session-id");r=p;let{value:m,rest:u}=_e(r,"--mime");r=u;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 $T(t){let e=t,{value:n,rest:r}=_e(e,"--pat-token");e=r;let{value:i,rest:s}=_e(e,"--env");e=s;let{value:o,rest:a}=_e(e,"--handshake-url");e=a;let{value:c,rest:l}=_e(e,"--frontier-url");e=l;let{value:d,rest:p}=_e(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 GT=`
123
+ `)}return 0}async function pT(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 gT(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}KB`:`${(t/1024/1024).toFixed(1)}MB`}var Fg=b("cli");function ge(t,e){let{value:n,rest:r}=Kt(t,e);return{value:n,rest:r}}function zo(t,e){process.stderr.write(`[deprecated] '${t}' will be removed in a future release, use '${e}' instead
124
+ `)}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]==="reload"){let{value:S}=ge(e.slice(1),"--agent-id");return S?{mode:"reload",agentId:S}:{mode:"reload"}}if(e[0]==="update")return{mode:"update"};if(e[0]==="purge")return{mode:"purge"};if(e[0]==="service")return e[1]==="install"?{mode:"service-install"}:e[1]==="uninstall"?{mode:"service-uninstall"}:{mode:"help"};if(e[0]==="send")return zT(e.slice(1));if(e[0]==="log")return{mode:"log",...Ig(e.slice(1))};if(e[0]==="connect")return $T(e.slice(1));if(e.includes("--status"))return zo("--status","coze-bridge status"),{mode:"status"};if(e.includes("--stop"))return zo("--stop","coze-bridge stop"),{mode:"stop"};if(e.includes("--uninstall"))return zo("--uninstall","coze-bridge purge"),{mode:"purge"};if(e.includes("--install-service"))return zo("--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:u,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),u&&(w.mockScenario=u),g&&(w.agentId=g),w}function zT(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:u}=ge(r,"--mime");r=u;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 $T(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 GT=`
125
125
  coze-bridge - local bridge daemon for cloud Agent Service
126
126
 
127
127
  Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
@@ -130,7 +130,8 @@ Pair (paste from cloud UI; start/reuse daemon and deliver pair-code):
130
130
  Daemon control:
131
131
  coze-bridge status show daemon status
132
132
  coze-bridge stop stop daemon
133
- coze-bridge refresh re-detect agent binaries (claude/codex/openclaw)
133
+ coze-bridge reload \u56DE\u6536\u6240\u6709 agent \u5B50\u8FDB\u7A0B, \u4E0B\u6B21 prompt \u7528\u6700\u65B0 env \u91CD spawn
134
+ coze-bridge reload --agent-id <id> \u53EA\u56DE\u6536\u6307\u5B9A agent \u7684\u5B50\u8FDB\u7A0B
134
135
 
135
136
  View logs (D126; \u76F4\u63A5\u8BFB\u76D8\u67E5 dated \u65E5\u5FD7, \u4E0D\u8D70 daemon):
136
137
  coze-bridge log bridge \u4ECA\u5929\u6700\u540E 200 \u884C
@@ -193,7 +194,6 @@ Info:
193
194
  Deprecated flags (still work, but emit a warning; will be removed in a future release):
194
195
  --status \u2192 coze-bridge status
195
196
  --stop \u2192 coze-bridge stop
196
- --refresh \u2192 coze-bridge refresh
197
197
  --install-service \u2192 coze-bridge service install
198
198
  --uninstall \u2192 coze-bridge purge (note: deletes only ~/.coze/bridge now,
199
199
  no longer touches ~/.coze/agents)
@@ -201,11 +201,11 @@ Deprecated flags (still work, but emit a warning; will be removed in a future re
201
201
  Internal:
202
202
  <node> <entry> --daemon daemon mode (OS supervisor only)
203
203
  `.trimStart();async function Mg(t=process.argv,e={}){let n=UT(t);switch(n.mode){case"help":return process.stdout.write(GT),0;case"version":return process.stdout.write(`${rr}
204
- `),0;case"daemon":{try{await gg()}catch(r){return Fg.error("daemon start failed",{err:String(r)}),1}return new Promise(()=>{})}case"status":return HT(e);case"stop":return Ug(e);case"refresh":return qT(e);case"log":return kg(n,e);case"update":return jT(e);case"purge":return JT(e);case"service-install":return VT(e);case"service-uninstall":return ZT(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),KT(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),XT(n.privatecode,e,r)}case"send":return bg({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 Bg(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 HT(t){let e=t.paths??L(),n=new bt(e),r=await n.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
204
+ `),0;case"daemon":{try{await gg()}catch(r){return Fg.error("daemon start failed",{err:String(r)}),1}return new Promise(()=>{})}case"status":return HT(e);case"stop":return Ug(e);case"reload":return qT(n.agentId,e);case"log":return kg(n,e);case"update":return jT(e);case"purge":return JT(e);case"service-install":return VT(e);case"service-uninstall":return ZT(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),KT(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),XT(n.privatecode,e,r)}case"send":return bg({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 Bg(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 HT(t){let e=t.paths??L(),n=new bt(e),r=await n.probe();if(r.kind==="not-running")return process.stdout.write(`coze-bridge: not running
205
205
  `),1;if(r.kind==="stale")return await Bg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
206
206
  `),1;let i=await n.request({method:"GET",path:"/status"});return process.stdout.write(`coze-bridge: running
207
207
  ${JSON.stringify(i.body,null,2)}
208
- `),0}async function Ug(t){let e=t.paths??L(),n=new bt(e),r=await Bi(t),i=!1;if(r)try{await r.uninstall(),i=!0}catch(o){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(o)}
208
+ `),0}async function Ug(t){let e=t.paths??L(),n=new bt(e),r=await Mi(t),i=!1;if(r)try{await r.uninstall(),i=!0}catch(o){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(o)}
209
209
  `)}let s=await n.probe();if(s.kind==="not-running")return process.stdout.write(i?`coze-bridge: stopped
210
210
  `:`coze-bridge: not running
211
211
  `),0;if(s.kind==="stale")return await Bg(e),process.stdout.write(`coze-bridge: not running (cleaned stale state)
@@ -213,37 +213,37 @@ ${JSON.stringify(i.body,null,2)}
213
213
  `),0}catch(o){return(await n.probe()).kind!=="connected"?(process.stdout.write(`coze-bridge: stopped
214
214
  `),0):(process.stdout.write(`coze-bridge: stop failed: ${String(o)}
215
215
  `),1)}}async function jT(t){return await Ug(t),(t.spawnNpx??WT)(["-y","--ignore-existing","coze-bridge@latest","connect"])}function WT(t){return new Promise(e=>{let n=Fe("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)}
216
- `),e(1)})})}async function qT(t){let e=new bt(t.paths);if((await e.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
217
- `),1;try{let r=await e.request({method:"POST",path:"/refresh",timeoutMs:35e3});return r.status===200?(process.stdout.write(`coze-bridge: refreshed
218
- ${JSON.stringify(r.body,null,2)}
219
- `),0):(process.stderr.write(`coze-bridge: refresh failed: ${JSON.stringify(r.body)}
220
- `),1)}catch(r){return process.stderr.write(`coze-bridge: refresh failed: ${String(r)}
221
- `),1}}async function Bi(t){if(t.supervisor){let s=t.supervisor,o={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:s.platform,install:a=>s.install(o,a),uninstall:()=>s.uninstall(o)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Ng(),Dg)),r=e(),i=n();return{platform:r.platform,install:s=>r.install(i,s),uninstall:()=>r.uninstall(i)}}async function zg(t,e){let n=await e.probe();if(n.kind==="connected")return n;let r=t.spawnDaemon??hg,i=t.waitTimeoutMs??15e3,s=t.sleep??QT,o=t.paths??L(),a=await Bi(t);if(a&&(a.platform==="darwin"||a.platform==="linux")){try{await a.install({activate:!0});let c=await Lg(e,i,s);if(c.kind==="connected")return c;xr(o.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(c){xr(o.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(c)})}await a.uninstall().catch(()=>{}),await YT(o.pidFile,s)}else a&&await a.install({activate:!1}).catch(c=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(c)}
216
+ `),e(1)})})}async function qT(t,e){let n=new bt(e.paths);if((await n.probe()).kind==="not-running")return process.stdout.write(`coze-bridge: not running (start daemon first)
217
+ `),1;try{let i=await n.request({method:"POST",path:"/reload",body:t?{agent_id:t}:{},timeoutMs:35e3});if(i.status===200&&i.body?.ok){let s=i.body.recycled??[];return t&&s.length===0?process.stdout.write(`coze-bridge: agent ${t} \u65E0\u8FD0\u884C\u4E2D\u5B50\u8FDB\u7A0B\u53EF\u56DE\u6536 (\u672A\u6CE8\u518C / \u5DF2 idle)
218
+ `):process.stdout.write(`coze-bridge: reloaded ${s.length} agent(s): ${s.join(", ")||"(none)"}
219
+ `),0}return process.stderr.write(`coze-bridge: reload failed: ${JSON.stringify(i.body)}
220
+ `),1}catch(i){return process.stderr.write(`coze-bridge: reload failed: ${String(i)}
221
+ `),1}}async function Mi(t){if(t.supervisor){let s=t.supervisor,o={nodeBin:"",entry:"",logFile:"",homeDir:"",userName:""};return{platform:s.platform,install:a=>s.install(o,a),uninstall:()=>s.uninstall(o)}}if(t.skipSupervisor)return;let{getSupervisor:e,buildContext:n}=await Promise.resolve().then(()=>(Ng(),Dg)),r=e(),i=n();return{platform:r.platform,install:s=>r.install(i,s),uninstall:()=>r.uninstall(i)}}async function zg(t,e){let n=await e.probe();if(n.kind==="connected")return n;let r=t.spawnDaemon??hg,i=t.waitTimeoutMs??15e3,s=t.sleep??QT,o=t.paths??L(),a=await Mi(t);if(a&&(a.platform==="darwin"||a.platform==="linux")){try{await a.install({activate:!0});let c=await Lg(e,i,s);if(c.kind==="connected")return c;Ar(o.bridgeLogsDir,"warn","cli","supervisor \u8D77 daemon \u8D85\u65F6, \u56DE\u9000\u624B\u52A8 spawn (\u672C\u6B21\u65E0\u5D29\u6E83\u4FDD\u6D3B)",{waitMs:i})}catch(c){Ar(o.bridgeLogsDir,"warn","cli","supervisor \u63A5\u7BA1\u5931\u8D25, \u56DE\u9000\u624B\u52A8 spawn",{err:String(c)})}await a.uninstall().catch(()=>{}),await YT(o.pidFile,s)}else a&&await a.install({activate:!1}).catch(c=>process.stderr.write(`coze-bridge: \u81EA\u542F\u6CE8\u518C\u5931\u8D25(\u4E0D\u5F71\u54CD\u672C\u6B21): ${String(c)}
222
222
  `));return process.stdout.write(`coze-bridge: starting daemon...
223
223
  `),await r({paths:t.paths}),Lg(e,i,s)}async function JT(t){let e=new bt(t.paths);if((await e.probe()).kind==="connected"){process.stdout.write(`coze-bridge: stopping daemon...
224
224
  `);try{await e.request({method:"POST",path:"/shutdown"})}catch(o){process.stderr.write(`coze-bridge: stop failed (continuing): ${String(o)}
225
- `)}await new Promise(o=>setTimeout(o,500))}let r=await Bi(t);if(r)try{await r.uninstall(),process.stdout.write(`coze-bridge: ${r.platform} supervisor unregistered
225
+ `)}await new Promise(o=>setTimeout(o,500))}let r=await Mi(t);if(r)try{await r.uninstall(),process.stdout.write(`coze-bridge: ${r.platform} supervisor unregistered
226
226
  `)}catch(o){process.stderr.write(`coze-bridge: supervisor uninstall failed (continuing): ${String(o)}
227
227
  `)}let i=t.paths??L(),{rm:s}=await import("node:fs/promises");try{await s(i.bridgeRoot,{recursive:!0,force:!0}),process.stdout.write(`coze-bridge: removed ${i.bridgeRoot}
228
228
  `)}catch(o){return process.stderr.write(`coze-bridge: remove failed: ${String(o)}
229
229
  `),1}return process.stdout.write(`coze-bridge: purged (agents workspaces preserved under ~/.coze/agents)
230
- `),0}async function VT(t){let e=await Bi(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
230
+ `),0}async function VT(t){let e=await Mi(t);if(!e)return 0;try{return process.stdout.write(`coze-bridge: installing ${e.platform} supervisor...
231
231
  `),await e.install(),process.stdout.write(`coze-bridge: supervisor installed (daemon will auto-start on login)
232
232
  `),0}catch(n){return process.stderr.write(`coze-bridge: service install failed: ${String(n)}
233
- `),1}}async function ZT(t){let e=await Bi(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
233
+ `),1}}async function ZT(t){let e=await Mi(t);if(!e)return 0;try{return await e.uninstall(),process.stdout.write(`coze-bridge: ${e.platform} supervisor unregistered
234
234
  `),0}catch(n){return process.stderr.write(`coze-bridge: service uninstall failed: ${String(n)}
235
- `),1}}async function KT(t,e,n,r={},i){let s=new bt(n.paths),o=n.paths??L();if(await _c(o).catch(l=>xr(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(l)})),!n.skipDistInstall){let l=await Ol({paths:n.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
235
+ `),1}}async function KT(t,e,n,r={},i){let s=new bt(n.paths),o=n.paths??L();if(await _c(o).catch(l=>Ar(o.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(l)})),!n.skipDistInstall){let l=await Ol({paths:n.paths});l.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${l.fromVersion} \u2192 ${l.toVersion}
236
236
  `),(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}
237
237
  `)}let a=await zg(n,s);if(a.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${a.kind}
238
238
  `),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}
239
239
  `),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"
240
240
  `),0)}return process.stderr.write(`coze-bridge: pair failed: ${JSON.stringify(l.body)}
241
241
  `),1}catch(l){return process.stderr.write(`coze-bridge: pair failed: ${String(l)}
242
- `),1}}async function XT(t,e,n={}){let r=e.paths??L(),i=t??await Ro(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 bt(e.paths);if(await _c(r).catch(c=>xr(r.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(c)})),!e.skipDistInstall){let c=await Ol({paths:e.paths});c.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${c.fromVersion} \u2192 ${c.toVersion}
242
+ `),1}}async function XT(t,e,n={}){let r=e.paths??L(),i=t??await To(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 bt(e.paths);if(await _c(r).catch(c=>Ar(r.bridgeLogsDir,"warn","cli","writeAgentEnv failed (ignored)",{err:String(c)})),!e.skipDistInstall){let c=await Ol({paths:e.paths});c.kind==="version-changed"?(process.stdout.write(`coze-bridge: upgraded ${c.fromVersion} \u2192 ${c.toVersion}
243
243
  `),(await s.probe()).kind==="connected"&&(await s.request({method:"POST",path:"/shutdown"}).catch(()=>{}),await new Promise(d=>setTimeout(d,500)))):c.kind==="first-install"&&process.stdout.write(`coze-bridge: installed ${c.libVersion}
244
244
  `)}let o=await zg(e,s);if(o.kind!=="connected")return process.stderr.write(`coze-bridge: daemon did not come up: ${o.kind}
245
245
  `),1;let a={privatecode:i};n.env&&(a.env=n.env),n.handshakeUrl&&(a.handshake_url=n.handshakeUrl),n.frontierUrl&&(a.frontier_url=n.frontierUrl),n.mockScenario&&(a.mock_scenario=n.mockScenario);try{let c=await s.request({method:"POST",path:"/connect",body:a,timeoutMs:35e3});return c.status===200&&c.body?.ok?(process.stdout.write(`coze-bridge: connected (${c.body.note??"ok"})
246
246
  `),await Ni(i,r).catch(l=>Fg.warn("writePatToken after connect failed (ignored)",{err:String(l)})),0):(process.stderr.write(`coze-bridge: connect failed: ${JSON.stringify(c.body)}
247
247
  `),1)}catch(c){return process.stderr.write(`coze-bridge: connect failed: ${String(c)}
248
- `),1}}async function Lg(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)}async function YT(t,e,n=60,r=200){let{readFile:i}=await import("node:fs/promises");for(let s=0;s<n;s++){let o;try{o=await i(t,"utf8")}catch{return}let a=Number.parseInt(o.trim(),10);if(!Number.isFinite(a)||a<=0||!bo(a))return;await e(r)}}function QT(t){return new Promise(e=>setTimeout(e,t))}F();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Bl("warn");Mg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
248
+ `),1}}async function Lg(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)}async function YT(t,e,n=60,r=200){let{readFile:i}=await import("node:fs/promises");for(let s=0;s<n;s++){let o;try{o=await i(t,"utf8")}catch{return}let a=Number.parseInt(o.trim(),10);if(!Number.isFinite(a)||a<=0||!ko(a))return;await e(r)}}function QT(t){return new Promise(e=>setTimeout(e,t))}F();!process.argv.includes("--daemon")&&!process.env.COZE_BRIDGE_LOG_LEVEL&&Bl("warn");Mg(process.argv).then(t=>process.exit(t),t=>{process.stderr.write(`fatal: ${t instanceof Error?t.stack??t.message:String(t)}
249
249
  `),process.exit(1)});