@miomioos/mio-agent 0.3.2 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +72 -72
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import{createRequire as ___cr}from'module';import{fileURLToPath as ___fu}from'url';import{dirname as ___dn}from'path';const require=___cr(import.meta.url);const __filename=___fu(import.meta.url);const __dirname=___dn(__filename);
|
|
3
|
-
var ef=Object.create;var ms=Object.defineProperty;var tf=Object.getOwnPropertyDescriptor;var nf=Object.getOwnPropertyNames;var rf=Object.getPrototypeOf,sf=Object.prototype.hasOwnProperty;var Z=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var O=(n,e)=>()=>(n&&(e=n(n=0)),e);var X=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),
|
|
3
|
+
var ef=Object.create;var ms=Object.defineProperty;var tf=Object.getOwnPropertyDescriptor;var nf=Object.getOwnPropertyNames;var rf=Object.getPrototypeOf,sf=Object.prototype.hasOwnProperty;var Z=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var O=(n,e)=>()=>(n&&(e=n(n=0)),e);var X=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Le=(n,e)=>{for(var t in e)ms(n,t,{get:e[t],enumerable:!0})},of=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of nf(e))!sf.call(n,s)&&s!==t&&ms(n,s,{get:()=>e[s],enumerable:!(r=tf(e,s))||r.enumerable});return n};var re=(n,e,t)=>(t=n!=null?ef(rf(n)):{},of(e||!n||!n.__esModule?ms(t,"default",{value:n,enumerable:!0}):t,n));var oo={};Le(oo,{MIO_AGENT_VERSION:()=>io,getPackageVersion:()=>af});function af(){return io}var io,ao=O(()=>{"use strict";io="0.2.1"});import{readFileSync as uo,writeFileSync as cf}from"fs";import{basename as lf,extname as df}from"path";import{randomUUID as fo}from"crypto";async function ho(n,e={}){let t=e.stdout??process.stdout,r=e.stderr??process.stderr,s=e.stdin??process.stdin;if(n.length===0||n[0]==="--help"||n[0]==="-h")return t.write(Yf),0;let i=process.env.MIO_AGENT_PROXY_URL;if(!i)return r.write(JSON.stringify({ok:!1,code:"MISSING_PROXY_URL",message:"MIO_AGENT_PROXY_URL is not set"})+`
|
|
4
4
|
`),1;let o=process.env.MIO_AGENT_PROXY_TOKEN_FILE;if(!o)return r.write(JSON.stringify({ok:!1,code:"MISSING_PROXY_TOKEN",message:"MIO_AGENT_PROXY_TOKEN_FILE is not set"})+`
|
|
5
5
|
`),1;let a;try{a=uo(o,"utf8").trim()}catch(u){let m=u instanceof Error?u.message:String(u);return r.write(JSON.stringify({ok:!1,code:"MISSING_PROXY_TOKEN",message:`Cannot read proxy token file: ${m}`})+`
|
|
6
6
|
`),1}if(!a)return r.write(JSON.stringify({ok:!1,code:"MISSING_PROXY_TOKEN",message:"Proxy token file is empty"})+`
|
|
@@ -11,9 +11,9 @@ var ef=Object.create;var ms=Object.defineProperty;var tf=Object.getOwnPropertyDe
|
|
|
11
11
|
`),1)}async function hf(n,e,t,r,s,i){let o=U(n,"--target");if(!o)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for message send"})+`
|
|
12
12
|
`),1;if(r.isTTY)return i.write(JSON.stringify({ok:!1,code:"NO_STDIN",message:'message body must be piped on stdin, e.g. mio message send --target "#x" <<EOF'})+`
|
|
13
13
|
`),1;let a=await mo(r);if(a.trim()==="")return i.write(JSON.stringify({ok:!1,code:"EMPTY_MESSAGE",message:"message body is empty \u2014 nothing to send"})+`
|
|
14
|
-
`),1;let c=fo(),d=nr(n,"--attachment");for(let
|
|
14
|
+
`),1;let c=fo(),d=nr(n,"--attachment");for(let _ of nr(n,"--attach-file")){let b=await ws(_,o,e,t);if(!b.ok)return i.write(JSON.stringify(b.error)+`
|
|
15
15
|
`),1;d.push(b.id)}let l={target:o,content:a,clientIdempotencyKey:c};d.length>0&&(l.attachment_ids=d);let u=await ce(e,t,"send",l);if(!u.ok)return i.write(JSON.stringify(u.error)+`
|
|
16
|
-
`),1;let m=u.data,f=String(m.id??""),
|
|
16
|
+
`),1;let m=u.data,f=String(m.id??""),p=String(m.short_id??m.shortId??"").slice(0,8),g=m.seq!==void 0?`seq=${m.seq} `:"",y=typeof m.routed_to=="string"?m.routed_to:"",S=typeof m.task_number=="number"?m.task_number:null,v="";return y==="thread"&&S!==null&&(v=` (auto-routed to thread of task #${S} \u2014 you have an active task in this channel, so this send went into its thread, NOT the main channel. Tell users your message is in the task thread, not main.)`),s.write(`sent: id=${f} ${p?`short=${p} `:""}${g}target=${o}${v}
|
|
17
17
|
`),0}async function gf(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message read"})+`
|
|
18
18
|
`),1;let o={channel:i},a=U(n,"--after"),c=U(n,"--around"),d=U(n,"--before"),l=U(n,"--limit");if([a,c,d].filter(f=>f!==void 0).length>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --after, --around, --before may be provided"})+`
|
|
19
19
|
`),1;if(a&&(o.after_seq=a),c&&(o.around=c),d&&(o.around=d),l!==void 0){let f=Number(l);if(!Number.isInteger(f)||f<=0)return s.write(JSON.stringify({ok:!1,code:"INVALID_LIMIT",message:`--limit must be a positive integer, got: ${l}`})+`
|
|
@@ -29,7 +29,7 @@ var ef=Object.create;var ms=Object.defineProperty;var tf=Object.getOwnPropertyDe
|
|
|
29
29
|
`),1;let c=await mo(r);if(c.trim()==="")return i.write(JSON.stringify({ok:!1,code:"EMPTY_MESSAGE",message:"reply body is empty \u2014 nothing to send"})+`
|
|
30
30
|
`),1;let d=fo(),l=nr(n,"--attachment");for(let S of nr(n,"--attach-file")){let v=await ws(S,a,e,t);if(!v.ok)return i.write(JSON.stringify(v.error)+`
|
|
31
31
|
`),1;l.push(v.id)}let u={target:a,parent_message_id:o,content:c,clientIdempotencyKey:d};l.length>0&&(u.attachment_ids=l);let m=await ce(e,t,"reply",u);if(!m.ok)return i.write(JSON.stringify(m.error)+`
|
|
32
|
-
`),1;let f=m.data,
|
|
32
|
+
`),1;let f=m.data,p=String(f.id??""),g=String(f.short_id??f.shortId??"").slice(0,8),y=f.seq!==void 0?`seq=${f.seq} `:"";return s.write(`replied: id=${p} ${g?`short=${g} `:""}${y}parent=${o} target=${a}
|
|
33
33
|
`),0}async function yf(n,e,t,r,s,i){switch(n){case"list":return wf(e,t,r,s,i);case"create":return vf(e,t,r,s,i);case"claim":return co("claim",e,t,r,s,i);case"unclaim":return co("unclaim",e,t,r,s,i);case"update":return bf(e,t,r,s,i);case"review":return _f(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown task subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
34
34
|
`),1}}async function _f(n,e,t,r,s){let i=ys(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a task number (e.g. #5 or 5) is required for task review"})+`
|
|
35
35
|
`),1;let o=U(n,"--channel");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task review"})+`
|
|
@@ -59,10 +59,10 @@ var ef=Object.create;var ms=Object.defineProperty;var tf=Object.getOwnPropertyDe
|
|
|
59
59
|
`),1;let o=U(n,"--in"),a=U(n,"--at"),c=U(n,"--cadence"),d=[o,a,c].filter(S=>S!==void 0).length;if(d===0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"one of --in <dur>, --at <ISO>, or --cadence <rule> is required for reminder schedule"})+`
|
|
60
60
|
`),1;if(d>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --at, --cadence may be provided"})+`
|
|
61
61
|
`),1;let l=U(n,"--channel"),u=U(n,"--message-id"),m={op:"schedule",title:i};o!==void 0&&(m.in=o),a!==void 0&&(m.at=a),c!==void 0&&(m.cadence=c),l!==void 0&&(m.channel=l),u!==void 0&&(m.message_id=u);let f=await ce(e,t,"reminder",m);if(!f.ok)return s.write(JSON.stringify(f.error)+`
|
|
62
|
-
`),1;let
|
|
62
|
+
`),1;let p=Pf(f.data),g=p?.id??"(new)",y=p?.fireAt?` fireAt=${p.fireAt}`:"";return r.write(`Scheduled reminder ${g}: ${i}${y}
|
|
63
63
|
`),0}async function Tf(n,e,t,r,s){let i=U(n,"--channel"),o=U(n,"--status"),a={op:"list"};i!==void 0&&(a.channel=i),o!==void 0&&(a.status=o);let c=await ce(e,t,"reminder",a);return c.ok?(Nf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
|
|
64
64
|
`),1)}async function Cf(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder snooze"})+`
|
|
65
|
-
`),1;let o=U(n,"--in"),a=U(n,"--until"),c=[o,a].filter(
|
|
65
|
+
`),1;let o=U(n,"--in"),a=U(n,"--until"),c=[o,a].filter(p=>p!==void 0).length;if(c===0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"one of --in <dur> or --until <ISO> is required for reminder snooze"})+`
|
|
66
66
|
`),1;if(c>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --until may be provided"})+`
|
|
67
67
|
`),1;let d=await _s(i,e,t,s);if(d===void 0)return 1;let l={op:"snooze",id:i,version:d};o!==void 0&&(l.in=o),a!==void 0&&(l.until=a);let u=await ce(e,t,"reminder",l);if(!u.ok)return s.write(JSON.stringify(u.error)+`
|
|
68
68
|
`),1;let m=If(u.data),f=m?.fireAt?` \u2192 ${m.fireAt}`:"";return r.write(`Snoozed reminder ${i}${f}
|
|
@@ -103,9 +103,9 @@ var ef=Object.create;var ms=Object.defineProperty;var tf=Object.getOwnPropertyDe
|
|
|
103
103
|
`),1)}async function qf(n,e,t,r,s){let i=at(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"an attachment id is required for attachment view"})+`
|
|
104
104
|
`),1;let o=U(n,"--out"),a=await ce(e,t,"attachment",{op:"view",attachment_id:i});if(!a.ok)return s.write(JSON.stringify(a.error)+`
|
|
105
105
|
`),1;let c=a.data,d=String(c.filename??""),l=String(c.mime_type??""),u=c.size_bytes;if(o!==void 0){let f=c.data_base64;if(typeof f!="string")return s.write(JSON.stringify({ok:!1,code:"NO_ATTACHMENT_DATA",message:`attachment ${i} response did not include data_base64 bytes to save`})+`
|
|
106
|
-
`),1;let
|
|
107
|
-
`),1}try{cf(o,
|
|
108
|
-
`),1}return r.write(`saved: ${o} (${
|
|
106
|
+
`),1;let p=Buffer.from(f,"base64");if(u!==void 0){let g=Number(u);if(!Number.isNaN(g)&&p.length!==g)return s.write(JSON.stringify({ok:!1,code:"SIZE_MISMATCH",message:`attachment ${i} byte length mismatch: server reported size_bytes=${g} but decoded ${p.length} bytes \u2014 not writing ${o}`})+`
|
|
107
|
+
`),1}try{cf(o,p)}catch(g){let y=g instanceof Error?g.message:String(g);return s.write(JSON.stringify({ok:!1,code:"FILE_WRITE_ERROR",message:`Cannot write to ${o}: ${y}`})+`
|
|
108
|
+
`),1}return r.write(`saved: ${o} (${p.length} bytes)
|
|
109
109
|
`),0}let m=u!==void 0?String(u):"?";return r.write(`attachment ${i}: filename=${d} mime_type=${l} size_bytes=${m}
|
|
110
110
|
`),r.write(`(pass --out <path> to save the decoded bytes to a file)
|
|
111
111
|
`),0}async function Gf(n,e,t,r,s,i){switch(n){case"show":return Wf(e,t,r,s,i);case"update":return jf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown profile subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
@@ -183,11 +183,11 @@ Error codes (relayed from proxy):
|
|
|
183
183
|
CAPABILITY_DENIED launch lacks the required capability
|
|
184
184
|
UPSTREAM_UNREACHABLE proxy cannot reach the server
|
|
185
185
|
(and others from agentProxy.ts / the server)
|
|
186
|
-
`});var _o={};Me(_o,{runAgentcliCommand:()=>Vf});async function Vf(){return ho(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var wo=O(()=>{"use strict";yo()});import{execFileSync as vs}from"child_process";function ir(n){return vs("security",["add-generic-password","-U","-s",rr,"-a",sr,"-w",n]),`${rr}:${sr}`}function kt(){return vs("security",["find-generic-password","-s",rr,"-a",sr,"-w"]).toString().trim()}function vo(){vs("security",["delete-generic-password","-s",rr,"-a",sr])}var rr,sr,Yt=O(()=>{"use strict";rr="io.miomioos.mio-agent",sr="machine_token"});var bs=X((bw,bo)=>{bo.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var Eo=X((kw,So)=>{var zf=bs();function ko(n){this.mode=zf.MODE_8BIT_BYTE,this.data=n}ko.prototype={getLength:function(){return this.data.length},write:function(n){for(var e=0;e<this.data.length;e++)n.put(this.data.charCodeAt(e),8)}};So.exports=ko});var ks=X((Sw,xo)=>{var We={glog:function(n){if(n<1)throw new Error("glog("+n+")");return We.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return We.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(de=0;de<8;de++)We.EXP_TABLE[de]=1<<de;var de;for(de=8;de<256;de++)We.EXP_TABLE[de]=We.EXP_TABLE[de-4]^We.EXP_TABLE[de-5]^We.EXP_TABLE[de-6]^We.EXP_TABLE[de-8];var de;for(de=0;de<255;de++)We.LOG_TABLE[We.EXP_TABLE[de]]=de;var de;xo.exports=We});var Ss=X((Ew,To)=>{var It=ks();function or(n,e){if(n.length===void 0)throw new Error(n.length+"/"+e);for(var t=0;t<n.length&&n[t]===0;)t++;this.num=new Array(n.length-t+e);for(var r=0;r<n.length-t;r++)this.num[r]=n[r+t]}or.prototype={get:function(n){return this.num[n]},getLength:function(){return this.num.length},multiply:function(n){for(var e=new Array(this.getLength()+n.getLength()-1),t=0;t<this.getLength();t++)for(var r=0;r<n.getLength();r++)e[t+r]^=It.gexp(It.glog(this.get(t))+It.glog(n.get(r)));return new or(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=It.glog(this.get(0))-It.glog(n.get(0)),t=new Array(this.getLength()),r=0;r<this.getLength();r++)t[r]=this.get(r);for(var s=0;s<n.getLength();s++)t[s]^=It.gexp(It.glog(n.get(s))+e);return new or(t,0).mod(n)}};To.exports=or});var Ro=X((xw,Co)=>{Co.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Po=X((Tw,Oo)=>{var Be=bs(),Ao=Ss(),Kf=ks(),St=Ro(),_e={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(n){for(var e=n<<10;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15)>=0;)e^=_e.G15<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15);return(n<<10|e)^_e.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18)>=0;)e^=_e.G18<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return _e.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case St.PATTERN000:return(e+t)%2===0;case St.PATTERN001:return e%2===0;case St.PATTERN010:return t%3===0;case St.PATTERN011:return(e+t)%3===0;case St.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case St.PATTERN101:return e*t%2+e*t%3===0;case St.PATTERN110:return(e*t%2+e*t%3)%2===0;case St.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new Ao([1],0),t=0;t<n;t++)e=e.multiply(new Ao([1,Kf.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case Be.MODE_NUMBER:return 10;case Be.MODE_ALPHA_NUM:return 9;case Be.MODE_8BIT_BYTE:return 8;case Be.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case Be.MODE_NUMBER:return 12;case Be.MODE_ALPHA_NUM:return 11;case Be.MODE_8BIT_BYTE:return 16;case Be.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case Be.MODE_NUMBER:return 14;case Be.MODE_ALPHA_NUM:return 13;case Be.MODE_8BIT_BYTE:return 16;case Be.MODE_KANJI:return 12;default:throw new Error("mode:"+n)}else throw new Error("type:"+e)},getLostPoint:function(n){var e=n.getModuleCount(),t=0,r=0,s=0;for(r=0;r<e;r++)for(s=0;s<e;s++){for(var i=0,o=n.isDark(r,s),a=-1;a<=1;a++)if(!(r+a<0||e<=r+a))for(var c=-1;c<=1;c++)s+c<0||e<=s+c||a===0&&c===0||o===n.isDark(r+a,s+c)&&i++;i>5&&(t+=3+i-5)}for(r=0;r<e-1;r++)for(s=0;s<e-1;s++){var d=0;n.isDark(r,s)&&d++,n.isDark(r+1,s)&&d++,n.isDark(r,s+1)&&d++,n.isDark(r+1,s+1)&&d++,(d===0||d===4)&&(t+=3)}for(r=0;r<e;r++)for(s=0;s<e-6;s++)n.isDark(r,s)&&!n.isDark(r,s+1)&&n.isDark(r,s+2)&&n.isDark(r,s+3)&&n.isDark(r,s+4)&&!n.isDark(r,s+5)&&n.isDark(r,s+6)&&(t+=40);for(s=0;s<e;s++)for(r=0;r<e-6;r++)n.isDark(r,s)&&!n.isDark(r+1,s)&&n.isDark(r+2,s)&&n.isDark(r+3,s)&&n.isDark(r+4,s)&&!n.isDark(r+5,s)&&n.isDark(r+6,s)&&(t+=40);var l=0;for(s=0;s<e;s++)for(r=0;r<e;r++)n.isDark(r,s)&&l++;var u=Math.abs(100*l/e/e-50)/5;return t+=u*10,t}};Oo.exports=_e});var Es=X((Cw,Io)=>{Io.exports={L:1,M:0,Q:3,H:2}});var Mo=X((Rw,No)=>{var ar=Es();function Ze(n,e){this.totalCount=n,this.dataCount=e}Ze.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];Ze.getRSBlocks=function(n,e){var t=Ze.getRsBlockTable(n,e);if(t===void 0)throw new Error("bad rs block @ typeNumber:"+n+"/errorCorrectLevel:"+e);for(var r=t.length/3,s=[],i=0;i<r;i++)for(var o=t[i*3+0],a=t[i*3+1],c=t[i*3+2],d=0;d<o;d++)s.push(new Ze(a,c));return s};Ze.getRsBlockTable=function(n,e){switch(e){case ar.L:return Ze.RS_BLOCK_TABLE[(n-1)*4+0];case ar.M:return Ze.RS_BLOCK_TABLE[(n-1)*4+1];case ar.Q:return Ze.RS_BLOCK_TABLE[(n-1)*4+2];case ar.H:return Ze.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};No.exports=Ze});var Do=X((Aw,$o)=>{function Lo(){this.buffer=[],this.length=0}Lo.prototype={get:function(n){var e=Math.floor(n/8);return(this.buffer[e]>>>7-n%8&1)==1},put:function(n,e){for(var t=0;t<e;t++)this.putBit((n>>>e-t-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(n){var e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),n&&(this.buffer[e]|=128>>>this.length%8),this.length++}};$o.exports=Lo});var Ho=X((Ow,Uo)=>{var Xf=Eo(),Et=Po(),Qf=Ss(),Bo=Mo(),Fo=Do();function et(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}et.prototype={addData:function(n){var e=new Xf(n);this.dataList.push(e),this.dataCache=null},isDark:function(n,e){if(n<0||this.moduleCount<=n||e<0||this.moduleCount<=e)throw new Error(n+","+e);return this.modules[n][e]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var n=1;for(n=1;n<40;n++){for(var e=Bo.getRSBlocks(n,this.errorCorrectLevel),t=new Fo,r=0,s=0;s<e.length;s++)r+=e[s].dataCount;for(var i=0;i<this.dataList.length;i++){var o=this.dataList[i];t.put(o.mode,4),t.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(t)}if(t.getLengthInBits()<=r*8)break}this.typeNumber=n}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(n,e){this.moduleCount=this.typeNumber*4+17,this.modules=new Array(this.moduleCount);for(var t=0;t<this.moduleCount;t++){this.modules[t]=new Array(this.moduleCount);for(var r=0;r<this.moduleCount;r++)this.modules[t][r]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(n,e),this.typeNumber>=7&&this.setupTypeNumber(n),this.dataCache===null&&(this.dataCache=et.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,e)},setupPositionProbePattern:function(n,e){for(var t=-1;t<=7;t++)if(!(n+t<=-1||this.moduleCount<=n+t))for(var r=-1;r<=7;r++)e+r<=-1||this.moduleCount<=e+r||(0<=t&&t<=6&&(r===0||r===6)||0<=r&&r<=6&&(t===0||t===6)||2<=t&&t<=4&&2<=r&&r<=4?this.modules[n+t][e+r]=!0:this.modules[n+t][e+r]=!1)},getBestMaskPattern:function(){for(var n=0,e=0,t=0;t<8;t++){this.makeImpl(!0,t);var r=Et.getLostPoint(this);(t===0||n>r)&&(n=r,e=t)}return e},createMovieClip:function(n,e,t){var r=n.createEmptyMovieClip(e,t),s=1;this.make();for(var i=0;i<this.modules.length;i++)for(var o=i*s,a=0;a<this.modules[i].length;a++){var c=a*s,d=this.modules[i][a];d&&(r.beginFill(0,100),r.moveTo(c,o),r.lineTo(c+s,o),r.lineTo(c+s,o+s),r.lineTo(c,o+s),r.endFill())}return r},setupTimingPattern:function(){for(var n=8;n<this.moduleCount-8;n++)this.modules[n][6]===null&&(this.modules[n][6]=n%2===0);for(var e=8;e<this.moduleCount-8;e++)this.modules[6][e]===null&&(this.modules[6][e]=e%2===0)},setupPositionAdjustPattern:function(){for(var n=Et.getPatternPosition(this.typeNumber),e=0;e<n.length;e++)for(var t=0;t<n.length;t++){var r=n[e],s=n[t];if(this.modules[r][s]===null)for(var i=-2;i<=2;i++)for(var o=-2;o<=2;o++)Math.abs(i)===2||Math.abs(o)===2||i===0&&o===0?this.modules[r+i][s+o]=!0:this.modules[r+i][s+o]=!1}},setupTypeNumber:function(n){for(var e=Et.getBCHTypeNumber(this.typeNumber),t,r=0;r<18;r++)t=!n&&(e>>r&1)===1,this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=t;for(var s=0;s<18;s++)t=!n&&(e>>s&1)===1,this.modules[s%3+this.moduleCount-8-3][Math.floor(s/3)]=t},setupTypeInfo:function(n,e){for(var t=this.errorCorrectLevel<<3|e,r=Et.getBCHTypeInfo(t),s,i=0;i<15;i++)s=!n&&(r>>i&1)===1,i<6?this.modules[i][8]=s:i<8?this.modules[i+1][8]=s:this.modules[this.moduleCount-15+i][8]=s;for(var o=0;o<15;o++)s=!n&&(r>>o&1)===1,o<8?this.modules[8][this.moduleCount-o-1]=s:o<9?this.modules[8][15-o-1+1]=s:this.modules[8][15-o-1]=s;this.modules[this.moduleCount-8][8]=!n},mapData:function(n,e){for(var t=-1,r=this.moduleCount-1,s=7,i=0,o=this.moduleCount-1;o>0;o-=2)for(o===6&&o--;;){for(var a=0;a<2;a++)if(this.modules[r][o-a]===null){var c=!1;i<n.length&&(c=(n[i]>>>s&1)===1);var d=Et.getMask(e,r,o-a);d&&(c=!c),this.modules[r][o-a]=c,s--,s===-1&&(i++,s=7)}if(r+=t,r<0||this.moduleCount<=r){r-=t,t=-t;break}}}};et.PAD0=236;et.PAD1=17;et.createData=function(n,e,t){for(var r=Bo.getRSBlocks(n,e),s=new Fo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(s)}for(var a=0,c=0;c<r.length;c++)a+=r[c].dataCount;if(s.getLengthInBits()>a*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+a*8+")");for(s.getLengthInBits()+4<=a*8&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(!1);for(;!(s.getLengthInBits()>=a*8||(s.put(et.PAD0,8),s.getLengthInBits()>=a*8));)s.put(et.PAD1,8);return et.createBytes(s,r)};et.createBytes=function(n,e){for(var t=0,r=0,s=0,i=new Array(e.length),o=new Array(e.length),a=0;a<e.length;a++){var c=e[a].dataCount,d=e[a].totalCount-c;r=Math.max(r,c),s=Math.max(s,d),i[a]=new Array(c);for(var l=0;l<i[a].length;l++)i[a][l]=255&n.buffer[l+t];t+=c;var u=Et.getErrorCorrectPolynomial(d),m=new Qf(i[a],u.getLength()-1),f=m.mod(u);o[a]=new Array(u.getLength()-1);for(var g=0;g<o[a].length;g++){var p=g+f.getLength()-o[a].length;o[a][g]=p>=0?f.get(p):0}}for(var y=0,S=0;S<e.length;S++)y+=e[S].totalCount;for(var v=new Array(y),w=0,b=0;b<r;b++)for(var P=0;P<e.length;P++)b<i[P].length&&(v[w++]=i[P][b]);for(var x=0;x<s;x++)for(var N=0;N<e.length;N++)x<o[N].length&&(v[w++]=o[N][x]);return v};Uo.exports=et});var Ts=X((Pw,Go)=>{var Zf=Ho(),qo=Es(),eh="\x1B[40m \x1B[0m",cr="\x1B[47m \x1B[0m",th=function(n){return n?eh:cr},xs=function(n){return{times:function(e){return new Array(e).join(n)}}},nh=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};Go.exports={error:qo.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new Zf(-1,this.error);r.addData(n),r.make();var s="";if(e&&e.small){var i=!0,o=!1,a=r.getModuleCount(),c=r.modules.slice(),d=a%2===1;d&&c.push(nh(a,o));var l={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=xs(l.BLACK_WHITE).times(a+3),m=xs(l.WHITE_BLACK).times(a+3);s+=u+`
|
|
187
|
-
`;for(var f=0;f<a;f+=2){s+=l.WHITE_ALL;for(var
|
|
188
|
-
`}d||(s+=m)}else{var
|
|
186
|
+
`});var _o={};Le(_o,{runAgentcliCommand:()=>Vf});async function Vf(){return ho(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var wo=O(()=>{"use strict";yo()});import{execFileSync as vs}from"child_process";function ir(n){return vs("security",["add-generic-password","-U","-s",rr,"-a",sr,"-w",n]),`${rr}:${sr}`}function kt(){return vs("security",["find-generic-password","-s",rr,"-a",sr,"-w"]).toString().trim()}function vo(){vs("security",["delete-generic-password","-s",rr,"-a",sr])}var rr,sr,Yt=O(()=>{"use strict";rr="io.miomioos.mio-agent",sr="machine_token"});var bs=X((bw,bo)=>{bo.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var Eo=X((kw,So)=>{var zf=bs();function ko(n){this.mode=zf.MODE_8BIT_BYTE,this.data=n}ko.prototype={getLength:function(){return this.data.length},write:function(n){for(var e=0;e<this.data.length;e++)n.put(this.data.charCodeAt(e),8)}};So.exports=ko});var ks=X((Sw,xo)=>{var We={glog:function(n){if(n<1)throw new Error("glog("+n+")");return We.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return We.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(de=0;de<8;de++)We.EXP_TABLE[de]=1<<de;var de;for(de=8;de<256;de++)We.EXP_TABLE[de]=We.EXP_TABLE[de-4]^We.EXP_TABLE[de-5]^We.EXP_TABLE[de-6]^We.EXP_TABLE[de-8];var de;for(de=0;de<255;de++)We.LOG_TABLE[We.EXP_TABLE[de]]=de;var de;xo.exports=We});var Ss=X((Ew,To)=>{var It=ks();function or(n,e){if(n.length===void 0)throw new Error(n.length+"/"+e);for(var t=0;t<n.length&&n[t]===0;)t++;this.num=new Array(n.length-t+e);for(var r=0;r<n.length-t;r++)this.num[r]=n[r+t]}or.prototype={get:function(n){return this.num[n]},getLength:function(){return this.num.length},multiply:function(n){for(var e=new Array(this.getLength()+n.getLength()-1),t=0;t<this.getLength();t++)for(var r=0;r<n.getLength();r++)e[t+r]^=It.gexp(It.glog(this.get(t))+It.glog(n.get(r)));return new or(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=It.glog(this.get(0))-It.glog(n.get(0)),t=new Array(this.getLength()),r=0;r<this.getLength();r++)t[r]=this.get(r);for(var s=0;s<n.getLength();s++)t[s]^=It.gexp(It.glog(n.get(s))+e);return new or(t,0).mod(n)}};To.exports=or});var Ro=X((xw,Co)=>{Co.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Po=X((Tw,Oo)=>{var Be=bs(),Ao=Ss(),Kf=ks(),St=Ro(),_e={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(n){for(var e=n<<10;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15)>=0;)e^=_e.G15<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15);return(n<<10|e)^_e.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18)>=0;)e^=_e.G18<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return _e.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case St.PATTERN000:return(e+t)%2===0;case St.PATTERN001:return e%2===0;case St.PATTERN010:return t%3===0;case St.PATTERN011:return(e+t)%3===0;case St.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case St.PATTERN101:return e*t%2+e*t%3===0;case St.PATTERN110:return(e*t%2+e*t%3)%2===0;case St.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new Ao([1],0),t=0;t<n;t++)e=e.multiply(new Ao([1,Kf.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case Be.MODE_NUMBER:return 10;case Be.MODE_ALPHA_NUM:return 9;case Be.MODE_8BIT_BYTE:return 8;case Be.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case Be.MODE_NUMBER:return 12;case Be.MODE_ALPHA_NUM:return 11;case Be.MODE_8BIT_BYTE:return 16;case Be.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case Be.MODE_NUMBER:return 14;case Be.MODE_ALPHA_NUM:return 13;case Be.MODE_8BIT_BYTE:return 16;case Be.MODE_KANJI:return 12;default:throw new Error("mode:"+n)}else throw new Error("type:"+e)},getLostPoint:function(n){var e=n.getModuleCount(),t=0,r=0,s=0;for(r=0;r<e;r++)for(s=0;s<e;s++){for(var i=0,o=n.isDark(r,s),a=-1;a<=1;a++)if(!(r+a<0||e<=r+a))for(var c=-1;c<=1;c++)s+c<0||e<=s+c||a===0&&c===0||o===n.isDark(r+a,s+c)&&i++;i>5&&(t+=3+i-5)}for(r=0;r<e-1;r++)for(s=0;s<e-1;s++){var d=0;n.isDark(r,s)&&d++,n.isDark(r+1,s)&&d++,n.isDark(r,s+1)&&d++,n.isDark(r+1,s+1)&&d++,(d===0||d===4)&&(t+=3)}for(r=0;r<e;r++)for(s=0;s<e-6;s++)n.isDark(r,s)&&!n.isDark(r,s+1)&&n.isDark(r,s+2)&&n.isDark(r,s+3)&&n.isDark(r,s+4)&&!n.isDark(r,s+5)&&n.isDark(r,s+6)&&(t+=40);for(s=0;s<e;s++)for(r=0;r<e-6;r++)n.isDark(r,s)&&!n.isDark(r+1,s)&&n.isDark(r+2,s)&&n.isDark(r+3,s)&&n.isDark(r+4,s)&&!n.isDark(r+5,s)&&n.isDark(r+6,s)&&(t+=40);var l=0;for(s=0;s<e;s++)for(r=0;r<e;r++)n.isDark(r,s)&&l++;var u=Math.abs(100*l/e/e-50)/5;return t+=u*10,t}};Oo.exports=_e});var Es=X((Cw,Io)=>{Io.exports={L:1,M:0,Q:3,H:2}});var Mo=X((Rw,No)=>{var ar=Es();function Ze(n,e){this.totalCount=n,this.dataCount=e}Ze.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];Ze.getRSBlocks=function(n,e){var t=Ze.getRsBlockTable(n,e);if(t===void 0)throw new Error("bad rs block @ typeNumber:"+n+"/errorCorrectLevel:"+e);for(var r=t.length/3,s=[],i=0;i<r;i++)for(var o=t[i*3+0],a=t[i*3+1],c=t[i*3+2],d=0;d<o;d++)s.push(new Ze(a,c));return s};Ze.getRsBlockTable=function(n,e){switch(e){case ar.L:return Ze.RS_BLOCK_TABLE[(n-1)*4+0];case ar.M:return Ze.RS_BLOCK_TABLE[(n-1)*4+1];case ar.Q:return Ze.RS_BLOCK_TABLE[(n-1)*4+2];case ar.H:return Ze.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};No.exports=Ze});var Do=X((Aw,$o)=>{function Lo(){this.buffer=[],this.length=0}Lo.prototype={get:function(n){var e=Math.floor(n/8);return(this.buffer[e]>>>7-n%8&1)==1},put:function(n,e){for(var t=0;t<e;t++)this.putBit((n>>>e-t-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(n){var e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),n&&(this.buffer[e]|=128>>>this.length%8),this.length++}};$o.exports=Lo});var Ho=X((Ow,Uo)=>{var Xf=Eo(),Et=Po(),Qf=Ss(),Bo=Mo(),Fo=Do();function et(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}et.prototype={addData:function(n){var e=new Xf(n);this.dataList.push(e),this.dataCache=null},isDark:function(n,e){if(n<0||this.moduleCount<=n||e<0||this.moduleCount<=e)throw new Error(n+","+e);return this.modules[n][e]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var n=1;for(n=1;n<40;n++){for(var e=Bo.getRSBlocks(n,this.errorCorrectLevel),t=new Fo,r=0,s=0;s<e.length;s++)r+=e[s].dataCount;for(var i=0;i<this.dataList.length;i++){var o=this.dataList[i];t.put(o.mode,4),t.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(t)}if(t.getLengthInBits()<=r*8)break}this.typeNumber=n}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(n,e){this.moduleCount=this.typeNumber*4+17,this.modules=new Array(this.moduleCount);for(var t=0;t<this.moduleCount;t++){this.modules[t]=new Array(this.moduleCount);for(var r=0;r<this.moduleCount;r++)this.modules[t][r]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(n,e),this.typeNumber>=7&&this.setupTypeNumber(n),this.dataCache===null&&(this.dataCache=et.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,e)},setupPositionProbePattern:function(n,e){for(var t=-1;t<=7;t++)if(!(n+t<=-1||this.moduleCount<=n+t))for(var r=-1;r<=7;r++)e+r<=-1||this.moduleCount<=e+r||(0<=t&&t<=6&&(r===0||r===6)||0<=r&&r<=6&&(t===0||t===6)||2<=t&&t<=4&&2<=r&&r<=4?this.modules[n+t][e+r]=!0:this.modules[n+t][e+r]=!1)},getBestMaskPattern:function(){for(var n=0,e=0,t=0;t<8;t++){this.makeImpl(!0,t);var r=Et.getLostPoint(this);(t===0||n>r)&&(n=r,e=t)}return e},createMovieClip:function(n,e,t){var r=n.createEmptyMovieClip(e,t),s=1;this.make();for(var i=0;i<this.modules.length;i++)for(var o=i*s,a=0;a<this.modules[i].length;a++){var c=a*s,d=this.modules[i][a];d&&(r.beginFill(0,100),r.moveTo(c,o),r.lineTo(c+s,o),r.lineTo(c+s,o+s),r.lineTo(c,o+s),r.endFill())}return r},setupTimingPattern:function(){for(var n=8;n<this.moduleCount-8;n++)this.modules[n][6]===null&&(this.modules[n][6]=n%2===0);for(var e=8;e<this.moduleCount-8;e++)this.modules[6][e]===null&&(this.modules[6][e]=e%2===0)},setupPositionAdjustPattern:function(){for(var n=Et.getPatternPosition(this.typeNumber),e=0;e<n.length;e++)for(var t=0;t<n.length;t++){var r=n[e],s=n[t];if(this.modules[r][s]===null)for(var i=-2;i<=2;i++)for(var o=-2;o<=2;o++)Math.abs(i)===2||Math.abs(o)===2||i===0&&o===0?this.modules[r+i][s+o]=!0:this.modules[r+i][s+o]=!1}},setupTypeNumber:function(n){for(var e=Et.getBCHTypeNumber(this.typeNumber),t,r=0;r<18;r++)t=!n&&(e>>r&1)===1,this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=t;for(var s=0;s<18;s++)t=!n&&(e>>s&1)===1,this.modules[s%3+this.moduleCount-8-3][Math.floor(s/3)]=t},setupTypeInfo:function(n,e){for(var t=this.errorCorrectLevel<<3|e,r=Et.getBCHTypeInfo(t),s,i=0;i<15;i++)s=!n&&(r>>i&1)===1,i<6?this.modules[i][8]=s:i<8?this.modules[i+1][8]=s:this.modules[this.moduleCount-15+i][8]=s;for(var o=0;o<15;o++)s=!n&&(r>>o&1)===1,o<8?this.modules[8][this.moduleCount-o-1]=s:o<9?this.modules[8][15-o-1+1]=s:this.modules[8][15-o-1]=s;this.modules[this.moduleCount-8][8]=!n},mapData:function(n,e){for(var t=-1,r=this.moduleCount-1,s=7,i=0,o=this.moduleCount-1;o>0;o-=2)for(o===6&&o--;;){for(var a=0;a<2;a++)if(this.modules[r][o-a]===null){var c=!1;i<n.length&&(c=(n[i]>>>s&1)===1);var d=Et.getMask(e,r,o-a);d&&(c=!c),this.modules[r][o-a]=c,s--,s===-1&&(i++,s=7)}if(r+=t,r<0||this.moduleCount<=r){r-=t,t=-t;break}}}};et.PAD0=236;et.PAD1=17;et.createData=function(n,e,t){for(var r=Bo.getRSBlocks(n,e),s=new Fo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(s)}for(var a=0,c=0;c<r.length;c++)a+=r[c].dataCount;if(s.getLengthInBits()>a*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+a*8+")");for(s.getLengthInBits()+4<=a*8&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(!1);for(;!(s.getLengthInBits()>=a*8||(s.put(et.PAD0,8),s.getLengthInBits()>=a*8));)s.put(et.PAD1,8);return et.createBytes(s,r)};et.createBytes=function(n,e){for(var t=0,r=0,s=0,i=new Array(e.length),o=new Array(e.length),a=0;a<e.length;a++){var c=e[a].dataCount,d=e[a].totalCount-c;r=Math.max(r,c),s=Math.max(s,d),i[a]=new Array(c);for(var l=0;l<i[a].length;l++)i[a][l]=255&n.buffer[l+t];t+=c;var u=Et.getErrorCorrectPolynomial(d),m=new Qf(i[a],u.getLength()-1),f=m.mod(u);o[a]=new Array(u.getLength()-1);for(var p=0;p<o[a].length;p++){var g=p+f.getLength()-o[a].length;o[a][p]=g>=0?f.get(g):0}}for(var y=0,S=0;S<e.length;S++)y+=e[S].totalCount;for(var v=new Array(y),_=0,b=0;b<r;b++)for(var P=0;P<e.length;P++)b<i[P].length&&(v[_++]=i[P][b]);for(var x=0;x<s;x++)for(var N=0;N<e.length;N++)x<o[N].length&&(v[_++]=o[N][x]);return v};Uo.exports=et});var Ts=X((Pw,Go)=>{var Zf=Ho(),qo=Es(),eh="\x1B[40m \x1B[0m",cr="\x1B[47m \x1B[0m",th=function(n){return n?eh:cr},xs=function(n){return{times:function(e){return new Array(e).join(n)}}},nh=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};Go.exports={error:qo.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new Zf(-1,this.error);r.addData(n),r.make();var s="";if(e&&e.small){var i=!0,o=!1,a=r.getModuleCount(),c=r.modules.slice(),d=a%2===1;d&&c.push(nh(a,o));var l={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=xs(l.BLACK_WHITE).times(a+3),m=xs(l.WHITE_BLACK).times(a+3);s+=u+`
|
|
187
|
+
`;for(var f=0;f<a;f+=2){s+=l.WHITE_ALL;for(var p=0;p<a;p++)c[f][p]===o&&c[f+1][p]===o?s+=l.WHITE_ALL:c[f][p]===o&&c[f+1][p]===i?s+=l.WHITE_BLACK:c[f][p]===i&&c[f+1][p]===o?s+=l.BLACK_WHITE:s+=l.BLACK_ALL;s+=l.WHITE_ALL+`
|
|
188
|
+
`}d||(s+=m)}else{var g=xs(cr).times(r.getModuleCount()+3);s+=g+`
|
|
189
189
|
`,r.modules.forEach(function(y){s+=cr,s+=y.map(th).join(""),s+=cr+`
|
|
190
|
-
`}),s+=
|
|
190
|
+
`}),s+=g}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=qo[n]||this.error}}});var Vo={};Le(Vo,{runLogin:()=>lh});import{parseArgs as rh}from"node:util";import bn from"node:os";import{mkdirSync as sh,writeFileSync as ih,existsSync as oh}from"node:fs";import{join as Wo}from"node:path";function ch(n){return new Promise(e=>setTimeout(e,n))}function Yo(){console.log(`Usage: mio-agent login [--server <url>] [--device-name <name>]
|
|
191
191
|
|
|
192
192
|
Zero-touch machine enrollment via QR + phone approval.
|
|
193
193
|
|
|
@@ -195,25 +195,25 @@ Options:
|
|
|
195
195
|
--server <url> MioServer base URL (default: ${Cs})
|
|
196
196
|
--device-name <name> Friendly name for this machine (default: hostname)
|
|
197
197
|
--help Show this message
|
|
198
|
-
`)}async function lh(n){let e;try{({values:e}=rh({args:n,options:{server:{type:"string",default:Cs},"device-name":{type:"string",default:bn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(
|
|
199
|
-
`);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=uh("tail",s,{stdio:"inherit"});return await new Promise(o=>{i.on("exit",c=>o(c??0)),i.on("error",c=>{console.error(`Failed to spawn tail: ${c.message}`),o(1)});let a=()=>i.kill("SIGINT");process.on("SIGINT",a),process.on("SIGTERM",a)})}var Qo=O(()=>{"use strict"});function h(n,e,t,r){let s={time:new Date().toISOString(),level:n,component:e,message:t,...r};console.log(JSON.stringify(s))}function k(n,e,t){h("error",n,e,{error:t instanceof Error?t.message:String(t)})}var le=O(()=>{"use strict"});import{readFileSync as gh,writeFileSync as ph,mkdirSync as As,chmodSync as mh,existsSync as Zo}from"fs";import{homedir as yh}from"os";import{join as kn}from"path";function Sn(){As(ge,{recursive:!0,mode:448}),As(_h,{recursive:!0,mode:448}),As(Nt,{recursive:!0,mode:448})}function ta(){return Zo(Vt)}function je(){if(!Zo(Vt))throw new Error(`No config at ${Vt}. Run: mio-agent login`);return JSON.parse(gh(Vt,"utf-8"))}function lr(n){Sn();let e=JSON.stringify(n,null,2);ph(Vt,e,{encoding:"utf-8",mode:384}),mh(Vt,384)}var ge,Vt,_h,Nt,jw,ea,Je=O(()=>{"use strict";ge=kn(yh(),".mio"),Vt=kn(ge,"agent.json"),_h=kn(ge,"logs"),Nt=kn(ge,"tmp"),jw=kn(ge,"agent.sock"),ea=7878});import{readFileSync as wh,writeFileSync as vh,existsSync as bh}from"fs";import{join as kh}from"path";function na(){if(!bh(Os))return{};try{return JSON.parse(wh(Os,"utf-8"))}catch{return{}}}function Sh(n){Sn(),vh(Os,JSON.stringify(n,null,2),{mode:384})}function ra(){let n=na();return new Map(Object.entries(n))}function sa(n,e){let t=na(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Sh(t))}var Os,ia=O(()=>{"use strict";Je();Os=kh(ge,"cursors.json")});async function te(n,e={}){let t=await fetch(n,{...e,headers:{"Content-Type":"application/json",...e.headers}});if(!t.ok){let r=await t.text().catch(()=>""),s="UNKNOWN";try{s=JSON.parse(r)?.error?.code??s}catch{}throw new En(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function pe(n){return{Authorization:`Bearer ${n}`}}async function oa(n,e){return te(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:pe(e)})}async function aa(n,e,t){return te(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:pe(t),body:JSON.stringify({})})}async function ca(n,e,t){await te(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:pe(t),body:JSON.stringify({})})}async function la(n,e,t=!1,r){await te(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:pe(e),body:JSON.stringify(t?{going_offline:!0}:r?{usage:r}:{})})}async function da(n,e,t,r){await te(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:pe(r),body:JSON.stringify({status:t})})}async function ua(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return te(s,{headers:pe(r)})}async function fa(n,e,t){return te(`${n}/api/v1/actions/${e}`,{headers:pe(t)})}async function ha(n,e,t){return te(`${n}/api/v1/approvals/${e}`,{headers:pe(t)})}async function ga(n,e,t,r){let s=r?{approval_id:r}:{};return te(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:pe(t),body:JSON.stringify(s)})}async function pa(n,e,t){await te(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:pe(t),body:JSON.stringify({})})}async function ma(n,e,t,r,s,i){let o=new URLSearchParams;r!==void 0&&o.set("after_seq",r),s!==void 0&&o.set("limit",String(s));let a=o.toString()?`?${o.toString()}`:"",c=`${n}/api/v1/workrooms/${e}/channels/${t}/messages${a}`,d=await te(c,{headers:pe(i)});return{messages:d.messages,hasMore:d.has_more}}async function xn(n,e,t,r,s){let i={content:r.content,client_idempotency_key:r.clientIdempotencyKey};return r.agentId!==void 0&&(i.agent_id=r.agentId),te(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:pe(s),body:JSON.stringify(i)})}async function ya(n,e,t){return(await te(`${n}/api/v1/workrooms/${e}/members`,{headers:pe(t)})).members??[]}async function _a(n,e,t){return te(`${n}/api/v1/workrooms/${e}/roster`,{headers:pe(t)})}async function wa(n,e,t){return(await te(`${n}/api/v1/workrooms/${e}/channels`,{headers:pe(t)})).channels??[]}async function va(n,e,t){return(await te(`${n}/internal/agent-api/channels`,{headers:{...pe(e),"X-Mio-Agent-Id":t}})).channels??[]}async function ba(n,e,t,r){return(await te(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...pe(e),"X-Mio-Agent-Id":t}})).tasks??[]}function Fe(n,e){return{...pe(n),"X-Mio-Agent-Id":e}}async function ka(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Sa(n,e,t){return(await te(`${n}/internal/agent-api/reminders/list`,{headers:Fe(e,t)})).reminders??[]}async function Ea(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function xa(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Ta(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Ca(n,e,t){return(await te(`${n}/internal/agent-api/reminders/log`,{headers:Fe(e,t)})).events??[]}async function Ra(n,e,t,r){await te(`${n}/internal/agent-api/typing`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Aa(n,e,t,r){await te(`${n}/internal/agent-api/status`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Oa(n,e,t,r){await te(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})}async function Pa(n,e,t,r,s,i){let o=new URLSearchParams;s!==void 0&&o.set("limit",String(s)),i!==void 0&&o.set("after_seq",i);let a=o.toString()?`?${o.toString()}`:"";return(await te(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${a}`,{headers:Fe(e,t)})).messages??[]}async function Ia(n,e,t,r){return(await te(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:Fe(e,t)})).message}async function Na(n,e,t,r){return te(`${n}/internal/agent-api/attachments/${r}`,{headers:Fe(e,t)})}var En,dr=O(()=>{"use strict";En=class extends Error{constructor(t,r,s){super(s);this.statusCode=t;this.errorCode=r;this.name="ApiError"}statusCode;errorCode;get isDefinitiveRejection(){return this.statusCode>=400&&this.statusCode<500}}});var $a=X((Qw,La)=>{var zt=Z("fs"),Ma=Z("url"),Eh=Z("child_process").spawn;La.exports=Ps;Ps.XMLHttpRequest=Ps;function Ps(n){"use strict";n=n||{};var e=this,t=Z("http"),r=Z("https"),s,i,o={},a=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},c),l=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],u=["TRACE","TRACK","CONNECT"],m=!1,f=!1,
|
|
200
|
-
`);return w.substr(0,w.length-2)},this.getRequestHeader=function(w){return typeof w=="string"&&d[w]?d[w]:""},this.send=function(w){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(m)throw new Error("INVALID_STATE_ERR: send has already been called");var b=!1,P=!1,x=Ma.parse(o.url),N;switch(x.protocol){case"https:":b=!0;case"http:":N=x.hostname;break;case"file:":P=!0;break;case void 0:case"":N="localhost";break;default:throw new Error("Protocol not supported.")}if(P){if(o.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(o.async)zt.readFile(unescape(x.pathname),function(F,V){F?e.handleError(F,F.errno||-1):(e.status=200,e.responseText=V.toString("utf8"),e.response=V,v(e.DONE))});else try{this.response=zt.readFileSync(unescape(x.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,v(e.DONE)}catch(F){this.handleError(F,F.errno||-1)}return}var G=x.port||(b?443:80),J=x.pathname+(x.search?x.search:"");if(d.Host=N,b&&G===443||G===80||(d.Host+=":"+x.port),o.user){typeof o.password>"u"&&(o.password="");var W=new Buffer(o.user+":"+o.password);d.Authorization="Basic "+W.toString("base64")}if(o.method==="GET"||o.method==="HEAD")w=null;else if(w){d["Content-Length"]=Buffer.isBuffer(w)?w.length:Buffer.byteLength(w);var Q=Object.keys(d);Q.some(function(F){return F.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(d["Content-Length"]=0);var ne=n.agent||!1,H={host:N,port:G,path:J,method:o.method,headers:d,agent:ne};if(b&&(H.pfx=n.pfx,H.key=n.key,H.passphrase=n.passphrase,H.cert=n.cert,H.ca=n.ca,H.ciphers=n.ciphers,H.rejectUnauthorized=n.rejectUnauthorized!==!1),f=!1,o.async){var ie=b?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var M=function(F){if(i=F,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var V=Ma.parse(o.url);N=V.hostname;var ae={hostname:V.hostname,port:V.port,path:V.path,method:i.statusCode===303?"GET":o.method,headers:d};b&&(ae.pfx=n.pfx,ae.key=n.key,ae.passphrase=n.passphrase,ae.cert=n.cert,ae.ca=n.ca,ae.ciphers=n.ciphers,ae.rejectUnauthorized=n.rejectUnauthorized!==!1),s=ie(ae,M).on("error",C),s.end();return}v(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(fe){if(fe){var I=Buffer.from(fe);e.response=Buffer.concat([e.response,I])}m&&v(e.LOADING)}),i.on("end",function(){m&&(m=!1,v(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(fe){e.handleError(fe)})},C=function(F){if(s.reusedSocket&&F.code==="ECONNRESET")return ie(H,M).on("error",C);e.handleError(F)};s=ie(H,M).on("error",C),n.autoUnref&&s.on("socket",F=>{F.unref()}),w&&s.write(w),s.end(),e.dispatchEvent("loadstart")}else{var _=".node-xmlhttprequest-content-"+process.pid,R=".node-xmlhttprequest-sync-"+process.pid;zt.writeFileSync(R,"","utf8");for(var A="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(b?"s":"")+".request;var options = "+JSON.stringify(H)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+_+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+R+"');});response.on('error', function(error) {fs.writeFileSync('"+_+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});}).on('error', function(error) {fs.writeFileSync('"+_+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});"+(w?"req.write('"+JSON.stringify(w).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",T=Eh(process.argv[0],["-e",A]),L;zt.existsSync(R););if(e.responseText=zt.readFileSync(_,"utf8"),T.stdin.end(),zt.unlinkSync(_),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var E=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(E,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var $=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:$.data.headers},e.responseText=$.data.text,e.response=Buffer.from($.data.data,"base64"),v(e.DONE,!0)}}},this.handleError=function(w,b){this.status=b||0,this.statusText=w,this.responseText=w.stack,f=!0,v(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),f=g=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||m)&&this.readyState!==this.DONE&&(m=!1,v(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(w,b){w in p||(p[w]=[]),p[w].push(b)},this.removeEventListener=function(w,b){w in p&&(p[w]=p[w].filter(function(P){return P!==b}))},this.dispatchEvent=function(w){if(typeof e["on"+w]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+w]()},0):e["on"+w]()),w in p)for(let b=0,P=p[w].length;b<P;b++)this.readyState===this.DONE?setTimeout(function(){p[w][b].call(e)},0):p[w][b].call(e)};var v=function(w){if(!(e.readyState===w||e.readyState===e.UNSENT&&g)&&(e.readyState=w,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let b;g?b="abort":f?b="error":b="load",e.dispatchEvent(b),e.dispatchEvent("loadend")}}}});var Ye,Tn,Cn,ur=O(()=>{Ye=Object.create(null);Ye.open="0";Ye.close="1";Ye.ping="2";Ye.pong="3";Ye.message="4";Ye.upgrade="5";Ye.noop="6";Tn=Object.create(null);Object.keys(Ye).forEach(n=>{Tn[Ye[n]]=n});Cn={type:"error",data:"parser error"}});function Ba(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(Da(n.data,!1));Rn(n,!0,t=>{Is||(Is=new TextEncoder),e(Is.encode(t))})}var Rn,Da,Is,Fa=O(()=>{ur();Rn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+Da(e,!0).toString("base64")):r(Ye[n]+(e||"")),Da=(n,e)=>Buffer.isBuffer(n)||n instanceof Uint8Array&&!e?n:n instanceof ArrayBuffer?Buffer.from(n):Buffer.from(n.buffer,n.byteOffset,n.byteLength)});var An,Ua,Ha=O(()=>{ur();An=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ua(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:Ua(r,e)}}return Tn[t]?n.length>1?{type:Tn[t],data:n.substring(1)}:{type:Tn[t]}:Cn},Ua=(n,e)=>e==="arraybuffer"?n instanceof ArrayBuffer?n:Buffer.isBuffer(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n.buffer:Buffer.isBuffer(n)?n:Buffer.from(n)});function ja(){return new TransformStream({transform(n,e){Ba(n,t=>{let r=t.length,s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);let i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{s=new Uint8Array(9);let i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}n.data&&typeof n.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}function fr(n){return n.reduce((e,t)=>e+t.length,0)}function hr(n,e){if(n[0].length===e)return n.shift();let t=new Uint8Array(e),r=0;for(let s=0;s<e;s++)t[s]=n[0][r++],r===n[0].length&&(n.shift(),r=0);return n.length&&r<n[0].length&&(n[0]=n[0].slice(r)),t}function Ja(n,e){Ns||(Ns=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(fr(t)<1)break;let c=hr(t,1);i=(c[0]&128)===128,s=c[0]&127,s<126?r=3:s===126?r=1:r=2}else if(r===1){if(fr(t)<2)break;let c=hr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(fr(t)<8)break;let c=hr(t,8),d=new DataView(c.buffer,c.byteOffset,c.length),l=d.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(Cn);break}s=l*Math.pow(2,32)+d.getUint32(4),r=3}else{if(fr(t)<s)break;let c=hr(t,s);a.enqueue(An(i?c:Ns.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(Cn);break}}}})}var qa,Ga,Wa,Ns,Ms,Kt=O(()=>{Fa();Ha();ur();qa="",Ga=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Rn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(qa))})})},Wa=(n,e)=>{let t=n.split(qa),r=[];for(let s=0;s<t.length;s++){let i=An(t[s],e);if(r.push(i),i.type==="error")break}return r};Ms=4});var Mt=X(Ya=>{Ya.Emitter=Se;function Se(n){if(n)return xh(n)}function xh(n){for(var e in Se.prototype)n[e]=Se.prototype[e];return n}Se.prototype.on=Se.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Se.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Se.prototype.off=Se.prototype.removeListener=Se.prototype.removeAllListeners=Se.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var r,s=0;s<t.length;s++)if(r=t[s],r===e||r.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+n],this};Se.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(t){t=t.slice(0);for(var r=0,s=t.length;r<s;++r)t[r].apply(this,e)}return this};Se.prototype.emitReserved=Se.prototype.emit;Se.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Se.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function za(){return new Ls}function Th(n){let e=n.split("; "),t=e[0].indexOf("=");if(t===-1)return;let r=e[0].substring(0,t).trim();if(!r.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:r,value:s};for(let o=1;o<e.length;o++){let a=e[o].split("=");if(a.length!==2)continue;let c=a[0].trim(),d=a[1].trim();switch(c){case"Expires":i.expires=new Date(d);break;case"Max-Age":let l=new Date;l.setUTCSeconds(l.getUTCSeconds()+parseInt(d,10)),i.expires=l;break;default:}}return i}var ct,Ee,Va,Ls,Lt=O(()=>{ct=process.nextTick,Ee=global,Va="nodebuffer";Ls=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=Th(t);r&&this._cookies.set(r.name,r)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,r)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(r)}),this._cookies.entries()}addCookies(e){let t=[];for(let[r,s]of this.cookies)t.push(`${r}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,r]of this.cookies)e.append("cookie",`${t}=${r.value}`)}}});function gr(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function lt(n,e){e.useNativeTimers?(n.setTimeoutFn=Ch.bind(Ee),n.clearTimeoutFn=Rh.bind(Ee)):(n.setTimeoutFn=Ee.setTimeout.bind(Ee),n.clearTimeoutFn=Ee.clearTimeout.bind(Ee))}function Ka(n){return typeof n=="string"?Oh(n):Math.ceil((n.byteLength||n.size)*Ah)}function Oh(n){let e=0,t=0;for(let r=0,s=n.length;r<s;r++)e=n.charCodeAt(r),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(r++,t+=4);return t}function pr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Ch,Rh,Ah,$t=O(()=>{Lt();Ch=Ee.setTimeout,Rh=Ee.clearTimeout;Ah=1.33});function Xa(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Qa(n){let e={},t=n.split("&");for(let r=0,s=t.length;r<s;r++){let i=t[r].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}var $s=O(()=>{});var ec=X((hv,Za)=>{var Xt=1e3,Qt=Xt*60,Zt=Qt*60,Dt=Zt*24,Ph=Dt*7,Ih=Dt*365.25;Za.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return Nh(n);if(t==="number"&&isFinite(n))return e.long?Lh(n):Mh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function Nh(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Ih;case"weeks":case"week":case"w":return t*Ph;case"days":case"day":case"d":return t*Dt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Zt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Qt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Xt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Mh(n){var e=Math.abs(n);return e>=Dt?Math.round(n/Dt)+"d":e>=Zt?Math.round(n/Zt)+"h":e>=Qt?Math.round(n/Qt)+"m":e>=Xt?Math.round(n/Xt)+"s":n+"ms"}function Lh(n){var e=Math.abs(n);return e>=Dt?mr(n,e,Dt,"day"):e>=Zt?mr(n,e,Zt,"hour"):e>=Qt?mr(n,e,Qt,"minute"):e>=Xt?mr(n,e,Xt,"second"):n+" ms"}function mr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Ds=X((gv,tc)=>{function $h(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=ec(),t.destroy=d,Object.keys(n).forEach(l=>{t[l]=n[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let u=0;for(let m=0;m<l.length;m++)u=(u<<5)-u+l.charCodeAt(m),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,m=null,f,g;function p(...y){if(!p.enabled)return;let S=p,v=Number(new Date),w=v-(u||v);S.diff=w,S.prev=u,S.curr=v,u=v,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let b=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(x,N)=>{if(x==="%%")return"%";b++;let G=t.formatters[N];if(typeof G=="function"){let J=y[b];x=G.call(S,J),y.splice(b,1),b--}return x}),t.formatArgs.call(S,y),(S.log||t.log).apply(S,y)}return p.namespace=l,p.useColors=t.useColors(),p.color=t.selectColor(l),p.extend=r,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(f!==t.namespaces&&(f=t.namespaces,g=t.enabled(l)),g),set:y=>{m=y}}),typeof t.init=="function"&&t.init(p),p}function r(l,u){let m=t(this.namespace+(typeof u>"u"?":":u)+l);return m.log=this.log,m}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let u=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of u)m[0]==="-"?t.skips.push(m.slice(1)):t.names.push(m)}function i(l,u){let m=0,f=0,g=-1,p=0;for(;m<l.length;)if(f<u.length&&(u[f]===l[m]||u[f]==="*"))u[f]==="*"?(g=f,p=m,f++):(m++,f++);else if(g!==-1)f=g+1,p++,m=p;else return!1;for(;f<u.length&&u[f]==="*";)f++;return f===u.length}function o(){let l=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),l}function a(l){for(let u of t.skips)if(i(l,u))return!1;for(let u of t.names)if(i(l,u))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}tc.exports=$h});var nc=X((Ae,yr)=>{Ae.formatArgs=Bh;Ae.save=Fh;Ae.load=Uh;Ae.useColors=Dh;Ae.storage=Hh();Ae.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Ae.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Dh(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Bh(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+yr.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}Ae.log=console.debug||console.log||(()=>{});function Fh(n){try{n?Ae.storage.setItem("debug",n):Ae.storage.removeItem("debug")}catch{}}function Uh(){let n;try{n=Ae.storage.getItem("debug")||Ae.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Hh(){try{return localStorage}catch{}}yr.exports=Ds()(Ae);var{formatters:qh}=yr.exports;qh.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var sc=X((me,wr)=>{var Gh=Z("tty"),_r=Z("util");me.init=Kh;me.log=Yh;me.formatArgs=jh;me.save=Vh;me.load=zh;me.useColors=Wh;me.destroy=_r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");me.colors=[6,2,3,4,5,1];try{let n=Z("supports-color");n&&(n.stderr||n).level>=2&&(me.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}me.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function Wh(){return"colors"in me.inspectOpts?!!me.inspectOpts.colors:Gh.isatty(process.stderr.fd)}function jh(n){let{namespace:e,useColors:t}=this;if(t){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${s};1m${e} \x1B[0m`;n[0]=i+n[0].split(`
|
|
198
|
+
`)}async function lh(n){let e;try{({values:e}=rh({args:n,options:{server:{type:"string",default:Cs},"device-name":{type:"string",default:bn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(_){let b=_ instanceof Error?_.message:String(_);return console.error(`Error: ${b}`),Yo(),1}if(e.help)return Yo(),0;let t=(e.server??Cs).replace(/\/+$/,""),r=e["device-name"]??bn.hostname(),s=bn.platform(),i=bn.arch(),o;try{let _=await fetch(`${t}/api/v1/enrollment-intents`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_name:r,platform:s,arch:i})});if(!_.ok)return console.error(`Failed to create enrollment intent (HTTP ${_.status}). Check --server (currently ${t}).`),1;o=await _.json()}catch(_){let b=_ instanceof Error?_.message:String(_);return console.error(`Network error contacting ${t}: ${b}`),1}let a=new URLSearchParams({code:o.opaque_code,server:t,name:r,platform:s,arch:i}),c=`mio://enroll/${o.intent_id}?${a.toString()}`;console.log("Open CodeLight on your phone and scan the QR (or use iOS Camera):"),console.log("");let d=await Promise.resolve().then(()=>re(Ts(),1)).catch(()=>null),l=d?.default??d,u=typeof l?.generate=="function"?(_,b,P)=>l.generate(_,b,P):null;u?await new Promise(_=>{u(c,{small:!0},b=>{console.log(b),_()})}):console.log("(qrcode-terminal unavailable \u2014 paste the URL below into iOS Safari instead.)"),console.log(`(or paste this URL into Safari on iPhone: ${c})`),console.log(""),console.log(`Intent expires at ${o.expires_at}.`),console.log("Waiting for phone approval (up to 5 minutes)...");let m=Date.now(),f=jo,p=null;for(;Date.now()-m<ah;){await ch(f);try{let _=await fetch(`${t}/api/v1/enrollment-intents/${o.intent_id}?code=${encodeURIComponent(o.opaque_code)}`,{method:"GET"});if(_.status===200){p=await _.json();break}if(_.status===202){f=jo;continue}if(_.status===403)return console.error("Enrollment code became invalid (expired, canceled, or already consumed). Re-run `mio-agent login`."),1;f=Math.min(f*2,Jo);continue}catch{f=Math.min(f*2,Jo);continue}}if(!p)return console.error("Enrollment timed out (5 min). Re-run `mio-agent login` to retry."),1;let g=ir(p.machine_token),y=Wo(bn.homedir(),".mio");oh(y)||sh(y,{recursive:!0,mode:448});let S=Wo(y,"agent.json"),v={machine_id:p.machine_id,org_id:p.org_id,workroom_id:p.workroom_id,server_url:t,keychain_item_ref:g,runtimes:[],token_buffer:!1};return ih(S,JSON.stringify(v,null,2),{mode:384}),console.log(""),console.log(`Successfully enrolled as "${r}" in workroom ${p.workroom_id.slice(0,8)}.`),console.log("Config: ~/.mio/agent.json (0600)"),console.log(`Token: macOS Keychain (${g})`),console.log(""),console.log("Run `mio-agent doctor` to verify."),0}var Cs,jo,Jo,ah,zo=O(()=>{"use strict";Yt();Cs="https://mio.wdao.chat",jo=2e3,Jo=3e4,ah=300*1e3});var Xo={};Le(Xo,{runLogs:()=>hh});import{existsSync as Rs}from"node:fs";import{homedir as dh}from"node:os";import{join as Ko}from"node:path";import{spawn as uh}from"node:child_process";function fh(){let n=dh(),e=Ko(n,".mio","logs","mio-agent.log"),t=Ko(n,".mio","logs","mio-agent-error.log"),r="/tmp/mio-agent.log",s=[];return Rs(e)&&s.push(e),Rs(t)&&s.push(t),s.length===0&&Rs(r)&&s.push(r),s}async function hh(n){let e=!0,t=50;for(let o=0;o<n.length;o++){let a=n[o];if(a==="-f"||a==="--follow")e=!0;else if(a==="--no-follow")e=!1;else if(a==="-n"&&n[o+1]){let c=parseInt(n[++o],10);isNaN(c)||(t=c)}}let r=fh();if(r.length===0)return console.error("No log file found."),console.error(" Looked for: ~/.mio/logs/mio-agent.log and /tmp/mio-agent.log"),console.error(" Run `mio-agent start` or `mio-agent install --background --version <v>` first."),1;console.error(`# tailing: ${r.join(", ")}
|
|
199
|
+
`);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=uh("tail",s,{stdio:"inherit"});return await new Promise(o=>{i.on("exit",c=>o(c??0)),i.on("error",c=>{console.error(`Failed to spawn tail: ${c.message}`),o(1)});let a=()=>i.kill("SIGINT");process.on("SIGINT",a),process.on("SIGTERM",a)})}var Qo=O(()=>{"use strict"});function h(n,e,t,r){let s={time:new Date().toISOString(),level:n,component:e,message:t,...r};console.log(JSON.stringify(s))}function k(n,e,t){h("error",n,e,{error:t instanceof Error?t.message:String(t)})}var le=O(()=>{"use strict"});import{readFileSync as gh,writeFileSync as ph,mkdirSync as As,chmodSync as mh,existsSync as Zo}from"fs";import{homedir as yh}from"os";import{join as kn}from"path";function Sn(){As(ge,{recursive:!0,mode:448}),As(_h,{recursive:!0,mode:448}),As(Nt,{recursive:!0,mode:448})}function ta(){return Zo(Vt)}function je(){if(!Zo(Vt))throw new Error(`No config at ${Vt}. Run: mio-agent login`);return JSON.parse(gh(Vt,"utf-8"))}function lr(n){Sn();let e=JSON.stringify(n,null,2);ph(Vt,e,{encoding:"utf-8",mode:384}),mh(Vt,384)}var ge,Vt,_h,Nt,jw,ea,Je=O(()=>{"use strict";ge=kn(yh(),".mio"),Vt=kn(ge,"agent.json"),_h=kn(ge,"logs"),Nt=kn(ge,"tmp"),jw=kn(ge,"agent.sock"),ea=7878});import{readFileSync as wh,writeFileSync as vh,existsSync as bh}from"fs";import{join as kh}from"path";function na(){if(!bh(Os))return{};try{return JSON.parse(wh(Os,"utf-8"))}catch{return{}}}function Sh(n){Sn(),vh(Os,JSON.stringify(n,null,2),{mode:384})}function ra(){let n=na();return new Map(Object.entries(n))}function sa(n,e){let t=na(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Sh(t))}var Os,ia=O(()=>{"use strict";Je();Os=kh(ge,"cursors.json")});async function te(n,e={}){let t=await fetch(n,{...e,headers:{"Content-Type":"application/json",...e.headers}});if(!t.ok){let r=await t.text().catch(()=>""),s="UNKNOWN";try{s=JSON.parse(r)?.error?.code??s}catch{}throw new En(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function pe(n){return{Authorization:`Bearer ${n}`}}async function oa(n,e){return te(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:pe(e)})}async function aa(n,e,t){return te(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:pe(t),body:JSON.stringify({})})}async function ca(n,e,t){await te(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:pe(t),body:JSON.stringify({})})}async function la(n,e,t=!1,r){await te(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:pe(e),body:JSON.stringify(t?{going_offline:!0}:r?{usage:r}:{})})}async function da(n,e,t,r){await te(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:pe(r),body:JSON.stringify({status:t})})}async function ua(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return te(s,{headers:pe(r)})}async function fa(n,e,t){return te(`${n}/api/v1/actions/${e}`,{headers:pe(t)})}async function ha(n,e,t){return te(`${n}/api/v1/approvals/${e}`,{headers:pe(t)})}async function ga(n,e,t,r){let s=r?{approval_id:r}:{};return te(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:pe(t),body:JSON.stringify(s)})}async function pa(n,e,t){await te(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:pe(t),body:JSON.stringify({})})}async function ma(n,e,t,r,s,i){let o=new URLSearchParams;r!==void 0&&o.set("after_seq",r),s!==void 0&&o.set("limit",String(s));let a=o.toString()?`?${o.toString()}`:"",c=`${n}/api/v1/workrooms/${e}/channels/${t}/messages${a}`,d=await te(c,{headers:pe(i)});return{messages:d.messages,hasMore:d.has_more}}async function xn(n,e,t,r,s){let i={content:r.content,client_idempotency_key:r.clientIdempotencyKey};return r.agentId!==void 0&&(i.agent_id=r.agentId),te(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:pe(s),body:JSON.stringify(i)})}async function ya(n,e,t){return(await te(`${n}/api/v1/workrooms/${e}/members`,{headers:pe(t)})).members??[]}async function _a(n,e,t){return te(`${n}/api/v1/workrooms/${e}/roster`,{headers:pe(t)})}async function wa(n,e,t){return(await te(`${n}/api/v1/workrooms/${e}/channels`,{headers:pe(t)})).channels??[]}async function va(n,e,t){return(await te(`${n}/internal/agent-api/channels`,{headers:{...pe(e),"X-Mio-Agent-Id":t}})).channels??[]}async function ba(n,e,t,r){return(await te(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...pe(e),"X-Mio-Agent-Id":t}})).tasks??[]}function Fe(n,e){return{...pe(n),"X-Mio-Agent-Id":e}}async function ka(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Sa(n,e,t){return(await te(`${n}/internal/agent-api/reminders/list`,{headers:Fe(e,t)})).reminders??[]}async function Ea(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function xa(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Ta(n,e,t,r){return(await te(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Ca(n,e,t){return(await te(`${n}/internal/agent-api/reminders/log`,{headers:Fe(e,t)})).events??[]}async function Ra(n,e,t,r){await te(`${n}/internal/agent-api/typing`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Aa(n,e,t,r){await te(`${n}/internal/agent-api/status`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Oa(n,e,t,r){await te(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})}async function Pa(n,e,t,r,s,i){let o=new URLSearchParams;s!==void 0&&o.set("limit",String(s)),i!==void 0&&o.set("after_seq",i);let a=o.toString()?`?${o.toString()}`:"";return(await te(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${a}`,{headers:Fe(e,t)})).messages??[]}async function Ia(n,e,t,r){return(await te(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:Fe(e,t)})).message}async function Na(n,e,t,r){return te(`${n}/internal/agent-api/attachments/${r}`,{headers:Fe(e,t)})}var En,dr=O(()=>{"use strict";En=class extends Error{constructor(t,r,s){super(s);this.statusCode=t;this.errorCode=r;this.name="ApiError"}statusCode;errorCode;get isDefinitiveRejection(){return this.statusCode>=400&&this.statusCode<500}}});var $a=X((Qw,La)=>{var zt=Z("fs"),Ma=Z("url"),Eh=Z("child_process").spawn;La.exports=Ps;Ps.XMLHttpRequest=Ps;function Ps(n){"use strict";n=n||{};var e=this,t=Z("http"),r=Z("https"),s,i,o={},a=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},c),l=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],u=["TRACE","TRACK","CONNECT"],m=!1,f=!1,p=!1,g={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var y=function(_){return a||_&&l.indexOf(_.toLowerCase())===-1},S=function(_){return _&&u.indexOf(_)===-1};this.open=function(_,b,P,x,N){if(this.abort(),f=!1,p=!1,!S(_))throw new Error("SecurityError: Request method not allowed");o={method:_,url:b.toString(),async:typeof P!="boolean"?!0:P,user:x||null,password:N||null},v(this.OPENED)},this.setDisableHeaderCheck=function(_){a=_},this.setRequestHeader=function(_,b){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!y(_))return console.warn('Refused to set unsafe header "'+_+'"'),!1;if(m)throw new Error("INVALID_STATE_ERR: send flag is true");return d[_]=b,!0},this.getResponseHeader=function(_){return typeof _=="string"&&this.readyState>this.OPENED&&i.headers[_.toLowerCase()]&&!f?i.headers[_.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||f)return"";var _="";for(var b in i.headers)b!=="set-cookie"&&b!=="set-cookie2"&&(_+=b+": "+i.headers[b]+`\r
|
|
200
|
+
`);return _.substr(0,_.length-2)},this.getRequestHeader=function(_){return typeof _=="string"&&d[_]?d[_]:""},this.send=function(_){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(m)throw new Error("INVALID_STATE_ERR: send has already been called");var b=!1,P=!1,x=Ma.parse(o.url),N;switch(x.protocol){case"https:":b=!0;case"http:":N=x.hostname;break;case"file:":P=!0;break;case void 0:case"":N="localhost";break;default:throw new Error("Protocol not supported.")}if(P){if(o.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(o.async)zt.readFile(unescape(x.pathname),function(F,V){F?e.handleError(F,F.errno||-1):(e.status=200,e.responseText=V.toString("utf8"),e.response=V,v(e.DONE))});else try{this.response=zt.readFileSync(unescape(x.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,v(e.DONE)}catch(F){this.handleError(F,F.errno||-1)}return}var G=x.port||(b?443:80),J=x.pathname+(x.search?x.search:"");if(d.Host=N,b&&G===443||G===80||(d.Host+=":"+x.port),o.user){typeof o.password>"u"&&(o.password="");var W=new Buffer(o.user+":"+o.password);d.Authorization="Basic "+W.toString("base64")}if(o.method==="GET"||o.method==="HEAD")_=null;else if(_){d["Content-Length"]=Buffer.isBuffer(_)?_.length:Buffer.byteLength(_);var Q=Object.keys(d);Q.some(function(F){return F.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(d["Content-Length"]=0);var ne=n.agent||!1,H={host:N,port:G,path:J,method:o.method,headers:d,agent:ne};if(b&&(H.pfx=n.pfx,H.key=n.key,H.passphrase=n.passphrase,H.cert=n.cert,H.ca=n.ca,H.ciphers=n.ciphers,H.rejectUnauthorized=n.rejectUnauthorized!==!1),f=!1,o.async){var ie=b?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var M=function(F){if(i=F,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var V=Ma.parse(o.url);N=V.hostname;var oe={hostname:V.hostname,port:V.port,path:V.path,method:i.statusCode===303?"GET":o.method,headers:d};b&&(oe.pfx=n.pfx,oe.key=n.key,oe.passphrase=n.passphrase,oe.cert=n.cert,oe.ca=n.ca,oe.ciphers=n.ciphers,oe.rejectUnauthorized=n.rejectUnauthorized!==!1),s=ie(oe,M).on("error",C),s.end();return}v(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(fe){if(fe){var I=Buffer.from(fe);e.response=Buffer.concat([e.response,I])}m&&v(e.LOADING)}),i.on("end",function(){m&&(m=!1,v(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(fe){e.handleError(fe)})},C=function(F){if(s.reusedSocket&&F.code==="ECONNRESET")return ie(H,M).on("error",C);e.handleError(F)};s=ie(H,M).on("error",C),n.autoUnref&&s.on("socket",F=>{F.unref()}),_&&s.write(_),s.end(),e.dispatchEvent("loadstart")}else{var w=".node-xmlhttprequest-content-"+process.pid,R=".node-xmlhttprequest-sync-"+process.pid;zt.writeFileSync(R,"","utf8");for(var A="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(b?"s":"")+".request;var options = "+JSON.stringify(H)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+w+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+R+"');});response.on('error', function(error) {fs.writeFileSync('"+w+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});}).on('error', function(error) {fs.writeFileSync('"+w+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});"+(_?"req.write('"+JSON.stringify(_).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",T=Eh(process.argv[0],["-e",A]),D;zt.existsSync(R););if(e.responseText=zt.readFileSync(w,"utf8"),T.stdin.end(),zt.unlinkSync(w),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var E=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(E,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var B=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:B.data.headers},e.responseText=B.data.text,e.response=Buffer.from(B.data.data,"base64"),v(e.DONE,!0)}}},this.handleError=function(_,b){this.status=b||0,this.statusText=_,this.responseText=_.stack,f=!0,v(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),f=p=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||m)&&this.readyState!==this.DONE&&(m=!1,v(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(_,b){_ in g||(g[_]=[]),g[_].push(b)},this.removeEventListener=function(_,b){_ in g&&(g[_]=g[_].filter(function(P){return P!==b}))},this.dispatchEvent=function(_){if(typeof e["on"+_]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+_]()},0):e["on"+_]()),_ in g)for(let b=0,P=g[_].length;b<P;b++)this.readyState===this.DONE?setTimeout(function(){g[_][b].call(e)},0):g[_][b].call(e)};var v=function(_){if(!(e.readyState===_||e.readyState===e.UNSENT&&p)&&(e.readyState=_,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let b;p?b="abort":f?b="error":b="load",e.dispatchEvent(b),e.dispatchEvent("loadend")}}}});var Ye,Tn,Cn,ur=O(()=>{Ye=Object.create(null);Ye.open="0";Ye.close="1";Ye.ping="2";Ye.pong="3";Ye.message="4";Ye.upgrade="5";Ye.noop="6";Tn=Object.create(null);Object.keys(Ye).forEach(n=>{Tn[Ye[n]]=n});Cn={type:"error",data:"parser error"}});function Ba(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(Da(n.data,!1));Rn(n,!0,t=>{Is||(Is=new TextEncoder),e(Is.encode(t))})}var Rn,Da,Is,Fa=O(()=>{ur();Rn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+Da(e,!0).toString("base64")):r(Ye[n]+(e||"")),Da=(n,e)=>Buffer.isBuffer(n)||n instanceof Uint8Array&&!e?n:n instanceof ArrayBuffer?Buffer.from(n):Buffer.from(n.buffer,n.byteOffset,n.byteLength)});var An,Ua,Ha=O(()=>{ur();An=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ua(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:Ua(r,e)}}return Tn[t]?n.length>1?{type:Tn[t],data:n.substring(1)}:{type:Tn[t]}:Cn},Ua=(n,e)=>e==="arraybuffer"?n instanceof ArrayBuffer?n:Buffer.isBuffer(n)?n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength):n.buffer:Buffer.isBuffer(n)?n:Buffer.from(n)});function ja(){return new TransformStream({transform(n,e){Ba(n,t=>{let r=t.length,s;if(r<126)s=new Uint8Array(1),new DataView(s.buffer).setUint8(0,r);else if(r<65536){s=new Uint8Array(3);let i=new DataView(s.buffer);i.setUint8(0,126),i.setUint16(1,r)}else{s=new Uint8Array(9);let i=new DataView(s.buffer);i.setUint8(0,127),i.setBigUint64(1,BigInt(r))}n.data&&typeof n.data!="string"&&(s[0]|=128),e.enqueue(s),e.enqueue(t)})}})}function fr(n){return n.reduce((e,t)=>e+t.length,0)}function hr(n,e){if(n[0].length===e)return n.shift();let t=new Uint8Array(e),r=0;for(let s=0;s<e;s++)t[s]=n[0][r++],r===n[0].length&&(n.shift(),r=0);return n.length&&r<n[0].length&&(n[0]=n[0].slice(r)),t}function Ja(n,e){Ns||(Ns=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(fr(t)<1)break;let c=hr(t,1);i=(c[0]&128)===128,s=c[0]&127,s<126?r=3:s===126?r=1:r=2}else if(r===1){if(fr(t)<2)break;let c=hr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(fr(t)<8)break;let c=hr(t,8),d=new DataView(c.buffer,c.byteOffset,c.length),l=d.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(Cn);break}s=l*Math.pow(2,32)+d.getUint32(4),r=3}else{if(fr(t)<s)break;let c=hr(t,s);a.enqueue(An(i?c:Ns.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(Cn);break}}}})}var qa,Ga,Wa,Ns,Ms,Kt=O(()=>{Fa();Ha();ur();qa="",Ga=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Rn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(qa))})})},Wa=(n,e)=>{let t=n.split(qa),r=[];for(let s=0;s<t.length;s++){let i=An(t[s],e);if(r.push(i),i.type==="error")break}return r};Ms=4});var Mt=X(Ya=>{Ya.Emitter=Se;function Se(n){if(n)return xh(n)}function xh(n){for(var e in Se.prototype)n[e]=Se.prototype[e];return n}Se.prototype.on=Se.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Se.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Se.prototype.off=Se.prototype.removeListener=Se.prototype.removeAllListeners=Se.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var r,s=0;s<t.length;s++)if(r=t[s],r===e||r.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+n],this};Se.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(t){t=t.slice(0);for(var r=0,s=t.length;r<s;++r)t[r].apply(this,e)}return this};Se.prototype.emitReserved=Se.prototype.emit;Se.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Se.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function za(){return new Ls}function Th(n){let e=n.split("; "),t=e[0].indexOf("=");if(t===-1)return;let r=e[0].substring(0,t).trim();if(!r.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:r,value:s};for(let o=1;o<e.length;o++){let a=e[o].split("=");if(a.length!==2)continue;let c=a[0].trim(),d=a[1].trim();switch(c){case"Expires":i.expires=new Date(d);break;case"Max-Age":let l=new Date;l.setUTCSeconds(l.getUTCSeconds()+parseInt(d,10)),i.expires=l;break;default:}}return i}var ct,Ee,Va,Ls,Lt=O(()=>{ct=process.nextTick,Ee=global,Va="nodebuffer";Ls=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=Th(t);r&&this._cookies.set(r.name,r)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,r)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(r)}),this._cookies.entries()}addCookies(e){let t=[];for(let[r,s]of this.cookies)t.push(`${r}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,r]of this.cookies)e.append("cookie",`${t}=${r.value}`)}}});function gr(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function lt(n,e){e.useNativeTimers?(n.setTimeoutFn=Ch.bind(Ee),n.clearTimeoutFn=Rh.bind(Ee)):(n.setTimeoutFn=Ee.setTimeout.bind(Ee),n.clearTimeoutFn=Ee.clearTimeout.bind(Ee))}function Ka(n){return typeof n=="string"?Oh(n):Math.ceil((n.byteLength||n.size)*Ah)}function Oh(n){let e=0,t=0;for(let r=0,s=n.length;r<s;r++)e=n.charCodeAt(r),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(r++,t+=4);return t}function pr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Ch,Rh,Ah,$t=O(()=>{Lt();Ch=Ee.setTimeout,Rh=Ee.clearTimeout;Ah=1.33});function Xa(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Qa(n){let e={},t=n.split("&");for(let r=0,s=t.length;r<s;r++){let i=t[r].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}var $s=O(()=>{});var ec=X((hv,Za)=>{var Xt=1e3,Qt=Xt*60,Zt=Qt*60,Dt=Zt*24,Ph=Dt*7,Ih=Dt*365.25;Za.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return Nh(n);if(t==="number"&&isFinite(n))return e.long?Lh(n):Mh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function Nh(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Ih;case"weeks":case"week":case"w":return t*Ph;case"days":case"day":case"d":return t*Dt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Zt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Qt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Xt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Mh(n){var e=Math.abs(n);return e>=Dt?Math.round(n/Dt)+"d":e>=Zt?Math.round(n/Zt)+"h":e>=Qt?Math.round(n/Qt)+"m":e>=Xt?Math.round(n/Xt)+"s":n+"ms"}function Lh(n){var e=Math.abs(n);return e>=Dt?mr(n,e,Dt,"day"):e>=Zt?mr(n,e,Zt,"hour"):e>=Qt?mr(n,e,Qt,"minute"):e>=Xt?mr(n,e,Xt,"second"):n+" ms"}function mr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Ds=X((gv,tc)=>{function $h(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=ec(),t.destroy=d,Object.keys(n).forEach(l=>{t[l]=n[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let u=0;for(let m=0;m<l.length;m++)u=(u<<5)-u+l.charCodeAt(m),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,m=null,f,p;function g(...y){if(!g.enabled)return;let S=g,v=Number(new Date),_=v-(u||v);S.diff=_,S.prev=u,S.curr=v,u=v,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let b=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(x,N)=>{if(x==="%%")return"%";b++;let G=t.formatters[N];if(typeof G=="function"){let J=y[b];x=G.call(S,J),y.splice(b,1),b--}return x}),t.formatArgs.call(S,y),(S.log||t.log).apply(S,y)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=r,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(l)),p),set:y=>{m=y}}),typeof t.init=="function"&&t.init(g),g}function r(l,u){let m=t(this.namespace+(typeof u>"u"?":":u)+l);return m.log=this.log,m}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let u=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of u)m[0]==="-"?t.skips.push(m.slice(1)):t.names.push(m)}function i(l,u){let m=0,f=0,p=-1,g=0;for(;m<l.length;)if(f<u.length&&(u[f]===l[m]||u[f]==="*"))u[f]==="*"?(p=f,g=m,f++):(m++,f++);else if(p!==-1)f=p+1,g++,m=g;else return!1;for(;f<u.length&&u[f]==="*";)f++;return f===u.length}function o(){let l=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),l}function a(l){for(let u of t.skips)if(i(l,u))return!1;for(let u of t.names)if(i(l,u))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}tc.exports=$h});var nc=X((Ae,yr)=>{Ae.formatArgs=Bh;Ae.save=Fh;Ae.load=Uh;Ae.useColors=Dh;Ae.storage=Hh();Ae.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Ae.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Dh(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Bh(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+yr.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}Ae.log=console.debug||console.log||(()=>{});function Fh(n){try{n?Ae.storage.setItem("debug",n):Ae.storage.removeItem("debug")}catch{}}function Uh(){let n;try{n=Ae.storage.getItem("debug")||Ae.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Hh(){try{return localStorage}catch{}}yr.exports=Ds()(Ae);var{formatters:qh}=yr.exports;qh.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var sc=X((me,wr)=>{var Gh=Z("tty"),_r=Z("util");me.init=Kh;me.log=Yh;me.formatArgs=jh;me.save=Vh;me.load=zh;me.useColors=Wh;me.destroy=_r.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");me.colors=[6,2,3,4,5,1];try{let n=Z("supports-color");n&&(n.stderr||n).level>=2&&(me.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}me.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function Wh(){return"colors"in me.inspectOpts?!!me.inspectOpts.colors:Gh.isatty(process.stderr.fd)}function jh(n){let{namespace:e,useColors:t}=this;if(t){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${s};1m${e} \x1B[0m`;n[0]=i+n[0].split(`
|
|
201
201
|
`).join(`
|
|
202
202
|
`+i),n.push(s+"m+"+wr.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=Jh()+e+" "+n[0]}function Jh(){return me.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Yh(...n){return process.stderr.write(_r.formatWithOptions(me.inspectOpts,...n)+`
|
|
203
203
|
`)}function Vh(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function zh(){return process.env.DEBUG}function Kh(n){n.inspectOpts={};let e=Object.keys(me.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=me.inspectOpts[e[t]]}wr.exports=Ds()(me);var{formatters:rc}=wr.exports;rc.o=function(n){return this.inspectOpts.colors=this.useColors,_r.inspect(n,this.inspectOpts).split(`
|
|
204
|
-
`).map(e=>e.trim()).join(" ")};rc.O=function(n){return this.inspectOpts.colors=this.useColors,_r.inspect(n,this.inspectOpts)}});var Ue=X((pv,Bs)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Bs.exports=nc():Bs.exports=sc()});var ic,oc,Xh,vr,dt,On=O(()=>{Kt();ic=re(Mt(),1);$t();$s();oc=re(Ue(),1),Xh=(0,oc.default)("engine.io-client:transport"),vr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},dt=class extends ic.Emitter{constructor(e){super(),this.writable=!1,lt(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new vr(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Xh("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=An(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Xa(e);return t.length?"?"+t:""}}});var ac,Ve,Pn,Fs=O(()=>{On();$t();Kt();ac=re(Ue(),1),Ve=(0,ac.default)("engine.io-client:polling"),Pn=class extends dt{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Ve("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(Ve("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){Ve("pre-pause polling complete"),--r||t()})),this.writable||(Ve("we are currently writing - waiting to pause"),r++,this.once("drain",function(){Ve("pre-pause writing complete"),--r||t()}))}else t()}_poll(){Ve("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ve("polling got data %s",e);let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};Wa(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ve('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Ve("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ve("transport open - closing"),e()):(Ve("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,Ga(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=pr()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var cc,lc,dc=O(()=>{cc=!1;try{cc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}lc=cc});function Qh(){}function uc(){for(let n in ut.requests)ut.requests.hasOwnProperty(n)&&ut.requests[n].abort()}function Zh(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||lc))return new XMLHttpRequest}catch{}if(!e)try{return new Ee[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var fc,hc,Us,br,ut,Av,Hs=O(()=>{Fs();fc=re(Mt(),1);$t();Lt();dc();hc=re(Ue(),1),Us=(0,hc.default)("engine.io-client:polling");br=class extends Pn{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){Us("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},ut=class n extends fc.Emitter{constructor(e,t,r){super(),this.createRequest=e,lt(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var e;let t=gr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{Us("xhr open %s: %s",this._method,this._uri),r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&r.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var s;r.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},Us("xhr data %s",this._data),r.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=n.requestsCount++,n.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Qh,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete n.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ut.requestsCount=0;ut.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",uc);else if(typeof addEventListener=="function"){let n="onpagehide"in Ee?"pagehide":"unload";addEventListener(n,uc,!1)}}Av=(function(){let n=Zh({xdomain:!1});return n&&n.responseType!==null})()});var qs,eg,en,Gs=O(()=>{qs=re($a(),1);Hs();eg=qs.default||qs,en=class extends br{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new ut(r=>new eg(r),this.uri(),e)}}});var ft=X((Nv,mc)=>{"use strict";var gc=["nodebuffer","arraybuffer","fragments"],pc=typeof Blob<"u";pc&&gc.push("blob");mc.exports={BINARY_TYPES:gc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:pc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var In=X((Mv,kr)=>{"use strict";var{EMPTY_BUFFER:tg}=ft(),Ws=Buffer[Symbol.species];function ng(n,e){if(n.length===0)return tg;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new Ws(t.buffer,t.byteOffset,r):t}function yc(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function _c(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function rg(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function js(n){if(js.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Ws(n):ArrayBuffer.isView(n)?e=new Ws(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),js.readOnly=!1),e}kr.exports={concat:ng,mask:yc,toArrayBuffer:rg,toBuffer:js,unmask:_c};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=Z("bufferutil");kr.exports.mask=function(e,t,r,s,i){i<48?yc(e,t,r,s,i):n.mask(e,t,r,s,i)},kr.exports.unmask=function(e,t){e.length<32?_c(e,t):n.unmask(e,t)}}catch{}});var bc=X((Lv,vc)=>{"use strict";var wc=Symbol("kDone"),Js=Symbol("kRun"),Ys=class{constructor(e){this[wc]=()=>{this.pending--,this[Js]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Js]()}[Js](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[wc])}}};vc.exports=Ys});var rn=X(($v,xc)=>{"use strict";var Nn=Z("zlib"),kc=In(),sg=bc(),{kStatusCode:Sc}=ft(),ig=Buffer[Symbol.species],og=Buffer.from([0,0,255,255]),Er=Symbol("permessage-deflate"),ht=Symbol("total-length"),tn=Symbol("callback"),xt=Symbol("buffers"),nn=Symbol("error"),Sr,Vs=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,!Sr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Sr=new sg(t)}}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[tn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){Sr.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Sr.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Nn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Er]=this,this._inflate[ht]=0,this._inflate[xt]=[],this._inflate.on("error",cg),this._inflate.on("data",Ec)}this._inflate[tn]=r,this._inflate.write(e),t&&this._inflate.write(og),this._inflate.flush(()=>{let i=this._inflate[nn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=kc.concat(this._inflate[xt],this._inflate[ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ht]=0,this._inflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Nn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ht]=0,this._deflate[xt]=[],this._deflate.on("data",ag)}this._deflate[tn]=r,this._deflate.write(e),this._deflate.flush(Nn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=kc.concat(this._deflate[xt],this._deflate[ht]);t&&(i=new ig(i.buffer,i.byteOffset,i.length-4)),this._deflate[tn]=null,this._deflate[ht]=0,this._deflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};xc.exports=Vs;function ag(n){this[xt].push(n),this[ht]+=n.length}function Ec(n){if(this[ht]+=n.length,this[Er]._maxPayload<1||this[ht]<=this[Er]._maxPayload){this[xt].push(n);return}this[nn]=new RangeError("Max payload size exceeded"),this[nn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[nn][Sc]=1009,this.removeListener("data",Ec),this.reset()}function cg(n){if(this[Er]._inflate=null,this[nn]){this[tn](this[nn]);return}n[Sc]=1007,this[tn](n)}});var sn=X((Dv,xr)=>{"use strict";var{isUtf8:Tc}=Z("buffer"),{hasBlob:lg}=ft(),dg=[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 ug(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function zs(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function fg(n){return lg&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}xr.exports={isBlob:fg,isValidStatusCode:ug,isValidUTF8:zs,tokenChars:dg};if(Tc)xr.exports.isValidUTF8=function(n){return n.length<24?zs(n):Tc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=Z("utf-8-validate");xr.exports.isValidUTF8=function(e){return e.length<32?zs(e):n(e)}}catch{}});var ei=X((Bv,Nc)=>{"use strict";var{Writable:hg}=Z("stream"),Cc=rn(),{BINARY_TYPES:gg,EMPTY_BUFFER:Rc,kStatusCode:pg,kWebSocket:mg}=ft(),{concat:Ks,toArrayBuffer:yg,unmask:_g}=In(),{isValidStatusCode:wg,isValidUTF8:Ac}=sn(),Tr=Buffer[Symbol.species],He=0,Oc=1,Pc=2,Ic=3,Xs=4,Qs=5,Cr=6,Zs=class extends hg{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||gg[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[mg]=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=He}_write(e,t,r){if(this._opcode===8&&this._state==He)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 Tr(r.buffer,r.byteOffset+e,r.length-e),new Tr(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Tr(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case He:this.getInfo(e);break;case Oc:this.getPayloadLength16(e);break;case Pc:this.getPayloadLength64(e);break;case Ic:this.getMask();break;case Xs:this.getData(e);break;case Qs:case Cr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(t[0]&64)===64;if(r&&!this._extensions[Cc.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Oc:this._payloadLength===127?this._state=Pc: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 t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+t.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 t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Ic:this._state=Xs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Xs}getData(e){let t=Rc;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&_g(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Qs,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Cc.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===He&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=He;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ks(r,t):this._binaryType==="arraybuffer"?s=yg(Ks(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=He):(this._state=Cr,setImmediate(()=>{this.emit("message",s,!0),this._state=He,this.startLoop(e)}))}else{let s=Ks(r,t);if(!this._skipUTF8Validation&&!Ac(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Qs||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=He):(this._state=Cr,setImmediate(()=>{this.emit("message",s,!1),this._state=He,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Rc),this.end();else{let r=e.readUInt16BE(0);if(!wg(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Tr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ac(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=He;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=He):(this._state=Cr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=He,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[pg]=s,o}};Nc.exports=Zs});var ri=X((Uv,$c)=>{"use strict";var{Duplex:Fv}=Z("stream"),{randomFillSync:vg}=Z("crypto"),{types:{isUint8Array:bg}}=Z("util"),Mc=rn(),{EMPTY_BUFFER:kg,kWebSocket:Sg,NOOP:Eg}=ft(),{isBlob:on,isValidStatusCode:xg}=sn(),{mask:Lc,toBuffer:Bt}=In(),qe=Symbol("kByteLength"),Tg=Buffer.alloc(4),Rr=8*1024,Ft,an=Rr,ze=0,Cg=1,Rg=2,ti=class n{constructor(e,t,r){this._extensions=t||{},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=ze,this.onerror=Eg,this[Sg]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Tg,t.generateMask?t.generateMask(r):(an===Rr&&(Ft===void 0&&(Ft=Buffer.alloc(Rr)),vg(Ft,0,Rr),an=0),r[0]=Ft[an++],r[1]=Ft[an++],r[2]=Ft[an++],r[3]=Ft[an++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[qe]!==void 0?a=t[qe]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let d=Buffer.allocUnsafe(s?a+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(a,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),t.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(Lc(e,r,d,i,a),[d]):(Lc(e,r,e,0,a),[d,e])):[d,e]}close(e,t,r,s){let i;if(e===void 0)i=kg;else{if(typeof e!="number"||!xg(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(bg(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[qe]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ze?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):on(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[qe]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};on(e)?this._state!==ze?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ze?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):on(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[qe]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};on(e)?this._state!==ze?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ze?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Mc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):on(e)?(a=e.size,c=!1):(e=Bt(e),a=e.length,c=Bt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[qe]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};on(e)?this._state!==ze?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==ze?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[qe],this._state=Rg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ni,this,a,s);return}this._bufferedBytes-=r[qe];let o=Bt(i);t?this.dispatch(o,t,r,s):(this._state=ze,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ag,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Mc.extensionName];this._bufferedBytes+=r[qe],this._state=Cg,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ni(this,c,s);return}this._bufferedBytes-=r[qe],this._state=ze,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ze&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][qe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][qe],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};$c.exports=ti;function ni(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Ag(n,e,t){ni(n,e,t),n.onerror(e)}});var jc=X((Hv,Wc)=>{"use strict";var{kForOnEventAttribute:Mn,kListener:si}=ft(),Dc=Symbol("kCode"),Bc=Symbol("kData"),Fc=Symbol("kError"),Uc=Symbol("kMessage"),Hc=Symbol("kReason"),cn=Symbol("kTarget"),qc=Symbol("kType"),Gc=Symbol("kWasClean"),gt=class{constructor(e){this[cn]=null,this[qc]=e}get target(){return this[cn]}get type(){return this[qc]}};Object.defineProperty(gt.prototype,"target",{enumerable:!0});Object.defineProperty(gt.prototype,"type",{enumerable:!0});var Ut=class extends gt{constructor(e,t={}){super(e),this[Dc]=t.code===void 0?0:t.code,this[Hc]=t.reason===void 0?"":t.reason,this[Gc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Dc]}get reason(){return this[Hc]}get wasClean(){return this[Gc]}};Object.defineProperty(Ut.prototype,"code",{enumerable:!0});Object.defineProperty(Ut.prototype,"reason",{enumerable:!0});Object.defineProperty(Ut.prototype,"wasClean",{enumerable:!0});var ln=class extends gt{constructor(e,t={}){super(e),this[Fc]=t.error===void 0?null:t.error,this[Uc]=t.message===void 0?"":t.message}get error(){return this[Fc]}get message(){return this[Uc]}};Object.defineProperty(ln.prototype,"error",{enumerable:!0});Object.defineProperty(ln.prototype,"message",{enumerable:!0});var Ln=class extends gt{constructor(e,t={}){super(e),this[Bc]=t.data===void 0?null:t.data}get data(){return this[Bc]}};Object.defineProperty(Ln.prototype,"data",{enumerable:!0});var Og={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Mn]&&s[si]===e&&!s[Mn])return;let r;if(n==="message")r=function(i,o){let a=new Ln("message",{data:o?i:i.toString()});a[cn]=this,Ar(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ut("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[cn]=this,Ar(e,this,a)};else if(n==="error")r=function(i){let o=new ln("error",{error:i,message:i.message});o[cn]=this,Ar(e,this,o)};else if(n==="open")r=function(){let i=new gt("open");i[cn]=this,Ar(e,this,i)};else return;r[Mn]=!!t[Mn],r[si]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[si]===e&&!t[Mn]){this.removeListener(n,t);break}}};Wc.exports={CloseEvent:Ut,ErrorEvent:ln,Event:gt,EventTarget:Og,MessageEvent:Ln};function Ar(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Or=X((qv,Jc)=>{"use strict";var{tokenChars:$n}=sn();function tt(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Pg(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,d=-1,l=-1,u=0;for(;u<n.length;u++)if(d=n.charCodeAt(u),o===void 0)if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(u!==0&&(d===32||d===9))l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let f=n.slice(c,l);d===44?(tt(e,f,t),t=Object.create(null)):o=f,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(d===32||d===9)l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u),tt(t,n.slice(c,l),!0),d===44&&(tt(e,o,t),t=Object.create(null),o=void 0),c=l=-1}else if(d===61&&c!==-1&&l===-1)a=n.slice(c,u),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if($n[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if($n[d]===1)c===-1&&(c=u);else if(d===34&&c!==-1)i=!1,l=u;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(d===34&&n.charCodeAt(u-1)===61)i=!0;else if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(c!==-1&&(d===32||d===9))l===-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let f=n.slice(c,l);r&&(f=f.replace(/\\/g,""),r=!1),tt(t,a,f),d===44&&(tt(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=u);let m=n.slice(c,l);return o===void 0?tt(e,m,t):(a===void 0?tt(t,m,!0):r?tt(t,a,m.replace(/\\/g,"")):tt(t,a,m),tt(e,o,t)),e}function Ig(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Jc.exports={format:Ig,parse:Pg}});var Mr=X((jv,sl)=>{"use strict";var Ng=Z("events"),Mg=Z("https"),Lg=Z("http"),zc=Z("net"),$g=Z("tls"),{randomBytes:Dg,createHash:Bg}=Z("crypto"),{Duplex:Gv,Readable:Wv}=Z("stream"),{URL:ii}=Z("url"),Tt=rn(),Fg=ei(),Ug=ri(),{isBlob:Hg}=sn(),{BINARY_TYPES:Yc,CLOSE_TIMEOUT:qg,EMPTY_BUFFER:Pr,GUID:Gg,kForOnEventAttribute:oi,kListener:Wg,kStatusCode:jg,kWebSocket:ye,NOOP:Kc}=ft(),{EventTarget:{addEventListener:Jg,removeEventListener:Yg}}=jc(),{format:Vg,parse:zg}=Or(),{toBuffer:Kg}=In(),Xc=Symbol("kAborted"),ai=[8,13],pt=["CONNECTING","OPEN","CLOSING","CLOSED"],Xg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,oe=class n extends Ng{constructor(e,t,r){super(),this._binaryType=Yc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Pr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),Qc(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yc.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,t,r){let s=new Fg({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Ug(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ye]=this,i[ye]=this,e[ye]=this,s.on("conclude",ep),s.on("drain",tp),s.on("error",np),s.on("message",rp),s.on("ping",sp),s.on("pong",ip),i.onerror=op,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",tl),e.on("data",Nr),e.on("end",nl),e.on("error",rl),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Tt.extensionName]&&this._extensions[Tt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Le(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),el(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ci(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Pr,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ci(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Pr,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ci(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Tt.extensionName]||(s.compress=!1),this._sender.send(e||Pr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Le(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(oe,"CONNECTING",{enumerable:!0,value:pt.indexOf("CONNECTING")});Object.defineProperty(oe.prototype,"CONNECTING",{enumerable:!0,value:pt.indexOf("CONNECTING")});Object.defineProperty(oe,"OPEN",{enumerable:!0,value:pt.indexOf("OPEN")});Object.defineProperty(oe.prototype,"OPEN",{enumerable:!0,value:pt.indexOf("OPEN")});Object.defineProperty(oe,"CLOSING",{enumerable:!0,value:pt.indexOf("CLOSING")});Object.defineProperty(oe.prototype,"CLOSING",{enumerable:!0,value:pt.indexOf("CLOSING")});Object.defineProperty(oe,"CLOSED",{enumerable:!0,value:pt.indexOf("CLOSED")});Object.defineProperty(oe.prototype,"CLOSED",{enumerable:!0,value:pt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(oe.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(oe.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[oi])return e[Wg];return null},set(e){for(let t of this.listeners(n))if(t[oi]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[oi]:!0})}})});oe.prototype.addEventListener=Jg;oe.prototype.removeEventListener=Yg;sl.exports=oe;function Qc(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qg,protocolVersion:ai[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(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!ai.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ai.join(", ")})`);let i;if(e instanceof ii)i=e;else try{i=new ii(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let p=new SyntaxError(c);if(n._redirects===0)throw p;Ir(n,p);return}let d=o?443:80,l=Dg(16).toString("base64"),u=o?Mg.request:Lg.request,m=new Set,f;if(s.createConnection=s.createConnection||(o?Zg:Qg),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(f=new Tt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Vg({[Tt.extensionName]:f.offer()})),t.length){for(let p of t){if(typeof p!="string"||!Xg.test(p)||m.has(p))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(p)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let p=s.path.split(":");s.socketPath=p[0],s.path=p[1]}let g;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let p=r&&r.headers;if(r={...r,headers:{}},p)for(let[y,S]of Object.entries(p))r.headers[y.toLowerCase()]=S}else if(n.listenerCount("redirect")===0){let p=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!p||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,p||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=n._req=u(s),n._redirects&&n.emit("redirect",n.url,g)}else g=n._req=u(s);s.timeout&&g.on("timeout",()=>{Le(n,g,"Opening handshake has timed out")}),g.on("error",p=>{g===null||g[Xc]||(g=n._req=null,Ir(n,p))}),g.on("response",p=>{let y=p.headers.location,S=p.statusCode;if(y&&s.followRedirects&&S>=300&&S<400){if(++n._redirects>s.maxRedirects){Le(n,g,"Maximum redirects exceeded");return}g.abort();let v;try{v=new ii(y,e)}catch{let b=new SyntaxError(`Invalid URL: ${y}`);Ir(n,b);return}Qc(n,v,t,r)}else n.emit("unexpected-response",g,p)||Le(n,g,`Unexpected server response: ${p.statusCode}`)}),g.on("upgrade",(p,y,S)=>{if(n.emit("upgrade",p),n.readyState!==oe.CONNECTING)return;g=n._req=null;let v=p.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Le(n,y,"Invalid Upgrade header");return}let w=Bg("sha1").update(l+Gg).digest("base64");if(p.headers["sec-websocket-accept"]!==w){Le(n,y,"Invalid Sec-WebSocket-Accept header");return}let b=p.headers["sec-websocket-protocol"],P;if(b!==void 0?m.size?m.has(b)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":m.size&&(P="Server sent no subprotocol"),P){Le(n,y,P);return}b&&(n._protocol=b);let x=p.headers["sec-websocket-extensions"];if(x!==void 0){if(!f){Le(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=zg(x)}catch{Le(n,y,"Invalid Sec-WebSocket-Extensions header");return}let G=Object.keys(N);if(G.length!==1||G[0]!==Tt.extensionName){Le(n,y,"Server indicated an extension that was not requested");return}try{f.accept(N[Tt.extensionName])}catch{Le(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Tt.extensionName]=f}n.setSocket(y,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,n):g.end()}function Ir(n,e){n._readyState=oe.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Qg(n){return n.path=n.socketPath,zc.connect(n)}function Zg(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=zc.isIP(n.host)?"":n.host),$g.connect(n)}function Le(n,e,t){n._readyState=oe.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Le),e.setHeader?(e[Xc]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ir,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function ci(n,e,t){if(e){let r=Hg(e)?e.size:Kg(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${pt[n.readyState]})`);process.nextTick(t,r)}}function ep(n,e){let t=this[ye];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ye]!==void 0&&(t._socket.removeListener("data",Nr),process.nextTick(Zc,t._socket),n===1005?t.close():t.close(n,e))}function tp(){let n=this[ye];n.isPaused||n._socket.resume()}function np(n){let e=this[ye];e._socket[ye]!==void 0&&(e._socket.removeListener("data",Nr),process.nextTick(Zc,e._socket),e.close(n[jg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function Vc(){this[ye].emitClose()}function rp(n,e){this[ye].emit("message",n,e)}function sp(n){let e=this[ye];e._autoPong&&e.pong(n,!this._isServer,Kc),e.emit("ping",n)}function ip(n){this[ye].emit("pong",n)}function Zc(n){n.resume()}function op(n){let e=this[ye];e.readyState!==oe.CLOSED&&(e.readyState===oe.OPEN&&(e._readyState=oe.CLOSING,el(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function el(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function tl(){let n=this[ye];if(this.removeListener("close",tl),this.removeListener("data",Nr),this.removeListener("end",nl),n._readyState=oe.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ye]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Vc),n._receiver.on("finish",Vc))}function Nr(n){this[ye]._receiver.write(n)||this.pause()}function nl(){let n=this[ye];n._readyState=oe.CLOSING,n._receiver.end(),this.end()}function rl(){let n=this[ye];this.removeListener("error",rl),this.on("error",Kc),n&&(n._readyState=oe.CLOSING,this.destroy())}});var cl=X((Yv,al)=>{"use strict";var Jv=Mr(),{Duplex:ap}=Z("stream");function il(n){n.emit("close")}function cp(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ol(n){this.removeListener("error",ol),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function lp(n,e){let t=!0,r=new ap({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(il,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(il,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",cp),r.on("error",ol),r}al.exports=lp});var li=X((Vv,ll)=>{"use strict";var{tokenChars:dp}=sn();function up(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&dp[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}ll.exports={parse:up}});var ml=X((Kv,pl)=>{"use strict";var fp=Z("events"),Lr=Z("http"),{Duplex:zv}=Z("stream"),{createHash:hp}=Z("crypto"),dl=Or(),Ht=rn(),gp=li(),pp=Mr(),{CLOSE_TIMEOUT:mp,GUID:yp,kWebSocket:_p}=ft(),wp=/^[+/0-9A-Za-z]{22}==$/,ul=0,fl=1,gl=2,di=class extends fp{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:mp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:pp,...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=Lr.createServer((r,s)=>{let i=Lr.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=vp(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ul}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===gl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Dn,this);return}if(e&&this.once("close",e),this._state!==fl)if(this._state=fl,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(Dn,this):process.nextTick(Dn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Dn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",hl);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!wp.test(i)){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Bn(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=gp.parse(c)}catch{qt(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&l!==void 0){let m=new Ht({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=dl.parse(l);f[Ht.extensionName]&&(m.accept(f[Ht.extensionName]),u[Ht.extensionName]=m)}catch{qt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,g,p,y)=>{if(!f)return Bn(t,g||401,p,y);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(m))return Bn(t,401)}this.completeUpgrade(u,i,d,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[_p])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ul)return Bn(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hp("sha1").update(t+yp).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;u&&(d.push(`Sec-WebSocket-Protocol: ${u}`),l._protocol=u)}if(e[Ht.extensionName]){let u=e[Ht.extensionName].params,m=dl.format({[Ht.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${m}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
204
|
+
`).map(e=>e.trim()).join(" ")};rc.O=function(n){return this.inspectOpts.colors=this.useColors,_r.inspect(n,this.inspectOpts)}});var Ue=X((pv,Bs)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Bs.exports=nc():Bs.exports=sc()});var ic,oc,Xh,vr,dt,On=O(()=>{Kt();ic=re(Mt(),1);$t();$s();oc=re(Ue(),1),Xh=(0,oc.default)("engine.io-client:transport"),vr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},dt=class extends ic.Emitter{constructor(e){super(),this.writable=!1,lt(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new vr(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):Xh("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=An(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=Xa(e);return t.length?"?"+t:""}}});var ac,Ve,Pn,Fs=O(()=>{On();$t();Kt();ac=re(Ue(),1),Ve=(0,ac.default)("engine.io-client:polling"),Pn=class extends dt{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Ve("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(Ve("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){Ve("pre-pause polling complete"),--r||t()})),this.writable||(Ve("we are currently writing - waiting to pause"),r++,this.once("drain",function(){Ve("pre-pause writing complete"),--r||t()}))}else t()}_poll(){Ve("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ve("polling got data %s",e);let t=r=>{if(this.readyState==="opening"&&r.type==="open"&&this.onOpen(),r.type==="close")return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(r)};Wa(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ve('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Ve("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ve("transport open - closing"),e()):(Ve("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,Ga(e,t=>{this.doWrite(t,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){let e=this.opts.secure?"https":"http",t=this.query||{};return this.opts.timestampRequests!==!1&&(t[this.opts.timestampParam]=pr()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var cc,lc,dc=O(()=>{cc=!1;try{cc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}lc=cc});function Qh(){}function uc(){for(let n in ut.requests)ut.requests.hasOwnProperty(n)&&ut.requests[n].abort()}function Zh(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||lc))return new XMLHttpRequest}catch{}if(!e)try{return new Ee[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var fc,hc,Us,br,ut,Av,Hs=O(()=>{Fs();fc=re(Mt(),1);$t();Lt();dc();hc=re(Ue(),1),Us=(0,hc.default)("engine.io-client:polling");br=class extends Pn{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){Us("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},ut=class n extends fc.Emitter{constructor(e,t,r){super(),this.createRequest=e,lt(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var e;let t=gr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{Us("xhr open %s: %s",this._method,this._uri),r.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){r.setDisableHeaderCheck&&r.setDisableHeaderCheck(!0);for(let s in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(s)&&r.setRequestHeader(s,this._opts.extraHeaders[s])}}catch{}if(this._method==="POST")try{r.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch{}try{r.setRequestHeader("Accept","*/*")}catch{}(e=this._opts.cookieJar)===null||e===void 0||e.addCookies(r),"withCredentials"in r&&(r.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(r.timeout=this._opts.requestTimeout),r.onreadystatechange=()=>{var s;r.readyState===3&&((s=this._opts.cookieJar)===null||s===void 0||s.parseCookies(r.getResponseHeader("set-cookie"))),r.readyState===4&&(r.status===200||r.status===1223?this._onLoad():this.setTimeoutFn(()=>{this._onError(typeof r.status=="number"?r.status:0)},0))},Us("xhr data %s",this._data),r.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=n.requestsCount++,n.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=Qh,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete n.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ut.requestsCount=0;ut.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",uc);else if(typeof addEventListener=="function"){let n="onpagehide"in Ee?"pagehide":"unload";addEventListener(n,uc,!1)}}Av=(function(){let n=Zh({xdomain:!1});return n&&n.responseType!==null})()});var qs,eg,en,Gs=O(()=>{qs=re($a(),1);Hs();eg=qs.default||qs,en=class extends br{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new ut(r=>new eg(r),this.uri(),e)}}});var ft=X((Nv,mc)=>{"use strict";var gc=["nodebuffer","arraybuffer","fragments"],pc=typeof Blob<"u";pc&&gc.push("blob");mc.exports={BINARY_TYPES:gc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:pc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var In=X((Mv,kr)=>{"use strict";var{EMPTY_BUFFER:tg}=ft(),Ws=Buffer[Symbol.species];function ng(n,e){if(n.length===0)return tg;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new Ws(t.buffer,t.byteOffset,r):t}function yc(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function _c(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function rg(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function js(n){if(js.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Ws(n):ArrayBuffer.isView(n)?e=new Ws(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),js.readOnly=!1),e}kr.exports={concat:ng,mask:yc,toArrayBuffer:rg,toBuffer:js,unmask:_c};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=Z("bufferutil");kr.exports.mask=function(e,t,r,s,i){i<48?yc(e,t,r,s,i):n.mask(e,t,r,s,i)},kr.exports.unmask=function(e,t){e.length<32?_c(e,t):n.unmask(e,t)}}catch{}});var bc=X((Lv,vc)=>{"use strict";var wc=Symbol("kDone"),Js=Symbol("kRun"),Ys=class{constructor(e){this[wc]=()=>{this.pending--,this[Js]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Js]()}[Js](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[wc])}}};vc.exports=Ys});var rn=X(($v,xc)=>{"use strict";var Nn=Z("zlib"),kc=In(),sg=bc(),{kStatusCode:Sc}=ft(),ig=Buffer[Symbol.species],og=Buffer.from([0,0,255,255]),Er=Symbol("permessage-deflate"),ht=Symbol("total-length"),tn=Symbol("callback"),xt=Symbol("buffers"),nn=Symbol("error"),Sr,Vs=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,!Sr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Sr=new sg(t)}}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[tn];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,r=e.find(s=>!(t.serverNoContextTakeover===!1&&s.server_no_context_takeover||s.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>s.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!s.client_max_window_bits));if(!r)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(r.server_no_context_takeover=!0),t.clientNoContextTakeover&&(r.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(r.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?r.client_max_window_bits=t.clientMaxWindowBits:(r.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete r.client_max_window_bits,r}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(r=>{let s=t[r];if(s.length>1)throw new Error(`Parameter "${r}" must have only a single value`);if(s=s[0],r==="client_max_window_bits"){if(s!==!0){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else if(r==="server_max_window_bits"){let i=+s;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${r}": ${s}`);s=i}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(s!==!0)throw new TypeError(`Invalid value for parameter "${r}": ${s}`)}else throw new Error(`Unknown parameter "${r}"`);t[r]=s})}),e}decompress(e,t,r){Sr.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Sr.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Nn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Er]=this,this._inflate[ht]=0,this._inflate[xt]=[],this._inflate.on("error",cg),this._inflate.on("data",Ec)}this._inflate[tn]=r,this._inflate.write(e),t&&this._inflate.write(og),this._inflate.flush(()=>{let i=this._inflate[nn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=kc.concat(this._inflate[xt],this._inflate[ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ht]=0,this._inflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Nn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ht]=0,this._deflate[xt]=[],this._deflate.on("data",ag)}this._deflate[tn]=r,this._deflate.write(e),this._deflate.flush(Nn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=kc.concat(this._deflate[xt],this._deflate[ht]);t&&(i=new ig(i.buffer,i.byteOffset,i.length-4)),this._deflate[tn]=null,this._deflate[ht]=0,this._deflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};xc.exports=Vs;function ag(n){this[xt].push(n),this[ht]+=n.length}function Ec(n){if(this[ht]+=n.length,this[Er]._maxPayload<1||this[ht]<=this[Er]._maxPayload){this[xt].push(n);return}this[nn]=new RangeError("Max payload size exceeded"),this[nn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[nn][Sc]=1009,this.removeListener("data",Ec),this.reset()}function cg(n){if(this[Er]._inflate=null,this[nn]){this[tn](this[nn]);return}n[Sc]=1007,this[tn](n)}});var sn=X((Dv,xr)=>{"use strict";var{isUtf8:Tc}=Z("buffer"),{hasBlob:lg}=ft(),dg=[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 ug(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function zs(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function fg(n){return lg&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}xr.exports={isBlob:fg,isValidStatusCode:ug,isValidUTF8:zs,tokenChars:dg};if(Tc)xr.exports.isValidUTF8=function(n){return n.length<24?zs(n):Tc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=Z("utf-8-validate");xr.exports.isValidUTF8=function(e){return e.length<32?zs(e):n(e)}}catch{}});var ei=X((Bv,Nc)=>{"use strict";var{Writable:hg}=Z("stream"),Cc=rn(),{BINARY_TYPES:gg,EMPTY_BUFFER:Rc,kStatusCode:pg,kWebSocket:mg}=ft(),{concat:Ks,toArrayBuffer:yg,unmask:_g}=In(),{isValidStatusCode:wg,isValidUTF8:Ac}=sn(),Tr=Buffer[Symbol.species],He=0,Oc=1,Pc=2,Ic=3,Xs=4,Qs=5,Cr=6,Zs=class extends hg{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||gg[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[mg]=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=He}_write(e,t,r){if(this._opcode===8&&this._state==He)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 Tr(r.buffer,r.byteOffset+e,r.length-e),new Tr(r.buffer,r.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let r=this._buffers[0],s=t.length-e;e>=r.length?t.set(this._buffers.shift(),s):(t.set(new Uint8Array(r.buffer,r.byteOffset,e),s),this._buffers[0]=new Tr(r.buffer,r.byteOffset+e,r.length-e)),e-=r.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case He:this.getInfo(e);break;case Oc:this.getPayloadLength16(e);break;case Pc:this.getPayloadLength64(e);break;case Ic:this.getMask();break;case Xs:this.getData(e);break;case Qs:case Cr:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let s=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(s);return}let r=(t[0]&64)===64;if(r&&!this._extensions[Cc.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=Oc:this._payloadLength===127?this._state=Pc: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 t=this.consume(8),r=t.readUInt32BE(0);if(r>Math.pow(2,21)-1){let s=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(s);return}this._payloadLength=r*Math.pow(2,32)+t.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 t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=Ic:this._state=Xs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Xs}getData(e){let t=Rc;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&_g(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Qs,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Cc.extensionName].decompress(e,this._fin,(s,i)=>{if(s)return t(s);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===He&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=He;return}let t=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let s;this._binaryType==="nodebuffer"?s=Ks(r,t):this._binaryType==="arraybuffer"?s=yg(Ks(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=He):(this._state=Cr,setImmediate(()=>{this.emit("message",s,!0),this._state=He,this.startLoop(e)}))}else{let s=Ks(r,t);if(!this._skipUTF8Validation&&!Ac(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Qs||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=He):(this._state=Cr,setImmediate(()=>{this.emit("message",s,!1),this._state=He,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Rc),this.end();else{let r=e.readUInt16BE(0);if(!wg(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Tr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ac(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=He;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=He):(this._state=Cr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=He,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[pg]=s,o}};Nc.exports=Zs});var ri=X((Uv,$c)=>{"use strict";var{Duplex:Fv}=Z("stream"),{randomFillSync:vg}=Z("crypto"),{types:{isUint8Array:bg}}=Z("util"),Mc=rn(),{EMPTY_BUFFER:kg,kWebSocket:Sg,NOOP:Eg}=ft(),{isBlob:on,isValidStatusCode:xg}=sn(),{mask:Lc,toBuffer:Bt}=In(),qe=Symbol("kByteLength"),Tg=Buffer.alloc(4),Rr=8*1024,Ft,an=Rr,ze=0,Cg=1,Rg=2,ti=class n{constructor(e,t,r){this._extensions=t||{},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=ze,this.onerror=Eg,this[Sg]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Tg,t.generateMask?t.generateMask(r):(an===Rr&&(Ft===void 0&&(Ft=Buffer.alloc(Rr)),vg(Ft,0,Rr),an=0),r[0]=Ft[an++],r[1]=Ft[an++],r[2]=Ft[an++],r[3]=Ft[an++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[qe]!==void 0?a=t[qe]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let d=Buffer.allocUnsafe(s?a+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(a,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),t.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(Lc(e,r,d,i,a),[d]):(Lc(e,r,e,0,a),[d,e])):[d,e]}close(e,t,r,s){let i;if(e===void 0)i=kg;else{if(typeof e!="number"||!xg(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(bg(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[qe]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==ze?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):on(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[qe]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};on(e)?this._state!==ze?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ze?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):on(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[qe]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};on(e)?this._state!==ze?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==ze?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Mc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):on(e)?(a=e.size,c=!1):(e=Bt(e),a=e.length,c=Bt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[qe]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};on(e)?this._state!==ze?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==ze?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[qe],this._state=Rg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ni,this,a,s);return}this._bufferedBytes-=r[qe];let o=Bt(i);t?this.dispatch(o,t,r,s):(this._state=ze,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Ag,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Mc.extensionName];this._bufferedBytes+=r[qe],this._state=Cg,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ni(this,c,s);return}this._bufferedBytes-=r[qe],this._state=ze,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===ze&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][qe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][qe],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};$c.exports=ti;function ni(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function Ag(n,e,t){ni(n,e,t),n.onerror(e)}});var jc=X((Hv,Wc)=>{"use strict";var{kForOnEventAttribute:Mn,kListener:si}=ft(),Dc=Symbol("kCode"),Bc=Symbol("kData"),Fc=Symbol("kError"),Uc=Symbol("kMessage"),Hc=Symbol("kReason"),cn=Symbol("kTarget"),qc=Symbol("kType"),Gc=Symbol("kWasClean"),gt=class{constructor(e){this[cn]=null,this[qc]=e}get target(){return this[cn]}get type(){return this[qc]}};Object.defineProperty(gt.prototype,"target",{enumerable:!0});Object.defineProperty(gt.prototype,"type",{enumerable:!0});var Ut=class extends gt{constructor(e,t={}){super(e),this[Dc]=t.code===void 0?0:t.code,this[Hc]=t.reason===void 0?"":t.reason,this[Gc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Dc]}get reason(){return this[Hc]}get wasClean(){return this[Gc]}};Object.defineProperty(Ut.prototype,"code",{enumerable:!0});Object.defineProperty(Ut.prototype,"reason",{enumerable:!0});Object.defineProperty(Ut.prototype,"wasClean",{enumerable:!0});var ln=class extends gt{constructor(e,t={}){super(e),this[Fc]=t.error===void 0?null:t.error,this[Uc]=t.message===void 0?"":t.message}get error(){return this[Fc]}get message(){return this[Uc]}};Object.defineProperty(ln.prototype,"error",{enumerable:!0});Object.defineProperty(ln.prototype,"message",{enumerable:!0});var Ln=class extends gt{constructor(e,t={}){super(e),this[Bc]=t.data===void 0?null:t.data}get data(){return this[Bc]}};Object.defineProperty(Ln.prototype,"data",{enumerable:!0});var Og={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Mn]&&s[si]===e&&!s[Mn])return;let r;if(n==="message")r=function(i,o){let a=new Ln("message",{data:o?i:i.toString()});a[cn]=this,Ar(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ut("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[cn]=this,Ar(e,this,a)};else if(n==="error")r=function(i){let o=new ln("error",{error:i,message:i.message});o[cn]=this,Ar(e,this,o)};else if(n==="open")r=function(){let i=new gt("open");i[cn]=this,Ar(e,this,i)};else return;r[Mn]=!!t[Mn],r[si]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[si]===e&&!t[Mn]){this.removeListener(n,t);break}}};Wc.exports={CloseEvent:Ut,ErrorEvent:ln,Event:gt,EventTarget:Og,MessageEvent:Ln};function Ar(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Or=X((qv,Jc)=>{"use strict";var{tokenChars:$n}=sn();function tt(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Pg(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,d=-1,l=-1,u=0;for(;u<n.length;u++)if(d=n.charCodeAt(u),o===void 0)if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(u!==0&&(d===32||d===9))l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let f=n.slice(c,l);d===44?(tt(e,f,t),t=Object.create(null)):o=f,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(d===32||d===9)l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u),tt(t,n.slice(c,l),!0),d===44&&(tt(e,o,t),t=Object.create(null),o=void 0),c=l=-1}else if(d===61&&c!==-1&&l===-1)a=n.slice(c,u),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if($n[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if($n[d]===1)c===-1&&(c=u);else if(d===34&&c!==-1)i=!1,l=u;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(d===34&&n.charCodeAt(u-1)===61)i=!0;else if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(c!==-1&&(d===32||d===9))l===-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let f=n.slice(c,l);r&&(f=f.replace(/\\/g,""),r=!1),tt(t,a,f),d===44&&(tt(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=u);let m=n.slice(c,l);return o===void 0?tt(e,m,t):(a===void 0?tt(t,m,!0):r?tt(t,a,m.replace(/\\/g,"")):tt(t,a,m),tt(e,o,t)),e}function Ig(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}Jc.exports={format:Ig,parse:Pg}});var Mr=X((jv,sl)=>{"use strict";var Ng=Z("events"),Mg=Z("https"),Lg=Z("http"),zc=Z("net"),$g=Z("tls"),{randomBytes:Dg,createHash:Bg}=Z("crypto"),{Duplex:Gv,Readable:Wv}=Z("stream"),{URL:ii}=Z("url"),Tt=rn(),Fg=ei(),Ug=ri(),{isBlob:Hg}=sn(),{BINARY_TYPES:Yc,CLOSE_TIMEOUT:qg,EMPTY_BUFFER:Pr,GUID:Gg,kForOnEventAttribute:oi,kListener:Wg,kStatusCode:jg,kWebSocket:ye,NOOP:Kc}=ft(),{EventTarget:{addEventListener:Jg,removeEventListener:Yg}}=jc(),{format:Vg,parse:zg}=Or(),{toBuffer:Kg}=In(),Xc=Symbol("kAborted"),ai=[8,13],pt=["CONNECTING","OPEN","CLOSING","CLOSED"],Xg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ae=class n extends Ng{constructor(e,t,r){super(),this._binaryType=Yc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Pr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),Qc(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Yc.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,t,r){let s=new Fg({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Ug(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ye]=this,i[ye]=this,e[ye]=this,s.on("conclude",ep),s.on("drain",tp),s.on("error",np),s.on("message",rp),s.on("ping",sp),s.on("pong",ip),i.onerror=op,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",tl),e.on("data",Nr),e.on("end",nl),e.on("error",rl),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Tt.extensionName]&&this._extensions[Tt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,r=>{r||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),el(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ci(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Pr,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ci(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Pr,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){ci(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Tt.extensionName]||(s.compress=!1),this._sender.send(e||Pr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){$e(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(ae,"CONNECTING",{enumerable:!0,value:pt.indexOf("CONNECTING")});Object.defineProperty(ae.prototype,"CONNECTING",{enumerable:!0,value:pt.indexOf("CONNECTING")});Object.defineProperty(ae,"OPEN",{enumerable:!0,value:pt.indexOf("OPEN")});Object.defineProperty(ae.prototype,"OPEN",{enumerable:!0,value:pt.indexOf("OPEN")});Object.defineProperty(ae,"CLOSING",{enumerable:!0,value:pt.indexOf("CLOSING")});Object.defineProperty(ae.prototype,"CLOSING",{enumerable:!0,value:pt.indexOf("CLOSING")});Object.defineProperty(ae,"CLOSED",{enumerable:!0,value:pt.indexOf("CLOSED")});Object.defineProperty(ae.prototype,"CLOSED",{enumerable:!0,value:pt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(ae.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(ae.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[oi])return e[Wg];return null},set(e){for(let t of this.listeners(n))if(t[oi]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[oi]:!0})}})});ae.prototype.addEventListener=Jg;ae.prototype.removeEventListener=Yg;sl.exports=ae;function Qc(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:qg,protocolVersion:ai[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(n._autoPong=s.autoPong,n._closeTimeout=s.closeTimeout,!ai.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ai.join(", ")})`);let i;if(e instanceof ii)i=e;else try{i=new ii(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",c;if(i.protocol!=="ws:"&&!o&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?c="The URL's pathname is empty":i.hash&&(c="The URL contains a fragment identifier"),c){let g=new SyntaxError(c);if(n._redirects===0)throw g;Ir(n,g);return}let d=o?443:80,l=Dg(16).toString("base64"),u=o?Mg.request:Lg.request,m=new Set,f;if(s.createConnection=s.createConnection||(o?Zg:Qg),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(f=new Tt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Vg({[Tt.extensionName]:f.offer()})),t.length){for(let g of t){if(typeof g!="string"||!Xg.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let p;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[y,S]of Object.entries(g))r.headers[y.toLowerCase()]=S}else if(n.listenerCount("redirect")===0){let g=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!g||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,g||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=n._req=u(s),n._redirects&&n.emit("redirect",n.url,p)}else p=n._req=u(s);s.timeout&&p.on("timeout",()=>{$e(n,p,"Opening handshake has timed out")}),p.on("error",g=>{p===null||p[Xc]||(p=n._req=null,Ir(n,g))}),p.on("response",g=>{let y=g.headers.location,S=g.statusCode;if(y&&s.followRedirects&&S>=300&&S<400){if(++n._redirects>s.maxRedirects){$e(n,p,"Maximum redirects exceeded");return}p.abort();let v;try{v=new ii(y,e)}catch{let b=new SyntaxError(`Invalid URL: ${y}`);Ir(n,b);return}Qc(n,v,t,r)}else n.emit("unexpected-response",p,g)||$e(n,p,`Unexpected server response: ${g.statusCode}`)}),p.on("upgrade",(g,y,S)=>{if(n.emit("upgrade",g),n.readyState!==ae.CONNECTING)return;p=n._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){$e(n,y,"Invalid Upgrade header");return}let _=Bg("sha1").update(l+Gg).digest("base64");if(g.headers["sec-websocket-accept"]!==_){$e(n,y,"Invalid Sec-WebSocket-Accept header");return}let b=g.headers["sec-websocket-protocol"],P;if(b!==void 0?m.size?m.has(b)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":m.size&&(P="Server sent no subprotocol"),P){$e(n,y,P);return}b&&(n._protocol=b);let x=g.headers["sec-websocket-extensions"];if(x!==void 0){if(!f){$e(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=zg(x)}catch{$e(n,y,"Invalid Sec-WebSocket-Extensions header");return}let G=Object.keys(N);if(G.length!==1||G[0]!==Tt.extensionName){$e(n,y,"Server indicated an extension that was not requested");return}try{f.accept(N[Tt.extensionName])}catch{$e(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Tt.extensionName]=f}n.setSocket(y,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,n):p.end()}function Ir(n,e){n._readyState=ae.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Qg(n){return n.path=n.socketPath,zc.connect(n)}function Zg(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=zc.isIP(n.host)?"":n.host),$g.connect(n)}function $e(n,e,t){n._readyState=ae.CLOSING;let r=new Error(t);Error.captureStackTrace(r,$e),e.setHeader?(e[Xc]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ir,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function ci(n,e,t){if(e){let r=Hg(e)?e.size:Kg(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${pt[n.readyState]})`);process.nextTick(t,r)}}function ep(n,e){let t=this[ye];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ye]!==void 0&&(t._socket.removeListener("data",Nr),process.nextTick(Zc,t._socket),n===1005?t.close():t.close(n,e))}function tp(){let n=this[ye];n.isPaused||n._socket.resume()}function np(n){let e=this[ye];e._socket[ye]!==void 0&&(e._socket.removeListener("data",Nr),process.nextTick(Zc,e._socket),e.close(n[jg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function Vc(){this[ye].emitClose()}function rp(n,e){this[ye].emit("message",n,e)}function sp(n){let e=this[ye];e._autoPong&&e.pong(n,!this._isServer,Kc),e.emit("ping",n)}function ip(n){this[ye].emit("pong",n)}function Zc(n){n.resume()}function op(n){let e=this[ye];e.readyState!==ae.CLOSED&&(e.readyState===ae.OPEN&&(e._readyState=ae.CLOSING,el(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function el(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function tl(){let n=this[ye];if(this.removeListener("close",tl),this.removeListener("data",Nr),this.removeListener("end",nl),n._readyState=ae.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ye]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Vc),n._receiver.on("finish",Vc))}function Nr(n){this[ye]._receiver.write(n)||this.pause()}function nl(){let n=this[ye];n._readyState=ae.CLOSING,n._receiver.end(),this.end()}function rl(){let n=this[ye];this.removeListener("error",rl),this.on("error",Kc),n&&(n._readyState=ae.CLOSING,this.destroy())}});var cl=X((Yv,al)=>{"use strict";var Jv=Mr(),{Duplex:ap}=Z("stream");function il(n){n.emit("close")}function cp(){!this.destroyed&&this._writableState.finished&&this.destroy()}function ol(n){this.removeListener("error",ol),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function lp(n,e){let t=!0,r=new ap({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(il,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(il,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",cp),r.on("error",ol),r}al.exports=lp});var li=X((Vv,ll)=>{"use strict";var{tokenChars:dp}=sn();function up(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&dp[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}ll.exports={parse:up}});var ml=X((Kv,pl)=>{"use strict";var fp=Z("events"),Lr=Z("http"),{Duplex:zv}=Z("stream"),{createHash:hp}=Z("crypto"),dl=Or(),Ht=rn(),gp=li(),pp=Mr(),{CLOSE_TIMEOUT:mp,GUID:yp,kWebSocket:_p}=ft(),wp=/^[+/0-9A-Za-z]{22}==$/,ul=0,fl=1,gl=2,di=class extends fp{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:mp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:pp,...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=Lr.createServer((r,s)=>{let i=Lr.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=vp(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=ul}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===gl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Dn,this);return}if(e&&this.once("close",e),this._state!==fl)if(this._state=fl,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(Dn,this):process.nextTick(Dn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Dn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",hl);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!wp.test(i)){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Bn(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=gp.parse(c)}catch{qt(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&l!==void 0){let m=new Ht({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=dl.parse(l);f[Ht.extensionName]&&(m.accept(f[Ht.extensionName]),u[Ht.extensionName]=m)}catch{qt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,p,g,y)=>{if(!f)return Bn(t,p||401,g,y);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(m))return Bn(t,401)}this.completeUpgrade(u,i,d,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[_p])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>ul)return Bn(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${hp("sha1").update(t+yp).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;u&&(d.push(`Sec-WebSocket-Protocol: ${u}`),l._protocol=u)}if(e[Ht.extensionName]){let u=e[Ht.extensionName].params,m=dl.format({[Ht.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${m}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
205
205
|
`).join(`\r
|
|
206
206
|
`)),i.removeListener("error",hl),l.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Dn,this)})),a(l,s)}};pl.exports=di;function vp(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function Dn(n){n._state=gl,n.emit("close")}function hl(){this.destroy()}function Bn(n,e,t,r){t=t||Lr.STATUS_CODES[e],r={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...r},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${Lr.STATUS_CODES[e]}\r
|
|
207
207
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
208
208
|
`)+`\r
|
|
209
209
|
\r
|
|
210
|
-
`+t)}function qt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qt),n.emit("wsClientError",o,t,e)}else Bn(t,r,s,i)}});var bp,kp,Sp,Ep,xp,Tp,ui,Cp,yl=O(()=>{bp=re(cl(),1),kp=re(Or(),1),Sp=re(rn(),1),Ep=re(ei(),1),xp=re(ri(),1),Tp=re(li(),1),ui=re(Mr(),1),Cp=re(ml(),1)});var _l,Ap,Op,$r,tb,fi=O(()=>{On();$t();Kt();Lt();_l=re(Ue(),1),Ap=(0,_l.default)("engine.io-client:websocket"),Op=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",$r=class extends dt{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Op?{}:gr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;Rn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{Ap("websocket closed before onclose event")}s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=pr()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},tb=Ee.WebSocket||Ee.MozWebSocket});var dn,hi=O(()=>{yl();fi();dn=class extends $r{createSocket(e,t,r){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){r.headers=r.headers||{},r.headers.cookie=typeof r.headers.cookie=="string"?[r.headers.cookie]:r.headers.cookie||[];for(let[i,o]of this.socket._cookieJar.cookies)r.headers.cookie.push(`${i}=${o.value}`)}return new ui.default(e,t,r)}doWrite(e,t){let r={};e.options&&(r.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(r.compress=!1),this.ws.send(t,r)}}});var wl,Fn,un,gi=O(()=>{On();Lt();Kt();wl=re(Ue(),1),Fn=(0,wl.default)("engine.io-client:webtransport"),un=class extends dt{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{Fn("transport closed gracefully"),this.onClose()}).catch(e=>{Fn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Ja(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=ja();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){Fn("session is closed");return}Fn("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{Fn("an error occurred while reading: %s",a)})};i();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;this._writer.write(r).then(()=>{s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var pi,mi=O(()=>{Gs();hi();gi();pi={websocket:dn,webtransport:un,polling:en}});function fn(n){if(n.length>8e3)throw"URI too long";let e=n,t=n.indexOf("["),r=n.indexOf("]");t!=-1&&r!=-1&&(n=n.substring(0,t)+n.substring(t,r).replace(/:/g,";")+n.substring(r,n.length));let s=Pp.exec(n||""),i={},o=14;for(;o--;)i[Ip[o]]=s[o]||"";return t!=-1&&r!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Np(i,i.path),i.queryKey=Mp(i,i.query),i}function Np(n,e){let t=/\/{2,9}/g,r=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&r.splice(0,1),e.slice(-1)=="/"&&r.splice(r.length-1,1),r}function Mp(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var Pp,Ip,yi=O(()=>{Pp=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Ip=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var vl,bl,se,_i,Un,Gt,Dr,hn,wi=O(()=>{mi();$t();$s();yi();vl=re(Mt(),1);Kt();Lt();bl=re(Ue(),1),se=(0,bl.default)("engine.io-client:socket"),_i=typeof addEventListener=="function"&&typeof removeEventListener=="function",Un=[];_i&&addEventListener("offline",()=>{se("closing %d connection(s) because the network was lost",Un.length),Un.forEach(n=>n())},!1);Gt=class n extends vl.Emitter{constructor(e,t){if(super(),this.binaryType=Va,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let r=fn(e);t.hostname=r.host,t.secure=r.protocol==="https"||r.protocol==="wss",t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=fn(t.host).host);lt(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(r=>{let s=r.prototype.name;this.transports.push(s),this._transportsByName[s]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Qa(this.opts.query)),_i&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(se("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Un.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=za()),this._open()}createTransport(e){se('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Ms,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return se("options: %j",r),new this._transportsByName[e](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){se("setting transport %s",e.name),this.transport&&(se("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){se("socket open"),this.readyState="open",n.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(se('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else se('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();se("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let s=this.writeBuffer[r].data;if(s&&(t+=Ka(s)),r>0&&t>this._maxPayload)return se("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return se("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(se("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,ct(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,s){if(typeof t=="function"&&(s=t,t=void 0),typeof r=="function"&&(s=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;let i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),se("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(se("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return se("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(se('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),_i&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Un.indexOf(this._offlineEventListener);r!==-1&&(se("removing listener for the 'offline' event"),Un.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Gt.protocol=Ms;Dr=class extends Gt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){se("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){se('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Gt.priorWebsocketSuccess=!1;let s=()=>{r||(se('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(se('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Gt.priorWebsocketSuccess=t.name==="websocket",se('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(se("changing transport and sending upgrade packet"),l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{se('probe transport "%s" failed',e);let m=new Error("probe error");m.transport=t.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,l(),t.close(),t=null)}let o=u=>{let m=new Error("probe error: "+u);m.transport=t.name,i(),se('probe transport "%s" failed because of error: %s',e,u),this.emitReserved("upgradeError",m)};function a(){o("transport closed")}function c(){o("socket closed")}function d(u){t&&u.name!==t.name&&(se('"%s" works - aborting "%s"',u.name,t.name),i())}let l=()=>{t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}},hn=class extends Dr{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(s=>pi[s]).filter(s=>!!s)),super(e,r)}}});var kl=O(()=>{Fs()});var Eb,Br=O(()=>{wi();wi();On();mi();$t();yi();Lt();kl();Gs();Hs();hi();fi();gi();Eb=hn.protocol});function xl(n,e="",t){let r=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(Sl("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Sl("parse %s",n),r=fn(n)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";let i=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(t&&t.port===r.port?"":":"+r.port),r}var El,Sl,Tl=O(()=>{Br();El=re(Ue(),1),Sl=(0,El.default)("socket.io-client:url")});function qn(n){return Bp&&(n instanceof ArrayBuffer||Fp(n))||Up&&n instanceof Blob||Hp&&n instanceof File}function Hn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Hn(n[t]))return!0;return!1}if(qn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Hn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Hn(n[t]))return!0;return!1}var Bp,Fp,Cl,Up,Hp,vi=O(()=>{Bp=typeof ArrayBuffer=="function",Fp=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Cl=Object.prototype.toString,Up=typeof Blob=="function"||typeof Blob<"u"&&Cl.call(Blob)==="[object BlobConstructor]",Hp=typeof File=="function"||typeof File<"u"&&Cl.call(File)==="[object FileConstructor]"});function Rl(n){let e=[],t=n.data,r=n;return r.data=bi(t,e),r.attachments=e.length,{packet:r,buffers:e}}function bi(n,e){if(!n)return n;if(qn(n)){let t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){let t=new Array(n.length);for(let r=0;r<n.length;r++)t[r]=bi(n[r],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){let t={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=bi(n[r],e));return t}return n}function Al(n,e){return n.data=ki(n.data,e),delete n.attachments,n}function ki(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=ki(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=ki(n[t],e));return n}var Ol=O(()=>{vi()});var Ci={};Me(Ci,{Decoder:()=>xi,Encoder:()=>Ei,PacketType:()=>j,isPacketValid:()=>jp,protocol:()=>Ml});function qp(n){return typeof n=="string"}function Gp(n){return n===void 0||Ll(n)}function Fr(n){return Object.prototype.toString.call(n)==="[object Object]"}function Wp(n,e){switch(n){case j.CONNECT:return e===void 0||Fr(e);case j.DISCONNECT:return e===void 0;case j.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Nl.indexOf(e[0])===-1);case j.ACK:return Array.isArray(e);case j.CONNECT_ERROR:return typeof e=="string"||Fr(e);default:return!1}}function jp(n){return qp(n.nsp)&&Gp(n.id)&&Wp(n.type,n.data)}var Pl,Il,Si,Nl,Ml,j,Ei,xi,Ti,Ll,Ur=O(()=>{Pl=re(Mt(),1);Ol();vi();Il=re(Ue(),1),Si=(0,Il.default)("socket.io-parser"),Nl=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Ml=5;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(j||(j={}));Ei=class{constructor(e){this.replacer=e}encode(e){return Si("encoding packet %j",e),(e.type===j.EVENT||e.type===j.ACK)&&Hn(e)?this.encodeAsBinary({type:e.type===j.EVENT?j.BINARY_EVENT:j.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===j.BINARY_EVENT||e.type===j.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Si("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=Rl(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},xi=class n extends Pl.Emitter{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let r=t.type===j.BINARY_EVENT;r||t.type===j.BINARY_ACK?(t.type=r?j.EVENT:j.ACK,this.reconstructor=new Ti(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(qn(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,r={type:Number(e.charAt(0))};if(j[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===j.BINARY_EVENT||r.type===j.BINARY_ACK){let i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");let a=Number(o);if(!Ll(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");r.attachments=a}if(e.charAt(t+1)==="/"){let i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););r.nsp=e.substring(i,t)}else r.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let i=t+1;for(;++t;){let o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){let i=this.tryParse(e.substr(t));if(n.isPayloadValid(r.type,i))r.data=i;else throw new Error("invalid payload")}return Si("decoded %s as %j",e,r),r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case j.CONNECT:return Fr(t);case j.DISCONNECT:return t===void 0;case j.CONNECT_ERROR:return typeof t=="string"||Fr(t);case j.EVENT:case j.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Nl.indexOf(t[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Ti=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=Al(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};Ll=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function $e(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Ri=O(()=>{});var $l,Dl,ue,Jp,gn,Ai=O(()=>{Ur();Ri();$l=re(Mt(),1),Dl=re(Ue(),1),ue=(0,Dl.default)("socket.io-client:socket"),Jp=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),gn=class extends $l.Emitter{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[$e(e,"open",this.onopen.bind(this)),$e(e,"packet",this.onpacket.bind(this)),$e(e,"error",this.onerror.bind(this)),$e(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,s,i;if(Jp.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let o={type:j.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let l=this.ids++;ue("emitting packet with ack id %d",l);let u=t.pop();this._registerAckCallback(l,u),o.id=l}let a=(s=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||s===void 0?void 0:s.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a?ue("discard packet as the transport is not currently writable"):c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o),this.flags={},this}_registerAckCallback(e,t){var r;let s=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&(ue("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));ue("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,s)=>{let i=(o,a)=>o?s(o):r(a);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>r!==this._queue[0]?ue("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(ue("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(ue("packet [%d] was successfully sent",r.id),this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(ue("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ue("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ue("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){ue("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:j.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){ue("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(r=>String(r.id)===e)){let r=this.acks[e];delete this.acks[e],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case j.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case j.EVENT:case j.BINARY_EVENT:this.onevent(e);break;case j.ACK:case j.BINARY_ACK:this.onack(e);break;case j.DISCONNECT:this.ondisconnect();break;case j.CONNECT_ERROR:this.destroy();let r=new Error(e.data.message);r.data=e.data.data,this.emitReserved("connect_error",r);break}}onevent(e){let t=e.data||[];ue("emitting event %j",t),e.id!=null&&(ue("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...s){r||(r=!0,ue("sending ack %j",s),t.packet({type:j.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ue("bad ack %s",e.id);return}delete this.acks[e.id],ue("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ue("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){ue("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(ue("performing disconnect (%s)",this.nsp),this.packet({type:j.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}}});function Wt(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}var Bl=O(()=>{Wt.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=(Math.floor(e*10)&1)==0?n-t:n+t}return Math.min(n,this.max)|0};Wt.prototype.reset=function(){this.attempts=0};Wt.prototype.setMin=function(n){this.ms=n};Wt.prototype.setMax=function(n){this.max=n};Wt.prototype.setJitter=function(n){this.jitter=n}});var Fl,Ul,we,pn,Hl=O(()=>{Br();Ai();Ur();Ri();Bl();Fl=re(Mt(),1),Ul=re(Ue(),1),we=(0,Ul.default)("socket.io-client:manager"),pn=class extends Fl.Emitter{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,lt(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Wt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||Ci;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(we("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;we("opening %s",this.uri),this.engine=new hn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=$e(t,"open",function(){r.onopen(),e&&e()}),i=a=>{we("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=$e(t,"error",i);if(this._timeout!==!1){let a=this._timeout;we("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{we("connect attempt timed out after %d",a),s(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(s),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){we("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push($e(e,"ping",this.onping.bind(this)),$e(e,"data",this.ondata.bind(this)),$e(e,"error",this.onerror.bind(this)),$e(e,"close",this.onclose.bind(this)),$e(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){ct(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){we("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new gn(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active){we("socket %s is still active, skipping close",r);return}this._close()}_packet(e){we("writing packet %j",e);let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){we("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){we("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;we("closed due to %s",e),this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)we("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();we("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(we("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(we("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(we("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}});function Wn(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=xl(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Gn[s]&&i in Gn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(ql("ignoring socket cache for %s",r),c=new pn(r,e)):(Gn[s]||(ql("new io instance for %s",r),Gn[s]=new pn(r,e)),c=Gn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var Gl,ql,Gn,Wl=O(()=>{Tl();Hl();Ai();Gl=re(Ue(),1);Ur();Br();ql=(0,Gl.default)("socket.io-client"),Gn={};Object.assign(Wn,{Manager:pn,Socket:gn,io:Wn,connect:Wn})});var nt,Yp,Hr,jl=O(()=>{"use strict";Wl();le();nt="wsClient",Yp=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),Hr=class{constructor(e){this.opts=e;this.token=e.token}opts;socket=null;handlers=new Map;lastSeenSeq=new Map;reconnectAttempt=0;reconnectTimer=null;destroyed=!1;authFailed=!1;token;connect(){this.socket||this._connect()}subscribe(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),this.socket?.connected&&this._emitSubscribe(e)}unsubscribe(e,t){let r=this.handlers.get(e);r&&(r.delete(t),r.size===0&&(this.handlers.delete(e),this.socket?.connected&&this.socket.emit("unsubscribe",{workroom_id:e})))}updateToken(e){this.token=e,h("info",nt,"Token updated (will take effect on next subscribe)")}async dispatchCatchUpEvents(e,t){let r=this.handlers.get(e);if(r)for(let s of t){this._advanceSeq(s.workroom_id,s.seq);for(let i of r)await Promise.resolve(i(s)).catch(o=>{k(nt,"catch-up handler threw",o)})}}destroy(){this.destroyed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null)}_connect(){if(this.destroyed||this.authFailed)return;let e=Wn(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",nt,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{k(nt,"onReconnect hook failed",t),this._resubscribeAll()}):this._resubscribeAll()}),e.on("workroom:event",t=>{this._advanceSeq(t.workroom_id,t.seq);let r=this.handlers.get(t.workroom_id);if(r)for(let s of r)Promise.resolve(s(t)).catch(i=>{k(nt,"event handler threw",i)})});for(let t of Yp)e.on(t,r=>{h("error",nt,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",nt,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",nt,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{k(nt,"WS connect_error",t),this.socket=null,this._scheduleReconnect()})}_emitSubscribe(e){this.socket?.connected&&this.socket.emit("subscribe",{token:this.token,workroom_id:e})}_resubscribeAll(){for(let e of this.handlers.keys())this._emitSubscribe(e)}_advanceSeq(e,t){let r=this.lastSeenSeq.get(e);(!r||BigInt(t)>BigInt(r))&&(this.lastSeenSeq.set(e,t),this.opts.onSeqUpdate?.(e,t))}_scheduleReconnect(){if(this.destroyed||this.authFailed)return;let r=Math.min(1e3*Math.pow(2,this.reconnectAttempt),6e4);this.reconnectAttempt+=1,h("info",nt,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var Ke,qr,Jl=O(()=>{"use strict";Yt();ia();dr();jl();le();Ke="serverGateway",qr=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=kt(),h("info",Ke,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new Hr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>sa(t,r)});let e=ra();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",Ke,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",Ke,`Gateway started \u2192 ${this.config.server_url}`)}async stop(){this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null),this.wsClient?.destroy(),this.wsClient=null,h("info",Ke,"Gateway stopped")}subscribe(e,t){if(!this.wsClient)throw new Error("Gateway not started \u2014 call start() first");this.wsClient.subscribe(e,t),h("info",Ke,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return aa(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await ca(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await la(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await da(this.config.server_url,e,t,this._getToken())}async getAction(e){return fa(this.config.server_url,e,this._getToken())}async getApproval(e){return ha(this.config.server_url,e,this._getToken())}async fireAction(e,t){return ga(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await pa(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return ma(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return xn(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return ya(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return wa(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return va(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return _a(this.config.server_url,e,this._getToken())}async getTasks(e,t){return ba(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return ka(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return Sa(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return Ea(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return xa(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Ta(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return Ca(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await Oa(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await Ra(this.config.server_url,this._getToken(),e,{channel_id:t,state:r})}async notifyAgentStatus(e,t,r){let s={state:r};t!==void 0&&(s.channel_id=t),await Aa(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return Pa(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Ia(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",Ke,"Running catch-up after WS reconnect");for(let[e,t]of this.wsClient.lastSeenSeq)await this._runCatchUp(e,t)}}async _runCatchUp(e,t){try{let r=await ua(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",Ke,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",Ke,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){k(Ke,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=kt(),t=await oa(this.config.server_url,e);ir(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",Ke,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){k(Ke,"token refresh failed",e)}}_getToken(){return this.token||(this.token=kt()),this.token}}});import{execFile as Vp}from"node:child_process";import{promisify as zp}from"node:util";import{readFileSync as Kp,readdirSync as Gr,statSync as Oi,openSync as Xp,readSync as Qp,closeSync as Zp}from"node:fs";import{join as jt}from"node:path";import{homedir as Yl}from"node:os";async function em(){try{if(process.platform==="darwin"){let{stdout:n}=await Vl("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=Kp(jt(Yl(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function tm(){let n=await em();if(!n)return null;try{let{stdout:e}=await Vl("curl",["-s","--max-time","10","-H",`Authorization: Bearer ${n}`,"-H","anthropic-beta: oauth-2025-04-20","https://api.anthropic.com/api/oauth/usage"]),t=JSON.parse(e);return typeof t.five_hour?.utilization!="number"?null:{five_hour_pct:t.five_hour.utilization,seven_day_pct:t.seven_day?.utilization??0,five_hour_resets_at:t.five_hour.resets_at??null,seven_day_resets_at:t.seven_day?.resets_at??null}}catch{return null}}function nm(n,e){let t=[];try{for(let r of Gr(n).sort().reverse().slice(0,2)){let s=jt(n,r);for(let i of Gr(s).sort().reverse().slice(0,2)){let o=jt(s,i);for(let a of Gr(o).sort().reverse().slice(0,7)){let c=jt(o,a);for(let d of Gr(c)){if(!d.endsWith(".jsonl"))continue;let l=jt(c,d);try{t.push({path:l,mtime:Oi(l).mtimeMs})}catch{}}}if(t.length>=e*4)break}if(t.length>=e*4)break}}catch{}return t.sort((r,s)=>s.mtime-r.mtime).slice(0,e).map(r=>r.path)}function rm(n,e){let t=Xp(n,"r");try{let r=Oi(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return Qp(t,i,0,s,r-s),i.toString("utf-8")}finally{Zp(t)}}function sm(){let n=process.env.CODEX_HOME??jt(Yl(),".codex");for(let e of nm(jt(n,"sessions"),5))try{let t=rm(e,262144).split(`
|
|
210
|
+
`+t)}function qt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qt),n.emit("wsClientError",o,t,e)}else Bn(t,r,s,i)}});var bp,kp,Sp,Ep,xp,Tp,ui,Cp,yl=O(()=>{bp=re(cl(),1),kp=re(Or(),1),Sp=re(rn(),1),Ep=re(ei(),1),xp=re(ri(),1),Tp=re(li(),1),ui=re(Mr(),1),Cp=re(ml(),1)});var _l,Ap,Op,$r,tb,fi=O(()=>{On();$t();Kt();Lt();_l=re(Ue(),1),Ap=(0,_l.default)("engine.io-client:websocket"),Op=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",$r=class extends dt{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Op?{}:gr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;Rn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{Ap("websocket closed before onclose event")}s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=pr()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},tb=Ee.WebSocket||Ee.MozWebSocket});var dn,hi=O(()=>{yl();fi();dn=class extends $r{createSocket(e,t,r){var s;if(!((s=this.socket)===null||s===void 0)&&s._cookieJar){r.headers=r.headers||{},r.headers.cookie=typeof r.headers.cookie=="string"?[r.headers.cookie]:r.headers.cookie||[];for(let[i,o]of this.socket._cookieJar.cookies)r.headers.cookie.push(`${i}=${o.value}`)}return new ui.default(e,t,r)}doWrite(e,t){let r={};e.options&&(r.compress=e.options.compress),this.opts.perMessageDeflate&&(typeof t=="string"?Buffer.byteLength(t):t.length)<this.opts.perMessageDeflate.threshold&&(r.compress=!1),this.ws.send(t,r)}}});var wl,Fn,un,gi=O(()=>{On();Lt();Kt();wl=re(Ue(),1),Fn=(0,wl.default)("engine.io-client:webtransport"),un=class extends dt{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{Fn("transport closed gracefully"),this.onClose()}).catch(e=>{Fn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Ja(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=ja();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){Fn("session is closed");return}Fn("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{Fn("an error occurred while reading: %s",a)})};i();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;this._writer.write(r).then(()=>{s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var pi,mi=O(()=>{Gs();hi();gi();pi={websocket:dn,webtransport:un,polling:en}});function fn(n){if(n.length>8e3)throw"URI too long";let e=n,t=n.indexOf("["),r=n.indexOf("]");t!=-1&&r!=-1&&(n=n.substring(0,t)+n.substring(t,r).replace(/:/g,";")+n.substring(r,n.length));let s=Pp.exec(n||""),i={},o=14;for(;o--;)i[Ip[o]]=s[o]||"";return t!=-1&&r!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=Np(i,i.path),i.queryKey=Mp(i,i.query),i}function Np(n,e){let t=/\/{2,9}/g,r=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&r.splice(0,1),e.slice(-1)=="/"&&r.splice(r.length-1,1),r}function Mp(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var Pp,Ip,yi=O(()=>{Pp=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Ip=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var vl,bl,se,_i,Un,Gt,Dr,hn,wi=O(()=>{mi();$t();$s();yi();vl=re(Mt(),1);Kt();Lt();bl=re(Ue(),1),se=(0,bl.default)("engine.io-client:socket"),_i=typeof addEventListener=="function"&&typeof removeEventListener=="function",Un=[];_i&&addEventListener("offline",()=>{se("closing %d connection(s) because the network was lost",Un.length),Un.forEach(n=>n())},!1);Gt=class n extends vl.Emitter{constructor(e,t){if(super(),this.binaryType=Va,this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&typeof e=="object"&&(t=e,e=null),e){let r=fn(e);t.hostname=r.host,t.secure=r.protocol==="https"||r.protocol==="wss",t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=fn(t.host).host);lt(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(r=>{let s=r.prototype.name;this.transports.push(s),this._transportsByName[s]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=Qa(this.opts.query)),_i&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(se("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Un.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=za()),this._open()}createTransport(e){se('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Ms,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return se("options: %j",r),new this._transportsByName[e](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){se("setting transport %s",e.name),this.transport&&(se("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){se("socket open"),this.readyState="open",n.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(se('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else se('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();se("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let s=this.writeBuffer[r].data;if(s&&(t+=Ka(s)),r>0&&t>this._maxPayload)return se("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return se("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(se("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,ct(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,s){if(typeof t=="function"&&(s=t,t=void 0),typeof r=="function"&&(s=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;let i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),se("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(se("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return se("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(se('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),_i&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Un.indexOf(this._offlineEventListener);r!==-1&&(se("removing listener for the 'offline' event"),Un.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Gt.protocol=Ms;Dr=class extends Gt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){se("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){se('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Gt.priorWebsocketSuccess=!1;let s=()=>{r||(se('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(se('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Gt.priorWebsocketSuccess=t.name==="websocket",se('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(se("changing transport and sending upgrade packet"),l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{se('probe transport "%s" failed',e);let m=new Error("probe error");m.transport=t.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,l(),t.close(),t=null)}let o=u=>{let m=new Error("probe error: "+u);m.transport=t.name,i(),se('probe transport "%s" failed because of error: %s',e,u),this.emitReserved("upgradeError",m)};function a(){o("transport closed")}function c(){o("socket closed")}function d(u){t&&u.name!==t.name&&(se('"%s" works - aborting "%s"',u.name,t.name),i())}let l=()=>{t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}},hn=class extends Dr{constructor(e,t={}){let r=typeof e=="object"?e:t;(!r.transports||r.transports&&typeof r.transports[0]=="string")&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(s=>pi[s]).filter(s=>!!s)),super(e,r)}}});var kl=O(()=>{Fs()});var Eb,Br=O(()=>{wi();wi();On();mi();$t();yi();Lt();kl();Gs();Hs();hi();fi();gi();Eb=hn.protocol});function xl(n,e="",t){let r=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(Sl("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Sl("parse %s",n),r=fn(n)),r.port||(/^(http|ws)$/.test(r.protocol)?r.port="80":/^(http|ws)s$/.test(r.protocol)&&(r.port="443")),r.path=r.path||"/";let i=r.host.indexOf(":")!==-1?"["+r.host+"]":r.host;return r.id=r.protocol+"://"+i+":"+r.port+e,r.href=r.protocol+"://"+i+(t&&t.port===r.port?"":":"+r.port),r}var El,Sl,Tl=O(()=>{Br();El=re(Ue(),1),Sl=(0,El.default)("socket.io-client:url")});function qn(n){return Bp&&(n instanceof ArrayBuffer||Fp(n))||Up&&n instanceof Blob||Hp&&n instanceof File}function Hn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Hn(n[t]))return!0;return!1}if(qn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Hn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Hn(n[t]))return!0;return!1}var Bp,Fp,Cl,Up,Hp,vi=O(()=>{Bp=typeof ArrayBuffer=="function",Fp=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Cl=Object.prototype.toString,Up=typeof Blob=="function"||typeof Blob<"u"&&Cl.call(Blob)==="[object BlobConstructor]",Hp=typeof File=="function"||typeof File<"u"&&Cl.call(File)==="[object FileConstructor]"});function Rl(n){let e=[],t=n.data,r=n;return r.data=bi(t,e),r.attachments=e.length,{packet:r,buffers:e}}function bi(n,e){if(!n)return n;if(qn(n)){let t={_placeholder:!0,num:e.length};return e.push(n),t}else if(Array.isArray(n)){let t=new Array(n.length);for(let r=0;r<n.length;r++)t[r]=bi(n[r],e);return t}else if(typeof n=="object"&&!(n instanceof Date)){let t={};for(let r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=bi(n[r],e));return t}return n}function Al(n,e){return n.data=ki(n.data,e),delete n.attachments,n}function ki(n,e){if(!n)return n;if(n&&n._placeholder===!0){if(typeof n.num=="number"&&n.num>=0&&n.num<e.length)return e[n.num];throw new Error("illegal attachments")}else if(Array.isArray(n))for(let t=0;t<n.length;t++)n[t]=ki(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=ki(n[t],e));return n}var Ol=O(()=>{vi()});var Ci={};Le(Ci,{Decoder:()=>xi,Encoder:()=>Ei,PacketType:()=>j,isPacketValid:()=>jp,protocol:()=>Ml});function qp(n){return typeof n=="string"}function Gp(n){return n===void 0||Ll(n)}function Fr(n){return Object.prototype.toString.call(n)==="[object Object]"}function Wp(n,e){switch(n){case j.CONNECT:return e===void 0||Fr(e);case j.DISCONNECT:return e===void 0;case j.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Nl.indexOf(e[0])===-1);case j.ACK:return Array.isArray(e);case j.CONNECT_ERROR:return typeof e=="string"||Fr(e);default:return!1}}function jp(n){return qp(n.nsp)&&Gp(n.id)&&Wp(n.type,n.data)}var Pl,Il,Si,Nl,Ml,j,Ei,xi,Ti,Ll,Ur=O(()=>{Pl=re(Mt(),1);Ol();vi();Il=re(Ue(),1),Si=(0,Il.default)("socket.io-parser"),Nl=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Ml=5;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(j||(j={}));Ei=class{constructor(e){this.replacer=e}encode(e){return Si("encoding packet %j",e),(e.type===j.EVENT||e.type===j.ACK)&&Hn(e)?this.encodeAsBinary({type:e.type===j.EVENT?j.BINARY_EVENT:j.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===j.BINARY_EVENT||e.type===j.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Si("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=Rl(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},xi=class n extends Pl.Emitter{constructor(e){super(),this.opts=Object.assign({reviver:void 0,maxAttachments:10},typeof e=="function"?{reviver:e}:e)}add(e){let t;if(typeof e=="string"){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);let r=t.type===j.BINARY_EVENT;r||t.type===j.BINARY_ACK?(t.type=r?j.EVENT:j.ACK,this.reconstructor=new Ti(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(qn(e)||e.base64)if(this.reconstructor)t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t));else throw new Error("got binary data when not reconstructing a packet");else throw new Error("Unknown type: "+e)}decodeString(e){let t=0,r={type:Number(e.charAt(0))};if(j[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===j.BINARY_EVENT||r.type===j.BINARY_ACK){let i=t+1;for(;e.charAt(++t)!=="-"&&t!=e.length;);let o=e.substring(i,t);if(o!=Number(o)||e.charAt(t)!=="-")throw new Error("Illegal attachments");let a=Number(o);if(!Ll(a)||a<0)throw new Error("Illegal attachments");if(a>this.opts.maxAttachments)throw new Error("too many attachments");r.attachments=a}if(e.charAt(t+1)==="/"){let i=t+1;for(;++t&&!(e.charAt(t)===","||t===e.length););r.nsp=e.substring(i,t)}else r.nsp="/";let s=e.charAt(t+1);if(s!==""&&Number(s)==s){let i=t+1;for(;++t;){let o=e.charAt(t);if(o==null||Number(o)!=o){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){let i=this.tryParse(e.substr(t));if(n.isPayloadValid(r.type,i))r.data=i;else throw new Error("invalid payload")}return Si("decoded %s as %j",e,r),r}tryParse(e){try{return JSON.parse(e,this.opts.reviver)}catch{return!1}}static isPayloadValid(e,t){switch(e){case j.CONNECT:return Fr(t);case j.DISCONNECT:return t===void 0;case j.CONNECT_ERROR:return typeof t=="string"||Fr(t);case j.EVENT:case j.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Nl.indexOf(t[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Ti=class{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){let t=Al(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};Ll=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function De(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Ri=O(()=>{});var $l,Dl,ue,Jp,gn,Ai=O(()=>{Ur();Ri();$l=re(Mt(),1),Dl=re(Ue(),1),ue=(0,Dl.default)("socket.io-client:socket"),Jp=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),gn=class extends $l.Emitter{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;let e=this.io;this.subs=[De(e,"open",this.onopen.bind(this)),De(e,"packet",this.onpacket.bind(this)),De(e,"error",this.onerror.bind(this)),De(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,s,i;if(Jp.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let o={type:j.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let l=this.ids++;ue("emitting packet with ack id %d",l);let u=t.pop();this._registerAckCallback(l,u),o.id=l}let a=(s=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||s===void 0?void 0:s.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a?ue("discard packet as the transport is not currently writable"):c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o),this.flags={},this}_registerAckCallback(e,t){var r;let s=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&(ue("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));ue("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,s)=>{let i=(o,a)=>o?s(o):r(a);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>r!==this._queue[0]?ue("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(ue("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(ue("packet [%d] was successfully sent",r.id),this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(ue("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ue("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ue("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){ue("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:j.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){ue("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(r=>String(r.id)===e)){let r=this.acks[e];delete this.acks[e],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case j.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case j.EVENT:case j.BINARY_EVENT:this.onevent(e);break;case j.ACK:case j.BINARY_ACK:this.onack(e);break;case j.DISCONNECT:this.ondisconnect();break;case j.CONNECT_ERROR:this.destroy();let r=new Error(e.data.message);r.data=e.data.data,this.emitReserved("connect_error",r);break}}onevent(e){let t=e.data||[];ue("emitting event %j",t),e.id!=null&&(ue("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...s){r||(r=!0,ue("sending ack %j",s),t.packet({type:j.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ue("bad ack %s",e.id);return}delete this.acks[e.id],ue("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ue("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){ue("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(ue("performing disconnect (%s)",this.nsp),this.packet({type:j.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}}});function Wt(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}var Bl=O(()=>{Wt.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=(Math.floor(e*10)&1)==0?n-t:n+t}return Math.min(n,this.max)|0};Wt.prototype.reset=function(){this.attempts=0};Wt.prototype.setMin=function(n){this.ms=n};Wt.prototype.setMax=function(n){this.max=n};Wt.prototype.setJitter=function(n){this.jitter=n}});var Fl,Ul,we,pn,Hl=O(()=>{Br();Ai();Ur();Ri();Bl();Fl=re(Mt(),1),Ul=re(Ue(),1),we=(0,Ul.default)("socket.io-client:manager"),pn=class extends Fl.Emitter{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,lt(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Wt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||Ci;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(we("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;we("opening %s",this.uri),this.engine=new hn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=De(t,"open",function(){r.onopen(),e&&e()}),i=a=>{we("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=De(t,"error",i);if(this._timeout!==!1){let a=this._timeout;we("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{we("connect attempt timed out after %d",a),s(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(s),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){we("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(De(e,"ping",this.onping.bind(this)),De(e,"data",this.ondata.bind(this)),De(e,"error",this.onerror.bind(this)),De(e,"close",this.onclose.bind(this)),De(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){ct(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){we("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new gn(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active){we("socket %s is still active, skipping close",r);return}this._close()}_packet(e){we("writing packet %j",e);let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){we("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){we("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;we("closed due to %s",e),this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)we("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();we("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(we("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(we("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(we("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}});function Wn(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=xl(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Gn[s]&&i in Gn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(ql("ignoring socket cache for %s",r),c=new pn(r,e)):(Gn[s]||(ql("new io instance for %s",r),Gn[s]=new pn(r,e)),c=Gn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var Gl,ql,Gn,Wl=O(()=>{Tl();Hl();Ai();Gl=re(Ue(),1);Ur();Br();ql=(0,Gl.default)("socket.io-client"),Gn={};Object.assign(Wn,{Manager:pn,Socket:gn,io:Wn,connect:Wn})});var nt,Yp,Hr,jl=O(()=>{"use strict";Wl();le();nt="wsClient",Yp=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),Hr=class{constructor(e){this.opts=e;this.token=e.token}opts;socket=null;handlers=new Map;lastSeenSeq=new Map;reconnectAttempt=0;reconnectTimer=null;destroyed=!1;authFailed=!1;token;connect(){this.socket||this._connect()}subscribe(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),this.socket?.connected&&this._emitSubscribe(e)}unsubscribe(e,t){let r=this.handlers.get(e);r&&(r.delete(t),r.size===0&&(this.handlers.delete(e),this.socket?.connected&&this.socket.emit("unsubscribe",{workroom_id:e})))}updateToken(e){this.token=e,h("info",nt,"Token updated (will take effect on next subscribe)")}async dispatchCatchUpEvents(e,t){let r=this.handlers.get(e);if(r)for(let s of t){this._advanceSeq(s.workroom_id,s.seq);for(let i of r)await Promise.resolve(i(s)).catch(o=>{k(nt,"catch-up handler threw",o)})}}destroy(){this.destroyed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null)}_connect(){if(this.destroyed||this.authFailed)return;let e=Wn(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",nt,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{k(nt,"onReconnect hook failed",t),this._resubscribeAll()}):this._resubscribeAll()}),e.on("workroom:event",t=>{this._advanceSeq(t.workroom_id,t.seq);let r=this.handlers.get(t.workroom_id);if(r)for(let s of r)Promise.resolve(s(t)).catch(i=>{k(nt,"event handler threw",i)})});for(let t of Yp)e.on(t,r=>{h("error",nt,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",nt,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",nt,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{k(nt,"WS connect_error",t),this.socket=null,this._scheduleReconnect()})}_emitSubscribe(e){this.socket?.connected&&this.socket.emit("subscribe",{token:this.token,workroom_id:e})}_resubscribeAll(){for(let e of this.handlers.keys())this._emitSubscribe(e)}_advanceSeq(e,t){let r=this.lastSeenSeq.get(e);(!r||BigInt(t)>BigInt(r))&&(this.lastSeenSeq.set(e,t),this.opts.onSeqUpdate?.(e,t))}_scheduleReconnect(){if(this.destroyed||this.authFailed)return;let r=Math.min(1e3*Math.pow(2,this.reconnectAttempt),6e4);this.reconnectAttempt+=1,h("info",nt,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var Ke,qr,Jl=O(()=>{"use strict";Yt();ia();dr();jl();le();Ke="serverGateway",qr=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=kt(),h("info",Ke,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new Hr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>sa(t,r)});let e=ra();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",Ke,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",Ke,`Gateway started \u2192 ${this.config.server_url}`)}async stop(){this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null),this.wsClient?.destroy(),this.wsClient=null,h("info",Ke,"Gateway stopped")}subscribe(e,t){if(!this.wsClient)throw new Error("Gateway not started \u2014 call start() first");this.wsClient.subscribe(e,t),h("info",Ke,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return aa(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await ca(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await la(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await da(this.config.server_url,e,t,this._getToken())}async getAction(e){return fa(this.config.server_url,e,this._getToken())}async getApproval(e){return ha(this.config.server_url,e,this._getToken())}async fireAction(e,t){return ga(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await pa(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return ma(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return xn(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return ya(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return wa(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return va(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return _a(this.config.server_url,e,this._getToken())}async getTasks(e,t){return ba(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return ka(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return Sa(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return Ea(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return xa(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Ta(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return Ca(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await Oa(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await Ra(this.config.server_url,this._getToken(),e,{channel_id:t,state:r})}async notifyAgentStatus(e,t,r){let s={state:r};t!==void 0&&(s.channel_id=t),await Aa(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return Pa(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Ia(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",Ke,"Running catch-up after WS reconnect");for(let[e,t]of this.wsClient.lastSeenSeq)await this._runCatchUp(e,t)}}async _runCatchUp(e,t){try{let r=await ua(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",Ke,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",Ke,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){k(Ke,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=kt(),t=await oa(this.config.server_url,e);ir(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",Ke,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){k(Ke,"token refresh failed",e)}}_getToken(){return this.token||(this.token=kt()),this.token}}});import{execFile as Vp}from"node:child_process";import{promisify as zp}from"node:util";import{readFileSync as Kp,readdirSync as Gr,statSync as Oi,openSync as Xp,readSync as Qp,closeSync as Zp}from"node:fs";import{join as jt}from"node:path";import{homedir as Yl}from"node:os";async function em(){try{if(process.platform==="darwin"){let{stdout:n}=await Vl("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=Kp(jt(Yl(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function tm(){let n=await em();if(!n)return null;try{let{stdout:e}=await Vl("curl",["-s","--max-time","10","-H",`Authorization: Bearer ${n}`,"-H","anthropic-beta: oauth-2025-04-20","https://api.anthropic.com/api/oauth/usage"]),t=JSON.parse(e);return typeof t.five_hour?.utilization!="number"?null:{five_hour_pct:t.five_hour.utilization,seven_day_pct:t.seven_day?.utilization??0,five_hour_resets_at:t.five_hour.resets_at??null,seven_day_resets_at:t.seven_day?.resets_at??null}}catch{return null}}function nm(n,e){let t=[];try{for(let r of Gr(n).sort().reverse().slice(0,2)){let s=jt(n,r);for(let i of Gr(s).sort().reverse().slice(0,2)){let o=jt(s,i);for(let a of Gr(o).sort().reverse().slice(0,7)){let c=jt(o,a);for(let d of Gr(c)){if(!d.endsWith(".jsonl"))continue;let l=jt(c,d);try{t.push({path:l,mtime:Oi(l).mtimeMs})}catch{}}}if(t.length>=e*4)break}if(t.length>=e*4)break}}catch{}return t.sort((r,s)=>s.mtime-r.mtime).slice(0,e).map(r=>r.path)}function rm(n,e){let t=Xp(n,"r");try{let r=Oi(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return Qp(t,i,0,s,r-s),i.toString("utf-8")}finally{Zp(t)}}function sm(){let n=process.env.CODEX_HOME??jt(Yl(),".codex");for(let e of nm(jt(n,"sessions"),5))try{let t=rm(e,262144).split(`
|
|
211
211
|
`).filter(r=>r.includes('"rate_limits"'));for(let r=t.length-1;r>=0;r--)try{let s=JSON.parse(t[r]),i=s.payload?.rate_limits;if(!i?.primary)continue;let o=a=>a?new Date(a*1e3).toISOString():null;return{five_hour_pct:i.primary.used_percent??0,seven_day_pct:i.secondary?.used_percent??0,five_hour_resets_at:o(i.primary.resets_at),seven_day_resets_at:o(i.secondary?.resets_at),plan:i.plan_type??null,observed_at:s.timestamp??new Date(Oi(e).mtimeMs).toISOString()}}catch{}}catch{}return null}async function zl(){let[n,e]=await Promise.all([tm(),Promise.resolve().then(sm)]);return{sampled_at:new Date().toISOString(),claude:n,codex:e}}var Vl,Kl=O(()=>{"use strict";Vl=zp(Vp)});var Ct,Xl,Wr,Ql=O(()=>{"use strict";le();Ct="sessionManager",Xl=3e4,Wr=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},Xl),h("info",Ct,`Heartbeat timer started (every ${Xl/1e3}s)`))}async stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);let e=[...this.sessions.values()].filter(t=>t.status!=="completed"&&t.status!=="failed");await Promise.all(e.map(t=>this.updateStatus(t.sessionId,"disconnected").catch(r=>{k(Ct,`Failed to mark session ${t.sessionId} disconnected`,r)}))),h("info",Ct,`SessionManager stopped, ${e.length} sessions marked disconnected`)}async createSession(e){let r={sessionId:(await this.gateway.createSession(e)).id,workroomId:e,status:"idle"};return this.sessions.set(r.sessionId,r),h("info",Ct,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){h("warn",Ct,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,h("info",Ct,"Session status updated",{sessionId:e,status:t})}getSession(e){return this.sessions.get(e)}getAllSessions(){return[...this.sessions.values()]}async _sendHeartbeats(){let e=[...this.sessions.values()].filter(t=>t.status!=="completed"&&t.status!=="failed"&&t.status!=="disconnected");await Promise.all(e.map(t=>this.gateway.sessionHeartbeat(t.sessionId).catch(r=>{k(Ct,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&h("debug",Ct,`Sent ${e.length} heartbeat(s)`)}}});var mt,jr,Zl=O(()=>{"use strict";le();mt="workroomCoordinator",jr=class{constructor(e,t){this.sessionManager=e;this.actionGate=t}sessionManager;actionGate;workroomRegistry=new Map;shuttingDown=!1;async openWorkroom(e){if(this.shuttingDown)return h("warn",mt,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return h("info",mt,"openWorkroom: workroom already open \u2014 reusing session",{workroomId:e,sessionId:t.sessionId}),t;let r;try{r=await this.sessionManager.createSession(e)}catch(s){return k(mt,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return k(mt,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{k(mt,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),h("info",mt,"workroom opened successfully",{workroomId:e,sessionId:r.sessionId,openCount:this.workroomRegistry.size}),r}shutdownAll(){this.shuttingDown=!0;for(let e of this.workroomRegistry.keys())try{this.actionGate.deregisterWorkroom(e),h("info",mt,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){k(mt,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),h("info",mt,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as Ii,unlink as im,readdir as om,stat as am}from"fs/promises";import{join as Jr}from"path";import{randomBytes as Ni}from"crypto";async function td(n,e){let t=Ni(8).toString("hex"),r=Jr(Nt,`action-${n}-${t}${ed}`),s;try{s=await Ii(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return h("info",yt,"secret file written",{actionId:n,filePath:r}),r}async function jn(n){try{await im(n),h("info",yt,"secret file deleted",{filePath:n})}catch(e){if(Pi(e))return;k(yt,"failed to delete secret file (best-effort)",e)}}async function nd(){let n;try{n=await om(Nt)}catch(s){if(Pi(s))return;k(yt,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(ed)),r=0;for(let s of t){let i=Jr(Nt,s);try{let o=await am(i),a=e-o.mtimeMs;a>=cm&&(await jn(i),r++,h("info",yt,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(Pi(o))continue;k(yt,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&h("info",yt,"TTL scan complete",{scanned:t.length,purged:r})}async function rd(n){let e=Date.now(),t=Ni(4).toString("hex"),r=Jr(Nt,`drain-evidence-${e}-${t}.json`),s;try{s=await Ii(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",yt,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function sd(n){let e=Date.now(),t=Ni(4).toString("hex"),r=Jr(Nt,`response-lost-${e}-${t}.json`),s;try{s=await Ii(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",yt,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function Pi(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var yt,cm,ed,Yr=O(()=>{"use strict";Je();le();yt="secretManager",cm=600*1e3,ed=".secret"});import{spawn as lm}from"child_process";import{stat as dm}from"fs/promises";async function id(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return h("warn",Jt,"no enabled runtime found for kind",{kind:n.kind,actionId:n.actionId,availableKinds:n.runtimes.map(i=>i.kind)}),{ok:!1,reason_code:"RUNTIME_NOT_FOUND"};try{await dm(e.path)}catch{return h("warn",Jt,"runtime binary not accessible",{kind:n.kind,actionId:n.actionId}),{ok:!1,reason_code:"RUNTIME_NOT_FOUND"}}let t={PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,TMPDIR:process.env.TMPDIR,LANG:process.env.LANG,MIO_ACTION_ID:n.actionId,MIO_SESSION_ID:n.sessionId,MIO_WORKROOM_ID:n.workroomId,MIO_ACTION_KIND:n.kind,MIO_IPC_SOCKET:n.ipcSocketPath,...n.serverUrl?{MIO_SERVER_URL:n.serverUrl}:{},MIO_RUNTIME_MODE:n.mode??"controlled-delegated",...process.env.MIO_CLAUDE_CONFIG_DIR?{MIO_CLAUDE_CONFIG_DIR:process.env.MIO_CLAUDE_CONFIG_DIR}:{}},r;if(n.secretContent)try{r=await td(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return k(Jt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=lm(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return k(Jt,"spawn failed",i),r&&jn(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{h("info",Jt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&jn(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{k(Jt,"subprocess error after spawn",i),r&&jn(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),h("info",Jt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var Jt,od=O(()=>{"use strict";le();Yr();Jt="runtimeAdapter"});var q,ad,Jn,cd,Yn,ld,um,Vr,Mi=O(()=>{"use strict";dr();le();od();Yr();q="actionGate",ad=new Set(["proposed","approved"]),Jn=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),cd="irreversible_no_abort",Yn=new Set(["transmission_complete","succeeded","canceled","failed"]),ld=15,um=8e3,Vr=class{constructor(e,t={runtimes:[],ipcSocketPath:""}){this.gateway=e;this.gateConfig=t;this.boundHandler=r=>this._handleEvent(r)}gateway;gateConfig;pendingApproval=new Map;_shuttingDown=!1;inFlightIrreversible=new Map;drainResolve=null;drainTimeoutId=null;boundHandler;registerWorkroom(e){this.gateway.subscribe(e,this.boundHandler),h("info",q,"registered for workroom",{workroomId:e})}deregisterWorkroom(e){this.gateway.unsubscribe(e,this.boundHandler);for(let[t,r]of this.pendingApproval)r===e&&this.pendingApproval.delete(t);h("info",q,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,h("info",q,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=um){if(this.inFlightIrreversible.size===0){h("info",q,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return h("warn",q,"SIGTERM with irreversible_no_abort actions in flight \u2014 bounded drain started",{count:this.inFlightIrreversible.size,actionIds:t,deadlineMs:e}),new Promise(r=>{this.drainResolve=r,this.drainTimeoutId=setTimeout(async()=>{this.drainResolve=null,this.drainTimeoutId=null;let s=new Map(this.inFlightIrreversible);k(q,"drainIrreversible: DEADLINE reached \u2014 actions did not confirm transmission_complete; writing evidence before shutdown",{remainingCount:s.size,remainingActionIds:[...s.keys()],deadlineMs:e});try{let i=await rd({schema_version:1,drain_timeout_ms:e,shutdown_at:new Date().toISOString(),action_ids:[...s.keys()],actions:Object.fromEntries([...s.entries()].map(([o,a])=>[o,{workroom_id:a.workroomId,session_id:a.sessionId,fired_at:a.firedAt.toISOString()}])),operator_note:"Daemon shut down while irreversible_no_abort actions were in flight. Server-side status is unknown. Verify each action_id on the server before restarting the daemon.",server_todo:'Server reconcile endpoint implemented (Phase 5C). POST /api/v1/actions/:id/reconcile with { reason: "drain_deadline_exceeded", evidence_id: "<this-file-uuid>" } for each action_id. Auth: machine_token bearer. TODO (daemon auto-POST): daemon does not yet auto-scan evidence files on startup. Remove this file after reconcile confirms needs_human status.'});h("info",q,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){k(q,"drainIrreversible: failed to write evidence file \u2014 action states unknown (CRITICAL)",i)}r()},e)})}onIpcMessage(e){if(e.type!=="status_changed")return;let t=e.action_id,r=e.status;!t||!r||this.inFlightIrreversible.has(t)&&Yn.has(r)&&this.gateway.getAction(t).then(s=>{Yn.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):h("warn",q,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{k(q,"onIpcMessage: failed to re-query action \u2014 keeping in drain",s)})}_registerInFlight(e){this.inFlightIrreversible.set(e.action_id,{workroomId:e.workroom_id,sessionId:e.session_id,firedAt:new Date}),h("info",q,"registered in-flight irreversible action",{actionId:e.action_id,workroomId:e.workroom_id,inFlightCount:this.inFlightIrreversible.size})}_deregisterInFlight(e,t){this.inFlightIrreversible.has(e)&&(this.inFlightIrreversible.delete(e),h("info",q,"deregistered in-flight irreversible action",{actionId:e,source:t,remainingCount:this.inFlightIrreversible.size}),this._checkDrainComplete())}_checkDrainComplete(){if(this.inFlightIrreversible.size===0&&this.drainResolve!==null){h("info",q,"drainIrreversible: all in-flight actions drained \u2014 resolving"),this.drainTimeoutId!==null&&(clearTimeout(this.drainTimeoutId),this.drainTimeoutId=null);let e=this.drainResolve;this.drainResolve=null,e()}}_onSubprocessExitForDrain(e,t,r){this.inFlightIrreversible.has(e)&&this.gateway.getAction(e).then(s=>{Yn.has(s.status)?(h("info",q,"subprocess exit: action confirmed drain-complete \u2014 deregistering",{actionId:e,exitCode:t,exitSignal:r,serverStatus:s.status}),this._deregisterInFlight(e,`subprocess_exit:${s.status}`)):h("warn",q,"subprocess exit: action not yet drain-complete \u2014 awaiting WS/IPC signal or drain deadline",{actionId:e,exitCode:t,exitSignal:r,serverStatus:s.status,note:"subprocess may have sent output; server may still be processing"})}).catch(s=>{k(q,"subprocess exit: failed to re-query action \u2014 keeping in drain (conservative)",s)})}async _handleEvent(e){let{topic:t,payload:r}=e;try{t==="action.created"?await this._onActionCreated(r):t==="approval.decided"?await this._onApprovalDecided(r):t==="action.status_changed"&&await this._onActionStatusChanged(r)}catch(s){k(q,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){h("info",q,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){h("warn",q,"action.created: missing action_id in payload \u2014 ignoring");return}h("info",q,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(Jn.has(r.status)){h("info",q,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!ad.has(r.status)){h("info",q,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===cd?await this._handleIrreversible(r):await this._fireAndSpawn(r)}async _handleIrreversible(e){let{action_id:t,workroom_id:r,approval_id:s}=e;if(s){let i=await this.gateway.getApproval(s),o=i.expires_at!==null&&new Date(i.expires_at)<=new Date;if(i.status==="approved"&&!i.consumed&&!o){h("info",q,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&h("info",q,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),h("info",q,"irreversible_no_abort \u2014 awaiting approval decision",{actionId:t,workroomId:r,pendingCount:this.pendingApproval.size})}async _onApprovalDecided(e){let t=e.approval_id,r=e.action_id,s=e.decision;if(!t||!r){h("warn",q,"approval.decided: missing required fields \u2014 ignoring");return}if(h("info",q,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),h("info",q,"approval not approved \u2014 clearing pending watch",{actionId:r,decision:s});return}let[i,o]=await Promise.all([this.gateway.getAction(r),this.gateway.getApproval(t)]);if(this.pendingApproval.delete(r),Jn.has(i.status)){h("info",q,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!ad.has(i.status)){h("warn",q,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){h("warn",q,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){h("warn",q,"approval already consumed \u2014 abort fire (anti-replay)",{approvalId:t});return}if(o.expires_at!==null&&new Date(o.expires_at)<=new Date){h("warn",q,"approval past expiresAt \u2014 aborting fire (server CAS would also reject)",{approvalId:t,expires_at:o.expires_at});return}await this._fireAndSpawn(i,t)}async _onActionStatusChanged(e){let t=e.action_id,r=e.status;if(!t||!r)return;let s=this.pendingApproval.has(t),i=this.inFlightIrreversible.has(t);if(!s&&!i)return;let o=s&&Jn.has(r),a=i&&Yn.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&Jn.has(c.status)&&(this.pendingApproval.delete(t),h("info",q,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&Yn.has(c.status)&&this._deregisterInFlight(t,`ws_status_changed:${c.status}`))}async _fireAndSpawn(e,t){let{action_id:r,session_id:s,workroom_id:i}=e;h("info",q,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let l=await this.gateway.fireAction(r,t);h("info",q,"action fired",{actionId:r,fired_at:l.fired_at}),a=l.action_token,o=!0}catch(l){if(l instanceof En&&l.isDefinitiveRejection){k(q,`fire definitively rejected (${l.statusCode} ${l.errorCode}) \u2014 re-querying before cancel`,l);let m=await this.gateway.getAction(r).catch(()=>null);if(!m||Jn.has(m.status)){h("info",q,"action already in non-cancelable state after rejected fire \u2014 skipping cancel (concurrent winner?)",{actionId:r,currentStatus:m?.status});return}await this.gateway.cancelAction(r).catch(f=>{k(q,"cancel after rejected fire also failed",f)});return}k(q,"fire failed with uncertain error \u2014 reconciling action state",l);let u=await this.gateway.getAction(r).catch(()=>null);if(u?.status==="fired"){h("warn",q,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let m=u.fired_at??new Date().toISOString();await sd({schema_version:1,reason:"fire_response_lost_token_unrecoverable",action_id:r,workroom_id:i,session_id:s,fired_at:m,operator_note:"The fire HTTP response was lost before the action_token was received. The raw token is unrecoverable (server stores only hash). The subprocess was NOT spawned. Verify action status on the server manually.",server_todo:'Server reconcile endpoint implemented (Phase 5C). POST /api/v1/actions/:id/reconcile with { reason: "fire_response_lost_token_unrecoverable", evidence_id: "<this-file-uuid>" }. Auth: machine_token bearer. Remove this file after reconcile confirms needs_human status.'}).catch(f=>{k(q,"failed to write response-lost evidence (CRITICAL)",f)});return}else{h("warn",q,"reconcile: fire outcome uncertain \u2014 halting without cancel or spawn",{actionId:r,reconciledStatus:u?.status??"fetch-failed"});return}}if(!o)return;let c=e.reversibility===cd;c&&this._registerInFlight(e);let d=await id({actionId:r,sessionId:s,workroomId:i,kind:e.kind,reversibility:e.reversibility,runtimes:this.gateConfig.runtimes,ipcSocketPath:this.gateConfig.ipcSocketPath,secretContent:a,serverUrl:this.gateConfig.serverUrl,onSubprocessExit:c?(l,u)=>this._onSubprocessExitForDrain(r,l,u):void 0});d.ok||(h("warn",q,"spawn returned not-ok",{actionId:r,reason_code:d.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as fm}from"net";import{chmod as hm}from"fs/promises";var rt,zr,dd=O(()=>{"use strict";le();rt="ipcServer",zr=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=fm(s=>{this._handleConnection(s)}),this.server.once("error",s=>{k(rt,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await hm(e,384)}catch(s){k(rt,"Failed to chmod IPC socket",s)}h("info",rt,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",rt,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){h("debug",rt,"subprocess connected");let t="";e.on("data",r=>{t+=r.toString("utf8");let s=t.split(`
|
|
212
212
|
`);t=s.pop()??"";for(let i of s){let o=i.trim();o&&this._processLine(o)}}),e.on("error",r=>{k(rt,"IPC socket connection error",r)}),e.on("close",()=>{h("debug",rt,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{h("warn",rt,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){h("warn",rt,"IPC message missing required `type` field \u2014 ignored");return}h("debug",rt,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as gm}from"http";var Li,pm,mm,Kr,ud=O(()=>{"use strict";le();Li="healthServer",pm="127.0.0.1",mm=7878,Kr=class{constructor(e){this.version=e}version;server=null;startTime=Date.now();async listen(e=pm,t=mm){return new Promise((r,s)=>{this.server=gm((i,o)=>this._handleRequest(i,o)),this.server.once("error",i=>{k(Li,"Health server startup error",i),s(i)}),this.server.listen(t,e,()=>{h("info",Li,`Health server listening on ${e}:${t}`),r()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",Li,"Health server stopped"),e()}),this.server=null})}_handleRequest(e,t){if(e.method==="GET"&&e.url==="/health"){let r={status:"ok",version:this.version,pid:process.pid,uptime_sec:Math.floor((Date.now()-this.startTime)/1e3)},s=JSON.stringify(r);t.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(s)}),t.end(s)}else t.writeHead(404),t.end()}}});import{appendFile as fd,mkdir as hd}from"node:fs/promises";import{homedir as ym}from"node:os";import{dirname as _m,join as gd}from"node:path";function wm(){return Xr||(Xr=hd(pd,{recursive:!0}).then(()=>{},n=>{throw Xr=null,n})),Xr}function Qr(n){return n&&n.replace(/-/g,"").slice(0,8)||"unknown"}function vm(n){return gd(pd,`agent-${Qr(n)}.jsonl`)}function ee(n,e,t){let r;try{let i={ts:new Date().toISOString(),agent_id:n,kind:e,...t};r=JSON.stringify(i)+`
|
|
213
213
|
`}catch(i){process.stderr.write(`[agentTrace] serialize error agent=${Qr(n)} kind=${e}: ${i.message}
|
|
214
214
|
`);return}let s=vm(n);wm().then(()=>fd(s,r,{encoding:"utf8"})).catch(i=>{if(i.code==="ENOENT"){let o=_m(s);hd(o,{recursive:!0}).then(()=>fd(s,r,{encoding:"utf8"})).catch(a=>{process.stderr.write(`[agentTrace] append failed agent=${Qr(n)} kind=${e}: ${a.message}
|
|
215
215
|
`)});return}process.stderr.write(`[agentTrace] append failed agent=${Qr(n)} kind=${e}: ${i.message}
|
|
216
|
-
`)})}var pd,Xr,Rt=O(()=>{"use strict";pd=gd(ym(),".mio","logs"),Xr=null});import{readFileSync as bm,writeFileSync as km,existsSync as Sm}from"fs";import{join as Em}from"path";function md(){return Em(ge,"agent-inbox-cursor.json")}function yd(){let n=md();if(!Sm(n))return{};try{return JSON.parse(bm(n,"utf-8"))}catch{return{}}}function xm(n){Sn(),km(md(),JSON.stringify(n,null,2),{mode:384})}function _d(n,e){return yd()[`${n}:${e}`]??"0"}function _t(n,e,t){let r=yd(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,xm(r))}var $i=O(()=>{"use strict";Je()});import{createServer as Tm}from"http";import{randomBytes as Cm,timingSafeEqual as Rm}from"crypto";function Oe(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Nm(n,e){return new Promise((t,r)=>{let s=[],i=0;n.on("data",o=>{if(i+=o.length,i>e){n.destroy(),r(new Zr);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function Mm(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Rm(t,r)}async function xe(n,e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{return await fetch(n,{...e,signal:r.signal})}finally{clearTimeout(s)}}async function wd(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??Pm,c=i instanceof Set?i:new Set(i),d=Cm(32).toString("hex");async function l(p,y){if(p.method!=="POST"||p.url!=="/act"){y.writeHead(404),y.end();return}let S=p.headers.authorization??"",v=`Bearer ${d}`;if(!Mm(S,v)){Oe(y,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let w;try{w=await Nm(p,Om)}catch(W){if(W instanceof Zr){Oe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Oe(y,400,{ok:!1,code:"INVALID_JSON"});return}let b;try{b=JSON.parse(w)}catch{Oe(y,400,{ok:!1,code:"INVALID_JSON"});return}let P=b.action,x=b.payload!=null&&typeof b.payload=="object"?b.payload:{};if(P!=="attachment"&&Buffer.byteLength(w)>Am){Oe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(P)){Oe(y,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let N=Im[P];if(!c.has(N)){Oe(y,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let G={Authorization:`Bearer ${s}`,"X-Perf-Caller-Context":"agent_originated","X-Mio-Agent-Id":e,"Content-Type":"application/json"},J=Date.now();try{if(P==="send"){let W=x,Q=null;if(o)try{let M=o.get(e);M&&typeof x.context_message_id!="string"&&(W={...x,context_message_id:M},Q=M)}catch(M){k(At,"contextTracker.get threw (non-fatal)",M)}let ne=typeof x.target=="string"?x.target:null,H=typeof x.parent_message_id=="string"?x.parent_message_id:null,ie=typeof x.content=="string"?x.content.slice(0,120):null;h("info",At,"forward send",{agentId:e,target:ne,parent_message_id:H,stamped_context:Q!==null,context_message_id:Q}),ee(e,"outbound",{action:"send",target:ne,parent_message_id:H,context_message_id:Q,context_message_id_short:Q?Q.replace(/-/g,"").slice(0,8):null,content_preview:ie,content_bytes:typeof x.content=="string"?x.content.length:0}),await Lm(y,r,G,W,a),ee(e,"outbound_done",{action:"send",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="reply"){let W=typeof x.target=="string"?x.target:null,Q=typeof x.parent_message_id=="string"?x.parent_message_id:null,ne=typeof x.content=="string"?x.content.slice(0,120):null;ee(e,"outbound",{action:"reply",target:W,parent_message_id:Q,parent_message_id_short:Q?Q.replace(/-/g,"").slice(0,8):null,content_preview:ne}),await $m(y,r,G,x,a),ee(e,"outbound_done",{action:"reply",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="history")await Dm(y,r,G,x,a);else if(P==="task"){let W=typeof x.op=="string"?x.op:null;ee(e,"task",{action:W,task_id:typeof x.task_id=="string"?x.task_id:null,number:typeof x.number=="number"?x.number:null,title:typeof x.title=="string"?x.title.slice(0,200):null,status:typeof x.status=="string"?x.status:null,channel:typeof x.channel=="string"?x.channel:null}),await Fm(y,r,G,x,a),ee(e,"task_done",{action:W,status:y.statusCode,duration_ms:Date.now()-J})}else P==="reminder"?await Hm(y,r,G,x,a):P==="action"?await Gm(y,r,G,x,a):P==="react"?await Wm(y,r,G,x,a):P==="attachment"?await jm(y,r,G,x,a):P==="profile"?await Jm(y,r,G,x,a):await Ym(y,r,G,e,x,a)}catch(W){k(At,"upstream forwarding error",W);let Q=W instanceof Error&&W.name==="AbortError";Oe(y,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:Q?`upstream timed out after ${a}ms`:String(W)})}}let u=Tm((p,y)=>{l(p,y).catch(S=>{k(At,"unhandled request error",S),y.writeHead(500),y.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((p,y)=>{u.once("error",S=>{k(At,"agent proxy startup error",S),y(S)}),u.listen(0,"127.0.0.1",()=>{let S=u.address(),v=typeof S=="object"&&S?S.port:0;h("info",At,"agent proxy listening",{agentId:e,launchId:t,port:v}),p(v)})})}`,proxyToken:d,close:()=>new Promise(p=>{u.close(()=>{h("info",At,"agent proxy stopped",{agentId:e,launchId:t}),p()})})}}async function Lm(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function $m(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function Dm(n,e,t,r,s){let i=Vm(r),o=await xe(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Te(n,o)}async function Fm(n,e,t,r,s){let i=String(r.op??""),o=Bm[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_TASK_OP",message:`Unknown task op: ${i}`});return}let a=`${e}/internal/agent-api/tasks/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await xe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Te(n,l)}else{let{op:c,...d}=r,l=await xe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Te(n,l)}}async function Hm(n,e,t,r,s){let i=String(r.op??""),o=Um[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_REMINDER_OP",message:`Unknown reminder op: ${i}`});return}let a=`${e}/internal/agent-api/reminders/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await xe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Te(n,l)}else{let{op:c,...d}=r,l=await xe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Te(n,l)}}async function Gm(n,e,t,r,s){let i=String(r.op??""),o=qm[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_ACTION_OP",message:`Unknown action op: ${i}`});return}let a=`${e}/internal/agent-api/actions/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await xe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Te(n,l)}else{let{op:c,...d}=r,l=await xe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Te(n,l)}}async function Wm(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function jm(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await xe(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Te(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await xe(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Te(n,a);return}Oe(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function Jm(n,e,t,r,s){let i=String(r.op??"");if(i==="show"){let o=`${e}/internal/agent-api/profile`,a=r.handle,c=a!==void 0?`${o}?handle=${encodeURIComponent(String(a))}`:o,d=await xe(c,{method:"GET",headers:t},s);await Te(n,d);return}if(i==="update"){let{op:o,...a}=r,c=await xe(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Te(n,c);return}Oe(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function Ym(n,e,t,r,s,i){let o=String(s.channel??""),a=_d(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),d=await xe(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!d.ok){await Te(n,d);return}let l=await d.json(),u=l.messages??[];if(u.length>0){let f=u.reduce((g,p)=>{let y=0n;try{y=BigInt(String(p.seq??"0"))}catch{k(At,"bad seq from upstream",{seq:p.seq}),y=0n}return y>g?y:g},0n);f>0n&&_t(r,o,f.toString())}let m=JSON.stringify(l);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Te(n,e){if(e.ok){let i=await e.text();n.writeHead(e.status,{"Content-Type":"application/json"}),n.end(i);return}let t=await e.text().catch(()=>""),r=e.status>=500?"SERVER_5XX":"UPSTREAM_ERROR",s=t;try{let i=JSON.parse(t);r=i?.error?.code??r,s=i?.error?.message??s}catch{}Oe(n,e.status,{ok:!1,code:r,message:s})}function Vm(n){let e=new URLSearchParams;n.channel!==void 0&&e.set("channel",String(n.channel)),n.after_seq!==void 0&&e.set("after_seq",String(n.after_seq)),n.limit!==void 0&&e.set("limit",String(n.limit)),n.around!==void 0&&e.set("around",String(n.around));let t=e.toString();return t?`?${t}`:""}var At,Am,Om,Pm,Im,Zr,Bm,Um,qm,vd=O(()=>{"use strict";le();Rt();$i();At="agentProxy",Am=1024*1024,Om=12*1024*1024,Pm=15e3,Im={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};Zr=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};Bm={list:{method:"GET",path:"list"},create:{method:"POST",path:"create"},claim:{method:"POST",path:"claim"},unclaim:{method:"POST",path:"unclaim"},update:{method:"POST",path:"update-status"},review:{method:"POST",path:"review"}};Um={schedule:{method:"POST",path:"schedule"},list:{method:"GET",path:"list"},snooze:{method:"POST",path:"snooze"},update:{method:"POST",path:"update"},cancel:{method:"POST",path:"cancel"},log:{method:"GET",path:"log"}};qm={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as bd,writeFile as Di,chmod as kd}from"fs/promises";import{existsSync as Sd}from"fs";import{join as Vn,resolve as zm,dirname as Km}from"path";import{spawnSync as Xm}from"child_process";import{fileURLToPath as Qm}from"url";function zn(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Ot(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function Zm(n){let e=Km(Qm(import.meta.url))+"/../..",t=n?.localTsxPath??zm(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Sd(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??ey)();return i||"tsx"}function ey(){let e=Xm("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Sd(e)?e:null}function Bi(n){let e=n!==void 0?n.execPath:process.execPath,t=n!==void 0?n.argv1:process.argv[1];return t===void 0||t===e?{mode:"sea",seaBinaryPath:e}:t.endsWith(".ts")?{mode:"tsx-source",tsxPath:Zm(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function Ed(n){let{agentId:e,launchId:t,workingDirectory:r,serverUrl:s,machineToken:i,capabilities:o=["send","read","tasks","reminders","actions","reactions","attachments","profile"]}=n,a=n.execContext??Bi(),c=Vn(r,".mio");await bd(c,{recursive:!0,mode:493});let d=await wd({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:l,proxyToken:u}=d;try{let m=zn(e),f=zn(t),g=Vn(ge,"agent-proxy-tokens",m),p=Vn(g,`${f}.token`);await bd(g,{recursive:!0,mode:448}),await Di(p,u,{encoding:"utf8",mode:384}),await kd(p,384);let y=o.join(","),S=ty({execContext:a,proxyUrl:l,tokenFile:p,capabilityStr:y}),v=Vn(c,"mio");await Di(v,S,{encoding:"utf8",mode:493}),await kd(v,493),await Di(Vn(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let w={...process.env},b=w.PATH??"";return w.PATH=b?`${c}:${b}`:c,delete w.CLAUDECODE,{mioDir:c,spawnEnv:w,proxyHandle:d}}catch(m){throw await d.close().catch(()=>{}),m}}function ty(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${Ot(t)} MIO_AGENT_PROXY_TOKEN_FILE=${Ot(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${Ot(s)}`,o;return e.mode==="npm"?o=`exec ${Ot(e.nodePath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${Ot(e.tsxPath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:o=`exec ${Ot(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
|
|
216
|
+
`)})}var pd,Xr,Rt=O(()=>{"use strict";pd=gd(ym(),".mio","logs"),Xr=null});import{readFileSync as bm,writeFileSync as km,existsSync as Sm}from"fs";import{join as Em}from"path";function md(){return Em(ge,"agent-inbox-cursor.json")}function yd(){let n=md();if(!Sm(n))return{};try{return JSON.parse(bm(n,"utf-8"))}catch{return{}}}function xm(n){Sn(),km(md(),JSON.stringify(n,null,2),{mode:384})}function _d(n,e){return yd()[`${n}:${e}`]??"0"}function _t(n,e,t){let r=yd(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,xm(r))}var $i=O(()=>{"use strict";Je()});import{createServer as Tm}from"http";import{randomBytes as Cm,timingSafeEqual as Rm}from"crypto";function Oe(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Nm(n,e){return new Promise((t,r)=>{let s=[],i=0;n.on("data",o=>{if(i+=o.length,i>e){n.destroy(),r(new Zr);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function Mm(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Rm(t,r)}async function xe(n,e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{return await fetch(n,{...e,signal:r.signal})}finally{clearTimeout(s)}}async function wd(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??Pm,c=i instanceof Set?i:new Set(i),d=Cm(32).toString("hex");async function l(g,y){if(g.method!=="POST"||g.url!=="/act"){y.writeHead(404),y.end();return}let S=g.headers.authorization??"",v=`Bearer ${d}`;if(!Mm(S,v)){Oe(y,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let _;try{_=await Nm(g,Om)}catch(W){if(W instanceof Zr){Oe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Oe(y,400,{ok:!1,code:"INVALID_JSON"});return}let b;try{b=JSON.parse(_)}catch{Oe(y,400,{ok:!1,code:"INVALID_JSON"});return}let P=b.action,x=b.payload!=null&&typeof b.payload=="object"?b.payload:{};if(P!=="attachment"&&Buffer.byteLength(_)>Am){Oe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(P)){Oe(y,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let N=Im[P];if(!c.has(N)){Oe(y,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let G={Authorization:`Bearer ${s}`,"X-Perf-Caller-Context":"agent_originated","X-Mio-Agent-Id":e,"Content-Type":"application/json"},J=Date.now();try{if(P==="send"){let W=x,Q=null;if(o)try{let M=o.get(e);M&&typeof x.context_message_id!="string"&&(W={...x,context_message_id:M},Q=M)}catch(M){k(At,"contextTracker.get threw (non-fatal)",M)}let ne=typeof x.target=="string"?x.target:null,H=typeof x.parent_message_id=="string"?x.parent_message_id:null,ie=typeof x.content=="string"?x.content.slice(0,120):null;h("info",At,"forward send",{agentId:e,target:ne,parent_message_id:H,stamped_context:Q!==null,context_message_id:Q}),ee(e,"outbound",{action:"send",target:ne,parent_message_id:H,context_message_id:Q,context_message_id_short:Q?Q.replace(/-/g,"").slice(0,8):null,content_preview:ie,content_bytes:typeof x.content=="string"?x.content.length:0}),await Lm(y,r,G,W,a),ee(e,"outbound_done",{action:"send",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="reply"){let W=typeof x.target=="string"?x.target:null,Q=typeof x.parent_message_id=="string"?x.parent_message_id:null,ne=typeof x.content=="string"?x.content.slice(0,120):null;ee(e,"outbound",{action:"reply",target:W,parent_message_id:Q,parent_message_id_short:Q?Q.replace(/-/g,"").slice(0,8):null,content_preview:ne}),await $m(y,r,G,x,a),ee(e,"outbound_done",{action:"reply",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="history")await Dm(y,r,G,x,a);else if(P==="task"){let W=typeof x.op=="string"?x.op:null;ee(e,"task",{action:W,task_id:typeof x.task_id=="string"?x.task_id:null,number:typeof x.number=="number"?x.number:null,title:typeof x.title=="string"?x.title.slice(0,200):null,status:typeof x.status=="string"?x.status:null,channel:typeof x.channel=="string"?x.channel:null}),await Fm(y,r,G,x,a),ee(e,"task_done",{action:W,status:y.statusCode,duration_ms:Date.now()-J})}else P==="reminder"?await Hm(y,r,G,x,a):P==="action"?await Gm(y,r,G,x,a):P==="react"?await Wm(y,r,G,x,a):P==="attachment"?await jm(y,r,G,x,a):P==="profile"?await Jm(y,r,G,x,a):await Ym(y,r,G,e,x,a)}catch(W){k(At,"upstream forwarding error",W);let Q=W instanceof Error&&W.name==="AbortError";Oe(y,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:Q?`upstream timed out after ${a}ms`:String(W)})}}let u=Tm((g,y)=>{l(g,y).catch(S=>{k(At,"unhandled request error",S),y.writeHead(500),y.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((g,y)=>{u.once("error",S=>{k(At,"agent proxy startup error",S),y(S)}),u.listen(0,"127.0.0.1",()=>{let S=u.address(),v=typeof S=="object"&&S?S.port:0;h("info",At,"agent proxy listening",{agentId:e,launchId:t,port:v}),g(v)})})}`,proxyToken:d,close:()=>new Promise(g=>{u.close(()=>{h("info",At,"agent proxy stopped",{agentId:e,launchId:t}),g()})})}}async function Lm(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function $m(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function Dm(n,e,t,r,s){let i=Vm(r),o=await xe(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Te(n,o)}async function Fm(n,e,t,r,s){let i=String(r.op??""),o=Bm[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_TASK_OP",message:`Unknown task op: ${i}`});return}let a=`${e}/internal/agent-api/tasks/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await xe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Te(n,l)}else{let{op:c,...d}=r,l=await xe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Te(n,l)}}async function Hm(n,e,t,r,s){let i=String(r.op??""),o=Um[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_REMINDER_OP",message:`Unknown reminder op: ${i}`});return}let a=`${e}/internal/agent-api/reminders/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await xe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Te(n,l)}else{let{op:c,...d}=r,l=await xe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Te(n,l)}}async function Gm(n,e,t,r,s){let i=String(r.op??""),o=qm[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_ACTION_OP",message:`Unknown action op: ${i}`});return}let a=`${e}/internal/agent-api/actions/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await xe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Te(n,l)}else{let{op:c,...d}=r,l=await xe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Te(n,l)}}async function Wm(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function jm(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await xe(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Te(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await xe(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Te(n,a);return}Oe(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function Jm(n,e,t,r,s){let i=String(r.op??"");if(i==="show"){let o=`${e}/internal/agent-api/profile`,a=r.handle,c=a!==void 0?`${o}?handle=${encodeURIComponent(String(a))}`:o,d=await xe(c,{method:"GET",headers:t},s);await Te(n,d);return}if(i==="update"){let{op:o,...a}=r,c=await xe(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Te(n,c);return}Oe(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function Ym(n,e,t,r,s,i){let o=String(s.channel??""),a=_d(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),d=await xe(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!d.ok){await Te(n,d);return}let l=await d.json(),u=l.messages??[];if(u.length>0){let f=u.reduce((p,g)=>{let y=0n;try{y=BigInt(String(g.seq??"0"))}catch{k(At,"bad seq from upstream",{seq:g.seq}),y=0n}return y>p?y:p},0n);f>0n&&_t(r,o,f.toString())}let m=JSON.stringify(l);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Te(n,e){if(e.ok){let i=await e.text();n.writeHead(e.status,{"Content-Type":"application/json"}),n.end(i);return}let t=await e.text().catch(()=>""),r=e.status>=500?"SERVER_5XX":"UPSTREAM_ERROR",s=t;try{let i=JSON.parse(t);r=i?.error?.code??r,s=i?.error?.message??s}catch{}Oe(n,e.status,{ok:!1,code:r,message:s})}function Vm(n){let e=new URLSearchParams;n.channel!==void 0&&e.set("channel",String(n.channel)),n.after_seq!==void 0&&e.set("after_seq",String(n.after_seq)),n.limit!==void 0&&e.set("limit",String(n.limit)),n.around!==void 0&&e.set("around",String(n.around));let t=e.toString();return t?`?${t}`:""}var At,Am,Om,Pm,Im,Zr,Bm,Um,qm,vd=O(()=>{"use strict";le();Rt();$i();At="agentProxy",Am=1024*1024,Om=12*1024*1024,Pm=15e3,Im={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};Zr=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};Bm={list:{method:"GET",path:"list"},create:{method:"POST",path:"create"},claim:{method:"POST",path:"claim"},unclaim:{method:"POST",path:"unclaim"},update:{method:"POST",path:"update-status"},review:{method:"POST",path:"review"}};Um={schedule:{method:"POST",path:"schedule"},list:{method:"GET",path:"list"},snooze:{method:"POST",path:"snooze"},update:{method:"POST",path:"update"},cancel:{method:"POST",path:"cancel"},log:{method:"GET",path:"log"}};qm={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as bd,writeFile as Di,chmod as kd}from"fs/promises";import{existsSync as Sd}from"fs";import{join as Vn,resolve as zm,dirname as Km}from"path";import{spawnSync as Xm}from"child_process";import{fileURLToPath as Qm}from"url";function zn(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Ot(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function Zm(n){let e=Km(Qm(import.meta.url))+"/../..",t=n?.localTsxPath??zm(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Sd(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??ey)();return i||"tsx"}function ey(){let e=Xm("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Sd(e)?e:null}function Bi(n){let e=n!==void 0?n.execPath:process.execPath,t=n!==void 0?n.argv1:process.argv[1];return t===void 0||t===e?{mode:"sea",seaBinaryPath:e}:t.endsWith(".ts")?{mode:"tsx-source",tsxPath:Zm(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function Ed(n){let{agentId:e,launchId:t,workingDirectory:r,serverUrl:s,machineToken:i,capabilities:o=["send","read","tasks","reminders","actions","reactions","attachments","profile"]}=n,a=n.execContext??Bi(),c=Vn(r,".mio");await bd(c,{recursive:!0,mode:493});let d=await wd({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:l,proxyToken:u}=d;try{let m=zn(e),f=zn(t),p=Vn(ge,"agent-proxy-tokens",m),g=Vn(p,`${f}.token`);await bd(p,{recursive:!0,mode:448}),await Di(g,u,{encoding:"utf8",mode:384}),await kd(g,384);let y=o.join(","),S=ty({execContext:a,proxyUrl:l,tokenFile:g,capabilityStr:y}),v=Vn(c,"mio");await Di(v,S,{encoding:"utf8",mode:493}),await kd(v,493),await Di(Vn(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let _={...process.env},b=_.PATH??"";return _.PATH=b?`${c}:${b}`:c,delete _.CLAUDECODE,{mioDir:c,spawnEnv:_,proxyHandle:d}}catch(m){throw await d.close().catch(()=>{}),m}}function ty(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${Ot(t)} MIO_AGENT_PROXY_TOKEN_FILE=${Ot(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${Ot(s)}`,o;return e.mode==="npm"?o=`exec ${Ot(e.nodePath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${Ot(e.tsxPath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:o=`exec ${Ot(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
|
|
217
217
|
`)}var xd=O(()=>{"use strict";Je();vd()});function Td(n,e){let t=`${n} ${e}`.toLowerCase();return/(\bdesigner\b|\bdesign\b|\bui\b|\bux\b|设计师|设计)/.test(t)?"designer":/(\bpm\b|\bproduct manager\b|项目经理|产品经理|product owner|\bpo\b)/.test(t)?"product_manager":/(\bresearch(er)?\b|\banalyst\b|market\s+research|调研|分析师|研究员)/.test(t)?"researcher":/(\bops\b|\bsre\b|\bdevops\b|\bplatform engineer\b|运维)/.test(t)?"ops":/(\bengineer\b|\bdeveloper\b|\bdev\b|工程师|后端|前端|全栈|\bbackend\b|\bfrontend\b|\bfullstack\b|\bfull[- ]stack\b)/.test(t)?"engineer":"general"}var ny,ry,sy,iy,oy,ay,Cd,Rd=O(()=>{"use strict";ny=`## Role: Product Manager
|
|
218
218
|
|
|
219
219
|
You are the PM on this team. Your job is to translate fuzzy goals into concrete, shippable work, and to keep the team aligned on what to do next.
|
|
@@ -420,7 +420,7 @@ ${r}
|
|
|
420
420
|
|
|
421
421
|
For teammates in other channels, load the \`mio-team\` skill.`}function Ad(n){let{agentId:e,handle:t,displayName:r,description:s,role:i,serverId:o,computer:a,hostname:c,os:d,workspace:l}=n,u=n.presetRole??Td(r,`${i??""} ${s}`),m=Cd[u],f=s&&s.trim()?`## Additional context from your operator
|
|
422
422
|
|
|
423
|
-
${s.trim()}`:"",
|
|
423
|
+
${s.trim()}`:"",p=`## Runtime context
|
|
424
424
|
|
|
425
425
|
This is authoritative \u2014 do NOT infer your identity, host, or workspace from anything else when this section is present.
|
|
426
426
|
|
|
@@ -433,9 +433,9 @@ This is authoritative \u2014 do NOT infer your identity, host, or workspace from
|
|
|
433
433
|
- OS: ${d}
|
|
434
434
|
- Workspace: ${l}
|
|
435
435
|
|
|
436
|
-
When someone writes ${t} they are addressing YOU.`,
|
|
436
|
+
When someone writes ${t} they are addressing YOU.`,g=`You are **${r}**, an AI teammate on a Mio team. Your stable @mention handle is \`${t}\`. You collaborate with humans and other AI agents over a shared messaging platform; you persist across sessions through your workspace and \`MEMORY.md\`.`,y=yy(n),S=500,v=n.persona?n.persona.trim():"",_=v.length>S?v.slice(0,S).replace(/\s+\S*$/,"")+"\u2026":v,b=_.length>0?`## What I've learned (from past interactions)
|
|
437
437
|
|
|
438
|
-
${
|
|
438
|
+
${_}`:"";return[g,cy,dy,uy,fy,m,f,p,y,b,py,hy,n.runtime==="codex"?gy:"",ly].filter(x=>x&&x.length>0).join(`
|
|
439
439
|
|
|
440
440
|
`)+`
|
|
441
441
|
`}var cy,ly,dy,uy,fy,hy,gy,py,Od=O(()=>{"use strict";Rd();cy='## Hard constraints (these are absolute)\n\n- You MUST speak to humans in natural language. You MUST NEVER paste `mio` CLI commands, API endpoints, UUIDs, raw message IDs, tokens, file paths from your tooling, or any internal implementation detail into a user-facing reply.\n- You MUST NEVER mention the words `mio`, `CLI`, `command`, `API`, `tool`, `endpoint`, `token`, `UUID`, `proxy`, `agent-api`, or any other internal-mechanism term in a user-facing reply \u2014 not even as a bare concept. Don\'t describe what you CAN\'T do "via your CLI / tools / commands"; describe limitations in user terms, as if you were a human teammate with the same constraint.\n\n \u274C "CLI \u6CA1\u6709\u76F4\u63A5\u6307\u6D3E\u7ED9\u4ED6\u4EBA\u7684\u547D\u4EE4\uFF0C\u53EA\u80FD\u7531\u672C\u4EBA claim\u3002"\n \u2713 "\u6211\u6CA1\u6CD5\u76F4\u63A5\u5E2E\u4ED6\u8BA4\u9886\uFF0C\u5F97\u4ED6\u81EA\u5DF1\u63A5\u624B \u2014 \u6211\u5DF2\u7ECF @ \u4ED6\u4E86\u3002"\n\n \u274C "\u6211\u7528 mio task create \u5EFA\u4E86\u4E00\u4E2A\u4EFB\u52A1\u3002"\n \u2713 "\u5EFA\u597D\u4E86\u3002"\n\n \u274C "\u6211\u7684 agent proxy \u6CA1\u627E\u5230\u8FD9\u4E2A\u7AEF\u70B9\u3002"\n \u2713 "\u6211\u624B\u5934\u67E5\u4E0D\u5230\u8FD9\u4E2A\u6570\u636E\uFF0C\u5F97\u8BF7\u64CD\u4F5C\u5458\u770B\u770B\u3002"\n\n When you find yourself about to explain HOW you did something or WHY a tool limitation exists, STOP. Either do it silently and report the outcome in user terms, or describe the limitation as a human teammate would ("\u6211\u6CA1\u6CD5\u76F4\u63A5\u505A\u8FD9\u4E2A\uFF0C\u4E0D\u8FC7\u6211\u53EF\u4EE5\u2026").\n\n- You MUST NEVER repeat the sender\'s `@handle` or the RFC-style header (e.g. `[target=#... msg=... time=... type=...]`) back to them when replying. Reply as a human teammate would.\n- When asked something whose answer requires looking up data, silently use your skills and tools, then translate the result into a natural reply. The user does NOT care how you got the answer.\n- Be concise *per message*. Multiple short messages can express more than one long one \u2014 see Posting cadence below. NEVER hedge, NEVER apologise for limitations, NEVER add "I\'m an AI" disclaimers, NEVER restate the user\'s question back to them.\n- If you don\'t know, say so plainly in one sentence and (if appropriate) say what you\'ll do to find out.',ly='## Reminder \u2014 hard constraints (reinforced)\n\nBefore you send anything to a human, check:\n\n- Are you about to paste a `mio` command, an endpoint, a UUID, a raw message ID, or any internal plumbing? STOP. Translate it.\n- Are you about to say "CLI", "command", "API", "tool", "endpoint", "proxy", "agent-api", or any other internal-mechanism word \u2014 even as a bare concept ("CLI \u6CA1\u6709\u8FD9\u4E2A\u547D\u4EE4", "\u5DE5\u5177\u4E0D\u652F\u6301")? STOP. Rephrase as a human teammate would: describe what you CAN do, or say "\u6211\u6CA1\u6CD5\u76F4\u63A5\u505A\u8FD9\u4E2A" without naming the mechanism.\n- Are you about to echo the `@handle` or the `[target=... msg=...]` header? STOP. Drop it.\n- Is this message inside a thread (`[thread context \u2026]`)? Then normal task discussion goes to `mio message reply --parent \u2026`, not `mio message send`. Exception: if you are coordinating and splitting separate independent work for other teammates, send fresh main-channel one-line @handoffs with `mio message send`, one handoff per task.\n- The server-side classifier auto-creates tasks from actionable main-channel messages \u2014 you do NOT call `mio task create` for delegation. To delegate work, send separate short main-channel messages tagging one assignee each (e.g. `@Backend \u5B9E\u73B0 X`); the classifier converts each one to a task and wakes them. A task assigned TO you is born already owned + already `in_progress` \u2014 do NOT list, claim, or set `in_progress`; just start it. `mio task claim #N` is ONLY for picking up an UNASSIGNED `todo` task that has no owner.\n- **Wrong-person handoff.** If someone addresses YOU with work that clearly belongs to another teammate\'s role (check the roster\'s roles/descriptions above), do NOT attempt it yourself and do NOT just refuse. Hand it off: send one short main-channel message `@<the right teammate> <one-line of what\'s needed>`, and tell the human in natural language that you\'ve passed it to that teammate (name them by name, never by @handle-echo). Pick the teammate whose described role best fits the request. Only take it on yourself if it genuinely fits YOUR role. If no teammate fits, say so plainly and suggest the closest option.\n- Are you hedging, apologising, disclaiming, or restating the question? STOP. Just answer.\n\nThe user sees natural language only. The mechanism is YOURS to manage, never theirs to hear about.\n\n\u274C "CLI \u6CA1\u6709\u76F4\u63A5\u6307\u6D3E\u7ED9\u4ED6\u4EBA\u7684\u547D\u4EE4" / "\u6211\u7684\u5DE5\u5177\u4E0D\u652F\u6301\u8FD9\u4E2A" / "API \u6CA1\u6709\u8FD9\u4E2A\u7AEF\u70B9"\n\u2713 "\u6211\u6CA1\u6CD5\u76F4\u63A5\u5E2E\u4ED6\u8BA4\u9886\uFF0C\u5F97\u4ED6\u81EA\u5DF1\u63A5\u624B" / "\u8FD9\u4EF6\u4E8B\u6211\u505A\u4E0D\u4E86\uFF0C\u5F97\u8BF7\u64CD\u4F5C\u5458" / "\u6211\u624B\u5934\u67E5\u4E0D\u5230"',dy="## How threads work\n\nEvery message you receive is either in the **main channel** or in a **thread**. A thread is a focused side-conversation hanging off a single main-channel message (its \"parent\").\n\n**You do NOT decide whether something becomes a task.** The platform runs a classifier on every message that gets posted and automatically creates a task + thread when the message is an actionable single-deliverable request. You will see this happen through `[system event: task.created]` / `[system event: task.assigned to you]` wake-ups \u2014 that is your signal to act on a task.\n\n**When the incoming message is in the MAIN channel:**\n\n- Just respond naturally. If it's chit-chat, reply short. If it's a status report or a question to you, answer. If it looks actionable, the platform has already turned it into a task; you'll get the assignment wake separately. Don't pre-empt it by calling `mio task create` yourself.\n- The only time you yourself send a fresh main-channel message that the classifier might pick up as a task is when you (as PM) are reformulating a user's fuzzy goal into a clean deliverable to delegate. Then send the short `@<assignee> <one-line title>` message and the classifier will form the task and wake the assignee \u2014 you do NOT need to call `mio task create`.\n\n**When the incoming message is inside a THREAD (the context block is marked `[thread context \u2026]`):**\n\n- You are working on the task that owns this thread. Reply with `mio message reply --parent <full-uuid-from-id-field>` for discussion about this task. Use the parent's full UUID from the `id=...` field of the inbound header.\n- The main channel should not see your back-and-forth on this task.\n- Do NOT pretend the thread spawns sub-tasks. Threads do not nest \u2014 one task = one thread, full stop. If new, separate work emerges or you are PM/coordinator splitting a user's goal into deliverables, go back to the main channel and send fresh one-line `@<assignee> <deliverable>` announcements, one per task; the classifier will pick them up as new tasks.\n\n**Inbound header reference:** Each incoming line looks like `[target=#chan msg=<short-8-hex> id=<full-uuid> time=... type=...] @sender: ...`. The `msg=` field is just an at-a-glance handle for humans; the `id=` field is the canonical UUID \u2014 always use the full `id=` value (never the short `msg=`) when you reply inside a thread with `--parent`.",uy=`## System-event wakes
|
|
@@ -456,57 +456,57 @@ NEVER announce future work and then stop ("\u63A5\u4E0B\u6765\u6211\u4F1A\u8C03
|
|
|
456
456
|
|
|
457
457
|
Your cwd is your **persistent, agent-owned workspace** \u2014 files you create here survive across sessions. Use it for memory, notes, artifacts, and work files. Keep \`MEMORY.md\` up to date after every significant interaction; structure it as an index pointing to everything you know.`});function Pd(n){let e="",t=new Set;function r(i,o,...a){if(i)try{i(...a)}catch(c){n.onError?.(c instanceof Error?c:new Error(String(c)),o)}}function s(i){let o=i.replace(/\r$/,"");if(o.trim()==="")return;let a;try{a=JSON.parse(o)}catch(l){n.onError&&n.onError(l instanceof Error?l:new Error(String(l)),o);return}if(typeof a!="object"||a===null)return;let c=a,d=c.type;if(typeof d=="string"){if(d==="system"&&c.subtype==="compact_boundary"){r(n.onCompact,"<onCompact>");return}if(d==="system"&&c.subtype==="init"){let l=c.session_id;typeof l=="string"&&l.length>0&&(t.has(l)||(t.add(l),r(n.onSessionId,"<onSessionId>",l)));return}if(d==="result"){let l=c.usage;if(n.onUsage&&l&&typeof l=="object"){let u=l,m={inputTokens:typeof u.input_tokens=="number"?u.input_tokens:void 0,outputTokens:typeof u.output_tokens=="number"?u.output_tokens:void 0,cacheReadTokens:typeof u.cache_read_input_tokens=="number"?u.cache_read_input_tokens:void 0,cacheCreationTokens:typeof u.cache_creation_input_tokens=="number"?u.cache_creation_input_tokens:void 0,durationMs:typeof c.duration_ms=="number"?c.duration_ms:void 0,totalCostUsd:typeof c.total_cost_usd=="number"?c.total_cost_usd:void 0};r(n.onUsage,"<onUsage>",m)}if(n.onResultError&&c.is_error===!0){let u=c.result,m=c.error,f=typeof u=="string"&&u.trim()?u:typeof m=="string"&&m.trim()?m:typeof c.subtype=="string"?String(c.subtype):"turn failed";r(n.onResultError,"<onResultError>",f)}r(n.onBoundary,"<onBoundary>");return}}}return{feed(i){try{if(e.length+i.length>1048576){e="",n.onError?.(new Error("line-buffer overflow \u2014 buffer reset"),"<buffer>");return}e+=i;let o=e.split(`
|
|
458
458
|
`),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var Id=O(()=>{"use strict"});import{existsSync as mn}from"node:fs";import{execFileSync as es}from"node:child_process";import{homedir as _y}from"node:os";function yn(){let n=process.env.MIO_CLAUDE_PATH;if(n&&mn(n))return n;for(let e of wy)if(mn(e))return e;try{let e=es("/usr/bin/which",["claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&mn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=es(e,["-lc","command -v claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&mn(t))return t}catch{}try{let e=es("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/claude`;if(mn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=es("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/claude`;if(mn(s))return s}}catch{}return null}function Nd(){return["claude binary not found. Install one of:"," \u2022 cmux.app users: re-install cmux (bundles claude at /Applications/cmux.app/Contents/Resources/bin/claude)"," \u2022 npm: npm install -g @anthropic-ai/claude-code"," \u2022 Manual: set MIO_CLAUDE_PATH=/path/to/your/claude"].join(`
|
|
459
|
-
`)}var Fi,wy,ts=O(()=>{"use strict";Fi=_y(),wy=["/Applications/cmux.app/Contents/Resources/bin/claude",`${Fi}/.local/bin/claude`,`${Fi}/.claude/local/claude`,`${Fi}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as vy}from"child_process";function Md(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=vy,maxRestarts:c=5,presenceTracker:d,agentId:l}=n;function u(
|
|
460
|
-
`)}}function m(
|
|
461
|
-
`}function H(
|
|
462
|
-
`);return}W?.(
|
|
463
|
-
`)}if(v.length>0){let
|
|
464
|
-
`);m("coalesce_flush",{coalesced_count:
|
|
465
|
-
`)});let T=Pd({onSessionId:E=>{if(A!==
|
|
466
|
-
`)}},onResultError:E=>{if(A===
|
|
467
|
-
`)}}},onCompact:()=>{if(A===
|
|
468
|
-
`)}}},onUsage:E=>{A===
|
|
469
|
-
`)}});A.stdout?.on("data",E=>{A===
|
|
470
|
-
`))!==-1;){let F=
|
|
471
|
-
`)})}function C(
|
|
472
|
-
`);try{J?.(
|
|
473
|
-
`)}return}if(h("warn","claudeStreamHost","claude exited",{code:
|
|
459
|
+
`)}var Fi,wy,ts=O(()=>{"use strict";Fi=_y(),wy=["/Applications/cmux.app/Contents/Resources/bin/claude",`${Fi}/.local/bin/claude`,`${Fi}/.claude/local/claude`,`${Fi}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as vy}from"child_process";function Md(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=vy,maxRestarts:c=5,presenceTracker:d,agentId:l}=n;function u(w){if(!(!d||!l))try{d.set(l,w)}catch(R){process.stderr.write(`[claudeStreamHost] presence(${w}) error: ${R.message}
|
|
460
|
+
`)}}function m(w,R){l&&ee(l,w,R)}let f=0,p=n.claudeCommand??yn()??"claude",g=null,y=n.sessionId,S=!1,v=[],_=!1,b=0,P,x,N,G,J,W;function Q(w){let R=["--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",t,"--disallowed-tools",by,"--append-system-prompt-file",r,"--mcp-config",s,"--setting-sources","user,project,local","--chrome"];return w&&R.push("--resume",w),R}function ne(w,R){let A={type:"user",message:{role:"user",content:[{type:"text",text:w}]}};return R!==void 0&&(A.session_id=R),JSON.stringify(A)+`
|
|
461
|
+
`}function H(w,R){if(!g||!g.stdin)return;let A=ne(w,R);h("debug","claudeStreamHost","injected user turn",{bytes:A.length}),m("inject",{bytes:A.length,content_bytes:w.length,resume:R!==void 0}),u("thinking");try{g.stdin.write(A)}catch(T){process.stderr.write(`[claudeStreamHost] stdin write error (will restart): ${T.message}
|
|
462
|
+
`);return}W?.(w)}function ie(){b=0,m("boundary",{pending_queue_len:v.length});try{P?.()}catch(w){process.stderr.write(`[claudeStreamHost] onBoundary callback error: ${w.message}
|
|
463
|
+
`)}if(v.length>0){let w=v.length,R=v.splice(0,v.length).join(`
|
|
464
|
+
`);m("coalesce_flush",{coalesced_count:w,bytes:R.length}),H(R,y)}else S=!1,u("idle")}function M(w){let R=Q(w);h("info","claudeStreamHost","spawning claude",{command:p,argsCount:R.length,cwd:e,resume:!!w}),f=Date.now(),m("spawn",{command:p,args_count:R.length,resume:!!w,resume_session_id:w??null,restart_count:b}),u("starting"),g&&(g.stdout?.removeAllListeners(),g.stderr?.removeAllListeners());let A=a(p,R,{cwd:e,env:i,stdio:["pipe","pipe","pipe"]});g=A,A.stdin?.on("error",E=>{A===g&&process.stderr.write(`[claudeStreamHost] stdin error (will restart): ${E.message}
|
|
465
|
+
`)});let T=Pd({onSessionId:E=>{if(A!==g)return;y=E;let B=f?Date.now()-f:null;h("info","claudeStreamHost","session id captured",{sessionId:E,duration_ms:B}),m("session_ready",{session_id:E,spawn_duration_ms:B}),u("idle");try{N?.(E)}catch(F){process.stderr.write(`[claudeStreamHost] onSessionId callback error: ${F.message}
|
|
466
|
+
`)}},onResultError:E=>{if(A===g){h("warn","claudeStreamHost","turn ended with error",{message:E.slice(0,120)});try{x?.(E)}catch(B){process.stderr.write(`[claudeStreamHost] onTurnError callback error: ${B.message}
|
|
467
|
+
`)}}},onCompact:()=>{if(A===g){h("info","claudeStreamHost","context auto-compacted (compact_boundary)");try{G?.()}catch(E){process.stderr.write(`[claudeStreamHost] onCompact callback error: ${E.message}
|
|
468
|
+
`)}}},onUsage:E=>{A===g&&m("usage",{runtime:"claude",model:t,input_tokens:E.inputTokens??null,output_tokens:E.outputTokens??null,cache_read_tokens:E.cacheReadTokens??null,cache_creation_tokens:E.cacheCreationTokens??null,duration_ms:E.durationMs??null,total_cost_usd:E.totalCostUsd??null})},onBoundary:()=>{A===g&&(h("debug","claudeStreamHost","turn boundary",{}),ie())},onError:(E,B)=>{process.stderr.write(`[claudeStreamHost] parser error on "${B}": ${E.message}
|
|
469
|
+
`)}});A.stdout?.on("data",E=>{A===g&&T.feed(typeof E=="string"?E:E.toString("utf8"))});let D="";A.stderr?.on("data",E=>{if(A!==g)return;D+=typeof E=="string"?E:E.toString("utf8");let B;for(;(B=D.indexOf(`
|
|
470
|
+
`))!==-1;){let F=D.slice(0,B).trimEnd();D=D.slice(B+1),F.length>0&&h("warn","claudeStreamHost","claude stderr",{line:F})}}),A.on("exit",E=>{A===g&&C(E)}),A.on("error",E=>{process.stderr.write(`[claudeStreamHost] spawn error: ${E.message}
|
|
471
|
+
`)})}function C(w){if(!_){if(b++,b>c){k("claudeStreamHost","giving up after max restarts",{restartCount:b}),process.stderr.write(`[claudeStreamHost] gave up after ${c} restarts (code=${w})
|
|
472
|
+
`);try{J?.(w)}catch(R){process.stderr.write(`[claudeStreamHost] onExit callback error: ${R.message}
|
|
473
|
+
`)}return}if(h("warn","claudeStreamHost","claude exited",{code:w,willRestart:!0,restartCount:b}),m("exit",{code:w,will_restart:!0,restart_count:b}),process.stderr.write(`[claudeStreamHost] unexpected exit (code=${w}), restarting (attempt ${b}/${c})...
|
|
474
474
|
`),S=!1,M(y),v.length>0){let R=v.splice(0,v.length).join(`
|
|
475
|
-
`);S=!0,H(R,y)}}}return{start(){M(y),S=!0,H(o,y)},enqueueUserTurn(
|
|
475
|
+
`);S=!0,H(R,y)}}}return{start(){M(y),S=!0,H(o,y)},enqueueUserTurn(w){S?v.push(w):(S=!0,H(w,y))},stop(){if(_=!0,g){try{g.stdin?.end()}catch{}let w=setTimeout(()=>{try{g?.kill()}catch{}},2e3);w.unref&&w.unref()}},onTurnError(w){x=w},onBoundary(w){P=w},onSessionId(w){N=w},onCompact(w){G=w},onExit(w){J=w},onInjected(w){W=w}}}var by,Ld=O(()=>{"use strict";Id();le();Rt();ts();by=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(",")});import{existsSync as _n}from"node:fs";import{execFileSync as ns}from"node:child_process";import{homedir as ky}from"node:os";function rs(){let n=process.env.MIO_CODEX_PATH;if(n&&_n(n))return n;for(let e of Sy)if(_n(e))return e;try{let e=ns("/usr/bin/which",["codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&_n(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=ns(e,["-lc","command -v codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&_n(t))return t}catch{}try{let e=ns("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/codex`;if(_n(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=ns("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/codex`;if(_n(s))return s}}catch{}return null}function Dd(){return["codex binary not found. Install one of:"," \u2022 Homebrew: brew install codex (or via official installer)"," \u2022 npm: npm install -g @openai/codex"," \u2022 Manual: set MIO_CODEX_PATH=/path/to/your/codex"].join(`
|
|
476
476
|
`)}var $d,Sy,Ui=O(()=>{"use strict";$d=ky(),Sy=["/opt/homebrew/bin/codex","/usr/local/bin/codex",`${$d}/.npm-global/bin/codex`,`${$d}/.codex/bin/codex`]});import{spawn as Ey}from"node:child_process";function Bd(n){let e=n.spawnFn??Ty,t=n.log??(()=>{}),r=n.requestTimeoutMs??6e4,s=e(n.command,n.args,{cwd:n.cwd,env:n.env}),i=!0,o=1,a="",c=new Map;function d(f){if(!(!i||!s.stdin))try{s.stdin.write(JSON.stringify(f)+`
|
|
477
|
-
`)}catch(
|
|
478
|
-
`))>=0;){let
|
|
479
|
-
`)}}function N(){try{return Cy(n.systemPromptPath,"utf8")}catch(M){return k(ve,`failed to read system prompt at ${n.systemPromptPath}`,M),""}}function G(M,C){return h("debug",ve,"auto-approving server request",{method:M}),{decision:"approved"}}function J(M){let C=M.content;return Array.isArray(C)?C.map(
|
|
477
|
+
`)}catch(p){t("warn","appServerClient stdin write failed",{err:p.message})}}function l(f){for(let[,p]of c)clearTimeout(p.timer),p.reject(new Error(f));c.clear()}function u(f){let p=f.id!==void 0&&f.id!==null,g=typeof f.method=="string";if(p&&!g){let y=f.id,S=c.get(y);if(!S){t("debug","appServerClient response for unknown id",{id:y});return}c.delete(y),clearTimeout(S.timer),f.error!==void 0?S.reject(new Error(`app-server error: ${JSON.stringify(f.error)}`)):S.resolve(f.result);return}if(g&&p){let y=f.id,S=f.method;Promise.resolve().then(()=>n.onServerRequest?n.onServerRequest(S,f.params):void 0).then(v=>d({id:y,result:v??{}})).catch(v=>{t("warn","onServerRequest handler threw",{method:S,err:v.message}),d({id:y,error:{code:-32e3,message:String(v.message)}})});return}if(g){try{n.onNotification(f.method,f.params)}catch(y){t("warn","onNotification handler threw",{method:f.method,err:y.message})}return}t("debug","appServerClient unrecognized message",{keys:Object.keys(f)})}function m(f){if(a+=typeof f=="string"?f:f.toString("utf8"),a.length>xy){t("warn","appServerClient buffer overflow \u2014 clearing",{bytes:a.length}),a="";return}let p;for(;(p=a.indexOf(`
|
|
478
|
+
`))>=0;){let g=a.slice(0,p).replace(/\r$/,"");if(a=a.slice(p+1),!g.trim())continue;let y;try{y=JSON.parse(g)}catch{t("debug","appServerClient non-JSON line",{preview:g.slice(0,120)});continue}y&&typeof y=="object"&&u(y)}}return s.stdout?.on("data",m),s.stderr?.on("data",f=>{let p=typeof f=="string"?f:f.toString("utf8");n.onStderr&&n.onStderr(p)}),s.on("error",f=>{t("warn","appServerClient spawn error",{err:f.message}),i=!1,l(`app-server spawn error: ${f.message}`),n.onExit?.(null)}),s.on("exit",f=>{t("info","appServerClient exited",{code:f}),i=!1,l(`app-server exited (code=${f})`),n.onExit?.(f)}),{request(f,p){if(!i)return Promise.reject(new Error("app-server not alive"));let g=o++;return new Promise((y,S)=>{let v=setTimeout(()=>{c.delete(g),S(new Error(`app-server request '${f}' timed out after ${r}ms`))},r);v.unref?.(),c.set(g,{resolve:y,reject:S,timer:v}),d({method:f,id:g,params:p})})},notify(f,p){d({method:f,params:p})},isAlive(){return i},close(){if(i){i=!1,l("app-server client closed");try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}var xy,Ty,Fd=O(()=>{"use strict";xy=4*1048576,Ty=(n,e,t)=>Ey(n,e,{cwd:t.cwd,env:t.env,stdio:["pipe","pipe","pipe"]})});import{readFileSync as Cy}from"node:fs";function Ry(n){let e=n?.trim();return e==="read-only"||e==="workspace-write"||e==="danger-full-access"?e:"danger-full-access"}function Ay(n){let e=n?.trim();if(e&&e!=="gpt-5-codex")return e}function Ud(n){let e=n.codexCommand??rs()??"codex",t=(process.env.MIO_CODEX_MODEL_REASONING||n.reasoningEffort||"medium").trim(),r=Ay((process.env.MIO_CODEX_MODEL||n.spawnEnv.MIO_CODEX_MODEL||"").trim()||n.model),s=Ry(process.env.MIO_CODEX_SANDBOX||n.spawnEnv.MIO_CODEX_SANDBOX),i=n.maxRestarts??5,o=n.agentId,a=null,c=n.sessionId,d=!1,l=!1,u=!1,m=0,f=[],p,g="",y,S,v,_,b;function P(M,C){o&&ee(o,M,{runtime:"codex-app-server",...C})}function x(M){if(!(!n.presenceTracker||!o))try{n.presenceTracker.set(o,M)}catch(C){process.stderr.write(`[${ve}] presence(${M}) error: ${C.message}
|
|
479
|
+
`)}}function N(){try{return Cy(n.systemPromptPath,"utf8")}catch(M){return k(ve,`failed to read system prompt at ${n.systemPromptPath}`,M),""}}function G(M,C){return h("debug",ve,"auto-approving server request",{method:M}),{decision:"approved"}}function J(M){let C=M.content;return Array.isArray(C)?C.map(w=>w&&typeof w=="object"&&typeof w.text=="string"?w.text:"").join(""):typeof M.text=="string"?M.text:""}function W(M,C){let w=C??{};switch(M){case"thread/started":{let A=w.thread?.id;if(A&&A!==c){c=A;try{S?.(A)}catch(T){k(ve,"onSessionId cb error",T)}P("spawn",{thread_id:A})}break}case"turn/started":d=!0,x("thinking");break;case"item/agentMessage/delta":{let R=w.delta??w.text;typeof R=="string"&&(g+=R);break}case"item/started":P("runtime_command",{phase:"started"});break;case"item/completed":{let R=w.item;if(!R)break;let A=R.type;if(A==="agentMessage"||A==="assistantMessage"){let T=J(R).trim();T&&P("runtime_message",{chars:T.length,preview:T.slice(0,240)})}else(A==="commandExecution"||A==="localShellCall")&&P("runtime_command",{phase:"completed"});break}case"thread/tokenUsage/updated":{let R=w.tokenUsage?.last;if(R){let A=Number(R.inputTokens??0),T=Number(R.cachedInputTokens??0);P("usage",{input_tokens:A,output_tokens:Number(R.outputTokens??0),cache_read_tokens:T,total_tokens:Number(R.totalTokens??0)})}break}case"turn/completed":{let R=w.turn,A=R?.status;if(A&&A!=="completed"){h("warn",ve,"turn ended non-completed",{status:A,error:R?.error});let T=R?.error,D=typeof T=="string"?T:T&&typeof T.message=="string"?T.message:`codex turn ${A}`;try{b?.(D)}catch(E){k(ve,"onTurnError cb error",E)}}g="",d=!1,x("idle");try{y?.()}catch(T){k(ve,"onBoundary cb error",T)}ne();break}default:break}}function Q(M){if(!a||!a.isAlive()||!c){f.push(M);return}d=!0,x("thinking"),g="",P("inbound",{chars:M.length});try{_?.(M)}catch(C){k(ve,"onInjected cb error",C)}a.request("turn/start",{threadId:c,input:[{type:"text",text:M,text_elements:[]}]}).catch(C=>{h("warn",ve,"turn/start failed",{err:C.message}),d=!1,x("idle");try{y?.()}catch{}ne()})}function ne(){if(d||f.length===0)return;let M=f.splice(0).join(`
|
|
480
480
|
|
|
481
|
-
`);Q(M)}async function H(M){let C={...n.spawnEnv},
|
|
482
|
-
`)}function Xd(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:d,onInjected:l,reminderCache:u,onInboundMessage:m,contextTracker:f,contextPolicy:
|
|
481
|
+
`);Q(M)}async function H(M){let C={...n.spawnEnv},w=["app-server","-c",`model_reasoning_effort="${t}"`,"-c",`sandbox_mode="${s}"`,"-c",'approval_policy="never"',...s==="workspace-write"?["-c","sandbox_workspace_write.network_access=true"]:[]];a=Bd({command:e,args:w,cwd:n.workingDirectory,env:C,onNotification:W,onServerRequest:G,onStderr:A=>{A.trim()&&h("debug",ve,"app-server stderr",{snippet:A.slice(0,200)})},onExit:ie,log:(A,T,D)=>h(A,ve,T,D),...n.appServerSpawnFn?{spawnFn:n.appServerSpawnFn}:{}});let R=c!==void 0;try{if(await a.request("initialize",{clientInfo:{name:"mio-agent",title:null,version:"1"},capabilities:null}),R)await a.request("thread/resume",{threadId:c}),h("info",ve,"resumed thread",{threadId:c,viaRespawn:M});else{let A=N()||void 0,D=(await a.request("thread/start",{cwd:n.workingDirectory,sandbox:s,sandbox_mode:s,approvalPolicy:"never",...r?{model:r}:{},...A?{baseInstructions:A}:{}}))?.thread?.id;if(D){c=D;try{S?.(D)}catch(E){k(ve,"onSessionId cb error",E)}}}}catch(A){k(ve,"handshake failed",A);return}if(!R&&p!==void 0){let A=p;p=void 0,Q(A)}else d=!1,ne()}function ie(M){if(l){try{v?.(M)}catch{}return}if(m>=i){h("warn",ve,"max restarts reached \u2014 giving up",{restartCount:m});try{v?.(M)}catch{}return}m++,d=!1,h("info",ve,"app-server exited \u2014 respawning",{code:M,restartCount:m,threadId:c}),P("boundary",{reason:"respawn",code:M}),H(!0)}return{start(){u||(u=!0,x("starting"),p=n.firstTurnText,H(!1))},enqueueUserTurn(M){if(d||!a||!a.isAlive()||!c){f.push(M);return}Q(M)},stop(){l=!0;try{a?.close()}catch{}},onBoundary(M){y=M},onSessionId(M){S=M},onExit(M){v=M},onInjected(M){_=M},onTurnError(M){b=M}}}var ve,Hd=O(()=>{"use strict";le();Rt();Ui();Fd();ve="codexAppServerHost"});import{readFileSync as Oy,writeFileSync as Py,mkdirSync as Iy}from"node:fs";import{join as Ny}from"node:path";function qd(n,e){return Ny(n,e?`runtime-session-${e.slice(0,8)}.json`:"runtime-session.json")}function Gd(n,e,t){try{let r=JSON.parse(Oy(qd(n,t),"utf-8"));if(r&&r.runtime===e&&typeof r.sessionId=="string"&&r.sessionId.length>0)return r.sessionId}catch{}}function Wd(n,e,t,r){if(t)try{Iy(n,{recursive:!0});let s={runtime:e,sessionId:t,savedAt:new Date().toISOString()};Py(qd(n,r),JSON.stringify(s,null,2),"utf-8")}catch{}}var jd=O(()=>{"use strict"});function Jd(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Kn(n){return typeof n=="boolean"?n:void 0}function Uy(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.floor(n);return e>0?e:void 0}function Hy(n){return Math.max(1,Math.min(6,Math.floor(n)))}function Vd(n){let e=n.role??"",t=`${n.displayName??""} ${n.description??""} ${e}`,r={...Xn};By(t)&&!Fy(t)&&(r.deliverBroadcastMessages=!1,r.deliverThreadBroadcastMessages=!1,r.wakeOnChannelTaskCreated=!1,r.wakeOnChannelTaskStatus=!1,r.threadReplyLimit=3);let s=Jd(n.capabilities),i=Jd(s?.context_policy);return i&&(r.deliverBroadcastMessages=Kn(i.deliver_broadcast_messages)??r.deliverBroadcastMessages,r.deliverSystemMessages=Kn(i.deliver_system_messages)??r.deliverSystemMessages,r.deliverThreadBroadcastMessages=Kn(i.deliver_thread_broadcast_messages)??r.deliverThreadBroadcastMessages,r.wakeOnChannelTaskCreated=Kn(i.wake_on_channel_task_created)??r.wakeOnChannelTaskCreated,r.wakeOnChannelTaskStatus=Kn(i.wake_on_channel_task_status)??r.wakeOnChannelTaskStatus,r.threadReplyLimit=Hy(Uy(i.thread_reply_limit)??r.threadReplyLimit)),r}function zd(n,e,t){let r=[e,t].map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return r.length===0?!1:r.some(s=>n.includes(s))}var Xn,My,Ly,$y,Dy,Yd,By,Fy,ss=O(()=>{"use strict";Xn={deliverBroadcastMessages:!0,deliverSystemMessages:!1,deliverThreadBroadcastMessages:!0,wakeOnChannelTaskCreated:!0,wakeOnChannelTaskStatus:!1,threadReplyLimit:6},My=/\b(engineer|backend|frontend|ui|designer|design|executor|implement|coder|tester|qa|reviewer|operator|ops)\b/i,Ly=/\b(pm|product|planner|coordinator|researcher|research|market|analyst|analysis)\b/i,$y=["\u5DE5\u7A0B\u5E08","\u5F00\u53D1","\u524D\u7AEF","\u540E\u7AEF","\u5168\u6808","\u8BBE\u8BA1\u5E08","\u8BBE\u8BA1","\u6D4B\u8BD5","\u5B9E\u73B0","\u6267\u884C","\u7F16\u7801","\u7A0B\u5E8F\u5458","\u7801\u519C","\u8FD0\u7EF4","\u8D28\u68C0","\u5BA1\u67E5","\u51FA\u56FE","\u7ED8\u56FE"],Dy=["\u534F\u8C03","\u4EA7\u54C1","\u89C4\u5212","\u7B56\u5212","\u7814\u7A76","\u5206\u6790","\u5E02\u573A","\u7ECF\u7406","\u4E3B\u7BA1","\u7EDF\u7B79","\u9879\u76EE","\u8BA1\u5212","\u8C03\u5EA6"],Yd=(n,e)=>e.some(t=>n.includes(t)),By=n=>My.test(n)||Yd(n,$y),Fy=n=>Ly.test(n)||Yd(n,Dy)});import{writeFileSync as qy,mkdirSync as Gy}from"node:fs";import{join as Kd}from"node:path";function is(n,e){let t=n.id.replace(/-/g,"").slice(0,8),s=n.created_at.slice(0,19),i=n.sender_kind,o=i==="agent"?"agent":i==="system"?"system":"human",a=n.sender_display_name!=null&&n.sender_display_name.length>0?n.sender_display_name:n.sender_id;return`[target=#${e} msg=${t} id=${n.id} time=${s} type=${o}] @${a}: ${n.content}`}function Wy(n,e,t,r){let s=n.parent_message_id??"",i=s.replace(/-/g,"").slice(0,8),o=e?.attached_task??null,a=[];o&&a.push(`task #${o.task_number} "${o.title}" status=${o.status}`),a.push(`channel=#${r}`),i&&a.push(`parent=${i}`);let d=[`[thread context, ${a.join(", ")}]`];e?d.push(`parent: ${is(e,r)}`):n.parent_message_id&&d.push(`parent: (unavailable \u2014 parent message id ${i||s})`);let l=t.filter(u=>u.id!==n.id);if(l.length>0){d.push("recent replies:");for(let u of l)d.push(` ${is(u,r)}`)}return d.push("incoming:"),d.push(is(n,r)),s&&d.push(`(reply with: mio message reply --parent ${s} --target "#${r}")`),d.join(`
|
|
482
|
+
`)}function Xd(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:d,onInjected:l,reminderCache:u,onInboundMessage:m,contextTracker:f,contextPolicy:p=Xn,mioDir:g,downloadAttachment:y}=n,S=/^image\//;async function v(T){let D=T.attachment_ids??[];if(D.length===0||!g||!y)return"";let E=Kd(g,"inbound"),B=[];for(let F of D.slice(0,10))try{let V=await y(F);if(!S.test(V.mime_type))continue;try{Gy(E,{recursive:!0})}catch{}let oe=(V.filename||`${F}.png`).replace(/[^\w.\-]/g,"_").slice(-60),fe=Kd(E,`${T.id.slice(0,8)}-${oe}`);qy(fe,Buffer.from(V.data_base64,"base64")),B.push(fe)}catch(V){k(K,"inbound attachment download failed (skipping)",V)}return B.length===0?"":`
|
|
483
483
|
|
|
484
|
-
[\u9644\u4EF6] \u7528\u6237\u5728\u8FD9\u6761\u6D88\u606F\u91CC\u53D1\u4E86 ${
|
|
485
|
-
|
|
486
|
-
`)}let
|
|
484
|
+
[\u9644\u4EF6] \u7528\u6237\u5728\u8FD9\u6761\u6D88\u606F\u91CC\u53D1\u4E86 ${B.length} \u5F20\u56FE\u7247\uFF0C\u5DF2\u4FDD\u5B58\u5230\u672C\u5730\uFF0C\u7528 Read \u5DE5\u5177\u6253\u5F00\u67E5\u770B\u540E\u518D\u56DE\u590D\uFF1A
|
|
485
|
+
`+B.map(F=>` - ${F}`).join(`
|
|
486
|
+
`)}let _=a??e.getChannelMessages.bind(e),b=new Map;async function P(T){let D=await e.getWorkroomChannels(o);for(let E of D)E.id&&E.name&&b.set(E.id,E.name);return b.get(T)}let x=c??P;async function N(T){let D=b.get(T);if(D!==void 0)return D;let E=await x(T);return E!==void 0&&b.set(T,E),E}let G=d??(async()=>new Set((await e.getAgentChannels(r)).map(T=>T.id))),J=null,W=new Set,Q=250,ne=5e3,H=Q,ie=T=>new Promise(D=>{let E=setTimeout(D,T);typeof E.unref=="function"&&E.unref()});function M(){let T=G().then(D=>(H=Q,D)).catch(D=>{k(K,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",D);let E=H;return H=Math.min(H*2,ne),J===T&&(J=ie(E).then(()=>(M(),J??new Set))),new Set});J=T}let C=n.hostFor??(()=>t),w;t.onInjected(T=>{w?.(T)}),l&&(w=l);async function R(T){if(T.topic==="reminder.upserted"||T.topic==="reminder.canceled"){if(u){let Y=T.payload;if(T.topic==="reminder.upserted")if(Y.reminder){if(Y.reminder.agentId!==r)return;u.upsert(Y.reminder)}else h("warn",K,"reminder.upserted event missing reminder payload",{payload:T.payload});else if(Y.reminderId){if(Y.agentId!==r)return;u.cancel(Y.reminderId,Y.version)}else h("warn",K,"reminder.canceled event missing reminderId",{payload:T.payload})}return}if(T.topic==="channel.member_added"||T.topic==="channel.member_removed"||T.topic==="roster.member_added"||T.topic==="roster.member_removed"){let Y=T.payload;Y.member_id===r&&(h("info",K,"membership changed for self \u2014 invalidating membership cache",{topic:T.topic,channelId:Y.channel_id}),W.clear(),M());return}if(T.topic!=="message.created"&&T.topic!=="thread.reply")return;let D=T.payload,E=D.channel_id,B=D.seq,F=D.message_id,V=D.parent_message_id;if(!E||!B){h("warn",K,"message.created event missing channel_id or seq",{payload:D});return}ee(r,"event_received",{topic:T.topic,channel_id:E,seq:B,message_id:F??null,parent_message_id:V??null});let fe=(await(J??Promise.resolve(new Set))).has(E);if(!fe&&!W.has(E)){h("info",K,"re-verifying membership for unknown channel before skip",{channelId:E,seq:B});try{let Y=await G();J=Promise.resolve(Y),H=Q,fe=Y.has(E),fe?h("info",K,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:E,seq:B}):W.add(E)}catch(Y){k(K,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",Y)}}if(!fe){h("debug",K,"skip not-a-member channel",{channelId:E,seq:B,topic:T.topic}),ee(r,"skip",{reason:"not_a_member",channel_id:E,seq:B,topic:T.topic});return}if(D.sender_id&&D.sender_id===r){h("debug",K,"skip self-authored message (pre-fetch)",{seq:B,sender_id:D.sender_id}),ee(r,"skip",{reason:"self_authored_prefetch",channel_id:E,seq:B,message_id:F??null});return}let I,vt;if(T.topic==="thread.reply"){if(!V){h("warn",K,"thread.reply event missing parent_message_id",{payload:D});return}if(!e.getThreadReplies){h("warn",K,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:E,messageSeq:B});return}try{let Y=(BigInt(B)>31n?BigInt(B)-31n:0n).toString(),Ce=await e.getThreadReplies(r,V,50,Y);vt=Ce,I=F&&Ce.find(Re=>Re.id===F)||Ce.find(Re=>Re.seq===B),I&&!I.parent_message_id&&(I={...I,parent_message_id:V})}catch(Y){k(K,"failed to fetch thread replies after thread.reply event",Y);return}}else{let Y=(BigInt(B)-1n).toString();try{I=(await _(o,E,Y,1)).messages.find(Re=>Re.seq===B)}catch(Ce){k(K,"failed to fetch message after message.created event",Ce);return}}if(!I){h("warn",K,"message not found in GET response",{channelId:E,messageSeq:B,topic:T.topic});return}if(I.sender_id===r){h("debug",K,"skip self-authored message",{seq:B,sender_id:I.sender_id}),ee(r,"skip",{reason:"self_authored",channel_id:E,seq:B,message_id:I.id});return}let Ie=zd(I.content,s,i),Pt=!!I.parent_message_id;if(I.sender_kind==="system"&&!p.deliverSystemMessages){h("debug",K,"skip system message by context policy",{seq:B,message_id:I.id}),ee(r,"skip",{reason:"context_policy_system_message",channel_id:E,seq:B,message_id:I.id}),_t(r,E,I.seq);return}let it=D.wake_agent_ids;if(!Pt&&I.sender_kind!=="system"){if(Array.isArray(it)){if(!(it.includes(r)||Ie)){h("debug",K,"skip: not in server wake set",{seq:B,message_id:I.id}),ee(r,"skip",{reason:"not_in_wake_set",channel_id:E,seq:B,message_id:I.id}),_t(r,E,I.seq);return}}else if(!p.deliverBroadcastMessages&&!Ie){h("debug",K,"skip broadcast message by context policy",{seq:B,message_id:I.id}),ee(r,"skip",{reason:"context_policy_broadcast_message",channel_id:E,seq:B,message_id:I.id}),_t(r,E,I.seq);return}}if(Pt&&I.sender_kind!=="system"&&Array.isArray(it)){if(!(it.includes(r)||Ie)){h("debug",K,"skip thread reply: not in server wake set",{seq:B,message_id:I.id}),ee(r,"skip",{reason:"thread_not_in_wake_set",channel_id:E,seq:B,message_id:I.id}),_t(r,E,I.seq);return}}else if(Pt&&I.sender_kind!=="system"&&!p.deliverThreadBroadcastMessages&&!Ie){h("debug",K,"skip thread broadcast message by context policy",{seq:B,message_id:I.id}),ee(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:E,seq:B,message_id:I.id}),_t(r,E,I.seq);return}let Ge;try{Ge=await N(E)}catch(Y){k(K,"failed to resolve channel name \u2014 dropping message",Y);return}if(!Ge){h("warn",K,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:E,messageSeq:B});return}let Ne;if(I.parent_message_id){let Y,Ce=[],Re=!1;if(e.getMessageById)try{Y=await e.getMessageById(r,I.parent_message_id)}catch(Qe){Re=!0,h("warn",K,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:I.parent_message_id,err:Qe instanceof Error?Qe.message:String(Qe)})}else Re=!0;if(vt&&I.parent_message_id===V)Ce=vt.slice(0,p.threadReplyLimit);else if(e.getThreadReplies)try{Ce=await e.getThreadReplies(r,I.parent_message_id,p.threadReplyLimit)}catch(Qe){Re=!0,h("warn",K,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:I.parent_message_id,err:Qe instanceof Error?Qe.message:String(Qe)})}else Re=!0;Ne=Wy(I,Y,Ce,Ge),Re&&h("info",K,"thread context degraded (parent or replies missing)",{channelId:E,parent_message_id:I.parent_message_id})}else Ne=is(I,Ge);let er=I.parent_message_id?[{name:"thread_context",bytes:Ne.length,reply_limit:p.threadReplyLimit},{name:"incoming",bytes:I.content.length}]:[{name:"inbound_message",bytes:Ne.length}];if(ee(r,"context_injection",{topic:T.topic,channel_id:E,channel_name:Ge,message_id:I.id,parent_message_id:I.parent_message_id??null,sender_kind:I.sender_kind,mode:I.parent_message_id?"thread":"main",explicitly_mentioned:Ie,policy:{deliver_broadcast_messages:p.deliverBroadcastMessages,deliver_system_messages:p.deliverSystemMessages,deliver_thread_broadcast_messages:p.deliverThreadBroadcastMessages,thread_reply_limit:p.threadReplyLimit},sections:er,rendered_bytes:Ne.length}),!I.parent_message_id&&I.sender_kind!=="system"&&Array.isArray(D.wake_agent_ids)&&D.wake_agent_ids.includes(r)&&!Ie&&(Ne+=`
|
|
487
487
|
|
|
488
|
-
[routing] No teammate was @-named in this message \u2014 you have been chosen to handle it. Answer it directly. If it truly belongs to another teammate's role, hand it off by @-mentioning them in one short line instead.`),
|
|
489
|
-
(\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${Ge}" \u2014\u2014 \u4F60\u7684\u7EAF\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u9001\u8FBE\u4EFB\u4F55\u4EBA)`),C(E).enqueueUserTurn(
|
|
488
|
+
[routing] No teammate was @-named in this message \u2014 you have been chosen to handle it. Answer it directly. If it truly belongs to another teammate's role, hand it off by @-mentioning them in one short line instead.`),Ne+=await v(I),!I.parent_message_id&&I.sender_kind!=="system"&&(Ne+=`
|
|
489
|
+
(\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${Ge}" \u2014\u2014 \u4F60\u7684\u7EAF\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u9001\u8FBE\u4EFB\u4F55\u4EBA)`),C(E).enqueueUserTurn(Ne),f&&I.sender_kind!=="system")try{f.set(r,I.id)}catch(Y){k(K,"contextTracker.set threw (non-fatal)",Y)}if(m)try{m(E)}catch(Y){k(K,"onInboundMessage callback threw (non-fatal)",Y)}_t(r,E,I.seq),h("info",K,"enqueued inbound message",{channelId:E,channelName:Ge,seq:I.seq,sender_id:I.sender_id}),ee(r,"inbound",{topic:T.topic,channel_id:E,channel_name:Ge,seq:I.seq,message_id:I.id,message_id_short:I.id.replace(/-/g,"").slice(0,8),parent_message_id:I.parent_message_id??null,sender_id:I.sender_id,sender_kind:I.sender_kind,sender_display_name:I.sender_display_name??null,content_preview:I.content.slice(0,120),rendered_bytes:Ne.length})}let A=T=>R(T).catch(D=>{k(K,"unhandled error in handleEvent",D)});return{start(){M(),e.subscribe(o,A),h("info",K,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,A),h("info",K,"InboxCoordinator stopped",{workroomId:o})},onInjected(T){w=T}}}var K,Qd=O(()=>{"use strict";$i();le();Rt();ss();K="inboxDelivery"});var Zd,os,eu=O(()=>{"use strict";le();Zd="typingNotifier",os=class{constructor(e){this.gateway=e}gateway;inFlight=new Map;start(e,t){this.inFlight.has(e)||(this.inFlight.set(e,t),this.gateway.notifyTyping&&this.gateway.notifyTyping(e,t,"started").catch(r=>{h("warn",Zd,"notifyTyping(started) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}stop(e){let t=this.inFlight.get(e);t&&(this.inFlight.delete(e),this.gateway.notifyTyping&&this.gateway.notifyTyping(e,t,"stopped").catch(r=>{h("warn",Zd,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var Qn,as,tu=O(()=>{"use strict";le();Rt();Qn="agentPresence",as=class{constructor(e){this.gateway=e}gateway;current=new Map;set(e,t,r){let s=this.current.get(e);if(s===t){h("debug",Qn,"presence transition deduped",{agentId:e,state:t,channelId:r});return}if(this.current.set(e,t),h("info",Qn,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),ee(e,"presence",{state:t,prev:s??null,channel_id:r??null}),!this.gateway.notifyAgentStatus){h("warn",Qn,"gateway.notifyAgentStatus MISSING \u2014 presence not sent to server",{agentId:e,state:t});return}h("debug",Qn,"notifyAgentStatus \u2192",{agentId:e,state:t}),this.gateway.notifyAgentStatus(e,r,t).catch(i=>{h("warn",Qn,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function nu(n){let{agentId:e,onFire:t,clock:r=()=>Date.now()}=n,s=new Map,i=new Map;function o(l){let u=s.get(l);u?.timer&&clearTimeout(u.timer),s.delete(l)}function a(){for(let l of s.values())l.timer&&clearTimeout(l.timer);s.clear()}function c(l){let u=s.get(l);if(!u)return;let m=u.reminder.version,f=i.get(l);f!==void 0&&f>=m||(i.set(l,m),Promise.resolve().then(()=>t(u.reminder)).catch(p=>{k(jy,`onFire callback failed for reminder ${l} (agent ${e})`,p)}))}function d(l){let u=s.get(l.id);if(u&&u.reminder.version>=l.version)return;u?.timer&&clearTimeout(u.timer);let m=Date.parse(l.fireAt),f=r(),p=Math.max(0,m-f);if(m<=f){s.set(l.id,{reminder:l,timer:null}),c(l.id);return}let g=setTimeout(()=>c(l.id),p);typeof g.unref=="function"&&g.unref(),s.set(l.id,{reminder:l,timer:g})}return{upsert:d,cancel(l,u){o(l)},snapshot(l){a();for(let u of l)d(u)},clear(){a()},stop(){a(),i.clear()}}}var jy,ru=O(()=>{"use strict";le();jy="reminderCache"});function su(n){let e=n?.ttlMs??3e5,t=new Map;return{set(r,s){let i=t.get(r);t.set(r,{id:s,expiresAt:Date.now()+e}),h("debug",Hi,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),ee(r,"context",{action:"set",message_id:s,message_id_short:s.replace(/-/g,"").slice(0,8),prev_message_id:i?.id??null,ttl_ms:e})},get(r){let s=t.get(r);if(!s){h("debug",Hi,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),h("debug",Hi,"context get expired",{agentId:r,messageId:s.id}),ee(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var Hi,iu=O(()=>{"use strict";le();Rt();Hi="contextTracker"});import{readFileSync as Jy,writeFileSync as Yy,existsSync as Vy,mkdirSync as zy}from"fs";import{dirname as Ky}from"path";function au(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function cu(){return{version:1,entities:{},relations:{},observations:[],obs_seq:0}}function qi(n,e){for(let t of e.members)n.upsertEntity({id:t.id,kind:t.kind,display_name:t.display_name,role:t.role,description:t.description});for(let t of e.channels){n.upsertEntity({id:t.id,kind:"channel",display_name:t.name,data:{workroom_id:e.workroom.id,visibility:t.visibility}});for(let r of t.member_ids)n.upsertRelation({from_id:t.id,to_id:r,kind:"has_member"}),n.upsertRelation({from_id:r,to_id:t.id,kind:"member_of"})}}var ou,cs,lu=O(()=>{"use strict";ou=500;cs=class{constructor(e){this.path=e;if(Vy(e))try{let t=Jy(e,"utf8");this.file=JSON.parse(t),this.file.entities||(this.file.entities={}),this.file.relations||(this.file.relations={}),this.file.observations||(this.file.observations=[]),typeof this.file.obs_seq!="number"&&(this.file.obs_seq=0)}catch{this.file=cu()}else this.file=cu(),zy(Ky(e),{recursive:!0})}path;file;dirty=!1;flushTimer=null;upsertEntity(e){let t=this.file.entities[e.id];this.file.entities[e.id]={id:e.id,kind:e.kind,display_name:e.display_name??t?.display_name,role:e.role??t?.role,description:e.description??t?.description,data:e.data??t?.data,updated_at:new Date().toISOString()},this.markDirty()}upsertRelation(e){this.file.relations[au(e)]={from_id:e.from_id,to_id:e.to_id,kind:e.kind,data:e.data,updated_at:new Date().toISOString()},this.markDirty()}removeRelation(e){delete this.file.relations[au(e)],this.markDirty()}logObservation(e){this.file.obs_seq+=1,this.file.observations.push({id:this.file.obs_seq,entity_id:e.entity_id,channel_id:e.channel_id,kind:e.kind,data:e.data,observed_at:new Date().toISOString()}),this.file.observations.length>ou&&this.file.observations.splice(0,this.file.observations.length-ou),this.markDirty()}listChannelMembers(e){let t=[];for(let r of Object.values(this.file.relations))if(r.kind==="has_member"&&r.from_id===e){let s=this.file.entities[r.to_id];s&&t.push(s)}return t}listWorkroomEntities(e){let t=new Set;for(let s of Object.values(this.file.entities))s.kind==="channel"&&s.data?.workroom_id===e&&t.add(s.id);if(t.size===0)return Object.values(this.file.entities).filter(s=>s.kind!=="channel");let r=new Set;for(let s of Object.values(this.file.relations))s.kind==="has_member"&&t.has(s.from_id)&&r.add(s.to_id);return Array.from(r).map(s=>this.file.entities[s]).filter(s=>!!s)}getEntity(e){return this.file.entities[e]??null}flush(){this.dirty&&(Yy(this.path,JSON.stringify(this.file,null,2),{encoding:"utf8",mode:384}),this.dirty=!1)}close(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.flush()}markDirty(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null;try{this.flush()}catch{}},250),typeof this.flushTimer=="object"&&this.flushTimer&&"unref"in this.flushTimer&&this.flushTimer.unref())}}});function Xe(n){return n.replace(/-/g,"").slice(0,8)}function wn(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+Xe(e)}function Zn(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+Xe(e)}function du(n){let{subscribe:e,unsubscribe:t,host:r,hostFor:s,selfAgentId:i,workroomId:o,companion:a,quietSeconds:c,maxRepliesPerWindow:d,windowSeconds:l,contextPolicy:u=Xn,now:m=()=>Date.now()}=n,f=[],p=new Map,g=3e4,y=new Set;function S(C=m()){f.push(C);let w=C-l*1e3;for(;f.length>0&&f[0]<w;)f.shift()}function v(C){return f.length===0?Number.POSITIVE_INFINITY:C-f[f.length-1]}function _(C){let w=C-l*1e3;for(;f.length>0&&f[0]<w;)f.shift();return f.length}function b(C){return C?a.listChannelMembers(C).some(R=>R.id===i):!1}function P(C){let w=m();for(let[R,A]of p)w-A>g&&p.delete(R);return p.has(C)?!1:(p.set(C,w),!0)}function x(C){return`assigned:${C}:${i}`}function N(C,w){let R=m(),A=v(R);if(A<c*1e3)return h("debug",st,"wake skipped: quiet_seconds gate",{reason:C,taskId:w,sinceMs:A,quietSeconds:c}),!1;let T=_(R);return T>=d?(h("debug",st,"wake skipped: max_replies_per_window gate",{reason:C,taskId:w,count:T,max:d,windowSeconds:l}),!1):!0}function G(C,w,R,A){h("info",st,"poking agent with system event",{reason:w,taskId:R,channelId:A}),ee(i,"wake",{reason:w,task_id:R,task_id_short:Xe(R),bytes:C.length}),(A&&s?s(A):r).enqueueUserTurn(C)}function J(C){let w=C.task_id,R=C.channel_id,A=C.title,T=C.created_by,D=C.owner_id??C.assignee_id;if(!w||T===i||D===i)return;if(!(u.wakeOnChannelTaskCreated&&b(R))){h("debug",st,"task.created not relevant \u2014 skip",{taskId:w});return}if(!P(`created:${w}`)||!N("task-created",w))return;let B=wn(a,T),F=Zn(a,R),V=`[system event: task #${Xe(w)} was just created in your channel ${F}]
|
|
490
490
|
Title: ${A?`"${A}"`:"(no title)"}
|
|
491
|
-
Created by ${
|
|
492
|
-
You may want to volunteer for it, acknowledge, or skip.`;G(V,"task-created",
|
|
491
|
+
Created by ${B}.${D?` Assigned to ${wn(a,D)}.`:" No assignee yet."}
|
|
492
|
+
You may want to volunteer for it, acknowledge, or skip.`;G(V,"task-created",w,R)}function W(C){let{taskId:w,channelId:R,parentMessageId:A,assignerId:T,reason:D,dedupeAlreadyReserved:E}=C;if(!E){if(y.has(x(w)))return h("debug",st,"assigned wake suppressed: boot-scoped self-heal reservation",{taskId:w,reason:D}),!1;if(!P(x(w)))return!1}if(!N(D,w))return!1;let B=Zn(a,R),F=T?` by ${wn(a,T)}`:"",V=A?`
|
|
493
493
|
|
|
494
494
|
This task lives in a THREAD under the originating message. Acknowledgements, clarifying questions, drafts, status, and final delivery for THIS task go in the thread using:
|
|
495
|
-
mio message reply --parent ${A} --target ${
|
|
495
|
+
mio message reply --parent ${A} --target ${B} <<'EOF'
|
|
496
496
|
\u2026
|
|
497
497
|
EOF
|
|
498
|
-
If you are coordinating and need to split out separate independent work for another teammate, do that as a fresh main-channel one-line @handoff with \`mio message send\`; one main-channel @handoff per separate task.`:"",
|
|
499
|
-
Channel: ${
|
|
500
|
-
You already OWN this task and it is already in_progress \u2014 do NOT list, claim, or set in_progress; just start the work now. When the deliverable is done, set it done with \`mio task update #${Xe(
|
|
501
|
-
Channel: ${
|
|
498
|
+
If you are coordinating and need to split out separate independent work for another teammate, do that as a fresh main-channel one-line @handoff with \`mio message send\`; one main-channel @handoff per separate task.`:"",oe=`[system event: task #${Xe(w)} was assigned to you${F}]
|
|
499
|
+
Channel: ${B}
|
|
500
|
+
You already OWN this task and it is already in_progress \u2014 do NOT list, claim, or set in_progress; just start the work now. When the deliverable is done, set it done with \`mio task update #${Xe(w)} --status done\`. Briefly acknowledge then begin.`+V;return G(oe,D,w,R),!0}function Q(C){let w=C.task_id,R=C.channel_id,A=C.assignee_id,T=C.assigner_id,D=C.parent_message_id;if(w&&T!==i){if(A!==i){h("debug",st,"task.assigned not to self \u2014 skip",{taskId:w,assigneeId:A});return}W({taskId:w,channelId:R,parentMessageId:D,assignerId:T,reason:"task-assigned"})}}function ne(C){let w=C.task_id,R=C.channel_id,A=C.from,T=C.to,D=C.actor_id,E=C.assignee_id;if(!w||D===i)return;if(!(E===i||u.wakeOnChannelTaskStatus&&b(R))){h("debug",st,"task.status_changed not relevant \u2014 skip",{taskId:w});return}let F=C.review_verdict,V=C.review_feedback;if(F==="bounce"&&E===i){if(!P(`bounce:${w}`))return;let vt=wn(a,D),Ie=Zn(a,R),Pt=V&&V.trim()?V.trim():"(see the task thread)",it=`[system event: your task #${Xe(w)} was BOUNCED back for rework by ${vt} after independent review]
|
|
501
|
+
Channel: ${Ie}.
|
|
502
502
|
Reviewer feedback: ${Pt}
|
|
503
|
-
Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${Xe(
|
|
503
|
+
Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${Xe(w)} --channel ${Ie} --status done\` again \u2014 it auto-closes after this one rework, no second review. This is NOT optional; do not stay silent.`;G(it,"task-bounce",w,R);return}if(!P(`status:${w}:${T}`)||!N("task-status",w))return;let oe=wn(a,D),fe=Zn(a,R),I=`[system event: task #${Xe(w)} status changed from ${A??"?"} to ${T??"?"} by ${oe}]
|
|
504
504
|
Channel: ${fe}.
|
|
505
|
-
Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;G(I,"task-status",
|
|
505
|
+
Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;G(I,"task-status",w,R)}function H(C){let w=C.task_id,R=C.channel_id,A=C.reviewer_id,T=C.owner_id,D=C.parent_message_id,E=C.title,B=C.number;if(!w)return;if(A!==i){h("debug",st,"review_requested not for self \u2014 skip",{taskId:w,reviewerId:A});return}if(!P(`review:${w}`))return;let F=wn(a,T),V=Zn(a,R),oe=B!==void 0?`#${B}`:`#${Xe(w)}`,fe=D?`
|
|
506
506
|
Get the surrounding context, then inspect the ACTUAL deliverable (its files \u2014 build it, run its tests), not just the chat:
|
|
507
|
-
mio message read --channel ${V} --around ${Xe(
|
|
507
|
+
mio message read --channel ${V} --around ${Xe(D)}
|
|
508
508
|
Post your review findings in the task thread:
|
|
509
|
-
mio message reply --parent ${
|
|
509
|
+
mio message reply --parent ${D} --target ${V}`:"",I=`[system event: task ${oe} "${E??""}" by ${F} is awaiting YOUR independent review]
|
|
510
510
|
Channel: ${V}.${fe}
|
|
511
511
|
|
|
512
512
|
You are the INDEPENDENT reviewer. Do an adversarial / mutation audit of the ACTUAL deliverable \u2014 do not take the author's word that it works:
|
|
@@ -516,12 +516,12 @@ You are the INDEPENDENT reviewer. Do an adversarial / mutation audit of the ACTU
|
|
|
516
516
|
|
|
517
517
|
Then submit your verdict:
|
|
518
518
|
\u2022 Everything works AND every claimed feature has a test that fails when broken \u2192
|
|
519
|
-
mio task review ${
|
|
519
|
+
mio task review ${oe} --channel ${V} --pass
|
|
520
520
|
\u2022 A feature is unprotected (mutation stayed green), or you found a real bug \u2192
|
|
521
|
-
mio task review ${
|
|
522
|
-
A bounce sends it back to ${F} to add the missing test/fix; after their rework it closes without a second review.`;G(I,"task-review",
|
|
521
|
+
mio task review ${oe} --channel ${V} --bounce --feedback "<exactly what is untested/broken>"
|
|
522
|
+
A bounce sends it back to ${F} to add the missing test/fix; after their rework it closes without a second review.`;G(I,"task-review",w,R)}function ie(C){C.sender_id===i&&S()}let M=C=>{try{let w=C.payload??{};switch(C.topic){case"task.created":J(w);break;case"task.assigned":Q(w);break;case"task.status_changed":ne(w);break;case"task.review_requested":H(w);break;case"message.created":ie(w);break;default:break}}catch(w){h("warn",st,"task wake handler error (non-fatal)",{err:String(w)})}};return{start(){e(o,M),h("info",st,"task wake router started",{workroomId:o,selfAgentId:i,quietSeconds:c,maxRepliesPerWindow:d,windowSeconds:l})},stop(){try{t(o,M)}catch{}},noteSelfPost:S,synthesizeAssignedWake(C){return C.task_id?W({taskId:C.task_id,channelId:C.channel_id,parentMessageId:C.parent_message_id,reason:"task-assigned-selfheal",dedupeAlreadyReserved:!0}):!1},reserveAssignedDedupeKeys(C){for(let w of C)w&&(P(x(w)),y.add(x(w)))}}}var st,uu=O(()=>{"use strict";le();Rt();ss();st="taskWakeRouter"});import{spawn as Xy}from"node:child_process";import{readFileSync as ls,writeFileSync as fu,existsSync as ds,renameSync as Qy,statSync as Zy,unlinkSync as e_}from"node:fs";import{join as us}from"node:path";function yu(n){let e=us(n.mioDir,"persona-counter.json"),t=us(n.mioDir,"persona.md"),r=t+".tmp",s=n.claudeCommand??yn()??"claude",i=!1,o=0,a=!1,c=d();function d(){if(ds(e))try{let p=ls(e,"utf8"),g=JSON.parse(p);if(g&&typeof g.messages_since_last_extract=="number")return{version:1,messages_since_last_extract:g.messages_since_last_extract,last_extract_at:g.last_extract_at??null}}catch{}return{version:1,messages_since_last_extract:0,last_extract_at:null}}function l(){try{fu(e,JSON.stringify(c,null,2),{encoding:"utf8",mode:384})}catch(p){k(be,"persona-counter write failed (non-fatal)",p)}}function u(){let p=Date.now();if(i)return{go:!1,reason:"already running"};if(p-o<n.quietSeconds*1e3)return{go:!1,reason:"within quietSeconds"};if(c.messages_since_last_extract>=hu)return{go:!0,reason:`message threshold (${c.messages_since_last_extract})`};if(c.last_extract_at){let g=Date.parse(c.last_extract_at);if(!Number.isNaN(g)&&p-g>=t_)return{go:!0,reason:"elapsed 24h"}}return{go:!1,reason:"no trigger"}}async function m(p){if(!i&&!a){i=!0,o=Date.now();try{h("info",be,"persona extraction starting",{agentId:n.agentId,reason:p});let g=[];if(n.channelId)try{g=(await n.gateway.getChannelMessages(n.workroomId,n.channelId,void 0,pu)).messages.slice(-pu).map(J=>({sender:J.sender_display_name||`${J.sender_kind}:${J.sender_id.slice(0,8)}`,content:J.content,at:J.created_at}))}catch(N){k(be,"getChannelMessages failed (continuing with empty messages)",N)}let y=[];try{let N=us(n.mioDir,"companion.json");if(ds(N)){let G=ls(N,"utf8"),J=JSON.parse(G);y=(Array.isArray(J.observations)?J.observations:[]).slice(-n_)}}catch(N){k(be,"companion.json read failed (continuing without observations)",N)}let S=[];try{n.channelId&&(S=n.companion.listChannelMembers(n.channelId).map(N=>({id:N.id,name:N.display_name??N.id,role:N.role??"",description:N.description??""}))),S.length===0&&(S=n.companion.listWorkroomEntities(n.workroomId).map(N=>({id:N.id,name:N.display_name??N.id,role:N.role??"",description:N.description??""})))}catch(N){k(be,"roster derivation failed",N)}let v="";if(ds(t))try{v=ls(t,"utf8")}catch{}let _=r_(n.displayName,n.handle,n.role),b=s_({existingPersona:v,messages:g,observations:y,roster:S}),P=await i_(s,_,b,n.workspace,n.spawnEnv);if(!P||P.trim().length===0){h("warn",be,"persona extraction produced empty output (keeping prior persona)",{agentId:n.agentId});return}let x=P.trim();x.startsWith("<!-- mio:persona v1 -->")||(x=`<!-- mio:persona v1 -->
|
|
523
523
|
|
|
524
|
-
${x}`),x=o_(x);try{fu(r,x,{encoding:"utf8",mode:384}),Qy(r,t)}catch(N){k(be,"persona.md atomic write failed",N);try{e_(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),l(),h("info",be,"persona extraction completed",{agentId:n.agentId,bytes:x.length,reason:
|
|
524
|
+
${x}`),x=o_(x);try{fu(r,x,{encoding:"utf8",mode:384}),Qy(r,t)}catch(N){k(be,"persona.md atomic write failed",N);try{e_(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),l(),h("info",be,"persona extraction completed",{agentId:n.agentId,bytes:x.length,reason:p})}catch(g){k(be,"persona extraction failed (keeping prior persona)",g)}finally{i=!1}}}function f(p){let{go:g,reason:y}=u();if(!g){h("debug",be,"extraction skipped",{agentId:n.agentId,reason:p,gate:y});return}m(p)}return{noteMessage(){a||(c.messages_since_last_extract+=1,l(),c.messages_since_last_extract>=hu&&f("threshold"))},kick(p="kick"){if(a)return;let g=Date.now();if(i){h("debug",be,"kick ignored: already running",{agentId:n.agentId});return}if(g-o<n.quietSeconds*1e3){h("debug",be,"kick ignored: within quietSeconds",{agentId:n.agentId});return}m(p)},stop(){a=!0}}}function r_(n,e,t){let r=t&&t.trim()?t.trim():"(unspecified)";return`You are a memory consolidator for AI agent ${n} (handle ${e}, role ${r}).
|
|
525
525
|
|
|
526
526
|
Below you'll see:
|
|
527
527
|
- The agent's existing persona.md (their cumulative knowledge so far)
|
|
@@ -549,16 +549,16 @@ Constraints:
|
|
|
549
549
|
|
|
550
550
|
Output the persona.md now.`}function s_(n){let e=[];if(e.push("=== EXISTING persona.md ==="),e.push(n.existingPersona.trim()||"(none yet \u2014 first extraction)"),e.push(""),e.push("=== ROSTER (current channel members) ==="),n.roster.length===0)e.push("(roster unknown)");else for(let t of n.roster){let r=t.description?` \u2014 ${t.description}`:"";e.push(`- ${t.name} (${t.role||"unspecified"})${r}`)}if(e.push(""),e.push("=== LAST 50 MESSAGES (oldest \u2192 newest) ==="),n.messages.length===0)e.push("(no recent messages)");else for(let t of n.messages){let r=t.content.length>400?t.content.slice(0,400)+"\u2026":t.content;e.push(`[${t.at}] ${t.sender}: ${r.replace(/\n+/g," ")}`)}if(e.push(""),e.push("=== RECENT OBSERVATIONS (companion graph) ==="),n.observations.length===0)e.push("(no observations recorded)");else for(let t of n.observations)e.push(JSON.stringify(t));return e.join(`
|
|
551
551
|
`)}function i_(n,e,t,r,s){return new Promise(i=>{let o=["-p","--output-format","text","--append-system-prompt",e,"--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--permission-mode","bypassPermissions","--setting-sources","project,local"],a={...s??process.env};delete a.CLAUDECODE;let c="",d="",l=!1,u=Xy(n,o,{cwd:r,env:a,stdio:["pipe","pipe","pipe"]}),m=setTimeout(()=>{if(!l){l=!0;try{u.kill("SIGTERM")}catch{}k(be,"one-shot claude timed out",{timeoutMs:gu,stderrSnippet:d.slice(0,200)}),i("")}},gu);m.unref?.(),u.stdout?.on("data",f=>{c+=typeof f=="string"?f:f.toString("utf8")}),u.stderr?.on("data",f=>{d+=typeof f=="string"?f:f.toString("utf8")}),u.on("error",f=>{l||(l=!0,clearTimeout(m),k(be,"one-shot claude spawn error",f),i(""))}),u.on("exit",f=>{if(!l){if(l=!0,clearTimeout(m),f!==0){h("warn",be,"one-shot claude exited non-zero",{code:f,stderrSnippet:d.slice(0,400),stdoutSnippet:c.slice(0,400)}),i("");return}i(c)}});try{u.stdin?.write(t),u.stdin?.end()}catch(f){k(be,"one-shot claude stdin write failed",f)}})}function o_(n){if(n.length<=mu)return n;let e=n.split(`
|
|
552
|
-
`),t=[],r=[],s=null;for(let l of e)l.startsWith("## ")?(s&&t.push(s),s={header:l,body:[]}):s?s.body.push(l):r.push(l);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((l,u)=>{let m=i.findIndex(
|
|
552
|
+
`),t=[],r=[],s=null;for(let l of e)l.startsWith("## ")?(s&&t.push(s),s={header:l,body:[]}):s?s.body.push(l):r.push(l);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((l,u)=>{let m=i.findIndex(p=>l.header.includes(p)),f=i.findIndex(p=>u.header.includes(p));return(m===-1?99:m)-(f===-1?99:f)}),a=[...r],c=mu-a.join(`
|
|
553
553
|
`).length,d=new Set;for(let l of o){let u=l.header.length+1+l.body.join(`
|
|
554
554
|
`).length+1;u<=c&&(d.add(l),c-=u)}for(let l of t)d.has(l)&&(a.push(l.header),a.push(...l.body));return a.join(`
|
|
555
555
|
`).trim()+`
|
|
556
|
-
`}function _u(n){let e=us(n,"persona.md");if(!ds(e))return null;try{let t=Zy(e);if(!t.isFile()||t.size===0)return null;let s=ls(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var be,hu,t_,gu,pu,n_,mu,wu=O(()=>{"use strict";ts();le();be="personaCrystallizer",hu=50,t_=1440*60*1e3,gu=6e4,pu=50,n_=50;mu=4e3});var Ru={};
|
|
556
|
+
`}function _u(n){let e=us(n,"persona.md");if(!ds(e))return null;try{let t=Zy(e);if(!t.isFile()||t.size===0)return null;let s=ls(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var be,hu,t_,gu,pu,n_,mu,wu=O(()=>{"use strict";ts();le();be="personaCrystallizer",hu=50,t_=1440*60*1e3,gu=6e4,pu=50,n_=50;mu=4e3});var Ru={};Le(Ru,{bootAgentSpine:()=>Cu,deriveAgentWorkspace:()=>xu,normalizeRuntime:()=>Tu,runDaemon:()=>Ji,startAgentSpine:()=>Su});import{join as Pe,dirname as a_}from"path";import{fileURLToPath as c_}from"url";import{homedir as l_,hostname as vu,arch as d_}from"os";import{unlink as u_,writeFile as bu,mkdir as Wi,readdir as f_,copyFile as h_,readFile as g_}from"fs/promises";import{readFileSync as p_}from"node:fs";import{existsSync as m_}from"fs";import{spawnSync as y_}from"child_process";import{randomUUID as ji}from"crypto";async function Su(n){let{config:e,machineToken:t,workingDirectory:r,gateway:s,agentId:i,launchId:o,agentHandle:a,displayName:c,description:d,role:l,spawnFn:u,claudeCommand:m,codexCommand:f,model:p,runtime:g="claude",reasoningEffort:y,contextTracker:S,presenceTracker:v,contextPolicy:_}=n,b=n.execContext??Bi(),P=_??Vd({role:l,displayName:c,description:d,capabilities:n.serverCapabilities}),x=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:N,spawnEnv:G,proxyHandle:J}=await Ed({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:x,execContext:b,...S?{contextTracker:S}:{}}),W=null,Q=Pe(N,"companion.json"),ne=new cs(Q),H=null,ie=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{H=await s.getWorkroomRoster(ie),qi(ne,H),h("info",$,"CompanionGraph hydrated from roster",{agentId:i,channels:H.channels.length,members:H.members.length})}catch(R){k($,"CompanionGraph hydrate failed (continuing with empty graph)",R)}let M;if(H){let A=H.channels.filter(T=>T.member_ids.includes(i))[0]??H.channels[0];if(A){let T=new Map(H.members.map(F=>[F.id,F])),D=A.member_ids.map(F=>T.get(F)).filter(F=>!!F),E=new Set(A.member_ids),B=H.members.filter(F=>!E.has(F.id));M={channelId:A.id,channelName:A.name,inChannel:D,otherInWorkroom:B}}}try{let Ne=function(){try{let L=p_(Pe(r,"MEMORY.md"),"utf-8").trim();return L?`
|
|
557
557
|
|
|
558
558
|
[\u4F60\u7684\u6301\u4E45\u8BB0\u5FC6 MEMORY.md \u2014\u2014 \u5148\u8BFB\u5B8C\u518D\u5F00\u59CB\u5DE5\u4F5C;\u5176\u4E2D\u7D22\u5F15\u6307\u5411\u7684\u6587\u4EF6\u53EF\u7528 Read \u6253\u5F00]
|
|
559
|
-
${
|
|
560
|
-
\u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:B}`:""}catch{return""}},er=function(B){let z=Gd(N,p,B);h("info",D,z?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:p,channelId:B,...z?{sessionId:z}:{}});let bt=Pt(B),Ne={workingDirectory:r,systemPromptPath:T,mcpConfigPath:L,spawnEnv:G,firstTurnText:z?E:E+Ie(),...z?{sessionId:z}:{},...u?{spawnFn:u}:{},...bt?{presenceTracker:bt,agentId:i}:{}},ke=p==="codex"?Ud({...Ne,model:g??"gpt-5-codex",...y?{reasoningEffort:y}:{},...f?{codexCommand:f}:{}}):Md({...Ne,model:g??"sonnet",...m?{claudeCommand:m}:{}});return ke.onSessionId(he=>{h("info",D,"agent session id",{agentId:i,runtime:p,channelId:B,sessionId:he}),Wd(N,p,he,B)}),ke.onInjected(he=>{for(let ot of fe)try{ot(he)}catch{}}),ke.onBoundary(()=>{for(let he of I)try{he()}catch{}}),ke.onExit(he=>{for(let ot of vt)try{ot(he)}catch{}}),ke.onTurnError?.(he=>{let ot=Date.now();if(he===Ge&&ot-it<6e4)return;Ge=he,it=ot;let Qu=/usage limit/i.test(he)?"\u7528\u91CF\u5DF2\u8FBE\u4E0A\u9650,\u8BF7\u5145\u503C\u6216\u7A0D\u540E\u518D\u8BD5":/unauthor|auth|401|403/i.test(he)?"\u8BA4\u8BC1\u5931\u8D25,\u8BF7\u68C0\u67E5\u767B\u5F55/\u5BC6\u94A5":he.slice(0,160);xn(e.server_url,$,B,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${Qu})`,clientIdempotencyKey:ji(),agentId:i},t).catch(Zu=>k("run","post turn-error notice failed",Zu))}),ke.onCompact?.(()=>{xn(e.server_url,$,B,{content:`\u{1F9F9} ${c} \u5728\u672C\u9891\u9053\u7684\u4E0A\u4E0B\u6587\u521A\u5B8C\u6210\u4E86\u4E00\u6B21\u81EA\u52A8\u538B\u7F29(\u8F83\u65E9\u7684\u5BF9\u8BDD\u88AB\u7CBE\u7B80,\u7EC6\u8282\u53EF\u80FD\u9700\u8981\u91CD\u65B0\u63D0\u4F9B)`,clientIdempotencyKey:ji(),agentId:i},t).catch(he=>k("run","post compact notice failed",he))}),ke.start(),ke};var C=Ie,_=er;let R={agentId:i,handle:a,displayName:c,description:d,role:l,serverId:e.org_id,computer:`${vu()} (${e.machine_id})`,hostname:vu(),os:`${process.platform} ${d_()}`,workspace:r,runtime:p,capabilities:x,roster:M,persona:_u(N)??void 0},A=Ad(R),T=Pe(N,"system-prompt.md");if(await bu(T,A,{encoding:"utf8",mode:384}),p==="claude")try{let B=Pe(r,".claude","skills");await Wi(B,{recursive:!0});let z=a_(c_(import.meta.url)),bt=Pe(z,"..","..","runtimes","skills"),Ne=(await f_(bt)).filter(ke=>ke.endsWith(".md"));for(let ke of Ne){let he=ke.replace(/\.md$/,""),ot=Pe(B,he);await Wi(ot,{recursive:!0}),await h_(Pe(bt,ke),Pe(ot,"SKILL.md"))}h("info",D,"Materialised Claude skills",{count:Ne.length,destRoot:B})}catch(B){k(D,"Failed to materialise Claude skills (continuing without)",B)}let L=Pe(N,"mcp-config.json"),E="You are now online. Read MEMORY.md first if it exists, then wait for incoming messages. Do not send any message until you receive one.",$=e.autonomous_agent.workroom_id,F,V=H?.channels.find(B=>B.member_ids.includes(i))?.id,ae=new Map,fe=[],I=[],vt=[],De=new Map,Pt=B=>{if(v)return{set:(z,bt)=>{De.set(B,bt);let Ne=[...De.values()].some(ke=>ke!=="idle");v.set(z,Ne?"thinking":"idle")}}},it=0,Ge="",Y=B=>{let z=ae.get(B);return z||(z=er(B),ae.set(B,z)),z};W={start(){},enqueueUserTurn(B){Y(F??V??"__default").enqueueUserTurn(B)},stop(){for(let B of ae.values())try{B.stop()}catch{}},onBoundary(B){I.push(B)},onSessionId(B){},onExit(B){vt.push(B)},onInjected(B){fe.push(B)},onTurnError(B){},onCompact(B){}},Y(V??"__default");let Ce=nu({agentId:i,onFire:async B=>{W.enqueueUserTurn(`[reminder fired] ${B.title}`);try{await s.reminderFire(i,B.id,B.version)}catch(z){k(D,`reminder report-fire failed (agent ${i}, reminder ${B.id}) \u2014 local wake already happened; will retry on next sync`,z)}}}),Re=new os(s),Qe=Xd({gateway:s,host:W,hostFor:Y,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:$,reminderCache:Ce,onInboundMessage:B=>{F=B,Re.start(i,B)},...S?{contextTracker:S}:{},contextPolicy:P,mioDir:N,downloadAttachment:B=>Na(e.server_url,t,i,B).then(z=>({filename:z.filename,mime_type:z.mime_type,data_base64:z.data_base64}))});Qe.start(),W.onBoundary(()=>{Re.stop(i)});let tr=e.autonomous_agent,ps=du({subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:W,hostFor:Y,selfAgentId:i,workroomId:$,companion:ne,quietSeconds:tr.quiet_seconds,maxRepliesPerWindow:tr.max_replies_per_window,windowSeconds:tr.window_seconds,contextPolicy:P});ps.start();let Xu=M?.channelId??H?.channels.find(B=>B.member_ids.includes(i))?.id,ro=yu({workspace:r,mioDir:N,agentId:i,displayName:c,handle:a,role:l,workroomId:ie,channelId:Xu,gateway:s,companion:ne,quietSeconds:tr.quiet_seconds,spawnEnv:G,...m?{claudeCommand:m}:{}}),so=B=>{try{let z=B.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(B.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(ie).then(Ne=>qi(ne,Ne)).catch(Ne=>k(D,`roster refetch failed for ${B.topic}`,Ne)),z.channel_id&&z.member_id&&ne.logObservation({channel_id:z.channel_id,entity_id:z.member_id,kind:B.topic})),B.topic==="message.created"&&z.sender_id&&z.channel_id){ne.logObservation({entity_id:z.sender_id,channel_id:z.channel_id,kind:"sent_message"});try{ro.noteMessage()}catch(Ne){k(D,"personaCrystallizer.noteMessage error (non-fatal)",Ne)}}}catch(z){k(D,"companionWsHandler error (non-fatal)",z)}};return s.subscribe(ie,so),s.listReminders(i).then(B=>Ce.snapshot(B)).catch(B=>k(D,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,B)),E_({gateway:s,agentId:i,taskWakeRouter:ps,bootRoster:H,mioDir:N}).catch(B=>k(D,`cold-start task self-heal failed for agent ${i} (non-fatal)`,B)),h("info",D,"Agentic spine started",{agentId:i,workroomId:$,mioDir:N}),v_(Qe,W,J,i,Ce,{companion:ne,gateway:s,workroomId:ie,companionWsHandler:so,taskWakeRouter:ps,personaCrystallizer:ro})}catch(R){try{W?.stop()}catch{}try{ne.close()}catch{}throw await J.close().catch(()=>{}),R}}function v_(n,e,t,r,s,i){e.onExit(c=>{h("warn",D,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",D,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){k(D,"coord.stop() error",c)}try{s.stop()}catch(c){k(D,"reminderCache.stop() error",c)}try{e.stop()}catch(c){k(D,"host.stop() error",c)}try{await t.close()}catch(c){k(D,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){k(D,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){k(D,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){k(D,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){k(D,"companion.close() error",c)}}h("info",D,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function k_(n){try{let e=await g_(Pe(n,Eu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function S_(n,e){try{await bu(Pe(n,Eu),JSON.stringify([...e]),"utf8")}catch(t){k(D,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function E_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",D,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(g=>g.member_ids.includes(t)).map(g=>g.name).filter(g=>!!g)),o.length===0)try{o=(await e.getAgentChannels(t)).map(p=>p.name).filter(p=>!!p)}catch(g){k(D,`self-heal: getAgentChannels failed for agent ${t}`,g);return}if(o.length===0){h("debug",D,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],d=await Promise.allSettled(o.map(g=>a(t,g.startsWith("#")?g:`#${g}`)));for(let g of d)if(g.status==="fulfilled")for(let p of g.value)p.assignee_id===t&&p.status==="in_progress"&&c.push(p);else k(D,`self-heal: getTasks failed for a channel (agent ${t})`,g.reason);if(c.length===0){h("debug",D,"self-heal: no owned in_progress tasks",{agentId:t});return}let l=g=>{let p=g.updated_at??g.created_at,y=p?Date.parse(p):NaN;return Number.isFinite(y)?y:0};c.sort((g,p)=>l(p)-l(g));let u=await k_(i),m=c.filter(g=>!u.has(g.id)).slice(0,b_);if(m.length===0){h("debug",D,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(g=>g.id));let f=0;try{for(let g of m){let p=!1;if(g.parent_message_id&&e.getThreadReplies)try{p=(await e.getThreadReplies(t,g.parent_message_id,50)).some(S=>S.sender_id===t)}catch(y){k(D,`self-heal: getThreadReplies failed for task ${g.id} (agent ${t}) \u2014 treating as no activity`,y)}if(u.add(g.id),p){h("debug",D,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:g.id});continue}try{r.synthesizeAssignedWake({task_id:g.id,...g.channel_id?{channel_id:g.channel_id}:{},...g.parent_message_id?{parent_message_id:g.parent_message_id}:{}})&&(f+=1)}catch(y){k(D,`self-heal: synthesizeAssignedWake threw for task ${g.id} (agent ${t}) \u2014 task already marked seen, continuing`,y)}}}finally{await S_(i,u)}h("info",D,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:f})}function xu(n,e,t){let r=zn(n.replace(/^@/,"").toLowerCase()),s=zn(e),i=`${r}-${s}`,o=Pe(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function Tu(n){let e=typeof n=="string"?n.trim():"";return e===""||e==="claude"?{selected:"claude",raw:"claude"}:e==="codex"?{selected:"codex",raw:e}:{selected:"unsupported",raw:e}}function x_(n){try{let t=y_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&m_(t)}catch{return!1}}async function Cu(n){let{config:e,gateway:t,retrieveTokenFn:r=kt,mkdirFn:s=v=>Wi(v,{recursive:!0,mode:448}),startSpineFn:i=Su,mioDir:o=ku,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=x_}=n,d=e.autonomous_agent;if(!d?.enabled)return;let l,u;try{l=r(),u=await a(d.workroom_id)}catch(v){k(D,"Failed to start agentic spine \u2014 daemon continues without spine",v);return}let m=u.filter(v=>v.kind==="agent"&&v.machine_id===e.machine_id);if(m.length===0){h("error",D,`No agent for this machine in workroom ${d.workroom_id} \u2014 create one first (daemon continues without spine)`,{machine_id:e.machine_id,workroom_id:d.workroom_id});return}let f=su(),g=new as(t),p=[],y=async v=>{let w=v.handle??"@"+v.display_name,{selected:b,raw:P}=Tu(v.runtime);if(b==="codex"){if(!c("codex"))return h("error",D,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:v.id,handle:w}),!1}else if(b==="unsupported")return h("warn",D,`runtime '${P}' not supported; spine not started for this agent ${v.id}`,{agentId:v.id,handle:w,runtime:P}),!1;if(b==="claude"&&!c("claude"))return h("error",D,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:v.id,handle:w}),!1;try{let x=v.id,{workingDirectory:N}=xu(w,e.machine_id,o);await s(N);let G=v.display_name||w.replace(/^@/,""),J=v.description||"An AI agent running on this machine.",W=b==="codex"?"gpt-5-codex":"sonnet",Q={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},ne=v.model||W,H=Q[ne.trim().toLowerCase()]??ne,ie;if(b==="codex"){let C=v.capabilities;if(C&&typeof C=="object"){let _=C.reasoning_effort;typeof _=="string"&&(_==="low"||_==="medium"||_==="high")&&(ie=_)}ie=ie??"medium"}let M=await i({config:e,machineToken:l,workingDirectory:N,gateway:t,agentId:x,launchId:ji(),agentHandle:w,displayName:G,description:J,role:v.role,serverCapabilities:v.capabilities,model:H,runtime:b,...ie?{reasoningEffort:ie}:{},contextTracker:f,presenceTracker:g});return p.push(M),h("info",D,"Agentic spine started",{agentId:x,workroomId:d.workroom_id}),!0}catch(x){return k(D,`Failed to start spine for agent ${v.id} \u2014 continuing`,x),!1}return!0};for(let v of m)await y(v);if(p.length===0)return;let S=!1;return{handles:p,async stop(){S||(S=!0,await Promise.allSettled(p.map(v=>v.stop())))},async addAgentById(v){if(S)return!1;if(p.some(P=>P.agentId===v))return h("info",D,"hot-add skipped \u2014 spine already running",{agentId:v}),!1;let b=(await a(d.workroom_id)).find(P=>P.kind==="agent"&&P.id===v&&P.machine_id===e.machine_id);return b?y(b):(h("warn",D,"hot-add: agent not found on this machine",{agentId:v}),!1)}}}async function Ji(){h("info",D,"Starting mio-agent daemon");let n=je();h("info",D,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await nd();let e=new zr;await u_(Gi).catch(()=>{}),await e.listen(Gi);let t=new Kr("0.1.0");await t.listen(__,w_);let r=new qr(n);await r.start();let s=new Wr(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>zl().then(y=>{a=y}).catch(()=>{});c().then(()=>r.machineHeartbeat(!1,a).catch(y=>k(D,"Initial machine heartbeat failed (non-fatal)",y)));let d=setInterval(()=>{c()},o),l=setInterval(()=>{r.machineHeartbeat(!1,a).catch(y=>k(D,"Machine heartbeat failed (non-fatal)",y))},i),u=new Vr(r,{runtimes:n.runtimes,ipcSocketPath:Gi}),m=new jr(s,u),f=await Cu({config:n,gateway:r,getWorkroomMembersFn:y=>r.getWorkroomMembers(y)});if(f&&n.autonomous_agent?.enabled){let y=n.autonomous_agent.workroom_id;r.subscribe(y,S=>{if(S.topic!=="agent.created")return;let v=S.payload??{};if(v.machine_id!==n.machine_id)return;let w=v.agent_id;typeof w=="string"&&(h("info",D,"agent.created for this machine \u2014 hot-starting spine",{agentId:w}),f.addAgentById(w).then(b=>h("info",D,b?"hot-added agent spine \u2713":"hot-add no-op",{agentId:w})).catch(b=>k(D,"hot-add failed",b)))})}e.onMessage(y=>{if(h("info",D,"IPC message from subprocess",{type:y.type}),u.onIpcMessage(y),y.type==="kick_persona"){let S=y.agent_id,v=y.reason??"ipc_kick";if(!f){h("warn",D,"IPC kick_persona: no spine running \u2014 ignoring");return}let w=0;for(let b of f.handles)if(!(S&&b.agentId!==S))try{b.personaCrystallizer?.kick(v),w+=1}catch(P){k(D,"IPC kick_persona: kick failed",P)}h("info",D,"IPC kick_persona dispatched",{kicked:w,targetAgent:S,reason:v});return}if(y.type==="join_workroom"){let S=y.workroom_id;if(!S){h("warn",D,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}m.openWorkroom(S).then(v=>{v?h("info",D,"IPC join_workroom: workroom opened",{workroomId:S,sessionId:v.sessionId}):h("warn",D,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:S})}).catch(v=>{k(D,"IPC join_workroom: unexpected error (should not happen)",v)})}}),h("info",D,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let g=!1;async function p(y){if(!g){g=!0,h("info",D,`${y} received \u2014 initiating graceful shutdown`);try{clearInterval(l),clearInterval(d),await r.machineHeartbeat(!0).catch(S=>k(D,"Going-offline heartbeat failed (non-fatal)",S)),u.beginShutdown(),await u.drainIrreversible(),m.shutdownAll(),await s.stop(),f&&await f.stop(),await r.stop(),await e.stop(),await t.stop(),h("info",D,"Graceful shutdown complete")}catch(S){k(D,"Error during shutdown",S)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{p("SIGTERM")}),process.on("SIGINT",()=>{p("SIGINT")}),await new Promise(()=>{})}var D,ku,Gi,__,w_,b_,Eu,Yi=O(()=>{"use strict";Je();Yt();le();Jl();Kl();Ql();Zl();Mi();dd();ud();Yr();xd();Od();Ld();Hd();jd();Qd();eu();tu();ru();iu();lu();uu();wu();ss();dr();D="daemon",ku=Pe(l_(),".mio"),Gi=Pe(ku,"agent.sock"),__="127.0.0.1",w_=7878;b_=5,Eu="self-heal-seen.json"});var Vi={};Me(Vi,{runStart:()=>T_});async function T_(n){if(n.background){let{execFileSync:e}=await import("child_process");try{e("launchctl",["start","io.miomioos.mio-agent"]),console.log("Daemon started via LaunchAgent.")}catch{console.error("LaunchAgent not installed. Run: mio-agent install --background --version <semver>"),process.exit(1)}return}h("info","start","Starting mio-agent in foreground (dev mode, latest OK)"),await Ji()}var zi=O(()=>{"use strict";le();Yi()});import{createHash as C_}from"crypto";import{mkdtempSync as R_,rmSync as Au,readFileSync as A_,copyFileSync as O_,chmodSync as P_,renameSync as I_,existsSync as Ou}from"fs";import{execFileSync as vn}from"child_process";import{tmpdir as N_,platform as M_}from"os";import{join as fs}from"path";function B_(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function F_(n){return`https://github.com/${L_}/${$_}/releases/download/v${n}/`}function Pu(n,e){try{return vn("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function U_(n,e){for(let t of n.split(`
|
|
561
|
-
`)){let r=t.trim().match(/^([0-9a-f]{64})\s+(.+)$/);if(!r)continue;let s=r[2];if(s===e||s.endsWith(`/${e}`))return r[1]}return null}function Iu(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=B_(),i=n._baseUrl??F_(e),o=`mio-agent-${e}-${s}.tar.gz`,a=`mio-agent-${e}-${s}`,c=`mio-agent-${e}-manifest.json`;r("Verifying release manifest...");let d;try{d=JSON.parse(Pu(i+c,"release manifest"))}catch(
|
|
559
|
+
${L.length>6e3?L.slice(0,6e3)+`
|
|
560
|
+
\u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:L}`:""}catch{return""}},er=function(L){let z=Gd(N,g,L);h("info",$,z?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:g,channelId:L,...z?{sessionId:z}:{}});let bt=Pt(L),Me={workingDirectory:r,systemPromptPath:T,mcpConfigPath:D,spawnEnv:G,firstTurnText:z?E:E+Ne(),...z?{sessionId:z}:{},...u?{spawnFn:u}:{},...bt?{presenceTracker:bt,agentId:i}:{}},ke=g==="codex"?Ud({...Me,model:p??"gpt-5-codex",...y?{reasoningEffort:y}:{},...f?{codexCommand:f}:{}}):Md({...Me,model:p??"sonnet",...m?{claudeCommand:m}:{}});return ke.onSessionId(he=>{h("info",$,"agent session id",{agentId:i,runtime:g,channelId:L,sessionId:he}),Wd(N,g,he,L)}),ke.onInjected(he=>{for(let ot of fe)try{ot(he)}catch{}}),ke.onBoundary(()=>{for(let he of I)try{he()}catch{}}),ke.onExit(he=>{for(let ot of vt)try{ot(he)}catch{}}),ke.onTurnError?.(he=>{let ot=Date.now();if(he===Ge&&ot-it<6e4)return;Ge=he,it=ot;let Qu=/usage limit/i.test(he)?"\u7528\u91CF\u5DF2\u8FBE\u4E0A\u9650,\u8BF7\u5145\u503C\u6216\u7A0D\u540E\u518D\u8BD5":/unauthor|auth|401|403/i.test(he)?"\u8BA4\u8BC1\u5931\u8D25,\u8BF7\u68C0\u67E5\u767B\u5F55/\u5BC6\u94A5":he.slice(0,160);xn(e.server_url,B,L,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${Qu})`,clientIdempotencyKey:ji(),agentId:i},t).catch(Zu=>k("run","post turn-error notice failed",Zu))}),ke.onCompact?.(()=>{xn(e.server_url,B,L,{content:`\u{1F9F9} ${c} \u5728\u672C\u9891\u9053\u7684\u4E0A\u4E0B\u6587\u521A\u5B8C\u6210\u4E86\u4E00\u6B21\u81EA\u52A8\u538B\u7F29(\u8F83\u65E9\u7684\u5BF9\u8BDD\u88AB\u7CBE\u7B80,\u7EC6\u8282\u53EF\u80FD\u9700\u8981\u91CD\u65B0\u63D0\u4F9B)`,clientIdempotencyKey:ji(),agentId:i},t).catch(he=>k("run","post compact notice failed",he))}),ke.start(),ke};var C=Ne,w=er;let R={agentId:i,handle:a,displayName:c,description:d,role:l,serverId:e.org_id,computer:`${vu()} (${e.machine_id})`,hostname:vu(),os:`${process.platform} ${d_()}`,workspace:r,runtime:g,capabilities:x,roster:M,persona:_u(N)??void 0},A=Ad(R),T=Pe(N,"system-prompt.md");if(await bu(T,A,{encoding:"utf8",mode:384}),g==="claude")try{let L=Pe(r,".claude","skills");await Wi(L,{recursive:!0});let z=a_(c_(import.meta.url)),bt=Pe(z,"..","..","runtimes","skills"),Me=(await f_(bt)).filter(ke=>ke.endsWith(".md"));for(let ke of Me){let he=ke.replace(/\.md$/,""),ot=Pe(L,he);await Wi(ot,{recursive:!0}),await h_(Pe(bt,ke),Pe(ot,"SKILL.md"))}h("info",$,"Materialised Claude skills",{count:Me.length,destRoot:L})}catch(L){k($,"Failed to materialise Claude skills (continuing without)",L)}let D=Pe(N,"mcp-config.json"),E="You are now online. Read MEMORY.md first if it exists, then wait for incoming messages. Do not send any message until you receive one.",B=e.autonomous_agent.workroom_id,F,V=H?.channels.find(L=>L.member_ids.includes(i))?.id,oe=new Map,fe=[],I=[],vt=[],Ie=new Map,Pt=L=>{if(v)return{set:(z,bt)=>{Ie.set(L,bt);let Me=[...Ie.values()].some(ke=>ke!=="idle");v.set(z,Me?"thinking":"idle")}}},it=0,Ge="",Y=L=>{let z=oe.get(L);return z||(z=er(L),oe.set(L,z)),z};W={start(){},enqueueUserTurn(L){Y(F??V??"__default").enqueueUserTurn(L)},stop(){for(let L of oe.values())try{L.stop()}catch{}},stopChannel(L){let z=oe.get(L);if(!z)return!1;try{z.stop()}catch{}return oe.delete(L),Ie.delete(L),!0},onBoundary(L){I.push(L)},onSessionId(L){},onExit(L){vt.push(L)},onInjected(L){fe.push(L)},onTurnError(L){},onCompact(L){}},Y(V??"__default");let Ce=nu({agentId:i,onFire:async L=>{W.enqueueUserTurn(`[reminder fired] ${L.title}`);try{await s.reminderFire(i,L.id,L.version)}catch(z){k($,`reminder report-fire failed (agent ${i}, reminder ${L.id}) \u2014 local wake already happened; will retry on next sync`,z)}}}),Re=new os(s),Qe=Xd({gateway:s,host:W,hostFor:Y,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:B,reminderCache:Ce,onInboundMessage:L=>{F=L,Re.start(i,L)},...S?{contextTracker:S}:{},contextPolicy:P,mioDir:N,downloadAttachment:L=>Na(e.server_url,t,i,L).then(z=>({filename:z.filename,mime_type:z.mime_type,data_base64:z.data_base64}))});Qe.start(),W.onBoundary(()=>{Re.stop(i)});let tr=e.autonomous_agent,ps=du({subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:W,hostFor:Y,selfAgentId:i,workroomId:B,companion:ne,quietSeconds:tr.quiet_seconds,maxRepliesPerWindow:tr.max_replies_per_window,windowSeconds:tr.window_seconds,contextPolicy:P});ps.start();let Xu=M?.channelId??H?.channels.find(L=>L.member_ids.includes(i))?.id,ro=yu({workspace:r,mioDir:N,agentId:i,displayName:c,handle:a,role:l,workroomId:ie,channelId:Xu,gateway:s,companion:ne,quietSeconds:tr.quiet_seconds,spawnEnv:G,...m?{claudeCommand:m}:{}}),so=L=>{try{let z=L.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(L.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(ie).then(Me=>qi(ne,Me)).catch(Me=>k($,`roster refetch failed for ${L.topic}`,Me)),z.channel_id&&z.member_id&&ne.logObservation({channel_id:z.channel_id,entity_id:z.member_id,kind:L.topic})),L.topic==="message.created"&&z.sender_id&&z.channel_id){ne.logObservation({entity_id:z.sender_id,channel_id:z.channel_id,kind:"sent_message"});try{ro.noteMessage()}catch(Me){k($,"personaCrystallizer.noteMessage error (non-fatal)",Me)}}}catch(z){k($,"companionWsHandler error (non-fatal)",z)}};return s.subscribe(ie,so),s.listReminders(i).then(L=>Ce.snapshot(L)).catch(L=>k($,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,L)),E_({gateway:s,agentId:i,taskWakeRouter:ps,bootRoster:H,mioDir:N}).catch(L=>k($,`cold-start task self-heal failed for agent ${i} (non-fatal)`,L)),h("info",$,"Agentic spine started",{agentId:i,workroomId:B,mioDir:N}),v_(Qe,W,J,i,Ce,{companion:ne,gateway:s,workroomId:ie,companionWsHandler:so,taskWakeRouter:ps,personaCrystallizer:ro})}catch(R){try{W?.stop()}catch{}try{ne.close()}catch{}throw await J.close().catch(()=>{}),R}}function v_(n,e,t,r,s,i){e.onExit(c=>{h("warn",$,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",$,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){k($,"coord.stop() error",c)}try{s.stop()}catch(c){k($,"reminderCache.stop() error",c)}try{e.stop()}catch(c){k($,"host.stop() error",c)}try{await t.close()}catch(c){k($,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){k($,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){k($,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){k($,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){k($,"companion.close() error",c)}}h("info",$,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function k_(n){try{let e=await g_(Pe(n,Eu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function S_(n,e){try{await bu(Pe(n,Eu),JSON.stringify([...e]),"utf8")}catch(t){k($,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function E_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",$,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(p=>p.member_ids.includes(t)).map(p=>p.name).filter(p=>!!p)),o.length===0)try{o=(await e.getAgentChannels(t)).map(g=>g.name).filter(g=>!!g)}catch(p){k($,`self-heal: getAgentChannels failed for agent ${t}`,p);return}if(o.length===0){h("debug",$,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],d=await Promise.allSettled(o.map(p=>a(t,p.startsWith("#")?p:`#${p}`)));for(let p of d)if(p.status==="fulfilled")for(let g of p.value)g.assignee_id===t&&g.status==="in_progress"&&c.push(g);else k($,`self-heal: getTasks failed for a channel (agent ${t})`,p.reason);if(c.length===0){h("debug",$,"self-heal: no owned in_progress tasks",{agentId:t});return}let l=p=>{let g=p.updated_at??p.created_at,y=g?Date.parse(g):NaN;return Number.isFinite(y)?y:0};c.sort((p,g)=>l(g)-l(p));let u=await k_(i),m=c.filter(p=>!u.has(p.id)).slice(0,b_);if(m.length===0){h("debug",$,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(p=>p.id));let f=0;try{for(let p of m){let g=!1;if(p.parent_message_id&&e.getThreadReplies)try{g=(await e.getThreadReplies(t,p.parent_message_id,50)).some(S=>S.sender_id===t)}catch(y){k($,`self-heal: getThreadReplies failed for task ${p.id} (agent ${t}) \u2014 treating as no activity`,y)}if(u.add(p.id),g){h("debug",$,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:p.id});continue}try{r.synthesizeAssignedWake({task_id:p.id,...p.channel_id?{channel_id:p.channel_id}:{},...p.parent_message_id?{parent_message_id:p.parent_message_id}:{}})&&(f+=1)}catch(y){k($,`self-heal: synthesizeAssignedWake threw for task ${p.id} (agent ${t}) \u2014 task already marked seen, continuing`,y)}}}finally{await S_(i,u)}h("info",$,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:f})}function xu(n,e,t){let r=zn(n.replace(/^@/,"").toLowerCase()),s=zn(e),i=`${r}-${s}`,o=Pe(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function Tu(n){let e=typeof n=="string"?n.trim():"";return e===""||e==="claude"?{selected:"claude",raw:"claude"}:e==="codex"?{selected:"codex",raw:e}:{selected:"unsupported",raw:e}}function x_(n){try{let t=y_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&m_(t)}catch{return!1}}async function Cu(n){let{config:e,gateway:t,retrieveTokenFn:r=kt,mkdirFn:s=v=>Wi(v,{recursive:!0,mode:448}),startSpineFn:i=Su,mioDir:o=ku,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=x_}=n,d=e.autonomous_agent;if(!d?.enabled)return;let l,u;try{l=r(),u=await a(d.workroom_id)}catch(v){k($,"Failed to start agentic spine \u2014 daemon continues without spine",v);return}let m=u.filter(v=>v.kind==="agent"&&v.machine_id===e.machine_id);if(m.length===0){h("error",$,`No agent for this machine in workroom ${d.workroom_id} \u2014 create one first (daemon continues without spine)`,{machine_id:e.machine_id,workroom_id:d.workroom_id});return}let f=su(),p=new as(t),g=[],y=async v=>{let _=v.handle??"@"+v.display_name,{selected:b,raw:P}=Tu(v.runtime);if(b==="codex"){if(!c("codex"))return h("error",$,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:v.id,handle:_}),!1}else if(b==="unsupported")return h("warn",$,`runtime '${P}' not supported; spine not started for this agent ${v.id}`,{agentId:v.id,handle:_,runtime:P}),!1;if(b==="claude"&&!c("claude"))return h("error",$,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:v.id,handle:_}),!1;try{let x=v.id,{workingDirectory:N}=xu(_,e.machine_id,o);await s(N);let G=v.display_name||_.replace(/^@/,""),J=v.description||"An AI agent running on this machine.",W=b==="codex"?"gpt-5-codex":"sonnet",Q={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},ne=v.model||W,H=Q[ne.trim().toLowerCase()]??ne,ie;if(b==="codex"){let C=v.capabilities;if(C&&typeof C=="object"){let w=C.reasoning_effort;typeof w=="string"&&(w==="low"||w==="medium"||w==="high")&&(ie=w)}ie=ie??"medium"}let M=await i({config:e,machineToken:l,workingDirectory:N,gateway:t,agentId:x,launchId:ji(),agentHandle:_,displayName:G,description:J,role:v.role,serverCapabilities:v.capabilities,model:H,runtime:b,...ie?{reasoningEffort:ie}:{},contextTracker:f,presenceTracker:p});return g.push(M),h("info",$,"Agentic spine started",{agentId:x,workroomId:d.workroom_id}),!0}catch(x){return k($,`Failed to start spine for agent ${v.id} \u2014 continuing`,x),!1}return!0};for(let v of m)await y(v);if(g.length===0)return;let S=!1;return{handles:g,async stop(){S||(S=!0,await Promise.allSettled(g.map(v=>v.stop())))},async addAgentById(v){if(S)return!1;if(g.some(P=>P.agentId===v))return h("info",$,"hot-add skipped \u2014 spine already running",{agentId:v}),!1;let b=(await a(d.workroom_id)).find(P=>P.kind==="agent"&&P.id===v&&P.machine_id===e.machine_id);return b?y(b):(h("warn",$,"hot-add: agent not found on this machine",{agentId:v}),!1)},async removeAgentById(v){let _=g.findIndex(P=>P.agentId===v);if(_<0)return!1;let[b]=g.splice(_,1);return await b.stop().catch(()=>{}),!0},dropChannel(v){for(let _ of g)_.host.stopChannel?.(v)}}}async function Ji(){h("info",$,"Starting mio-agent daemon");let n=je();h("info",$,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await nd();let e=new zr;await u_(Gi).catch(()=>{}),await e.listen(Gi);let t=new Kr("0.1.0");await t.listen(__,w_);let r=new qr(n);await r.start();let s=new Wr(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>zl().then(y=>{a=y}).catch(()=>{});c().then(()=>r.machineHeartbeat(!1,a).catch(y=>k($,"Initial machine heartbeat failed (non-fatal)",y)));let d=setInterval(()=>{c()},o),l=setInterval(()=>{r.machineHeartbeat(!1,a).catch(y=>k($,"Machine heartbeat failed (non-fatal)",y))},i),u=new Vr(r,{runtimes:n.runtimes,ipcSocketPath:Gi}),m=new jr(s,u),f=await Cu({config:n,gateway:r,getWorkroomMembersFn:y=>r.getWorkroomMembers(y)});if(f&&n.autonomous_agent?.enabled){let y=n.autonomous_agent.workroom_id;r.subscribe(y,S=>{let v=S.payload??{};if(S.topic==="agent.created"){if(v.machine_id!==n.machine_id)return;let _=v.agent_id;if(typeof _!="string")return;h("info",$,"agent.created for this machine \u2014 hot-starting spine",{agentId:_}),f.addAgentById(_).then(b=>h("info",$,b?"hot-added agent spine \u2713":"hot-add no-op",{agentId:_})).catch(b=>k($,"hot-add failed",b));return}if(S.topic==="agent.status"){if(!("machine_id"in v)||v.machine_id!==null||!v.disabled_by)return;let _=v.agent_id;if(typeof _!="string")return;f.removeAgentById(_).then(b=>{b&&h("info",$,"agent deleted \u2014 spine stopped, runtime processes reaped \u2713",{agentId:_})}).catch(b=>k($,"hot-remove failed",b));return}if(S.topic==="channel.deleted"){let _=v.channel_id;if(typeof _!="string")return;f.dropChannel(_),h("info",$,"channel deleted \u2014 per-channel hosts reaped",{channelId:_})}})}e.onMessage(y=>{if(h("info",$,"IPC message from subprocess",{type:y.type}),u.onIpcMessage(y),y.type==="kick_persona"){let S=y.agent_id,v=y.reason??"ipc_kick";if(!f){h("warn",$,"IPC kick_persona: no spine running \u2014 ignoring");return}let _=0;for(let b of f.handles)if(!(S&&b.agentId!==S))try{b.personaCrystallizer?.kick(v),_+=1}catch(P){k($,"IPC kick_persona: kick failed",P)}h("info",$,"IPC kick_persona dispatched",{kicked:_,targetAgent:S,reason:v});return}if(y.type==="join_workroom"){let S=y.workroom_id;if(!S){h("warn",$,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}m.openWorkroom(S).then(v=>{v?h("info",$,"IPC join_workroom: workroom opened",{workroomId:S,sessionId:v.sessionId}):h("warn",$,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:S})}).catch(v=>{k($,"IPC join_workroom: unexpected error (should not happen)",v)})}}),h("info",$,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let p=!1;async function g(y){if(!p){p=!0,h("info",$,`${y} received \u2014 initiating graceful shutdown`);try{clearInterval(l),clearInterval(d),await r.machineHeartbeat(!0).catch(S=>k($,"Going-offline heartbeat failed (non-fatal)",S)),u.beginShutdown(),await u.drainIrreversible(),m.shutdownAll(),await s.stop(),f&&await f.stop(),await r.stop(),await e.stop(),await t.stop(),h("info",$,"Graceful shutdown complete")}catch(S){k($,"Error during shutdown",S)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{g("SIGTERM")}),process.on("SIGINT",()=>{g("SIGINT")}),await new Promise(()=>{})}var $,ku,Gi,__,w_,b_,Eu,Yi=O(()=>{"use strict";Je();Yt();le();Jl();Kl();Ql();Zl();Mi();dd();ud();Yr();xd();Od();Ld();Hd();jd();Qd();eu();tu();ru();iu();lu();uu();wu();ss();dr();$="daemon",ku=Pe(l_(),".mio"),Gi=Pe(ku,"agent.sock"),__="127.0.0.1",w_=7878;b_=5,Eu="self-heal-seen.json"});var Vi={};Le(Vi,{runStart:()=>T_});async function T_(n){if(n.background){let{execFileSync:e}=await import("child_process");try{e("launchctl",["start","io.miomioos.mio-agent"]),console.log("Daemon started via LaunchAgent.")}catch{console.error("LaunchAgent not installed. Run: mio-agent install --background --version <semver>"),process.exit(1)}return}h("info","start","Starting mio-agent in foreground (dev mode, latest OK)"),await Ji()}var zi=O(()=>{"use strict";le();Yi()});import{createHash as C_}from"crypto";import{mkdtempSync as R_,rmSync as Au,readFileSync as A_,copyFileSync as O_,chmodSync as P_,renameSync as I_,existsSync as Ou}from"fs";import{execFileSync as vn}from"child_process";import{tmpdir as N_,platform as M_}from"os";import{join as fs}from"path";function B_(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function F_(n){return`https://github.com/${L_}/${$_}/releases/download/v${n}/`}function Pu(n,e){try{return vn("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function U_(n,e){for(let t of n.split(`
|
|
561
|
+
`)){let r=t.trim().match(/^([0-9a-f]{64})\s+(.+)$/);if(!r)continue;let s=r[2];if(s===e||s.endsWith(`/${e}`))return r[1]}return null}function Iu(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=B_(),i=n._baseUrl??F_(e),o=`mio-agent-${e}-${s}.tar.gz`,a=`mio-agent-${e}-${s}`,c=`mio-agent-${e}-manifest.json`;r("Verifying release manifest...");let d;try{d=JSON.parse(Pu(i+c,"release manifest"))}catch(p){throw new Error(`Release manifest fetch/parse failed: ${p.message}`)}let l=new Set(d.required_fixes??[]),u=D_.filter(p=>!l.has(p));if(u.length>0)throw new Error(`Release v${e} is missing required fixes: ${u.join(", ")}. This release is too old to install safely \u2014 bump the pinned version.`);r("Fetching release checksum...");let m=U_(Pu(i+"SHASUMS256.txt","SHASUMS256.txt"),o);if(!m)throw new Error(`SHA-256 entry for '${o}' not found in SHASUMS256.txt`);let f=R_(fs(N_(),"mio-agent-install-"));try{r(`Downloading mio-agent ${e}...`);let p=fs(f,o);try{vn("curl",["-fSL",i+o,"-o",p])}catch(_){throw new Error(`Binary download failed: ${_.message}`)}r("Verifying checksum...");let g=C_("sha256").update(A_(p)).digest("hex");if(g!==m)throw new Error(`Checksum mismatch \u2014 expected ${m.slice(0,12)}\u2026, got ${g.slice(0,12)}\u2026`);r("Extracting binary...");let y=fs(f,"extract");vn("mkdir",["-p",y]),vn("tar",["-xzf",p,"-C",y]);let S=fs(y,a);if(!Ou(S))throw new Error(`mio-agent binary '${a}' not found inside the downloaded tarball`);r("Installing mio-agent...");let v=`${t}.staging`;Ou(v)&&Au(v,{force:!0}),O_(S,v),P_(v,493),M_()==="darwin"&&!n._skipSign&&(vn("codesign",["--force","--sign","-",v]),vn("xattr",["-dr","com.apple.quarantine",v])),I_(v,t)}finally{Au(f,{recursive:!0,force:!0})}}var L_,$_,D_,Nu=O(()=>{"use strict";L_="MioMioOS",$_="mio-agent",D_=["machine-api-v1-prefix","socketio-control-path"]});var Du={};Le(Du,{runInstall:()=>Zi});import{mkdirSync as Mu,writeFileSync as H_}from"fs";import{execFileSync as q_}from"child_process";import{homedir as Lu}from"os";import{join as hs}from"path";async function Zi(n){if(!n.background){console.log("Starting daemon in foreground (use --background --version <semver> for LaunchAgent)");let{runStart:i}=await Promise.resolve().then(()=>(zi(),Vi));await i({background:!1});return}n.version||(console.error("Error: --background requires --version <semver>"),process.exit(1));let e=je(),t=n.version;console.log(`Installing mio-agent ${t} as LaunchAgent...`),Mu(hs(ge,"bin"),{recursive:!0,mode:448}),Iu({version:t,destPath:Xi,onProgress:i=>console.log(i)}),e.pinned_version=t,lr(e),Mu($u,{recursive:!0});let r=Lu(),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
562
562
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
563
563
|
<plist version="1.0">
|
|
564
564
|
<dict>
|
|
@@ -582,12 +582,12 @@ ${B.length>6e3?B.slice(0,6e3)+`
|
|
|
582
582
|
</dict>
|
|
583
583
|
</plist>`;H_(Ki,s,{encoding:"utf-8",mode:420}),q_("launchctl",["bootstrap",`gui/${process.getuid()}`,Ki]),console.log(`
|
|
584
584
|
mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${Xi}`),console.log(` Plist: ${Ki}`),console.log(` Label: ${Qi}`),console.log(`
|
|
585
|
-
Run: mio-agent doctor \u2014 to verify health`)}var Qi,$u,Ki,Xi,eo=O(()=>{"use strict";Je();Mi();Nu();Qi="io.miomioos.mio-agent",$u=hs(Lu(),"Library","LaunchAgents"),Ki=hs($u,`${Qi}.plist`),Xi=hs(ge,"bin","mio-agent")});var to={};
|
|
586
|
-
To upgrade: mio-agent upgrade --version ${t}`)}async function j_(n){let e=je();e.pinned_version=n.version,lr(e),console.log(`Pinned version updated to ${n.version} in config.`),await Zi({background:!0,version:n.version})}var no=O(()=>{"use strict";Je();eo()});var Bu={};
|
|
587
|
-
mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var Q_,gs,Gu=O(()=>{"use strict";Yt();Je();Q_="io.miomioos.mio-agent",gs=K_(X_(),"Library","LaunchAgents",`${Q_}.plist`)});var ju={};
|
|
585
|
+
Run: mio-agent doctor \u2014 to verify health`)}var Qi,$u,Ki,Xi,eo=O(()=>{"use strict";Je();Mi();Nu();Qi="io.miomioos.mio-agent",$u=hs(Lu(),"Library","LaunchAgents"),Ki=hs($u,`${Qi}.plist`),Xi=hs(ge,"bin","mio-agent")});var to={};Le(to,{runUpgrade:()=>j_,runUpgradeCheck:()=>W_});import{execFileSync as G_}from"child_process";async function W_(){let e=je().pinned_version??"unknown (foreground/dev mode)",t=G_("npm",["view","@miomioos/mio-agent","version"],{encoding:"utf-8"}).trim();console.log(`Current pinned: ${e}`),console.log(`Latest on npm: ${t}`),console.log(e===t?"Already on latest pinned version.":`
|
|
586
|
+
To upgrade: mio-agent upgrade --version ${t}`)}async function j_(n){let e=je();e.pinned_version=n.version,lr(e),console.log(`Pinned version updated to ${n.version} in config.`),await Zi({background:!0,version:n.version})}var no=O(()=>{"use strict";Je();eo()});var Bu={};Le(Bu,{runStop:()=>V_});import{execFileSync as J_}from"child_process";async function V_(){try{J_("launchctl",["stop",Y_]),console.log("Daemon stopped.")}catch{console.log("Daemon was not running or stop signal sent.")}}var Y_,Fu=O(()=>{"use strict";Y_="io.miomioos.mio-agent"});var qu={};Le(qu,{runUninstall:()=>Z_});import{execFileSync as z_}from"child_process";import{rmSync as Uu,existsSync as Hu}from"fs";import{join as K_}from"path";import{homedir as X_}from"os";async function Z_(){console.log("Uninstalling mio-agent...");try{z_("launchctl",["bootout",`gui/${process.getuid()}`,gs]),console.log(" LaunchAgent unregistered.")}catch{console.log(" LaunchAgent was not registered (skipped).")}Hu(gs)&&(Uu(gs),console.log(` Deleted: ${gs}`));try{vo(),console.log(" Keychain entry deleted.")}catch{console.log(" No Keychain entry found (skipped).")}Hu(ge)&&(Uu(ge,{recursive:!0,force:!0}),console.log(` Deleted: ${ge}`)),console.log(`
|
|
587
|
+
mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var Q_,gs,Gu=O(()=>{"use strict";Yt();Je();Q_="io.miomioos.mio-agent",gs=K_(X_(),"Library","LaunchAgents",`${Q_}.plist`)});var ju={};Le(ju,{runDoctor:()=>nw});import{execFileSync as ew,spawnSync as Wu}from"child_process";import{existsSync as tw}from"fs";function wt(n,e,t){let r=e?"\u2705":"\u274C",s=t?`${r} ${n}: ${t}`:`${r} ${n}`;console.log(s)}async function nw(){console.log(`mio-agent doctor
|
|
588
588
|
`);let n=ta();if(wt("Config (~/.mio/agent.json)",n,n?"found":"missing \u2014 run: mio-agent login"),!n)return;let e=je(),t=!1;try{ew("security",["find-generic-password","-s","io.miomioos.mio-agent","-a","machine_token"],{stdio:"ignore"}),t=!0}catch{}wt("Keychain (machine_token)",t,t?"found":"missing \u2014 run: mio-agent login");let r=!1;try{r=Wu("curl",["-fsS","--max-time","3",`${e.server_url}/health`]).status===0}catch{}wt("Server connectivity",r,r?e.server_url:`unreachable: ${e.server_url}`);let s=!1;try{s=Wu("curl",["-fsS","--max-time","1",`http://127.0.0.1:${ea}/health`]).status===0}catch{}wt("Daemon (127.0.0.1:7878)",s,s?"running":"not running"),console.log(""),console.log("Runtimes:");let i=yn();if(i)wt(" claude",!0,i);else{wt(" claude",!1,"not found");for(let c of Nd().split(`
|
|
589
589
|
`))console.log(` ${c}`)}let o=rs();if(o){let c=(process.env.MIO_CODEX_MODEL||"").trim();wt(" codex",!0,c?`${o} (model override: ${c})`:`${o} (model: local default)`)}else{wt(" codex",!1,"not found");for(let c of Dd().split(`
|
|
590
|
-
`))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>tw(c));wt(" opencode",!!a,a??"not found in PATH"),console.log("")}var Ju=O(()=>{"use strict";Je();ts();Ui()});var Vu={};
|
|
590
|
+
`))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>tw(c));wt(" opencode",!!a,a??"not found in PATH"),console.log("")}var Ju=O(()=>{"use strict";Je();ts();Ui()});var Vu={};Le(Vu,{buildPairingDeeplink:()=>Yu,runPairPhone:()=>iw});function Yu(n,e){return`codelight://pair?${new URLSearchParams({v:"1",base:n,pid:e.pairing_id,code:e.code,wr:e.workroom_display,scope:e.scope_label,exp:e.expires_at}).toString()}`}function rw(n){let e=new Date(n).getTime()-Date.now();return`${Math.max(0,Math.round(e/6e4))} min`}function sw(n){switch(n){case 401:return"Machine token invalid or expired. Run: mio-agent login";case 403:return"This machine cannot grant access (token / machine mismatch).";case 409:return"This machine is not bound to an org. Finish Mac setup first.";case 404:return"Workroom not found for this machine's org.";case 400:return"Invalid request (check workroom_id / ttl).";default:return"Unexpected error."}}async function iw(n){n||(console.error("Usage: mio-agent pair-phone <workroom_id>"),process.exit(1));let e=je(),t;try{t=kt()}catch{console.error("No machine_token in Keychain. Run: mio-agent login"),process.exit(1);return}let r=`${e.server_url}/api/v1/machines/${e.machine_id}/pairings`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({workroom_id:n})});if(!s.ok){console.error(`Pairing failed: ${s.status} \u2014 ${sw(s.status)}`),process.exit(1);return}let i=await s.json(),o=Yu(e.server_url,i);console.log(""),console.log("=== Pair CodeLight on your phone ==="),console.log(` Workroom: ${i.workroom_display}`),console.log(` Scope: ${i.scope_label}`),console.log(` Server: ${i.server_host??e.server_url}`),console.log(` Expires: in ${rw(i.expires_at)} (${i.expires_at})`),console.log(` Pairing: ${i.pairing_id}`),console.log("");let a=!1;try{let c=await Promise.resolve().then(()=>re(Ts(),1)).catch(()=>null),d=c?.default??c;typeof d?.generate=="function"&&(d.generate(o,{small:!0},l=>console.log(l)),a=!0)}catch{}a||console.log(" Render this payload as a QR (MioIsland shows it on screen; or paste into any QR tool):"),console.log(` ${o}`),console.log(""),console.log(" The raw operator token is NOT in this code \u2014 the phone mints it securely on redeem."),console.log(" To cancel/regenerate, re-run pair-phone (old code stays valid until it expires unless canceled in MioIsland)."),console.log("")}var zu=O(()=>{"use strict";Je();Yt()});import{parseArgs as ow}from"util";import{fileURLToPath as aw}from"url";import{realpathSync as Ku}from"fs";function cw(n){return n[0]==="agentcli"}function lw(n){return n[0]==="login"}async function dw(){let n=process.argv.slice(2);if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){let{getPackageVersion:i}=await Promise.resolve().then(()=>(ao(),oo));console.log(i()),process.exit(0)}if(cw(n)){let{runAgentcliCommand:i}=await Promise.resolve().then(()=>(wo(),_o));process.exit(await i())}if(lw(n)){let{runLogin:i}=await Promise.resolve().then(()=>(zo(),Vo));process.exit(await i(process.argv.slice(3)))}if(n[0]==="logs"){let{runLogs:i}=await Promise.resolve().then(()=>(Qo(),Xo));process.exit(await i(process.argv.slice(3)))}let{values:e,positionals:t}=ow({args:n,options:{version:{type:"string"},background:{type:"boolean",default:!1},check:{type:"boolean",default:!1},help:{type:"boolean",default:!1}},allowPositionals:!0}),[r,...s]=t;switch(r){case"start":{let{runStart:i}=await Promise.resolve().then(()=>(zi(),Vi));await i({background:e.background??!1});break}case"install":{!e.version&&e.background&&(console.error("Error: --background requires --version <semver>"),console.error("Background services must have a pinned, auditable version."),process.exit(1));let{runInstall:i}=await Promise.resolve().then(()=>(eo(),Du));await i({background:e.background??!1,version:e.version});break}case"upgrade":{if(e.check){let{runUpgradeCheck:i}=await Promise.resolve().then(()=>(no(),to));await i()}else if(e.version){let{runUpgrade:i}=await Promise.resolve().then(()=>(no(),to));await i({version:e.version})}else console.error("Usage: mio-agent upgrade --check | --version <semver>"),process.exit(1);break}case"run":{let{runDaemon:i}=await Promise.resolve().then(()=>(Yi(),Ru));await i();break}case"stop":{let{runStop:i}=await Promise.resolve().then(()=>(Fu(),Bu));await i();break}case"uninstall":{let{runUninstall:i}=await Promise.resolve().then(()=>(Gu(),qu));await i();break}case"doctor":{let{runDoctor:i}=await Promise.resolve().then(()=>(Ju(),ju));await i();break}case"pair-phone":{let{runPairPhone:i}=await Promise.resolve().then(()=>(zu(),Vu));await i(s[0]);break}default:console.log(`Mio Agent \u2014 background AI worker daemon
|
|
591
591
|
|
|
592
592
|
Global flags:
|
|
593
593
|
--version, -v Print version and exit
|