@miomioos/mio-agent 0.3.14 → 0.3.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/cli/index.js +163 -162
  2. package/package.json +1 -1
package/dist/cli/index.js CHANGED
@@ -1,130 +1,130 @@
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 yf=Object.create;var Rs=Object.defineProperty;var _f=Object.getOwnPropertyDescriptor;var wf=Object.getOwnPropertyNames;var vf=Object.getPrototypeOf,bf=Object.prototype.hasOwnProperty;var te=(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 C=(n,e)=>()=>(n&&(e=n(n=0)),e);var ee=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),He=(n,e)=>{for(var t in e)Rs(n,t,{get:e[t],enumerable:!0})},kf=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wf(e))!bf.call(n,s)&&s!==t&&Rs(n,s,{get:()=>e[s],enumerable:!(r=_f(e,s))||r.enumerable});return n};var oe=(n,e,t)=>(t=n!=null?yf(vf(n)):{},kf(e||!n||!n.__esModule?Rs(t,"default",{value:n,enumerable:!0}):t,n));var vo={};He(vo,{MIO_AGENT_VERSION:()=>wo,getPackageVersion:()=>Sf});function Sf(){return wo}var wo,bo=C(()=>{"use strict";wo="0.2.1"});import{readFileSync as Eo,writeFileSync as Ef}from"fs";import{basename as xf,extname as Tf}from"path";import{randomUUID as xo}from"crypto";async function To(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(dh),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"})+`
3
+ var Ef=Object.create;var Is=Object.defineProperty;var xf=Object.getOwnPropertyDescriptor;var Tf=Object.getOwnPropertyNames;var Cf=Object.getPrototypeOf,Rf=Object.prototype.hasOwnProperty;var te=(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 C=(n,e)=>()=>(n&&(e=n(n=0)),e);var ee=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),He=(n,e)=>{for(var t in e)Is(n,t,{get:e[t],enumerable:!0})},Af=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tf(e))!Rf.call(n,s)&&s!==t&&Is(n,s,{get:()=>e[s],enumerable:!(r=xf(e,s))||r.enumerable});return n};var oe=(n,e,t)=>(t=n!=null?Ef(Cf(n)):{},Af(e||!n||!n.__esModule?Is(t,"default",{value:n,enumerable:!0}):t,n));var xo={};He(xo,{MIO_AGENT_VERSION:()=>Eo,getPackageVersion:()=>Of});function Of(){return Eo}var Eo,To=C(()=>{"use strict";Eo="0.2.1"});import{readFileSync as Ao,writeFileSync as Pf}from"fs";import{basename as If,extname as Nf}from"path";import{randomUUID as Oo}from"crypto";async function Po(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(mh),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
- `),1;let a;try{a=Eo(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}`})+`
5
+ `),1;let a;try{a=Ao(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"})+`
7
- `),1;let[c,l,...d]=n;return c==="message"?Cf(l,d,i,a,s,t,r):c==="task"?Nf(l,d,i,a,t,r):c==="reminder"?Ff(l,d,i,a,t,r):c==="action"?Xf(l,d,i,a,t,r):c==="attachment"?nh(l,d,i,a,t,r):c==="profile"?ih(l,d,i,a,t,r):(r.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown command: ${n.join(" ")}`})+`
8
- `),1)}async function Cf(n,e,t,r,s,i,o){switch(n){case"check":return Rf(e,t,r,i,o);case"send":return Af(e,t,r,s,i,o);case"read":return Of(e,t,r,i,o);case"react":return Pf(e,t,r,i,o);case"reply":return If(e,t,r,s,i,o);default:return o.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown message subcommand: ${n??"(none)"}. Try --help.`})+`
9
- `),1}}async function Rf(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message check"})+`
10
- `),1;let o=await he(e,t,"check",{channel:i});return o.ok?(Ro(o.data,r),0):(s.write(JSON.stringify(o.error)+`
11
- `),1)}async function Af(n,e,t,r,s,i){if(n.includes("--help")||n.includes("-h"))return s.write(`\u7528\u6CD5: mio message send --target "#\u9891\u9053\u540D" <<EOF
7
+ `),1;let[c,l,...d]=n;return c==="message"?Mf(l,d,i,a,s,t,r):c==="task"?Ff(l,d,i,a,t,r):c==="reminder"?Yf(l,d,i,a,t,r):c==="action"?sh(l,d,i,a,t,r):c==="attachment"?dh(l,d,i,a,t,r):c==="profile"?fh(l,d,i,a,t,r):(r.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown command: ${n.join(" ")}`})+`
8
+ `),1)}async function Mf(n,e,t,r,s,i,o){switch(n){case"check":return Lf(e,t,r,i,o);case"send":return $f(e,t,r,s,i,o);case"read":return Df(e,t,r,i,o);case"react":return Bf(e,t,r,i,o);case"reply":return Uf(e,t,r,s,i,o);default:return o.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown message subcommand: ${n??"(none)"}. Try --help.`})+`
9
+ `),1}}async function Lf(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message check"})+`
10
+ `),1;let o=await he(e,t,"check",{channel:i});return o.ok?(No(o.data,r),0):(s.write(JSON.stringify(o.error)+`
11
+ `),1)}async function $f(n,e,t,r,s,i){if(n.includes("--help")||n.includes("-h"))return s.write(`\u7528\u6CD5: mio message send --target "#\u9891\u9053\u540D" <<EOF
12
12
  \u6D88\u606F\u5185\u5BB9(stdin \u4F20\u5165,\u652F\u6301\u591A\u884C)
13
13
  EOF
14
14
  \u53EF\u9009: --thread <\u6D88\u606Fid> \u56DE\u590D\u5230\u6307\u5B9A\u6D88\u606F\u7684 thread
15
15
  `),0;let o=H(n,"--target");if(!o)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for message send (--help \u67E5\u770B\u7528\u6CD5)"})+`
16
16
  `),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'})+`
17
- `),1;let a=await Ao(r);if(a.trim()==="")return i.write(JSON.stringify({ok:!1,code:"EMPTY_MESSAGE",message:"message body is empty \u2014 nothing to send"})+`
18
- `),1;let c=xo(),l=gr(n,"--attachment");for(let y of gr(n,"--attach-file")){let k=await Ps(y,o,e,t);if(!k.ok)return i.write(JSON.stringify(k.error)+`
19
- `),1;l.push(k.id)}let d={target:o,content:a,clientIdempotencyKey:c};l.length>0&&(d.attachment_ids=l);let u=await he(e,t,"send",d);if(!u.ok)return i.write(JSON.stringify(u.error)+`
20
- `),1;let m=u.data,p=String(m.id??""),f=String(m.short_id??m.shortId??"").slice(0,8),g=m.seq!==void 0?`seq=${m.seq} `:"",_=typeof m.routed_to=="string"?m.routed_to:"",S=typeof m.task_number=="number"?m.task_number:null,v="";return _==="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=${p} ${f?`short=${f} `:""}${g}target=${o}${v}
21
- `),0}async function Of(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message read"})+`
22
- `),1;let o={channel:i},a=H(n,"--after"),c=H(n,"--around"),l=H(n,"--before"),d=H(n,"--limit");if([a,c,l].filter(p=>p!==void 0).length>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --after, --around, --before may be provided"})+`
23
- `),1;if(a&&(o.after_seq=a),c&&(o.around=c),l&&(o.around=l),d!==void 0){let p=Number(d);if(!Number.isInteger(p)||p<=0)return s.write(JSON.stringify({ok:!1,code:"INVALID_LIMIT",message:`--limit must be a positive integer, got: ${d}`})+`
24
- `),1;o.limit=p}let m=await he(e,t,"history",o);return m.ok?(Ro(m.data,r),0):(s.write(JSON.stringify(m.error)+`
25
- `),1)}async function Pf(n,e,t,r,s){let i=gt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a message id is required for message react"})+`
17
+ `),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"})+`
18
+ `),1;let c=Oo(),l=gr(n,"--attachment");for(let _ of gr(n,"--attach-file")){let S=await Ls(_,o,e,t);if(!S.ok)return i.write(JSON.stringify(S.error)+`
19
+ `),1;l.push(S.id)}let d={target:o,content:a,clientIdempotencyKey:c};l.length>0&&(d.attachment_ids=l);let u=await he(e,t,"send",d);if(!u.ok)return i.write(JSON.stringify(u.error)+`
20
+ `),1;let m=u.data,g=String(m.id??""),f=String(m.short_id??m.shortId??"").slice(0,8),p=m.seq!==void 0?`seq=${m.seq} `:"",w=typeof m.routed_to=="string"?m.routed_to:"",k=typeof m.task_number=="number"?m.task_number:null,v="";return w==="thread"&&k!==null&&(v=` (auto-routed to thread of task #${k} \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=${g} ${f?`short=${f} `:""}${p}target=${o}${v}
21
+ `),0}async function Df(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message read"})+`
22
+ `),1;let o={channel:i},a=H(n,"--after"),c=H(n,"--around"),l=H(n,"--before"),d=H(n,"--limit");if([a,c,l].filter(g=>g!==void 0).length>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --after, --around, --before may be provided"})+`
23
+ `),1;if(a&&(o.after_seq=a),c&&(o.around=c),l&&(o.around=l),d!==void 0){let g=Number(d);if(!Number.isInteger(g)||g<=0)return s.write(JSON.stringify({ok:!1,code:"INVALID_LIMIT",message:`--limit must be a positive integer, got: ${d}`})+`
24
+ `),1;o.limit=g}let m=await he(e,t,"history",o);return m.ok?(No(m.data,r),0):(s.write(JSON.stringify(m.error)+`
25
+ `),1)}async function Bf(n,e,t,r,s){let i=pt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a message id is required for message react"})+`
26
26
  `),1;let o=H(n,"--target");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#channel> is required for message react"})+`
27
27
  `),1;let a=H(n,"--emoji");if(!a)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--emoji <emoji> is required for message react"})+`
28
28
  `),1;let c=n.includes("--remove")?"remove":"add",l=await he(e,t,"react",{target:o,message_id:i,emoji:a,op:c});return l.ok?(r.write(`reacted: ${c} ${a} on msg=${i} in ${o}
29
29
  `),0):(s.write(JSON.stringify(l.error)+`
30
- `),1)}async function If(n,e,t,r,s,i){let o=H(n,"--parent");if(!o)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--parent <message-id> is required for message reply"})+`
30
+ `),1)}async function Uf(n,e,t,r,s,i){let o=H(n,"--parent");if(!o)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--parent <message-id> is required for message reply"})+`
31
31
  `),1;let a=H(n,"--target");if(!a)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for message reply"})+`
32
32
  `),1;if(r.isTTY)return i.write(JSON.stringify({ok:!1,code:"NO_STDIN",message:'reply body must be piped on stdin, e.g. mio message reply --parent <id> --target "#x" <<EOF'})+`
33
- `),1;let c=await Ao(r);if(c.trim()==="")return i.write(JSON.stringify({ok:!1,code:"EMPTY_MESSAGE",message:"reply body is empty \u2014 nothing to send"})+`
34
- `),1;let l=xo(),d=gr(n,"--attachment");for(let S of gr(n,"--attach-file")){let v=await Ps(S,a,e,t);if(!v.ok)return i.write(JSON.stringify(v.error)+`
33
+ `),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"})+`
34
+ `),1;let l=Oo(),d=gr(n,"--attachment");for(let k of gr(n,"--attach-file")){let v=await Ls(k,a,e,t);if(!v.ok)return i.write(JSON.stringify(v.error)+`
35
35
  `),1;d.push(v.id)}let u={target:a,parent_message_id:o,content:c,clientIdempotencyKey:l};d.length>0&&(u.attachment_ids=d);let m=await he(e,t,"reply",u);if(!m.ok)return i.write(JSON.stringify(m.error)+`
36
- `),1;let p=m.data,f=String(p.id??""),g=String(p.short_id??p.shortId??"").slice(0,8),_=p.seq!==void 0?`seq=${p.seq} `:"";return s.write(`replied: id=${f} ${g?`short=${g} `:""}${_}parent=${o} target=${a}
37
- `),0}async function Nf(n,e,t,r,s,i){switch(n){case"list":return Lf(e,t,r,s,i);case"create":return $f(e,t,r,s,i);case"claim":return ko("claim",e,t,r,s,i);case"unclaim":return ko("unclaim",e,t,r,s,i);case"update":return Df(e,t,r,s,i);case"review":return Mf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown task subcommand: ${n??"(none)"}. Try --help.`})+`
38
- `),1}}async function Mf(n,e,t,r,s){let i=As(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"})+`
36
+ `),1;let g=m.data,f=String(g.id??""),p=String(g.short_id??g.shortId??"").slice(0,8),w=g.seq!==void 0?`seq=${g.seq} `:"";return s.write(`replied: id=${f} ${p?`short=${p} `:""}${w}parent=${o} target=${a}
37
+ `),0}async function Ff(n,e,t,r,s,i){switch(n){case"list":return qf(e,t,r,s,i);case"create":return Gf(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 Wf(e,t,r,s,i);case"review":return Hf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown task subcommand: ${n??"(none)"}. Try --help.`})+`
38
+ `),1}}async function Hf(n,e,t,r,s){let i=Ns(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"})+`
39
39
  `),1;let o=H(n,"--channel");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task review"})+`
40
40
  `),1;let a=n.includes("--pass"),c=n.includes("--bounce");if(a===c)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"exactly one of --pass or --bounce is required for task review"})+`
41
41
  `),1;let l=a?"pass":"bounce",d=H(n,"--feedback")??"",u=await he(e,t,"task",{op:"review",channel:o,number:i,verdict:l,feedback:d});return u.ok?(r.write(`Reviewed task #${i} \u2192 ${l==="pass"?"passed (done)":"bounced back for rework"}
42
42
  `),0):(s.write(JSON.stringify(u.error)+`
43
- `),1)}async function Lf(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task list"})+`
44
- `),1;let o=await he(e,t,"task",{op:"list",channel:i});return o.ok?(Uf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
45
- `),1)}async function $f(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task create"})+`
43
+ `),1)}async function qf(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task list"})+`
44
+ `),1;let o=await he(e,t,"task",{op:"list",channel:i});return o.ok?(Jf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
45
+ `),1)}async function Gf(n,e,t,r,s){let i=H(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task create"})+`
46
46
  `),1;let o=H(n,"--title");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--title <text> is required for task create"})+`
47
47
  `),1;let a=H(n,"--attach"),c={op:"create",channel:i,title:o};a!==void 0&&a!==""&&(c.attach_to_message_id=a),n.includes("--self")&&(c.self=!0);let l=await he(e,t,"task",c);if(!l.ok)return s.write(JSON.stringify(l.error)+`
48
- `),1;let d=Bf(l.data),u=d?.number!==void 0?`#${d.number}`:"(new)";return r.write(`Created task ${u}: ${o}
49
- `),0}async function ko(n,e,t,r,s,i){let o=As(e);if(o===void 0)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:`a task number (e.g. #5 or 5) is required for task ${n}`})+`
48
+ `),1;let d=jf(l.data),u=d?.number!==void 0?`#${d.number}`:"(new)";return r.write(`Created task ${u}: ${o}
49
+ `),0}async function Co(n,e,t,r,s,i){let o=Ns(e);if(o===void 0)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:`a task number (e.g. #5 or 5) is required for task ${n}`})+`
50
50
  `),1;let a=H(e,"--channel");if(!a)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:`--channel <#name> is required for task ${n}`})+`
51
51
  `),1;let c=await he(t,r,"task",{op:n,channel:a,number:o});return c.ok?(s.write(`${n==="claim"?"Claimed":"Unclaimed"} task #${o}
52
52
  `),0):(i.write(JSON.stringify(c.error)+`
53
- `),1)}async function Df(n,e,t,r,s){let i=As(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 update"})+`
53
+ `),1)}async function Wf(n,e,t,r,s){let i=Ns(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 update"})+`
54
54
  `),1;let o=H(n,"--channel");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task update"})+`
55
55
  `),1;let a=H(n,"--status");if(!a)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--status <state> is required for task update"})+`
56
56
  `),1;let c=await he(e,t,"task",{op:"update",channel:o,number:i,status:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
57
57
  `),1;let l=c.data??{};if(a==="done"&&l.diverted_to_review===!0)r.write(`Submitted task #${i} for independent review \u2014 it is now in_review and will close once a teammate audits your work. If it bounces back, you'll be pinged to address the feedback and re-submit \`done\`.
58
58
  `);else{let d=typeof l.status=="string"?l.status:a;r.write(`Updated task #${i} \u2192 ${d}
59
- `)}return 0}function As(n){let e=gt(n);if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;if(!(t===""||!/^\d+$/.test(t)))return Number(t)}function gt(n){for(let e=0;e<n.length;e++){let t=n[e];if(t.startsWith("--")){e++;continue}return t}}function Bf(n){let e=n;return(Array.isArray(e?.tasks)?e.tasks:[])[0]}function Uf(n,e){let t=n,r=Array.isArray(t?.tasks)?t.tasks:[];if(r.length===0){e.write(`(no tasks)
59
+ `)}return 0}function Ns(n){let e=pt(n);if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;if(!(t===""||!/^\d+$/.test(t)))return Number(t)}function pt(n){for(let e=0;e<n.length;e++){let t=n[e];if(t.startsWith("--")){e++;continue}return t}}function jf(n){let e=n;return(Array.isArray(e?.tasks)?e.tasks:[])[0]}function Jf(n,e){let t=n,r=Array.isArray(t?.tasks)?t.tasks:[];if(r.length===0){e.write(`(no tasks)
60
60
  `);return}for(let s of r){let i=`#${s.number??"?"}`,o=s.status??"unknown",a=s.title??"",c=s.assignee??s.assignee_id,l=c?`@${c}`:"unassigned";e.write(`${i} ${o} ${a} ${l}
61
- `)}}async function Ff(n,e,t,r,s,i){switch(n){case"schedule":return Hf(e,t,r,s,i);case"list":return qf(e,t,r,s,i);case"snooze":return Gf(e,t,r,s,i);case"update":return Wf(e,t,r,s,i);case"cancel":return jf(e,t,r,s,i);case"log":return Jf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown reminder subcommand: ${n??"(none)"}. Try --help.`})+`
62
- `),1}}async function Hf(n,e,t,r,s){let i=H(n,"--title");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:'--title "<text>" is required for reminder schedule'})+`
63
- `),1;let o=H(n,"--in"),a=H(n,"--at"),c=H(n,"--cadence"),l=[o,a,c].filter(S=>S!==void 0).length;if(l===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"})+`
61
+ `)}}async function Yf(n,e,t,r,s,i){switch(n){case"schedule":return Vf(e,t,r,s,i);case"list":return Kf(e,t,r,s,i);case"snooze":return zf(e,t,r,s,i);case"update":return Xf(e,t,r,s,i);case"cancel":return Qf(e,t,r,s,i);case"log":return Zf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown reminder subcommand: ${n??"(none)"}. Try --help.`})+`
62
+ `),1}}async function Vf(n,e,t,r,s){let i=H(n,"--title");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:'--title "<text>" is required for reminder schedule'})+`
63
+ `),1;let o=H(n,"--in"),a=H(n,"--at"),c=H(n,"--cadence"),l=[o,a,c].filter(k=>k!==void 0).length;if(l===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"})+`
64
64
  `),1;if(l>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --at, --cadence may be provided"})+`
65
- `),1;let d=H(n,"--channel"),u=H(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),d!==void 0&&(m.channel=d),u!==void 0&&(m.message_id=u);let p=await he(e,t,"reminder",m);if(!p.ok)return s.write(JSON.stringify(p.error)+`
66
- `),1;let f=Yf(p.data),g=f?.id??"(new)",_=f?.fireAt?` fireAt=${f.fireAt}`:"";return r.write(`Scheduled reminder ${g}: ${i}${_}
67
- `),0}async function qf(n,e,t,r,s){let i=H(n,"--channel"),o=H(n,"--status"),a={op:"list"};i!==void 0&&(a.channel=i),o!==void 0&&(a.status=o);let c=await he(e,t,"reminder",a);return c.ok?(zf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
68
- `),1)}async function Gf(n,e,t,r,s){let i=gt(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 d=H(n,"--channel"),u=H(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),d!==void 0&&(m.channel=d),u!==void 0&&(m.message_id=u);let g=await he(e,t,"reminder",m);if(!g.ok)return s.write(JSON.stringify(g.error)+`
66
+ `),1;let f=eh(g.data),p=f?.id??"(new)",w=f?.fireAt?` fireAt=${f.fireAt}`:"";return r.write(`Scheduled reminder ${p}: ${i}${w}
67
+ `),0}async function Kf(n,e,t,r,s){let i=H(n,"--channel"),o=H(n,"--status"),a={op:"list"};i!==void 0&&(a.channel=i),o!==void 0&&(a.status=o);let c=await he(e,t,"reminder",a);return c.ok?(nh(c.data,r),0):(s.write(JSON.stringify(c.error)+`
68
+ `),1)}async function zf(n,e,t,r,s){let i=pt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder snooze"})+`
69
69
  `),1;let o=H(n,"--in"),a=H(n,"--until"),c=[o,a].filter(f=>f!==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"})+`
70
70
  `),1;if(c>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --until may be provided"})+`
71
- `),1;let l=await Os(i,e,t,s);if(l===void 0)return 1;let d={op:"snooze",id:i,version:l};o!==void 0&&(d.in=o),a!==void 0&&(d.until=a);let u=await he(e,t,"reminder",d);if(!u.ok)return s.write(JSON.stringify(u.error)+`
72
- `),1;let m=Vf(u.data),p=m?.fireAt?` \u2192 ${m.fireAt}`:"";return r.write(`Snoozed reminder ${i}${p}
73
- `),0}async function Wf(n,e,t,r,s){let i=gt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder update"})+`
74
- `),1;let o=H(n,"--title"),a=H(n,"--cadence"),c=H(n,"--in"),l=H(n,"--at");if([o,a,c,l].every(p=>p===void 0))return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"at least one of --title, --cadence, --in, --at is required for reminder update"})+`
71
+ `),1;let l=await Ms(i,e,t,s);if(l===void 0)return 1;let d={op:"snooze",id:i,version:l};o!==void 0&&(d.in=o),a!==void 0&&(d.until=a);let u=await he(e,t,"reminder",d);if(!u.ok)return s.write(JSON.stringify(u.error)+`
72
+ `),1;let m=th(u.data),g=m?.fireAt?` \u2192 ${m.fireAt}`:"";return r.write(`Snoozed reminder ${i}${g}
73
+ `),0}async function Xf(n,e,t,r,s){let i=pt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder update"})+`
74
+ `),1;let o=H(n,"--title"),a=H(n,"--cadence"),c=H(n,"--in"),l=H(n,"--at");if([o,a,c,l].every(g=>g===void 0))return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"at least one of --title, --cadence, --in, --at is required for reminder update"})+`
75
75
  `),1;if(c!==void 0&&l!==void 0)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --at may be provided"})+`
76
- `),1;let d=await Os(i,e,t,s);if(d===void 0)return 1;let u={op:"update",id:i,version:d};o!==void 0&&(u.title=o),a!==void 0&&(u.cadence=a),c!==void 0&&(u.in=c),l!==void 0&&(u.at=l);let m=await he(e,t,"reminder",u);return m.ok?(r.write(`Updated reminder ${i}
76
+ `),1;let d=await Ms(i,e,t,s);if(d===void 0)return 1;let u={op:"update",id:i,version:d};o!==void 0&&(u.title=o),a!==void 0&&(u.cadence=a),c!==void 0&&(u.in=c),l!==void 0&&(u.at=l);let m=await he(e,t,"reminder",u);return m.ok?(r.write(`Updated reminder ${i}
77
77
  `),0):(s.write(JSON.stringify(m.error)+`
78
- `),1)}async function jf(n,e,t,r,s){let i=gt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder cancel"})+`
79
- `),1;let o=await Os(i,e,t,s);if(o===void 0)return 1;let a=await he(e,t,"reminder",{op:"cancel",id:i,version:o});return a.ok?(r.write(`Canceled reminder ${i}
78
+ `),1)}async function Qf(n,e,t,r,s){let i=pt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder cancel"})+`
79
+ `),1;let o=await Ms(i,e,t,s);if(o===void 0)return 1;let a=await he(e,t,"reminder",{op:"cancel",id:i,version:o});return a.ok?(r.write(`Canceled reminder ${i}
80
80
  `),0):(s.write(JSON.stringify(a.error)+`
81
- `),1)}async function Jf(n,e,t,r,s){let i=gt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder log"})+`
82
- `),1;let o=await he(e,t,"reminder",{op:"log",id:i});return o.ok?(Kf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
83
- `),1)}function Yf(n){let e=n;return e?.reminder?e.reminder:(Array.isArray(e?.reminders)?e.reminders:[])[0]}function Vf(n){return n?.reminder}async function Os(n,e,t,r){let s=await he(e,t,"reminder",{op:"list"});if(!s.ok){r.write(JSON.stringify(s.error)+`
81
+ `),1)}async function Zf(n,e,t,r,s){let i=pt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder log"})+`
82
+ `),1;let o=await he(e,t,"reminder",{op:"log",id:i});return o.ok?(rh(o.data,r),0):(s.write(JSON.stringify(o.error)+`
83
+ `),1)}function eh(n){let e=n;return e?.reminder?e.reminder:(Array.isArray(e?.reminders)?e.reminders:[])[0]}function th(n){return n?.reminder}async function Ms(n,e,t,r){let s=await he(e,t,"reminder",{op:"list"});if(!s.ok){r.write(JSON.stringify(s.error)+`
84
84
  `);return}let i=s.data,a=(Array.isArray(i?.reminders)?i.reminders:[]).find(c=>c.id===n);if(!a){r.write(JSON.stringify({ok:!1,code:"REMINDER_NOT_FOUND",message:`No reminder found with id ${n}`})+`
85
85
  `);return}if(typeof a.version!="number"){r.write(JSON.stringify({ok:!1,code:"REMINDER_NO_VERSION",message:`Reminder ${n} has no version field`})+`
86
- `);return}return a.version}function zf(n,e){let t=n,r=Array.isArray(t?.reminders)?t.reminders:[];if(r.length===0){e.write(`(no reminders)
86
+ `);return}return a.version}function nh(n,e){let t=n,r=Array.isArray(t?.reminders)?t.reminders:[];if(r.length===0){e.write(`(no reminders)
87
87
  `);return}for(let s of r){let i=s.id??"?",o=s.fireAt??"?",a=s.status??"unknown",c=s.title??"",l=s.cadence?` cadence=${s.cadence}`:"";e.write(`${i} ${o} ${a} ${c}${l}
88
- `)}}function Kf(n,e){let t=n,r=Array.isArray(t?.events)?t.events:[];if(r.length===0){e.write(`(no events)
88
+ `)}}function rh(n,e){let t=n,r=Array.isArray(t?.events)?t.events:[];if(r.length===0){e.write(`(no events)
89
89
  `);return}for(let s of r){let i=s.at??"?",o=s.event??"unknown",a=s.id??s.reminderId??"";e.write(`${i} ${o} ${a}
90
- `)}}async function Xf(n,e,t,r,s,i){switch(n){case"prepare":return Qf(e,t,r,s,i);case"list":return Zf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown action subcommand: ${n??"(none)"}. Try --help.`})+`
91
- `),1}}async function Qf(n,e,t,r,s){let i=H(n,"--target");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for action prepare"})+`
90
+ `)}}async function sh(n,e,t,r,s,i){switch(n){case"prepare":return ih(e,t,r,s,i);case"list":return oh(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown action subcommand: ${n??"(none)"}. Try --help.`})+`
91
+ `),1}}async function ih(n,e,t,r,s){let i=H(n,"--target");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for action prepare"})+`
92
92
  `),1;let o=H(n,"--type");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--type <channel:create|channel:add_member> is required for action prepare"})+`
93
93
  `),1;let a;if(o==="channel:create"){let u=H(n,"--name");if(!u)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--name <#name> is required for action prepare --type channel:create"})+`
94
94
  `),1;a={name:u};let m=H(n,"--visibility");m!==void 0&&(a.visibility=m)}else if(o==="channel:add_member"){let u=H(n,"--channel");if(!u)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for action prepare --type channel:add_member"})+`
95
- `),1;let m=H(n,"--member"),p=H(n,"--member-id");if(m===void 0&&p===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--member <@handle> (or --member-id <id>) is required for action prepare --type channel:add_member"})+`
96
- `),1;a={channel:u},m!==void 0&&(a.member_handle=m),p!==void 0&&(a.member_id=p)}else return s.write(JSON.stringify({ok:!1,code:"INVALID_TYPE",message:`Unknown action type: ${o}. Supported: channel:create, channel:add_member`})+`
95
+ `),1;let m=H(n,"--member"),g=H(n,"--member-id");if(m===void 0&&g===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--member <@handle> (or --member-id <id>) is required for action prepare --type channel:add_member"})+`
96
+ `),1;a={channel:u},m!==void 0&&(a.member_handle=m),g!==void 0&&(a.member_id=g)}else return s.write(JSON.stringify({ok:!1,code:"INVALID_TYPE",message:`Unknown action type: ${o}. Supported: channel:create, channel:add_member`})+`
97
97
  `),1;let c=await he(e,t,"action",{op:"prepare",target:i,type:o,params:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
98
- `),1;let d=eh(c.data)?.id??"(new)";return r.write(`Proposed action ${d}: ${o} (target=${i}) \u2014 awaiting human approval
99
- `),0}async function Zf(n,e,t,r,s){let i=H(n,"--status"),o=H(n,"--channel"),a={op:"list"};i!==void 0&&(a.status=i),o!==void 0&&(a.channel=o);let c=await he(e,t,"action",a);return c.ok?(th(c.data,r),0):(s.write(JSON.stringify(c.error)+`
100
- `),1)}function eh(n){let e=n;return e?.action?e.action:(Array.isArray(e?.actions)?e.actions:[])[0]}function th(n,e){let t=n,r=Array.isArray(t?.actions)?t.actions:[];if(r.length===0){e.write(`(no actions)
98
+ `),1;let d=ah(c.data)?.id??"(new)";return r.write(`Proposed action ${d}: ${o} (target=${i}) \u2014 awaiting human approval
99
+ `),0}async function oh(n,e,t,r,s){let i=H(n,"--status"),o=H(n,"--channel"),a={op:"list"};i!==void 0&&(a.status=i),o!==void 0&&(a.channel=o);let c=await he(e,t,"action",a);return c.ok?(ch(c.data,r),0):(s.write(JSON.stringify(c.error)+`
100
+ `),1)}function ah(n){let e=n;return e?.action?e.action:(Array.isArray(e?.actions)?e.actions:[])[0]}function ch(n,e){let t=n,r=Array.isArray(t?.actions)?t.actions:[];if(r.length===0){e.write(`(no actions)
101
101
  `);return}for(let s of r){let i=s.id??"?",o=s.type??"unknown",a=s.status??"unknown",c=s.summary??s.target??"";e.write(`${i} ${o} ${a} ${c}
102
- `)}}async function nh(n,e,t,r,s,i){switch(n){case"upload":return rh(e,t,r,s,i);case"view":return sh(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown attachment subcommand: ${n??"(none)"}. Try --help.`})+`
103
- `),1}}async function Ps(n,e,t,r){let s=Tf(n).toLowerCase(),i=So[s];if(!i){let u=Object.keys(So).join(", ");return{ok:!1,error:{ok:!1,code:"UNSUPPORTED_FILE_TYPE",message:`Cannot detect mime type for extension '${s||"(none)"}'. Supported: ${u}`}}}let o;try{o=Eo(n).toString("base64")}catch(u){let m=u instanceof Error?u.message:String(u);return{ok:!1,error:{ok:!1,code:"FILE_READ_ERROR",message:`Cannot read file ${n}: ${m}`}}}let a=xf(n),c=await he(t,r,"attachment",{op:"upload",filename:a,mime_type:i,data_base64:o,target:e});if(!c.ok)return{ok:!1,error:c.error};let l=c.data;return{ok:!0,id:String(l.attachment_id??l.id??""),filename:a,mimeType:i}}async function rh(n,e,t,r,s){let i=gt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a local file path is required for attachment upload"})+`
102
+ `)}}async function dh(n,e,t,r,s,i){switch(n){case"upload":return lh(e,t,r,s,i);case"view":return uh(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown attachment subcommand: ${n??"(none)"}. Try --help.`})+`
103
+ `),1}}async function Ls(n,e,t,r){let s=Nf(n).toLowerCase(),i=Ro[s];if(!i){let u=Object.keys(Ro).join(", ");return{ok:!1,error:{ok:!1,code:"UNSUPPORTED_FILE_TYPE",message:`Cannot detect mime type for extension '${s||"(none)"}'. Supported: ${u}`}}}let o;try{o=Ao(n).toString("base64")}catch(u){let m=u instanceof Error?u.message:String(u);return{ok:!1,error:{ok:!1,code:"FILE_READ_ERROR",message:`Cannot read file ${n}: ${m}`}}}let a=If(n),c=await he(t,r,"attachment",{op:"upload",filename:a,mime_type:i,data_base64:o,target:e});if(!c.ok)return{ok:!1,error:c.error};let l=c.data;return{ok:!0,id:String(l.attachment_id??l.id??""),filename:a,mimeType:i}}async function lh(n,e,t,r,s){let i=pt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a local file path is required for attachment upload"})+`
104
104
  `),1;let o=H(n,"--target");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for attachment upload"})+`
105
- `),1;let a=await Ps(i,o,e,t);return a.ok?(r.write(`uploaded: attachment_id=${a.id} filename=${a.filename} mime=${a.mimeType}
105
+ `),1;let a=await Ls(i,o,e,t);return a.ok?(r.write(`uploaded: attachment_id=${a.id} filename=${a.filename} mime=${a.mimeType}
106
106
  `),0):(s.write(JSON.stringify(a.error)+`
107
- `),1)}async function sh(n,e,t,r,s){let i=gt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"an attachment id is required for attachment view"})+`
107
+ `),1)}async function uh(n,e,t,r,s){let i=pt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"an attachment id is required for attachment view"})+`
108
108
  `),1;let o=H(n,"--out"),a=await he(e,t,"attachment",{op:"view",attachment_id:i});if(!a.ok)return s.write(JSON.stringify(a.error)+`
109
- `),1;let c=a.data,l=String(c.filename??""),d=String(c.mime_type??""),u=c.size_bytes;if(o!==void 0){let p=c.data_base64;if(typeof p!="string")return s.write(JSON.stringify({ok:!1,code:"NO_ATTACHMENT_DATA",message:`attachment ${i} response did not include data_base64 bytes to save`})+`
110
- `),1;let f=Buffer.from(p,"base64");if(u!==void 0){let g=Number(u);if(!Number.isNaN(g)&&f.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 ${f.length} bytes \u2014 not writing ${o}`})+`
111
- `),1}try{Ef(o,f)}catch(g){let _=g instanceof Error?g.message:String(g);return s.write(JSON.stringify({ok:!1,code:"FILE_WRITE_ERROR",message:`Cannot write to ${o}: ${_}`})+`
109
+ `),1;let c=a.data,l=String(c.filename??""),d=String(c.mime_type??""),u=c.size_bytes;if(o!==void 0){let g=c.data_base64;if(typeof g!="string")return s.write(JSON.stringify({ok:!1,code:"NO_ATTACHMENT_DATA",message:`attachment ${i} response did not include data_base64 bytes to save`})+`
110
+ `),1;let f=Buffer.from(g,"base64");if(u!==void 0){let p=Number(u);if(!Number.isNaN(p)&&f.length!==p)return s.write(JSON.stringify({ok:!1,code:"SIZE_MISMATCH",message:`attachment ${i} byte length mismatch: server reported size_bytes=${p} but decoded ${f.length} bytes \u2014 not writing ${o}`})+`
111
+ `),1}try{Pf(o,f)}catch(p){let w=p instanceof Error?p.message:String(p);return s.write(JSON.stringify({ok:!1,code:"FILE_WRITE_ERROR",message:`Cannot write to ${o}: ${w}`})+`
112
112
  `),1}return r.write(`saved: ${o} (${f.length} bytes)
113
113
  `),0}let m=u!==void 0?String(u):"?";return r.write(`attachment ${i}: filename=${l} mime_type=${d} size_bytes=${m}
114
114
  `),r.write(`(pass --out <path> to save the decoded bytes to a file)
115
- `),0}async function ih(n,e,t,r,s,i){switch(n){case"show":return oh(e,t,r,s,i);case"update":return ah(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown profile subcommand: ${n??"(none)"}. Try --help.`})+`
116
- `),1}}async function oh(n,e,t,r,s){let i=gt(n),o={op:"show"};i!==void 0&&(o.handle=i);let a=await he(e,t,"profile",o);return a.ok?(Co(a.data,r),0):(s.write(JSON.stringify(a.error)+`
117
- `),1)}async function ah(n,e,t,r,s){let i=H(n,"--display-name"),o=H(n,"--description");if(i===void 0&&o===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"at least one of --display-name or --description is required for profile update"})+`
118
- `),1;let a={op:"update"};i!==void 0&&(a.display_name=i),o!==void 0&&(a.description=o);let c=await he(e,t,"profile",a);return c.ok?(Co(c.data,r),0):(s.write(JSON.stringify(c.error)+`
119
- `),1)}function Co(n,e){let t=n;if(!t){e.write(`(no profile data)
115
+ `),0}async function fh(n,e,t,r,s,i){switch(n){case"show":return hh(e,t,r,s,i);case"update":return ph(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown profile subcommand: ${n??"(none)"}. Try --help.`})+`
116
+ `),1}}async function hh(n,e,t,r,s){let i=pt(n),o={op:"show"};i!==void 0&&(o.handle=i);let a=await he(e,t,"profile",o);return a.ok?(Io(a.data,r),0):(s.write(JSON.stringify(a.error)+`
117
+ `),1)}async function ph(n,e,t,r,s){let i=H(n,"--display-name"),o=H(n,"--description");if(i===void 0&&o===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"at least one of --display-name or --description is required for profile update"})+`
118
+ `),1;let a={op:"update"};i!==void 0&&(a.display_name=i),o!==void 0&&(a.description=o);let c=await he(e,t,"profile",a);return c.ok?(Io(c.data,r),0):(s.write(JSON.stringify(c.error)+`
119
+ `),1)}function Io(n,e){let t=n;if(!t){e.write(`(no profile data)
120
120
  `);return}let r=t.handle??"(unknown)",s=t.display_name??"",i=t.role??"",o=t.description??"";if(e.write(`handle: ${r}
121
121
  `),s&&e.write(`display_name: ${s}
122
122
  `),i&&e.write(`role: ${i}
123
123
  `),o&&e.write(`description: ${o}
124
124
  `),t.avatar!==void 0){let a=Buffer.byteLength(t.avatar,"utf8");e.write(`avatar: (generated identicon, ${a} bytes)
125
- `)}}async function he(n,e,t,r){let s;try{s=await fetch(`${n}/act`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({action:t,payload:r})})}catch(a){let c=a instanceof Error?a.message:String(a);return{ok:!1,error:{ok:!1,code:"PROXY_UNREACHABLE",message:`Cannot reach proxy at ${n}: ${c}`}}}let i=await s.text().catch(()=>"");if(s.ok){let a=i;try{a=JSON.parse(i)}catch{}return{ok:!0,data:a}}let o;try{if(o=JSON.parse(i),typeof o.code!="string")throw new Error("no code")}catch{o={ok:!1,code:"PROXY_ERROR",message:i||`HTTP ${s.status}`}}return{ok:!1,error:o}}function ch(n){let e=n.channel??"",t=String(n.short_id??n.id??"").slice(0,8),r=n.created_at??"",s=n.type??"human",i=n.display_name??n.sender_id??"unknown",o=n.content??"";return`[target=${e} msg=${t} time=${r} type=${s}] @${i}: ${o}`}function Ro(n,e){let t=n,r=Array.isArray(t?.messages)?t.messages:[];if(r.length===0){e.write(`(no messages)
126
- `);return}for(let s of r)e.write(ch(s)+`
127
- `)}function H(n,e){let t=n.indexOf(e);if(t===-1)return;let r=n[t+1];return r===void 0||r.startsWith("--")?void 0:r}function gr(n,e){let t=[];for(let r=0;r<n.length;r++){if(n[r]!==e)continue;let s=n[r+1];s!==void 0&&!s.startsWith("--")&&t.push(s)}return t}function Ao(n){return new Promise((e,t)=>{let r=[];n.on("data",s=>{r.push(typeof s=="string"?Buffer.from(s):s)}),n.on("end",()=>e(Buffer.concat(r).toString("utf8"))),n.on("error",t)})}var So,dh,Oo=C(()=>{"use strict";So={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".heic":"image/heic",".webp":"image/webp",".gif":"image/gif"};dh=`mio-agent agentcli \u2014 agent-facing message CLI (Slice 1)
125
+ `)}}async function he(n,e,t,r){let s;try{s=await fetch(`${n}/act`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({action:t,payload:r})})}catch(a){let c=a instanceof Error?a.message:String(a);return{ok:!1,error:{ok:!1,code:"PROXY_UNREACHABLE",message:`Cannot reach proxy at ${n}: ${c}`}}}let i=await s.text().catch(()=>"");if(s.ok){let a=i;try{a=JSON.parse(i)}catch{}return{ok:!0,data:a}}let o;try{if(o=JSON.parse(i),typeof o.code!="string")throw new Error("no code")}catch{o={ok:!1,code:"PROXY_ERROR",message:i||`HTTP ${s.status}`}}return{ok:!1,error:o}}function gh(n){let e=n.channel??"",t=String(n.short_id??n.id??"").slice(0,8),r=n.created_at??"",s=n.type??"human",i=n.display_name??n.sender_id??"unknown",o=n.content??"";return`[target=${e} msg=${t} time=${r} type=${s}] @${i}: ${o}`}function No(n,e){let t=n,r=Array.isArray(t?.messages)?t.messages:[];if(r.length===0){e.write(`(no messages)
126
+ `);return}for(let s of r)e.write(gh(s)+`
127
+ `)}function H(n,e){let t=n.indexOf(e);if(t===-1)return;let r=n[t+1];return r===void 0||r.startsWith("--")?void 0:r}function gr(n,e){let t=[];for(let r=0;r<n.length;r++){if(n[r]!==e)continue;let s=n[r+1];s!==void 0&&!s.startsWith("--")&&t.push(s)}return t}function Mo(n){return new Promise((e,t)=>{let r=[];n.on("data",s=>{r.push(typeof s=="string"?Buffer.from(s):s)}),n.on("end",()=>e(Buffer.concat(r).toString("utf8"))),n.on("error",t)})}var Ro,mh,Lo=C(()=>{"use strict";Ro={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".heic":"image/heic",".webp":"image/webp",".gif":"image/gif"};mh=`mio-agent agentcli \u2014 agent-facing message CLI (Slice 1)
128
128
 
129
129
  Usage:
130
130
  mio-agent agentcli message check --channel <#name>
@@ -187,38 +187,39 @@ Error codes (relayed from proxy):
187
187
  CAPABILITY_DENIED launch lacks the required capability
188
188
  UPSTREAM_UNREACHABLE proxy cannot reach the server
189
189
  (and others from agentProxy.ts / the server)
190
- `});var Po={};He(Po,{runAgentcliCommand:()=>lh});async function lh(){return To(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var Io=C(()=>{"use strict";Oo()});import{execFileSync as Is}from"child_process";function yr(n){return Is("security",["add-generic-password","-U","-s",pr,"-a",mr,"-w",n]),`${pr}:${mr}`}function Rt(){return Is("security",["find-generic-password","-s",pr,"-a",mr,"-w"]).toString().trim()}function No(){Is("security",["delete-generic-password","-s",pr,"-a",mr])}var pr,mr,en=C(()=>{"use strict";pr="io.miomioos.mio-agent",mr="machine_token"});var Ns=ee((Hw,Mo)=>{Mo.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var Do=ee((qw,$o)=>{var uh=Ns();function Lo(n){this.mode=uh.MODE_8BIT_BYTE,this.data=n}Lo.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)}};$o.exports=Lo});var Ms=ee((Gw,Bo)=>{var Ke={glog:function(n){if(n<1)throw new Error("glog("+n+")");return Ke.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return Ke.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(pe=0;pe<8;pe++)Ke.EXP_TABLE[pe]=1<<pe;var pe;for(pe=8;pe<256;pe++)Ke.EXP_TABLE[pe]=Ke.EXP_TABLE[pe-4]^Ke.EXP_TABLE[pe-5]^Ke.EXP_TABLE[pe-6]^Ke.EXP_TABLE[pe-8];var pe;for(pe=0;pe<255;pe++)Ke.LOG_TABLE[Ke.EXP_TABLE[pe]]=pe;var pe;Bo.exports=Ke});var Ls=ee((Ww,Uo)=>{var Bt=Ms();function _r(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]}_r.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]^=Bt.gexp(Bt.glog(this.get(t))+Bt.glog(n.get(r)));return new _r(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=Bt.glog(this.get(0))-Bt.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]^=Bt.gexp(Bt.glog(n.get(s))+e);return new _r(t,0).mod(n)}};Uo.exports=_r});var Ho=ee((jw,Fo)=>{Fo.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Wo=ee((Jw,Go)=>{var je=Ns(),qo=Ls(),fh=Ms(),At=Ho(),Se={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;Se.getBCHDigit(e)-Se.getBCHDigit(Se.G15)>=0;)e^=Se.G15<<Se.getBCHDigit(e)-Se.getBCHDigit(Se.G15);return(n<<10|e)^Se.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;Se.getBCHDigit(e)-Se.getBCHDigit(Se.G18)>=0;)e^=Se.G18<<Se.getBCHDigit(e)-Se.getBCHDigit(Se.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return Se.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case At.PATTERN000:return(e+t)%2===0;case At.PATTERN001:return e%2===0;case At.PATTERN010:return t%3===0;case At.PATTERN011:return(e+t)%3===0;case At.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case At.PATTERN101:return e*t%2+e*t%3===0;case At.PATTERN110:return(e*t%2+e*t%3)%2===0;case At.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new qo([1],0),t=0;t<n;t++)e=e.multiply(new qo([1,fh.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case je.MODE_NUMBER:return 10;case je.MODE_ALPHA_NUM:return 9;case je.MODE_8BIT_BYTE:return 8;case je.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case je.MODE_NUMBER:return 12;case je.MODE_ALPHA_NUM:return 11;case je.MODE_8BIT_BYTE:return 16;case je.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case je.MODE_NUMBER:return 14;case je.MODE_ALPHA_NUM:return 13;case je.MODE_8BIT_BYTE:return 16;case je.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 l=0;n.isDark(r,s)&&l++,n.isDark(r+1,s)&&l++,n.isDark(r,s+1)&&l++,n.isDark(r+1,s+1)&&l++,(l===0||l===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 d=0;for(s=0;s<e;s++)for(r=0;r<e;r++)n.isDark(r,s)&&d++;var u=Math.abs(100*d/e/e-50)/5;return t+=u*10,t}};Go.exports=Se});var $s=ee((Yw,jo)=>{jo.exports={L:1,M:0,Q:3,H:2}});var Yo=ee((Vw,Jo)=>{var wr=$s();function ot(n,e){this.totalCount=n,this.dataCount=e}ot.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]];ot.getRSBlocks=function(n,e){var t=ot.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],l=0;l<o;l++)s.push(new ot(a,c));return s};ot.getRsBlockTable=function(n,e){switch(e){case wr.L:return ot.RS_BLOCK_TABLE[(n-1)*4+0];case wr.M:return ot.RS_BLOCK_TABLE[(n-1)*4+1];case wr.Q:return ot.RS_BLOCK_TABLE[(n-1)*4+2];case wr.H:return ot.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};Jo.exports=ot});var Ko=ee((zw,zo)=>{function Vo(){this.buffer=[],this.length=0}Vo.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++}};zo.exports=Vo});var ea=ee((Kw,Zo)=>{var hh=Do(),Ot=Wo(),gh=Ls(),Xo=Yo(),Qo=Ko();function at(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}at.prototype={addData:function(n){var e=new hh(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=Xo.getRSBlocks(n,this.errorCorrectLevel),t=new Qo,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(),Ot.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=at.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=Ot.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,l=this.modules[i][a];l&&(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=Ot.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=Ot.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=Ot.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 l=Ot.getMask(e,r,o-a);l&&(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}}}};at.PAD0=236;at.PAD1=17;at.createData=function(n,e,t){for(var r=Xo.getRSBlocks(n,e),s=new Qo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Ot.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(at.PAD0,8),s.getLengthInBits()>=a*8));)s.put(at.PAD1,8);return at.createBytes(s,r)};at.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,l=e[a].totalCount-c;r=Math.max(r,c),s=Math.max(s,l),i[a]=new Array(c);for(var d=0;d<i[a].length;d++)i[a][d]=255&n.buffer[d+t];t+=c;var u=Ot.getErrorCorrectPolynomial(l),m=new gh(i[a],u.getLength()-1),p=m.mod(u);o[a]=new Array(u.getLength()-1);for(var f=0;f<o[a].length;f++){var g=f+p.getLength()-o[a].length;o[a][f]=g>=0?p.get(g):0}}for(var _=0,S=0;S<e.length;S++)_+=e[S].totalCount;for(var v=new Array(_),y=0,k=0;k<r;k++)for(var P=0;P<e.length;P++)k<i[P].length&&(v[y++]=i[P][k]);for(var x=0;x<s;x++)for(var O=0;O<e.length;O++)x<o[O].length&&(v[y++]=o[O][x]);return v};Zo.exports=at});var Bs=ee((Xw,na)=>{var ph=ea(),ta=$s(),mh="\x1B[40m \x1B[0m",vr="\x1B[47m \x1B[0m",yh=function(n){return n?mh:vr},Ds=function(n){return{times:function(e){return new Array(e).join(n)}}},_h=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};na.exports={error:ta.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new ph(-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(),l=a%2===1;l&&c.push(_h(a,o));var d={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=Ds(d.BLACK_WHITE).times(a+3),m=Ds(d.WHITE_BLACK).times(a+3);s+=u+`
191
- `;for(var p=0;p<a;p+=2){s+=d.WHITE_ALL;for(var f=0;f<a;f++)c[p][f]===o&&c[p+1][f]===o?s+=d.WHITE_ALL:c[p][f]===o&&c[p+1][f]===i?s+=d.WHITE_BLACK:c[p][f]===i&&c[p+1][f]===o?s+=d.BLACK_WHITE:s+=d.BLACK_ALL;s+=d.WHITE_ALL+`
192
- `}l||(s+=m)}else{var g=Ds(vr).times(r.getModuleCount()+3);s+=g+`
193
- `,r.modules.forEach(function(_){s+=vr,s+=_.map(yh).join(""),s+=vr+`
194
- `}),s+=g}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=ta[n]||this.error}}});var aa={};He(aa,{runLogin:()=>xh});import{parseArgs as wh}from"node:util";import Pn from"node:os";import{mkdirSync as vh,writeFileSync as bh,existsSync as kh}from"node:fs";import{join as ra}from"node:path";function Eh(n){return new Promise(e=>setTimeout(e,n))}function oa(){console.log(`Usage: mio-agent login [--server <url>] [--device-name <name>]
190
+ `});var $o={};He($o,{runAgentcliCommand:()=>yh});async function yh(){return Po(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var Do=C(()=>{"use strict";Lo()});import{execFileSync as $s}from"child_process";function _r(n){return $s("security",["add-generic-password","-U","-s",mr,"-a",yr,"-w",n]),`${mr}:${yr}`}function Rt(){return $s("security",["find-generic-password","-s",mr,"-a",yr,"-w"]).toString().trim()}function Bo(){$s("security",["delete-generic-password","-s",mr,"-a",yr])}var mr,yr,en=C(()=>{"use strict";mr="io.miomioos.mio-agent",yr="machine_token"});var Ds=ee((Kw,Uo)=>{Uo.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var qo=ee((zw,Ho)=>{var _h=Ds();function Fo(n){this.mode=_h.MODE_8BIT_BYTE,this.data=n}Fo.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)}};Ho.exports=Fo});var Bs=ee((Xw,Go)=>{var ze={glog:function(n){if(n<1)throw new Error("glog("+n+")");return ze.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return ze.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(ge=0;ge<8;ge++)ze.EXP_TABLE[ge]=1<<ge;var ge;for(ge=8;ge<256;ge++)ze.EXP_TABLE[ge]=ze.EXP_TABLE[ge-4]^ze.EXP_TABLE[ge-5]^ze.EXP_TABLE[ge-6]^ze.EXP_TABLE[ge-8];var ge;for(ge=0;ge<255;ge++)ze.LOG_TABLE[ze.EXP_TABLE[ge]]=ge;var ge;Go.exports=ze});var Us=ee((Qw,Wo)=>{var Bt=Bs();function wr(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]}wr.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]^=Bt.gexp(Bt.glog(this.get(t))+Bt.glog(n.get(r)));return new wr(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=Bt.glog(this.get(0))-Bt.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]^=Bt.gexp(Bt.glog(n.get(s))+e);return new wr(t,0).mod(n)}};Wo.exports=wr});var Jo=ee((Zw,jo)=>{jo.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Ko=ee((ev,Vo)=>{var je=Ds(),Yo=Us(),wh=Bs(),At=Jo(),Se={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;Se.getBCHDigit(e)-Se.getBCHDigit(Se.G15)>=0;)e^=Se.G15<<Se.getBCHDigit(e)-Se.getBCHDigit(Se.G15);return(n<<10|e)^Se.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;Se.getBCHDigit(e)-Se.getBCHDigit(Se.G18)>=0;)e^=Se.G18<<Se.getBCHDigit(e)-Se.getBCHDigit(Se.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return Se.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case At.PATTERN000:return(e+t)%2===0;case At.PATTERN001:return e%2===0;case At.PATTERN010:return t%3===0;case At.PATTERN011:return(e+t)%3===0;case At.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case At.PATTERN101:return e*t%2+e*t%3===0;case At.PATTERN110:return(e*t%2+e*t%3)%2===0;case At.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new Yo([1],0),t=0;t<n;t++)e=e.multiply(new Yo([1,wh.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case je.MODE_NUMBER:return 10;case je.MODE_ALPHA_NUM:return 9;case je.MODE_8BIT_BYTE:return 8;case je.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case je.MODE_NUMBER:return 12;case je.MODE_ALPHA_NUM:return 11;case je.MODE_8BIT_BYTE:return 16;case je.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case je.MODE_NUMBER:return 14;case je.MODE_ALPHA_NUM:return 13;case je.MODE_8BIT_BYTE:return 16;case je.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 l=0;n.isDark(r,s)&&l++,n.isDark(r+1,s)&&l++,n.isDark(r,s+1)&&l++,n.isDark(r+1,s+1)&&l++,(l===0||l===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 d=0;for(s=0;s<e;s++)for(r=0;r<e;r++)n.isDark(r,s)&&d++;var u=Math.abs(100*d/e/e-50)/5;return t+=u*10,t}};Vo.exports=Se});var Fs=ee((tv,zo)=>{zo.exports={L:1,M:0,Q:3,H:2}});var Qo=ee((nv,Xo)=>{var vr=Fs();function ot(n,e){this.totalCount=n,this.dataCount=e}ot.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]];ot.getRSBlocks=function(n,e){var t=ot.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],l=0;l<o;l++)s.push(new ot(a,c));return s};ot.getRsBlockTable=function(n,e){switch(e){case vr.L:return ot.RS_BLOCK_TABLE[(n-1)*4+0];case vr.M:return ot.RS_BLOCK_TABLE[(n-1)*4+1];case vr.Q:return ot.RS_BLOCK_TABLE[(n-1)*4+2];case vr.H:return ot.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};Xo.exports=ot});var ta=ee((rv,ea)=>{function Zo(){this.buffer=[],this.length=0}Zo.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++}};ea.exports=Zo});var ia=ee((sv,sa)=>{var vh=qo(),Ot=Ko(),bh=Us(),na=Qo(),ra=ta();function at(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}at.prototype={addData:function(n){var e=new vh(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=na.getRSBlocks(n,this.errorCorrectLevel),t=new ra,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(),Ot.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=at.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=Ot.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,l=this.modules[i][a];l&&(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=Ot.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=Ot.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=Ot.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 l=Ot.getMask(e,r,o-a);l&&(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}}}};at.PAD0=236;at.PAD1=17;at.createData=function(n,e,t){for(var r=na.getRSBlocks(n,e),s=new ra,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Ot.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(at.PAD0,8),s.getLengthInBits()>=a*8));)s.put(at.PAD1,8);return at.createBytes(s,r)};at.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,l=e[a].totalCount-c;r=Math.max(r,c),s=Math.max(s,l),i[a]=new Array(c);for(var d=0;d<i[a].length;d++)i[a][d]=255&n.buffer[d+t];t+=c;var u=Ot.getErrorCorrectPolynomial(l),m=new bh(i[a],u.getLength()-1),g=m.mod(u);o[a]=new Array(u.getLength()-1);for(var f=0;f<o[a].length;f++){var p=f+g.getLength()-o[a].length;o[a][f]=p>=0?g.get(p):0}}for(var w=0,k=0;k<e.length;k++)w+=e[k].totalCount;for(var v=new Array(w),_=0,S=0;S<r;S++)for(var P=0;P<e.length;P++)S<i[P].length&&(v[_++]=i[P][S]);for(var x=0;x<s;x++)for(var O=0;O<e.length;O++)x<o[O].length&&(v[_++]=o[O][x]);return v};sa.exports=at});var qs=ee((iv,aa)=>{var kh=ia(),oa=Fs(),Sh="\x1B[40m \x1B[0m",br="\x1B[47m \x1B[0m",Eh=function(n){return n?Sh:br},Hs=function(n){return{times:function(e){return new Array(e).join(n)}}},xh=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};aa.exports={error:oa.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new kh(-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(),l=a%2===1;l&&c.push(xh(a,o));var d={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=Hs(d.BLACK_WHITE).times(a+3),m=Hs(d.WHITE_BLACK).times(a+3);s+=u+`
191
+ `;for(var g=0;g<a;g+=2){s+=d.WHITE_ALL;for(var f=0;f<a;f++)c[g][f]===o&&c[g+1][f]===o?s+=d.WHITE_ALL:c[g][f]===o&&c[g+1][f]===i?s+=d.WHITE_BLACK:c[g][f]===i&&c[g+1][f]===o?s+=d.BLACK_WHITE:s+=d.BLACK_ALL;s+=d.WHITE_ALL+`
192
+ `}l||(s+=m)}else{var p=Hs(br).times(r.getModuleCount()+3);s+=p+`
193
+ `,r.modules.forEach(function(w){s+=br,s+=w.map(Eh).join(""),s+=br+`
194
+ `}),s+=p}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=oa[n]||this.error}}});var fa={};He(fa,{runLogin:()=>Ih});import{parseArgs as Th}from"node:util";import Pn from"node:os";import{mkdirSync as Ch,writeFileSync as Rh,existsSync as Ah}from"node:fs";import{join as ca}from"node:path";function Ph(n){return new Promise(e=>setTimeout(e,n))}function ua(){console.log(`Usage: mio-agent login [--server <url>] [--device-name <name>]
195
195
 
196
196
  Zero-touch machine enrollment via QR + phone approval.
197
197
 
198
198
  Options:
199
- --server <url> MioServer base URL (default: ${Us})
199
+ --server <url> MioServer base URL (default: ${Gs})
200
200
  --device-name <name> Friendly name for this machine (default: hostname)
201
201
  --help Show this message
202
- `)}async function xh(n){let e;try{({values:e}=wh({args:n,options:{server:{type:"string",default:Us},"device-name":{type:"string",default:Pn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(y){let k=y instanceof Error?y.message:String(y);return console.error(`Error: ${k}`),oa(),1}if(e.help)return oa(),0;let t=(e.server??Us).replace(/\/+$/,""),r=e["device-name"]??Pn.hostname(),s=Pn.platform(),i=Pn.arch(),o;try{let y=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(!y.ok)return console.error(`Failed to create enrollment intent (HTTP ${y.status}). Check --server (currently ${t}).`),1;o=await y.json()}catch(y){let k=y instanceof Error?y.message:String(y);return console.error(`Network error contacting ${t}: ${k}`),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 l=await Promise.resolve().then(()=>oe(Bs(),1)).catch(()=>null),d=l?.default??l,u=typeof d?.generate=="function"?(y,k,P)=>d.generate(y,k,P):null;u?await new Promise(y=>{u(c,{small:!0},k=>{console.log(k),y()})}):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(),p=sa,f=null;for(;Date.now()-m<Sh;){await Eh(p);try{let y=await fetch(`${t}/api/v1/enrollment-intents/${o.intent_id}?code=${encodeURIComponent(o.opaque_code)}`,{method:"GET"});if(y.status===200){f=await y.json();break}if(y.status===202){p=sa;continue}if(y.status===403)return console.error("Enrollment code became invalid (expired, canceled, or already consumed). Re-run `mio-agent login`."),1;p=Math.min(p*2,ia);continue}catch{p=Math.min(p*2,ia);continue}}if(!f)return console.error("Enrollment timed out (5 min). Re-run `mio-agent login` to retry."),1;let g=yr(f.machine_token),_=ra(Pn.homedir(),".mio");kh(_)||vh(_,{recursive:!0,mode:448});let S=ra(_,"agent.json"),v={machine_id:f.machine_id,org_id:f.org_id,workroom_id:f.workroom_id,server_url:t,keychain_item_ref:g,runtimes:[],token_buffer:!1};return bh(S,JSON.stringify(v,null,2),{mode:384}),console.log(""),console.log(`Successfully enrolled as "${r}" in workroom ${f.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 Us,sa,ia,Sh,ca=C(()=>{"use strict";en();Us="https://mio.wdao.chat",sa=2e3,ia=3e4,Sh=300*1e3});var la={};He(la,{runLogs:()=>Ah});import{existsSync as Fs}from"node:fs";import{homedir as Th}from"node:os";import{join as da}from"node:path";import{spawn as Ch}from"node:child_process";function Rh(){let n=Th(),e=da(n,".mio","logs","mio-agent.log"),t=da(n,".mio","logs","mio-agent-error.log"),r="/tmp/mio-agent.log",s=[];return Fs(e)&&s.push(e),Fs(t)&&s.push(t),s.length===0&&Fs(r)&&s.push(r),s}async function Ah(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=Rh();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(", ")}
203
- `);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=Ch("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 ua=C(()=>{"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 E(n,e,t){h("error",n,e,{error:t instanceof Error?t.message:String(t)})}var ge=C(()=>{"use strict"});import{readFileSync as Oh,writeFileSync as Ph,mkdirSync as Hs,chmodSync as Ih,existsSync as fa}from"fs";import{homedir as Nh}from"os";import{join as In}from"path";function Nn(){Hs(_e,{recursive:!0,mode:448}),Hs(Mh,{recursive:!0,mode:448}),Hs(Ut,{recursive:!0,mode:448})}function ga(){return fa(tn)}function Xe(){if(!fa(tn))throw new Error(`No config at ${tn}. Run: mio-agent login`);return JSON.parse(Oh(tn,"utf-8"))}function br(n){Nn();let e=JSON.stringify(n,null,2);Ph(tn,e,{encoding:"utf-8",mode:384}),Ih(tn,384)}var _e,tn,Mh,Ut,uv,ha,Qe=C(()=>{"use strict";_e=In(Nh(),".mio"),tn=In(_e,"agent.json"),Mh=In(_e,"logs"),Ut=In(_e,"tmp"),uv=In(_e,"agent.sock"),ha=7878});import{readFileSync as Lh,writeFileSync as $h,existsSync as Dh}from"fs";import{join as Bh}from"path";function pa(){if(!Dh(qs))return{};try{return JSON.parse(Lh(qs,"utf-8"))}catch{return{}}}function Uh(n){Nn(),$h(qs,JSON.stringify(n,null,2),{mode:384})}function ma(){let n=pa();return new Map(Object.entries(n))}function ya(n,e){let t=pa(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Uh(t))}var qs,_a=C(()=>{"use strict";Qe();qs=Bh(_e,"cursors.json")});async function ie(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 Mn(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function we(n){return{Authorization:`Bearer ${n}`}}async function wa(n,e){return ie(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:we(e)})}async function va(n,e,t){return ie(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:we(t),body:JSON.stringify({})})}async function ba(n,e,t){await ie(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:we(t),body:JSON.stringify({})})}async function ka(n,e,t=!1,r){await ie(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:we(e),body:JSON.stringify(t?{going_offline:!0}:r?{usage:r}:{})})}async function Sa(n,e,t,r){await ie(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:we(r),body:JSON.stringify({status:t})})}async function Ea(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return ie(s,{headers:we(r)})}async function xa(n,e,t){return ie(`${n}/api/v1/actions/${e}`,{headers:we(t)})}async function Ta(n,e,t){return ie(`${n}/api/v1/approvals/${e}`,{headers:we(t)})}async function Ca(n,e,t,r){let s=r?{approval_id:r}:{};return ie(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:we(t),body:JSON.stringify(s)})}async function Ra(n,e,t){await ie(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:we(t),body:JSON.stringify({})})}async function Aa(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}`,l=await ie(c,{headers:we(i)});return{messages:l.messages,hasMore:l.has_more}}async function nn(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),ie(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:we(s),body:JSON.stringify(i)})}async function Oa(n,e,t){return(await ie(`${n}/api/v1/workrooms/${e}/members`,{headers:we(t)})).members??[]}async function Pa(n,e,t){return ie(`${n}/api/v1/workrooms/${e}/roster`,{headers:we(t)})}async function Ia(n,e,t){return(await ie(`${n}/api/v1/workrooms/${e}/channels`,{headers:we(t)})).channels??[]}async function Na(n,e,t){return(await ie(`${n}/internal/agent-api/channels`,{headers:{...we(e),"X-Mio-Agent-Id":t}})).channels??[]}async function kr(n,e,t,r){return(await ie(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...we(e),"X-Mio-Agent-Id":t}})).tasks??[]}function Je(n,e){return{...we(n),"X-Mio-Agent-Id":e}}async function Ma(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function La(n,e,t){return(await ie(`${n}/internal/agent-api/reminders/list`,{headers:Je(e,t)})).reminders??[]}async function $a(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function Da(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function Ba(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function Ua(n,e,t){return(await ie(`${n}/internal/agent-api/reminders/log`,{headers:Je(e,t)})).events??[]}async function Fa(n,e,t,r){await ie(`${n}/internal/agent-api/typing`,{method:"POST",headers:Je(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Ha(n,e,t,r){await ie(`${n}/internal/agent-api/status`,{method:"POST",headers:Je(e,t),body:JSON.stringify({agent_id:t,...r})})}async function qa(n,e,t,r){await ie(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})}async function Ga(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 ie(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${a}`,{headers:Je(e,t)})).messages??[]}async function Wa(n,e,t,r){return(await ie(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:Je(e,t)})).message}async function ja(n,e,t,r){return ie(`${n}/internal/agent-api/attachments/${r}`,{headers:Je(e,t)})}var Mn,Ln=C(()=>{"use strict";Mn=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 Va=ee((_v,Ya)=>{var rn=te("fs"),Ja=te("url"),Fh=te("child_process").spawn;Ya.exports=Gs;Gs.XMLHttpRequest=Gs;function Gs(n){"use strict";n=n||{};var e=this,t=te("http"),r=te("https"),s,i,o={},a=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},l=Object.assign({},c),d=["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,p=!1,f=!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 _=function(y){return a||y&&d.indexOf(y.toLowerCase())===-1},S=function(y){return y&&u.indexOf(y)===-1};this.open=function(y,k,P,x,O){if(this.abort(),p=!1,f=!1,!S(y))throw new Error("SecurityError: Request method not allowed");o={method:y,url:k.toString(),async:typeof P!="boolean"?!0:P,user:x||null,password:O||null},v(this.OPENED)},this.setDisableHeaderCheck=function(y){a=y},this.setRequestHeader=function(y,k){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 "'+y+'"'),!1;if(m)throw new Error("INVALID_STATE_ERR: send flag is true");return l[y]=k,!0},this.getResponseHeader=function(y){return typeof y=="string"&&this.readyState>this.OPENED&&i.headers[y.toLowerCase()]&&!p?i.headers[y.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||p)return"";var y="";for(var k in i.headers)k!=="set-cookie"&&k!=="set-cookie2"&&(y+=k+": "+i.headers[k]+`\r
204
- `);return y.substr(0,y.length-2)},this.getRequestHeader=function(y){return typeof y=="string"&&l[y]?l[y]:""},this.send=function(y){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 k=!1,P=!1,x=Ja.parse(o.url),O;switch(x.protocol){case"https:":k=!0;case"http:":O=x.hostname;break;case"file:":P=!0;break;case void 0:case"":O="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)rn.readFile(unescape(x.pathname),function(U,K){U?e.handleError(U,U.errno||-1):(e.status=200,e.responseText=K.toString("utf8"),e.response=K,v(e.DONE))});else try{this.response=rn.readFileSync(unescape(x.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,v(e.DONE)}catch(U){this.handleError(U,U.errno||-1)}return}var W=x.port||(k?443:80),J=x.pathname+(x.search?x.search:"");if(l.Host=O,k&&W===443||W===80||(l.Host+=":"+x.port),o.user){typeof o.password>"u"&&(o.password="");var Y=new Buffer(o.user+":"+o.password);l.Authorization="Basic "+Y.toString("base64")}if(o.method==="GET"||o.method==="HEAD")y=null;else if(y){l["Content-Length"]=Buffer.isBuffer(y)?y.length:Buffer.byteLength(y);var re=Object.keys(l);re.some(function(U){return U.toLowerCase()==="content-type"})||(l["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(l["Content-Length"]=0);var ae=n.agent||!1,V={host:O,port:W,path:J,method:o.method,headers:l,agent:ae};if(k&&(V.pfx=n.pfx,V.key=n.key,V.passphrase=n.passphrase,V.cert=n.cert,V.ca=n.ca,V.ciphers=n.ciphers,V.rejectUnauthorized=n.rejectUnauthorized!==!1),p=!1,o.async){var le=k?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var ue=function(U){if(i=U,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var K=Ja.parse(o.url);O=K.hostname;var se={hostname:K.hostname,port:K.port,path:K.path,method:i.statusCode===303?"GET":o.method,headers:l};k&&(se.pfx=n.pfx,se.key=n.key,se.passphrase=n.passphrase,se.cert=n.cert,se.ca=n.ca,se.ciphers=n.ciphers,se.rejectUnauthorized=n.rejectUnauthorized!==!1),s=le(se,ue).on("error",$),s.end();return}v(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(R){if(R){var B=Buffer.from(R);e.response=Buffer.concat([e.response,B])}m&&v(e.LOADING)}),i.on("end",function(){m&&(m=!1,v(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(R){e.handleError(R)})},$=function(U){if(s.reusedSocket&&U.code==="ECONNRESET")return le(V,ue).on("error",$);e.handleError(U)};s=le(V,ue).on("error",$),n.autoUnref&&s.on("socket",U=>{U.unref()}),y&&s.write(y),s.end(),e.dispatchEvent("loadstart")}else{var Q=".node-xmlhttprequest-content-"+process.pid,w=".node-xmlhttprequest-sync-"+process.pid;rn.writeFileSync(w,"","utf8");for(var b="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(k?"s":"")+".request;var options = "+JSON.stringify(V)+";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('"+Q+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+w+"');});response.on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+w+"');});}).on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+w+"');});"+(y?"req.write('"+JSON.stringify(y).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",T=Fh(process.argv[0],["-e",b]),D;rn.existsSync(w););if(e.responseText=rn.readFileSync(Q,"utf8"),T.stdin.end(),rn.unlinkSync(Q),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var q=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(q,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var I=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:I.data.headers},e.responseText=I.data.text,e.response=Buffer.from(I.data.data,"base64"),v(e.DONE,!0)}}},this.handleError=function(y,k){this.status=k||0,this.statusText=y,this.responseText=y.stack,p=!0,v(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),l=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),p=f=!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(y,k){y in g||(g[y]=[]),g[y].push(k)},this.removeEventListener=function(y,k){y in g&&(g[y]=g[y].filter(function(P){return P!==k}))},this.dispatchEvent=function(y){if(typeof e["on"+y]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+y]()},0):e["on"+y]()),y in g)for(let k=0,P=g[y].length;k<P;k++)this.readyState===this.DONE?setTimeout(function(){g[y][k].call(e)},0):g[y][k].call(e)};var v=function(y){if(!(e.readyState===y||e.readyState===e.UNSENT&&f)&&(e.readyState=y,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let k;f?k="abort":p?k="error":k="load",e.dispatchEvent(k),e.dispatchEvent("loadend")}}}});var Ze,$n,Dn,Sr=C(()=>{Ze=Object.create(null);Ze.open="0";Ze.close="1";Ze.ping="2";Ze.pong="3";Ze.message="4";Ze.upgrade="5";Ze.noop="6";$n=Object.create(null);Object.keys(Ze).forEach(n=>{$n[Ze[n]]=n});Dn={type:"error",data:"parser error"}});function Ka(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(za(n.data,!1));Bn(n,!0,t=>{Ws||(Ws=new TextEncoder),e(Ws.encode(t))})}var Bn,za,Ws,Xa=C(()=>{Sr();Bn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+za(e,!0).toString("base64")):r(Ze[n]+(e||"")),za=(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 Un,Qa,Za=C(()=>{Sr();Un=(n,e)=>{if(typeof n!="string")return{type:"message",data:Qa(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:Qa(r,e)}}return $n[t]?n.length>1?{type:$n[t],data:n.substring(1)}:{type:$n[t]}:Dn},Qa=(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 rc(){return new TransformStream({transform(n,e){Ka(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 Er(n){return n.reduce((e,t)=>e+t.length,0)}function xr(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 sc(n,e){js||(js=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(Er(t)<1)break;let c=xr(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(Er(t)<2)break;let c=xr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(Er(t)<8)break;let c=xr(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),d=l.getUint32(0);if(d>Math.pow(2,21)-1){a.enqueue(Dn);break}s=d*Math.pow(2,32)+l.getUint32(4),r=3}else{if(Er(t)<s)break;let c=xr(t,s);a.enqueue(Un(i?c:js.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(Dn);break}}}})}var ec,tc,nc,js,Js,sn=C(()=>{Xa();Za();Sr();ec="",tc=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Bn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(ec))})})},nc=(n,e)=>{let t=n.split(ec),r=[];for(let s=0;s<t.length;s++){let i=Un(t[s],e);if(r.push(i),i.type==="error")break}return r};Js=4});var Ft=ee(ic=>{ic.Emitter=Oe;function Oe(n){if(n)return Hh(n)}function Hh(n){for(var e in Oe.prototype)n[e]=Oe.prototype[e];return n}Oe.prototype.on=Oe.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Oe.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Oe.prototype.off=Oe.prototype.removeListener=Oe.prototype.removeAllListeners=Oe.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};Oe.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};Oe.prototype.emitReserved=Oe.prototype.emit;Oe.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Oe.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function ac(){return new Ys}function qh(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(),l=a[1].trim();switch(c){case"Expires":i.expires=new Date(l);break;case"Max-Age":let d=new Date;d.setUTCSeconds(d.getUTCSeconds()+parseInt(l,10)),i.expires=d;break;default:}}return i}var pt,Pe,oc,Ys,Ht=C(()=>{pt=process.nextTick,Pe=global,oc="nodebuffer";Ys=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=qh(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 Tr(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function mt(n,e){e.useNativeTimers?(n.setTimeoutFn=Gh.bind(Pe),n.clearTimeoutFn=Wh.bind(Pe)):(n.setTimeoutFn=Pe.setTimeout.bind(Pe),n.clearTimeoutFn=Pe.clearTimeout.bind(Pe))}function cc(n){return typeof n=="string"?Jh(n):Math.ceil((n.byteLength||n.size)*jh)}function Jh(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 Cr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Gh,Wh,jh,qt=C(()=>{Ht();Gh=Pe.setTimeout,Wh=Pe.clearTimeout;jh=1.33});function dc(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function lc(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 Vs=C(()=>{});var fc=ee((Nv,uc)=>{var on=1e3,an=on*60,cn=an*60,Gt=cn*24,Yh=Gt*7,Vh=Gt*365.25;uc.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return zh(n);if(t==="number"&&isFinite(n))return e.long?Xh(n):Kh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function zh(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*Vh;case"weeks":case"week":case"w":return t*Yh;case"days":case"day":case"d":return t*Gt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*cn;case"minutes":case"minute":case"mins":case"min":case"m":return t*an;case"seconds":case"second":case"secs":case"sec":case"s":return t*on;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Kh(n){var e=Math.abs(n);return e>=Gt?Math.round(n/Gt)+"d":e>=cn?Math.round(n/cn)+"h":e>=an?Math.round(n/an)+"m":e>=on?Math.round(n/on)+"s":n+"ms"}function Xh(n){var e=Math.abs(n);return e>=Gt?Rr(n,e,Gt,"day"):e>=cn?Rr(n,e,cn,"hour"):e>=an?Rr(n,e,an,"minute"):e>=on?Rr(n,e,on,"second"):n+" ms"}function Rr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var zs=ee((Mv,hc)=>{function Qh(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=fc(),t.destroy=l,Object.keys(n).forEach(d=>{t[d]=n[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let m=0;m<d.length;m++)u=(u<<5)-u+d.charCodeAt(m),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,m=null,p,f;function g(..._){if(!g.enabled)return;let S=g,v=Number(new Date),y=v-(u||v);S.diff=y,S.prev=u,S.curr=v,u=v,_[0]=t.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let k=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(x,O)=>{if(x==="%%")return"%";k++;let W=t.formatters[O];if(typeof W=="function"){let J=_[k];x=W.call(S,J),_.splice(k,1),k--}return x}),t.formatArgs.call(S,_),(S.log||t.log).apply(S,_)}return g.namespace=d,g.useColors=t.useColors(),g.color=t.selectColor(d),g.extend=r,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(p!==t.namespaces&&(p=t.namespaces,f=t.enabled(d)),f),set:_=>{m=_}}),typeof t.init=="function"&&t.init(g),g}function r(d,u){let m=t(this.namespace+(typeof u>"u"?":":u)+d);return m.log=this.log,m}function s(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u=(typeof d=="string"?d:"").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(d,u){let m=0,p=0,f=-1,g=0;for(;m<d.length;)if(p<u.length&&(u[p]===d[m]||u[p]==="*"))u[p]==="*"?(f=p,g=m,p++):(m++,p++);else if(f!==-1)p=f+1,g++,m=g;else return!1;for(;p<u.length&&u[p]==="*";)p++;return p===u.length}function o(){let d=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),d}function a(d){for(let u of t.skips)if(i(d,u))return!1;for(let u of t.names)if(i(d,u))return!0;return!1}function c(d){return d instanceof Error?d.stack||d.message:d}function l(){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}hc.exports=Qh});var gc=ee((Le,Ar)=>{Le.formatArgs=eg;Le.save=tg;Le.load=ng;Le.useColors=Zh;Le.storage=rg();Le.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`."))}})();Le.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 Zh(){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 eg(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Ar.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)}Le.log=console.debug||console.log||(()=>{});function tg(n){try{n?Le.storage.setItem("debug",n):Le.storage.removeItem("debug")}catch{}}function ng(){let n;try{n=Le.storage.getItem("debug")||Le.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function rg(){try{return localStorage}catch{}}Ar.exports=zs()(Le);var{formatters:sg}=Ar.exports;sg.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var mc=ee((ve,Pr)=>{var ig=te("tty"),Or=te("util");ve.init=fg;ve.log=dg;ve.formatArgs=ag;ve.save=lg;ve.load=ug;ve.useColors=og;ve.destroy=Or.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ve.colors=[6,2,3,4,5,1];try{let n=te("supports-color");n&&(n.stderr||n).level>=2&&(ve.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{}ve.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 og(){return"colors"in ve.inspectOpts?!!ve.inspectOpts.colors:ig.isatty(process.stderr.fd)}function ag(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(`
202
+ `)}async function Ih(n){let e;try{({values:e}=Th({args:n,options:{server:{type:"string",default:Gs},"device-name":{type:"string",default:Pn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(_){let S=_ instanceof Error?_.message:String(_);return console.error(`Error: ${S}`),ua(),1}if(e.help)return ua(),0;let t=(e.server??Gs).replace(/\/+$/,""),r=e["device-name"]??Pn.hostname(),s=Pn.platform(),i=Pn.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 S=_ instanceof Error?_.message:String(_);return console.error(`Network error contacting ${t}: ${S}`),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 l=await Promise.resolve().then(()=>oe(qs(),1)).catch(()=>null),d=l?.default??l,u=typeof d?.generate=="function"?(_,S,P)=>d.generate(_,S,P):null;u?await new Promise(_=>{u(c,{small:!0},S=>{console.log(S),_()})}):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(),g=da,f=null;for(;Date.now()-m<Oh;){await Ph(g);try{let _=await fetch(`${t}/api/v1/enrollment-intents/${o.intent_id}?code=${encodeURIComponent(o.opaque_code)}`,{method:"GET"});if(_.status===200){f=await _.json();break}if(_.status===202){g=da;continue}if(_.status===403)return console.error("Enrollment code became invalid (expired, canceled, or already consumed). Re-run `mio-agent login`."),1;g=Math.min(g*2,la);continue}catch{g=Math.min(g*2,la);continue}}if(!f)return console.error("Enrollment timed out (5 min). Re-run `mio-agent login` to retry."),1;let p=_r(f.machine_token),w=ca(Pn.homedir(),".mio");Ah(w)||Ch(w,{recursive:!0,mode:448});let k=ca(w,"agent.json"),v={machine_id:f.machine_id,org_id:f.org_id,workroom_id:f.workroom_id,server_url:t,keychain_item_ref:p,runtimes:[],token_buffer:!1};return Rh(k,JSON.stringify(v,null,2),{mode:384}),console.log(""),console.log(`Successfully enrolled as "${r}" in workroom ${f.workroom_id.slice(0,8)}.`),console.log("Config: ~/.mio/agent.json (0600)"),console.log(`Token: macOS Keychain (${p})`),console.log(""),console.log("Run `mio-agent doctor` to verify."),0}var Gs,da,la,Oh,ha=C(()=>{"use strict";en();Gs="https://mio.wdao.chat",da=2e3,la=3e4,Oh=300*1e3});var ga={};He(ga,{runLogs:()=>$h});import{existsSync as Ws}from"node:fs";import{homedir as Nh}from"node:os";import{join as pa}from"node:path";import{spawn as Mh}from"node:child_process";function Lh(){let n=Nh(),e=pa(n,".mio","logs","mio-agent.log"),t=pa(n,".mio","logs","mio-agent-error.log"),r="/tmp/mio-agent.log",s=[];return Ws(e)&&s.push(e),Ws(t)&&s.push(t),s.length===0&&Ws(r)&&s.push(r),s}async function $h(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=Lh();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(", ")}
203
+ `);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=Mh("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 ma=C(()=>{"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 E(n,e,t){h("error",n,e,{error:t instanceof Error?t.message:String(t)})}var pe=C(()=>{"use strict"});import{readFileSync as Dh,writeFileSync as Bh,mkdirSync as js,chmodSync as Uh,existsSync as ya}from"fs";import{homedir as Fh}from"os";import{join as In}from"path";function Nn(){js(_e,{recursive:!0,mode:448}),js(Hh,{recursive:!0,mode:448}),js(Ut,{recursive:!0,mode:448})}function wa(){return ya(tn)}function Xe(){if(!ya(tn))throw new Error(`No config at ${tn}. Run: mio-agent login`);return JSON.parse(Dh(tn,"utf-8"))}function kr(n){Nn();let e=JSON.stringify(n,null,2);Bh(tn,e,{encoding:"utf-8",mode:384}),Uh(tn,384)}var _e,tn,Hh,Ut,wv,_a,Qe=C(()=>{"use strict";_e=In(Fh(),".mio"),tn=In(_e,"agent.json"),Hh=In(_e,"logs"),Ut=In(_e,"tmp"),wv=In(_e,"agent.sock"),_a=7878});import{readFileSync as qh,writeFileSync as Gh,existsSync as Wh}from"fs";import{join as jh}from"path";function va(){if(!Wh(Js))return{};try{return JSON.parse(qh(Js,"utf-8"))}catch{return{}}}function Jh(n){Nn(),Gh(Js,JSON.stringify(n,null,2),{mode:384})}function ba(){let n=va();return new Map(Object.entries(n))}function ka(n,e){let t=va(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Jh(t))}var Js,Sa=C(()=>{"use strict";Qe();Js=jh(_e,"cursors.json")});async function ie(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 Mn(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function we(n){return{Authorization:`Bearer ${n}`}}async function Ea(n,e){return ie(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:we(e)})}async function xa(n,e,t){return ie(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:we(t),body:JSON.stringify({})})}async function Ta(n,e,t){await ie(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:we(t),body:JSON.stringify({})})}async function Ca(n,e,t=!1,r){await ie(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:we(e),body:JSON.stringify(t?{going_offline:!0}:r?{usage:r}:{})})}async function Ra(n,e,t,r){await ie(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:we(r),body:JSON.stringify({status:t})})}async function Aa(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return ie(s,{headers:we(r)})}async function Oa(n,e,t){return ie(`${n}/api/v1/actions/${e}`,{headers:we(t)})}async function Pa(n,e,t){return ie(`${n}/api/v1/approvals/${e}`,{headers:we(t)})}async function Ia(n,e,t,r){let s=r?{approval_id:r}:{};return ie(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:we(t),body:JSON.stringify(s)})}async function Na(n,e,t){await ie(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:we(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}`,l=await ie(c,{headers:we(i)});return{messages:l.messages,hasMore:l.has_more}}async function nn(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),ie(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:we(s),body:JSON.stringify(i)})}async function La(n,e,t){return(await ie(`${n}/api/v1/workrooms/${e}/members`,{headers:we(t)})).members??[]}async function $a(n,e,t){return ie(`${n}/api/v1/workrooms/${e}/roster`,{headers:we(t)})}async function Da(n,e,t){return(await ie(`${n}/api/v1/workrooms/${e}/channels`,{headers:we(t)})).channels??[]}async function Ba(n,e,t){return(await ie(`${n}/internal/agent-api/channels`,{headers:{...we(e),"X-Mio-Agent-Id":t}})).channels??[]}async function Sr(n,e,t,r){return(await ie(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...we(e),"X-Mio-Agent-Id":t}})).tasks??[]}function Je(n,e){return{...we(n),"X-Mio-Agent-Id":e}}async function Ua(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function Fa(n,e,t){return(await ie(`${n}/internal/agent-api/reminders/list`,{headers:Je(e,t)})).reminders??[]}async function Ha(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function qa(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function Ga(n,e,t,r){return(await ie(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})).reminder}async function Wa(n,e,t){return(await ie(`${n}/internal/agent-api/reminders/log`,{headers:Je(e,t)})).events??[]}async function ja(n,e,t,r){await ie(`${n}/internal/agent-api/typing`,{method:"POST",headers:Je(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Ja(n,e,t,r){await ie(`${n}/internal/agent-api/status`,{method:"POST",headers:Je(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Ya(n,e,t,r){await ie(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:Je(e,t),body:JSON.stringify(r)})}async function Va(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 ie(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${a}`,{headers:Je(e,t)})).messages??[]}async function Ka(n,e,t,r){return(await ie(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:Je(e,t)})).message}async function za(n,e,t,r){return ie(`${n}/internal/agent-api/attachments/${r}`,{headers:Je(e,t)})}var Mn,Ln=C(()=>{"use strict";Mn=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 Za=ee((Tv,Qa)=>{var rn=te("fs"),Xa=te("url"),Yh=te("child_process").spawn;Qa.exports=Ys;Ys.XMLHttpRequest=Ys;function Ys(n){"use strict";n=n||{};var e=this,t=te("http"),r=te("https"),s,i,o={},a=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},l=Object.assign({},c),d=["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,g=!1,f=!1,p={};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 w=function(_){return a||_&&d.indexOf(_.toLowerCase())===-1},k=function(_){return _&&u.indexOf(_)===-1};this.open=function(_,S,P,x,O){if(this.abort(),g=!1,f=!1,!k(_))throw new Error("SecurityError: Request method not allowed");o={method:_,url:S.toString(),async:typeof P!="boolean"?!0:P,user:x||null,password:O||null},v(this.OPENED)},this.setDisableHeaderCheck=function(_){a=_},this.setRequestHeader=function(_,S){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!w(_))return console.warn('Refused to set unsafe header "'+_+'"'),!1;if(m)throw new Error("INVALID_STATE_ERR: send flag is true");return l[_]=S,!0},this.getResponseHeader=function(_){return typeof _=="string"&&this.readyState>this.OPENED&&i.headers[_.toLowerCase()]&&!g?i.headers[_.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||g)return"";var _="";for(var S in i.headers)S!=="set-cookie"&&S!=="set-cookie2"&&(_+=S+": "+i.headers[S]+`\r
204
+ `);return _.substr(0,_.length-2)},this.getRequestHeader=function(_){return typeof _=="string"&&l[_]?l[_]:""},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 S=!1,P=!1,x=Xa.parse(o.url),O;switch(x.protocol){case"https:":S=!0;case"http:":O=x.hostname;break;case"file:":P=!0;break;case void 0:case"":O="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)rn.readFile(unescape(x.pathname),function(U,z){U?e.handleError(U,U.errno||-1):(e.status=200,e.responseText=z.toString("utf8"),e.response=z,v(e.DONE))});else try{this.response=rn.readFileSync(unescape(x.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,v(e.DONE)}catch(U){this.handleError(U,U.errno||-1)}return}var W=x.port||(S?443:80),J=x.pathname+(x.search?x.search:"");if(l.Host=O,S&&W===443||W===80||(l.Host+=":"+x.port),o.user){typeof o.password>"u"&&(o.password="");var Y=new Buffer(o.user+":"+o.password);l.Authorization="Basic "+Y.toString("base64")}if(o.method==="GET"||o.method==="HEAD")_=null;else if(_){l["Content-Length"]=Buffer.isBuffer(_)?_.length:Buffer.byteLength(_);var re=Object.keys(l);re.some(function(U){return U.toLowerCase()==="content-type"})||(l["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(l["Content-Length"]=0);var ae=n.agent||!1,V={host:O,port:W,path:J,method:o.method,headers:l,agent:ae};if(S&&(V.pfx=n.pfx,V.key=n.key,V.passphrase=n.passphrase,V.cert=n.cert,V.ca=n.ca,V.ciphers=n.ciphers,V.rejectUnauthorized=n.rejectUnauthorized!==!1),g=!1,o.async){var le=S?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var ue=function(U){if(i=U,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var z=Xa.parse(o.url);O=z.hostname;var se={hostname:z.hostname,port:z.port,path:z.path,method:i.statusCode===303?"GET":o.method,headers:l};S&&(se.pfx=n.pfx,se.key=n.key,se.passphrase=n.passphrase,se.cert=n.cert,se.ca=n.ca,se.ciphers=n.ciphers,se.rejectUnauthorized=n.rejectUnauthorized!==!1),s=le(se,ue).on("error",$),s.end();return}v(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(R){if(R){var B=Buffer.from(R);e.response=Buffer.concat([e.response,B])}m&&v(e.LOADING)}),i.on("end",function(){m&&(m=!1,v(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(R){e.handleError(R)})},$=function(U){if(s.reusedSocket&&U.code==="ECONNRESET")return le(V,ue).on("error",$);e.handleError(U)};s=le(V,ue).on("error",$),n.autoUnref&&s.on("socket",U=>{U.unref()}),_&&s.write(_),s.end(),e.dispatchEvent("loadstart")}else{var Q=".node-xmlhttprequest-content-"+process.pid,y=".node-xmlhttprequest-sync-"+process.pid;rn.writeFileSync(y,"","utf8");for(var b="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(S?"s":"")+".request;var options = "+JSON.stringify(V)+";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('"+Q+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+y+"');});response.on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+y+"');});}).on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+y+"');});"+(_?"req.write('"+JSON.stringify(_).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",T=Yh(process.argv[0],["-e",b]),D;rn.existsSync(y););if(e.responseText=rn.readFileSync(Q,"utf8"),T.stdin.end(),rn.unlinkSync(Q),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var q=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(q,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var I=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:I.data.headers},e.responseText=I.data.text,e.response=Buffer.from(I.data.data,"base64"),v(e.DONE,!0)}}},this.handleError=function(_,S){this.status=S||0,this.statusText=_,this.responseText=_.stack,g=!0,v(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),l=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),g=f=!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(_,S){_ in p||(p[_]=[]),p[_].push(S)},this.removeEventListener=function(_,S){_ in p&&(p[_]=p[_].filter(function(P){return P!==S}))},this.dispatchEvent=function(_){if(typeof e["on"+_]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+_]()},0):e["on"+_]()),_ in p)for(let S=0,P=p[_].length;S<P;S++)this.readyState===this.DONE?setTimeout(function(){p[_][S].call(e)},0):p[_][S].call(e)};var v=function(_){if(!(e.readyState===_||e.readyState===e.UNSENT&&f)&&(e.readyState=_,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let S;f?S="abort":g?S="error":S="load",e.dispatchEvent(S),e.dispatchEvent("loadend")}}}});var Ze,$n,Dn,Er=C(()=>{Ze=Object.create(null);Ze.open="0";Ze.close="1";Ze.ping="2";Ze.pong="3";Ze.message="4";Ze.upgrade="5";Ze.noop="6";$n=Object.create(null);Object.keys(Ze).forEach(n=>{$n[Ze[n]]=n});Dn={type:"error",data:"parser error"}});function tc(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(ec(n.data,!1));Bn(n,!0,t=>{Vs||(Vs=new TextEncoder),e(Vs.encode(t))})}var Bn,ec,Vs,nc=C(()=>{Er();Bn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+ec(e,!0).toString("base64")):r(Ze[n]+(e||"")),ec=(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 Un,rc,sc=C(()=>{Er();Un=(n,e)=>{if(typeof n!="string")return{type:"message",data:rc(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:rc(r,e)}}return $n[t]?n.length>1?{type:$n[t],data:n.substring(1)}:{type:$n[t]}:Dn},rc=(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 cc(){return new TransformStream({transform(n,e){tc(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 xr(n){return n.reduce((e,t)=>e+t.length,0)}function Tr(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 dc(n,e){Ks||(Ks=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(xr(t)<1)break;let c=Tr(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(xr(t)<2)break;let c=Tr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(xr(t)<8)break;let c=Tr(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),d=l.getUint32(0);if(d>Math.pow(2,21)-1){a.enqueue(Dn);break}s=d*Math.pow(2,32)+l.getUint32(4),r=3}else{if(xr(t)<s)break;let c=Tr(t,s);a.enqueue(Un(i?c:Ks.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(Dn);break}}}})}var ic,oc,ac,Ks,zs,sn=C(()=>{nc();sc();Er();ic="",oc=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Bn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(ic))})})},ac=(n,e)=>{let t=n.split(ic),r=[];for(let s=0;s<t.length;s++){let i=Un(t[s],e);if(r.push(i),i.type==="error")break}return r};zs=4});var Ft=ee(lc=>{lc.Emitter=Oe;function Oe(n){if(n)return Vh(n)}function Vh(n){for(var e in Oe.prototype)n[e]=Oe.prototype[e];return n}Oe.prototype.on=Oe.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Oe.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Oe.prototype.off=Oe.prototype.removeListener=Oe.prototype.removeAllListeners=Oe.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};Oe.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};Oe.prototype.emitReserved=Oe.prototype.emit;Oe.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Oe.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function fc(){return new Xs}function Kh(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(),l=a[1].trim();switch(c){case"Expires":i.expires=new Date(l);break;case"Max-Age":let d=new Date;d.setUTCSeconds(d.getUTCSeconds()+parseInt(l,10)),i.expires=d;break;default:}}return i}var gt,Pe,uc,Xs,Ht=C(()=>{gt=process.nextTick,Pe=global,uc="nodebuffer";Xs=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=Kh(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 Cr(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function mt(n,e){e.useNativeTimers?(n.setTimeoutFn=zh.bind(Pe),n.clearTimeoutFn=Xh.bind(Pe)):(n.setTimeoutFn=Pe.setTimeout.bind(Pe),n.clearTimeoutFn=Pe.clearTimeout.bind(Pe))}function hc(n){return typeof n=="string"?Zh(n):Math.ceil((n.byteLength||n.size)*Qh)}function Zh(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 Rr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var zh,Xh,Qh,qt=C(()=>{Ht();zh=Pe.setTimeout,Xh=Pe.clearTimeout;Qh=1.33});function pc(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function gc(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 Qs=C(()=>{});var yc=ee((Hv,mc)=>{var on=1e3,an=on*60,cn=an*60,Gt=cn*24,ep=Gt*7,tp=Gt*365.25;mc.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return np(n);if(t==="number"&&isFinite(n))return e.long?sp(n):rp(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function np(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*tp;case"weeks":case"week":case"w":return t*ep;case"days":case"day":case"d":return t*Gt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*cn;case"minutes":case"minute":case"mins":case"min":case"m":return t*an;case"seconds":case"second":case"secs":case"sec":case"s":return t*on;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function rp(n){var e=Math.abs(n);return e>=Gt?Math.round(n/Gt)+"d":e>=cn?Math.round(n/cn)+"h":e>=an?Math.round(n/an)+"m":e>=on?Math.round(n/on)+"s":n+"ms"}function sp(n){var e=Math.abs(n);return e>=Gt?Ar(n,e,Gt,"day"):e>=cn?Ar(n,e,cn,"hour"):e>=an?Ar(n,e,an,"minute"):e>=on?Ar(n,e,on,"second"):n+" ms"}function Ar(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Zs=ee((qv,_c)=>{function ip(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=yc(),t.destroy=l,Object.keys(n).forEach(d=>{t[d]=n[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let m=0;m<d.length;m++)u=(u<<5)-u+d.charCodeAt(m),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,m=null,g,f;function p(...w){if(!p.enabled)return;let k=p,v=Number(new Date),_=v-(u||v);k.diff=_,k.prev=u,k.curr=v,u=v,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let S=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(x,O)=>{if(x==="%%")return"%";S++;let W=t.formatters[O];if(typeof W=="function"){let J=w[S];x=W.call(k,J),w.splice(S,1),S--}return x}),t.formatArgs.call(k,w),(k.log||t.log).apply(k,w)}return p.namespace=d,p.useColors=t.useColors(),p.color=t.selectColor(d),p.extend=r,p.destroy=t.destroy,Object.defineProperty(p,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(g!==t.namespaces&&(g=t.namespaces,f=t.enabled(d)),f),set:w=>{m=w}}),typeof t.init=="function"&&t.init(p),p}function r(d,u){let m=t(this.namespace+(typeof u>"u"?":":u)+d);return m.log=this.log,m}function s(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u=(typeof d=="string"?d:"").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(d,u){let m=0,g=0,f=-1,p=0;for(;m<d.length;)if(g<u.length&&(u[g]===d[m]||u[g]==="*"))u[g]==="*"?(f=g,p=m,g++):(m++,g++);else if(f!==-1)g=f+1,p++,m=p;else return!1;for(;g<u.length&&u[g]==="*";)g++;return g===u.length}function o(){let d=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),d}function a(d){for(let u of t.skips)if(i(d,u))return!1;for(let u of t.names)if(i(d,u))return!0;return!1}function c(d){return d instanceof Error?d.stack||d.message:d}function l(){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}_c.exports=ip});var wc=ee((Le,Or)=>{Le.formatArgs=ap;Le.save=cp;Le.load=dp;Le.useColors=op;Le.storage=lp();Le.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`."))}})();Le.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 op(){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 ap(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Or.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)}Le.log=console.debug||console.log||(()=>{});function cp(n){try{n?Le.storage.setItem("debug",n):Le.storage.removeItem("debug")}catch{}}function dp(){let n;try{n=Le.storage.getItem("debug")||Le.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function lp(){try{return localStorage}catch{}}Or.exports=Zs()(Le);var{formatters:up}=Or.exports;up.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var bc=ee((ve,Ir)=>{var fp=te("tty"),Pr=te("util");ve.init=wp;ve.log=mp;ve.formatArgs=pp;ve.save=yp;ve.load=_p;ve.useColors=hp;ve.destroy=Pr.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ve.colors=[6,2,3,4,5,1];try{let n=te("supports-color");n&&(n.stderr||n).level>=2&&(ve.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{}ve.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 hp(){return"colors"in ve.inspectOpts?!!ve.inspectOpts.colors:fp.isatty(process.stderr.fd)}function pp(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(`
205
205
  `).join(`
206
- `+i),n.push(s+"m+"+Pr.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=cg()+e+" "+n[0]}function cg(){return ve.inspectOpts.hideDate?"":new Date().toISOString()+" "}function dg(...n){return process.stderr.write(Or.formatWithOptions(ve.inspectOpts,...n)+`
207
- `)}function lg(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function ug(){return process.env.DEBUG}function fg(n){n.inspectOpts={};let e=Object.keys(ve.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=ve.inspectOpts[e[t]]}Pr.exports=zs()(ve);var{formatters:pc}=Pr.exports;pc.o=function(n){return this.inspectOpts.colors=this.useColors,Or.inspect(n,this.inspectOpts).split(`
208
- `).map(e=>e.trim()).join(" ")};pc.O=function(n){return this.inspectOpts.colors=this.useColors,Or.inspect(n,this.inspectOpts)}});var Ye=ee((Lv,Ks)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ks.exports=gc():Ks.exports=mc()});var yc,_c,hg,Ir,yt,Fn=C(()=>{sn();yc=oe(Ft(),1);qt();Vs();_c=oe(Ye(),1),hg=(0,_c.default)("engine.io-client:transport"),Ir=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},yt=class extends yc.Emitter{constructor(e){super(),this.writable=!1,mt(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 Ir(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):hg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Un(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=dc(e);return t.length?"?"+t:""}}});var wc,et,Hn,Xs=C(()=>{Fn();qt();sn();wc=oe(Ye(),1),et=(0,wc.default)("engine.io-client:polling"),Hn=class extends yt{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{et("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(et("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){et("pre-pause polling complete"),--r||t()})),this.writable||(et("we are currently writing - waiting to pause"),r++,this.once("drain",function(){et("pre-pause writing complete"),--r||t()}))}else t()}_poll(){et("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){et("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)};nc(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():et('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{et("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(et("transport open - closing"),e()):(et("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,tc(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]=Cr()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var vc,bc,kc=C(()=>{vc=!1;try{vc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}bc=vc});function gg(){}function Sc(){for(let n in _t.requests)_t.requests.hasOwnProperty(n)&&_t.requests[n].abort()}function pg(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||bc))return new XMLHttpRequest}catch{}if(!e)try{return new Pe[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ec,xc,Qs,Nr,_t,zv,Zs=C(()=>{Xs();Ec=oe(Ft(),1);qt();Ht();kc();xc=oe(Ye(),1),Qs=(0,xc.default)("engine.io-client:polling");Nr=class extends Hn{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(){Qs("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}},_t=class n extends Ec.Emitter{constructor(e,t,r){super(),this.createRequest=e,mt(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=Tr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{Qs("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))},Qs("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=gg,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()}};_t.requestsCount=0;_t.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Sc);else if(typeof addEventListener=="function"){let n="onpagehide"in Pe?"pagehide":"unload";addEventListener(n,Sc,!1)}}zv=(function(){let n=pg({xdomain:!1});return n&&n.responseType!==null})()});var ei,mg,dn,ti=C(()=>{ei=oe(Va(),1);Zs();mg=ei.default||ei,dn=class extends Nr{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 _t(r=>new mg(r),this.uri(),e)}}});var wt=ee((Zv,Rc)=>{"use strict";var Tc=["nodebuffer","arraybuffer","fragments"],Cc=typeof Blob<"u";Cc&&Tc.push("blob");Rc.exports={BINARY_TYPES:Tc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Cc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qn=ee((eb,Mr)=>{"use strict";var{EMPTY_BUFFER:yg}=wt(),ni=Buffer[Symbol.species];function _g(n,e){if(n.length===0)return yg;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 ni(t.buffer,t.byteOffset,r):t}function Ac(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Oc(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function wg(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function ri(n){if(ri.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new ni(n):ArrayBuffer.isView(n)?e=new ni(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),ri.readOnly=!1),e}Mr.exports={concat:_g,mask:Ac,toArrayBuffer:wg,toBuffer:ri,unmask:Oc};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=te("bufferutil");Mr.exports.mask=function(e,t,r,s,i){i<48?Ac(e,t,r,s,i):n.mask(e,t,r,s,i)},Mr.exports.unmask=function(e,t){e.length<32?Oc(e,t):n.unmask(e,t)}}catch{}});var Nc=ee((tb,Ic)=>{"use strict";var Pc=Symbol("kDone"),si=Symbol("kRun"),ii=class{constructor(e){this[Pc]=()=>{this.pending--,this[si]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[si]()}[si](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Pc])}}};Ic.exports=ii});var fn=ee((nb,Dc)=>{"use strict";var Gn=te("zlib"),Mc=qn(),vg=Nc(),{kStatusCode:Lc}=wt(),bg=Buffer[Symbol.species],kg=Buffer.from([0,0,255,255]),$r=Symbol("permessage-deflate"),vt=Symbol("total-length"),ln=Symbol("callback"),Pt=Symbol("buffers"),un=Symbol("error"),Lr,oi=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,!Lr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Lr=new vg(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[ln];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){Lr.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Lr.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"?Gn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Gn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[$r]=this,this._inflate[vt]=0,this._inflate[Pt]=[],this._inflate.on("error",Eg),this._inflate.on("data",$c)}this._inflate[ln]=r,this._inflate.write(e),t&&this._inflate.write(kg),this._inflate.flush(()=>{let i=this._inflate[un];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Mc.concat(this._inflate[Pt],this._inflate[vt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[vt]=0,this._inflate[Pt]=[],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"?Gn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Gn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[vt]=0,this._deflate[Pt]=[],this._deflate.on("data",Sg)}this._deflate[ln]=r,this._deflate.write(e),this._deflate.flush(Gn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Mc.concat(this._deflate[Pt],this._deflate[vt]);t&&(i=new bg(i.buffer,i.byteOffset,i.length-4)),this._deflate[ln]=null,this._deflate[vt]=0,this._deflate[Pt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Dc.exports=oi;function Sg(n){this[Pt].push(n),this[vt]+=n.length}function $c(n){if(this[vt]+=n.length,this[$r]._maxPayload<1||this[vt]<=this[$r]._maxPayload){this[Pt].push(n);return}this[un]=new RangeError("Max payload size exceeded"),this[un].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[un][Lc]=1009,this.removeListener("data",$c),this.reset()}function Eg(n){if(this[$r]._inflate=null,this[un]){this[ln](this[un]);return}n[Lc]=1007,this[ln](n)}});var hn=ee((rb,Dr)=>{"use strict";var{isUtf8:Bc}=te("buffer"),{hasBlob:xg}=wt(),Tg=[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 Cg(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function ai(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 Rg(n){return xg&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Dr.exports={isBlob:Rg,isValidStatusCode:Cg,isValidUTF8:ai,tokenChars:Tg};if(Bc)Dr.exports.isValidUTF8=function(n){return n.length<24?ai(n):Bc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=te("utf-8-validate");Dr.exports.isValidUTF8=function(e){return e.length<32?ai(e):n(e)}}catch{}});var fi=ee((sb,jc)=>{"use strict";var{Writable:Ag}=te("stream"),Uc=fn(),{BINARY_TYPES:Og,EMPTY_BUFFER:Fc,kStatusCode:Pg,kWebSocket:Ig}=wt(),{concat:ci,toArrayBuffer:Ng,unmask:Mg}=qn(),{isValidStatusCode:Lg,isValidUTF8:Hc}=hn(),Br=Buffer[Symbol.species],Ve=0,qc=1,Gc=2,Wc=3,di=4,li=5,Ur=6,ui=class extends Ag{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Og[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ig]=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=Ve}_write(e,t,r){if(this._opcode===8&&this._state==Ve)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 Br(r.buffer,r.byteOffset+e,r.length-e),new Br(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 Br(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 Ve:this.getInfo(e);break;case qc:this.getPayloadLength16(e);break;case Gc:this.getPayloadLength64(e);break;case Wc:this.getMask();break;case di:this.getData(e);break;case li:case Ur: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[Uc.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=qc:this._payloadLength===127?this._state=Gc: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=Wc:this._state=di}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=di}getData(e){let t=Fc;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&&Mg(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=li,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Uc.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===Ve&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ve;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=ci(r,t):this._binaryType==="arraybuffer"?s=Ng(ci(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ve):(this._state=Ur,setImmediate(()=>{this.emit("message",s,!0),this._state=Ve,this.startLoop(e)}))}else{let s=ci(r,t);if(!this._skipUTF8Validation&&!Hc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===li||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ve):(this._state=Ur,setImmediate(()=>{this.emit("message",s,!1),this._state=Ve,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Fc),this.end();else{let r=e.readUInt16BE(0);if(!Lg(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Br(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Hc(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=Ve;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ve):(this._state=Ur,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ve,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}};jc.exports=ui});var pi=ee((ob,Vc)=>{"use strict";var{Duplex:ib}=te("stream"),{randomFillSync:$g}=te("crypto"),{types:{isUint8Array:Dg}}=te("util"),Jc=fn(),{EMPTY_BUFFER:Bg,kWebSocket:Ug,NOOP:Fg}=wt(),{isBlob:gn,isValidStatusCode:Hg}=hn(),{mask:Yc,toBuffer:Wt}=qn(),ze=Symbol("kByteLength"),qg=Buffer.alloc(4),Fr=8*1024,jt,pn=Fr,tt=0,Gg=1,Wg=2,hi=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=tt,this.onerror=Fg,this[Ug]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||qg,t.generateMask?t.generateMask(r):(pn===Fr&&(jt===void 0&&(jt=Buffer.alloc(Fr)),$g(jt,0,Fr),pn=0),r[0]=jt[pn++],r[1]=jt[pn++],r[2]=jt[pn++],r[3]=jt[pn++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[ze]!==void 0?a=t[ze]:(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 l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],o?[l,e]:s?(Yc(e,r,l,i,a),[l]):(Yc(e,r,e,0,a),[l,e])):[l,e]}close(e,t,r,s){let i;if(e===void 0)i=Bg;else{if(typeof e!="number"||!Hg(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(Dg(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[ze]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==tt?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):gn(e)?(s=e.size,i=!1):(e=Wt(e),s=e.length,i=Wt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ze]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};gn(e)?this._state!==tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==tt?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):gn(e)?(s=e.size,i=!1):(e=Wt(e),s=e.length,i=Wt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ze]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};gn(e)?this._state!==tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==tt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Jc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):gn(e)?(a=e.size,c=!1):(e=Wt(e),a=e.length,c=Wt.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 l={[ze]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};gn(e)?this._state!==tt?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==tt?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[ze],this._state=Wg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(gi,this,a,s);return}this._bufferedBytes-=r[ze];let o=Wt(i);t?this.dispatch(o,t,r,s):(this._state=tt,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(jg,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Jc.extensionName];this._bufferedBytes+=r[ze],this._state=Gg,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");gi(this,c,s);return}this._bufferedBytes-=r[ze],this._state=tt,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ze],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ze],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)}};Vc.exports=hi;function gi(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 jg(n,e,t){gi(n,e,t),n.onerror(e)}});var rd=ee((ab,nd)=>{"use strict";var{kForOnEventAttribute:Wn,kListener:mi}=wt(),zc=Symbol("kCode"),Kc=Symbol("kData"),Xc=Symbol("kError"),Qc=Symbol("kMessage"),Zc=Symbol("kReason"),mn=Symbol("kTarget"),ed=Symbol("kType"),td=Symbol("kWasClean"),bt=class{constructor(e){this[mn]=null,this[ed]=e}get target(){return this[mn]}get type(){return this[ed]}};Object.defineProperty(bt.prototype,"target",{enumerable:!0});Object.defineProperty(bt.prototype,"type",{enumerable:!0});var Jt=class extends bt{constructor(e,t={}){super(e),this[zc]=t.code===void 0?0:t.code,this[Zc]=t.reason===void 0?"":t.reason,this[td]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[zc]}get reason(){return this[Zc]}get wasClean(){return this[td]}};Object.defineProperty(Jt.prototype,"code",{enumerable:!0});Object.defineProperty(Jt.prototype,"reason",{enumerable:!0});Object.defineProperty(Jt.prototype,"wasClean",{enumerable:!0});var yn=class extends bt{constructor(e,t={}){super(e),this[Xc]=t.error===void 0?null:t.error,this[Qc]=t.message===void 0?"":t.message}get error(){return this[Xc]}get message(){return this[Qc]}};Object.defineProperty(yn.prototype,"error",{enumerable:!0});Object.defineProperty(yn.prototype,"message",{enumerable:!0});var jn=class extends bt{constructor(e,t={}){super(e),this[Kc]=t.data===void 0?null:t.data}get data(){return this[Kc]}};Object.defineProperty(jn.prototype,"data",{enumerable:!0});var Jg={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Wn]&&s[mi]===e&&!s[Wn])return;let r;if(n==="message")r=function(i,o){let a=new jn("message",{data:o?i:i.toString()});a[mn]=this,Hr(e,this,a)};else if(n==="close")r=function(i,o){let a=new Jt("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[mn]=this,Hr(e,this,a)};else if(n==="error")r=function(i){let o=new yn("error",{error:i,message:i.message});o[mn]=this,Hr(e,this,o)};else if(n==="open")r=function(){let i=new bt("open");i[mn]=this,Hr(e,this,i)};else return;r[Wn]=!!t[Wn],r[mi]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[mi]===e&&!t[Wn]){this.removeListener(n,t);break}}};nd.exports={CloseEvent:Jt,ErrorEvent:yn,Event:bt,EventTarget:Jg,MessageEvent:jn};function Hr(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var qr=ee((cb,sd)=>{"use strict";var{tokenChars:Jn}=hn();function ct(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Yg(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,u=0;for(;u<n.length;u++)if(l=n.charCodeAt(u),o===void 0)if(d===-1&&Jn[l]===1)c===-1&&(c=u);else if(u!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(c,d);l===44?(ct(e,p,t),t=Object.create(null)):o=p,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&Jn[l]===1)c===-1&&(c=u);else if(l===32||l===9)d===-1&&c!==-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),ct(t,n.slice(c,d),!0),l===44&&(ct(e,o,t),t=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=n.slice(c,u),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Jn[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(Jn[l]===1)c===-1&&(c=u);else if(l===34&&c!==-1)i=!1,d=u;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===34&&n.charCodeAt(u-1)===61)i=!0;else if(d===-1&&Jn[l]===1)c===-1&&(c=u);else if(c!==-1&&(l===32||l===9))d===-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(c,d);r&&(p=p.replace(/\\/g,""),r=!1),ct(t,a,p),l===44&&(ct(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let m=n.slice(c,d);return o===void 0?ct(e,m,t):(a===void 0?ct(t,m,!0):r?ct(t,a,m.replace(/\\/g,"")):ct(t,a,m),ct(e,o,t)),e}function Vg(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(", ")}sd.exports={format:Vg,parse:Yg}});var Jr=ee((ub,md)=>{"use strict";var zg=te("events"),Kg=te("https"),Xg=te("http"),ad=te("net"),Qg=te("tls"),{randomBytes:Zg,createHash:ep}=te("crypto"),{Duplex:db,Readable:lb}=te("stream"),{URL:yi}=te("url"),It=fn(),tp=fi(),np=pi(),{isBlob:rp}=hn(),{BINARY_TYPES:id,CLOSE_TIMEOUT:sp,EMPTY_BUFFER:Gr,GUID:ip,kForOnEventAttribute:_i,kListener:op,kStatusCode:ap,kWebSocket:be,NOOP:cd}=wt(),{EventTarget:{addEventListener:cp,removeEventListener:dp}}=rd(),{format:lp,parse:up}=qr(),{toBuffer:fp}=qn(),dd=Symbol("kAborted"),wi=[8,13],kt=["CONNECTING","OPEN","CLOSING","CLOSED"],hp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,fe=class n extends zg{constructor(e,t,r){super(),this._binaryType=id[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Gr,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]),ld(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){id.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 tp({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new np(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[be]=this,i[be]=this,e[be]=this,s.on("conclude",mp),s.on("drain",yp),s.on("error",_p),s.on("message",wp),s.on("ping",vp),s.on("pong",bp),i.onerror=kp,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",hd),e.on("data",jr),e.on("end",gd),e.on("error",pd),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[It.extensionName]&&this._extensions[It.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){qe(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())}),fd(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){vi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Gr,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){vi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Gr,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){vi(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[It.extensionName]||(s.compress=!1),this._sender.send(e||Gr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){qe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(fe,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(fe.prototype,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(fe,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(fe.prototype,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(fe,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(fe.prototype,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(fe,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});Object.defineProperty(fe.prototype,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(fe.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(fe.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[_i])return e[op];return null},set(e){for(let t of this.listeners(n))if(t[_i]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[_i]:!0})}})});fe.prototype.addEventListener=cp;fe.prototype.removeEventListener=dp;md.exports=fe;function ld(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:sp,protocolVersion:wi[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,!wi.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${wi.join(", ")})`);let i;if(e instanceof yi)i=e;else try{i=new yi(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;Wr(n,g);return}let l=o?443:80,d=Zg(16).toString("base64"),u=o?Kg.request:Xg.request,m=new Set,p;if(s.createConnection=s.createConnection||(o?pp:gp),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new It({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=lp({[It.extensionName]:p.offer()})),t.length){for(let g of t){if(typeof g!="string"||!hp.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 f;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[_,S]of Object.entries(g))r.headers[_.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")),f=n._req=u(s),n._redirects&&n.emit("redirect",n.url,f)}else f=n._req=u(s);s.timeout&&f.on("timeout",()=>{qe(n,f,"Opening handshake has timed out")}),f.on("error",g=>{f===null||f[dd]||(f=n._req=null,Wr(n,g))}),f.on("response",g=>{let _=g.headers.location,S=g.statusCode;if(_&&s.followRedirects&&S>=300&&S<400){if(++n._redirects>s.maxRedirects){qe(n,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new yi(_,e)}catch{let k=new SyntaxError(`Invalid URL: ${_}`);Wr(n,k);return}ld(n,v,t,r)}else n.emit("unexpected-response",f,g)||qe(n,f,`Unexpected server response: ${g.statusCode}`)}),f.on("upgrade",(g,_,S)=>{if(n.emit("upgrade",g),n.readyState!==fe.CONNECTING)return;f=n._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){qe(n,_,"Invalid Upgrade header");return}let y=ep("sha1").update(d+ip).digest("base64");if(g.headers["sec-websocket-accept"]!==y){qe(n,_,"Invalid Sec-WebSocket-Accept header");return}let k=g.headers["sec-websocket-protocol"],P;if(k!==void 0?m.size?m.has(k)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":m.size&&(P="Server sent no subprotocol"),P){qe(n,_,P);return}k&&(n._protocol=k);let x=g.headers["sec-websocket-extensions"];if(x!==void 0){if(!p){qe(n,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=up(x)}catch{qe(n,_,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(O);if(W.length!==1||W[0]!==It.extensionName){qe(n,_,"Server indicated an extension that was not requested");return}try{p.accept(O[It.extensionName])}catch{qe(n,_,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[It.extensionName]=p}n.setSocket(_,S,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(f,n):f.end()}function Wr(n,e){n._readyState=fe.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function gp(n){return n.path=n.socketPath,ad.connect(n)}function pp(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=ad.isIP(n.host)?"":n.host),Qg.connect(n)}function qe(n,e,t){n._readyState=fe.CLOSING;let r=new Error(t);Error.captureStackTrace(r,qe),e.setHeader?(e[dd]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Wr,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function vi(n,e,t){if(e){let r=rp(e)?e.size:fp(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${kt[n.readyState]})`);process.nextTick(t,r)}}function mp(n,e){let t=this[be];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[be]!==void 0&&(t._socket.removeListener("data",jr),process.nextTick(ud,t._socket),n===1005?t.close():t.close(n,e))}function yp(){let n=this[be];n.isPaused||n._socket.resume()}function _p(n){let e=this[be];e._socket[be]!==void 0&&(e._socket.removeListener("data",jr),process.nextTick(ud,e._socket),e.close(n[ap])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function od(){this[be].emitClose()}function wp(n,e){this[be].emit("message",n,e)}function vp(n){let e=this[be];e._autoPong&&e.pong(n,!this._isServer,cd),e.emit("ping",n)}function bp(n){this[be].emit("pong",n)}function ud(n){n.resume()}function kp(n){let e=this[be];e.readyState!==fe.CLOSED&&(e.readyState===fe.OPEN&&(e._readyState=fe.CLOSING,fd(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function fd(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function hd(){let n=this[be];if(this.removeListener("close",hd),this.removeListener("data",jr),this.removeListener("end",gd),n._readyState=fe.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[be]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",od),n._receiver.on("finish",od))}function jr(n){this[be]._receiver.write(n)||this.pause()}function gd(){let n=this[be];n._readyState=fe.CLOSING,n._receiver.end(),this.end()}function pd(){let n=this[be];this.removeListener("error",pd),this.on("error",cd),n&&(n._readyState=fe.CLOSING,this.destroy())}});var vd=ee((hb,wd)=>{"use strict";var fb=Jr(),{Duplex:Sp}=te("stream");function yd(n){n.emit("close")}function Ep(){!this.destroyed&&this._writableState.finished&&this.destroy()}function _d(n){this.removeListener("error",_d),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function xp(n,e){let t=!0,r=new Sp({...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(yd,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(yd,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",Ep),r.on("error",_d),r}wd.exports=xp});var bi=ee((gb,bd)=>{"use strict";var{tokenChars:Tp}=hn();function Cp(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&&Tp[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}bd.exports={parse:Cp}});var Rd=ee((mb,Cd)=>{"use strict";var Rp=te("events"),Yr=te("http"),{Duplex:pb}=te("stream"),{createHash:Ap}=te("crypto"),kd=qr(),Yt=fn(),Op=bi(),Pp=Jr(),{CLOSE_TIMEOUT:Ip,GUID:Np,kWebSocket:Mp}=wt(),Lp=/^[+/0-9A-Za-z]{22}==$/,Sd=0,Ed=1,Td=2,ki=class extends Rp{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Ip,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=Yr.createServer((r,s)=>{let i=Yr.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=$p(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=Sd}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===Td){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Yn,this);return}if(e&&this.once("close",e),this._state!==Ed)if(this._state=Ed,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(Yn,this):process.nextTick(Yn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Yn(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",xd);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Vt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Vt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Lp.test(i)){Vt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Vt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Vn(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Op.parse(c)}catch{Vt(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let m=new Yt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=kd.parse(d);p[Yt.extensionName]&&(m.accept(p[Yt.extensionName]),u[Yt.extensionName]=m)}catch{Vt(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,(p,f,g,_)=>{if(!p)return Vn(t,f||401,g,_);this.completeUpgrade(u,i,l,e,t,r,s)});return}if(!this.options.verifyClient(m))return Vn(t,401)}this.completeUpgrade(u,i,l,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Mp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Sd)return Vn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ap("sha1").update(t+Np).digest("base64")}`],d=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&&(l.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Yt.extensionName]){let u=e[Yt.extensionName].params,m=kd.format({[Yt.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
206
+ `+i),n.push(s+"m+"+Ir.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=gp()+e+" "+n[0]}function gp(){return ve.inspectOpts.hideDate?"":new Date().toISOString()+" "}function mp(...n){return process.stderr.write(Pr.formatWithOptions(ve.inspectOpts,...n)+`
207
+ `)}function yp(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function _p(){return process.env.DEBUG}function wp(n){n.inspectOpts={};let e=Object.keys(ve.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=ve.inspectOpts[e[t]]}Ir.exports=Zs()(ve);var{formatters:vc}=Ir.exports;vc.o=function(n){return this.inspectOpts.colors=this.useColors,Pr.inspect(n,this.inspectOpts).split(`
208
+ `).map(e=>e.trim()).join(" ")};vc.O=function(n){return this.inspectOpts.colors=this.useColors,Pr.inspect(n,this.inspectOpts)}});var Ye=ee((Gv,ei)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?ei.exports=wc():ei.exports=bc()});var kc,Sc,vp,Nr,yt,Fn=C(()=>{sn();kc=oe(Ft(),1);qt();Qs();Sc=oe(Ye(),1),vp=(0,Sc.default)("engine.io-client:transport"),Nr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},yt=class extends kc.Emitter{constructor(e){super(),this.writable=!1,mt(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 Nr(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):vp("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Un(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=pc(e);return t.length?"?"+t:""}}});var Ec,et,Hn,ti=C(()=>{Fn();qt();sn();Ec=oe(Ye(),1),et=(0,Ec.default)("engine.io-client:polling"),Hn=class extends yt{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{et("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(et("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){et("pre-pause polling complete"),--r||t()})),this.writable||(et("we are currently writing - waiting to pause"),r++,this.once("drain",function(){et("pre-pause writing complete"),--r||t()}))}else t()}_poll(){et("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){et("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)};ac(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():et('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{et("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(et("transport open - closing"),e()):(et("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,oc(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]=Rr()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var xc,Tc,Cc=C(()=>{xc=!1;try{xc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Tc=xc});function bp(){}function Rc(){for(let n in _t.requests)_t.requests.hasOwnProperty(n)&&_t.requests[n].abort()}function kp(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Tc))return new XMLHttpRequest}catch{}if(!e)try{return new Pe[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ac,Oc,ni,Mr,_t,rb,ri=C(()=>{ti();Ac=oe(Ft(),1);qt();Ht();Cc();Oc=oe(Ye(),1),ni=(0,Oc.default)("engine.io-client:polling");Mr=class extends Hn{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(){ni("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}},_t=class n extends Ac.Emitter{constructor(e,t,r){super(),this.createRequest=e,mt(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=Cr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{ni("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))},ni("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=bp,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()}};_t.requestsCount=0;_t.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Rc);else if(typeof addEventListener=="function"){let n="onpagehide"in Pe?"pagehide":"unload";addEventListener(n,Rc,!1)}}rb=(function(){let n=kp({xdomain:!1});return n&&n.responseType!==null})()});var si,Sp,dn,ii=C(()=>{si=oe(Za(),1);ri();Sp=si.default||si,dn=class extends Mr{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 _t(r=>new Sp(r),this.uri(),e)}}});var wt=ee((ab,Nc)=>{"use strict";var Pc=["nodebuffer","arraybuffer","fragments"],Ic=typeof Blob<"u";Ic&&Pc.push("blob");Nc.exports={BINARY_TYPES:Pc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ic,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var qn=ee((cb,Lr)=>{"use strict";var{EMPTY_BUFFER:Ep}=wt(),oi=Buffer[Symbol.species];function xp(n,e){if(n.length===0)return Ep;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 oi(t.buffer,t.byteOffset,r):t}function Mc(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Lc(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Tp(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function ai(n){if(ai.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new oi(n):ArrayBuffer.isView(n)?e=new oi(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),ai.readOnly=!1),e}Lr.exports={concat:xp,mask:Mc,toArrayBuffer:Tp,toBuffer:ai,unmask:Lc};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=te("bufferutil");Lr.exports.mask=function(e,t,r,s,i){i<48?Mc(e,t,r,s,i):n.mask(e,t,r,s,i)},Lr.exports.unmask=function(e,t){e.length<32?Lc(e,t):n.unmask(e,t)}}catch{}});var Bc=ee((db,Dc)=>{"use strict";var $c=Symbol("kDone"),ci=Symbol("kRun"),di=class{constructor(e){this[$c]=()=>{this.pending--,this[ci]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ci]()}[ci](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[$c])}}};Dc.exports=di});var fn=ee((lb,qc)=>{"use strict";var Gn=te("zlib"),Uc=qn(),Cp=Bc(),{kStatusCode:Fc}=wt(),Rp=Buffer[Symbol.species],Ap=Buffer.from([0,0,255,255]),Dr=Symbol("permessage-deflate"),vt=Symbol("total-length"),ln=Symbol("callback"),Pt=Symbol("buffers"),un=Symbol("error"),$r,li=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,!$r){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;$r=new Cp(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[ln];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){$r.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){$r.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"?Gn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Gn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Dr]=this,this._inflate[vt]=0,this._inflate[Pt]=[],this._inflate.on("error",Pp),this._inflate.on("data",Hc)}this._inflate[ln]=r,this._inflate.write(e),t&&this._inflate.write(Ap),this._inflate.flush(()=>{let i=this._inflate[un];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Uc.concat(this._inflate[Pt],this._inflate[vt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[vt]=0,this._inflate[Pt]=[],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"?Gn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Gn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[vt]=0,this._deflate[Pt]=[],this._deflate.on("data",Op)}this._deflate[ln]=r,this._deflate.write(e),this._deflate.flush(Gn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Uc.concat(this._deflate[Pt],this._deflate[vt]);t&&(i=new Rp(i.buffer,i.byteOffset,i.length-4)),this._deflate[ln]=null,this._deflate[vt]=0,this._deflate[Pt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};qc.exports=li;function Op(n){this[Pt].push(n),this[vt]+=n.length}function Hc(n){if(this[vt]+=n.length,this[Dr]._maxPayload<1||this[vt]<=this[Dr]._maxPayload){this[Pt].push(n);return}this[un]=new RangeError("Max payload size exceeded"),this[un].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[un][Fc]=1009,this.removeListener("data",Hc),this.reset()}function Pp(n){if(this[Dr]._inflate=null,this[un]){this[ln](this[un]);return}n[Fc]=1007,this[ln](n)}});var hn=ee((ub,Br)=>{"use strict";var{isUtf8:Gc}=te("buffer"),{hasBlob:Ip}=wt(),Np=[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 Mp(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function ui(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 Lp(n){return Ip&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Br.exports={isBlob:Lp,isValidStatusCode:Mp,isValidUTF8:ui,tokenChars:Np};if(Gc)Br.exports.isValidUTF8=function(n){return n.length<24?ui(n):Gc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=te("utf-8-validate");Br.exports.isValidUTF8=function(e){return e.length<32?ui(e):n(e)}}catch{}});var mi=ee((fb,zc)=>{"use strict";var{Writable:$p}=te("stream"),Wc=fn(),{BINARY_TYPES:Dp,EMPTY_BUFFER:jc,kStatusCode:Bp,kWebSocket:Up}=wt(),{concat:fi,toArrayBuffer:Fp,unmask:Hp}=qn(),{isValidStatusCode:qp,isValidUTF8:Jc}=hn(),Ur=Buffer[Symbol.species],Ve=0,Yc=1,Vc=2,Kc=3,hi=4,pi=5,Fr=6,gi=class extends $p{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Dp[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Up]=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=Ve}_write(e,t,r){if(this._opcode===8&&this._state==Ve)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 Ur(r.buffer,r.byteOffset+e,r.length-e),new Ur(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 Ur(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 Ve:this.getInfo(e);break;case Yc:this.getPayloadLength16(e);break;case Vc:this.getPayloadLength64(e);break;case Kc:this.getMask();break;case hi:this.getData(e);break;case pi:case Fr: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[Wc.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=Yc:this._payloadLength===127?this._state=Vc: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=Kc:this._state=hi}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=hi}getData(e){let t=jc;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&&Hp(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=pi,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Wc.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===Ve&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ve;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=fi(r,t):this._binaryType==="arraybuffer"?s=Fp(fi(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ve):(this._state=Fr,setImmediate(()=>{this.emit("message",s,!0),this._state=Ve,this.startLoop(e)}))}else{let s=fi(r,t);if(!this._skipUTF8Validation&&!Jc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===pi||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ve):(this._state=Fr,setImmediate(()=>{this.emit("message",s,!1),this._state=Ve,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,jc),this.end();else{let r=e.readUInt16BE(0);if(!qp(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ur(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Jc(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=Ve;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ve):(this._state=Fr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ve,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[Bp]=s,o}};zc.exports=gi});var wi=ee((pb,Zc)=>{"use strict";var{Duplex:hb}=te("stream"),{randomFillSync:Gp}=te("crypto"),{types:{isUint8Array:Wp}}=te("util"),Xc=fn(),{EMPTY_BUFFER:jp,kWebSocket:Jp,NOOP:Yp}=wt(),{isBlob:pn,isValidStatusCode:Vp}=hn(),{mask:Qc,toBuffer:Wt}=qn(),Ke=Symbol("kByteLength"),Kp=Buffer.alloc(4),Hr=8*1024,jt,gn=Hr,tt=0,zp=1,Xp=2,yi=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=tt,this.onerror=Yp,this[Jp]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Kp,t.generateMask?t.generateMask(r):(gn===Hr&&(jt===void 0&&(jt=Buffer.alloc(Hr)),Gp(jt,0,Hr),gn=0),r[0]=jt[gn++],r[1]=jt[gn++],r[2]=jt[gn++],r[3]=jt[gn++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Ke]!==void 0?a=t[Ke]:(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 l=Buffer.allocUnsafe(s?a+i:i);return l[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),t.mask?(l[1]|=128,l[i-4]=r[0],l[i-3]=r[1],l[i-2]=r[2],l[i-1]=r[3],o?[l,e]:s?(Qc(e,r,l,i,a),[l]):(Qc(e,r,e,0,a),[l,e])):[l,e]}close(e,t,r,s){let i;if(e===void 0)i=jp;else{if(typeof e!="number"||!Vp(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(Wp(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Ke]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==tt?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):pn(e)?(s=e.size,i=!1):(e=Wt(e),s=e.length,i=Wt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ke]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};pn(e)?this._state!==tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==tt?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):pn(e)?(s=e.size,i=!1):(e=Wt(e),s=e.length,i=Wt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ke]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};pn(e)?this._state!==tt?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==tt?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Xc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):pn(e)?(a=e.size,c=!1):(e=Wt(e),a=e.length,c=Wt.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 l={[Ke]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};pn(e)?this._state!==tt?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==tt?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[Ke],this._state=Xp,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(_i,this,a,s);return}this._bufferedBytes-=r[Ke];let o=Wt(i);t?this.dispatch(o,t,r,s):(this._state=tt,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Qp,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Xc.extensionName];this._bufferedBytes+=r[Ke],this._state=zp,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");_i(this,c,s);return}this._bufferedBytes-=r[Ke],this._state=tt,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===tt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ke],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ke],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)}};Zc.exports=yi;function _i(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 Qp(n,e,t){_i(n,e,t),n.onerror(e)}});var cd=ee((gb,ad)=>{"use strict";var{kForOnEventAttribute:Wn,kListener:vi}=wt(),ed=Symbol("kCode"),td=Symbol("kData"),nd=Symbol("kError"),rd=Symbol("kMessage"),sd=Symbol("kReason"),mn=Symbol("kTarget"),id=Symbol("kType"),od=Symbol("kWasClean"),bt=class{constructor(e){this[mn]=null,this[id]=e}get target(){return this[mn]}get type(){return this[id]}};Object.defineProperty(bt.prototype,"target",{enumerable:!0});Object.defineProperty(bt.prototype,"type",{enumerable:!0});var Jt=class extends bt{constructor(e,t={}){super(e),this[ed]=t.code===void 0?0:t.code,this[sd]=t.reason===void 0?"":t.reason,this[od]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[ed]}get reason(){return this[sd]}get wasClean(){return this[od]}};Object.defineProperty(Jt.prototype,"code",{enumerable:!0});Object.defineProperty(Jt.prototype,"reason",{enumerable:!0});Object.defineProperty(Jt.prototype,"wasClean",{enumerable:!0});var yn=class extends bt{constructor(e,t={}){super(e),this[nd]=t.error===void 0?null:t.error,this[rd]=t.message===void 0?"":t.message}get error(){return this[nd]}get message(){return this[rd]}};Object.defineProperty(yn.prototype,"error",{enumerable:!0});Object.defineProperty(yn.prototype,"message",{enumerable:!0});var jn=class extends bt{constructor(e,t={}){super(e),this[td]=t.data===void 0?null:t.data}get data(){return this[td]}};Object.defineProperty(jn.prototype,"data",{enumerable:!0});var Zp={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Wn]&&s[vi]===e&&!s[Wn])return;let r;if(n==="message")r=function(i,o){let a=new jn("message",{data:o?i:i.toString()});a[mn]=this,qr(e,this,a)};else if(n==="close")r=function(i,o){let a=new Jt("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[mn]=this,qr(e,this,a)};else if(n==="error")r=function(i){let o=new yn("error",{error:i,message:i.message});o[mn]=this,qr(e,this,o)};else if(n==="open")r=function(){let i=new bt("open");i[mn]=this,qr(e,this,i)};else return;r[Wn]=!!t[Wn],r[vi]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[vi]===e&&!t[Wn]){this.removeListener(n,t);break}}};ad.exports={CloseEvent:Jt,ErrorEvent:yn,Event:bt,EventTarget:Zp,MessageEvent:jn};function qr(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Gr=ee((mb,dd)=>{"use strict";var{tokenChars:Jn}=hn();function ct(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function eg(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,u=0;for(;u<n.length;u++)if(l=n.charCodeAt(u),o===void 0)if(d===-1&&Jn[l]===1)c===-1&&(c=u);else if(u!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=n.slice(c,d);l===44?(ct(e,g,t),t=Object.create(null)):o=g,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&Jn[l]===1)c===-1&&(c=u);else if(l===32||l===9)d===-1&&c!==-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),ct(t,n.slice(c,d),!0),l===44&&(ct(e,o,t),t=Object.create(null),o=void 0),c=d=-1}else if(l===61&&c!==-1&&d===-1)a=n.slice(c,u),c=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if(Jn[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(Jn[l]===1)c===-1&&(c=u);else if(l===34&&c!==-1)i=!1,d=u;else if(l===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(l===34&&n.charCodeAt(u-1)===61)i=!0;else if(d===-1&&Jn[l]===1)c===-1&&(c=u);else if(c!==-1&&(l===32||l===9))d===-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let g=n.slice(c,d);r&&(g=g.replace(/\\/g,""),r=!1),ct(t,a,g),l===44&&(ct(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||l===32||l===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let m=n.slice(c,d);return o===void 0?ct(e,m,t):(a===void 0?ct(t,m,!0):r?ct(t,a,m.replace(/\\/g,"")):ct(t,a,m),ct(e,o,t)),e}function tg(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(", ")}dd.exports={format:tg,parse:eg}});var Yr=ee((wb,bd)=>{"use strict";var ng=te("events"),rg=te("https"),sg=te("http"),fd=te("net"),ig=te("tls"),{randomBytes:og,createHash:ag}=te("crypto"),{Duplex:yb,Readable:_b}=te("stream"),{URL:bi}=te("url"),It=fn(),cg=mi(),dg=wi(),{isBlob:lg}=hn(),{BINARY_TYPES:ld,CLOSE_TIMEOUT:ug,EMPTY_BUFFER:Wr,GUID:fg,kForOnEventAttribute:ki,kListener:hg,kStatusCode:pg,kWebSocket:be,NOOP:hd}=wt(),{EventTarget:{addEventListener:gg,removeEventListener:mg}}=cd(),{format:yg,parse:_g}=Gr(),{toBuffer:wg}=qn(),pd=Symbol("kAborted"),Si=[8,13],kt=["CONNECTING","OPEN","CLOSING","CLOSED"],vg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,fe=class n extends ng{constructor(e,t,r){super(),this._binaryType=ld[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Wr,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]),gd(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ld.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 cg({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new dg(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[be]=this,i[be]=this,e[be]=this,s.on("conclude",Sg),s.on("drain",Eg),s.on("error",xg),s.on("message",Tg),s.on("ping",Cg),s.on("pong",Rg),i.onerror=Ag,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",_d),e.on("data",Jr),e.on("end",wd),e.on("error",vd),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[It.extensionName]&&this._extensions[It.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){qe(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())}),yd(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){Ei(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Wr,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){Ei(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Wr,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){Ei(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[It.extensionName]||(s.compress=!1),this._sender.send(e||Wr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){qe(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(fe,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(fe.prototype,"CONNECTING",{enumerable:!0,value:kt.indexOf("CONNECTING")});Object.defineProperty(fe,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(fe.prototype,"OPEN",{enumerable:!0,value:kt.indexOf("OPEN")});Object.defineProperty(fe,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(fe.prototype,"CLOSING",{enumerable:!0,value:kt.indexOf("CLOSING")});Object.defineProperty(fe,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});Object.defineProperty(fe.prototype,"CLOSED",{enumerable:!0,value:kt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(fe.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(fe.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[ki])return e[hg];return null},set(e){for(let t of this.listeners(n))if(t[ki]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[ki]:!0})}})});fe.prototype.addEventListener=gg;fe.prototype.removeEventListener=mg;bd.exports=fe;function gd(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:ug,protocolVersion:Si[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,!Si.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Si.join(", ")})`);let i;if(e instanceof bi)i=e;else try{i=new bi(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;jr(n,p);return}let l=o?443:80,d=og(16).toString("base64"),u=o?rg.request:sg.request,m=new Set,g;if(s.createConnection=s.createConnection||(o?kg:bg),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(g=new It({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=yg({[It.extensionName]:g.offer()})),t.length){for(let p of t){if(typeof p!="string"||!vg.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 f;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[w,k]of Object.entries(p))r.headers[w.toLowerCase()]=k}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")),f=n._req=u(s),n._redirects&&n.emit("redirect",n.url,f)}else f=n._req=u(s);s.timeout&&f.on("timeout",()=>{qe(n,f,"Opening handshake has timed out")}),f.on("error",p=>{f===null||f[pd]||(f=n._req=null,jr(n,p))}),f.on("response",p=>{let w=p.headers.location,k=p.statusCode;if(w&&s.followRedirects&&k>=300&&k<400){if(++n._redirects>s.maxRedirects){qe(n,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new bi(w,e)}catch{let S=new SyntaxError(`Invalid URL: ${w}`);jr(n,S);return}gd(n,v,t,r)}else n.emit("unexpected-response",f,p)||qe(n,f,`Unexpected server response: ${p.statusCode}`)}),f.on("upgrade",(p,w,k)=>{if(n.emit("upgrade",p),n.readyState!==fe.CONNECTING)return;f=n._req=null;let v=p.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){qe(n,w,"Invalid Upgrade header");return}let _=ag("sha1").update(d+fg).digest("base64");if(p.headers["sec-websocket-accept"]!==_){qe(n,w,"Invalid Sec-WebSocket-Accept header");return}let S=p.headers["sec-websocket-protocol"],P;if(S!==void 0?m.size?m.has(S)||(P="Server sent an invalid subprotocol"):P="Server sent a subprotocol but none was requested":m.size&&(P="Server sent no subprotocol"),P){qe(n,w,P);return}S&&(n._protocol=S);let x=p.headers["sec-websocket-extensions"];if(x!==void 0){if(!g){qe(n,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let O;try{O=_g(x)}catch{qe(n,w,"Invalid Sec-WebSocket-Extensions header");return}let W=Object.keys(O);if(W.length!==1||W[0]!==It.extensionName){qe(n,w,"Server indicated an extension that was not requested");return}try{g.accept(O[It.extensionName])}catch{qe(n,w,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[It.extensionName]=g}n.setSocket(w,k,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(f,n):f.end()}function jr(n,e){n._readyState=fe.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function bg(n){return n.path=n.socketPath,fd.connect(n)}function kg(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=fd.isIP(n.host)?"":n.host),ig.connect(n)}function qe(n,e,t){n._readyState=fe.CLOSING;let r=new Error(t);Error.captureStackTrace(r,qe),e.setHeader?(e[pd]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(jr,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function Ei(n,e,t){if(e){let r=lg(e)?e.size:wg(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${kt[n.readyState]})`);process.nextTick(t,r)}}function Sg(n,e){let t=this[be];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[be]!==void 0&&(t._socket.removeListener("data",Jr),process.nextTick(md,t._socket),n===1005?t.close():t.close(n,e))}function Eg(){let n=this[be];n.isPaused||n._socket.resume()}function xg(n){let e=this[be];e._socket[be]!==void 0&&(e._socket.removeListener("data",Jr),process.nextTick(md,e._socket),e.close(n[pg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function ud(){this[be].emitClose()}function Tg(n,e){this[be].emit("message",n,e)}function Cg(n){let e=this[be];e._autoPong&&e.pong(n,!this._isServer,hd),e.emit("ping",n)}function Rg(n){this[be].emit("pong",n)}function md(n){n.resume()}function Ag(n){let e=this[be];e.readyState!==fe.CLOSED&&(e.readyState===fe.OPEN&&(e._readyState=fe.CLOSING,yd(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function yd(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function _d(){let n=this[be];if(this.removeListener("close",_d),this.removeListener("data",Jr),this.removeListener("end",wd),n._readyState=fe.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[be]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",ud),n._receiver.on("finish",ud))}function Jr(n){this[be]._receiver.write(n)||this.pause()}function wd(){let n=this[be];n._readyState=fe.CLOSING,n._receiver.end(),this.end()}function vd(){let n=this[be];this.removeListener("error",vd),this.on("error",hd),n&&(n._readyState=fe.CLOSING,this.destroy())}});var xd=ee((bb,Ed)=>{"use strict";var vb=Yr(),{Duplex:Og}=te("stream");function kd(n){n.emit("close")}function Pg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Sd(n){this.removeListener("error",Sd),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function Ig(n,e){let t=!0,r=new Og({...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(kd,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(kd,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",Pg),r.on("error",Sd),r}Ed.exports=Ig});var xi=ee((kb,Td)=>{"use strict";var{tokenChars:Ng}=hn();function Mg(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&&Ng[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}Td.exports={parse:Mg}});var Nd=ee((Eb,Id)=>{"use strict";var Lg=te("events"),Vr=te("http"),{Duplex:Sb}=te("stream"),{createHash:$g}=te("crypto"),Cd=Gr(),Yt=fn(),Dg=xi(),Bg=Yr(),{CLOSE_TIMEOUT:Ug,GUID:Fg,kWebSocket:Hg}=wt(),qg=/^[+/0-9A-Za-z]{22}==$/,Rd=0,Ad=1,Pd=2,Ti=class extends Lg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Ug,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Bg,...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=Vr.createServer((r,s)=>{let i=Vr.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=Gg(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=Rd}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===Pd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Yn,this);return}if(e&&this.once("close",e),this._state!==Ad)if(this._state=Ad,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(Yn,this):process.nextTick(Yn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Yn(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",Od);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Vt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Vt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!qg.test(i)){Vt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Vt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Vn(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Dg.parse(c)}catch{Vt(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let m=new Yt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Cd.parse(d);g[Yt.extensionName]&&(m.accept(g[Yt.extensionName]),u[Yt.extensionName]=m)}catch{Vt(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,(g,f,p,w)=>{if(!g)return Vn(t,f||401,p,w);this.completeUpgrade(u,i,l,e,t,r,s)});return}if(!this.options.verifyClient(m))return Vn(t,401)}this.completeUpgrade(u,i,l,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Hg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Rd)return Vn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${$g("sha1").update(t+Fg).digest("base64")}`],d=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&&(l.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Yt.extensionName]){let u=e[Yt.extensionName].params,m=Cd.format({[Yt.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
209
209
  `).join(`\r
210
- `)),i.removeListener("error",xd),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Yn,this)})),a(d,s)}};Cd.exports=ki;function $p(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 Yn(n){n._state=Td,n.emit("close")}function xd(){this.destroy()}function Vn(n,e,t,r){t=t||Yr.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} ${Yr.STATUS_CODES[e]}\r
210
+ `)),i.removeListener("error",Od),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Yn,this)})),a(d,s)}};Id.exports=Ti;function Gg(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 Yn(n){n._state=Pd,n.emit("close")}function Od(){this.destroy()}function Vn(n,e,t,r){t=t||Vr.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} ${Vr.STATUS_CODES[e]}\r
211
211
  `+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
212
212
  `)+`\r
213
213
  \r
214
- `+t)}function Vt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Vt),n.emit("wsClientError",o,t,e)}else Vn(t,r,s,i)}});var Dp,Bp,Up,Fp,Hp,qp,Si,Gp,Ad=C(()=>{Dp=oe(vd(),1),Bp=oe(qr(),1),Up=oe(fn(),1),Fp=oe(fi(),1),Hp=oe(pi(),1),qp=oe(bi(),1),Si=oe(Jr(),1),Gp=oe(Rd(),1)});var Od,jp,Jp,Vr,bb,Ei=C(()=>{Fn();qt();sn();Ht();Od=oe(Ye(),1),jp=(0,Od.default)("engine.io-client:websocket"),Jp=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Vr=class extends yt{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Jp?{}:Tr(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;Bn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{jp("websocket closed before onclose event")}s&&pt(()=>{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]=Cr()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},bb=Pe.WebSocket||Pe.MozWebSocket});var _n,xi=C(()=>{Ad();Ei();_n=class extends Vr{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 Si.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 Pd,zn,wn,Ti=C(()=>{Fn();Ht();sn();Pd=oe(Ye(),1),zn=(0,Pd.default)("engine.io-client:webtransport"),wn=class extends yt{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(()=>{zn("transport closed gracefully"),this.onClose()}).catch(e=>{zn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=sc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=rc();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){zn("session is closed");return}zn("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{zn("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&&pt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var Ci,Ri=C(()=>{ti();xi();Ti();Ci={websocket:_n,webtransport:wn,polling:dn}});function vn(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=Yp.exec(n||""),i={},o=14;for(;o--;)i[Vp[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=zp(i,i.path),i.queryKey=Kp(i,i.query),i}function zp(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 Kp(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var Yp,Vp,Ai=C(()=>{Yp=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Vp=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var Id,Nd,de,Oi,Kn,zt,zr,bn,Pi=C(()=>{Ri();qt();Vs();Ai();Id=oe(Ft(),1);sn();Ht();Nd=oe(Ye(),1),de=(0,Nd.default)("engine.io-client:socket"),Oi=typeof addEventListener=="function"&&typeof removeEventListener=="function",Kn=[];Oi&&addEventListener("offline",()=>{de("closing %d connection(s) because the network was lost",Kn.length),Kn.forEach(n=>n())},!1);zt=class n extends Id.Emitter{constructor(e,t){if(super(),this.binaryType=oc,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=vn(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=vn(t.host).host);mt(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=lc(this.opts.query)),Oi&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(de("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Kn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=ac()),this._open()}createTransport(e){de('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Js,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 de("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){de("setting transport %s",e.name),this.transport&&(de("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(){de("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(de('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 de('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();de("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+=cc(s)),r>0&&t>this._maxPayload)return de("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return de("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&&(de("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,pt(()=>{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"),de("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(de("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return de("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(de('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Oi&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Kn.indexOf(this._offlineEventListener);r!==-1&&(de("removing listener for the 'offline' event"),Kn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};zt.protocol=Js;zr=class extends zt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){de("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){de('probing transport "%s"',e);let t=this.createTransport(e),r=!1;zt.priorWebsocketSuccess=!1;let s=()=>{r||(de('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(de('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;zt.priorWebsocketSuccess=t.name==="websocket",de('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(de("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{de('probe transport "%s" failed',e);let m=new Error("probe error");m.transport=t.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,d(),t.close(),t=null)}let o=u=>{let m=new Error("probe error: "+u);m.transport=t.name,i(),de('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 l(u){t&&u.name!==t.name&&(de('"%s" works - aborting "%s"',u.name,t.name),i())}let d=()=>{t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",l)};t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",l),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}},bn=class extends zr{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=>Ci[s]).filter(s=>!!s)),super(e,r)}}});var Md=C(()=>{Xs()});var Wb,Kr=C(()=>{Pi();Pi();Fn();Ri();qt();Ai();Ht();Md();ti();Zs();xi();Ei();Ti();Wb=bn.protocol});function Dd(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)||(Ld("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Ld("parse %s",n),r=vn(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 $d,Ld,Bd=C(()=>{Kr();$d=oe(Ye(),1),Ld=(0,$d.default)("socket.io-client:url")});function Qn(n){return em&&(n instanceof ArrayBuffer||tm(n))||nm&&n instanceof Blob||rm&&n instanceof File}function Xn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Xn(n[t]))return!0;return!1}if(Qn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Xn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Xn(n[t]))return!0;return!1}var em,tm,Ud,nm,rm,Ii=C(()=>{em=typeof ArrayBuffer=="function",tm=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Ud=Object.prototype.toString,nm=typeof Blob=="function"||typeof Blob<"u"&&Ud.call(Blob)==="[object BlobConstructor]",rm=typeof File=="function"||typeof File<"u"&&Ud.call(File)==="[object FileConstructor]"});function Fd(n){let e=[],t=n.data,r=n;return r.data=Ni(t,e),r.attachments=e.length,{packet:r,buffers:e}}function Ni(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]=Ni(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]=Ni(n[r],e));return t}return n}function Hd(n,e){return n.data=Mi(n.data,e),delete n.attachments,n}function Mi(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]=Mi(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Mi(n[t],e));return n}var qd=C(()=>{Ii()});var Ui={};He(Ui,{Decoder:()=>Di,Encoder:()=>$i,PacketType:()=>j,isPacketValid:()=>am,protocol:()=>Jd});function sm(n){return typeof n=="string"}function im(n){return n===void 0||Yd(n)}function Xr(n){return Object.prototype.toString.call(n)==="[object Object]"}function om(n,e){switch(n){case j.CONNECT:return e===void 0||Xr(e);case j.DISCONNECT:return e===void 0;case j.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&jd.indexOf(e[0])===-1);case j.ACK:return Array.isArray(e);case j.CONNECT_ERROR:return typeof e=="string"||Xr(e);default:return!1}}function am(n){return sm(n.nsp)&&im(n.id)&&om(n.type,n.data)}var Gd,Wd,Li,jd,Jd,j,$i,Di,Bi,Yd,Qr=C(()=>{Gd=oe(Ft(),1);qd();Ii();Wd=oe(Ye(),1),Li=(0,Wd.default)("socket.io-parser"),jd=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Jd=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={}));$i=class{constructor(e){this.replacer=e}encode(e){return Li("encoding packet %j",e),(e.type===j.EVENT||e.type===j.ACK)&&Xn(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)),Li("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=Fd(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},Di=class n extends Gd.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 Bi(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(!Yd(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 Li("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 Xr(t);case j.DISCONNECT:return t===void 0;case j.CONNECT_ERROR:return typeof t=="string"||Xr(t);case j.EVENT:case j.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&jd.indexOf(t[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Bi=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=Hd(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};Yd=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function Ge(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Fi=C(()=>{});var Vd,zd,me,cm,kn,Hi=C(()=>{Qr();Fi();Vd=oe(Ft(),1),zd=oe(Ye(),1),me=(0,zd.default)("socket.io-client:socket"),cm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),kn=class extends Vd.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=[Ge(e,"open",this.onopen.bind(this)),Ge(e,"packet",this.onpacket.bind(this)),Ge(e,"error",this.onerror.bind(this)),Ge(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(cm.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 d=this.ids++;me("emitting packet with ack id %d",d);let u=t.pop();this._registerAckCallback(d,u),o.id=d}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?me("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&&(me("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));me("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]?me("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(me("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(me("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(me("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){me("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,me("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(){me("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){me("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||[];me("emitting event %j",t),e.id!=null&&(me("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,me("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"){me("bad ack %s",e.id);return}delete this.acks[e.id],me("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){me("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(){me("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&&(me("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 Kt(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 Kd=C(()=>{Kt.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};Kt.prototype.reset=function(){this.attempts=0};Kt.prototype.setMin=function(n){this.ms=n};Kt.prototype.setMax=function(n){this.max=n};Kt.prototype.setJitter=function(n){this.jitter=n}});var Xd,Qd,Ee,Sn,Zd=C(()=>{Kr();Hi();Qr();Fi();Kd();Xd=oe(Ft(),1),Qd=oe(Ye(),1),Ee=(0,Qd.default)("socket.io-client:manager"),Sn=class extends Xd.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,mt(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 Kt({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||Ui;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(Ee("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Ee("opening %s",this.uri),this.engine=new bn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Ge(t,"open",function(){r.onopen(),e&&e()}),i=a=>{Ee("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Ge(t,"error",i);if(this._timeout!==!1){let a=this._timeout;Ee("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{Ee("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(){Ee("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Ge(e,"ping",this.onping.bind(this)),Ge(e,"data",this.ondata.bind(this)),Ge(e,"error",this.onerror.bind(this)),Ge(e,"close",this.onclose.bind(this)),Ge(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){pt(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Ee("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new kn(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){Ee("socket %s is still active, skipping close",r);return}this._close()}_packet(e){Ee("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(){Ee("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Ee("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;Ee("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)Ee("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();Ee("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(Ee("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(Ee("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(Ee("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 er(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=Dd(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Zn[s]&&i in Zn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(el("ignoring socket cache for %s",r),c=new Sn(r,e)):(Zn[s]||(el("new io instance for %s",r),Zn[s]=new Sn(r,e)),c=Zn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var tl,el,Zn,nl=C(()=>{Bd();Zd();Hi();tl=oe(Ye(),1);Qr();Kr();el=(0,tl.default)("socket.io-client"),Zn={};Object.assign(er,{Manager:Sn,Socket:kn,io:er,connect:er})});var dt,dm,Zr,rl=C(()=>{"use strict";nl();ge();dt="wsClient",dm=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),Zr=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",dt,"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=>{E(dt,"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=er(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",dt,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{E(dt,"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=>{E(dt,"event handler threw",i)})});for(let t of dm)e.on(t,r=>{h("error",dt,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",dt,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",dt,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{E(dt,"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",dt,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var nt,es,sl=C(()=>{"use strict";en();_a();Ln();rl();ge();nt="serverGateway",es=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=Rt(),h("info",nt,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new Zr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>ya(t,r)});let e=ma();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",nt,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",nt,`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",nt,"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",nt,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return va(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await ba(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await ka(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await Sa(this.config.server_url,e,t,this._getToken())}async getAction(e){return xa(this.config.server_url,e,this._getToken())}async getApproval(e){return Ta(this.config.server_url,e,this._getToken())}async fireAction(e,t){return Ca(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await Ra(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return Aa(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return nn(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return Oa(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return Ia(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return Na(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return Pa(this.config.server_url,e,this._getToken())}async getTasks(e,t){return kr(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return Ma(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return La(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return $a(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return Da(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Ba(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return Ua(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await qa(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await Fa(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 Ha(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return Ga(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Wa(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",nt,"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 Ea(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",nt,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",nt,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){E(nt,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=Rt(),t=await wa(this.config.server_url,e);yr(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",nt,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){E(nt,"token refresh failed",e)}}_getToken(){return this.token||(this.token=Rt()),this.token}}});import{execFile as lm}from"node:child_process";import{promisify as um}from"node:util";import{readFileSync as fm,readdirSync as ts,statSync as qi,openSync as hm,readSync as gm,closeSync as pm}from"node:fs";import{join as Xt}from"node:path";import{homedir as il}from"node:os";async function mm(){try{if(process.platform==="darwin"){let{stdout:n}=await ol("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=fm(Xt(il(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function ym(){let n=await mm();if(!n)return null;try{let{stdout:e}=await ol("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 _m(n,e){let t=[];try{for(let r of ts(n).sort().reverse().slice(0,2)){let s=Xt(n,r);for(let i of ts(s).sort().reverse().slice(0,2)){let o=Xt(s,i);for(let a of ts(o).sort().reverse().slice(0,7)){let c=Xt(o,a);for(let l of ts(c)){if(!l.endsWith(".jsonl"))continue;let d=Xt(c,l);try{t.push({path:d,mtime:qi(d).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 wm(n,e){let t=hm(n,"r");try{let r=qi(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return gm(t,i,0,s,r-s),i.toString("utf-8")}finally{pm(t)}}function vm(){let n=process.env.CODEX_HOME??Xt(il(),".codex");for(let e of _m(Xt(n,"sessions"),5))try{let t=wm(e,262144).split(`
215
- `).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(qi(e).mtimeMs).toISOString()}}catch{}}catch{}return null}async function al(){let[n,e]=await Promise.all([ym(),Promise.resolve().then(vm)]);return{sampled_at:new Date().toISOString(),claude:n,codex:e}}var ol,cl=C(()=>{"use strict";ol=um(lm)});function ul(n,e,t){if(t){let r=`${n}:${t}`;if(tr.has(r))return;if(tr.set(r,Date.now()),tr.size>500){let s=Date.now()-36e5;for(let[i,o]of tr)o<s&&tr.delete(i)}}nr.set(`${n}:${e}`,Date.now())}function Gi(n){ll.set(n,Date.now());let e=`${n}:`;for(let t of nr.keys())t.startsWith(e)&&nr.delete(t)}function fl(n,e){let t=`${n}:${e}`,r=nr.get(t);if(r===void 0||(nr.delete(t),Date.now()-r>Sm))return!1;let s=ll.get(n)??0;if(Date.now()-s<bm)return!1;let i=dl.get(e)??0;return Date.now()-i<km?!1:(dl.set(e,Date.now()),!0)}var nr,dl,ll,tr,bm,km,Sm,Wi=C(()=>{"use strict";nr=new Map,dl=new Map,ll=new Map,tr=new Map,bm=180*1e3,km=600*1e3,Sm=1800*1e3});var Nt,hl,ns,gl=C(()=>{"use strict";ge();Nt="sessionManager",hl=3e4,ns=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},hl),h("info",Nt,`Heartbeat timer started (every ${hl/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=>{E(Nt,`Failed to mark session ${t.sessionId} disconnected`,r)}))),h("info",Nt,`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",Nt,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){h("warn",Nt,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,h("info",Nt,"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=>{E(Nt,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&h("debug",Nt,`Sent ${e.length} heartbeat(s)`)}}});var St,rs,pl=C(()=>{"use strict";ge();St="workroomCoordinator",rs=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",St,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return h("info",St,"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 E(St,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return E(St,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{E(St,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),h("info",St,"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",St,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){E(St,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),h("info",St,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as Ji,unlink as Em,readdir as xm,stat as Tm}from"fs/promises";import{join as ss}from"path";import{randomBytes as Yi}from"crypto";async function yl(n,e){let t=Yi(8).toString("hex"),r=ss(Ut,`action-${n}-${t}${ml}`),s;try{s=await Ji(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return h("info",Et,"secret file written",{actionId:n,filePath:r}),r}async function rr(n){try{await Em(n),h("info",Et,"secret file deleted",{filePath:n})}catch(e){if(ji(e))return;E(Et,"failed to delete secret file (best-effort)",e)}}async function _l(){let n;try{n=await xm(Ut)}catch(s){if(ji(s))return;E(Et,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(ml)),r=0;for(let s of t){let i=ss(Ut,s);try{let o=await Tm(i),a=e-o.mtimeMs;a>=Cm&&(await rr(i),r++,h("info",Et,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(ji(o))continue;E(Et,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&h("info",Et,"TTL scan complete",{scanned:t.length,purged:r})}async function wl(n){let e=Date.now(),t=Yi(4).toString("hex"),r=ss(Ut,`drain-evidence-${e}-${t}.json`),s;try{s=await Ji(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",Et,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function vl(n){let e=Date.now(),t=Yi(4).toString("hex"),r=ss(Ut,`response-lost-${e}-${t}.json`),s;try{s=await Ji(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",Et,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function ji(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var Et,Cm,ml,is=C(()=>{"use strict";Qe();ge();Et="secretManager",Cm=600*1e3,ml=".secret"});import{spawn as Rm}from"child_process";import{stat as Am}from"fs/promises";async function bl(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return h("warn",Qt,"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 Am(e.path)}catch{return h("warn",Qt,"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 yl(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return E(Qt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=Rm(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return E(Qt,"spawn failed",i),r&&rr(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{h("info",Qt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&rr(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{E(Qt,"subprocess error after spawn",i),r&&rr(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),h("info",Qt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var Qt,kl=C(()=>{"use strict";ge();is();Qt="runtimeAdapter"});var G,Sl,sr,El,ir,xl,Om,os,Vi=C(()=>{"use strict";Ln();ge();kl();is();G="actionGate",Sl=new Set(["proposed","approved"]),sr=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),El="irreversible_no_abort",ir=new Set(["transmission_complete","succeeded","canceled","failed"]),xl=15,Om=8e3,os=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",G,"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",G,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,h("info",G,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=Om){if(this.inFlightIrreversible.size===0){h("info",G,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return h("warn",G,"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);E(G,"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 wl({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",G,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){E(G,"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)&&ir.has(r)&&this.gateway.getAction(t).then(s=>{ir.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):h("warn",G,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{E(G,"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",G,"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",G,"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",G,"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=>{ir.has(s.status)?(h("info",G,"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",G,"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=>{E(G,"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){E(G,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){h("info",G,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){h("warn",G,"action.created: missing action_id in payload \u2014 ignoring");return}h("info",G,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(sr.has(r.status)){h("info",G,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!Sl.has(r.status)){h("info",G,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===El?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",G,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&h("info",G,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),h("info",G,"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",G,"approval.decided: missing required fields \u2014 ignoring");return}if(h("info",G,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),h("info",G,"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),sr.has(i.status)){h("info",G,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!Sl.has(i.status)){h("warn",G,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){h("warn",G,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){h("warn",G,"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",G,"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&&sr.has(r),a=i&&ir.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&sr.has(c.status)&&(this.pendingApproval.delete(t),h("info",G,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&ir.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",G,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let d=await this.gateway.fireAction(r,t);h("info",G,"action fired",{actionId:r,fired_at:d.fired_at}),a=d.action_token,o=!0}catch(d){if(d instanceof Mn&&d.isDefinitiveRejection){E(G,`fire definitively rejected (${d.statusCode} ${d.errorCode}) \u2014 re-querying before cancel`,d);let m=await this.gateway.getAction(r).catch(()=>null);if(!m||sr.has(m.status)){h("info",G,"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(p=>{E(G,"cancel after rejected fire also failed",p)});return}E(G,"fire failed with uncertain error \u2014 reconciling action state",d);let u=await this.gateway.getAction(r).catch(()=>null);if(u?.status==="fired"){h("warn",G,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let m=u.fired_at??new Date().toISOString();await vl({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(p=>{E(G,"failed to write response-lost evidence (CRITICAL)",p)});return}else{h("warn",G,"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===El;c&&this._registerInFlight(e);let l=await bl({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?(d,u)=>this._onSubprocessExitForDrain(r,d,u):void 0});l.ok||(h("warn",G,"spawn returned not-ok",{actionId:r,reason_code:l.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as Pm}from"net";import{chmod as Im}from"fs/promises";var lt,as,Tl=C(()=>{"use strict";ge();lt="ipcServer",as=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=Pm(s=>{this._handleConnection(s)}),this.server.once("error",s=>{E(lt,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Im(e,384)}catch(s){E(lt,"Failed to chmod IPC socket",s)}h("info",lt,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",lt,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){h("debug",lt,"subprocess connected");let t="";e.on("data",r=>{t+=r.toString("utf8");let s=t.split(`
216
- `);t=s.pop()??"";for(let i of s){let o=i.trim();o&&this._processLine(o)}}),e.on("error",r=>{E(lt,"IPC socket connection error",r)}),e.on("close",()=>{h("debug",lt,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{h("warn",lt,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){h("warn",lt,"IPC message missing required `type` field \u2014 ignored");return}h("debug",lt,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as Nm}from"http";var zi,Mm,Lm,cs,Cl=C(()=>{"use strict";ge();zi="healthServer",Mm="127.0.0.1",Lm=7878,cs=class{constructor(e){this.version=e}version;server=null;startTime=Date.now();async listen(e=Mm,t=Lm){return new Promise((r,s)=>{this.server=Nm((i,o)=>this._handleRequest(i,o)),this.server.once("error",i=>{E(zi,"Health server startup error",i),s(i)}),this.server.listen(t,e,()=>{h("info",zi,`Health server listening on ${e}:${t}`),r()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",zi,"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 Rl,mkdir as Al}from"node:fs/promises";import{homedir as $m}from"node:os";import{dirname as Dm,join as Ol}from"node:path";function Bm(){return ds||(ds=Al(Pl,{recursive:!0}).then(()=>{},n=>{throw ds=null,n})),ds}function ls(n){return n&&n.replace(/-/g,"").slice(0,8)||"unknown"}function Um(n){return Ol(Pl,`agent-${ls(n)}.jsonl`)}function ne(n,e,t){let r;try{let i={ts:new Date().toISOString(),agent_id:n,kind:e,...t};r=JSON.stringify(i)+`
217
- `}catch(i){process.stderr.write(`[agentTrace] serialize error agent=${ls(n)} kind=${e}: ${i.message}
218
- `);return}let s=Um(n);Bm().then(()=>Rl(s,r,{encoding:"utf8"})).catch(i=>{if(i.code==="ENOENT"){let o=Dm(s);Al(o,{recursive:!0}).then(()=>Rl(s,r,{encoding:"utf8"})).catch(a=>{process.stderr.write(`[agentTrace] append failed agent=${ls(n)} kind=${e}: ${a.message}
219
- `)});return}process.stderr.write(`[agentTrace] append failed agent=${ls(n)} kind=${e}: ${i.message}
220
- `)})}var Pl,ds,Mt=C(()=>{"use strict";Pl=Ol($m(),".mio","logs"),ds=null});import{readFileSync as Fm,writeFileSync as Hm,existsSync as qm}from"fs";import{join as Gm}from"path";function Il(){return Gm(_e,"agent-inbox-cursor.json")}function Nl(){let n=Il();if(!qm(n))return{};try{return JSON.parse(Fm(n,"utf-8"))}catch{return{}}}function Wm(n){Nn(),Hm(Il(),JSON.stringify(n,null,2),{mode:384})}function Ml(n,e){return Nl()[`${n}:${e}`]??"0"}function xt(n,e,t){let r=Nl(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,Wm(r))}var Ki=C(()=>{"use strict";Qe()});import{createServer as jm}from"http";import{randomBytes as Jm,timingSafeEqual as Ym}from"crypto";function $e(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Qm(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 us);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function Zm(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Ym(t,r)}async function Ie(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 Ll(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??Km,c=i instanceof Set?i:new Set(i),l=Jm(32).toString("hex");async function d(g,_){if(g.method!=="POST"||g.url!=="/act"){_.writeHead(404),_.end();return}let S=g.headers.authorization??"",v=`Bearer ${l}`;if(!Zm(S,v)){$e(_,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let y;try{y=await Qm(g,zm)}catch(Y){if(Y instanceof us){$e(_,413,{ok:!1,code:"BODY_TOO_LARGE"});return}$e(_,400,{ok:!1,code:"INVALID_JSON"});return}let k;try{k=JSON.parse(y)}catch{$e(_,400,{ok:!1,code:"INVALID_JSON"});return}let P=k.action,x=k.payload!=null&&typeof k.payload=="object"?k.payload:{};if(P!=="attachment"&&Buffer.byteLength(y)>Vm){$e(_,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(P)){$e(_,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let O=Xm[P];if(!c.has(O)){$e(_,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let W={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 Y=x,re=null;if(o)try{let ue=o.get(e);ue&&typeof x.context_message_id!="string"&&(Y={...x,context_message_id:ue},re=ue)}catch(ue){E(Lt,"contextTracker.get threw (non-fatal)",ue)}let ae=typeof x.target=="string"?x.target:null,V=typeof x.parent_message_id=="string"?x.parent_message_id:null,le=typeof x.content=="string"?x.content.slice(0,120):null;h("info",Lt,"forward send",{agentId:e,target:ae,parent_message_id:V,stamped_context:re!==null,context_message_id:re}),ne(e,"outbound",{action:"send",target:ae,parent_message_id:V,context_message_id:re,context_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:le,content_bytes:typeof x.content=="string"?x.content.length:0}),await ey(_,r,W,Y,a),_.statusCode<300&&Gi(e),ne(e,"outbound_done",{action:"send",status:_.statusCode,duration_ms:Date.now()-J})}else if(P==="reply"){let Y=typeof x.target=="string"?x.target:null,re=typeof x.parent_message_id=="string"?x.parent_message_id:null,ae=typeof x.content=="string"?x.content.slice(0,120):null;ne(e,"outbound",{action:"reply",target:Y,parent_message_id:re,parent_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:ae}),await ty(_,r,W,x,a),_.statusCode<300&&Gi(e),ne(e,"outbound_done",{action:"reply",status:_.statusCode,duration_ms:Date.now()-J})}else if(P==="history")await ny(_,r,W,x,a);else if(P==="task"){let Y=typeof x.op=="string"?x.op:null;ne(e,"task",{action:Y,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 sy(_,r,W,x,a),ne(e,"task_done",{action:Y,status:_.statusCode,duration_ms:Date.now()-J})}else P==="reminder"?await oy(_,r,W,x,a):P==="action"?await cy(_,r,W,x,a):P==="react"?await dy(_,r,W,x,a):P==="attachment"?await ly(_,r,W,x,a):P==="profile"?await uy(_,r,W,x,a):await fy(_,r,W,e,x,a)}catch(Y){E(Lt,"upstream forwarding error",Y);let re=Y instanceof Error&&Y.name==="AbortError";$e(_,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:re?`upstream timed out after ${a}ms`:String(Y)})}}let u=jm((g,_)=>{d(g,_).catch(S=>{E(Lt,"unhandled request error",S),_.writeHead(500),_.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((g,_)=>{u.once("error",S=>{E(Lt,"agent proxy startup error",S),_(S)}),u.listen(0,"127.0.0.1",()=>{let S=u.address(),v=typeof S=="object"&&S?S.port:0;h("info",Lt,"agent proxy listening",{agentId:e,launchId:t,port:v}),g(v)})})}`,proxyToken:l,close:()=>new Promise(g=>{u.close(()=>{h("info",Lt,"agent proxy stopped",{agentId:e,launchId:t}),g()})})}}async function ey(n,e,t,r,s){let i=await Ie(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ne(n,i)}async function ty(n,e,t,r,s){let i=await Ie(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ne(n,i)}async function ny(n,e,t,r,s){let i=hy(r),o=await Ie(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Ne(n,o)}async function sy(n,e,t,r,s){let i=String(r.op??""),o=ry[i];if(!o){$e(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 l=c.toString(),d=await Ie(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Ne(n,d)}else{let{op:c,...l}=r,d=await Ie(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Ne(n,d)}}async function oy(n,e,t,r,s){let i=String(r.op??""),o=iy[i];if(!o){$e(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 l=c.toString(),d=await Ie(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Ne(n,d)}else{let{op:c,...l}=r,d=await Ie(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Ne(n,d)}}async function cy(n,e,t,r,s){let i=String(r.op??""),o=ay[i];if(!o){$e(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 l=c.toString(),d=await Ie(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Ne(n,d)}else{let{op:c,...l}=r,d=await Ie(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Ne(n,d)}}async function dy(n,e,t,r,s){let i=await Ie(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ne(n,i)}async function ly(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await Ie(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Ne(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await Ie(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Ne(n,a);return}$e(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function uy(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,l=await Ie(c,{method:"GET",headers:t},s);await Ne(n,l);return}if(i==="update"){let{op:o,...a}=r,c=await Ie(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Ne(n,c);return}$e(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function fy(n,e,t,r,s,i){let o=String(s.channel??""),a=Ml(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),l=await Ie(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!l.ok){await Ne(n,l);return}let d=await l.json(),u=d.messages??[];if(u.length>0){let p=u.reduce((f,g)=>{let _=0n;try{_=BigInt(String(g.seq??"0"))}catch{E(Lt,"bad seq from upstream",{seq:g.seq}),_=0n}return _>f?_:f},0n);p>0n&&xt(r,o,p.toString())}let m=JSON.stringify(d);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Ne(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{}$e(n,e.status,{ok:!1,code:r,message:s})}function hy(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 Lt,Vm,zm,Km,Xm,us,ry,iy,ay,$l=C(()=>{"use strict";Wi();ge();Mt();Ki();Lt="agentProxy",Vm=1024*1024,zm=12*1024*1024,Km=15e3,Xm={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};us=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};ry={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"}};iy={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"}};ay={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as Dl,writeFile as Xi,chmod as Bl}from"fs/promises";import{existsSync as Ul}from"fs";import{join as or,resolve as gy,dirname as py}from"path";import{spawnSync as my}from"child_process";import{fileURLToPath as yy}from"url";function ar(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function $t(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function _y(n){let e=py(yy(import.meta.url))+"/../..",t=n?.localTsxPath??gy(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Ul(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??wy)();return i||"tsx"}function wy(){let e=my("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Ul(e)?e:null}function Qi(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:_y(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function Fl(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??Qi(),c=or(r,".mio");await Dl(c,{recursive:!0,mode:493});let l=await Ll({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:d,proxyToken:u}=l;try{let m=ar(e),p=ar(t),f=or(_e,"agent-proxy-tokens",m),g=or(f,`${p}.token`);await Dl(f,{recursive:!0,mode:448}),await Xi(g,u,{encoding:"utf8",mode:384}),await Bl(g,384);let _=o.join(","),S=vy({execContext:a,proxyUrl:d,tokenFile:g,capabilityStr:_}),v=or(c,"mio");await Xi(v,S,{encoding:"utf8",mode:493}),await Bl(v,493),await Xi(or(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let y={...process.env},k=y.PATH??"";return y.PATH=k?`${c}:${k}`:c,delete y.CLAUDECODE,{mioDir:c,spawnEnv:y,proxyHandle:l}}catch(m){throw await l.close().catch(()=>{}),m}}function vy(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${$t(t)} MIO_AGENT_PROXY_TOKEN_FILE=${$t(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${$t(s)}`,o;return e.mode==="npm"?o=`exec ${$t(e.nodePath)} ${$t(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${$t(e.tsxPath)} ${$t(e.cliEntryPath)} agentcli "$@"`:o=`exec ${$t(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
221
- `)}var Hl=C(()=>{"use strict";Qe();$l()});function ql(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 by,ky,Sy,Ey,xy,Ty,Gl,Wl=C(()=>{"use strict";by=`## Role: Product Manager
214
+ `+t)}function Vt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Vt),n.emit("wsClientError",o,t,e)}else Vn(t,r,s,i)}});var Wg,jg,Jg,Yg,Vg,Kg,Ci,zg,Md=C(()=>{Wg=oe(xd(),1),jg=oe(Gr(),1),Jg=oe(fn(),1),Yg=oe(mi(),1),Vg=oe(wi(),1),Kg=oe(xi(),1),Ci=oe(Yr(),1),zg=oe(Nd(),1)});var Ld,Qg,Zg,Kr,Ab,Ri=C(()=>{Fn();qt();sn();Ht();Ld=oe(Ye(),1),Qg=(0,Ld.default)("engine.io-client:websocket"),Zg=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Kr=class extends yt{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Zg?{}:Cr(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;Bn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{Qg("websocket closed before onclose event")}s&&gt(()=>{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]=Rr()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},Ab=Pe.WebSocket||Pe.MozWebSocket});var _n,Ai=C(()=>{Md();Ri();_n=class extends Kr{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 Ci.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 $d,Kn,wn,Oi=C(()=>{Fn();Ht();sn();$d=oe(Ye(),1),Kn=(0,$d.default)("engine.io-client:webtransport"),wn=class extends yt{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(()=>{Kn("transport closed gracefully"),this.onClose()}).catch(e=>{Kn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=dc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=cc();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){Kn("session is closed");return}Kn("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{Kn("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&&gt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var Pi,Ii=C(()=>{ii();Ai();Oi();Pi={websocket:_n,webtransport:wn,polling:dn}});function vn(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=em.exec(n||""),i={},o=14;for(;o--;)i[tm[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=nm(i,i.path),i.queryKey=rm(i,i.query),i}function nm(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 rm(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var em,tm,Ni=C(()=>{em=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,tm=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var Dd,Bd,de,Mi,zn,Kt,zr,bn,Li=C(()=>{Ii();qt();Qs();Ni();Dd=oe(Ft(),1);sn();Ht();Bd=oe(Ye(),1),de=(0,Bd.default)("engine.io-client:socket"),Mi=typeof addEventListener=="function"&&typeof removeEventListener=="function",zn=[];Mi&&addEventListener("offline",()=>{de("closing %d connection(s) because the network was lost",zn.length),zn.forEach(n=>n())},!1);Kt=class n extends Dd.Emitter{constructor(e,t){if(super(),this.binaryType=uc,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=vn(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=vn(t.host).host);mt(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=gc(this.opts.query)),Mi&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(de("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},zn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=fc()),this._open()}createTransport(e){de('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=zs,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 de("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){de("setting transport %s",e.name),this.transport&&(de("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(){de("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(de('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 de('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();de("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+=hc(s)),r>0&&t>this._maxPayload)return de("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return de("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&&(de("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,gt(()=>{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"),de("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(de("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return de("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(de('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Mi&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=zn.indexOf(this._offlineEventListener);r!==-1&&(de("removing listener for the 'offline' event"),zn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Kt.protocol=zs;zr=class extends Kt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){de("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){de('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Kt.priorWebsocketSuccess=!1;let s=()=>{r||(de('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(de('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Kt.priorWebsocketSuccess=t.name==="websocket",de('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(de("changing transport and sending upgrade packet"),d(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{de('probe transport "%s" failed',e);let m=new Error("probe error");m.transport=t.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,d(),t.close(),t=null)}let o=u=>{let m=new Error("probe error: "+u);m.transport=t.name,i(),de('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 l(u){t&&u.name!==t.name&&(de('"%s" works - aborting "%s"',u.name,t.name),i())}let d=()=>{t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",l)};t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",l),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}},bn=class extends zr{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 Ud=C(()=>{ti()});var Qb,Xr=C(()=>{Li();Li();Fn();Ii();qt();Ni();Ht();Ud();ii();ri();Ai();Ri();Oi();Qb=bn.protocol});function qd(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)||(Fd("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Fd("parse %s",n),r=vn(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 Hd,Fd,Gd=C(()=>{Xr();Hd=oe(Ye(),1),Fd=(0,Hd.default)("socket.io-client:url")});function Qn(n){return am&&(n instanceof ArrayBuffer||cm(n))||dm&&n instanceof Blob||lm&&n instanceof File}function Xn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Xn(n[t]))return!0;return!1}if(Qn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Xn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Xn(n[t]))return!0;return!1}var am,cm,Wd,dm,lm,$i=C(()=>{am=typeof ArrayBuffer=="function",cm=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Wd=Object.prototype.toString,dm=typeof Blob=="function"||typeof Blob<"u"&&Wd.call(Blob)==="[object BlobConstructor]",lm=typeof File=="function"||typeof File<"u"&&Wd.call(File)==="[object FileConstructor]"});function jd(n){let e=[],t=n.data,r=n;return r.data=Di(t,e),r.attachments=e.length,{packet:r,buffers:e}}function Di(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]=Di(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]=Di(n[r],e));return t}return n}function Jd(n,e){return n.data=Bi(n.data,e),delete n.attachments,n}function Bi(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]=Bi(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Bi(n[t],e));return n}var Yd=C(()=>{$i()});var Gi={};He(Gi,{Decoder:()=>Hi,Encoder:()=>Fi,PacketType:()=>j,isPacketValid:()=>pm,protocol:()=>Xd});function um(n){return typeof n=="string"}function fm(n){return n===void 0||Qd(n)}function Qr(n){return Object.prototype.toString.call(n)==="[object Object]"}function hm(n,e){switch(n){case j.CONNECT:return e===void 0||Qr(e);case j.DISCONNECT:return e===void 0;case j.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&zd.indexOf(e[0])===-1);case j.ACK:return Array.isArray(e);case j.CONNECT_ERROR:return typeof e=="string"||Qr(e);default:return!1}}function pm(n){return um(n.nsp)&&fm(n.id)&&hm(n.type,n.data)}var Vd,Kd,Ui,zd,Xd,j,Fi,Hi,qi,Qd,Zr=C(()=>{Vd=oe(Ft(),1);Yd();$i();Kd=oe(Ye(),1),Ui=(0,Kd.default)("socket.io-parser"),zd=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Xd=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={}));Fi=class{constructor(e){this.replacer=e}encode(e){return Ui("encoding packet %j",e),(e.type===j.EVENT||e.type===j.ACK)&&Xn(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)),Ui("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=jd(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},Hi=class n extends Vd.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 qi(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(!Qd(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 Ui("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 Qr(t);case j.DISCONNECT:return t===void 0;case j.CONNECT_ERROR:return typeof t=="string"||Qr(t);case j.EVENT:case j.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&zd.indexOf(t[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},qi=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=Jd(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};Qd=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function Ge(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Wi=C(()=>{});var Zd,el,me,gm,kn,ji=C(()=>{Zr();Wi();Zd=oe(Ft(),1),el=oe(Ye(),1),me=(0,el.default)("socket.io-client:socket"),gm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),kn=class extends Zd.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=[Ge(e,"open",this.onopen.bind(this)),Ge(e,"packet",this.onpacket.bind(this)),Ge(e,"error",this.onerror.bind(this)),Ge(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(gm.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 d=this.ids++;me("emitting packet with ack id %d",d);let u=t.pop();this._registerAckCallback(d,u),o.id=d}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?me("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&&(me("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));me("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]?me("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(me("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(me("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(me("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){me("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,me("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(){me("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){me("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||[];me("emitting event %j",t),e.id!=null&&(me("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,me("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"){me("bad ack %s",e.id);return}delete this.acks[e.id],me("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){me("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(){me("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&&(me("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 zt(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 tl=C(()=>{zt.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};zt.prototype.reset=function(){this.attempts=0};zt.prototype.setMin=function(n){this.ms=n};zt.prototype.setMax=function(n){this.max=n};zt.prototype.setJitter=function(n){this.jitter=n}});var nl,rl,Ee,Sn,sl=C(()=>{Xr();ji();Zr();Wi();tl();nl=oe(Ft(),1),rl=oe(Ye(),1),Ee=(0,rl.default)("socket.io-client:manager"),Sn=class extends nl.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,mt(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 zt({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||Gi;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(Ee("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;Ee("opening %s",this.uri),this.engine=new bn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Ge(t,"open",function(){r.onopen(),e&&e()}),i=a=>{Ee("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Ge(t,"error",i);if(this._timeout!==!1){let a=this._timeout;Ee("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{Ee("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(){Ee("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Ge(e,"ping",this.onping.bind(this)),Ge(e,"data",this.ondata.bind(this)),Ge(e,"error",this.onerror.bind(this)),Ge(e,"close",this.onclose.bind(this)),Ge(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){gt(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){Ee("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new kn(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){Ee("socket %s is still active, skipping close",r);return}this._close()}_packet(e){Ee("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(){Ee("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){Ee("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;Ee("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)Ee("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();Ee("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(Ee("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(Ee("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(Ee("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 er(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=qd(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Zn[s]&&i in Zn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(il("ignoring socket cache for %s",r),c=new Sn(r,e)):(Zn[s]||(il("new io instance for %s",r),Zn[s]=new Sn(r,e)),c=Zn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var ol,il,Zn,al=C(()=>{Gd();sl();ji();ol=oe(Ye(),1);Zr();Xr();il=(0,ol.default)("socket.io-client"),Zn={};Object.assign(er,{Manager:Sn,Socket:kn,io:er,connect:er})});var dt,mm,es,cl=C(()=>{"use strict";al();pe();dt="wsClient",mm=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),es=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",dt,"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=>{E(dt,"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=er(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",dt,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{E(dt,"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=>{E(dt,"event handler threw",i)})});for(let t of mm)e.on(t,r=>{h("error",dt,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",dt,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",dt,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{E(dt,"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",dt,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var nt,ts,dl=C(()=>{"use strict";en();Sa();Ln();cl();pe();nt="serverGateway",ts=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=Rt(),h("info",nt,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new es({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>ka(t,r)});let e=ba();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",nt,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",nt,`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",nt,"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",nt,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return xa(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await Ta(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await Ca(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await Ra(this.config.server_url,e,t,this._getToken())}async getAction(e){return Oa(this.config.server_url,e,this._getToken())}async getApproval(e){return Pa(this.config.server_url,e,this._getToken())}async fireAction(e,t){return Ia(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await Na(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 nn(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return La(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return Da(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return Ba(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return $a(this.config.server_url,e,this._getToken())}async getTasks(e,t){return Sr(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return Ua(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return Fa(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return Ha(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return qa(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Ga(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return Wa(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await Ya(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await ja(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 Ja(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return Va(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Ka(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",nt,"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 Aa(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",nt,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",nt,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){E(nt,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=Rt(),t=await Ea(this.config.server_url,e);_r(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",nt,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){E(nt,"token refresh failed",e)}}_getToken(){return this.token||(this.token=Rt()),this.token}}});import{execFile as ym}from"node:child_process";import{promisify as _m}from"node:util";import{readFileSync as wm,readdirSync as ns,statSync as Ji,openSync as vm,readSync as bm,closeSync as km}from"node:fs";import{join as Xt}from"node:path";import{homedir as ll}from"node:os";async function Sm(){try{if(process.platform==="darwin"){let{stdout:n}=await ul("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=wm(Xt(ll(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function Em(){let n=await Sm();if(!n)return null;try{let{stdout:e}=await ul("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 xm(n,e){let t=[];try{for(let r of ns(n).sort().reverse().slice(0,2)){let s=Xt(n,r);for(let i of ns(s).sort().reverse().slice(0,2)){let o=Xt(s,i);for(let a of ns(o).sort().reverse().slice(0,7)){let c=Xt(o,a);for(let l of ns(c)){if(!l.endsWith(".jsonl"))continue;let d=Xt(c,l);try{t.push({path:d,mtime:Ji(d).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 Tm(n,e){let t=vm(n,"r");try{let r=Ji(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return bm(t,i,0,s,r-s),i.toString("utf-8")}finally{km(t)}}function Cm(){let n=process.env.CODEX_HOME??Xt(ll(),".codex");for(let e of xm(Xt(n,"sessions"),5))try{let t=Tm(e,262144).split(`
215
+ `).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(Ji(e).mtimeMs).toISOString()}}catch{}}catch{}return null}async function fl(){let[n,e]=await Promise.all([Em(),Promise.resolve().then(Cm)]);return{sampled_at:new Date().toISOString(),claude:n,codex:e}}var ul,hl=C(()=>{"use strict";ul=_m(ym)});import{execFileSync as Rm}from"node:child_process";function ss(n){typeof n=="number"&&n>0&&rs.add(n)}function tr(n){typeof n=="number"&&rs.delete(n)}function pl(n,e){try{process.kill(-n,e)}catch{}try{process.kill(n,e)}catch{}}function Yi(n="SIGKILL"){for(let e of rs)pl(e,n);rs.clear()}function gl(n){try{let e=Rm("ps",["-axo","pid=,command="],{encoding:"utf-8",maxBuffer:8388608}),t=process.pid,r=[];for(let s of e.split(`
216
+ `)){let i=s.match(/^\s*(\d+)\s+(.*)$/);if(!i)continue;let o=Number(i[1]),a=i[2];if(o===t)continue;(/[/\s](claude|codex)(\s|$)/.test(a)||/\.local\/bin\/claude/.test(a))&&/\.mio\/workspaces\//.test(a)&&r.push(o)}for(let s of r)pl(s,"SIGKILL");n&&r.length&&n("reaped orphaned runtime processes from a previous daemon",r.length)}catch{}}var rs,is=C(()=>{"use strict";rs=new Set});function _l(n,e,t){if(t){let r=`${n}:${t}`;if(nr.has(r))return;if(nr.set(r,Date.now()),nr.size>500){let s=Date.now()-36e5;for(let[i,o]of nr)o<s&&nr.delete(i)}}rr.set(`${n}:${e}`,Date.now())}function Vi(n){yl.set(n,Date.now());let e=`${n}:`;for(let t of rr.keys())t.startsWith(e)&&rr.delete(t)}function wl(n,e){let t=`${n}:${e}`,r=rr.get(t);if(r===void 0||(rr.delete(t),Date.now()-r>Pm))return!1;let s=yl.get(n)??0;if(Date.now()-s<Am)return!1;let i=ml.get(e)??0;return Date.now()-i<Om?!1:(ml.set(e,Date.now()),!0)}var rr,ml,yl,nr,Am,Om,Pm,Ki=C(()=>{"use strict";rr=new Map,ml=new Map,yl=new Map,nr=new Map,Am=180*1e3,Om=600*1e3,Pm=1800*1e3});var Nt,vl,os,bl=C(()=>{"use strict";pe();Nt="sessionManager",vl=3e4,os=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},vl),h("info",Nt,`Heartbeat timer started (every ${vl/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=>{E(Nt,`Failed to mark session ${t.sessionId} disconnected`,r)}))),h("info",Nt,`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",Nt,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){h("warn",Nt,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,h("info",Nt,"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=>{E(Nt,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&h("debug",Nt,`Sent ${e.length} heartbeat(s)`)}}});var St,as,kl=C(()=>{"use strict";pe();St="workroomCoordinator",as=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",St,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return h("info",St,"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 E(St,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return E(St,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{E(St,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),h("info",St,"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",St,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){E(St,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),h("info",St,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as Xi,unlink as Im,readdir as Nm,stat as Mm}from"fs/promises";import{join as cs}from"path";import{randomBytes as Qi}from"crypto";async function El(n,e){let t=Qi(8).toString("hex"),r=cs(Ut,`action-${n}-${t}${Sl}`),s;try{s=await Xi(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return h("info",Et,"secret file written",{actionId:n,filePath:r}),r}async function sr(n){try{await Im(n),h("info",Et,"secret file deleted",{filePath:n})}catch(e){if(zi(e))return;E(Et,"failed to delete secret file (best-effort)",e)}}async function xl(){let n;try{n=await Nm(Ut)}catch(s){if(zi(s))return;E(Et,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(Sl)),r=0;for(let s of t){let i=cs(Ut,s);try{let o=await Mm(i),a=e-o.mtimeMs;a>=Lm&&(await sr(i),r++,h("info",Et,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(zi(o))continue;E(Et,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&h("info",Et,"TTL scan complete",{scanned:t.length,purged:r})}async function Tl(n){let e=Date.now(),t=Qi(4).toString("hex"),r=cs(Ut,`drain-evidence-${e}-${t}.json`),s;try{s=await Xi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",Et,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function Cl(n){let e=Date.now(),t=Qi(4).toString("hex"),r=cs(Ut,`response-lost-${e}-${t}.json`),s;try{s=await Xi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",Et,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function zi(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var Et,Lm,Sl,ds=C(()=>{"use strict";Qe();pe();Et="secretManager",Lm=600*1e3,Sl=".secret"});import{spawn as $m}from"child_process";import{stat as Dm}from"fs/promises";async function Rl(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return h("warn",Qt,"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",Qt,"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 El(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return E(Qt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=$m(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return E(Qt,"spawn failed",i),r&&sr(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{h("info",Qt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&sr(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{E(Qt,"subprocess error after spawn",i),r&&sr(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),h("info",Qt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var Qt,Al=C(()=>{"use strict";pe();ds();Qt="runtimeAdapter"});var G,Ol,ir,Pl,or,Il,Bm,ls,Zi=C(()=>{"use strict";Ln();pe();Al();ds();G="actionGate",Ol=new Set(["proposed","approved"]),ir=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),Pl="irreversible_no_abort",or=new Set(["transmission_complete","succeeded","canceled","failed"]),Il=15,Bm=8e3,ls=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",G,"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",G,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,h("info",G,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=Bm){if(this.inFlightIrreversible.size===0){h("info",G,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return h("warn",G,"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);E(G,"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 Tl({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",G,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){E(G,"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)&&or.has(r)&&this.gateway.getAction(t).then(s=>{or.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):h("warn",G,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{E(G,"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",G,"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",G,"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",G,"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=>{or.has(s.status)?(h("info",G,"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",G,"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=>{E(G,"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){E(G,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){h("info",G,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){h("warn",G,"action.created: missing action_id in payload \u2014 ignoring");return}h("info",G,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(ir.has(r.status)){h("info",G,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!Ol.has(r.status)){h("info",G,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===Pl?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",G,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&h("info",G,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),h("info",G,"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",G,"approval.decided: missing required fields \u2014 ignoring");return}if(h("info",G,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),h("info",G,"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),ir.has(i.status)){h("info",G,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!Ol.has(i.status)){h("warn",G,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){h("warn",G,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){h("warn",G,"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",G,"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&&ir.has(r),a=i&&or.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&ir.has(c.status)&&(this.pendingApproval.delete(t),h("info",G,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&or.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",G,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let d=await this.gateway.fireAction(r,t);h("info",G,"action fired",{actionId:r,fired_at:d.fired_at}),a=d.action_token,o=!0}catch(d){if(d instanceof Mn&&d.isDefinitiveRejection){E(G,`fire definitively rejected (${d.statusCode} ${d.errorCode}) \u2014 re-querying before cancel`,d);let m=await this.gateway.getAction(r).catch(()=>null);if(!m||ir.has(m.status)){h("info",G,"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(g=>{E(G,"cancel after rejected fire also failed",g)});return}E(G,"fire failed with uncertain error \u2014 reconciling action state",d);let u=await this.gateway.getAction(r).catch(()=>null);if(u?.status==="fired"){h("warn",G,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let m=u.fired_at??new Date().toISOString();await Cl({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(g=>{E(G,"failed to write response-lost evidence (CRITICAL)",g)});return}else{h("warn",G,"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===Pl;c&&this._registerInFlight(e);let l=await Rl({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?(d,u)=>this._onSubprocessExitForDrain(r,d,u):void 0});l.ok||(h("warn",G,"spawn returned not-ok",{actionId:r,reason_code:l.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as Um}from"net";import{chmod as Fm}from"fs/promises";var lt,us,Nl=C(()=>{"use strict";pe();lt="ipcServer",us=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=Um(s=>{this._handleConnection(s)}),this.server.once("error",s=>{E(lt,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Fm(e,384)}catch(s){E(lt,"Failed to chmod IPC socket",s)}h("info",lt,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",lt,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){h("debug",lt,"subprocess connected");let t="";e.on("data",r=>{t+=r.toString("utf8");let s=t.split(`
217
+ `);t=s.pop()??"";for(let i of s){let o=i.trim();o&&this._processLine(o)}}),e.on("error",r=>{E(lt,"IPC socket connection error",r)}),e.on("close",()=>{h("debug",lt,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{h("warn",lt,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){h("warn",lt,"IPC message missing required `type` field \u2014 ignored");return}h("debug",lt,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as Hm}from"http";var eo,qm,Gm,fs,Ml=C(()=>{"use strict";pe();eo="healthServer",qm="127.0.0.1",Gm=7878,fs=class{constructor(e){this.version=e}version;server=null;startTime=Date.now();async listen(e=qm,t=Gm){return new Promise((r,s)=>{this.server=Hm((i,o)=>this._handleRequest(i,o)),this.server.once("error",i=>{E(eo,"Health server startup error",i),s(i)}),this.server.listen(t,e,()=>{h("info",eo,`Health server listening on ${e}:${t}`),r()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",eo,"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 Ll,mkdir as $l}from"node:fs/promises";import{homedir as Wm}from"node:os";import{dirname as jm,join as Dl}from"node:path";function Jm(){return hs||(hs=$l(Bl,{recursive:!0}).then(()=>{},n=>{throw hs=null,n})),hs}function ps(n){return n&&n.replace(/-/g,"").slice(0,8)||"unknown"}function Ym(n){return Dl(Bl,`agent-${ps(n)}.jsonl`)}function ne(n,e,t){let r;try{let i={ts:new Date().toISOString(),agent_id:n,kind:e,...t};r=JSON.stringify(i)+`
218
+ `}catch(i){process.stderr.write(`[agentTrace] serialize error agent=${ps(n)} kind=${e}: ${i.message}
219
+ `);return}let s=Ym(n);Jm().then(()=>Ll(s,r,{encoding:"utf8"})).catch(i=>{if(i.code==="ENOENT"){let o=jm(s);$l(o,{recursive:!0}).then(()=>Ll(s,r,{encoding:"utf8"})).catch(a=>{process.stderr.write(`[agentTrace] append failed agent=${ps(n)} kind=${e}: ${a.message}
220
+ `)});return}process.stderr.write(`[agentTrace] append failed agent=${ps(n)} kind=${e}: ${i.message}
221
+ `)})}var Bl,hs,Mt=C(()=>{"use strict";Bl=Dl(Wm(),".mio","logs"),hs=null});import{readFileSync as Vm,writeFileSync as Km,existsSync as zm}from"fs";import{join as Xm}from"path";function Ul(){return Xm(_e,"agent-inbox-cursor.json")}function Fl(){let n=Ul();if(!zm(n))return{};try{return JSON.parse(Vm(n,"utf-8"))}catch{return{}}}function Qm(n){Nn(),Km(Ul(),JSON.stringify(n,null,2),{mode:384})}function Hl(n,e){return Fl()[`${n}:${e}`]??"0"}function xt(n,e,t){let r=Fl(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,Qm(r))}var to=C(()=>{"use strict";Qe()});import{createServer as Zm}from"http";import{randomBytes as ey,timingSafeEqual as ty}from"crypto";function $e(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function oy(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 gs);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function ay(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:ty(t,r)}async function Ie(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 ql(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??sy,c=i instanceof Set?i:new Set(i),l=ey(32).toString("hex");async function d(p,w){if(p.method!=="POST"||p.url!=="/act"){w.writeHead(404),w.end();return}let k=p.headers.authorization??"",v=`Bearer ${l}`;if(!ay(k,v)){$e(w,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let _;try{_=await oy(p,ry)}catch(Y){if(Y instanceof gs){$e(w,413,{ok:!1,code:"BODY_TOO_LARGE"});return}$e(w,400,{ok:!1,code:"INVALID_JSON"});return}let S;try{S=JSON.parse(_)}catch{$e(w,400,{ok:!1,code:"INVALID_JSON"});return}let P=S.action,x=S.payload!=null&&typeof S.payload=="object"?S.payload:{};if(P!=="attachment"&&Buffer.byteLength(_)>ny){$e(w,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(P)){$e(w,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let O=iy[P];if(!c.has(O)){$e(w,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let W={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 Y=x,re=null;if(o)try{let ue=o.get(e);ue&&typeof x.context_message_id!="string"&&(Y={...x,context_message_id:ue},re=ue)}catch(ue){E(Lt,"contextTracker.get threw (non-fatal)",ue)}let ae=typeof x.target=="string"?x.target:null,V=typeof x.parent_message_id=="string"?x.parent_message_id:null,le=typeof x.content=="string"?x.content.slice(0,120):null;h("info",Lt,"forward send",{agentId:e,target:ae,parent_message_id:V,stamped_context:re!==null,context_message_id:re}),ne(e,"outbound",{action:"send",target:ae,parent_message_id:V,context_message_id:re,context_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:le,content_bytes:typeof x.content=="string"?x.content.length:0}),await cy(w,r,W,Y,a),w.statusCode<300&&Vi(e),ne(e,"outbound_done",{action:"send",status:w.statusCode,duration_ms:Date.now()-J})}else if(P==="reply"){let Y=typeof x.target=="string"?x.target:null,re=typeof x.parent_message_id=="string"?x.parent_message_id:null,ae=typeof x.content=="string"?x.content.slice(0,120):null;ne(e,"outbound",{action:"reply",target:Y,parent_message_id:re,parent_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:ae}),await dy(w,r,W,x,a),w.statusCode<300&&Vi(e),ne(e,"outbound_done",{action:"reply",status:w.statusCode,duration_ms:Date.now()-J})}else if(P==="history")await ly(w,r,W,x,a);else if(P==="task"){let Y=typeof x.op=="string"?x.op:null;ne(e,"task",{action:Y,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 fy(w,r,W,x,a),ne(e,"task_done",{action:Y,status:w.statusCode,duration_ms:Date.now()-J})}else P==="reminder"?await py(w,r,W,x,a):P==="action"?await my(w,r,W,x,a):P==="react"?await yy(w,r,W,x,a):P==="attachment"?await _y(w,r,W,x,a):P==="profile"?await wy(w,r,W,x,a):await vy(w,r,W,e,x,a)}catch(Y){E(Lt,"upstream forwarding error",Y);let re=Y instanceof Error&&Y.name==="AbortError";$e(w,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:re?`upstream timed out after ${a}ms`:String(Y)})}}let u=Zm((p,w)=>{d(p,w).catch(k=>{E(Lt,"unhandled request error",k),w.writeHead(500),w.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((p,w)=>{u.once("error",k=>{E(Lt,"agent proxy startup error",k),w(k)}),u.listen(0,"127.0.0.1",()=>{let k=u.address(),v=typeof k=="object"&&k?k.port:0;h("info",Lt,"agent proxy listening",{agentId:e,launchId:t,port:v}),p(v)})})}`,proxyToken:l,close:()=>new Promise(p=>{u.close(()=>{h("info",Lt,"agent proxy stopped",{agentId:e,launchId:t}),p()})})}}async function cy(n,e,t,r,s){let i=await Ie(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ne(n,i)}async function dy(n,e,t,r,s){let i=await Ie(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ne(n,i)}async function ly(n,e,t,r,s){let i=by(r),o=await Ie(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Ne(n,o)}async function fy(n,e,t,r,s){let i=String(r.op??""),o=uy[i];if(!o){$e(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 l=c.toString(),d=await Ie(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Ne(n,d)}else{let{op:c,...l}=r,d=await Ie(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Ne(n,d)}}async function py(n,e,t,r,s){let i=String(r.op??""),o=hy[i];if(!o){$e(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 l=c.toString(),d=await Ie(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Ne(n,d)}else{let{op:c,...l}=r,d=await Ie(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Ne(n,d)}}async function my(n,e,t,r,s){let i=String(r.op??""),o=gy[i];if(!o){$e(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 l=c.toString(),d=await Ie(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Ne(n,d)}else{let{op:c,...l}=r,d=await Ie(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Ne(n,d)}}async function yy(n,e,t,r,s){let i=await Ie(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ne(n,i)}async function _y(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await Ie(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Ne(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await Ie(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Ne(n,a);return}$e(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function wy(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,l=await Ie(c,{method:"GET",headers:t},s);await Ne(n,l);return}if(i==="update"){let{op:o,...a}=r,c=await Ie(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Ne(n,c);return}$e(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function vy(n,e,t,r,s,i){let o=String(s.channel??""),a=Hl(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),l=await Ie(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!l.ok){await Ne(n,l);return}let d=await l.json(),u=d.messages??[];if(u.length>0){let g=u.reduce((f,p)=>{let w=0n;try{w=BigInt(String(p.seq??"0"))}catch{E(Lt,"bad seq from upstream",{seq:p.seq}),w=0n}return w>f?w:f},0n);g>0n&&xt(r,o,g.toString())}let m=JSON.stringify(d);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Ne(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{}$e(n,e.status,{ok:!1,code:r,message:s})}function by(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 Lt,ny,ry,sy,iy,gs,uy,hy,gy,Gl=C(()=>{"use strict";Ki();pe();Mt();to();Lt="agentProxy",ny=1024*1024,ry=12*1024*1024,sy=15e3,iy={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};gs=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};uy={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"}};hy={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"}};gy={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as Wl,writeFile as no,chmod as jl}from"fs/promises";import{existsSync as Jl}from"fs";import{join as ar,resolve as ky,dirname as Sy}from"path";import{spawnSync as Ey}from"child_process";import{fileURLToPath as xy}from"url";function cr(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function $t(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function Ty(n){let e=Sy(xy(import.meta.url))+"/../..",t=n?.localTsxPath??ky(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Jl(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??Cy)();return i||"tsx"}function Cy(){let e=Ey("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Jl(e)?e:null}function ro(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:Ty(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function Yl(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??ro(),c=ar(r,".mio");await Wl(c,{recursive:!0,mode:493});let l=await ql({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:d,proxyToken:u}=l;try{let m=cr(e),g=cr(t),f=ar(_e,"agent-proxy-tokens",m),p=ar(f,`${g}.token`);await Wl(f,{recursive:!0,mode:448}),await no(p,u,{encoding:"utf8",mode:384}),await jl(p,384);let w=o.join(","),k=Ry({execContext:a,proxyUrl:d,tokenFile:p,capabilityStr:w}),v=ar(c,"mio");await no(v,k,{encoding:"utf8",mode:493}),await jl(v,493),await no(ar(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let _={...process.env},S=_.PATH??"";return _.PATH=S?`${c}:${S}`:c,delete _.CLAUDECODE,{mioDir:c,spawnEnv:_,proxyHandle:l}}catch(m){throw await l.close().catch(()=>{}),m}}function Ry(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${$t(t)} MIO_AGENT_PROXY_TOKEN_FILE=${$t(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${$t(s)}`,o;return e.mode==="npm"?o=`exec ${$t(e.nodePath)} ${$t(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${$t(e.tsxPath)} ${$t(e.cliEntryPath)} agentcli "$@"`:o=`exec ${$t(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
222
+ `)}var Vl=C(()=>{"use strict";Qe();Gl()});function Kl(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 Ay,Oy,Py,Iy,Ny,My,zl,Xl=C(()=>{"use strict";Ay=`## Role: Product Manager
222
223
 
223
224
  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.
224
225
 
@@ -253,7 +254,7 @@ Deliberative on scope, decisive on next step. Default to "let's get one concrete
253
254
  - Bundle everything into one giant announcement. One concrete deliverable per message = one task.
254
255
 
255
256
  ### Posting cadence
256
- When delegating, post each \`@Assignee <deliverable>\` line as its own standalone message before any context dump. Status updates on owned tasks should be one line each, never combined.`,ky=`## Role: Engineer
257
+ When delegating, post each \`@Assignee <deliverable>\` line as its own standalone message before any context dump. Status updates on owned tasks should be one line each, never combined.`,Oy=`## Role: Engineer
257
258
 
258
259
  You are an engineer on this team. Your job is to build, fix, and harden the software \u2014 and to be honest about what's actually working vs what just looks like it's working.
259
260
 
@@ -287,7 +288,7 @@ Pragmatic. Prefer the boring correct solution. When two approaches are roughly e
287
288
  - Apologise for limitations. Just state what's done and what's left.
288
289
 
289
290
  ### Posting cadence
290
- During implementation, send three-beat updates: "starting on X", "found Y / decided Z mid-way", "done with X" or "blocked on W". Never describe what you did at the end as a wall of bullets.`,Sy=`## Role: Designer
291
+ During implementation, send three-beat updates: "starting on X", "found Y / decided Z mid-way", "done with X" or "blocked on W". Never describe what you did at the end as a wall of bullets.`,Py=`## Role: Designer
291
292
 
292
293
  You are the designer on this team. Your job is to make sure what we ship is intuitive, coherent, and respectful of the person on the other end of the screen.
293
294
 
@@ -320,7 +321,7 @@ Reference-driven. When in doubt, point to a precedent \u2014 either in this prod
320
321
  - Design the happy path only.
321
322
 
322
323
  ### Posting cadence
323
- When iterating between options, send each option as its own message so teammates can react to each. Don't put 3 design directions in one message.`,Ey=`## Role: Researcher
324
+ When iterating between options, send each option as its own message so teammates can react to each. Don't put 3 design directions in one message.`,Iy=`## Role: Researcher
324
325
 
325
326
  You are the researcher on this team. Your job is to find out what's true, summarise it clearly, and cite where it came from.
326
327
 
@@ -353,7 +354,7 @@ Evidence-led. Form an opinion only after you've seen the data; revise the opinio
353
354
  - Recommend an action without separating it from the evidence ("the data shows X; my read is therefore Y").
354
355
 
355
356
  ### Posting cadence
356
- When investigating, surface a finding as soon as you have it \u2014 don't wait to assemble a full report. Each finding is its own message; the synthesis comes at the end.`,xy=`## Role: Ops / SRE
357
+ When investigating, surface a finding as soon as you have it \u2014 don't wait to assemble a full report. Each finding is its own message; the synthesis comes at the end.`,Ny=`## Role: Ops / SRE
357
358
 
358
359
  You are the ops / SRE engineer on this team. Your job is to keep things running, make outages short and rare, and leave the system better-instrumented than you found it.
359
360
 
@@ -386,7 +387,7 @@ Cautious by default \u2014 production systems are real. Move faster on reversibl
386
387
  - Treat a fix as done until you've watched it stay healthy for at least one cycle.
387
388
 
388
389
  ### Posting cadence
389
- During a procedure (deploy / rollback / incident), post each step as it happens: "starting maintenance window", "pm2 restarted", "health check passing". Real-time visibility matters more than tidy summary.`,Ty=`## Role: Generalist
390
+ During a procedure (deploy / rollback / incident), post each step as it happens: "starting maintenance window", "pm2 restarted", "health check passing". Real-time visibility matters more than tidy summary.`,My=`## Role: Generalist
390
391
 
391
392
  You are a generalist teammate on this Mio team. You don't have a single specialty \u2014 you do whatever the current situation needs, well.
392
393
 
@@ -417,12 +418,12 @@ Take initiative on small, reversible things. Escalate to a human or specialist f
417
418
  - Stretch one request into a sprawling project. Stay scoped.
418
419
 
419
420
  ### Posting cadence
420
- Match the cadence of whoever you're talking to. When in doubt: send each logical step as its own short message.`,Gl={product_manager:by,engineer:ky,designer:Sy,researcher:Ey,ops:xy,general:Ty}});function $y(n){if(!n)return"\u2014";let e=n.trim();if(!e)return"\u2014";let t=e.match(/^[\s\S]{1,240}?[.!?。!?\n]/);return t?t[0].replace(/\s+$/,""):e.slice(0,140)}function Dy(n){let e=n.roster;if(!e||e.inChannel.length===0&&e.otherInWorkroom.length===0)return"";let t=(i,o)=>{let a="@"+(i.display_name||i.id);return`- ${o?`${a} (you, ${i.kind}, ${i.role})`:`${a} (${i.kind}, ${i.role})`} \u2014 ${$y(i.description)}`},r=e.inChannel.length===0?"- (no other members recorded in this channel yet)":e.inChannel.map(i=>t(i,i.id===n.agentId)).join(`
421
+ Match the cadence of whoever you're talking to. When in doubt: send each logical step as its own short message.`,zl={product_manager:Ay,engineer:Oy,designer:Py,researcher:Iy,ops:Ny,general:My}});function Wy(n){if(!n)return"\u2014";let e=n.trim();if(!e)return"\u2014";let t=e.match(/^[\s\S]{1,240}?[.!?。!?\n]/);return t?t[0].replace(/\s+$/,""):e.slice(0,140)}function jy(n){let e=n.roster;if(!e||e.inChannel.length===0&&e.otherInWorkroom.length===0)return"";let t=(i,o)=>{let a="@"+(i.display_name||i.id);return`- ${o?`${a} (you, ${i.kind}, ${i.role})`:`${a} (${i.kind}, ${i.role})`} \u2014 ${Wy(i.description)}`},r=e.inChannel.length===0?"- (no other members recorded in this channel yet)":e.inChannel.map(i=>t(i,i.id===n.agentId)).join(`
421
422
  `);return`${e.channelName?`## In #${e.channelName} right now`:"## In this channel right now"}
422
423
 
423
424
  ${r}
424
425
 
425
- For teammates in other channels, load the \`mio-team\` skill.`}function jl(n){let{agentId:e,handle:t,displayName:r,description:s,role:i,serverId:o,computer:a,hostname:c,os:l,workspace:d}=n,u=n.presetRole??ql(r,`${i??""} ${s}`),m=Gl[u],p=s&&s.trim()?`## Additional context from your operator
426
+ For teammates in other channels, load the \`mio-team\` skill.`}function Ql(n){let{agentId:e,handle:t,displayName:r,description:s,role:i,serverId:o,computer:a,hostname:c,os:l,workspace:d}=n,u=n.presetRole??Kl(r,`${i??""} ${s}`),m=zl[u],g=s&&s.trim()?`## Additional context from your operator
426
427
 
427
428
  ${s.trim()}`:"",f=`## Runtime context
428
429
 
@@ -437,64 +438,64 @@ This is authoritative \u2014 do NOT infer your identity, host, or workspace from
437
438
  - OS: ${l}
438
439
  - Workspace: ${d}
439
440
 
440
- 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\`.`,_=Dy(n),S=500,v=n.persona?n.persona.trim():"",y=v.length>S?v.slice(0,S).replace(/\s+\S*$/,"")+"\u2026":v,k=y.length>0?`## What I've learned (from past interactions)
441
+ When someone writes ${t} they are addressing YOU.`,p=`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\`.`,w=jy(n),k=500,v=n.persona?n.persona.trim():"",_=v.length>k?v.slice(0,k).replace(/\s+\S*$/,"")+"\u2026":v,S=_.length>0?`## What I've learned (from past interactions)
441
442
 
442
- ${y}`:"";return[g,Cy,Oy,Ay,Py,Iy,m,p,f,_,k,Ly,Ny,n.runtime==="codex"?My:"",Ry].filter(x=>x&&x.length>0).join(`
443
+ ${_}`:"";return[p,Ly,By,Dy,Uy,Fy,m,g,f,w,S,Gy,Hy,n.runtime==="codex"?qy:"",$y].filter(x=>x&&x.length>0).join(`
443
444
 
444
445
  `)+`
445
- `}var Cy,Ry,Ay,Oy,Py,Iy,Ny,My,Ly,Jl=C(()=>{"use strict";Wl();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.',Ry='## 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- Work assigned TO YOU by a human: create the task yourself with `mio task create \u2026 --self --attach <msg id>` (see Task protocol). To DELEGATE to a teammate, send a short main-channel message tagging exactly one assignee (`@Backend \u5B9E\u73B0 X`) \u2014 the handoff pipeline converts it to a task and wakes them. `mio task claim #N` is ONLY for picking up an UNASSIGNED todo task.\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- Is the message you are answering FROM THE MAIN CHANNEL (its envelope has NO [thread context])? Then your reply MUST go to the main channel via `mio message send` \u2014 NEVER into a task thread. Humans watch the main channel; an answer posted into a thread is invisible to them (07-08: PM answered a main-channel question inside an unrelated task thread and the human never saw it).\n- Are you about to END your turn on a promise ("\u6211\u6765\u505AX" / "\u63A5\u4E0B\u6765\u6211\u4F1A\u2026" / "\u6211\u9A6C\u4E0A\u5F00\u59CB") without having actually started? STOP. Nothing will re-wake you \u2014 do the first concrete step NOW and report it, or state precisely what input you are blocked on.\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"',Ay=`## Task protocol (how you manage your own work)
446
+ `}var Ly,$y,Dy,By,Uy,Fy,Hy,qy,Gy,Zl=C(()=>{"use strict";Xl();Ly='## 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.',$y='## 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- Work assigned TO YOU by a human: create the task yourself with `mio task create \u2026 --self --attach <msg id>` (see Task protocol). To DELEGATE to a teammate, send a short main-channel message tagging exactly one assignee (`@Backend \u5B9E\u73B0 X`) \u2014 the handoff pipeline converts it to a task and wakes them. `mio task claim #N` is ONLY for picking up an UNASSIGNED todo task.\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- Is the message you are answering FROM THE MAIN CHANNEL (its envelope has NO [thread context])? Then your reply MUST go to the main channel via `mio message send` \u2014 NEVER into a task thread. Humans watch the main channel; an answer posted into a thread is invisible to them (07-08: PM answered a main-channel question inside an unrelated task thread and the human never saw it).\n- Are you about to END your turn on a promise ("\u6211\u6765\u505AX" / "\u63A5\u4E0B\u6765\u6211\u4F1A\u2026" / "\u6211\u9A6C\u4E0A\u5F00\u59CB") without having actually started? STOP. Nothing will re-wake you \u2014 do the first concrete step NOW and report it, or state precisely what input you are blocked on.\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=`## Task protocol (how you manage your own work)
446
447
 
447
448
  Server no longer auto-creates tasks from human messages \u2014 YOU decide. When a human message assigns you concrete work (build/fix/change/run something with a deliverable):
448
449
 
449
- 1. **Create the task yourself, immediately, in the same turn**: \`mio task create --channel "#<channel>" --title "<short title>" --attach <the message id from the envelope> --self\`. The task anchors a thread under the human's message; do your work-progress posts THERE (\`mio message reply\`). Questions/chat/status pings are NOT tasks \u2014 just answer.
450
+ 1. **Create the task, then take EVERYTHING into its thread.** In the same turn: \`mio task create --channel "#<channel>" --title "<short title>" --attach <the message id from the envelope> --self\`. Then post EXACTLY ONE short line in the MAIN channel \u2014 an acknowledgement only: "\u6536\u5230,\u5728 #N \u91CC\u505A" (or "\u6536\u5230,\u65B9\u6848\u6211\u53D1\u5728 #N \u91CC\u4E86"). Every subsequent word about this task \u2014 clarifying questions, plans, progress, options, drafts, the final result, images \u2014 goes into the task THREAD via \`mio message reply --parent <the task's parent message id>\`, NOT the main channel. The main channel must stay a clean stream of one-line acks + milestones; the thread holds the whole conversation. Questions/chat/status pings that are NOT tasks \u2014 just answer inline, no task.
450
451
  2. **Queue discipline** (your envelope includes your live task panel \u2014 trust it, not memory):
451
452
  - Already working on #M and the new work RELATES to it \u2192 reply in main channel: "\u6211\u6B63\u5728 #M,\u8FD9\u4E2A\u548C\u5B83\u76F8\u5173,\u5B8C\u6210\u540E\u63A5\u7740\u505A" \u2192 create the task with --self anyway (it queues as yours).
452
453
  - New work UNRELATED to #M \u2192 same: create it --self, tell the human "\u5148\u505A\u5B8C #M,#N \u6392\u5728\u540E\u9762" \u2014 you will be woken automatically when #M closes. NEVER silently absorb a request; every assignment gets an explicit one-line decision reply in the MAIN channel.
453
454
  3. **Closing discipline**: finishing the work IS NOT the end of the turn \u2014 run \`mio task update #N --channel <chan> --status done\` in the SAME turn you deliver. A task left in_progress after delivery is a bug you caused (07-07: #5-#8 stranded for a day).
454
455
  4. **Stale tasks in your panel** (marked \u6EDE\u7559): either finish+close them or say in their thread why they are blocked. Never ignore them.
455
- 5. **Waiting on the human**: if you asked a question and cannot proceed, say so in the task thread ("\u7B49\u4F60\u786E\u8BA4 X \u624D\u80FD\u7EE7\u7EED") \u2014 and repeat the ask if the human's next message ignores it.`,Oy="## 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`.",Py=`## System-event wakes
456
+ 5. **Waiting on the human**: if you asked a question and cannot proceed, say so in the task thread ("\u7B49\u4F60\u786E\u8BA4 X \u624D\u80FD\u7EE7\u7EED") \u2014 and repeat the ask if the human's next message ignores it.`,By="## 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 decide whether human-assigned work becomes a task** (see Task protocol). When you take on work, create the task and move the whole conversation into its thread \u2014 the main channel only gets your one-line ack. You may also be woken by `[system event: task.assigned to you]` when a human dispatches a task to you; act on it the same way \u2014 work in its thread.\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
457
 
457
458
  A \`[system event: ...]\` wake = task status changed / assigned / new in channel.
458
459
  Post a brief status only if something meaningful actually changed worth telling
459
460
  the team. Otherwise stay silent. Never re-ack the same event twice; never fake
460
- activity.`,Iy=`## Posting cadence
461
+ activity.`,Fy=`## Posting cadence
461
462
 
462
463
  Multi-step work = multiple short messages at natural breakpoints (1\u20133 sentences each), NOT one bundled report at the end. One message per logical step. Final outcome (done / blocked / needs decision) is its own message. Don't post unless real progress happened.
463
464
 
464
- NEVER announce future work and then stop ("\u63A5\u4E0B\u6765\u6211\u4F1A\u8C03 X" and end the turn). Nothing re-wakes you after your turn ends \u2014 a promise without action simply evaporates and the human waits forever. Either DO the work in this turn (then report the result), or if it genuinely must wait, say exactly what you need to proceed (a file, a decision, an @mention when ready). "\u6211\u9A6C\u4E0A\u5F00\u59CB" as a turn-ending line is forbidden.`,Ny="## Your skills (load via the Skill tool when needed; don't pre-load)\n\n- `mio-messaging` \u2014 read/send/reply messages\n- `mio-tasks` \u2014 list/claim/update tasks (the board forms tasks automatically)\n- `mio-reminders` \u2014 schedule/snooze/cancel reminders\n- `mio-attachments` \u2014 upload/download files\n- `mio-profile` \u2014 view/update profile\n- `mio-team` \u2014 roster lookup (channel + workroom)\n- `mio-memory` \u2014 MEMORY.md, persona.md, companion graph",My='## Codex runtime Mio guide\n\nCodex cannot load Claude skills. Use these commands directly when you need to communicate or update the board. Run them silently; user-facing messages must stay natural and never mention commands.\n\n### Messages\n\nMain-channel message:\n\n```bash\nmio message send --target "#channel-name" <<\'EOF\'\n\u77ED\u6D88\u606F\u6B63\u6587\nEOF\n```\n\nThread reply. Use this whenever the inbound context includes `[thread context ...]` or the work belongs to an assigned task:\n\n```bash\nmio message reply --parent <full-parent-message-uuid> --target "#channel-name" <<\'EOF\'\n\u77ED\u6D88\u606F\u6B63\u6587\nEOF\n```\n\nUse the full `id=...` UUID from the inbound header for `--parent`, not the short `msg=...` value.\n\n### Tasks\n\n```bash\nmio task list --channel "#channel-name"\nmio task claim #5 --channel "#channel-name" # ONLY for an UNASSIGNED todo task you voluntarily pick up\nmio task update #5 --channel "#channel-name" --status done\n```\n\nA task assigned TO you is born already owned by you and already `in_progress`. When you get the `[system event: task #N assigned to you]` wake, do NOT list, claim, or set `in_progress` \u2014 that is your start signal. Just begin: post progress in its thread, do the work, post the result, then mark it `done`. (On a deliverable, the platform may route your `done` through a quick independent review before it closes \u2014 that\'s automatic; if it bounces back with feedback, fix it and set `done` again. You may also be woken to review a teammate\'s task \u2014 the wake explains how.) `claim` is ONLY for an UNASSIGNED `todo` task (no owner) that you choose to pick up. When you are PM/coordinator delegating work, send separate short main-channel `@Assignee deliverable title` messages, one per independent task; the platform creates the tasks automatically.\n\n### Attachments (images, files)\n\nTo share a file (image, avatar, diagram, SVG), attach it directly IN the send with `--attach-file` \u2014 ONE command that uploads AND displays it together:\n\n```bash\nmio message send --target "#channel-name" --attach-file ./avatar.png <<\'EOF\'\n\u8FD9\u662F\u4F60\u8981\u7684\u5934\u50CF\u3002\nEOF\n```\n\nIn a task thread, reply with it: `mio message reply --parent <full-message-uuid> --target "#channel-name" --attach-file ./avatar.png <<\'EOF\' \u2026 EOF`. `--attach-file` is repeatable. Supported images: jpg/jpeg/png/heic/webp/gif.\n\n**Do NOT use `mio attachment upload` by itself to share a file** \u2014 uploading alone does NOT display anything; the file stays invisible to everyone. That is the #1 mistake. Only `--attach-file` (or `--attachment <id>` with an id you already hold) actually shows it. Never say "\u5DF2\u53D1\u4E0A\u6765 / done / \u53D1\u6765\u4E86" about a file unless that send command succeeded. To inspect an existing one: `mio attachment view <attachment_id> [--out ./file.png]`.',Ly=`## Startup and memory
465
+ NEVER announce future work and then stop ("\u63A5\u4E0B\u6765\u6211\u4F1A\u8C03 X" and end the turn). Nothing re-wakes you after your turn ends \u2014 a promise without action simply evaporates and the human waits forever. Either DO the work in this turn (then report the result), or if it genuinely must wait, say exactly what you need to proceed (a file, a decision, an @mention when ready). "\u6211\u9A6C\u4E0A\u5F00\u59CB" as a turn-ending line is forbidden.`,Hy="## Your skills (load via the Skill tool when needed; don't pre-load)\n\n- `mio-messaging` \u2014 read/send/reply messages\n- `mio-tasks` \u2014 list/claim/update tasks (the board forms tasks automatically)\n- `mio-reminders` \u2014 schedule/snooze/cancel reminders\n- `mio-attachments` \u2014 upload/download files\n- `mio-profile` \u2014 view/update profile\n- `mio-team` \u2014 roster lookup (channel + workroom)\n- `mio-memory` \u2014 MEMORY.md, persona.md, companion graph",qy='## Codex runtime Mio guide\n\nCodex cannot load Claude skills. Use these commands directly when you need to communicate or update the board. Run them silently; user-facing messages must stay natural and never mention commands.\n\n### Messages\n\nMain-channel message:\n\n```bash\nmio message send --target "#channel-name" <<\'EOF\'\n\u77ED\u6D88\u606F\u6B63\u6587\nEOF\n```\n\nThread reply. Use this whenever the inbound context includes `[thread context ...]` or the work belongs to an assigned task:\n\n```bash\nmio message reply --parent <full-parent-message-uuid> --target "#channel-name" <<\'EOF\'\n\u77ED\u6D88\u606F\u6B63\u6587\nEOF\n```\n\nUse the full `id=...` UUID from the inbound header for `--parent`, not the short `msg=...` value.\n\n### Tasks\n\n```bash\nmio task list --channel "#channel-name"\nmio task claim #5 --channel "#channel-name" # ONLY for an UNASSIGNED todo task you voluntarily pick up\nmio task update #5 --channel "#channel-name" --status done\n```\n\nA task assigned TO you is born already owned by you and already `in_progress`. When you get the `[system event: task #N assigned to you]` wake, do NOT list, claim, or set `in_progress` \u2014 that is your start signal. Just begin: post progress in its thread, do the work, post the result, then mark it `done`. (On a deliverable, the platform may route your `done` through a quick independent review before it closes \u2014 that\'s automatic; if it bounces back with feedback, fix it and set `done` again. You may also be woken to review a teammate\'s task \u2014 the wake explains how.) `claim` is ONLY for an UNASSIGNED `todo` task (no owner) that you choose to pick up. When you are PM/coordinator delegating work, send separate short main-channel `@Assignee deliverable title` messages, one per independent task; the platform creates the tasks automatically.\n\n### Attachments (images, files)\n\nTo share a file (image, avatar, diagram, SVG), attach it directly IN the send with `--attach-file` \u2014 ONE command that uploads AND displays it together:\n\n```bash\nmio message send --target "#channel-name" --attach-file ./avatar.png <<\'EOF\'\n\u8FD9\u662F\u4F60\u8981\u7684\u5934\u50CF\u3002\nEOF\n```\n\nIn a task thread, reply with it: `mio message reply --parent <full-message-uuid> --target "#channel-name" --attach-file ./avatar.png <<\'EOF\' \u2026 EOF`. `--attach-file` is repeatable. Supported images: jpg/jpeg/png/heic/webp/gif.\n\n**Do NOT use `mio attachment upload` by itself to share a file** \u2014 uploading alone does NOT display anything; the file stays invisible to everyone. That is the #1 mistake. Only `--attach-file` (or `--attachment <id>` with an id you already hold) actually shows it. Never say "\u5DF2\u53D1\u4E0A\u6765 / done / \u53D1\u6765\u4E86" about a file unless that send command succeeded. To inspect an existing one: `mio attachment view <attachment_id> [--out ./file.png]`.',Gy=`## Startup and memory
465
466
 
466
467
  1. On every startup, read \`MEMORY.md\` in your cwd first. It is your recovery point after context compression or sleep.
467
468
  2. If this turn includes an incoming message, decide whether it needs a reply and handle it.
468
469
  3. If there is no incoming message, stop and wait. New messages may be delivered automatically.
469
470
  4. Complete ALL your work before stopping \u2014 don't leave a half-finished thought.
470
471
 
471
- 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 Yl(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(d){n.onError&&n.onError(d instanceof Error?d:new Error(String(d)),o);return}if(typeof a!="object"||a===null)return;let c=a,l=c.type;if(typeof l=="string"){if(l==="system"&&c.subtype==="compact_boundary"){r(n.onCompact,"<onCompact>");return}if(l==="system"&&c.subtype==="init"){let d=c.session_id;typeof d=="string"&&d.length>0&&(t.has(d)||(t.add(d),r(n.onSessionId,"<onSessionId>",d)));return}if(l==="result"){let d=c.usage;if(n.onUsage&&d&&typeof d=="object"){let u=d,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,p=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>",p)}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(`
472
- `),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var Vl=C(()=>{"use strict"});import{existsSync as En}from"node:fs";import{execFileSync as fs}from"node:child_process";import{homedir as By}from"node:os";function xn(){let n=process.env.MIO_CLAUDE_PATH;if(n&&En(n))return n;for(let e of Uy)if(En(e))return e;try{let e=fs("/usr/bin/which",["claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&En(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=fs(e,["-lc","command -v claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&En(t))return t}catch{}try{let e=fs("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/claude`;if(En(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=fs("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/claude`;if(En(s))return s}}catch{}return null}function zl(){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(`
473
- `)}var Zi,Uy,hs=C(()=>{"use strict";Zi=By(),Uy=["/Applications/cmux.app/Contents/Resources/bin/claude",`${Zi}/.local/bin/claude`,`${Zi}/.claude/local/claude`,`${Zi}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as Fy}from"child_process";function Kl(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=Fy,maxRestarts:c=5,presenceTracker:l,agentId:d}=n;function u(w){if(!(!l||!d))try{l.set(d,w)}catch(b){process.stderr.write(`[claudeStreamHost] presence(${w}) error: ${b.message}
474
- `)}}function m(w,b){d&&ne(d,w,b)}let p=0,f=n.claudeCommand??xn()??"claude",g=null,_=n.sessionId,S=!1,v=[],y=!1,k=0,P,x,O,W,J,Y,re;function ae(w){let b=["--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",t,"--disallowed-tools",Hy,"--append-system-prompt-file",r,"--mcp-config",s,"--setting-sources","user,project,local","--chrome"];return w&&b.push("--resume",w),b}function V(w,b){let T={type:"user",message:{role:"user",content:[{type:"text",text:w}]}};return b!==void 0&&(T.session_id=b),JSON.stringify(T)+`
475
- `}function le(w,b){if(!g||!g.stdin)return;let T=V(w,b);h("debug","claudeStreamHost","injected user turn",{bytes:T.length}),m("inject",{bytes:T.length,content_bytes:w.length,resume:b!==void 0}),u("thinking");try{g.stdin.write(T)}catch(D){process.stderr.write(`[claudeStreamHost] stdin write error (will restart): ${D.message}
476
- `);return}re?.(w)}function ue(){k=0,m("boundary",{pending_queue_len:v.length});try{P?.()}catch(w){process.stderr.write(`[claudeStreamHost] onBoundary callback error: ${w.message}
477
- `)}if(v.length>0){let w=v.length,b=v.splice(0,v.length).join(`
478
- `);m("coalesce_flush",{coalesced_count:w,bytes:b.length}),le(b,_)}else S=!1,u("idle")}function $(w){let b=ae(w);h("info","claudeStreamHost","spawning claude",{command:f,argsCount:b.length,cwd:e,resume:!!w}),p=Date.now(),m("spawn",{command:f,args_count:b.length,resume:!!w,resume_session_id:w??null,restart_count:k}),u("starting"),g&&(g.stdout?.removeAllListeners(),g.stderr?.removeAllListeners());let T=a(f,b,{cwd:e,env:i,stdio:["pipe","pipe","pipe"]});g=T,T.stdin?.on("error",I=>{T===g&&process.stderr.write(`[claudeStreamHost] stdin error (will restart): ${I.message}
479
- `)});let D=Yl({onSessionId:I=>{if(T!==g)return;_=I;let U=p?Date.now()-p:null;h("info","claudeStreamHost","session id captured",{sessionId:I,duration_ms:U}),m("session_ready",{session_id:I,spawn_duration_ms:U}),u("idle");try{O?.(I)}catch(K){process.stderr.write(`[claudeStreamHost] onSessionId callback error: ${K.message}
480
- `)}},onResultError:I=>{if(T===g){h("warn","claudeStreamHost","turn ended with error",{message:I.slice(0,120)});try{x?.(I)}catch(U){process.stderr.write(`[claudeStreamHost] onTurnError callback error: ${U.message}
481
- `)}}},onCompact:()=>{if(T===g){h("info","claudeStreamHost","context auto-compacted (compact_boundary)");try{W?.()}catch(I){process.stderr.write(`[claudeStreamHost] onCompact callback error: ${I.message}
482
- `)}}},onUsage:I=>{if(T===g){try{J?.({inputTokens:I.inputTokens??0,outputTokens:I.outputTokens??0,cacheReadTokens:I.cacheReadTokens??0,cacheCreationTokens:I.cacheCreationTokens??0})}catch{}m("usage",{runtime:"claude",model:t,input_tokens:I.inputTokens??null,output_tokens:I.outputTokens??null,cache_read_tokens:I.cacheReadTokens??null,cache_creation_tokens:I.cacheCreationTokens??null,duration_ms:I.durationMs??null,total_cost_usd:I.totalCostUsd??null})}},onBoundary:()=>{T===g&&(h("debug","claudeStreamHost","turn boundary",{}),ue())},onError:(I,U)=>{process.stderr.write(`[claudeStreamHost] parser error on "${U}": ${I.message}
483
- `)}});T.stdout?.on("data",I=>{T===g&&D.feed(typeof I=="string"?I:I.toString("utf8"))});let q="";T.stderr?.on("data",I=>{if(T!==g)return;q+=typeof I=="string"?I:I.toString("utf8");let U;for(;(U=q.indexOf(`
484
- `))!==-1;){let K=q.slice(0,U).trimEnd();q=q.slice(U+1),K.length>0&&h("warn","claudeStreamHost","claude stderr",{line:K})}}),T.on("exit",I=>{T===g&&Q(I)}),T.on("error",I=>{process.stderr.write(`[claudeStreamHost] spawn error: ${I.message}
485
- `)})}function Q(w){if(!y){if(k++,k>c){E("claudeStreamHost","giving up after max restarts",{restartCount:k}),process.stderr.write(`[claudeStreamHost] gave up after ${c} restarts (code=${w})
486
- `);try{Y?.(w)}catch(b){process.stderr.write(`[claudeStreamHost] onExit callback error: ${b.message}
487
- `)}return}if(h("warn","claudeStreamHost","claude exited",{code:w,willRestart:!0,restartCount:k}),m("exit",{code:w,will_restart:!0,restart_count:k}),process.stderr.write(`[claudeStreamHost] unexpected exit (code=${w}), restarting (attempt ${k}/${c})...
488
- `),S=!1,$(_),v.length>0){let b=v.splice(0,v.length).join(`
489
- `);S=!0,le(b,_)}}}return{start(){$(_),S=!0,le(o,_)},enqueueUserTurn(w){S?v.push(w):(S=!0,le(w,_))},stop(){if(y=!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){O=w},onCompact(w){W=w},onTurnUsage(w){J=w},onExit(w){Y=w},onInjected(w){re=w}}}var Hy,Xl=C(()=>{"use strict";Vl();ge();Mt();hs();Hy=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(",")});import{existsSync as Tn}from"node:fs";import{execFileSync as gs}from"node:child_process";import{homedir as qy}from"node:os";function ps(){let n=process.env.MIO_CODEX_PATH;if(n&&Tn(n))return n;for(let e of Gy)if(Tn(e))return e;try{let e=gs("/usr/bin/which",["codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&Tn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=gs(e,["-lc","command -v codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&Tn(t))return t}catch{}try{let e=gs("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/codex`;if(Tn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=gs("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/codex`;if(Tn(s))return s}}catch{}return null}function Zl(){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(`
490
- `)}var Ql,Gy,eo=C(()=>{"use strict";Ql=qy(),Gy=["/opt/homebrew/bin/codex","/usr/local/bin/codex",`${Ql}/.npm-global/bin/codex`,`${Ql}/.codex/bin/codex`]});import{spawn as Wy}from"node:child_process";function eu(n){let e=n.spawnFn??Jy,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 l(p){if(!(!i||!s.stdin))try{s.stdin.write(JSON.stringify(p)+`
491
- `)}catch(f){t("warn","appServerClient stdin write failed",{err:f.message})}}function d(p){for(let[,f]of c)clearTimeout(f.timer),f.reject(new Error(p));c.clear()}function u(p){let f=p.id!==void 0&&p.id!==null,g=typeof p.method=="string";if(f&&!g){let _=p.id,S=c.get(_);if(!S){t("debug","appServerClient response for unknown id",{id:_});return}c.delete(_),clearTimeout(S.timer),p.error!==void 0?S.reject(new Error(`app-server error: ${JSON.stringify(p.error)}`)):S.resolve(p.result);return}if(g&&f){let _=p.id,S=p.method;Promise.resolve().then(()=>n.onServerRequest?n.onServerRequest(S,p.params):void 0).then(v=>l({id:_,result:v??{}})).catch(v=>{t("warn","onServerRequest handler threw",{method:S,err:v.message}),l({id:_,error:{code:-32e3,message:String(v.message)}})});return}if(g){try{n.onNotification(p.method,p.params)}catch(_){t("warn","onNotification handler threw",{method:p.method,err:_.message})}return}t("debug","appServerClient unrecognized message",{keys:Object.keys(p)})}function m(p){if(a+=typeof p=="string"?p:p.toString("utf8"),a.length>jy){t("warn","appServerClient buffer overflow \u2014 clearing",{bytes:a.length}),a="";return}let f;for(;(f=a.indexOf(`
492
- `))>=0;){let g=a.slice(0,f).replace(/\r$/,"");if(a=a.slice(f+1),!g.trim())continue;let _;try{_=JSON.parse(g)}catch{t("debug","appServerClient non-JSON line",{preview:g.slice(0,120)});continue}_&&typeof _=="object"&&u(_)}}return s.stdout?.on("data",m),s.stderr?.on("data",p=>{let f=typeof p=="string"?p:p.toString("utf8");n.onStderr&&n.onStderr(f)}),s.on("error",p=>{t("warn","appServerClient spawn error",{err:p.message}),i=!1,d(`app-server spawn error: ${p.message}`),n.onExit?.(null)}),s.on("exit",p=>{t("info","appServerClient exited",{code:p}),i=!1,d(`app-server exited (code=${p})`),n.onExit?.(p)}),{request(p,f){if(!i)return Promise.reject(new Error("app-server not alive"));let g=o++;return new Promise((_,S)=>{let v=setTimeout(()=>{c.delete(g),S(new Error(`app-server request '${p}' timed out after ${r}ms`))},r);v.unref?.(),c.set(g,{resolve:_,reject:S,timer:v}),l({method:p,id:g,params:f})})},notify(p,f){l({method:p,params:f})},isAlive(){return i},close(){if(i){i=!1,d("app-server client closed");try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}var jy,Jy,tu=C(()=>{"use strict";jy=4*1048576,Jy=(n,e,t)=>Wy(n,e,{cwd:t.cwd,env:t.env,stdio:["pipe","pipe","pipe"]})});import{readFileSync as Yy}from"node:fs";function Vy(n){let e=n?.trim();return e==="read-only"||e==="workspace-write"||e==="danger-full-access"?e:"danger-full-access"}function zy(n){let e=n?.trim();if(e&&e!=="gpt-5-codex")return e}function nu(n){let e=n.codexCommand??ps()??"codex",t=(process.env.MIO_CODEX_MODEL_REASONING||n.reasoningEffort||"medium").trim(),r=zy((process.env.MIO_CODEX_MODEL||n.spawnEnv.MIO_CODEX_MODEL||"").trim()||n.model),s=Vy(process.env.MIO_CODEX_SANDBOX||n.spawnEnv.MIO_CODEX_SANDBOX),i=n.maxRestarts??5,o=n.agentId,a=null,c=n.sessionId,l=!1,d=!1,u=!1,m=0,p=[],f,g="",_,S,v,y,k,P;function x($,Q){o&&ne(o,$,{runtime:"codex-app-server",...Q})}function O($){if(!(!n.presenceTracker||!o))try{n.presenceTracker.set(o,$)}catch(Q){process.stderr.write(`[${Ce}] presence(${$}) error: ${Q.message}
493
- `)}}function W(){try{return Yy(n.systemPromptPath,"utf8")}catch($){return E(Ce,`failed to read system prompt at ${n.systemPromptPath}`,$),""}}function J($,Q){return h("debug",Ce,"auto-approving server request",{method:$}),{decision:"approved"}}function Y($){let Q=$.content;return Array.isArray(Q)?Q.map(w=>w&&typeof w=="object"&&typeof w.text=="string"?w.text:"").join(""):typeof $.text=="string"?$.text:""}function re($,Q){let w=Q??{};switch($){case"thread/started":{let T=w.thread?.id;if(T&&T!==c){c=T;try{S?.(T)}catch(D){E(Ce,"onSessionId cb error",D)}x("spawn",{thread_id:T})}break}case"turn/started":l=!0,O("thinking");break;case"item/agentMessage/delta":{let b=w.delta??w.text;typeof b=="string"&&(g+=b);break}case"item/started":x("runtime_command",{phase:"started"});break;case"item/completed":{let b=w.item;if(!b)break;let T=b.type;if(T==="agentMessage"||T==="assistantMessage"){let D=Y(b).trim();D&&x("runtime_message",{chars:D.length,preview:D.slice(0,240)})}else(T==="commandExecution"||T==="localShellCall")&&x("runtime_command",{phase:"completed"});break}case"thread/tokenUsage/updated":{let b=w.tokenUsage?.last;if(b){let T=Number(b.inputTokens??0),D=Number(b.cachedInputTokens??0);try{P?.({inputTokens:T,outputTokens:Number(b.outputTokens??0),cacheReadTokens:D,cacheCreationTokens:0})}catch{}x("usage",{input_tokens:T,output_tokens:Number(b.outputTokens??0),cache_read_tokens:D,total_tokens:Number(b.totalTokens??0)})}break}case"turn/completed":{let b=w.turn,T=b?.status;if(T&&T!=="completed"){h("warn",Ce,"turn ended non-completed",{status:T,error:b?.error});let D=b?.error,q=typeof D=="string"?D:D&&typeof D.message=="string"?D.message:`codex turn ${T}`;try{k?.(q)}catch(I){E(Ce,"onTurnError cb error",I)}}g="",l=!1,O("idle");try{_?.()}catch(D){E(Ce,"onBoundary cb error",D)}V();break}default:break}}function ae($){if(!a||!a.isAlive()||!c){p.push($);return}l=!0,O("thinking"),g="",x("inbound",{chars:$.length});try{y?.($)}catch(Q){E(Ce,"onInjected cb error",Q)}a.request("turn/start",{threadId:c,input:[{type:"text",text:$,text_elements:[]}]}).catch(Q=>{h("warn",Ce,"turn/start failed",{err:Q.message}),l=!1,O("idle");try{_?.()}catch{}V()})}function V(){if(l||p.length===0)return;let $=p.splice(0).join(`
494
-
495
- `);ae($)}async function le($){let Q={...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=eu({command:e,args:w,cwd:n.workingDirectory,env:Q,onNotification:re,onServerRequest:J,onStderr:T=>{T.trim()&&h("debug",Ce,"app-server stderr",{snippet:T.slice(0,200)})},onExit:ue,log:(T,D,q)=>h(T,Ce,D,q),...n.appServerSpawnFn?{spawnFn:n.appServerSpawnFn}:{}});let b=c!==void 0;try{if(await a.request("initialize",{clientInfo:{name:"mio-agent",title:null,version:"1"},capabilities:null}),b)await a.request("thread/resume",{threadId:c}),h("info",Ce,"resumed thread",{threadId:c,viaRespawn:$});else{let T=W()||void 0,q=(await a.request("thread/start",{cwd:n.workingDirectory,sandbox:s,sandbox_mode:s,approvalPolicy:"never",...r?{model:r}:{},...T?{baseInstructions:T}:{}}))?.thread?.id;if(q){c=q;try{S?.(q)}catch(I){E(Ce,"onSessionId cb error",I)}}}}catch(T){E(Ce,"handshake failed",T);return}if(!b&&f!==void 0){let T=f;f=void 0,ae(T)}else l=!1,V()}function ue($){if(d){try{v?.($)}catch{}return}if(m>=i){h("warn",Ce,"max restarts reached \u2014 giving up",{restartCount:m});try{v?.($)}catch{}return}m++,l=!1,h("info",Ce,"app-server exited \u2014 respawning",{code:$,restartCount:m,threadId:c}),x("boundary",{reason:"respawn",code:$}),le(!0)}return{start(){u||(u=!0,O("starting"),f=n.firstTurnText,le(!1))},enqueueUserTurn($){if(l||!a||!a.isAlive()||!c){p.push($);return}ae($)},stop(){d=!0;try{a?.close()}catch{}},onBoundary($){_=$},onSessionId($){S=$},onExit($){v=$},onInjected($){y=$},onTurnError($){k=$},onTurnUsage($){P=$}}}var Ce,ru=C(()=>{"use strict";ge();Mt();eo();tu();Ce="codexAppServerHost"});import{readFileSync as Ky,writeFileSync as Xy,mkdirSync as Qy}from"node:fs";import{join as Zy}from"node:path";function su(n,e){return Zy(n,e?`runtime-session-${e.slice(0,8)}.json`:"runtime-session.json")}function iu(n,e,t,r){try{let s=JSON.parse(Ky(su(n,t),"utf-8"));if(s&&s.runtime===e&&typeof s.sessionId=="string"&&s.sessionId.length>0)return r&&s.promptHash&&s.promptHash!==r||r&&!s.promptHash?void 0:s.sessionId}catch{}}function ou(n,e,t,r,s){if(t)try{Qy(n,{recursive:!0});let i={runtime:e,sessionId:t,savedAt:new Date().toISOString(),...s?{promptHash:s}:{}};Xy(su(n,r),JSON.stringify(i,null,2),"utf-8")}catch{}}var au=C(()=>{"use strict"});function cu(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function cr(n){return typeof n=="boolean"?n:void 0}function o_(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.floor(n);return e>0?e:void 0}function a_(n){return Math.max(1,Math.min(6,Math.floor(n)))}function lu(n){let e=n.role??"",t=`${n.displayName??""} ${n.description??""} ${e}`,r={...dr};s_(t)&&!i_(t)&&(r.deliverBroadcastMessages=!1,r.deliverThreadBroadcastMessages=!1,r.wakeOnChannelTaskCreated=!1,r.wakeOnChannelTaskStatus=!1,r.threadReplyLimit=3);let s=cu(n.capabilities),i=cu(s?.context_policy);return i&&(r.deliverBroadcastMessages=cr(i.deliver_broadcast_messages)??r.deliverBroadcastMessages,r.deliverSystemMessages=cr(i.deliver_system_messages)??r.deliverSystemMessages,r.deliverThreadBroadcastMessages=cr(i.deliver_thread_broadcast_messages)??r.deliverThreadBroadcastMessages,r.wakeOnChannelTaskCreated=cr(i.wake_on_channel_task_created)??r.wakeOnChannelTaskCreated,r.wakeOnChannelTaskStatus=cr(i.wake_on_channel_task_status)??r.wakeOnChannelTaskStatus,r.threadReplyLimit=a_(o_(i.thread_reply_limit)??r.threadReplyLimit)),r}function uu(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 dr,e_,t_,n_,r_,du,s_,i_,ms=C(()=>{"use strict";dr={deliverBroadcastMessages:!0,deliverSystemMessages:!1,deliverThreadBroadcastMessages:!0,wakeOnChannelTaskCreated:!0,wakeOnChannelTaskStatus:!1,threadReplyLimit:6},e_=/\b(engineer|backend|frontend|ui|designer|design|executor|implement|coder|tester|qa|reviewer|operator|ops)\b/i,t_=/\b(pm|product|planner|coordinator|researcher|research|market|analyst|analysis)\b/i,n_=["\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"],r_=["\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"],du=(n,e)=>e.some(t=>n.includes(t)),s_=n=>e_.test(n)||du(n,n_),i_=n=>t_.test(n)||du(n,r_)});import{writeFileSync as c_,mkdirSync as d_}from"node:fs";import{join as fu}from"node:path";function ys(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 l_(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 l=[`[thread context, ${a.join(", ")}]`];e?l.push(`parent: ${ys(e,r)}`):n.parent_message_id&&l.push(`parent: (unavailable \u2014 parent message id ${i||s})`);let d=t.filter(u=>u.id!==n.id);if(d.length>0){l.push("recent replies:");for(let u of d)l.push(` ${ys(u,r)}`)}return l.push("incoming:"),l.push(ys(n,r)),s&&l.push(`(reply with: mio message reply --parent ${s} --target "#${r}")`),l.join(`
496
- `)}function hu(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:l,onInjected:d,reminderCache:u,onInboundMessage:m,contextTracker:p,contextPolicy:f=dr,mioDir:g,downloadAttachment:_,listOwnTasks:S}=n,v=/^image\//,y=null;async function k(R){if(!S)return"";if(y&&y.chan===R&&Date.now()-y.at<3e4)return y.text;let B="";try{let M=(await S(R)).filter(F=>F.status==="in_progress"||F.status==="todo"||F.status==="in_review");if(M.length>0){let F=ye=>`#${ye.number??"?"}(${ye.status})${ye.title.slice(0,24)}`;B=`
497
- [\u4F60\u7684\u4EFB\u52A1\u9762\u677F(daemon \u5B9E\u65F6\u63D0\u4F9B,\u4EE5\u6B64\u4E3A\u51C6): ${M.map(F).join(" \xB7 ")}\u3002\u8FDB\u884C\u4E2D\u7684\u5148\u505A\u5B8C\u5E76 update done;\u6392\u961F(todo)\u7684\u4F1A\u5728\u524D\u4E00\u4E2A\u5173\u95ED\u540E\u81EA\u52A8\u5524\u9192\u4F60;\u6EDE\u7559\u7684\u8981\u4E48\u6536\u5C3E\u8981\u4E48\u5728\u5176 thread \u8BF4\u660E\u5361\u70B9]`}}catch{}return y={at:Date.now(),text:B,chan:R},B}async function P(R){let B=R.attachment_ids??[];if(B.length===0||!g||!_)return"";let M=fu(g,"inbound"),F=[];for(let ye of B.slice(0,10))try{let xe=await _(ye);if(!v.test(xe.mime_type))continue;try{d_(M,{recursive:!0})}catch{}let Dt=(xe.filename||`${ye}.png`).replace(/[^\w.\-]/g,"_").slice(-60),We=fu(M,`${R.id.slice(0,8)}-${Dt}`);c_(We,Buffer.from(xe.data_base64,"base64")),F.push(We)}catch(xe){E(Z,"inbound attachment download failed (skipping)",xe)}return F.length===0?"":`
472
+ 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 eu(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(d){n.onError&&n.onError(d instanceof Error?d:new Error(String(d)),o);return}if(typeof a!="object"||a===null)return;let c=a,l=c.type;if(typeof l=="string"){if(l==="system"&&c.subtype==="compact_boundary"){r(n.onCompact,"<onCompact>");return}if(l==="system"&&c.subtype==="init"){let d=c.session_id;typeof d=="string"&&d.length>0&&(t.has(d)||(t.add(d),r(n.onSessionId,"<onSessionId>",d)));return}if(l==="result"){let d=c.usage;if(n.onUsage&&d&&typeof d=="object"){let u=d,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,g=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>",g)}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(`
473
+ `),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var tu=C(()=>{"use strict"});import{existsSync as En}from"node:fs";import{execFileSync as ms}from"node:child_process";import{homedir as Jy}from"node:os";function xn(){let n=process.env.MIO_CLAUDE_PATH;if(n&&En(n))return n;for(let e of Yy)if(En(e))return e;try{let e=ms("/usr/bin/which",["claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&En(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=ms(e,["-lc","command -v claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&En(t))return t}catch{}try{let e=ms("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/claude`;if(En(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=ms("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/claude`;if(En(s))return s}}catch{}return null}function nu(){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(`
474
+ `)}var so,Yy,ys=C(()=>{"use strict";so=Jy(),Yy=["/Applications/cmux.app/Contents/Resources/bin/claude",`${so}/.local/bin/claude`,`${so}/.claude/local/claude`,`${so}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as Vy}from"child_process";function ru(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=Vy,maxRestarts:c=5,presenceTracker:l,agentId:d}=n;function u(y){if(!(!l||!d))try{l.set(d,y)}catch(b){process.stderr.write(`[claudeStreamHost] presence(${y}) error: ${b.message}
475
+ `)}}function m(y,b){d&&ne(d,y,b)}let g=0,f=n.claudeCommand??xn()??"claude",p=null,w=n.sessionId,k=!1,v=[],_=!1,S=0,P,x,O,W,J,Y,re;function ae(y){let b=["--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",t,"--disallowed-tools",Ky,"--append-system-prompt-file",r,"--mcp-config",s,"--setting-sources","user,project,local","--chrome"];return y&&b.push("--resume",y),b}function V(y,b){let T={type:"user",message:{role:"user",content:[{type:"text",text:y}]}};return b!==void 0&&(T.session_id=b),JSON.stringify(T)+`
476
+ `}function le(y,b){if(!p||!p.stdin)return;let T=V(y,b);h("debug","claudeStreamHost","injected user turn",{bytes:T.length}),m("inject",{bytes:T.length,content_bytes:y.length,resume:b!==void 0}),u("thinking");try{p.stdin.write(T)}catch(D){process.stderr.write(`[claudeStreamHost] stdin write error (will restart): ${D.message}
477
+ `);return}re?.(y)}function ue(){S=0,m("boundary",{pending_queue_len:v.length});try{P?.()}catch(y){process.stderr.write(`[claudeStreamHost] onBoundary callback error: ${y.message}
478
+ `)}if(v.length>0){let y=v.length,b=v.splice(0,v.length).join(`
479
+ `);m("coalesce_flush",{coalesced_count:y,bytes:b.length}),le(b,w)}else k=!1,u("idle")}function $(y){let b=ae(y);h("info","claudeStreamHost","spawning claude",{command:f,argsCount:b.length,cwd:e,resume:!!y}),g=Date.now(),m("spawn",{command:f,args_count:b.length,resume:!!y,resume_session_id:y??null,restart_count:S}),u("starting"),p&&(p.stdout?.removeAllListeners(),p.stderr?.removeAllListeners());let T=a(f,b,{cwd:e,env:i,stdio:["pipe","pipe","pipe"],detached:!0});p=T,ss(T.pid),T.stdin?.on("error",I=>{T===p&&process.stderr.write(`[claudeStreamHost] stdin error (will restart): ${I.message}
480
+ `)});let D=eu({onSessionId:I=>{if(T!==p)return;w=I;let U=g?Date.now()-g:null;h("info","claudeStreamHost","session id captured",{sessionId:I,duration_ms:U}),m("session_ready",{session_id:I,spawn_duration_ms:U}),u("idle");try{O?.(I)}catch(z){process.stderr.write(`[claudeStreamHost] onSessionId callback error: ${z.message}
481
+ `)}},onResultError:I=>{if(T===p){h("warn","claudeStreamHost","turn ended with error",{message:I.slice(0,120)});try{x?.(I)}catch(U){process.stderr.write(`[claudeStreamHost] onTurnError callback error: ${U.message}
482
+ `)}}},onCompact:()=>{if(T===p){h("info","claudeStreamHost","context auto-compacted (compact_boundary)");try{W?.()}catch(I){process.stderr.write(`[claudeStreamHost] onCompact callback error: ${I.message}
483
+ `)}}},onUsage:I=>{if(T===p){try{J?.({inputTokens:I.inputTokens??0,outputTokens:I.outputTokens??0,cacheReadTokens:I.cacheReadTokens??0,cacheCreationTokens:I.cacheCreationTokens??0})}catch{}m("usage",{runtime:"claude",model:t,input_tokens:I.inputTokens??null,output_tokens:I.outputTokens??null,cache_read_tokens:I.cacheReadTokens??null,cache_creation_tokens:I.cacheCreationTokens??null,duration_ms:I.durationMs??null,total_cost_usd:I.totalCostUsd??null})}},onBoundary:()=>{T===p&&(h("debug","claudeStreamHost","turn boundary",{}),ue())},onError:(I,U)=>{process.stderr.write(`[claudeStreamHost] parser error on "${U}": ${I.message}
484
+ `)}});T.stdout?.on("data",I=>{T===p&&D.feed(typeof I=="string"?I:I.toString("utf8"))});let q="";T.stderr?.on("data",I=>{if(T!==p)return;q+=typeof I=="string"?I:I.toString("utf8");let U;for(;(U=q.indexOf(`
485
+ `))!==-1;){let z=q.slice(0,U).trimEnd();q=q.slice(U+1),z.length>0&&h("warn","claudeStreamHost","claude stderr",{line:z})}}),T.on("exit",I=>{tr(T.pid),T===p&&Q(I)}),T.on("error",I=>{process.stderr.write(`[claudeStreamHost] spawn error: ${I.message}
486
+ `)})}function Q(y){if(!_){if(S++,S>c){E("claudeStreamHost","giving up after max restarts",{restartCount:S}),process.stderr.write(`[claudeStreamHost] gave up after ${c} restarts (code=${y})
487
+ `);try{Y?.(y)}catch(b){process.stderr.write(`[claudeStreamHost] onExit callback error: ${b.message}
488
+ `)}return}if(h("warn","claudeStreamHost","claude exited",{code:y,willRestart:!0,restartCount:S}),m("exit",{code:y,will_restart:!0,restart_count:S}),process.stderr.write(`[claudeStreamHost] unexpected exit (code=${y}), restarting (attempt ${S}/${c})...
489
+ `),k=!1,$(w),v.length>0){let b=v.splice(0,v.length).join(`
490
+ `);k=!0,le(b,w)}}}return{start(){$(w),k=!0,le(o,w)},enqueueUserTurn(y){k?v.push(y):(k=!0,le(y,w))},stop(){_=!0;let y=p;if(y){try{y.stdin?.end()}catch{}let b=y.pid;if(b)try{process.kill(-b,"SIGTERM")}catch{try{y.kill("SIGTERM")}catch{}}let T=setTimeout(()=>{if(b)try{process.kill(-b,"SIGKILL")}catch{try{y.kill("SIGKILL")}catch{}}},1e3);T.unref&&T.unref(),tr(b)}},onTurnError(y){x=y},onBoundary(y){P=y},onSessionId(y){O=y},onCompact(y){W=y},onTurnUsage(y){J=y},onExit(y){Y=y},onInjected(y){re=y}}}var Ky,su=C(()=>{"use strict";is();tu();pe();Mt();ys();Ky=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(",")});import{existsSync as Tn}from"node:fs";import{execFileSync as _s}from"node:child_process";import{homedir as zy}from"node:os";function ws(){let n=process.env.MIO_CODEX_PATH;if(n&&Tn(n))return n;for(let e of Xy)if(Tn(e))return e;try{let e=_s("/usr/bin/which",["codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&Tn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=_s(e,["-lc","command -v codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&Tn(t))return t}catch{}try{let e=_s("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/codex`;if(Tn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=_s("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/codex`;if(Tn(s))return s}}catch{}return null}function ou(){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(`
491
+ `)}var iu,Xy,io=C(()=>{"use strict";iu=zy(),Xy=["/opt/homebrew/bin/codex","/usr/local/bin/codex",`${iu}/.npm-global/bin/codex`,`${iu}/.codex/bin/codex`]});import{spawn as Qy}from"node:child_process";function au(n){let e=n.spawnFn??e_,t=n.log??(()=>{}),r=n.requestTimeoutMs??6e4,s=e(n.command,n.args,{cwd:n.cwd,env:n.env});ss(s.pid);let i=!0,o=1,a="",c=new Map;function l(g){if(!(!i||!s.stdin))try{s.stdin.write(JSON.stringify(g)+`
492
+ `)}catch(f){t("warn","appServerClient stdin write failed",{err:f.message})}}function d(g){for(let[,f]of c)clearTimeout(f.timer),f.reject(new Error(g));c.clear()}function u(g){let f=g.id!==void 0&&g.id!==null,p=typeof g.method=="string";if(f&&!p){let w=g.id,k=c.get(w);if(!k){t("debug","appServerClient response for unknown id",{id:w});return}c.delete(w),clearTimeout(k.timer),g.error!==void 0?k.reject(new Error(`app-server error: ${JSON.stringify(g.error)}`)):k.resolve(g.result);return}if(p&&f){let w=g.id,k=g.method;Promise.resolve().then(()=>n.onServerRequest?n.onServerRequest(k,g.params):void 0).then(v=>l({id:w,result:v??{}})).catch(v=>{t("warn","onServerRequest handler threw",{method:k,err:v.message}),l({id:w,error:{code:-32e3,message:String(v.message)}})});return}if(p){try{n.onNotification(g.method,g.params)}catch(w){t("warn","onNotification handler threw",{method:g.method,err:w.message})}return}t("debug","appServerClient unrecognized message",{keys:Object.keys(g)})}function m(g){if(a+=typeof g=="string"?g:g.toString("utf8"),a.length>Zy){t("warn","appServerClient buffer overflow \u2014 clearing",{bytes:a.length}),a="";return}let f;for(;(f=a.indexOf(`
493
+ `))>=0;){let p=a.slice(0,f).replace(/\r$/,"");if(a=a.slice(f+1),!p.trim())continue;let w;try{w=JSON.parse(p)}catch{t("debug","appServerClient non-JSON line",{preview:p.slice(0,120)});continue}w&&typeof w=="object"&&u(w)}}return s.stdout?.on("data",m),s.stderr?.on("data",g=>{let f=typeof g=="string"?g:g.toString("utf8");n.onStderr&&n.onStderr(f)}),s.on("error",g=>{t("warn","appServerClient spawn error",{err:g.message}),i=!1,d(`app-server spawn error: ${g.message}`),n.onExit?.(null)}),s.on("exit",g=>{tr(s.pid),t("info","appServerClient exited",{code:g}),i=!1,d(`app-server exited (code=${g})`),n.onExit?.(g)}),{request(g,f){if(!i)return Promise.reject(new Error("app-server not alive"));let p=o++;return new Promise((w,k)=>{let v=setTimeout(()=>{c.delete(p),k(new Error(`app-server request '${g}' timed out after ${r}ms`))},r);v.unref?.(),c.set(p,{resolve:w,reject:k,timer:v}),l({method:g,id:p,params:f})})},notify(g,f){l({method:g,params:f})},isAlive(){return i},close(){if(i){i=!1,d("app-server client closed");try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}var Zy,e_,cu=C(()=>{"use strict";is();Zy=4*1048576,e_=(n,e,t)=>Qy(n,e,{cwd:t.cwd,env:t.env,stdio:["pipe","pipe","pipe"],detached:!0})});import{readFileSync as t_}from"node:fs";function n_(n){let e=n?.trim();return e==="read-only"||e==="workspace-write"||e==="danger-full-access"?e:"danger-full-access"}function r_(n){let e=n?.trim();if(e&&e!=="gpt-5-codex")return e}function du(n){let e=n.codexCommand??ws()??"codex",t=(process.env.MIO_CODEX_MODEL_REASONING||n.reasoningEffort||"medium").trim(),r=r_((process.env.MIO_CODEX_MODEL||n.spawnEnv.MIO_CODEX_MODEL||"").trim()||n.model),s=n_(process.env.MIO_CODEX_SANDBOX||n.spawnEnv.MIO_CODEX_SANDBOX),i=n.maxRestarts??5,o=n.agentId,a=null,c=n.sessionId,l=!1,d=!1,u=!1,m=0,g=[],f,p="",w,k,v,_,S,P;function x($,Q){o&&ne(o,$,{runtime:"codex-app-server",...Q})}function O($){if(!(!n.presenceTracker||!o))try{n.presenceTracker.set(o,$)}catch(Q){process.stderr.write(`[${Ce}] presence(${$}) error: ${Q.message}
494
+ `)}}function W(){try{return t_(n.systemPromptPath,"utf8")}catch($){return E(Ce,`failed to read system prompt at ${n.systemPromptPath}`,$),""}}function J($,Q){return h("debug",Ce,"auto-approving server request",{method:$}),{decision:"approved"}}function Y($){let Q=$.content;return Array.isArray(Q)?Q.map(y=>y&&typeof y=="object"&&typeof y.text=="string"?y.text:"").join(""):typeof $.text=="string"?$.text:""}function re($,Q){let y=Q??{};switch($){case"thread/started":{let T=y.thread?.id;if(T&&T!==c){c=T;try{k?.(T)}catch(D){E(Ce,"onSessionId cb error",D)}x("spawn",{thread_id:T})}break}case"turn/started":l=!0,O("thinking");break;case"item/agentMessage/delta":{let b=y.delta??y.text;typeof b=="string"&&(p+=b);break}case"item/started":x("runtime_command",{phase:"started"});break;case"item/completed":{let b=y.item;if(!b)break;let T=b.type;if(T==="agentMessage"||T==="assistantMessage"){let D=Y(b).trim();D&&x("runtime_message",{chars:D.length,preview:D.slice(0,240)})}else(T==="commandExecution"||T==="localShellCall")&&x("runtime_command",{phase:"completed"});break}case"thread/tokenUsage/updated":{let b=y.tokenUsage?.last;if(b){let T=Number(b.inputTokens??0),D=Number(b.cachedInputTokens??0);try{P?.({inputTokens:T,outputTokens:Number(b.outputTokens??0),cacheReadTokens:D,cacheCreationTokens:0})}catch{}x("usage",{input_tokens:T,output_tokens:Number(b.outputTokens??0),cache_read_tokens:D,total_tokens:Number(b.totalTokens??0)})}break}case"turn/completed":{let b=y.turn,T=b?.status;if(T&&T!=="completed"){h("warn",Ce,"turn ended non-completed",{status:T,error:b?.error});let D=b?.error,q=typeof D=="string"?D:D&&typeof D.message=="string"?D.message:`codex turn ${T}`;try{S?.(q)}catch(I){E(Ce,"onTurnError cb error",I)}}p="",l=!1,O("idle");try{w?.()}catch(D){E(Ce,"onBoundary cb error",D)}V();break}default:break}}function ae($){if(!a||!a.isAlive()||!c){g.push($);return}l=!0,O("thinking"),p="",x("inbound",{chars:$.length});try{_?.($)}catch(Q){E(Ce,"onInjected cb error",Q)}a.request("turn/start",{threadId:c,input:[{type:"text",text:$,text_elements:[]}]}).catch(Q=>{h("warn",Ce,"turn/start failed",{err:Q.message}),l=!1,O("idle");try{w?.()}catch{}V()})}function V(){if(l||g.length===0)return;let $=g.splice(0).join(`
495
+
496
+ `);ae($)}async function le($){let Q={...n.spawnEnv},y=["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=au({command:e,args:y,cwd:n.workingDirectory,env:Q,onNotification:re,onServerRequest:J,onStderr:T=>{T.trim()&&h("debug",Ce,"app-server stderr",{snippet:T.slice(0,200)})},onExit:ue,log:(T,D,q)=>h(T,Ce,D,q),...n.appServerSpawnFn?{spawnFn:n.appServerSpawnFn}:{}});let b=c!==void 0;try{if(await a.request("initialize",{clientInfo:{name:"mio-agent",title:null,version:"1"},capabilities:null}),b)await a.request("thread/resume",{threadId:c}),h("info",Ce,"resumed thread",{threadId:c,viaRespawn:$});else{let T=W()||void 0,q=(await a.request("thread/start",{cwd:n.workingDirectory,sandbox:s,sandbox_mode:s,approvalPolicy:"never",...r?{model:r}:{},...T?{baseInstructions:T}:{}}))?.thread?.id;if(q){c=q;try{k?.(q)}catch(I){E(Ce,"onSessionId cb error",I)}}}}catch(T){E(Ce,"handshake failed",T);return}if(!b&&f!==void 0){let T=f;f=void 0,ae(T)}else l=!1,V()}function ue($){if(d){try{v?.($)}catch{}return}if(m>=i){h("warn",Ce,"max restarts reached \u2014 giving up",{restartCount:m});try{v?.($)}catch{}return}m++,l=!1,h("info",Ce,"app-server exited \u2014 respawning",{code:$,restartCount:m,threadId:c}),x("boundary",{reason:"respawn",code:$}),le(!0)}return{start(){u||(u=!0,O("starting"),f=n.firstTurnText,le(!1))},enqueueUserTurn($){if(l||!a||!a.isAlive()||!c){g.push($);return}ae($)},stop(){d=!0;try{a?.close()}catch{}},onBoundary($){w=$},onSessionId($){k=$},onExit($){v=$},onInjected($){_=$},onTurnError($){S=$},onTurnUsage($){P=$}}}var Ce,lu=C(()=>{"use strict";pe();Mt();io();cu();Ce="codexAppServerHost"});import{readFileSync as s_,writeFileSync as i_,mkdirSync as o_}from"node:fs";import{join as a_}from"node:path";function uu(n,e){return a_(n,e?`runtime-session-${e.slice(0,8)}.json`:"runtime-session.json")}function fu(n,e,t,r){try{let s=JSON.parse(s_(uu(n,t),"utf-8"));if(s&&s.runtime===e&&typeof s.sessionId=="string"&&s.sessionId.length>0)return r&&s.promptHash&&s.promptHash!==r||r&&!s.promptHash?void 0:s.sessionId}catch{}}function hu(n,e,t,r,s){if(t)try{o_(n,{recursive:!0});let i={runtime:e,sessionId:t,savedAt:new Date().toISOString(),...s?{promptHash:s}:{}};i_(uu(n,r),JSON.stringify(i,null,2),"utf-8")}catch{}}var pu=C(()=>{"use strict"});function gu(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function dr(n){return typeof n=="boolean"?n:void 0}function p_(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.floor(n);return e>0?e:void 0}function g_(n){return Math.max(1,Math.min(6,Math.floor(n)))}function yu(n){let e=n.role??"",t=`${n.displayName??""} ${n.description??""} ${e}`,r={...lr};f_(t)&&!h_(t)&&(r.deliverBroadcastMessages=!1,r.deliverThreadBroadcastMessages=!1,r.wakeOnChannelTaskCreated=!1,r.wakeOnChannelTaskStatus=!1,r.threadReplyLimit=3);let s=gu(n.capabilities),i=gu(s?.context_policy);return i&&(r.deliverBroadcastMessages=dr(i.deliver_broadcast_messages)??r.deliverBroadcastMessages,r.deliverSystemMessages=dr(i.deliver_system_messages)??r.deliverSystemMessages,r.deliverThreadBroadcastMessages=dr(i.deliver_thread_broadcast_messages)??r.deliverThreadBroadcastMessages,r.wakeOnChannelTaskCreated=dr(i.wake_on_channel_task_created)??r.wakeOnChannelTaskCreated,r.wakeOnChannelTaskStatus=dr(i.wake_on_channel_task_status)??r.wakeOnChannelTaskStatus,r.threadReplyLimit=g_(p_(i.thread_reply_limit)??r.threadReplyLimit)),r}function _u(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 lr,c_,d_,l_,u_,mu,f_,h_,vs=C(()=>{"use strict";lr={deliverBroadcastMessages:!0,deliverSystemMessages:!1,deliverThreadBroadcastMessages:!0,wakeOnChannelTaskCreated:!0,wakeOnChannelTaskStatus:!1,threadReplyLimit:6},c_=/\b(engineer|backend|frontend|ui|designer|design|executor|implement|coder|tester|qa|reviewer|operator|ops)\b/i,d_=/\b(pm|product|planner|coordinator|researcher|research|market|analyst|analysis)\b/i,l_=["\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"],u_=["\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"],mu=(n,e)=>e.some(t=>n.includes(t)),f_=n=>c_.test(n)||mu(n,l_),h_=n=>d_.test(n)||mu(n,u_)});import{writeFileSync as m_,mkdirSync as y_}from"node:fs";import{join as wu}from"node:path";function bs(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 __(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 l=[`[thread context, ${a.join(", ")}]`];e?l.push(`parent: ${bs(e,r)}`):n.parent_message_id&&l.push(`parent: (unavailable \u2014 parent message id ${i||s})`);let d=t.filter(u=>u.id!==n.id);if(d.length>0){l.push("recent replies:");for(let u of d)l.push(` ${bs(u,r)}`)}return l.push("incoming:"),l.push(bs(n,r)),s&&l.push(`(reply with: mio message reply --parent ${s} --target "#${r}")`),l.join(`
497
+ `)}function vu(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:l,onInjected:d,reminderCache:u,onInboundMessage:m,contextTracker:g,contextPolicy:f=lr,mioDir:p,downloadAttachment:w,listOwnTasks:k}=n,v=/^image\//,_=null;async function S(R){if(!k)return"";if(_&&_.chan===R&&Date.now()-_.at<3e4)return _.text;let B="";try{let M=(await k(R)).filter(F=>F.status==="in_progress"||F.status==="todo"||F.status==="in_review");if(M.length>0){let F=ye=>`#${ye.number??"?"}(${ye.status})${ye.title.slice(0,24)}`;B=`
498
+ [\u4F60\u7684\u4EFB\u52A1\u9762\u677F(daemon \u5B9E\u65F6\u63D0\u4F9B,\u4EE5\u6B64\u4E3A\u51C6): ${M.map(F).join(" \xB7 ")}\u3002\u8FDB\u884C\u4E2D\u7684\u5148\u505A\u5B8C\u5E76 update done;\u6392\u961F(todo)\u7684\u4F1A\u5728\u524D\u4E00\u4E2A\u5173\u95ED\u540E\u81EA\u52A8\u5524\u9192\u4F60;\u6EDE\u7559\u7684\u8981\u4E48\u6536\u5C3E\u8981\u4E48\u5728\u5176 thread \u8BF4\u660E\u5361\u70B9]`}}catch{}return _={at:Date.now(),text:B,chan:R},B}async function P(R){let B=R.attachment_ids??[];if(B.length===0||!p||!w)return"";let M=wu(p,"inbound"),F=[];for(let ye of B.slice(0,10))try{let xe=await w(ye);if(!v.test(xe.mime_type))continue;try{y_(M,{recursive:!0})}catch{}let Dt=(xe.filename||`${ye}.png`).replace(/[^\w.\-]/g,"_").slice(-60),We=wu(M,`${R.id.slice(0,8)}-${Dt}`);m_(We,Buffer.from(xe.data_base64,"base64")),F.push(We)}catch(xe){E(Z,"inbound attachment download failed (skipping)",xe)}return F.length===0?"":`
498
499
 
499
500
  [\u9644\u4EF6] \u7528\u6237\u5728\u8FD9\u6761\u6D88\u606F\u91CC\u53D1\u4E86 ${F.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
500
501
  `+F.map(ye=>` - ${ye}`).join(`
@@ -505,31 +506,31 @@ Your cwd is your **persistent, agent-owned workspace** \u2014 files you create h
505
506
  3. \u6BCF\u8F6E\u6700\u591A\u95EE 1-2 \u4E2A\u542F\u53D1\u5F0F\u95EE\u9898(\u76EE\u6807/\u8303\u56F4/\u9A8C\u6536\u6807\u51C6/\u8FB9\u754C\u60C5\u51B5),\u7136\u540E\u66F4\u65B0\u4E00\u4EFD\u7ED3\u6784\u5316\u8349\u6848(\u6807\u9898/\u80CC\u666F/\u8981\u505A\u4EC0\u4E48/\u600E\u6837\u7B97\u5B8C\u6210)\u8D34\u7ED9\u5BA2\u6237\u786E\u8BA4\u3002
506
507
  4. \u6279\u51C6\u95E8:\u53EA\u6709\u5BA2\u6237\u660E\u786E\u8868\u793A\u540C\u610F/\u786E\u8BA4/\u6279\u51C6\u540E,\u624D\u7528 mio task create --channel "#<\u672C\u9891\u9053>" --title "<\u9700\u6C42\u6807\u9898>" --attach <\u6279\u51C6\u90A3\u6761\u6D88\u606F\u7684 id> \u7ACB\u9700\u6C42\u5355(\u4E0D\u52A0 --self,\u9700\u6C42\u5355\u7B49\u771F\u4EBA\u6392\u671F,\u4E0D\u662F\u4F60\u6267\u884C)\u3002\u6279\u51C6\u524D\u7EDD\u4E0D\u5EFA\u5355\u3002
507
508
  5. \u7ACB\u5355\u540E\u56DE\u590D:"\u5DF2\u8BB0\u5F55\u4E3A\u9700\u6C42 #N,\u8FDB\u5165\u6392\u671F,\u6709\u8FDB\u5C55\u6211\u4F1A\u540C\u6B65\u60A8\u3002" \u4E0D\u627F\u8BFA\u65F6\u95F4,\u4E0D\u8BA8\u8BBA\u600E\u4E48\u5B9E\u73B0\u3002
508
- 6. \u5224\u65AD\u9700\u6C42\u65F6\u5141\u8BB8\u4F60\u9759\u9ED8\u67E5\u9605\u8D44\u6599\u7406\u89E3\u4E1A\u52A1,\u4F46\u8F93\u51FA\u53EA\u8C08:\u8FD9\u4E2A\u9700\u6C42\u662F\u5426\u5408\u7406\u3001\u662F\u5168\u65B0\u529F\u80FD\u8FD8\u662F\u73B0\u6709\u529F\u80FD\u7684\u4F18\u5316\u3001\u5F71\u54CD\u54EA\u4E9B\u4E1A\u52A1\u6A21\u5757\u3002`;async function le(R){let B=O.get(R);if(B!==void 0)return B;let M=await J(R);return M!==void 0&&O.set(R,M),M}let ue=l??(async()=>new Set((await e.getAgentChannels(r)).map(R=>R.id))),$=null,Q=new Set,w=250,b=5e3,T=w,D=R=>new Promise(B=>{let M=setTimeout(B,R);typeof M.unref=="function"&&M.unref()});function q(){let R=ue().then(B=>(T=w,B)).catch(B=>{E(Z,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",B);let M=T;return T=Math.min(T*2,b),$===R&&($=D(M).then(()=>(q(),$??new Set))),new Set});$=R}let I=n.hostFor??(()=>t),U;t.onInjected(R=>{U?.(R)}),d&&(U=d);async function K(R){if(R.topic==="reminder.upserted"||R.topic==="reminder.canceled"){if(u){let z=R.payload;if(R.topic==="reminder.upserted")if(z.reminder){if(z.reminder.agentId!==r)return;u.upsert(z.reminder)}else h("warn",Z,"reminder.upserted event missing reminder payload",{payload:R.payload});else if(z.reminderId){if(z.agentId!==r)return;u.cancel(z.reminderId,z.version)}else h("warn",Z,"reminder.canceled event missing reminderId",{payload:R.payload})}return}if(R.topic==="channel.member_added"||R.topic==="channel.member_removed"||R.topic==="roster.member_added"||R.topic==="roster.member_removed"){let z=R.payload;z.member_id===r&&(h("info",Z,"membership changed for self \u2014 invalidating membership cache",{topic:R.topic,channelId:z.channel_id}),Q.clear(),q());return}if(R.topic!=="message.created"&&R.topic!=="thread.reply")return;let B=R.payload,M=B.channel_id,F=B.seq,ye=B.message_id,xe=B.parent_message_id;if(!M||!F){h("warn",Z,"message.created event missing channel_id or seq",{payload:B});return}ne(r,"event_received",{topic:R.topic,channel_id:M,seq:F,message_id:ye??null,parent_message_id:xe??null});let We=(await($??Promise.resolve(new Set))).has(M);if(!We&&!Q.has(M)){h("info",Z,"re-verifying membership for unknown channel before skip",{channelId:M,seq:F});try{let z=await ue();$=Promise.resolve(z),T=w,We=z.has(M),We?h("info",Z,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:M,seq:F}):Q.add(M)}catch(z){E(Z,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",z)}}if(!We){h("debug",Z,"skip not-a-member channel",{channelId:M,seq:F,topic:R.topic}),ne(r,"skip",{reason:"not_a_member",channel_id:M,seq:F,topic:R.topic});return}if(B.sender_id&&B.sender_id===r){h("debug",Z,"skip self-authored message (pre-fetch)",{seq:F,sender_id:B.sender_id}),ne(r,"skip",{reason:"self_authored_prefetch",channel_id:M,seq:F,message_id:ye??null});return}let N,ft;if(R.topic==="thread.reply"){if(!xe){h("warn",Z,"thread.reply event missing parent_message_id",{payload:B});return}if(!e.getThreadReplies){h("warn",Z,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:M,messageSeq:F});return}try{let z=(BigInt(F)>31n?BigInt(F)-31n:0n).toString(),Me=await e.getThreadReplies(r,xe,50,z);ft=Me,N=ye&&Me.find(Ue=>Ue.id===ye)||Me.find(Ue=>Ue.seq===F),N&&!N.parent_message_id&&(N={...N,parent_message_id:xe})}catch(z){E(Z,"failed to fetch thread replies after thread.reply event",z);return}}else{let z=(BigInt(F)-1n).toString();try{N=(await x(o,M,z,1)).messages.find(Ue=>Ue.seq===F)}catch(Me){E(Z,"failed to fetch message after message.created event",Me);return}}if(!N){h("warn",Z,"message not found in GET response",{channelId:M,messageSeq:F,topic:R.topic});return}if(N.sender_id===r){h("debug",Z,"skip self-authored message",{seq:F,sender_id:N.sender_id}),ne(r,"skip",{reason:"self_authored",channel_id:M,seq:F,message_id:N.id});return}let st=uu(N.content,s,i),Zt=!!N.parent_message_id;if(N.sender_kind==="system"&&!f.deliverSystemMessages){h("debug",Z,"skip system message by context policy",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"context_policy_system_message",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}let ht=B.wake_agent_ids;if(!Zt&&N.sender_kind!=="system"){if(Array.isArray(ht)){if(!(ht.includes(r)||st)){h("debug",Z,"skip: not in server wake set",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"not_in_wake_set",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}}else if(!f.deliverBroadcastMessages&&!st){h("debug",Z,"skip broadcast message by context policy",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"context_policy_broadcast_message",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}}if(Zt&&N.sender_kind!=="system"&&Array.isArray(ht)){if(!(ht.includes(r)||st)){h("debug",Z,"skip thread reply: not in server wake set",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"thread_not_in_wake_set",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}}else if(Zt&&N.sender_kind!=="system"&&!f.deliverThreadBroadcastMessages&&!st){h("debug",Z,"skip thread broadcast message by context policy",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}let Be;try{Be=await le(M)}catch(z){E(Z,"failed to resolve channel name \u2014 dropping message",z);return}if(!Be){h("warn",Z,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:M,messageSeq:F});return}let ke;if(N.parent_message_id){let z,Me=[],Ue=!1;if(e.getMessageById)try{z=await e.getMessageById(r,N.parent_message_id)}catch(it){Ue=!0,h("warn",Z,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:N.parent_message_id,err:it instanceof Error?it.message:String(it)})}else Ue=!0;if(ft&&N.parent_message_id===xe)Me=ft.slice(0,f.threadReplyLimit);else if(e.getThreadReplies)try{Me=await e.getThreadReplies(r,N.parent_message_id,f.threadReplyLimit)}catch(it){Ue=!0,h("warn",Z,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:N.parent_message_id,err:it instanceof Error?it.message:String(it)})}else Ue=!0;ke=l_(N,z,Me,Be),Ue&&h("info",Z,"thread context degraded (parent or replies missing)",{channelId:M,parent_message_id:N.parent_message_id})}else ke=ys(N,Be);let fr=N.parent_message_id?[{name:"thread_context",bytes:ke.length,reply_limit:f.threadReplyLimit},{name:"incoming",bytes:N.content.length}]:[{name:"inbound_message",bytes:ke.length}];ne(r,"context_injection",{topic:R.topic,channel_id:M,channel_name:Be,message_id:N.id,parent_message_id:N.parent_message_id??null,sender_kind:N.sender_kind,mode:N.parent_message_id?"thread":"main",explicitly_mentioned:st,policy:{deliver_broadcast_messages:f.deliverBroadcastMessages,deliver_system_messages:f.deliverSystemMessages,deliver_thread_broadcast_messages:f.deliverThreadBroadcastMessages,thread_reply_limit:f.threadReplyLimit},sections:fr,rendered_bytes:ke.length}),!N.parent_message_id&&N.sender_kind!=="system"&&Array.isArray(B.wake_agent_ids)&&B.wake_agent_ids.includes(r)&&!st&&(ke+=`
509
+ 6. \u5224\u65AD\u9700\u6C42\u65F6\u5141\u8BB8\u4F60\u9759\u9ED8\u67E5\u9605\u8D44\u6599\u7406\u89E3\u4E1A\u52A1,\u4F46\u8F93\u51FA\u53EA\u8C08:\u8FD9\u4E2A\u9700\u6C42\u662F\u5426\u5408\u7406\u3001\u662F\u5168\u65B0\u529F\u80FD\u8FD8\u662F\u73B0\u6709\u529F\u80FD\u7684\u4F18\u5316\u3001\u5F71\u54CD\u54EA\u4E9B\u4E1A\u52A1\u6A21\u5757\u3002`;async function le(R){let B=O.get(R);if(B!==void 0)return B;let M=await J(R);return M!==void 0&&O.set(R,M),M}let ue=l??(async()=>new Set((await e.getAgentChannels(r)).map(R=>R.id))),$=null,Q=new Set,y=250,b=5e3,T=y,D=R=>new Promise(B=>{let M=setTimeout(B,R);typeof M.unref=="function"&&M.unref()});function q(){let R=ue().then(B=>(T=y,B)).catch(B=>{E(Z,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",B);let M=T;return T=Math.min(T*2,b),$===R&&($=D(M).then(()=>(q(),$??new Set))),new Set});$=R}let I=n.hostFor??(()=>t),U;t.onInjected(R=>{U?.(R)}),d&&(U=d);async function z(R){if(R.topic==="reminder.upserted"||R.topic==="reminder.canceled"){if(u){let K=R.payload;if(R.topic==="reminder.upserted")if(K.reminder){if(K.reminder.agentId!==r)return;u.upsert(K.reminder)}else h("warn",Z,"reminder.upserted event missing reminder payload",{payload:R.payload});else if(K.reminderId){if(K.agentId!==r)return;u.cancel(K.reminderId,K.version)}else h("warn",Z,"reminder.canceled event missing reminderId",{payload:R.payload})}return}if(R.topic==="channel.member_added"||R.topic==="channel.member_removed"||R.topic==="roster.member_added"||R.topic==="roster.member_removed"){let K=R.payload;K.member_id===r&&(h("info",Z,"membership changed for self \u2014 invalidating membership cache",{topic:R.topic,channelId:K.channel_id}),Q.clear(),q());return}if(R.topic!=="message.created"&&R.topic!=="thread.reply")return;let B=R.payload,M=B.channel_id,F=B.seq,ye=B.message_id,xe=B.parent_message_id;if(!M||!F){h("warn",Z,"message.created event missing channel_id or seq",{payload:B});return}ne(r,"event_received",{topic:R.topic,channel_id:M,seq:F,message_id:ye??null,parent_message_id:xe??null});let We=(await($??Promise.resolve(new Set))).has(M);if(!We&&!Q.has(M)){h("info",Z,"re-verifying membership for unknown channel before skip",{channelId:M,seq:F});try{let K=await ue();$=Promise.resolve(K),T=y,We=K.has(M),We?h("info",Z,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:M,seq:F}):Q.add(M)}catch(K){E(Z,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",K)}}if(!We){h("debug",Z,"skip not-a-member channel",{channelId:M,seq:F,topic:R.topic}),ne(r,"skip",{reason:"not_a_member",channel_id:M,seq:F,topic:R.topic});return}if(B.sender_id&&B.sender_id===r){h("debug",Z,"skip self-authored message (pre-fetch)",{seq:F,sender_id:B.sender_id}),ne(r,"skip",{reason:"self_authored_prefetch",channel_id:M,seq:F,message_id:ye??null});return}let N,ft;if(R.topic==="thread.reply"){if(!xe){h("warn",Z,"thread.reply event missing parent_message_id",{payload:B});return}if(!e.getThreadReplies){h("warn",Z,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:M,messageSeq:F});return}try{let K=(BigInt(F)>31n?BigInt(F)-31n:0n).toString(),Me=await e.getThreadReplies(r,xe,50,K);ft=Me,N=ye&&Me.find(Ue=>Ue.id===ye)||Me.find(Ue=>Ue.seq===F),N&&!N.parent_message_id&&(N={...N,parent_message_id:xe})}catch(K){E(Z,"failed to fetch thread replies after thread.reply event",K);return}}else{let K=(BigInt(F)-1n).toString();try{N=(await x(o,M,K,1)).messages.find(Ue=>Ue.seq===F)}catch(Me){E(Z,"failed to fetch message after message.created event",Me);return}}if(!N){h("warn",Z,"message not found in GET response",{channelId:M,messageSeq:F,topic:R.topic});return}if(N.sender_id===r){h("debug",Z,"skip self-authored message",{seq:F,sender_id:N.sender_id}),ne(r,"skip",{reason:"self_authored",channel_id:M,seq:F,message_id:N.id});return}let st=_u(N.content,s,i),Zt=!!N.parent_message_id;if(N.sender_kind==="system"&&!f.deliverSystemMessages){h("debug",Z,"skip system message by context policy",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"context_policy_system_message",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}let ht=B.wake_agent_ids;if(!Zt&&N.sender_kind!=="system"){if(Array.isArray(ht)){if(!(ht.includes(r)||st)){h("debug",Z,"skip: not in server wake set",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"not_in_wake_set",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}}else if(!f.deliverBroadcastMessages&&!st){h("debug",Z,"skip broadcast message by context policy",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"context_policy_broadcast_message",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}}if(Zt&&N.sender_kind!=="system"&&Array.isArray(ht)){if(!(ht.includes(r)||st)){h("debug",Z,"skip thread reply: not in server wake set",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"thread_not_in_wake_set",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}}else if(Zt&&N.sender_kind!=="system"&&!f.deliverThreadBroadcastMessages&&!st){h("debug",Z,"skip thread broadcast message by context policy",{seq:F,message_id:N.id}),ne(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:M,seq:F,message_id:N.id}),xt(r,M,N.seq);return}let Be;try{Be=await le(M)}catch(K){E(Z,"failed to resolve channel name \u2014 dropping message",K);return}if(!Be){h("warn",Z,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:M,messageSeq:F});return}let ke;if(N.parent_message_id){let K,Me=[],Ue=!1;if(e.getMessageById)try{K=await e.getMessageById(r,N.parent_message_id)}catch(it){Ue=!0,h("warn",Z,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:N.parent_message_id,err:it instanceof Error?it.message:String(it)})}else Ue=!0;if(ft&&N.parent_message_id===xe)Me=ft.slice(0,f.threadReplyLimit);else if(e.getThreadReplies)try{Me=await e.getThreadReplies(r,N.parent_message_id,f.threadReplyLimit)}catch(it){Ue=!0,h("warn",Z,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:N.parent_message_id,err:it instanceof Error?it.message:String(it)})}else Ue=!0;ke=__(N,K,Me,Be),Ue&&h("info",Z,"thread context degraded (parent or replies missing)",{channelId:M,parent_message_id:N.parent_message_id})}else ke=bs(N,Be);let hr=N.parent_message_id?[{name:"thread_context",bytes:ke.length,reply_limit:f.threadReplyLimit},{name:"incoming",bytes:N.content.length}]:[{name:"inbound_message",bytes:ke.length}];ne(r,"context_injection",{topic:R.topic,channel_id:M,channel_name:Be,message_id:N.id,parent_message_id:N.parent_message_id??null,sender_kind:N.sender_kind,mode:N.parent_message_id?"thread":"main",explicitly_mentioned:st,policy:{deliver_broadcast_messages:f.deliverBroadcastMessages,deliver_system_messages:f.deliverSystemMessages,deliver_thread_broadcast_messages:f.deliverThreadBroadcastMessages,thread_reply_limit:f.threadReplyLimit},sections:hr,rendered_bytes:ke.length}),!N.parent_message_id&&N.sender_kind!=="system"&&Array.isArray(B.wake_agent_ids)&&B.wake_agent_ids.includes(r)&&!st&&(ke+=`
509
510
 
510
511
  [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.`),ke+=await P(N);let On=await ae(M);if(On==="client"&&N.sender_kind==="user"&&(re.has(M)?ke+=`
511
512
  (\u5BA2\u6237\u9891\u9053\xB7\u987E\u95EE\u534F\u8BAE\u751F\u6548:\u5F52\u62E2\u788E\u7247\u3001\u9010\u9879\u6F84\u6E05\u3001\u6279\u51C6\u540E\u624D\u7ACB\u5355\u3001\u7EDD\u4E0D\u8C08\u5B9E\u73B0)`:(ke=V+`
512
513
 
513
- `+ke,re.add(M))),!N.parent_message_id&&N.sender_kind==="user"&&S&&On!=="client"&&(ke+=await k(Be)),!N.parent_message_id&&N.sender_kind!=="system"&&(ke+=`
514
- (\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${Be}"\u3002\u8FD9\u6761\u6D88\u606F\u6765\u81EA\u4E3B\u9891\u9053:\u7ED9\u4EBA\u7C7B\u7684\u56DE\u7B54\u5FC5\u987B\u53D1\u56DE\u4E3B\u9891\u9053,\u7981\u6B62\u7528 reply \u53D1\u8FDB\u4EFB\u4F55\u4EFB\u52A1 thread\u2014\u2014\u4EBA\u7C7B\u5728\u4E3B\u9891\u9053\u7B49\u4F60\u3002\u4F60\u7684\u7EAF\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u9001\u8FBE\u4EFB\u4F55\u4EBA)`),I(M).enqueueUserTurn(ke),p&&N.sender_kind!=="system")try{p.set(r,N.id)}catch(z){E(Z,"contextTracker.set threw (non-fatal)",z)}if(m)try{m(M)}catch(z){E(Z,"onInboundMessage callback threw (non-fatal)",z)}xt(r,M,N.seq),h("info",Z,"enqueued inbound message",{channelId:M,channelName:Be,seq:N.seq,sender_id:N.sender_id}),ne(r,"inbound",{topic:R.topic,channel_id:M,channel_name:Be,seq:N.seq,message_id:N.id,message_id_short:N.id.replace(/-/g,"").slice(0,8),parent_message_id:N.parent_message_id??null,sender_id:N.sender_id,sender_kind:N.sender_kind,sender_display_name:N.sender_display_name??null,content_preview:N.content.slice(0,120),rendered_bytes:ke.length})}let se=R=>K(R).catch(B=>{E(Z,"unhandled error in handleEvent",B)});return{start(){q(),e.subscribe(o,se),h("info",Z,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,se),h("info",Z,"InboxCoordinator stopped",{workroomId:o})},onInjected(R){U=R}}}var Z,gu=C(()=>{"use strict";Ki();ge();Mt();ms();Z="inboxDelivery"});var pu,_s,mu=C(()=>{"use strict";ge();pu="typingNotifier",_s=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",pu,"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",pu,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var lr,ws,yu=C(()=>{"use strict";ge();Mt();lr="agentPresence",ws=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",lr,"presence transition deduped",{agentId:e,state:t,channelId:r});return}if(this.current.set(e,t),h("info",lr,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),ne(e,"presence",{state:t,prev:s??null,channel_id:r??null}),!this.gateway.notifyAgentStatus){h("warn",lr,"gateway.notifyAgentStatus MISSING \u2014 presence not sent to server",{agentId:e,state:t});return}h("debug",lr,"notifyAgentStatus \u2192",{agentId:e,state:t}),this.gateway.notifyAgentStatus(e,r,t).catch(i=>{h("warn",lr,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function _u(n){let{agentId:e,onFire:t,clock:r=()=>Date.now()}=n,s=new Map,i=new Map;function o(d){let u=s.get(d);u?.timer&&clearTimeout(u.timer),s.delete(d)}function a(){for(let d of s.values())d.timer&&clearTimeout(d.timer);s.clear()}function c(d){let u=s.get(d);if(!u)return;let m=u.reminder.version,p=i.get(d);p!==void 0&&p>=m||(i.set(d,m),Promise.resolve().then(()=>t(u.reminder)).catch(f=>{E(u_,`onFire callback failed for reminder ${d} (agent ${e})`,f)}))}function l(d){let u=s.get(d.id);if(u&&u.reminder.version>=d.version)return;u?.timer&&clearTimeout(u.timer);let m=Date.parse(d.fireAt),p=r(),f=Math.max(0,m-p);if(m<=p){s.set(d.id,{reminder:d,timer:null}),c(d.id);return}let g=setTimeout(()=>c(d.id),f);typeof g.unref=="function"&&g.unref(),s.set(d.id,{reminder:d,timer:g})}return{upsert:l,cancel(d,u){o(d)},snapshot(d){a();for(let u of d)l(u)},clear(){a()},stop(){a(),i.clear()}}}var u_,wu=C(()=>{"use strict";ge();u_="reminderCache"});function vu(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",to,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),ne(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",to,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),h("debug",to,"context get expired",{agentId:r,messageId:s.id}),ne(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var to,bu=C(()=>{"use strict";ge();Mt();to="contextTracker"});import{readFileSync as f_,writeFileSync as h_,existsSync as g_,mkdirSync as p_}from"fs";import{dirname as m_}from"path";function Su(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function Eu(){return{version:1,entities:{},relations:{},observations:[],obs_seq:0}}function no(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 ku,vs,xu=C(()=>{"use strict";ku=500;vs=class{constructor(e){this.path=e;if(g_(e))try{let t=f_(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=Eu()}else this.file=Eu(),p_(m_(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[Su(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[Su(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>ku&&this.file.observations.splice(0,this.file.observations.length-ku),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&&(h_(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 rt(n){return n.replace(/-/g,"").slice(0,8)}function Cn(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+rt(e)}function Rn(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+rt(e)}function Tu(n){let{subscribe:e,unsubscribe:t,host:r,hostFor:s,selfAgentId:i,workroomId:o,companion:a,listOwnTasks:c,quietSeconds:l,maxRepliesPerWindow:d,windowSeconds:u,contextPolicy:m=dr,now:p=()=>Date.now()}=n,f=[],g=new Map,_=3e4,S=new Set;function v(w=p()){f.push(w);let b=w-u*1e3;for(;f.length>0&&f[0]<b;)f.shift()}function y(w){return f.length===0?Number.POSITIVE_INFINITY:w-f[f.length-1]}function k(w){let b=w-u*1e3;for(;f.length>0&&f[0]<b;)f.shift();return f.length}function P(w){return w?a.listChannelMembers(w).some(T=>T.id===i):!1}function x(w){let b=p();for(let[T,D]of g)b-D>_&&g.delete(T);return g.has(w)?!1:(g.set(w,b),!0)}function O(w){return`assigned:${w}:${i}`}function W(w,b){let T=p(),D=y(T);if(D<l*1e3)return h("debug",ut,"wake skipped: quiet_seconds gate",{reason:w,taskId:b,sinceMs:D,quietSeconds:l}),!1;let q=k(T);return q>=d?(h("debug",ut,"wake skipped: max_replies_per_window gate",{reason:w,taskId:b,count:q,max:d,windowSeconds:u}),!1):!0}function J(w,b,T,D){h("info",ut,"poking agent with system event",{reason:b,taskId:T,channelId:D}),ne(i,"wake",{reason:b,task_id:T,task_id_short:rt(T),bytes:w.length}),(D&&s?s(D):r).enqueueUserTurn(w)}function Y(w){let b=w.task_id,T=w.channel_id,D=w.title,q=w.created_by,I=w.owner_id??w.assignee_id;if(!b||q===i||I===i)return;if(!(m.wakeOnChannelTaskCreated&&P(T))){h("debug",ut,"task.created not relevant \u2014 skip",{taskId:b});return}if(!x(`created:${b}`)||!W("task-created",b))return;let K=Cn(a,q),se=Rn(a,T),R=`[system event: task #${rt(b)} was just created in your channel ${se}]
514
+ `+ke,re.add(M))),!N.parent_message_id&&N.sender_kind==="user"&&k&&On!=="client"&&(ke+=await S(Be)),!N.parent_message_id&&N.sender_kind!=="system"&&(ke+=`
515
+ (\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${Be}"\u3002\u8FD9\u6761\u6D88\u606F\u6765\u81EA\u4E3B\u9891\u9053:\u7ED9\u4EBA\u7C7B\u7684\u56DE\u7B54\u5FC5\u987B\u53D1\u56DE\u4E3B\u9891\u9053,\u7981\u6B62\u7528 reply \u53D1\u8FDB\u4EFB\u4F55\u4EFB\u52A1 thread\u2014\u2014\u4EBA\u7C7B\u5728\u4E3B\u9891\u9053\u7B49\u4F60\u3002\u4F60\u7684\u7EAF\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u9001\u8FBE\u4EFB\u4F55\u4EBA)`),I(M).enqueueUserTurn(ke),g&&N.sender_kind!=="system")try{g.set(r,N.id)}catch(K){E(Z,"contextTracker.set threw (non-fatal)",K)}if(m)try{m(M)}catch(K){E(Z,"onInboundMessage callback threw (non-fatal)",K)}xt(r,M,N.seq),h("info",Z,"enqueued inbound message",{channelId:M,channelName:Be,seq:N.seq,sender_id:N.sender_id}),ne(r,"inbound",{topic:R.topic,channel_id:M,channel_name:Be,seq:N.seq,message_id:N.id,message_id_short:N.id.replace(/-/g,"").slice(0,8),parent_message_id:N.parent_message_id??null,sender_id:N.sender_id,sender_kind:N.sender_kind,sender_display_name:N.sender_display_name??null,content_preview:N.content.slice(0,120),rendered_bytes:ke.length})}let se=R=>z(R).catch(B=>{E(Z,"unhandled error in handleEvent",B)});return{start(){q(),e.subscribe(o,se),h("info",Z,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,se),h("info",Z,"InboxCoordinator stopped",{workroomId:o})},onInjected(R){U=R}}}var Z,bu=C(()=>{"use strict";to();pe();Mt();vs();Z="inboxDelivery"});var ku,ks,Su=C(()=>{"use strict";pe();ku="typingNotifier",ks=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",ku,"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",ku,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var ur,Ss,Eu=C(()=>{"use strict";pe();Mt();ur="agentPresence",Ss=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",ur,"presence transition deduped",{agentId:e,state:t,channelId:r});return}if(this.current.set(e,t),h("info",ur,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),ne(e,"presence",{state:t,prev:s??null,channel_id:r??null}),!this.gateway.notifyAgentStatus){h("warn",ur,"gateway.notifyAgentStatus MISSING \u2014 presence not sent to server",{agentId:e,state:t});return}h("debug",ur,"notifyAgentStatus \u2192",{agentId:e,state:t}),this.gateway.notifyAgentStatus(e,r,t).catch(i=>{h("warn",ur,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function xu(n){let{agentId:e,onFire:t,clock:r=()=>Date.now()}=n,s=new Map,i=new Map;function o(d){let u=s.get(d);u?.timer&&clearTimeout(u.timer),s.delete(d)}function a(){for(let d of s.values())d.timer&&clearTimeout(d.timer);s.clear()}function c(d){let u=s.get(d);if(!u)return;let m=u.reminder.version,g=i.get(d);g!==void 0&&g>=m||(i.set(d,m),Promise.resolve().then(()=>t(u.reminder)).catch(f=>{E(w_,`onFire callback failed for reminder ${d} (agent ${e})`,f)}))}function l(d){let u=s.get(d.id);if(u&&u.reminder.version>=d.version)return;u?.timer&&clearTimeout(u.timer);let m=Date.parse(d.fireAt),g=r(),f=Math.max(0,m-g);if(m<=g){s.set(d.id,{reminder:d,timer:null}),c(d.id);return}let p=setTimeout(()=>c(d.id),f);typeof p.unref=="function"&&p.unref(),s.set(d.id,{reminder:d,timer:p})}return{upsert:l,cancel(d,u){o(d)},snapshot(d){a();for(let u of d)l(u)},clear(){a()},stop(){a(),i.clear()}}}var w_,Tu=C(()=>{"use strict";pe();w_="reminderCache"});function Cu(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",oo,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),ne(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",oo,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),h("debug",oo,"context get expired",{agentId:r,messageId:s.id}),ne(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var oo,Ru=C(()=>{"use strict";pe();Mt();oo="contextTracker"});import{readFileSync as v_,writeFileSync as b_,existsSync as k_,mkdirSync as S_}from"fs";import{dirname as E_}from"path";function Ou(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function Pu(){return{version:1,entities:{},relations:{},observations:[],obs_seq:0}}function ao(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 Au,Es,Iu=C(()=>{"use strict";Au=500;Es=class{constructor(e){this.path=e;if(k_(e))try{let t=v_(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=Pu()}else this.file=Pu(),S_(E_(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[Ou(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[Ou(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>Au&&this.file.observations.splice(0,this.file.observations.length-Au),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&&(b_(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 rt(n){return n.replace(/-/g,"").slice(0,8)}function Cn(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+rt(e)}function Rn(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+rt(e)}function Nu(n){let{subscribe:e,unsubscribe:t,host:r,hostFor:s,selfAgentId:i,workroomId:o,companion:a,listOwnTasks:c,quietSeconds:l,maxRepliesPerWindow:d,windowSeconds:u,contextPolicy:m=lr,now:g=()=>Date.now()}=n,f=[],p=new Map,w=3e4,k=new Set;function v(y=g()){f.push(y);let b=y-u*1e3;for(;f.length>0&&f[0]<b;)f.shift()}function _(y){return f.length===0?Number.POSITIVE_INFINITY:y-f[f.length-1]}function S(y){let b=y-u*1e3;for(;f.length>0&&f[0]<b;)f.shift();return f.length}function P(y){return y?a.listChannelMembers(y).some(T=>T.id===i):!1}function x(y){let b=g();for(let[T,D]of p)b-D>w&&p.delete(T);return p.has(y)?!1:(p.set(y,b),!0)}function O(y){return`assigned:${y}:${i}`}function W(y,b){let T=g(),D=_(T);if(D<l*1e3)return h("debug",ut,"wake skipped: quiet_seconds gate",{reason:y,taskId:b,sinceMs:D,quietSeconds:l}),!1;let q=S(T);return q>=d?(h("debug",ut,"wake skipped: max_replies_per_window gate",{reason:y,taskId:b,count:q,max:d,windowSeconds:u}),!1):!0}function J(y,b,T,D){h("info",ut,"poking agent with system event",{reason:b,taskId:T,channelId:D}),ne(i,"wake",{reason:b,task_id:T,task_id_short:rt(T),bytes:y.length}),(D&&s?s(D):r).enqueueUserTurn(y)}function Y(y){let b=y.task_id,T=y.channel_id,D=y.title,q=y.created_by,I=y.owner_id??y.assignee_id;if(!b||q===i||I===i)return;if(!(m.wakeOnChannelTaskCreated&&P(T))){h("debug",ut,"task.created not relevant \u2014 skip",{taskId:b});return}if(!x(`created:${b}`)||!W("task-created",b))return;let z=Cn(a,q),se=Rn(a,T),R=`[system event: task #${rt(b)} was just created in your channel ${se}]
515
516
  Title: ${D?`"${D}"`:"(no title)"}
516
- Created by ${K}.${I?` Assigned to ${Cn(a,I)}.`:" No assignee yet."}
517
- You may want to volunteer for it, acknowledge, or skip.`;J(R,"task-created",b,T)}function re(w){let{taskId:b,channelId:T,parentMessageId:D,assignerId:q,reason:I,dedupeAlreadyReserved:U}=w;if(!U){if(S.has(O(b)))return h("debug",ut,"assigned wake suppressed: boot-scoped self-heal reservation",{taskId:b,reason:I}),!1;if(!x(O(b)))return!1}if(!W(I,b))return!1;let K=Rn(a,T),se=q?` by ${Cn(a,q)}`:"",R=D?`
517
+ Created by ${z}.${I?` Assigned to ${Cn(a,I)}.`:" No assignee yet."}
518
+ You may want to volunteer for it, acknowledge, or skip.`;J(R,"task-created",b,T)}function re(y){let{taskId:b,channelId:T,parentMessageId:D,assignerId:q,reason:I,dedupeAlreadyReserved:U}=y;if(!U){if(k.has(O(b)))return h("debug",ut,"assigned wake suppressed: boot-scoped self-heal reservation",{taskId:b,reason:I}),!1;if(!x(O(b)))return!1}if(!W(I,b))return!1;let z=Rn(a,T),se=q?` by ${Cn(a,q)}`:"",R=D?`
518
519
 
519
520
  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:
520
- mio message reply --parent ${D} --target ${K} <<'EOF'
521
+ mio message reply --parent ${D} --target ${z} <<'EOF'
521
522
  \u2026
522
523
  EOF
523
524
  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.`:"",B=`[system event: task #${rt(b)} was assigned to you${se}]
524
- Channel: ${K}
525
- 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 #${rt(b)} --status done\`. Briefly acknowledge then begin.`+R;return J(B,I,b,T),!0}function ae(w){let b=w.task_id,T=w.channel_id,D=w.assignee_id,q=w.assigner_id,I=w.parent_message_id;if(b&&q!==i){if(D!==i){h("debug",ut,"task.assigned not to self \u2014 skip",{taskId:b,assigneeId:D});return}re({taskId:b,channelId:T,parentMessageId:I,assignerId:q,reason:"task-assigned"})}}function V(w){let b=w.task_id,T=w.channel_id,D=w.from,q=w.to,I=w.actor_id,U=w.assignee_id;if(!b||I===i)return;if(!(U===i||m.wakeOnChannelTaskStatus&&P(T))){h("debug",ut,"task.status_changed not relevant \u2014 skip",{taskId:b});return}let se=w.review_verdict,R=w.review_feedback;if(se==="bounce"&&U===i){if(!x(`bounce:${b}`))return;let ye=Cn(a,I),xe=Rn(a,T),Dt=R&&R.trim()?R.trim():"(see the task thread)",We=`[system event: your task #${rt(b)} was BOUNCED back for rework by ${ye} after independent review]
525
+ Channel: ${z}
526
+ 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 #${rt(b)} --status done\`. Briefly acknowledge then begin.`+R;return J(B,I,b,T),!0}function ae(y){let b=y.task_id,T=y.channel_id,D=y.assignee_id,q=y.assigner_id,I=y.parent_message_id;if(b&&q!==i){if(D!==i){h("debug",ut,"task.assigned not to self \u2014 skip",{taskId:b,assigneeId:D});return}re({taskId:b,channelId:T,parentMessageId:I,assignerId:q,reason:"task-assigned"})}}function V(y){let b=y.task_id,T=y.channel_id,D=y.from,q=y.to,I=y.actor_id,U=y.assignee_id;if(!b||I===i)return;if(!(U===i||m.wakeOnChannelTaskStatus&&P(T))){h("debug",ut,"task.status_changed not relevant \u2014 skip",{taskId:b});return}let se=y.review_verdict,R=y.review_feedback;if(se==="bounce"&&U===i){if(!x(`bounce:${b}`))return;let ye=Cn(a,I),xe=Rn(a,T),Dt=R&&R.trim()?R.trim():"(see the task thread)",We=`[system event: your task #${rt(b)} was BOUNCED back for rework by ${ye} after independent review]
526
527
  Channel: ${xe}.
527
528
  Reviewer feedback: ${Dt}
528
529
  Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${rt(b)} --channel ${xe} --status done\` again \u2014 it auto-closes after this one rework, no second review. This is NOT optional; do not stay silent.`;J(We,"task-bounce",b,T);return}if(!x(`status:${b}:${q}`)||!W("task-status",b))return;let B=Cn(a,I),M=Rn(a,T),F=`[system event: task #${rt(b)} status changed from ${D??"?"} to ${q??"?"} by ${B}]
529
530
  Channel: ${M}.
530
- Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;J(F,"task-status",b,T)}function le(w){if(!c)return;let b=w.to??w.status,T=w.assignee_id??w.owner_id,D=w.channel_id,q=w.task_id;if(b!=="done"&&b!=="DONE"||T!==i||!D||!q||!x(`chain:${q}`))return;let I=Rn(a,D);c(I).then(U=>{let se=U.filter(B=>B.status==="todo"&&B.assignee_id===i&&B.number!==null).sort((B,M)=>(B.number??0)-(M.number??0))[0];if(!se)return;let R=`[system event: task queue \u2014 your previous task is done]
531
+ Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;J(F,"task-status",b,T)}function le(y){if(!c)return;let b=y.to??y.status,T=y.assignee_id??y.owner_id,D=y.channel_id,q=y.task_id;if(b!=="done"&&b!=="DONE"||T!==i||!D||!q||!x(`chain:${q}`))return;let I=Rn(a,D);c(I).then(U=>{let se=U.filter(B=>B.status==="todo"&&B.assignee_id===i&&B.number!==null).sort((B,M)=>(B.number??0)-(M.number??0))[0];if(!se)return;let R=`[system event: task queue \u2014 your previous task is done]
531
532
  \u4F60\u540D\u4E0B\u6392\u961F\u7684\u4E0B\u4E00\u4E2A\u4EFB\u52A1:#${se.number} "${se.title}"(\u9891\u9053 ${I})\u3002
532
- \u73B0\u5728\u5F00\u59CB:\u5148\u5728\u5B83\u7684 thread \u91CC\u56DE\u4E00\u53E5\u4F60\u5F00\u59CB\u4E86,\u7136\u540E\u52A8\u624B\u505A;\u5B8C\u6210\u540E mio task update #${se.number} --channel ${I} --status done\u3002`;J(R,"task-chain",String(se.number),D)}).catch(()=>{})}function ue(w){let b=w.task_id,T=w.channel_id,D=w.reviewer_id,q=w.owner_id,I=w.parent_message_id,U=w.title,K=w.number;if(!b)return;if(D!==i){h("debug",ut,"review_requested not for self \u2014 skip",{taskId:b,reviewerId:D});return}if(!x(`review:${b}`))return;let se=Cn(a,q),R=Rn(a,T),B=K!==void 0?`#${K}`:`#${rt(b)}`,M=I?`
533
+ \u73B0\u5728\u5F00\u59CB:\u5148\u5728\u5B83\u7684 thread \u91CC\u56DE\u4E00\u53E5\u4F60\u5F00\u59CB\u4E86,\u7136\u540E\u52A8\u624B\u505A;\u5B8C\u6210\u540E mio task update #${se.number} --channel ${I} --status done\u3002`;J(R,"task-chain",String(se.number),D)}).catch(()=>{})}function ue(y){let b=y.task_id,T=y.channel_id,D=y.reviewer_id,q=y.owner_id,I=y.parent_message_id,U=y.title,z=y.number;if(!b)return;if(D!==i){h("debug",ut,"review_requested not for self \u2014 skip",{taskId:b,reviewerId:D});return}if(!x(`review:${b}`))return;let se=Cn(a,q),R=Rn(a,T),B=z!==void 0?`#${z}`:`#${rt(b)}`,M=I?`
533
534
  Get the surrounding context, then inspect the ACTUAL deliverable (its files \u2014 build it, run its tests), not just the chat:
534
535
  mio message read --channel ${R} --around ${rt(I)}
535
536
  Post your review findings in the task thread:
@@ -546,9 +547,9 @@ Then submit your verdict:
546
547
  mio task review ${B} --channel ${R} --pass
547
548
  \u2022 A feature is unprotected (mutation stayed green), or you found a real bug \u2192
548
549
  mio task review ${B} --channel ${R} --bounce --feedback "<exactly what is untested/broken>"
549
- A bounce sends it back to ${se} to add the missing test/fix; after their rework it closes without a second review.`;J(F,"task-review",b,T)}function $(w){w.sender_id===i&&v()}let Q=w=>{try{let b=w.payload??{};switch(w.topic){case"task.created":Y(b);break;case"task.assigned":ae(b);break;case"task.status_changed":V(b),le(b);break;case"task.review_requested":ue(b);break;case"message.created":$(b);break;default:break}}catch(b){h("warn",ut,"task wake handler error (non-fatal)",{err:String(b)})}};return{start(){e(o,Q),h("info",ut,"task wake router started",{workroomId:o,selfAgentId:i,quietSeconds:l,maxRepliesPerWindow:d,windowSeconds:u})},stop(){try{t(o,Q)}catch{}},noteSelfPost:v,synthesizeAssignedWake(w){return w.task_id?re({taskId:w.task_id,channelId:w.channel_id,parentMessageId:w.parent_message_id,reason:"task-assigned-selfheal",dedupeAlreadyReserved:!0}):!1},reserveAssignedDedupeKeys(w){for(let b of w)b&&(x(O(b)),S.add(O(b)))}}}var ut,Cu=C(()=>{"use strict";ge();Mt();ms();ut="taskWakeRouter"});import{spawn as y_}from"node:child_process";import{readFileSync as bs,writeFileSync as Ru,existsSync as ks,renameSync as __,statSync as w_,unlinkSync as v_}from"node:fs";import{join as Ss}from"node:path";function Nu(n){let e=Ss(n.mioDir,"persona-counter.json"),t=Ss(n.mioDir,"persona.md"),r=t+".tmp",s=n.claudeCommand??xn()??"claude",i=!1,o=0,a=!1,c=l();function l(){if(ks(e))try{let f=bs(e,"utf8"),g=JSON.parse(f);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 d(){try{Ru(e,JSON.stringify(c,null,2),{encoding:"utf8",mode:384})}catch(f){E(Re,"persona-counter write failed (non-fatal)",f)}}function u(){let f=Date.now();if(i)return{go:!1,reason:"already running"};if(f-o<n.quietSeconds*1e3)return{go:!1,reason:"within quietSeconds"};if(c.messages_since_last_extract>=Au)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)&&f-g>=b_)return{go:!0,reason:"elapsed 24h"}}return{go:!1,reason:"no trigger"}}async function m(f){if(!i&&!a){i=!0,o=Date.now();try{h("info",Re,"persona extraction starting",{agentId:n.agentId,reason:f});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(O){E(Re,"getChannelMessages failed (continuing with empty messages)",O)}let _=[];try{let O=Ss(n.mioDir,"companion.json");if(ks(O)){let W=bs(O,"utf8"),J=JSON.parse(W);_=(Array.isArray(J.observations)?J.observations:[]).slice(-k_)}}catch(O){E(Re,"companion.json read failed (continuing without observations)",O)}let S=[];try{n.channelId&&(S=n.companion.listChannelMembers(n.channelId).map(O=>({id:O.id,name:O.display_name??O.id,role:O.role??"",description:O.description??""}))),S.length===0&&(S=n.companion.listWorkroomEntities(n.workroomId).map(O=>({id:O.id,name:O.display_name??O.id,role:O.role??"",description:O.description??""})))}catch(O){E(Re,"roster derivation failed",O)}let v="";if(ks(t))try{v=bs(t,"utf8")}catch{}let y=S_(n.displayName,n.handle,n.role),k=E_({existingPersona:v,messages:g,observations:_,roster:S}),P=await x_(s,y,k,n.workspace,n.spawnEnv);if(!P||P.trim().length===0){h("warn",Re,"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 -->
550
+ A bounce sends it back to ${se} to add the missing test/fix; after their rework it closes without a second review.`;J(F,"task-review",b,T)}function $(y){y.sender_id===i&&v()}let Q=y=>{try{let b=y.payload??{};switch(y.topic){case"task.created":Y(b);break;case"task.assigned":ae(b);break;case"task.status_changed":V(b),le(b);break;case"task.review_requested":ue(b);break;case"message.created":$(b);break;default:break}}catch(b){h("warn",ut,"task wake handler error (non-fatal)",{err:String(b)})}};return{start(){e(o,Q),h("info",ut,"task wake router started",{workroomId:o,selfAgentId:i,quietSeconds:l,maxRepliesPerWindow:d,windowSeconds:u})},stop(){try{t(o,Q)}catch{}},noteSelfPost:v,synthesizeAssignedWake(y){return y.task_id?re({taskId:y.task_id,channelId:y.channel_id,parentMessageId:y.parent_message_id,reason:"task-assigned-selfheal",dedupeAlreadyReserved:!0}):!1},reserveAssignedDedupeKeys(y){for(let b of y)b&&(x(O(b)),k.add(O(b)))}}}var ut,Mu=C(()=>{"use strict";pe();Mt();vs();ut="taskWakeRouter"});import{spawn as x_}from"node:child_process";import{readFileSync as xs,writeFileSync as Lu,existsSync as Ts,renameSync as T_,statSync as C_,unlinkSync as R_}from"node:fs";import{join as Cs}from"node:path";function Fu(n){let e=Cs(n.mioDir,"persona-counter.json"),t=Cs(n.mioDir,"persona.md"),r=t+".tmp",s=n.claudeCommand??xn()??"claude",i=!1,o=0,a=!1,c=l();function l(){if(Ts(e))try{let f=xs(e,"utf8"),p=JSON.parse(f);if(p&&typeof p.messages_since_last_extract=="number")return{version:1,messages_since_last_extract:p.messages_since_last_extract,last_extract_at:p.last_extract_at??null}}catch{}return{version:1,messages_since_last_extract:0,last_extract_at:null}}function d(){try{Lu(e,JSON.stringify(c,null,2),{encoding:"utf8",mode:384})}catch(f){E(Re,"persona-counter write failed (non-fatal)",f)}}function u(){let f=Date.now();if(i)return{go:!1,reason:"already running"};if(f-o<n.quietSeconds*1e3)return{go:!1,reason:"within quietSeconds"};if(c.messages_since_last_extract>=$u)return{go:!0,reason:`message threshold (${c.messages_since_last_extract})`};if(c.last_extract_at){let p=Date.parse(c.last_extract_at);if(!Number.isNaN(p)&&f-p>=A_)return{go:!0,reason:"elapsed 24h"}}return{go:!1,reason:"no trigger"}}async function m(f){if(!i&&!a){i=!0,o=Date.now();try{h("info",Re,"persona extraction starting",{agentId:n.agentId,reason:f});let p=[];if(n.channelId)try{p=(await n.gateway.getChannelMessages(n.workroomId,n.channelId,void 0,Bu)).messages.slice(-Bu).map(J=>({sender:J.sender_display_name||`${J.sender_kind}:${J.sender_id.slice(0,8)}`,content:J.content,at:J.created_at}))}catch(O){E(Re,"getChannelMessages failed (continuing with empty messages)",O)}let w=[];try{let O=Cs(n.mioDir,"companion.json");if(Ts(O)){let W=xs(O,"utf8"),J=JSON.parse(W);w=(Array.isArray(J.observations)?J.observations:[]).slice(-O_)}}catch(O){E(Re,"companion.json read failed (continuing without observations)",O)}let k=[];try{n.channelId&&(k=n.companion.listChannelMembers(n.channelId).map(O=>({id:O.id,name:O.display_name??O.id,role:O.role??"",description:O.description??""}))),k.length===0&&(k=n.companion.listWorkroomEntities(n.workroomId).map(O=>({id:O.id,name:O.display_name??O.id,role:O.role??"",description:O.description??""})))}catch(O){E(Re,"roster derivation failed",O)}let v="";if(Ts(t))try{v=xs(t,"utf8")}catch{}let _=P_(n.displayName,n.handle,n.role),S=I_({existingPersona:v,messages:p,observations:w,roster:k}),P=await N_(s,_,S,n.workspace,n.spawnEnv);if(!P||P.trim().length===0){h("warn",Re,"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 -->
550
551
 
551
- ${x}`),x=T_(x);try{Ru(r,x,{encoding:"utf8",mode:384}),__(r,t)}catch(O){E(Re,"persona.md atomic write failed",O);try{v_(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),d(),h("info",Re,"persona extraction completed",{agentId:n.agentId,bytes:x.length,reason:f})}catch(g){E(Re,"persona extraction failed (keeping prior persona)",g)}finally{i=!1}}}function p(f){let{go:g,reason:_}=u();if(!g){h("debug",Re,"extraction skipped",{agentId:n.agentId,reason:f,gate:_});return}m(f)}return{noteMessage(){a||(c.messages_since_last_extract+=1,d(),c.messages_since_last_extract>=Au&&p("threshold"))},kick(f="kick"){if(a)return;let g=Date.now();if(i){h("debug",Re,"kick ignored: already running",{agentId:n.agentId});return}if(g-o<n.quietSeconds*1e3){h("debug",Re,"kick ignored: within quietSeconds",{agentId:n.agentId});return}m(f)},stop(){a=!0}}}function S_(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}).
552
+ ${x}`),x=M_(x);try{Lu(r,x,{encoding:"utf8",mode:384}),T_(r,t)}catch(O){E(Re,"persona.md atomic write failed",O);try{R_(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),d(),h("info",Re,"persona extraction completed",{agentId:n.agentId,bytes:x.length,reason:f})}catch(p){E(Re,"persona extraction failed (keeping prior persona)",p)}finally{i=!1}}}function g(f){let{go:p,reason:w}=u();if(!p){h("debug",Re,"extraction skipped",{agentId:n.agentId,reason:f,gate:w});return}m(f)}return{noteMessage(){a||(c.messages_since_last_extract+=1,d(),c.messages_since_last_extract>=$u&&g("threshold"))},kick(f="kick"){if(a)return;let p=Date.now();if(i){h("debug",Re,"kick ignored: already running",{agentId:n.agentId});return}if(p-o<n.quietSeconds*1e3){h("debug",Re,"kick ignored: within quietSeconds",{agentId:n.agentId});return}m(f)},stop(){a=!0}}}function P_(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}).
552
553
 
553
554
  Below you'll see:
554
555
  - The agent's existing persona.md (their cumulative knowledge so far)
@@ -574,26 +575,26 @@ Constraints:
574
575
  - NEVER include UUIDs, internal IDs, mio CLI commands, or implementation details
575
576
  - NEVER include speculation; only facts you can point to evidence for
576
577
 
577
- Output the persona.md now.`}function E_(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(`
578
- `)}function x_(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="",l="",d=!1,u=y_(n,o,{cwd:r,env:a,stdio:["pipe","pipe","pipe"]}),m=setTimeout(()=>{if(!d){d=!0;try{u.kill("SIGTERM")}catch{}E(Re,"one-shot claude timed out",{timeoutMs:Ou,stderrSnippet:l.slice(0,200)}),i("")}},Ou);m.unref?.(),u.stdout?.on("data",p=>{c+=typeof p=="string"?p:p.toString("utf8")}),u.stderr?.on("data",p=>{l+=typeof p=="string"?p:p.toString("utf8")}),u.on("error",p=>{d||(d=!0,clearTimeout(m),E(Re,"one-shot claude spawn error",p),i(""))}),u.on("exit",p=>{if(!d){if(d=!0,clearTimeout(m),p!==0){h("warn",Re,"one-shot claude exited non-zero",{code:p,stderrSnippet:l.slice(0,400),stdoutSnippet:c.slice(0,400)}),i("");return}i(c)}});try{u.stdin?.write(t),u.stdin?.end()}catch(p){E(Re,"one-shot claude stdin write failed",p)}})}function T_(n){if(n.length<=Iu)return n;let e=n.split(`
579
- `),t=[],r=[],s=null;for(let d of e)d.startsWith("## ")?(s&&t.push(s),s={header:d,body:[]}):s?s.body.push(d):r.push(d);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((d,u)=>{let m=i.findIndex(f=>d.header.includes(f)),p=i.findIndex(f=>u.header.includes(f));return(m===-1?99:m)-(p===-1?99:p)}),a=[...r],c=Iu-a.join(`
578
+ Output the persona.md now.`}function I_(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(`
579
+ `)}function N_(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="",l="",d=!1,u=x_(n,o,{cwd:r,env:a,stdio:["pipe","pipe","pipe"]}),m=setTimeout(()=>{if(!d){d=!0;try{u.kill("SIGTERM")}catch{}E(Re,"one-shot claude timed out",{timeoutMs:Du,stderrSnippet:l.slice(0,200)}),i("")}},Du);m.unref?.(),u.stdout?.on("data",g=>{c+=typeof g=="string"?g:g.toString("utf8")}),u.stderr?.on("data",g=>{l+=typeof g=="string"?g:g.toString("utf8")}),u.on("error",g=>{d||(d=!0,clearTimeout(m),E(Re,"one-shot claude spawn error",g),i(""))}),u.on("exit",g=>{if(!d){if(d=!0,clearTimeout(m),g!==0){h("warn",Re,"one-shot claude exited non-zero",{code:g,stderrSnippet:l.slice(0,400),stdoutSnippet:c.slice(0,400)}),i("");return}i(c)}});try{u.stdin?.write(t),u.stdin?.end()}catch(g){E(Re,"one-shot claude stdin write failed",g)}})}function M_(n){if(n.length<=Uu)return n;let e=n.split(`
580
+ `),t=[],r=[],s=null;for(let d of e)d.startsWith("## ")?(s&&t.push(s),s={header:d,body:[]}):s?s.body.push(d):r.push(d);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((d,u)=>{let m=i.findIndex(f=>d.header.includes(f)),g=i.findIndex(f=>u.header.includes(f));return(m===-1?99:m)-(g===-1?99:g)}),a=[...r],c=Uu-a.join(`
580
581
  `).length,l=new Set;for(let d of o){let u=d.header.length+1+d.body.join(`
581
582
  `).length+1;u<=c&&(l.add(d),c-=u)}for(let d of t)l.has(d)&&(a.push(d.header),a.push(...d.body));return a.join(`
582
583
  `).trim()+`
583
- `}function Mu(n){let e=Ss(n,"persona.md");if(!ks(e))return null;try{let t=w_(e);if(!t.isFile()||t.size===0)return null;let s=bs(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var Re,Au,b_,Ou,Pu,k_,Iu,Lu=C(()=>{"use strict";hs();ge();Re="personaCrystallizer",Au=50,b_=1440*60*1e3,Ou=6e4,Pu=50,k_=50;Iu=4e3});var ju={};He(ju,{bootAgentSpine:()=>Wu,deriveAgentWorkspace:()=>qu,normalizeRuntime:()=>Gu,runDaemon:()=>oo,snapshotLiveSessions:()=>io,startAgentSpine:()=>Fu});import{join as De,dirname as C_}from"path";import{fileURLToPath as R_}from"url";import{homedir as A_,hostname as $u,arch as O_}from"os";import{unlink as P_,writeFile as Bu,mkdir as so,readdir as I_,copyFile as N_,readFile as M_}from"fs/promises";import{readFileSync as Du}from"node:fs";import{existsSync as L_}from"fs";import{spawnSync as $_}from"child_process";import{randomUUID as Es}from"crypto";import{createHash as D_}from"crypto";function io(){return[...ur.values()]}async function Fu(n){let{config:e,machineToken:t,workingDirectory:r,gateway:s,agentId:i,launchId:o,agentHandle:a,displayName:c,description:l,role:d,spawnFn:u,claudeCommand:m,codexCommand:p,model:f,runtime:g="claude",reasoningEffort:_,contextTracker:S,presenceTracker:v,contextPolicy:y}=n,k=n.execContext??Qi(),P=y??lu({role:d,displayName:c,description:l,capabilities:n.serverCapabilities}),x=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:O,spawnEnv:W,proxyHandle:J}=await Fl({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:x,execContext:k,...S?{contextTracker:S}:{}}),Y=null,re=De(O,"companion.json"),ae=new vs(re),V=null,le=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{V=await s.getWorkroomRoster(le),no(ae,V),h("info",L,"CompanionGraph hydrated from roster",{agentId:i,channels:V.channels.length,members:V.members.length})}catch(b){E(L,"CompanionGraph hydrate failed (continuing with empty graph)",b)}let ue;if(V){let T=V.channels.filter(D=>D.member_ids.includes(i))[0]??V.channels[0];if(T){let D=new Map(V.members.map(K=>[K.id,K])),q=T.member_ids.map(K=>D.get(K)).filter(K=>!!K),I=new Set(T.member_ids),U=V.members.filter(K=>!I.has(K.id));ue={channelId:T.id,channelName:T.name,inChannel:q,otherInWorkroom:U}}}try{let N=function(){try{let A=Du(De(r,"MEMORY.md"),"utf-8").trim();return A?`
584
+ `}function Hu(n){let e=Cs(n,"persona.md");if(!Ts(e))return null;try{let t=C_(e);if(!t.isFile()||t.size===0)return null;let s=xs(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var Re,$u,A_,Du,Bu,O_,Uu,qu=C(()=>{"use strict";ys();pe();Re="personaCrystallizer",$u=50,A_=1440*60*1e3,Du=6e4,Bu=50,O_=50;Uu=4e3});var Qu={};He(Qu,{bootAgentSpine:()=>Xu,deriveAgentWorkspace:()=>Ku,normalizeRuntime:()=>zu,runDaemon:()=>fo,snapshotLiveSessions:()=>uo,startAgentSpine:()=>Yu});import{join as De,dirname as L_}from"path";import{fileURLToPath as $_}from"url";import{homedir as D_,hostname as Gu,arch as B_}from"os";import{unlink as U_,writeFile as ju,mkdir as lo,readdir as F_,copyFile as H_,readFile as q_}from"fs/promises";import{readFileSync as Wu}from"node:fs";import{existsSync as G_}from"fs";import{spawnSync as W_}from"child_process";import{randomUUID as Rs}from"crypto";import{createHash as j_}from"crypto";function uo(){return[...fr.values()]}async function Yu(n){let{config:e,machineToken:t,workingDirectory:r,gateway:s,agentId:i,launchId:o,agentHandle:a,displayName:c,description:l,role:d,spawnFn:u,claudeCommand:m,codexCommand:g,model:f,runtime:p="claude",reasoningEffort:w,contextTracker:k,presenceTracker:v,contextPolicy:_}=n,S=n.execContext??ro(),P=_??yu({role:d,displayName:c,description:l,capabilities:n.serverCapabilities}),x=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:O,spawnEnv:W,proxyHandle:J}=await Yl({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:x,execContext:S,...k?{contextTracker:k}:{}}),Y=null,re=De(O,"companion.json"),ae=new Es(re),V=null,le=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{V=await s.getWorkroomRoster(le),ao(ae,V),h("info",L,"CompanionGraph hydrated from roster",{agentId:i,channels:V.channels.length,members:V.members.length})}catch(b){E(L,"CompanionGraph hydrate failed (continuing with empty graph)",b)}let ue;if(V){let T=V.channels.filter(D=>D.member_ids.includes(i))[0]??V.channels[0];if(T){let D=new Map(V.members.map(z=>[z.id,z])),q=T.member_ids.map(z=>D.get(z)).filter(z=>!!z),I=new Set(T.member_ids),U=V.members.filter(z=>!I.has(z.id));ue={channelId:T.id,channelName:T.name,inChannel:q,otherInWorkroom:U}}}try{let N=function(){try{let A=Wu(De(r,"MEMORY.md"),"utf-8").trim();return A?`
584
585
 
585
586
  [\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]
586
587
  ${A.length>6e3?A.slice(0,6e3)+`
587
- \u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:A}`:""}catch{return""}},st=function(){if(g==="codex"){if(ft)return ft;try{ft=D_("sha1").update(Du(D)).digest("hex").slice(0,16)}catch{ft=void 0}return ft}},Zt=function(A){let X=iu(O,g,A,st());h("info",L,X?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:g,channelId:A,...X?{sessionId:X}:{}});let Ct=xe(A),Fe={workingDirectory:r,systemPromptPath:D,mcpConfigPath:q,spawnEnv:W,firstTurnText:X?I:I+N(),...X?{sessionId:X}:{},...u?{spawnFn:u}:{},...Ct?{presenceTracker:Ct,agentId:i}:{}},Te=g==="codex"?nu({...Fe,model:f??"gpt-5-codex",..._?{reasoningEffort:_}:{},...p?{codexCommand:p}:{}}):Kl({...Fe,model:f??"sonnet",...m?{claudeCommand:m}:{}});Te.onSessionId(ce=>{h("info",L,"agent session id",{agentId:i,runtime:g,channelId:A,sessionId:ce}),ou(O,g,ce,A,st())});let hr=`${i}:${A}`;return ur.set(hr,{agent_id:i,agent_name:c,channel_id:A,runtime:g,model:f??null,started_at:new Date().toISOString(),turns:0,input_tokens:0,output_tokens:0,cache_read_tokens:0}),Te.onTurnUsage?.(ce=>{let Ae=ur.get(hr);Ae&&(Ae.turns+=1,Ae.input_tokens+=ce.inputTokens,Ae.output_tokens+=ce.outputTokens,Ae.cache_read_tokens+=ce.cacheReadTokens,Ae.last_turn_at=new Date().toISOString())}),Te.onInjected(ce=>{if(ce.includes("type=human]")){let Ae=/\bmsg=([0-9a-f]{8})/.exec(ce);ul(i,A,Ae?.[1])}for(let Ae of B)try{Ae(ce)}catch{}}),Te.onBoundary(()=>{fl(i,A)&&nn(e.server_url,U,A,{content:`\u26A0\uFE0F ${c} \u6536\u5230\u6D88\u606F\u5E76\u5B8C\u6210\u4E86\u5904\u7406,\u4F46\u672C\u8F6E\u6CA1\u6709\u53D1\u51FA\u4EFB\u4F55\u56DE\u590D\u2014\u2014\u53EF\u80FD\u9047\u5230\u53D1\u9001\u6545\u969C\u3002\u53EF\u8BA9\u5B83\u91CD\u8BD5,\u6216\u67E5\u770B daemon \u65E5\u5FD7(agent-trace)\u3002`,clientIdempotencyKey:Es(),agentId:i},t).catch(ce=>E("run","silent-turn notice failed",ce));for(let ce of M)try{ce()}catch{}}),Te.onExit(ce=>{for(let Ae of F)try{Ae(ce)}catch{}}),Te.onTurnError?.(ce=>{let Ae=Date.now();if(ce===We&&Ae-Dt<6e4)return;We=ce,Dt=Ae;let pf=/usage limit/i.test(ce)?"\u7528\u91CF\u5DF2\u8FBE\u4E0A\u9650,\u8BF7\u5145\u503C\u6216\u7A0D\u540E\u518D\u8BD5":/unauthor|auth|401|403/i.test(ce)?"\u8BA4\u8BC1\u5931\u8D25,\u8BF7\u68C0\u67E5\u767B\u5F55/\u5BC6\u94A5":ce.slice(0,160);nn(e.server_url,U,A,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${pf})`,clientIdempotencyKey:Es(),agentId:i},t).catch(mf=>E("run","post turn-error notice failed",mf))}),Te.onCompact?.(()=>{nn(e.server_url,U,A,{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:Es(),agentId:i},t).catch(ce=>E("run","post compact notice failed",ce))}),Te.start(),Te};var $=N,Q=st,w=Zt;let b={agentId:i,handle:a,displayName:c,description:l,role:d,serverId:e.org_id,computer:`${$u()} (${e.machine_id})`,hostname:$u(),os:`${process.platform} ${O_()}`,workspace:r,runtime:g,capabilities:x,roster:ue,persona:Mu(O)??void 0},T=jl(b),D=De(O,"system-prompt.md");if(await Bu(D,T,{encoding:"utf8",mode:384}),g==="claude")try{let A=De(r,".claude","skills");await so(A,{recursive:!0});let X=C_(R_(import.meta.url)),Ct=De(X,"..","..","runtimes","skills"),Fe=(await I_(Ct)).filter(Te=>Te.endsWith(".md"));for(let Te of Fe){let hr=Te.replace(/\.md$/,""),ce=De(A,hr);await so(ce,{recursive:!0}),await N_(De(Ct,Te),De(ce,"SKILL.md"))}h("info",L,"Materialised Claude skills",{count:Fe.length,destRoot:A})}catch(A){E(L,"Failed to materialise Claude skills (continuing without)",A)}let q=De(O,"mcp-config.json"),I="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.",U=e.autonomous_agent.workroom_id,K,se=V?.channels.find(A=>A.member_ids.includes(i))?.id,R=new Map,B=[],M=[],F=[],ye=new Map,xe=A=>{if(v)return{set:(X,Ct)=>{ye.set(A,Ct);let Fe=[...ye.values()].some(Te=>Te!=="idle");v.set(X,Fe?"thinking":"idle")}}},Dt=0,We="",ft,ht=A=>{let X=R.get(A);return X||(X=Zt(A),R.set(A,X)),X};Y={start(){},enqueueUserTurn(A){ht(K??se??"__default").enqueueUserTurn(A)},stop(){for(let A of R.values())try{A.stop()}catch{}for(let A of R.keys())ur.delete(`${i}:${A}`)},stopChannel(A){let X=R.get(A);if(!X)return!1;try{X.stop()}catch{}return R.delete(A),ye.delete(A),ur.delete(`${i}:${A}`),!0},onBoundary(A){M.push(A)},onSessionId(A){},onExit(A){F.push(A)},onInjected(A){B.push(A)},onTurnError(A){},onCompact(A){}},ht(se??"__default");let Be=_u({agentId:i,onFire:async A=>{Y.enqueueUserTurn(`[reminder fired] ${A.title}`);try{await s.reminderFire(i,A.id,A.version)}catch(X){E(L,`reminder report-fire failed (agent ${i}, reminder ${A.id}) \u2014 local wake already happened; will retry on next sync`,X)}}}),ke=new _s(s),fr=A=>kr(e.server_url,t,i,A.startsWith("#")?A:"#"+A),On=hu({listOwnTasks:fr,gateway:s,host:Y,hostFor:ht,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:U,reminderCache:Be,onInboundMessage:A=>{K=A,ke.start(i,A)},...S?{contextTracker:S}:{},contextPolicy:P,mioDir:O,downloadAttachment:A=>ja(e.server_url,t,i,A).then(X=>({filename:X.filename,mime_type:X.mime_type,data_base64:X.data_base64}))});On.start(),Y.onBoundary(()=>{ke.stop(i)});let z=e.autonomous_agent,Me=Tu({listOwnTasks:fr,subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:Y,hostFor:ht,selfAgentId:i,workroomId:U,companion:ae,quietSeconds:z.quiet_seconds,maxRepliesPerWindow:z.max_replies_per_window,windowSeconds:z.window_seconds,contextPolicy:P});Me.start();let Ue=ue?.channelId??V?.channels.find(A=>A.member_ids.includes(i))?.id,it=Nu({workspace:r,mioDir:O,agentId:i,displayName:c,handle:a,role:d,workroomId:le,channelId:Ue,gateway:s,companion:ae,quietSeconds:z.quiet_seconds,spawnEnv:W,...m?{claudeCommand:m}:{}}),_o=A=>{try{let X=A.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(A.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(le).then(Fe=>no(ae,Fe)).catch(Fe=>E(L,`roster refetch failed for ${A.topic}`,Fe)),X.channel_id&&X.member_id&&ae.logObservation({channel_id:X.channel_id,entity_id:X.member_id,kind:A.topic})),A.topic==="message.created"&&X.sender_id&&X.channel_id){ae.logObservation({entity_id:X.sender_id,channel_id:X.channel_id,kind:"sent_message"});try{it.noteMessage()}catch(Fe){E(L,"personaCrystallizer.noteMessage error (non-fatal)",Fe)}}}catch(X){E(L,"companionWsHandler error (non-fatal)",X)}};return s.subscribe(le,_o),s.listReminders(i).then(A=>Be.snapshot(A)).catch(A=>E(L,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,A)),W_({gateway:s,agentId:i,taskWakeRouter:Me,bootRoster:V,mioDir:O}).catch(A=>E(L,`cold-start task self-heal failed for agent ${i} (non-fatal)`,A)),h("info",L,"Agentic spine started",{agentId:i,workroomId:U,mioDir:O}),F_(On,Y,J,i,Be,{companion:ae,gateway:s,workroomId:le,companionWsHandler:_o,taskWakeRouter:Me,personaCrystallizer:it})}catch(b){try{Y?.stop()}catch{}try{ae.close()}catch{}throw await J.close().catch(()=>{}),b}}function F_(n,e,t,r,s,i){e.onExit(c=>{h("warn",L,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",L,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){E(L,"coord.stop() error",c)}try{s.stop()}catch(c){E(L,"reminderCache.stop() error",c)}try{e.stop()}catch(c){E(L,"host.stop() error",c)}try{await t.close()}catch(c){E(L,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){E(L,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){E(L,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){E(L,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){E(L,"companion.close() error",c)}}h("info",L,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function q_(n){try{let e=await M_(De(n,Hu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function G_(n,e){try{await Bu(De(n,Hu),JSON.stringify([...e]),"utf8")}catch(t){E(L,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function W_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",L,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(f=>f.member_ids.includes(t)).map(f=>f.name).filter(f=>!!f)),o.length===0)try{o=(await e.getAgentChannels(t)).map(g=>g.name).filter(g=>!!g)}catch(f){E(L,`self-heal: getAgentChannels failed for agent ${t}`,f);return}if(o.length===0){h("debug",L,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],l=await Promise.allSettled(o.map(f=>a(t,f.startsWith("#")?f:`#${f}`)));for(let f of l)if(f.status==="fulfilled")for(let g of f.value)g.assignee_id===t&&g.status==="in_progress"&&c.push(g);else E(L,`self-heal: getTasks failed for a channel (agent ${t})`,f.reason);if(c.length===0){h("debug",L,"self-heal: no owned in_progress tasks",{agentId:t});return}let d=f=>{let g=f.updated_at??f.created_at,_=g?Date.parse(g):NaN;return Number.isFinite(_)?_:0};c.sort((f,g)=>d(g)-d(f));let u=await q_(i),m=c.filter(f=>!u.has(f.id)).slice(0,H_);if(m.length===0){h("debug",L,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(f=>f.id));let p=0;try{for(let f of m){let g=!1;if(f.parent_message_id&&e.getThreadReplies)try{g=(await e.getThreadReplies(t,f.parent_message_id,50)).some(S=>S.sender_id===t)}catch(_){E(L,`self-heal: getThreadReplies failed for task ${f.id} (agent ${t}) \u2014 treating as no activity`,_)}if(u.add(f.id),g){h("debug",L,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:f.id});continue}try{r.synthesizeAssignedWake({task_id:f.id,...f.channel_id?{channel_id:f.channel_id}:{},...f.parent_message_id?{parent_message_id:f.parent_message_id}:{}})&&(p+=1)}catch(_){E(L,`self-heal: synthesizeAssignedWake threw for task ${f.id} (agent ${t}) \u2014 task already marked seen, continuing`,_)}}}finally{await G_(i,u)}h("info",L,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:p})}function qu(n,e,t){let r=ar(n.replace(/^@/,"").toLowerCase()),s=ar(e),i=`${r}-${s}`,o=De(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function Gu(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 j_(n){try{let t=$_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&L_(t)}catch{return!1}}async function Wu(n){let{config:e,gateway:t,retrieveTokenFn:r=Rt,mkdirFn:s=v=>so(v,{recursive:!0,mode:448}),startSpineFn:i=Fu,mioDir:o=Uu,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=j_}=n,l=e.autonomous_agent;if(!l?.enabled)return;let d,u;try{d=r(),u=await a(l.workroom_id)}catch(v){E(L,"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",L,`No agent for this machine in workroom ${l.workroom_id} \u2014 create one first (daemon continues without spine)`,{machine_id:e.machine_id,workroom_id:l.workroom_id});return}let p=vu(),f=new ws(t),g=[],_=async v=>{let y=v.handle??"@"+v.display_name,P=y.replace(/^@/,"").toLowerCase().replace(/[^a-zA-Z0-9-]/g,"").length>0?y:`a${v.id.replace(/-/g,"").slice(0,8)}`,{selected:x,raw:O}=Gu(v.runtime);if(x==="codex"){if(!c("codex"))return h("error",L,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:v.id,handle:y}),!1}else if(x==="unsupported")return h("warn",L,`runtime '${O}' not supported; spine not started for this agent ${v.id}`,{agentId:v.id,handle:y,runtime:O}),!1;if(x==="claude"&&!c("claude"))return h("error",L,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:v.id,handle:y}),!1;try{let W=v.id,{workingDirectory:J}=qu(P,e.machine_id,o);await s(J);let Y=v.display_name||y.replace(/^@/,""),re=v.description||"An AI agent running on this machine.",ae=x==="codex"?"gpt-5-codex":"sonnet",V={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},le=v.model||ae,ue=V[le.trim().toLowerCase()]??le,$;if(x==="codex"){let w=v.capabilities;if(w&&typeof w=="object"){let b=w.reasoning_effort;typeof b=="string"&&(b==="low"||b==="medium"||b==="high")&&($=b)}$=$??"medium"}let Q=await i({config:e,machineToken:d,workingDirectory:J,gateway:t,agentId:W,launchId:Es(),agentHandle:y,displayName:Y,description:re,role:v.role,serverCapabilities:v.capabilities,model:ue,runtime:x,...$?{reasoningEffort:$}:{},contextTracker:p,presenceTracker:f});return g.push(Q),h("info",L,"Agentic spine started",{agentId:W,workroomId:l.workroom_id}),!0}catch(W){return E(L,`Failed to start spine for agent ${v.id} \u2014 continuing`,W),!1}return!0};for(let v of m)await _(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",L,"hot-add skipped \u2014 spine already running",{agentId:v}),!1;let k=(await a(l.workroom_id)).find(P=>P.kind==="agent"&&P.id===v&&P.machine_id===e.machine_id);return k?_(k):(h("warn",L,"hot-add: agent not found on this machine",{agentId:v}),!1)},async removeAgentById(v){let y=g.findIndex(P=>P.agentId===v);if(y<0)return!1;let[k]=g.splice(y,1);return await k.stop().catch(()=>{}),!0},dropChannel(v){for(let y of g)y.host.stopChannel?.(v)}}}async function oo(){h("info",L,"Starting mio-agent daemon");let n=Xe();h("info",L,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await _l();let e=new as;await P_(ro).catch(()=>{}),await e.listen(ro);let t=new cs("0.1.0");await t.listen(B_,U_);let r=new es(n);await r.start();let s=new ns(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>al().then(S=>{a=S}).catch(()=>{}),l=()=>a?{...a,sessions:io()}:{sampled_at:new Date().toISOString(),sessions:io()};c().then(()=>r.machineHeartbeat(!1,l()).catch(S=>E(L,"Initial machine heartbeat failed (non-fatal)",S)));let d=setInterval(()=>{c()},o),u=setInterval(()=>{r.machineHeartbeat(!1,l()).catch(S=>E(L,"Machine heartbeat failed (non-fatal)",S))},i),m=new os(r,{runtimes:n.runtimes,ipcSocketPath:ro}),p=new rs(s,m),f=await Wu({config:n,gateway:r,getWorkroomMembersFn:S=>r.getWorkroomMembers(S)});if(f&&n.autonomous_agent?.enabled){let S=n.autonomous_agent.workroom_id;r.subscribe(S,v=>{let y=v.payload??{};if(v.topic==="agent.created"){if(y.machine_id!==n.machine_id)return;let k=y.agent_id;if(typeof k!="string")return;h("info",L,"agent.created for this machine \u2014 hot-starting spine",{agentId:k}),f.addAgentById(k).then(P=>h("info",L,P?"hot-added agent spine \u2713":"hot-add no-op",{agentId:k})).catch(P=>E(L,"hot-add failed",P));return}if(v.topic==="agent.status"){if(!("machine_id"in y)||y.machine_id!==null||!y.disabled_by)return;let k=y.agent_id;if(typeof k!="string")return;f.removeAgentById(k).then(P=>{P&&h("info",L,"agent deleted \u2014 spine stopped, runtime processes reaped \u2713",{agentId:k})}).catch(P=>E(L,"hot-remove failed",P));return}if(v.topic==="channel.deleted"){let k=y.channel_id;if(typeof k!="string")return;f.dropChannel(k),h("info",L,"channel deleted \u2014 per-channel hosts reaped",{channelId:k})}})}e.onMessage(S=>{if(h("info",L,"IPC message from subprocess",{type:S.type}),m.onIpcMessage(S),S.type==="kick_persona"){let v=S.agent_id,y=S.reason??"ipc_kick";if(!f){h("warn",L,"IPC kick_persona: no spine running \u2014 ignoring");return}let k=0;for(let P of f.handles)if(!(v&&P.agentId!==v))try{P.personaCrystallizer?.kick(y),k+=1}catch(x){E(L,"IPC kick_persona: kick failed",x)}h("info",L,"IPC kick_persona dispatched",{kicked:k,targetAgent:v,reason:y});return}if(S.type==="join_workroom"){let v=S.workroom_id;if(!v){h("warn",L,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}p.openWorkroom(v).then(y=>{y?h("info",L,"IPC join_workroom: workroom opened",{workroomId:v,sessionId:y.sessionId}):h("warn",L,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:v})}).catch(y=>{E(L,"IPC join_workroom: unexpected error (should not happen)",y)})}}),h("info",L,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let g=!1;async function _(S){if(!g){g=!0,h("info",L,`${S} received \u2014 initiating graceful shutdown`);try{clearInterval(u),clearInterval(d),await r.machineHeartbeat(!0).catch(v=>E(L,"Going-offline heartbeat failed (non-fatal)",v)),m.beginShutdown(),await m.drainIrreversible(),p.shutdownAll(),await s.stop(),f&&await f.stop(),await r.stop(),await e.stop(),await t.stop(),h("info",L,"Graceful shutdown complete")}catch(v){E(L,"Error during shutdown",v)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{_("SIGTERM")}),process.on("SIGINT",()=>{_("SIGINT")}),await new Promise(()=>{})}var L,Uu,ro,B_,U_,ur,H_,Hu,ao=C(()=>{"use strict";Qe();en();ge();sl();cl();Wi();gl();pl();Vi();Tl();Cl();is();Hl();Jl();Xl();ru();au();gu();mu();yu();wu();bu();xu();Cu();Lu();ms();Ln();Ln();L="daemon",Uu=De(A_(),".mio"),ro=De(Uu,"agent.sock"),B_="127.0.0.1",U_=7878,ur=new Map;H_=5,Hu="self-heal-seen.json"});var co={};He(co,{runStart:()=>J_});async function J_(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 oo()}var lo=C(()=>{"use strict";ge();ao()});import{createHash as Y_}from"crypto";import{mkdtempSync as V_,rmSync as Ju,readFileSync as z_,copyFileSync as K_,chmodSync as X_,renameSync as Q_,existsSync as Yu}from"fs";import{execFileSync as An}from"child_process";import{tmpdir as Z_,platform as ew}from"os";import{join as xs}from"path";function sw(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function iw(n){return`https://github.com/${tw}/${nw}/releases/download/v${n}/`}function Vu(n,e){try{return An("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function ow(n,e){for(let t of n.split(`
588
- `)){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 zu(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=sw(),i=n._baseUrl??iw(e),o=`mio-agent-${e}-${s}.tar.gz`,a=`mio-agent-${e}-${s}`,c=`mio-agent-${e}-manifest.json`;r("Verifying release manifest...");let l;try{l=JSON.parse(Vu(i+c,"release manifest"))}catch(f){throw new Error(`Release manifest fetch/parse failed: ${f.message}`)}let d=new Set(l.required_fixes??[]),u=rw.filter(f=>!d.has(f));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=ow(Vu(i+"SHASUMS256.txt","SHASUMS256.txt"),o);if(!m)throw new Error(`SHA-256 entry for '${o}' not found in SHASUMS256.txt`);let p=V_(xs(Z_(),"mio-agent-install-"));try{r(`Downloading mio-agent ${e}...`);let f=xs(p,o);try{An("curl",["-fSL",i+o,"-o",f])}catch(y){throw new Error(`Binary download failed: ${y.message}`)}r("Verifying checksum...");let g=Y_("sha256").update(z_(f)).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 _=xs(p,"extract");An("mkdir",["-p",_]),An("tar",["-xzf",f,"-C",_]);let S=xs(_,a);if(!Yu(S))throw new Error(`mio-agent binary '${a}' not found inside the downloaded tarball`);r("Installing mio-agent...");let v=`${t}.staging`;Yu(v)&&Ju(v,{force:!0}),K_(S,v),X_(v,493),ew()==="darwin"&&!n._skipSign&&(An("codesign",["--force","--sign","-",v]),An("xattr",["-dr","com.apple.quarantine",v])),Q_(v,t)}finally{Ju(p,{recursive:!0,force:!0})}}var tw,nw,rw,Ku=C(()=>{"use strict";tw="MioMioOS",nw="mio-agent",rw=["machine-api-v1-prefix","socketio-control-path"]});var ef={};He(ef,{runInstall:()=>go});import{mkdirSync as Xu,writeFileSync as aw}from"fs";import{execFileSync as cw}from"child_process";import{homedir as Qu}from"os";import{join as Ts}from"path";async function go(n){if(!n.background){console.log("Starting daemon in foreground (use --background --version <semver> for LaunchAgent)");let{runStart:i}=await Promise.resolve().then(()=>(lo(),co));await i({background:!1});return}n.version||(console.error("Error: --background requires --version <semver>"),process.exit(1));let e=Xe(),t=n.version;console.log(`Installing mio-agent ${t} as LaunchAgent...`),Xu(Ts(_e,"bin"),{recursive:!0,mode:448}),zu({version:t,destPath:fo,onProgress:i=>console.log(i)}),e.pinned_version=t,br(e),Xu(Zu,{recursive:!0});let r=Qu(),s=`<?xml version="1.0" encoding="UTF-8"?>
588
+ \u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:A}`:""}catch{return""}},st=function(){if(p==="codex"){if(ft)return ft;try{ft=j_("sha1").update(Wu(D)).digest("hex").slice(0,16)}catch{ft=void 0}return ft}},Zt=function(A){let X=fu(O,p,A,st());h("info",L,X?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:p,channelId:A,...X?{sessionId:X}:{}});let Ct=xe(A),Fe={workingDirectory:r,systemPromptPath:D,mcpConfigPath:q,spawnEnv:W,firstTurnText:X?I:I+N(),...X?{sessionId:X}:{},...u?{spawnFn:u}:{},...Ct?{presenceTracker:Ct,agentId:i}:{}},Te=p==="codex"?du({...Fe,model:f??"gpt-5-codex",...w?{reasoningEffort:w}:{},...g?{codexCommand:g}:{}}):ru({...Fe,model:f??"sonnet",...m?{claudeCommand:m}:{}});Te.onSessionId(ce=>{h("info",L,"agent session id",{agentId:i,runtime:p,channelId:A,sessionId:ce}),hu(O,p,ce,A,st())});let pr=`${i}:${A}`;return fr.set(pr,{agent_id:i,agent_name:c,channel_id:A,runtime:p,model:f??null,started_at:new Date().toISOString(),turns:0,input_tokens:0,output_tokens:0,cache_read_tokens:0}),Te.onTurnUsage?.(ce=>{let Ae=fr.get(pr);Ae&&(Ae.turns+=1,Ae.input_tokens+=ce.inputTokens,Ae.output_tokens+=ce.outputTokens,Ae.cache_read_tokens+=ce.cacheReadTokens,Ae.last_turn_at=new Date().toISOString())}),Te.onInjected(ce=>{if(ce.includes("type=human]")){let Ae=/\bmsg=([0-9a-f]{8})/.exec(ce);_l(i,A,Ae?.[1])}for(let Ae of B)try{Ae(ce)}catch{}}),Te.onBoundary(()=>{wl(i,A)&&nn(e.server_url,U,A,{content:`\u26A0\uFE0F ${c} \u6536\u5230\u6D88\u606F\u5E76\u5B8C\u6210\u4E86\u5904\u7406,\u4F46\u672C\u8F6E\u6CA1\u6709\u53D1\u51FA\u4EFB\u4F55\u56DE\u590D\u2014\u2014\u53EF\u80FD\u9047\u5230\u53D1\u9001\u6545\u969C\u3002\u53EF\u8BA9\u5B83\u91CD\u8BD5,\u6216\u67E5\u770B daemon \u65E5\u5FD7(agent-trace)\u3002`,clientIdempotencyKey:Rs(),agentId:i},t).catch(ce=>E("run","silent-turn notice failed",ce));for(let ce of M)try{ce()}catch{}}),Te.onExit(ce=>{for(let Ae of F)try{Ae(ce)}catch{}}),Te.onTurnError?.(ce=>{let Ae=Date.now();if(ce===We&&Ae-Dt<6e4)return;We=ce,Dt=Ae;let kf=/usage limit/i.test(ce)?"\u7528\u91CF\u5DF2\u8FBE\u4E0A\u9650,\u8BF7\u5145\u503C\u6216\u7A0D\u540E\u518D\u8BD5":/unauthor|auth|401|403/i.test(ce)?"\u8BA4\u8BC1\u5931\u8D25,\u8BF7\u68C0\u67E5\u767B\u5F55/\u5BC6\u94A5":ce.slice(0,160);nn(e.server_url,U,A,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${kf})`,clientIdempotencyKey:Rs(),agentId:i},t).catch(Sf=>E("run","post turn-error notice failed",Sf))}),Te.onCompact?.(()=>{nn(e.server_url,U,A,{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:Rs(),agentId:i},t).catch(ce=>E("run","post compact notice failed",ce))}),Te.start(),Te};var $=N,Q=st,y=Zt;let b={agentId:i,handle:a,displayName:c,description:l,role:d,serverId:e.org_id,computer:`${Gu()} (${e.machine_id})`,hostname:Gu(),os:`${process.platform} ${B_()}`,workspace:r,runtime:p,capabilities:x,roster:ue,persona:Hu(O)??void 0},T=Ql(b),D=De(O,"system-prompt.md");if(await ju(D,T,{encoding:"utf8",mode:384}),p==="claude")try{let A=De(r,".claude","skills");await lo(A,{recursive:!0});let X=L_($_(import.meta.url)),Ct=De(X,"..","..","runtimes","skills"),Fe=(await F_(Ct)).filter(Te=>Te.endsWith(".md"));for(let Te of Fe){let pr=Te.replace(/\.md$/,""),ce=De(A,pr);await lo(ce,{recursive:!0}),await H_(De(Ct,Te),De(ce,"SKILL.md"))}h("info",L,"Materialised Claude skills",{count:Fe.length,destRoot:A})}catch(A){E(L,"Failed to materialise Claude skills (continuing without)",A)}let q=De(O,"mcp-config.json"),I="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.",U=e.autonomous_agent.workroom_id,z,se=V?.channels.find(A=>A.member_ids.includes(i))?.id,R=new Map,B=[],M=[],F=[],ye=new Map,xe=A=>{if(v)return{set:(X,Ct)=>{ye.set(A,Ct);let Fe=[...ye.values()].some(Te=>Te!=="idle");v.set(X,Fe?"thinking":"idle")}}},Dt=0,We="",ft,ht=A=>{let X=R.get(A);return X||(X=Zt(A),R.set(A,X)),X};Y={start(){},enqueueUserTurn(A){ht(z??se??"__default").enqueueUserTurn(A)},stop(){for(let A of R.values())try{A.stop()}catch{}for(let A of R.keys())fr.delete(`${i}:${A}`)},stopChannel(A){let X=R.get(A);if(!X)return!1;try{X.stop()}catch{}return R.delete(A),ye.delete(A),fr.delete(`${i}:${A}`),!0},onBoundary(A){M.push(A)},onSessionId(A){},onExit(A){F.push(A)},onInjected(A){B.push(A)},onTurnError(A){},onCompact(A){}},ht(se??"__default");let Be=xu({agentId:i,onFire:async A=>{Y.enqueueUserTurn(`[reminder fired] ${A.title}`);try{await s.reminderFire(i,A.id,A.version)}catch(X){E(L,`reminder report-fire failed (agent ${i}, reminder ${A.id}) \u2014 local wake already happened; will retry on next sync`,X)}}}),ke=new ks(s),hr=A=>Sr(e.server_url,t,i,A.startsWith("#")?A:"#"+A),On=vu({listOwnTasks:hr,gateway:s,host:Y,hostFor:ht,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:U,reminderCache:Be,onInboundMessage:A=>{z=A,ke.start(i,A)},...k?{contextTracker:k}:{},contextPolicy:P,mioDir:O,downloadAttachment:A=>za(e.server_url,t,i,A).then(X=>({filename:X.filename,mime_type:X.mime_type,data_base64:X.data_base64}))});On.start(),Y.onBoundary(()=>{ke.stop(i)});let K=e.autonomous_agent,Me=Nu({listOwnTasks:hr,subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:Y,hostFor:ht,selfAgentId:i,workroomId:U,companion:ae,quietSeconds:K.quiet_seconds,maxRepliesPerWindow:K.max_replies_per_window,windowSeconds:K.window_seconds,contextPolicy:P});Me.start();let Ue=ue?.channelId??V?.channels.find(A=>A.member_ids.includes(i))?.id,it=Fu({workspace:r,mioDir:O,agentId:i,displayName:c,handle:a,role:d,workroomId:le,channelId:Ue,gateway:s,companion:ae,quietSeconds:K.quiet_seconds,spawnEnv:W,...m?{claudeCommand:m}:{}}),So=A=>{try{let X=A.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(A.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(le).then(Fe=>ao(ae,Fe)).catch(Fe=>E(L,`roster refetch failed for ${A.topic}`,Fe)),X.channel_id&&X.member_id&&ae.logObservation({channel_id:X.channel_id,entity_id:X.member_id,kind:A.topic})),A.topic==="message.created"&&X.sender_id&&X.channel_id){ae.logObservation({entity_id:X.sender_id,channel_id:X.channel_id,kind:"sent_message"});try{it.noteMessage()}catch(Fe){E(L,"personaCrystallizer.noteMessage error (non-fatal)",Fe)}}}catch(X){E(L,"companionWsHandler error (non-fatal)",X)}};return s.subscribe(le,So),s.listReminders(i).then(A=>Be.snapshot(A)).catch(A=>E(L,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,A)),Q_({gateway:s,agentId:i,taskWakeRouter:Me,bootRoster:V,mioDir:O}).catch(A=>E(L,`cold-start task self-heal failed for agent ${i} (non-fatal)`,A)),h("info",L,"Agentic spine started",{agentId:i,workroomId:U,mioDir:O}),V_(On,Y,J,i,Be,{companion:ae,gateway:s,workroomId:le,companionWsHandler:So,taskWakeRouter:Me,personaCrystallizer:it})}catch(b){try{Y?.stop()}catch{}try{ae.close()}catch{}throw await J.close().catch(()=>{}),b}}function V_(n,e,t,r,s,i){e.onExit(c=>{h("warn",L,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",L,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){E(L,"coord.stop() error",c)}try{s.stop()}catch(c){E(L,"reminderCache.stop() error",c)}try{e.stop()}catch(c){E(L,"host.stop() error",c)}try{await t.close()}catch(c){E(L,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){E(L,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){E(L,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){E(L,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){E(L,"companion.close() error",c)}}h("info",L,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function z_(n){try{let e=await q_(De(n,Vu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function X_(n,e){try{await ju(De(n,Vu),JSON.stringify([...e]),"utf8")}catch(t){E(L,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function Q_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",L,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(f=>f.member_ids.includes(t)).map(f=>f.name).filter(f=>!!f)),o.length===0)try{o=(await e.getAgentChannels(t)).map(p=>p.name).filter(p=>!!p)}catch(f){E(L,`self-heal: getAgentChannels failed for agent ${t}`,f);return}if(o.length===0){h("debug",L,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],l=await Promise.allSettled(o.map(f=>a(t,f.startsWith("#")?f:`#${f}`)));for(let f of l)if(f.status==="fulfilled")for(let p of f.value)p.assignee_id===t&&p.status==="in_progress"&&c.push(p);else E(L,`self-heal: getTasks failed for a channel (agent ${t})`,f.reason);if(c.length===0){h("debug",L,"self-heal: no owned in_progress tasks",{agentId:t});return}let d=f=>{let p=f.updated_at??f.created_at,w=p?Date.parse(p):NaN;return Number.isFinite(w)?w:0};c.sort((f,p)=>d(p)-d(f));let u=await z_(i),m=c.filter(f=>!u.has(f.id)).slice(0,K_);if(m.length===0){h("debug",L,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(f=>f.id));let g=0;try{for(let f of m){let p=!1;if(f.parent_message_id&&e.getThreadReplies)try{p=(await e.getThreadReplies(t,f.parent_message_id,50)).some(k=>k.sender_id===t)}catch(w){E(L,`self-heal: getThreadReplies failed for task ${f.id} (agent ${t}) \u2014 treating as no activity`,w)}if(u.add(f.id),p){h("debug",L,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:f.id});continue}try{r.synthesizeAssignedWake({task_id:f.id,...f.channel_id?{channel_id:f.channel_id}:{},...f.parent_message_id?{parent_message_id:f.parent_message_id}:{}})&&(g+=1)}catch(w){E(L,`self-heal: synthesizeAssignedWake threw for task ${f.id} (agent ${t}) \u2014 task already marked seen, continuing`,w)}}}finally{await X_(i,u)}h("info",L,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:g})}function Ku(n,e,t){let r=cr(n.replace(/^@/,"").toLowerCase()),s=cr(e),i=`${r}-${s}`,o=De(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function zu(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 Z_(n){try{let t=W_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&G_(t)}catch{return!1}}async function Xu(n){let{config:e,gateway:t,retrieveTokenFn:r=Rt,mkdirFn:s=v=>lo(v,{recursive:!0,mode:448}),startSpineFn:i=Yu,mioDir:o=Ju,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=Z_}=n,l=e.autonomous_agent;if(!l?.enabled)return;let d,u;try{d=r(),u=await a(l.workroom_id)}catch(v){E(L,"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",L,`No agent for this machine in workroom ${l.workroom_id} \u2014 create one first (daemon continues without spine)`,{machine_id:e.machine_id,workroom_id:l.workroom_id});return}let g=Cu(),f=new Ss(t),p=[],w=async v=>{let _=v.handle??"@"+v.display_name,P=_.replace(/^@/,"").toLowerCase().replace(/[^a-zA-Z0-9-]/g,"").length>0?_:`a${v.id.replace(/-/g,"").slice(0,8)}`,{selected:x,raw:O}=zu(v.runtime);if(x==="codex"){if(!c("codex"))return h("error",L,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:v.id,handle:_}),!1}else if(x==="unsupported")return h("warn",L,`runtime '${O}' not supported; spine not started for this agent ${v.id}`,{agentId:v.id,handle:_,runtime:O}),!1;if(x==="claude"&&!c("claude"))return h("error",L,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:v.id,handle:_}),!1;try{let W=v.id,{workingDirectory:J}=Ku(P,e.machine_id,o);await s(J);let Y=v.display_name||_.replace(/^@/,""),re=v.description||"An AI agent running on this machine.",ae=x==="codex"?"gpt-5-codex":"sonnet",V={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},le=v.model||ae,ue=V[le.trim().toLowerCase()]??le,$;if(x==="codex"){let y=v.capabilities;if(y&&typeof y=="object"){let b=y.reasoning_effort;typeof b=="string"&&(b==="low"||b==="medium"||b==="high")&&($=b)}$=$??"medium"}let Q=await i({config:e,machineToken:d,workingDirectory:J,gateway:t,agentId:W,launchId:Rs(),agentHandle:_,displayName:Y,description:re,role:v.role,serverCapabilities:v.capabilities,model:ue,runtime:x,...$?{reasoningEffort:$}:{},contextTracker:g,presenceTracker:f});return p.push(Q),h("info",L,"Agentic spine started",{agentId:W,workroomId:l.workroom_id}),!0}catch(W){return E(L,`Failed to start spine for agent ${v.id} \u2014 continuing`,W),!1}return!0};for(let v of m)await w(v);if(p.length===0)return;let k=!1;return{handles:p,async stop(){k||(k=!0,await Promise.allSettled(p.map(v=>v.stop())))},async addAgentById(v){if(k)return!1;if(p.some(P=>P.agentId===v))return h("info",L,"hot-add skipped \u2014 spine already running",{agentId:v}),!1;let S=(await a(l.workroom_id)).find(P=>P.kind==="agent"&&P.id===v&&P.machine_id===e.machine_id);return S?w(S):(h("warn",L,"hot-add: agent not found on this machine",{agentId:v}),!1)},async removeAgentById(v){let _=p.findIndex(P=>P.agentId===v);if(_<0)return!1;let[S]=p.splice(_,1);return await S.stop().catch(()=>{}),!0},dropChannel(v){for(let _ of p)_.host.stopChannel?.(v)}}}async function fo(){h("info",L,"Starting mio-agent daemon");let n=Xe();h("info",L,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await xl(),gl((k,v)=>h("info",L,k,{count:v}));let e=new us;await U_(co).catch(()=>{}),await e.listen(co);let t=new fs("0.1.0");await t.listen(J_,Y_);let r=new ts(n);await r.start();let s=new os(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>fl().then(k=>{a=k}).catch(()=>{}),l=()=>a?{...a,sessions:uo()}:{sampled_at:new Date().toISOString(),sessions:uo()};c().then(()=>r.machineHeartbeat(!1,l()).catch(k=>E(L,"Initial machine heartbeat failed (non-fatal)",k)));let d=setInterval(()=>{c()},o),u=setInterval(()=>{r.machineHeartbeat(!1,l()).catch(k=>E(L,"Machine heartbeat failed (non-fatal)",k))},i),m=new ls(r,{runtimes:n.runtimes,ipcSocketPath:co}),g=new as(s,m),f=await Xu({config:n,gateway:r,getWorkroomMembersFn:k=>r.getWorkroomMembers(k)});if(f&&n.autonomous_agent?.enabled){let k=n.autonomous_agent.workroom_id;r.subscribe(k,v=>{let _=v.payload??{};if(v.topic==="agent.created"){if(_.machine_id!==n.machine_id)return;let S=_.agent_id;if(typeof S!="string")return;h("info",L,"agent.created for this machine \u2014 hot-starting spine",{agentId:S}),f.addAgentById(S).then(P=>h("info",L,P?"hot-added agent spine \u2713":"hot-add no-op",{agentId:S})).catch(P=>E(L,"hot-add failed",P));return}if(v.topic==="agent.status"){if(!("machine_id"in _)||_.machine_id!==null||!_.disabled_by)return;let S=_.agent_id;if(typeof S!="string")return;f.removeAgentById(S).then(P=>{P&&h("info",L,"agent deleted \u2014 spine stopped, runtime processes reaped \u2713",{agentId:S})}).catch(P=>E(L,"hot-remove failed",P));return}if(v.topic==="channel.deleted"){let S=_.channel_id;if(typeof S!="string")return;f.dropChannel(S),h("info",L,"channel deleted \u2014 per-channel hosts reaped",{channelId:S})}})}e.onMessage(k=>{if(h("info",L,"IPC message from subprocess",{type:k.type}),m.onIpcMessage(k),k.type==="kick_persona"){let v=k.agent_id,_=k.reason??"ipc_kick";if(!f){h("warn",L,"IPC kick_persona: no spine running \u2014 ignoring");return}let S=0;for(let P of f.handles)if(!(v&&P.agentId!==v))try{P.personaCrystallizer?.kick(_),S+=1}catch(x){E(L,"IPC kick_persona: kick failed",x)}h("info",L,"IPC kick_persona dispatched",{kicked:S,targetAgent:v,reason:_});return}if(k.type==="join_workroom"){let v=k.workroom_id;if(!v){h("warn",L,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}g.openWorkroom(v).then(_=>{_?h("info",L,"IPC join_workroom: workroom opened",{workroomId:v,sessionId:_.sessionId}):h("warn",L,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:v})}).catch(_=>{E(L,"IPC join_workroom: unexpected error (should not happen)",_)})}}),h("info",L,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let p=!1;async function w(k){if(!p){p=!0,h("info",L,`${k} received \u2014 initiating graceful shutdown`);try{clearInterval(u),clearInterval(d),await r.machineHeartbeat(!0).catch(v=>E(L,"Going-offline heartbeat failed (non-fatal)",v)),m.beginShutdown(),await m.drainIrreversible(),g.shutdownAll(),await s.stop(),f&&await f.stop(),Yi("SIGKILL"),await r.stop(),await e.stop(),await t.stop(),h("info",L,"Graceful shutdown complete")}catch(v){E(L,"Error during shutdown",v)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{w("SIGTERM")}),process.on("SIGINT",()=>{w("SIGINT")}),process.on("exit",()=>{Yi("SIGKILL")}),await new Promise(()=>{})}var L,Ju,co,J_,Y_,fr,K_,Vu,ho=C(()=>{"use strict";Qe();en();pe();dl();hl();is();Ki();bl();kl();Zi();Nl();Ml();ds();Vl();Zl();su();lu();pu();bu();Su();Eu();Tu();Ru();Iu();Mu();qu();vs();Ln();Ln();L="daemon",Ju=De(D_(),".mio"),co=De(Ju,"agent.sock"),J_="127.0.0.1",Y_=7878,fr=new Map;K_=5,Vu="self-heal-seen.json"});var po={};He(po,{runStart:()=>ew});async function ew(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 fo()}var go=C(()=>{"use strict";pe();ho()});import{createHash as tw}from"crypto";import{mkdtempSync as nw,rmSync as Zu,readFileSync as rw,copyFileSync as sw,chmodSync as iw,renameSync as ow,existsSync as ef}from"fs";import{execFileSync as An}from"child_process";import{tmpdir as aw,platform as cw}from"os";import{join as As}from"path";function fw(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function hw(n){return`https://github.com/${dw}/${lw}/releases/download/v${n}/`}function tf(n,e){try{return An("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function pw(n,e){for(let t of n.split(`
589
+ `)){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 nf(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=fw(),i=n._baseUrl??hw(e),o=`mio-agent-${e}-${s}.tar.gz`,a=`mio-agent-${e}-${s}`,c=`mio-agent-${e}-manifest.json`;r("Verifying release manifest...");let l;try{l=JSON.parse(tf(i+c,"release manifest"))}catch(f){throw new Error(`Release manifest fetch/parse failed: ${f.message}`)}let d=new Set(l.required_fixes??[]),u=uw.filter(f=>!d.has(f));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=pw(tf(i+"SHASUMS256.txt","SHASUMS256.txt"),o);if(!m)throw new Error(`SHA-256 entry for '${o}' not found in SHASUMS256.txt`);let g=nw(As(aw(),"mio-agent-install-"));try{r(`Downloading mio-agent ${e}...`);let f=As(g,o);try{An("curl",["-fSL",i+o,"-o",f])}catch(_){throw new Error(`Binary download failed: ${_.message}`)}r("Verifying checksum...");let p=tw("sha256").update(rw(f)).digest("hex");if(p!==m)throw new Error(`Checksum mismatch \u2014 expected ${m.slice(0,12)}\u2026, got ${p.slice(0,12)}\u2026`);r("Extracting binary...");let w=As(g,"extract");An("mkdir",["-p",w]),An("tar",["-xzf",f,"-C",w]);let k=As(w,a);if(!ef(k))throw new Error(`mio-agent binary '${a}' not found inside the downloaded tarball`);r("Installing mio-agent...");let v=`${t}.staging`;ef(v)&&Zu(v,{force:!0}),sw(k,v),iw(v,493),cw()==="darwin"&&!n._skipSign&&(An("codesign",["--force","--sign","-",v]),An("xattr",["-dr","com.apple.quarantine",v])),ow(v,t)}finally{Zu(g,{recursive:!0,force:!0})}}var dw,lw,uw,rf=C(()=>{"use strict";dw="MioMioOS",lw="mio-agent",uw=["machine-api-v1-prefix","socketio-control-path"]});var cf={};He(cf,{runInstall:()=>wo});import{mkdirSync as sf,writeFileSync as gw}from"fs";import{execFileSync as mw}from"child_process";import{homedir as of}from"os";import{join as Os}from"path";async function wo(n){if(!n.background){console.log("Starting daemon in foreground (use --background --version <semver> for LaunchAgent)");let{runStart:i}=await Promise.resolve().then(()=>(go(),po));await i({background:!1});return}n.version||(console.error("Error: --background requires --version <semver>"),process.exit(1));let e=Xe(),t=n.version;console.log(`Installing mio-agent ${t} as LaunchAgent...`),sf(Os(_e,"bin"),{recursive:!0,mode:448}),nf({version:t,destPath:yo,onProgress:i=>console.log(i)}),e.pinned_version=t,kr(e),sf(af,{recursive:!0});let r=of(),s=`<?xml version="1.0" encoding="UTF-8"?>
589
590
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
590
591
  <plist version="1.0">
591
592
  <dict>
592
593
  <key>Label</key>
593
- <string>${ho}</string>
594
+ <string>${_o}</string>
594
595
  <key>ProgramArguments</key>
595
596
  <array>
596
- <string>${fo}</string>
597
+ <string>${yo}</string>
597
598
  <string>run</string>
598
599
  </array>
599
600
  <key>RunAtLoad</key>
@@ -601,20 +602,20 @@ ${A.length>6e3?A.slice(0,6e3)+`
601
602
  <key>KeepAlive</key>
602
603
  <true/>
603
604
  <key>ExitTimeOut</key>
604
- <integer>${xl}</integer>
605
+ <integer>${Il}</integer>
605
606
  <key>StandardOutPath</key>
606
607
  <string>${r}/.mio/logs/mio-agent.log</string>
607
608
  <key>StandardErrorPath</key>
608
609
  <string>${r}/.mio/logs/mio-agent-error.log</string>
609
610
  </dict>
610
- </plist>`;aw(uo,s,{encoding:"utf-8",mode:420}),cw("launchctl",["bootstrap",`gui/${process.getuid()}`,uo]),console.log(`
611
- mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${fo}`),console.log(` Plist: ${uo}`),console.log(` Label: ${ho}`),console.log(`
612
- Run: mio-agent doctor \u2014 to verify health`)}var ho,Zu,uo,fo,po=C(()=>{"use strict";Qe();Vi();Ku();ho="io.miomioos.mio-agent",Zu=Ts(Qu(),"Library","LaunchAgents"),uo=Ts(Zu,`${ho}.plist`),fo=Ts(_e,"bin","mio-agent")});var mo={};He(mo,{runUpgrade:()=>uw,runUpgradeCheck:()=>lw});import{execFileSync as dw}from"child_process";async function lw(){let e=Xe().pinned_version??"unknown (foreground/dev mode)",t=dw("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.":`
613
- To upgrade: mio-agent upgrade --version ${t}`)}async function uw(n){let e=Xe();e.pinned_version=n.version,br(e),console.log(`Pinned version updated to ${n.version} in config.`),await go({background:!0,version:n.version})}var yo=C(()=>{"use strict";Qe();po()});var tf={};He(tf,{runStop:()=>gw});import{execFileSync as fw}from"child_process";async function gw(){try{fw("launchctl",["stop",hw]),console.log("Daemon stopped.")}catch{console.log("Daemon was not running or stop signal sent.")}}var hw,nf=C(()=>{"use strict";hw="io.miomioos.mio-agent"});var of={};He(of,{runUninstall:()=>ww});import{execFileSync as pw}from"child_process";import{rmSync as rf,existsSync as sf}from"fs";import{join as mw}from"path";import{homedir as yw}from"os";async function ww(){console.log("Uninstalling mio-agent...");try{pw("launchctl",["bootout",`gui/${process.getuid()}`,Cs]),console.log(" LaunchAgent unregistered.")}catch{console.log(" LaunchAgent was not registered (skipped).")}sf(Cs)&&(rf(Cs),console.log(` Deleted: ${Cs}`));try{No(),console.log(" Keychain entry deleted.")}catch{console.log(" No Keychain entry found (skipped).")}sf(_e)&&(rf(_e,{recursive:!0,force:!0}),console.log(` Deleted: ${_e}`)),console.log(`
614
- mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var _w,Cs,af=C(()=>{"use strict";en();Qe();_w="io.miomioos.mio-agent",Cs=mw(yw(),"Library","LaunchAgents",`${_w}.plist`)});var df={};He(df,{runDoctor:()=>kw});import{execFileSync as vw,spawnSync as cf}from"child_process";import{existsSync as bw}from"fs";function Tt(n,e,t){let r=e?"\u2705":"\u274C",s=t?`${r} ${n}: ${t}`:`${r} ${n}`;console.log(s)}async function kw(){console.log(`mio-agent doctor
615
- `);let n=ga();if(Tt("Config (~/.mio/agent.json)",n,n?"found":"missing \u2014 run: mio-agent login"),!n)return;let e=Xe(),t=!1;try{vw("security",["find-generic-password","-s","io.miomioos.mio-agent","-a","machine_token"],{stdio:"ignore"}),t=!0}catch{}Tt("Keychain (machine_token)",t,t?"found":"missing \u2014 run: mio-agent login");let r=!1;try{r=cf("curl",["-fsS","--max-time","3",`${e.server_url}/health`]).status===0}catch{}Tt("Server connectivity",r,r?e.server_url:`unreachable: ${e.server_url}`);let s=!1;try{s=cf("curl",["-fsS","--max-time","1",`http://127.0.0.1:${ha}/health`]).status===0}catch{}Tt("Daemon (127.0.0.1:7878)",s,s?"running":"not running"),console.log(""),console.log("Runtimes:");let i=xn();if(i)Tt(" claude",!0,i);else{Tt(" claude",!1,"not found");for(let c of zl().split(`
616
- `))console.log(` ${c}`)}let o=ps();if(o){let c=(process.env.MIO_CODEX_MODEL||"").trim();Tt(" codex",!0,c?`${o} (model override: ${c})`:`${o} (model: local default)`)}else{Tt(" codex",!1,"not found");for(let c of Zl().split(`
617
- `))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>bw(c));Tt(" opencode",!!a,a??"not found in PATH"),console.log("")}var lf=C(()=>{"use strict";Qe();hs();eo()});var ff={};He(ff,{buildPairingDeeplink:()=>uf,runPairPhone:()=>xw});function uf(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 Sw(n){let e=new Date(n).getTime()-Date.now();return`${Math.max(0,Math.round(e/6e4))} min`}function Ew(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 xw(n){n||(console.error("Usage: mio-agent pair-phone <workroom_id>"),process.exit(1));let e=Xe(),t;try{t=Rt()}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 ${Ew(s.status)}`),process.exit(1);return}let i=await s.json(),o=uf(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 ${Sw(i.expires_at)} (${i.expires_at})`),console.log(` Pairing: ${i.pairing_id}`),console.log("");let a=!1;try{let c=await Promise.resolve().then(()=>oe(Bs(),1)).catch(()=>null),l=c?.default??c;typeof l?.generate=="function"&&(l.generate(o,{small:!0},d=>console.log(d)),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 hf=C(()=>{"use strict";Qe();en()});import{parseArgs as Tw}from"util";import{fileURLToPath as Cw}from"url";import{realpathSync as gf}from"fs";function Rw(n){return n[0]==="agentcli"}function Aw(n){return n[0]==="login"}async function Ow(){let n=process.argv.slice(2);if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){let{getPackageVersion:i}=await Promise.resolve().then(()=>(bo(),vo));console.log(i()),process.exit(0)}if(Rw(n)){let{runAgentcliCommand:i}=await Promise.resolve().then(()=>(Io(),Po));process.exit(await i())}if(Aw(n)){let{runLogin:i}=await Promise.resolve().then(()=>(ca(),aa));process.exit(await i(process.argv.slice(3)))}if(n[0]==="logs"){let{runLogs:i}=await Promise.resolve().then(()=>(ua(),la));process.exit(await i(process.argv.slice(3)))}let{values:e,positionals:t}=Tw({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(()=>(lo(),co));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(()=>(po(),ef));await i({background:e.background??!1,version:e.version});break}case"upgrade":{if(e.check){let{runUpgradeCheck:i}=await Promise.resolve().then(()=>(yo(),mo));await i()}else if(e.version){let{runUpgrade:i}=await Promise.resolve().then(()=>(yo(),mo));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(()=>(ao(),ju));await i();break}case"stop":{let{runStop:i}=await Promise.resolve().then(()=>(nf(),tf));await i();break}case"uninstall":{let{runUninstall:i}=await Promise.resolve().then(()=>(af(),of));await i();break}case"doctor":{let{runDoctor:i}=await Promise.resolve().then(()=>(lf(),df));await i();break}case"pair-phone":{let{runPairPhone:i}=await Promise.resolve().then(()=>(hf(),ff));await i(s[0]);break}default:console.log(`Mio Agent \u2014 background AI worker daemon
611
+ </plist>`;gw(mo,s,{encoding:"utf-8",mode:420}),mw("launchctl",["bootstrap",`gui/${process.getuid()}`,mo]),console.log(`
612
+ mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${yo}`),console.log(` Plist: ${mo}`),console.log(` Label: ${_o}`),console.log(`
613
+ Run: mio-agent doctor \u2014 to verify health`)}var _o,af,mo,yo,vo=C(()=>{"use strict";Qe();Zi();rf();_o="io.miomioos.mio-agent",af=Os(of(),"Library","LaunchAgents"),mo=Os(af,`${_o}.plist`),yo=Os(_e,"bin","mio-agent")});var bo={};He(bo,{runUpgrade:()=>ww,runUpgradeCheck:()=>_w});import{execFileSync as yw}from"child_process";async function _w(){let e=Xe().pinned_version??"unknown (foreground/dev mode)",t=yw("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.":`
614
+ To upgrade: mio-agent upgrade --version ${t}`)}async function ww(n){let e=Xe();e.pinned_version=n.version,kr(e),console.log(`Pinned version updated to ${n.version} in config.`),await wo({background:!0,version:n.version})}var ko=C(()=>{"use strict";Qe();vo()});var df={};He(df,{runStop:()=>kw});import{execFileSync as vw}from"child_process";async function kw(){try{vw("launchctl",["stop",bw]),console.log("Daemon stopped.")}catch{console.log("Daemon was not running or stop signal sent.")}}var bw,lf=C(()=>{"use strict";bw="io.miomioos.mio-agent"});var hf={};He(hf,{runUninstall:()=>Cw});import{execFileSync as Sw}from"child_process";import{rmSync as uf,existsSync as ff}from"fs";import{join as Ew}from"path";import{homedir as xw}from"os";async function Cw(){console.log("Uninstalling mio-agent...");try{Sw("launchctl",["bootout",`gui/${process.getuid()}`,Ps]),console.log(" LaunchAgent unregistered.")}catch{console.log(" LaunchAgent was not registered (skipped).")}ff(Ps)&&(uf(Ps),console.log(` Deleted: ${Ps}`));try{Bo(),console.log(" Keychain entry deleted.")}catch{console.log(" No Keychain entry found (skipped).")}ff(_e)&&(uf(_e,{recursive:!0,force:!0}),console.log(` Deleted: ${_e}`)),console.log(`
615
+ mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var Tw,Ps,pf=C(()=>{"use strict";en();Qe();Tw="io.miomioos.mio-agent",Ps=Ew(xw(),"Library","LaunchAgents",`${Tw}.plist`)});var mf={};He(mf,{runDoctor:()=>Ow});import{execFileSync as Rw,spawnSync as gf}from"child_process";import{existsSync as Aw}from"fs";function Tt(n,e,t){let r=e?"\u2705":"\u274C",s=t?`${r} ${n}: ${t}`:`${r} ${n}`;console.log(s)}async function Ow(){console.log(`mio-agent doctor
616
+ `);let n=wa();if(Tt("Config (~/.mio/agent.json)",n,n?"found":"missing \u2014 run: mio-agent login"),!n)return;let e=Xe(),t=!1;try{Rw("security",["find-generic-password","-s","io.miomioos.mio-agent","-a","machine_token"],{stdio:"ignore"}),t=!0}catch{}Tt("Keychain (machine_token)",t,t?"found":"missing \u2014 run: mio-agent login");let r=!1;try{r=gf("curl",["-fsS","--max-time","3",`${e.server_url}/health`]).status===0}catch{}Tt("Server connectivity",r,r?e.server_url:`unreachable: ${e.server_url}`);let s=!1;try{s=gf("curl",["-fsS","--max-time","1",`http://127.0.0.1:${_a}/health`]).status===0}catch{}Tt("Daemon (127.0.0.1:7878)",s,s?"running":"not running"),console.log(""),console.log("Runtimes:");let i=xn();if(i)Tt(" claude",!0,i);else{Tt(" claude",!1,"not found");for(let c of nu().split(`
617
+ `))console.log(` ${c}`)}let o=ws();if(o){let c=(process.env.MIO_CODEX_MODEL||"").trim();Tt(" codex",!0,c?`${o} (model override: ${c})`:`${o} (model: local default)`)}else{Tt(" codex",!1,"not found");for(let c of ou().split(`
618
+ `))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>Aw(c));Tt(" opencode",!!a,a??"not found in PATH"),console.log("")}var yf=C(()=>{"use strict";Qe();ys();io()});var wf={};He(wf,{buildPairingDeeplink:()=>_f,runPairPhone:()=>Nw});function _f(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 Pw(n){let e=new Date(n).getTime()-Date.now();return`${Math.max(0,Math.round(e/6e4))} min`}function Iw(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 Nw(n){n||(console.error("Usage: mio-agent pair-phone <workroom_id>"),process.exit(1));let e=Xe(),t;try{t=Rt()}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 ${Iw(s.status)}`),process.exit(1);return}let i=await s.json(),o=_f(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 ${Pw(i.expires_at)} (${i.expires_at})`),console.log(` Pairing: ${i.pairing_id}`),console.log("");let a=!1;try{let c=await Promise.resolve().then(()=>oe(qs(),1)).catch(()=>null),l=c?.default??c;typeof l?.generate=="function"&&(l.generate(o,{small:!0},d=>console.log(d)),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 vf=C(()=>{"use strict";Qe();en()});import{parseArgs as Mw}from"util";import{fileURLToPath as Lw}from"url";import{realpathSync as bf}from"fs";function $w(n){return n[0]==="agentcli"}function Dw(n){return n[0]==="login"}async function Bw(){let n=process.argv.slice(2);if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){let{getPackageVersion:i}=await Promise.resolve().then(()=>(To(),xo));console.log(i()),process.exit(0)}if($w(n)){let{runAgentcliCommand:i}=await Promise.resolve().then(()=>(Do(),$o));process.exit(await i())}if(Dw(n)){let{runLogin:i}=await Promise.resolve().then(()=>(ha(),fa));process.exit(await i(process.argv.slice(3)))}if(n[0]==="logs"){let{runLogs:i}=await Promise.resolve().then(()=>(ma(),ga));process.exit(await i(process.argv.slice(3)))}let{values:e,positionals:t}=Mw({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(()=>(go(),po));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(()=>(vo(),cf));await i({background:e.background??!1,version:e.version});break}case"upgrade":{if(e.check){let{runUpgradeCheck:i}=await Promise.resolve().then(()=>(ko(),bo));await i()}else if(e.version){let{runUpgrade:i}=await Promise.resolve().then(()=>(ko(),bo));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(()=>(ho(),Qu));await i();break}case"stop":{let{runStop:i}=await Promise.resolve().then(()=>(lf(),df));await i();break}case"uninstall":{let{runUninstall:i}=await Promise.resolve().then(()=>(pf(),hf));await i();break}case"doctor":{let{runDoctor:i}=await Promise.resolve().then(()=>(yf(),mf));await i();break}case"pair-phone":{let{runPairPhone:i}=await Promise.resolve().then(()=>(vf(),wf));await i(s[0]);break}default:console.log(`Mio Agent \u2014 background AI worker daemon
618
619
 
619
620
  Global flags:
620
621
  --version, -v Print version and exit
@@ -633,7 +634,7 @@ Commands:
633
634
  logs [-n N] [-f] Tail daemon logs (~/.mio/logs/, or /tmp/mio-agent.log in dev mode)
634
635
  agentcli <subcommand> Agent-facing CLI (message check/send/read); use --help for details
635
636
  run Internal: launched by launchd (do not call directly)
636
- `),process.exit(r?1:0)}}function Pw(){try{let n=te("node:sea");return typeof n.isSea=="function"&&n.isSea()}catch{return!1}}function Iw(){if(Pw())return!0;let n=process.argv[1];if(!n)return!1;try{return gf(Cw(import.meta.url))===gf(n)}catch{return!1}}Iw()&&Ow().catch(n=>{console.error("Fatal:",n.message),process.exit(1)});export{Rw as isAgentcliInvocation,Aw as isLoginInvocation};
637
+ `),process.exit(r?1:0)}}function Uw(){try{let n=te("node:sea");return typeof n.isSea=="function"&&n.isSea()}catch{return!1}}function Fw(){if(Uw())return!0;let n=process.argv[1];if(!n)return!1;try{return bf(Lw(import.meta.url))===bf(n)}catch{return!1}}Fw()&&Bw().catch(n=>{console.error("Fatal:",n.message),process.exit(1)});export{$w as isAgentcliInvocation,Dw as isLoginInvocation};
637
638
  /*! Bundled license information:
638
639
 
639
640
  xmlhttprequest-ssl/lib/XMLHttpRequest.js: