@miomioos/mio-agent 0.3.9 → 0.3.10

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 +166 -166
  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 lf=Object.create;var vs=Object.defineProperty;var uf=Object.getOwnPropertyDescriptor;var ff=Object.getOwnPropertyNames;var hf=Object.getPrototypeOf,pf=Object.prototype.hasOwnProperty;var X=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var O=(n,e)=>()=>(n&&(e=n(n=0)),e);var K=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),$e=(n,e)=>{for(var t in e)vs(n,t,{get:e[t],enumerable:!0})},gf=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ff(e))!pf.call(n,s)&&s!==t&&vs(n,s,{get:()=>e[s],enumerable:!(r=uf(e,s))||r.enumerable});return n};var te=(n,e,t)=>(t=n!=null?lf(hf(n)):{},gf(e||!n||!n.__esModule?vs(t,"default",{value:n,enumerable:!0}):t,n));var ho={};$e(ho,{MIO_AGENT_VERSION:()=>fo,getPackageVersion:()=>mf});function mf(){return fo}var fo,po=O(()=>{"use strict";fo="0.2.1"});import{readFileSync as yo,writeFileSync as yf}from"fs";import{basename as _f,extname as wf}from"path";import{randomUUID as _o}from"crypto";async function wo(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(nh),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 ff=Object.create;var bs=Object.defineProperty;var hf=Object.getOwnPropertyDescriptor;var pf=Object.getOwnPropertyNames;var gf=Object.getPrototypeOf,mf=Object.prototype.hasOwnProperty;var X=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var O=(n,e)=>()=>(n&&(e=n(n=0)),e);var K=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),$e=(n,e)=>{for(var t in e)bs(n,t,{get:e[t],enumerable:!0})},yf=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pf(e))!mf.call(n,s)&&s!==t&&bs(n,s,{get:()=>e[s],enumerable:!(r=hf(e,s))||r.enumerable});return n};var te=(n,e,t)=>(t=n!=null?ff(gf(n)):{},yf(e||!n||!n.__esModule?bs(t,"default",{value:n,enumerable:!0}):t,n));var po={};$e(po,{MIO_AGENT_VERSION:()=>ho,getPackageVersion:()=>_f});function _f(){return ho}var ho,go=O(()=>{"use strict";ho="0.2.1"});import{readFileSync as _o,writeFileSync as wf}from"fs";import{basename as vf,extname as bf}from"path";import{randomUUID as wo}from"crypto";async function vo(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(sh),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=yo(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=_o(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"?vf(l,d,i,a,s,t,r):c==="task"?Tf(l,d,i,a,t,r):c==="reminder"?Nf(l,d,i,a,t,r):c==="action"?Wf(l,d,i,a,t,r):c==="attachment"?zf(l,d,i,a,t,r):c==="profile"?Qf(l,d,i,a,t,r):(r.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown command: ${n.join(" ")}`})+`
8
- `),1)}async function vf(n,e,t,r,s,i,o){switch(n){case"check":return bf(e,t,r,i,o);case"send":return kf(e,t,r,s,i,o);case"read":return Sf(e,t,r,i,o);case"react":return Ef(e,t,r,i,o);case"reply":return xf(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 bf(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message check"})+`
10
- `),1;let o=await de(e,t,"check",{channel:i});return o.ok?(bo(o.data,r),0):(s.write(JSON.stringify(o.error)+`
11
- `),1)}async function kf(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,d,...l]=n;return c==="message"?kf(d,l,i,a,s,t,r):c==="task"?Rf(d,l,i,a,t,r):c==="reminder"?Lf(d,l,i,a,t,r):c==="action"?Jf(d,l,i,a,t,r):c==="attachment"?Xf(d,l,i,a,t,r):c==="profile"?eh(d,l,i,a,t,r):(r.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown command: ${n.join(" ")}`})+`
8
+ `),1)}async function kf(n,e,t,r,s,i,o){switch(n){case"check":return Sf(e,t,r,i,o);case"send":return Ef(e,t,r,s,i,o);case"read":return xf(e,t,r,i,o);case"react":return Tf(e,t,r,i,o);case"reply":return Cf(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 Sf(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message check"})+`
10
+ `),1;let o=await le(e,t,"check",{channel:i});return o.ok?(ko(o.data,r),0):(s.write(JSON.stringify(o.error)+`
11
+ `),1)}async function Ef(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=U(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 ko(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=_o(),l=ir(n,"--attachment");for(let _ of ir(n,"--attach-file")){let k=await Ss(_,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 de(e,t,"send",d);if(!u.ok)return i.write(JSON.stringify(u.error)+`
17
+ `),1;let a=await So(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=wo(),d=or(n,"--attachment");for(let _ of or(n,"--attach-file")){let k=await Es(_,o,e,t);if(!k.ok)return i.write(JSON.stringify(k.error)+`
19
+ `),1;d.push(k.id)}let l={target:o,content:a,clientIdempotencyKey:c};d.length>0&&(l.attachment_ids=d);let u=await le(e,t,"send",l);if(!u.ok)return i.write(JSON.stringify(u.error)+`
20
20
  `),1;let m=u.data,f=String(m.id??""),p=String(m.short_id??m.shortId??"").slice(0,8),g=m.seq!==void 0?`seq=${m.seq} `:"",y=typeof m.routed_to=="string"?m.routed_to:"",E=typeof m.task_number=="number"?m.task_number:null,w="";return y==="thread"&&E!==null&&(w=` (auto-routed to thread of task #${E} \u2014 you have an active task in this channel, so this send went into its thread, NOT the main channel. Tell users your message is in the task thread, not main.)`),s.write(`sent: id=${f} ${p?`short=${p} `:""}${g}target=${o}${w}
21
- `),0}async function Sf(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message read"})+`
22
- `),1;let o={channel:i},a=U(n,"--after"),c=U(n,"--around"),l=U(n,"--before"),d=U(n,"--limit");if([a,c,l].filter(f=>f!==void 0).length>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --after, --around, --before may be provided"})+`
23
- `),1;if(a&&(o.after_seq=a),c&&(o.around=c),l&&(o.around=l),d!==void 0){let f=Number(d);if(!Number.isInteger(f)||f<=0)return s.write(JSON.stringify({ok:!1,code:"INVALID_LIMIT",message:`--limit must be a positive integer, got: ${d}`})+`
24
- `),1;o.limit=f}let m=await de(e,t,"history",o);return m.ok?(bo(m.data,r),0):(s.write(JSON.stringify(m.error)+`
25
- `),1)}async function Ef(n,e,t,r,s){let i=at(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a message id is required for message react"})+`
21
+ `),0}async function xf(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message read"})+`
22
+ `),1;let o={channel:i},a=U(n,"--after"),c=U(n,"--around"),d=U(n,"--before"),l=U(n,"--limit");if([a,c,d].filter(f=>f!==void 0).length>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --after, --around, --before may be provided"})+`
23
+ `),1;if(a&&(o.after_seq=a),c&&(o.around=c),d&&(o.around=d),l!==void 0){let f=Number(l);if(!Number.isInteger(f)||f<=0)return s.write(JSON.stringify({ok:!1,code:"INVALID_LIMIT",message:`--limit must be a positive integer, got: ${l}`})+`
24
+ `),1;o.limit=f}let m=await le(e,t,"history",o);return m.ok?(ko(m.data,r),0):(s.write(JSON.stringify(m.error)+`
25
+ `),1)}async function Tf(n,e,t,r,s){let i=at(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=U(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=U(n,"--emoji");if(!a)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--emoji <emoji> is required for message react"})+`
28
- `),1;let c=n.includes("--remove")?"remove":"add",l=await de(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
- `),0):(s.write(JSON.stringify(l.error)+`
30
- `),1)}async function xf(n,e,t,r,s,i){let o=U(n,"--parent");if(!o)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--parent <message-id> is required for message reply"})+`
28
+ `),1;let c=n.includes("--remove")?"remove":"add",d=await le(e,t,"react",{target:o,message_id:i,emoji:a,op:c});return d.ok?(r.write(`reacted: ${c} ${a} on msg=${i} in ${o}
29
+ `),0):(s.write(JSON.stringify(d.error)+`
30
+ `),1)}async function Cf(n,e,t,r,s,i){let o=U(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=U(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 ko(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=_o(),d=ir(n,"--attachment");for(let E of ir(n,"--attach-file")){let w=await Ss(E,a,e,t);if(!w.ok)return i.write(JSON.stringify(w.error)+`
35
- `),1;d.push(w.id)}let u={target:a,parent_message_id:o,content:c,clientIdempotencyKey:l};d.length>0&&(u.attachment_ids=d);let m=await de(e,t,"reply",u);if(!m.ok)return i.write(JSON.stringify(m.error)+`
33
+ `),1;let c=await So(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 d=wo(),l=or(n,"--attachment");for(let E of or(n,"--attach-file")){let w=await Es(E,a,e,t);if(!w.ok)return i.write(JSON.stringify(w.error)+`
35
+ `),1;l.push(w.id)}let u={target:a,parent_message_id:o,content:c,clientIdempotencyKey:d};l.length>0&&(u.attachment_ids=l);let m=await le(e,t,"reply",u);if(!m.ok)return i.write(JSON.stringify(m.error)+`
36
36
  `),1;let f=m.data,p=String(f.id??""),g=String(f.short_id??f.shortId??"").slice(0,8),y=f.seq!==void 0?`seq=${f.seq} `:"";return s.write(`replied: id=${p} ${g?`short=${g} `:""}${y}parent=${o} target=${a}
37
- `),0}async function Tf(n,e,t,r,s,i){switch(n){case"list":return Rf(e,t,r,s,i);case"create":return Af(e,t,r,s,i);case"claim":return go("claim",e,t,r,s,i);case"unclaim":return go("unclaim",e,t,r,s,i);case"update":return Of(e,t,r,s,i);case"review":return Cf(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 Cf(n,e,t,r,s){let i=bs(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"})+`
37
+ `),0}async function Rf(n,e,t,r,s,i){switch(n){case"list":return Of(e,t,r,s,i);case"create":return Pf(e,t,r,s,i);case"claim":return mo("claim",e,t,r,s,i);case"unclaim":return mo("unclaim",e,t,r,s,i);case"update":return If(e,t,r,s,i);case"review":return Af(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 Af(n,e,t,r,s){let i=ks(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=U(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
- `),1;let l=a?"pass":"bounce",d=U(n,"--feedback")??"",u=await de(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"}
41
+ `),1;let d=a?"pass":"bounce",l=U(n,"--feedback")??"",u=await le(e,t,"task",{op:"review",channel:o,number:i,verdict:d,feedback:l});return u.ok?(r.write(`Reviewed task #${i} \u2192 ${d==="pass"?"passed (done)":"bounced back for rework"}
42
42
  `),0):(s.write(JSON.stringify(u.error)+`
43
- `),1)}async function Rf(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task list"})+`
44
- `),1;let o=await de(e,t,"task",{op:"list",channel:i});return o.ok?(If(o.data,r),0):(s.write(JSON.stringify(o.error)+`
45
- `),1)}async function Af(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task create"})+`
43
+ `),1)}async function Of(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task list"})+`
44
+ `),1;let o=await le(e,t,"task",{op:"list",channel:i});return o.ok?(Mf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
45
+ `),1)}async function Pf(n,e,t,r,s){let i=U(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task create"})+`
46
46
  `),1;let o=U(n,"--title");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--title <text> is required for task create"})+`
47
- `),1;let a=U(n,"--attach"),c={op:"create",channel:i,title:o};a!==void 0&&a!==""&&(c.attach_to_message_id=a);let l=await de(e,t,"task",c);if(!l.ok)return s.write(JSON.stringify(l.error)+`
48
- `),1;let d=Pf(l.data),u=d?.number!==void 0?`#${d.number}`:"(new)";return r.write(`Created task ${u}: ${o}
49
- `),0}async function go(n,e,t,r,s,i){let o=bs(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}`})+`
47
+ `),1;let a=U(n,"--attach"),c={op:"create",channel:i,title:o};a!==void 0&&a!==""&&(c.attach_to_message_id=a);let d=await le(e,t,"task",c);if(!d.ok)return s.write(JSON.stringify(d.error)+`
48
+ `),1;let l=Nf(d.data),u=l?.number!==void 0?`#${l.number}`:"(new)";return r.write(`Created task ${u}: ${o}
49
+ `),0}async function mo(n,e,t,r,s,i){let o=ks(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=U(e,"--channel");if(!a)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:`--channel <#name> is required for task ${n}`})+`
51
- `),1;let c=await de(t,r,"task",{op:n,channel:a,number:o});return c.ok?(s.write(`${n==="claim"?"Claimed":"Unclaimed"} task #${o}
51
+ `),1;let c=await le(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 Of(n,e,t,r,s){let i=bs(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 If(n,e,t,r,s){let i=ks(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=U(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=U(n,"--status");if(!a)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--status <state> is required for task update"})+`
56
- `),1;let c=await de(e,t,"task",{op:"update",channel:o,number:i,status:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
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
- `);else{let d=typeof l.status=="string"?l.status:a;r.write(`Updated task #${i} \u2192 ${d}
59
- `)}return 0}function bs(n){let e=at(n);if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;if(!(t===""||!/^\d+$/.test(t)))return Number(t)}function at(n){for(let e=0;e<n.length;e++){let t=n[e];if(t.startsWith("--")){e++;continue}return t}}function Pf(n){let e=n;return(Array.isArray(e?.tasks)?e.tasks:[])[0]}function If(n,e){let t=n,r=Array.isArray(t?.tasks)?t.tasks:[];if(r.length===0){e.write(`(no tasks)
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 Nf(n,e,t,r,s,i){switch(n){case"schedule":return Mf(e,t,r,s,i);case"list":return Lf(e,t,r,s,i);case"snooze":return $f(e,t,r,s,i);case"update":return Df(e,t,r,s,i);case"cancel":return Bf(e,t,r,s,i);case"log":return Uf(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 Mf(n,e,t,r,s){let i=U(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=U(n,"--in"),a=U(n,"--at"),c=U(n,"--cadence"),l=[o,a,c].filter(E=>E!==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
- `),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=U(n,"--channel"),u=U(n,"--message-id"),m={op:"schedule",title:i};o!==void 0&&(m.in=o),a!==void 0&&(m.at=a),c!==void 0&&(m.cadence=c),d!==void 0&&(m.channel=d),u!==void 0&&(m.message_id=u);let f=await de(e,t,"reminder",m);if(!f.ok)return s.write(JSON.stringify(f.error)+`
66
- `),1;let p=Ff(f.data),g=p?.id??"(new)",y=p?.fireAt?` fireAt=${p.fireAt}`:"";return r.write(`Scheduled reminder ${g}: ${i}${y}
67
- `),0}async function Lf(n,e,t,r,s){let i=U(n,"--channel"),o=U(n,"--status"),a={op:"list"};i!==void 0&&(a.channel=i),o!==void 0&&(a.status=o);let c=await de(e,t,"reminder",a);return c.ok?(qf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
68
- `),1)}async function $f(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder snooze"})+`
56
+ `),1;let c=await le(e,t,"task",{op:"update",channel:o,number:i,status:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
57
+ `),1;let d=c.data??{};if(a==="done"&&d.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
+ `);else{let l=typeof d.status=="string"?d.status:a;r.write(`Updated task #${i} \u2192 ${l}
59
+ `)}return 0}function ks(n){let e=at(n);if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;if(!(t===""||!/^\d+$/.test(t)))return Number(t)}function at(n){for(let e=0;e<n.length;e++){let t=n[e];if(t.startsWith("--")){e++;continue}return t}}function Nf(n){let e=n;return(Array.isArray(e?.tasks)?e.tasks:[])[0]}function Mf(n,e){let t=n,r=Array.isArray(t?.tasks)?t.tasks:[];if(r.length===0){e.write(`(no tasks)
60
+ `);return}for(let s of r){let i=`#${s.number??"?"}`,o=s.status??"unknown",a=s.title??"",c=s.assignee??s.assignee_id,d=c?`@${c}`:"unassigned";e.write(`${i} ${o} ${a} ${d}
61
+ `)}}async function Lf(n,e,t,r,s,i){switch(n){case"schedule":return $f(e,t,r,s,i);case"list":return Df(e,t,r,s,i);case"snooze":return Bf(e,t,r,s,i);case"update":return Uf(e,t,r,s,i);case"cancel":return Ff(e,t,r,s,i);case"log":return Hf(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 $f(n,e,t,r,s){let i=U(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=U(n,"--in"),a=U(n,"--at"),c=U(n,"--cadence"),d=[o,a,c].filter(E=>E!==void 0).length;if(d===0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"one of --in <dur>, --at <ISO>, or --cadence <rule> is required for reminder schedule"})+`
64
+ `),1;if(d>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --at, --cadence may be provided"})+`
65
+ `),1;let l=U(n,"--channel"),u=U(n,"--message-id"),m={op:"schedule",title:i};o!==void 0&&(m.in=o),a!==void 0&&(m.at=a),c!==void 0&&(m.cadence=c),l!==void 0&&(m.channel=l),u!==void 0&&(m.message_id=u);let f=await le(e,t,"reminder",m);if(!f.ok)return s.write(JSON.stringify(f.error)+`
66
+ `),1;let p=qf(f.data),g=p?.id??"(new)",y=p?.fireAt?` fireAt=${p.fireAt}`:"";return r.write(`Scheduled reminder ${g}: ${i}${y}
67
+ `),0}async function Df(n,e,t,r,s){let i=U(n,"--channel"),o=U(n,"--status"),a={op:"list"};i!==void 0&&(a.channel=i),o!==void 0&&(a.status=o);let c=await le(e,t,"reminder",a);return c.ok?(Wf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
68
+ `),1)}async function Bf(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder snooze"})+`
69
69
  `),1;let o=U(n,"--in"),a=U(n,"--until"),c=[o,a].filter(p=>p!==void 0).length;if(c===0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"one of --in <dur> or --until <ISO> is required for reminder snooze"})+`
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 ks(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 de(e,t,"reminder",d);if(!u.ok)return s.write(JSON.stringify(u.error)+`
72
- `),1;let m=Hf(u.data),f=m?.fireAt?` \u2192 ${m.fireAt}`:"";return r.write(`Snoozed reminder ${i}${f}
73
- `),0}async function Df(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder update"})+`
74
- `),1;let o=U(n,"--title"),a=U(n,"--cadence"),c=U(n,"--in"),l=U(n,"--at");if([o,a,c,l].every(f=>f===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
- `),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 ks(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 de(e,t,"reminder",u);return m.ok?(r.write(`Updated reminder ${i}
71
+ `),1;let d=await Ss(i,e,t,s);if(d===void 0)return 1;let l={op:"snooze",id:i,version:d};o!==void 0&&(l.in=o),a!==void 0&&(l.until=a);let u=await le(e,t,"reminder",l);if(!u.ok)return s.write(JSON.stringify(u.error)+`
72
+ `),1;let m=Gf(u.data),f=m?.fireAt?` \u2192 ${m.fireAt}`:"";return r.write(`Snoozed reminder ${i}${f}
73
+ `),0}async function Uf(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder update"})+`
74
+ `),1;let o=U(n,"--title"),a=U(n,"--cadence"),c=U(n,"--in"),d=U(n,"--at");if([o,a,c,d].every(f=>f===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
+ `),1;if(c!==void 0&&d!==void 0)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --at may be provided"})+`
76
+ `),1;let l=await Ss(i,e,t,s);if(l===void 0)return 1;let u={op:"update",id:i,version:l};o!==void 0&&(u.title=o),a!==void 0&&(u.cadence=a),c!==void 0&&(u.in=c),d!==void 0&&(u.at=d);let m=await le(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 Bf(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder cancel"})+`
79
- `),1;let o=await ks(i,e,t,s);if(o===void 0)return 1;let a=await de(e,t,"reminder",{op:"cancel",id:i,version:o});return a.ok?(r.write(`Canceled reminder ${i}
78
+ `),1)}async function Ff(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder cancel"})+`
79
+ `),1;let o=await Ss(i,e,t,s);if(o===void 0)return 1;let a=await le(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 Uf(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder log"})+`
82
- `),1;let o=await de(e,t,"reminder",{op:"log",id:i});return o.ok?(Gf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
83
- `),1)}function Ff(n){let e=n;return e?.reminder?e.reminder:(Array.isArray(e?.reminders)?e.reminders:[])[0]}function Hf(n){return n?.reminder}async function ks(n,e,t,r){let s=await de(e,t,"reminder",{op:"list"});if(!s.ok){r.write(JSON.stringify(s.error)+`
81
+ `),1)}async function Hf(n,e,t,r,s){let i=at(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder log"})+`
82
+ `),1;let o=await le(e,t,"reminder",{op:"log",id:i});return o.ok?(jf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
83
+ `),1)}function qf(n){let e=n;return e?.reminder?e.reminder:(Array.isArray(e?.reminders)?e.reminders:[])[0]}function Gf(n){return n?.reminder}async function Ss(n,e,t,r){let s=await le(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 qf(n,e){let t=n,r=Array.isArray(t?.reminders)?t.reminders:[];if(r.length===0){e.write(`(no reminders)
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 Gf(n,e){let t=n,r=Array.isArray(t?.events)?t.events:[];if(r.length===0){e.write(`(no events)
86
+ `);return}return a.version}function Wf(n,e){let t=n,r=Array.isArray(t?.reminders)?t.reminders:[];if(r.length===0){e.write(`(no reminders)
87
+ `);return}for(let s of r){let i=s.id??"?",o=s.fireAt??"?",a=s.status??"unknown",c=s.title??"",d=s.cadence?` cadence=${s.cadence}`:"";e.write(`${i} ${o} ${a} ${c}${d}
88
+ `)}}function jf(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 Wf(n,e,t,r,s,i){switch(n){case"prepare":return jf(e,t,r,s,i);case"list":return Jf(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 jf(n,e,t,r,s){let i=U(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 Jf(n,e,t,r,s,i){switch(n){case"prepare":return Yf(e,t,r,s,i);case"list":return Vf(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 Yf(n,e,t,r,s){let i=U(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=U(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=U(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=U(n,"--visibility");m!==void 0&&(a.visibility=m)}else if(o==="channel:add_member"){let u=U(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
95
  `),1;let m=U(n,"--member"),f=U(n,"--member-id");if(m===void 0&&f===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
96
  `),1;a={channel:u},m!==void 0&&(a.member_handle=m),f!==void 0&&(a.member_id=f)}else return s.write(JSON.stringify({ok:!1,code:"INVALID_TYPE",message:`Unknown action type: ${o}. Supported: channel:create, channel:add_member`})+`
97
- `),1;let c=await de(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=Yf(c.data)?.id??"(new)";return r.write(`Proposed action ${d}: ${o} (target=${i}) \u2014 awaiting human approval
99
- `),0}async function Jf(n,e,t,r,s){let i=U(n,"--status"),o=U(n,"--channel"),a={op:"list"};i!==void 0&&(a.status=i),o!==void 0&&(a.channel=o);let c=await de(e,t,"action",a);return c.ok?(Vf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
100
- `),1)}function Yf(n){let e=n;return e?.action?e.action:(Array.isArray(e?.actions)?e.actions:[])[0]}function Vf(n,e){let t=n,r=Array.isArray(t?.actions)?t.actions:[];if(r.length===0){e.write(`(no actions)
97
+ `),1;let c=await le(e,t,"action",{op:"prepare",target:i,type:o,params:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
98
+ `),1;let l=zf(c.data)?.id??"(new)";return r.write(`Proposed action ${l}: ${o} (target=${i}) \u2014 awaiting human approval
99
+ `),0}async function Vf(n,e,t,r,s){let i=U(n,"--status"),o=U(n,"--channel"),a={op:"list"};i!==void 0&&(a.status=i),o!==void 0&&(a.channel=o);let c=await le(e,t,"action",a);return c.ok?(Kf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
100
+ `),1)}function zf(n){let e=n;return e?.action?e.action:(Array.isArray(e?.actions)?e.actions:[])[0]}function Kf(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 zf(n,e,t,r,s,i){switch(n){case"upload":return Kf(e,t,r,s,i);case"view":return Xf(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 Ss(n,e,t,r){let s=wf(n).toLowerCase(),i=mo[s];if(!i){let u=Object.keys(mo).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=yo(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=_f(n),c=await de(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 Kf(n,e,t,r,s){let i=at(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 Xf(n,e,t,r,s,i){switch(n){case"upload":return Qf(e,t,r,s,i);case"view":return Zf(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 Es(n,e,t,r){let s=bf(n).toLowerCase(),i=yo[s];if(!i){let u=Object.keys(yo).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=_o(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=vf(n),c=await le(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 d=c.data;return{ok:!0,id:String(d.attachment_id??d.id??""),filename:a,mimeType:i}}async function Qf(n,e,t,r,s){let i=at(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a local file path is required for attachment upload"})+`
104
104
  `),1;let o=U(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 Ss(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 Es(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 Xf(n,e,t,r,s){let i=at(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"an attachment id is required for attachment view"})+`
108
- `),1;let o=U(n,"--out"),a=await de(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 f=c.data_base64;if(typeof f!="string")return s.write(JSON.stringify({ok:!1,code:"NO_ATTACHMENT_DATA",message:`attachment ${i} response did not include data_base64 bytes to save`})+`
107
+ `),1)}async function Zf(n,e,t,r,s){let i=at(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"an attachment id is required for attachment view"})+`
108
+ `),1;let o=U(n,"--out"),a=await le(e,t,"attachment",{op:"view",attachment_id:i});if(!a.ok)return s.write(JSON.stringify(a.error)+`
109
+ `),1;let c=a.data,d=String(c.filename??""),l=String(c.mime_type??""),u=c.size_bytes;if(o!==void 0){let f=c.data_base64;if(typeof f!="string")return s.write(JSON.stringify({ok:!1,code:"NO_ATTACHMENT_DATA",message:`attachment ${i} response did not include data_base64 bytes to save`})+`
110
110
  `),1;let p=Buffer.from(f,"base64");if(u!==void 0){let g=Number(u);if(!Number.isNaN(g)&&p.length!==g)return s.write(JSON.stringify({ok:!1,code:"SIZE_MISMATCH",message:`attachment ${i} byte length mismatch: server reported size_bytes=${g} but decoded ${p.length} bytes \u2014 not writing ${o}`})+`
111
- `),1}try{yf(o,p)}catch(g){let y=g instanceof Error?g.message:String(g);return s.write(JSON.stringify({ok:!1,code:"FILE_WRITE_ERROR",message:`Cannot write to ${o}: ${y}`})+`
111
+ `),1}try{wf(o,p)}catch(g){let y=g instanceof Error?g.message:String(g);return s.write(JSON.stringify({ok:!1,code:"FILE_WRITE_ERROR",message:`Cannot write to ${o}: ${y}`})+`
112
112
  `),1}return r.write(`saved: ${o} (${p.length} bytes)
113
- `),0}let m=u!==void 0?String(u):"?";return r.write(`attachment ${i}: filename=${l} mime_type=${d} size_bytes=${m}
113
+ `),0}let m=u!==void 0?String(u):"?";return r.write(`attachment ${i}: filename=${d} mime_type=${l} size_bytes=${m}
114
114
  `),r.write(`(pass --out <path> to save the decoded bytes to a file)
115
- `),0}async function Qf(n,e,t,r,s,i){switch(n){case"show":return Zf(e,t,r,s,i);case"update":return eh(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 Zf(n,e,t,r,s){let i=at(n),o={op:"show"};i!==void 0&&(o.handle=i);let a=await de(e,t,"profile",o);return a.ok?(vo(a.data,r),0):(s.write(JSON.stringify(a.error)+`
117
- `),1)}async function eh(n,e,t,r,s){let i=U(n,"--display-name"),o=U(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 de(e,t,"profile",a);return c.ok?(vo(c.data,r),0):(s.write(JSON.stringify(c.error)+`
119
- `),1)}function vo(n,e){let t=n;if(!t){e.write(`(no profile data)
115
+ `),0}async function eh(n,e,t,r,s,i){switch(n){case"show":return th(e,t,r,s,i);case"update":return nh(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 th(n,e,t,r,s){let i=at(n),o={op:"show"};i!==void 0&&(o.handle=i);let a=await le(e,t,"profile",o);return a.ok?(bo(a.data,r),0):(s.write(JSON.stringify(a.error)+`
117
+ `),1)}async function nh(n,e,t,r,s){let i=U(n,"--display-name"),o=U(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 le(e,t,"profile",a);return c.ok?(bo(c.data,r),0):(s.write(JSON.stringify(c.error)+`
119
+ `),1)}function bo(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 de(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 th(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 bo(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(th(s)+`
127
- `)}function U(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 ir(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 ko(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 mo,nh,So=O(()=>{"use strict";mo={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".heic":"image/heic",".webp":"image/webp",".gif":"image/gif"};nh=`mio-agent agentcli \u2014 agent-facing message CLI (Slice 1)
125
+ `)}}async function le(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 rh(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 ko(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(rh(s)+`
127
+ `)}function U(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 or(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 So(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 yo,sh,Eo=O(()=>{"use strict";yo={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".heic":"image/heic",".webp":"image/webp",".gif":"image/gif"};sh=`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,38 @@ 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 Eo={};$e(Eo,{runAgentcliCommand:()=>rh});async function rh(){return wo(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var xo=O(()=>{"use strict";So()});import{execFileSync as Es}from"child_process";function cr(n){return Es("security",["add-generic-password","-U","-s",or,"-a",ar,"-w",n]),`${or}:${ar}`}function kt(){return Es("security",["find-generic-password","-s",or,"-a",ar,"-w"]).toString().trim()}function To(){Es("security",["delete-generic-password","-s",or,"-a",ar])}var or,ar,Yt=O(()=>{"use strict";or="io.miomioos.mio-agent",ar="machine_token"});var xs=K((Iw,Co)=>{Co.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var Oo=K((Nw,Ao)=>{var sh=xs();function Ro(n){this.mode=sh.MODE_8BIT_BYTE,this.data=n}Ro.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)}};Ao.exports=Ro});var Ts=K((Mw,Po)=>{var je={glog:function(n){if(n<1)throw new Error("glog("+n+")");return je.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return je.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(ue=0;ue<8;ue++)je.EXP_TABLE[ue]=1<<ue;var ue;for(ue=8;ue<256;ue++)je.EXP_TABLE[ue]=je.EXP_TABLE[ue-4]^je.EXP_TABLE[ue-5]^je.EXP_TABLE[ue-6]^je.EXP_TABLE[ue-8];var ue;for(ue=0;ue<255;ue++)je.LOG_TABLE[je.EXP_TABLE[ue]]=ue;var ue;Po.exports=je});var Cs=K((Lw,Io)=>{var It=Ts();function dr(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]}dr.prototype={get:function(n){return this.num[n]},getLength:function(){return this.num.length},multiply:function(n){for(var e=new Array(this.getLength()+n.getLength()-1),t=0;t<this.getLength();t++)for(var r=0;r<n.getLength();r++)e[t+r]^=It.gexp(It.glog(this.get(t))+It.glog(n.get(r)));return new dr(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=It.glog(this.get(0))-It.glog(n.get(0)),t=new Array(this.getLength()),r=0;r<this.getLength();r++)t[r]=this.get(r);for(var s=0;s<n.getLength();s++)t[s]^=It.gexp(It.glog(n.get(s))+e);return new dr(t,0).mod(n)}};Io.exports=dr});var Mo=K(($w,No)=>{No.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Do=K((Dw,$o)=>{var Ue=xs(),Lo=Cs(),ih=Ts(),St=Mo(),_e={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(n){for(var e=n<<10;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15)>=0;)e^=_e.G15<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15);return(n<<10|e)^_e.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18)>=0;)e^=_e.G18<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return _e.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case St.PATTERN000:return(e+t)%2===0;case St.PATTERN001:return e%2===0;case St.PATTERN010:return t%3===0;case St.PATTERN011:return(e+t)%3===0;case St.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case St.PATTERN101:return e*t%2+e*t%3===0;case St.PATTERN110:return(e*t%2+e*t%3)%2===0;case St.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new Lo([1],0),t=0;t<n;t++)e=e.multiply(new Lo([1,ih.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case Ue.MODE_NUMBER:return 10;case Ue.MODE_ALPHA_NUM:return 9;case Ue.MODE_8BIT_BYTE:return 8;case Ue.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case Ue.MODE_NUMBER:return 12;case Ue.MODE_ALPHA_NUM:return 11;case Ue.MODE_8BIT_BYTE:return 16;case Ue.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case Ue.MODE_NUMBER:return 14;case Ue.MODE_ALPHA_NUM:return 13;case Ue.MODE_8BIT_BYTE:return 16;case Ue.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}};$o.exports=_e});var Rs=K((Bw,Bo)=>{Bo.exports={L:1,M:0,Q:3,H:2}});var Fo=K((Uw,Uo)=>{var lr=Rs();function et(n,e){this.totalCount=n,this.dataCount=e}et.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]];et.getRSBlocks=function(n,e){var t=et.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 et(a,c));return s};et.getRsBlockTable=function(n,e){switch(e){case lr.L:return et.RS_BLOCK_TABLE[(n-1)*4+0];case lr.M:return et.RS_BLOCK_TABLE[(n-1)*4+1];case lr.Q:return et.RS_BLOCK_TABLE[(n-1)*4+2];case lr.H:return et.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};Uo.exports=et});var Go=K((Fw,qo)=>{function Ho(){this.buffer=[],this.length=0}Ho.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++}};qo.exports=Ho});var Yo=K((Hw,Jo)=>{var oh=Oo(),Et=Do(),ah=Cs(),Wo=Fo(),jo=Go();function tt(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}tt.prototype={addData:function(n){var e=new oh(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=Wo.getRSBlocks(n,this.errorCorrectLevel),t=new jo,r=0,s=0;s<e.length;s++)r+=e[s].dataCount;for(var i=0;i<this.dataList.length;i++){var o=this.dataList[i];t.put(o.mode,4),t.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(t)}if(t.getLengthInBits()<=r*8)break}this.typeNumber=n}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(n,e){this.moduleCount=this.typeNumber*4+17,this.modules=new Array(this.moduleCount);for(var t=0;t<this.moduleCount;t++){this.modules[t]=new Array(this.moduleCount);for(var r=0;r<this.moduleCount;r++)this.modules[t][r]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(n,e),this.typeNumber>=7&&this.setupTypeNumber(n),this.dataCache===null&&(this.dataCache=tt.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,e)},setupPositionProbePattern:function(n,e){for(var t=-1;t<=7;t++)if(!(n+t<=-1||this.moduleCount<=n+t))for(var r=-1;r<=7;r++)e+r<=-1||this.moduleCount<=e+r||(0<=t&&t<=6&&(r===0||r===6)||0<=r&&r<=6&&(t===0||t===6)||2<=t&&t<=4&&2<=r&&r<=4?this.modules[n+t][e+r]=!0:this.modules[n+t][e+r]=!1)},getBestMaskPattern:function(){for(var n=0,e=0,t=0;t<8;t++){this.makeImpl(!0,t);var r=Et.getLostPoint(this);(t===0||n>r)&&(n=r,e=t)}return e},createMovieClip:function(n,e,t){var r=n.createEmptyMovieClip(e,t),s=1;this.make();for(var i=0;i<this.modules.length;i++)for(var o=i*s,a=0;a<this.modules[i].length;a++){var c=a*s,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=Et.getPatternPosition(this.typeNumber),e=0;e<n.length;e++)for(var t=0;t<n.length;t++){var r=n[e],s=n[t];if(this.modules[r][s]===null)for(var i=-2;i<=2;i++)for(var o=-2;o<=2;o++)Math.abs(i)===2||Math.abs(o)===2||i===0&&o===0?this.modules[r+i][s+o]=!0:this.modules[r+i][s+o]=!1}},setupTypeNumber:function(n){for(var e=Et.getBCHTypeNumber(this.typeNumber),t,r=0;r<18;r++)t=!n&&(e>>r&1)===1,this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=t;for(var s=0;s<18;s++)t=!n&&(e>>s&1)===1,this.modules[s%3+this.moduleCount-8-3][Math.floor(s/3)]=t},setupTypeInfo:function(n,e){for(var t=this.errorCorrectLevel<<3|e,r=Et.getBCHTypeInfo(t),s,i=0;i<15;i++)s=!n&&(r>>i&1)===1,i<6?this.modules[i][8]=s:i<8?this.modules[i+1][8]=s:this.modules[this.moduleCount-15+i][8]=s;for(var o=0;o<15;o++)s=!n&&(r>>o&1)===1,o<8?this.modules[8][this.moduleCount-o-1]=s:o<9?this.modules[8][15-o-1+1]=s:this.modules[8][15-o-1]=s;this.modules[this.moduleCount-8][8]=!n},mapData:function(n,e){for(var t=-1,r=this.moduleCount-1,s=7,i=0,o=this.moduleCount-1;o>0;o-=2)for(o===6&&o--;;){for(var a=0;a<2;a++)if(this.modules[r][o-a]===null){var c=!1;i<n.length&&(c=(n[i]>>>s&1)===1);var l=Et.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}}}};tt.PAD0=236;tt.PAD1=17;tt.createData=function(n,e,t){for(var r=Wo.getRSBlocks(n,e),s=new jo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(s)}for(var a=0,c=0;c<r.length;c++)a+=r[c].dataCount;if(s.getLengthInBits()>a*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+a*8+")");for(s.getLengthInBits()+4<=a*8&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(!1);for(;!(s.getLengthInBits()>=a*8||(s.put(tt.PAD0,8),s.getLengthInBits()>=a*8));)s.put(tt.PAD1,8);return tt.createBytes(s,r)};tt.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=Et.getErrorCorrectPolynomial(l),m=new ah(i[a],u.getLength()-1),f=m.mod(u);o[a]=new Array(u.getLength()-1);for(var p=0;p<o[a].length;p++){var g=p+f.getLength()-o[a].length;o[a][p]=g>=0?f.get(g):0}}for(var y=0,E=0;E<e.length;E++)y+=e[E].totalCount;for(var w=new Array(y),_=0,k=0;k<r;k++)for(var P=0;P<e.length;P++)k<i[P].length&&(w[_++]=i[P][k]);for(var T=0;T<s;T++)for(var L=0;L<e.length;L++)T<o[L].length&&(w[_++]=o[L][T]);return w};Jo.exports=tt});var Os=K((qw,zo)=>{var ch=Yo(),Vo=Rs(),dh="\x1B[40m \x1B[0m",ur="\x1B[47m \x1B[0m",lh=function(n){return n?dh:ur},As=function(n){return{times:function(e){return new Array(e).join(n)}}},uh=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};zo.exports={error:Vo.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new ch(-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(uh(a,o));var d={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=As(d.BLACK_WHITE).times(a+3),m=As(d.WHITE_BLACK).times(a+3);s+=u+`
191
- `;for(var f=0;f<a;f+=2){s+=d.WHITE_ALL;for(var p=0;p<a;p++)c[f][p]===o&&c[f+1][p]===o?s+=d.WHITE_ALL:c[f][p]===o&&c[f+1][p]===i?s+=d.WHITE_BLACK:c[f][p]===i&&c[f+1][p]===o?s+=d.BLACK_WHITE:s+=d.BLACK_ALL;s+=d.WHITE_ALL+`
192
- `}l||(s+=m)}else{var g=As(ur).times(r.getModuleCount()+3);s+=g+`
193
- `,r.modules.forEach(function(y){s+=ur,s+=y.map(lh).join(""),s+=ur+`
194
- `}),s+=g}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=Vo[n]||this.error}}});var ea={};$e(ea,{runLogin:()=>_h});import{parseArgs as fh}from"node:util";import kn from"node:os";import{mkdirSync as hh,writeFileSync as ph,existsSync as gh}from"node:fs";import{join as Ko}from"node:path";function yh(n){return new Promise(e=>setTimeout(e,n))}function Zo(){console.log(`Usage: mio-agent login [--server <url>] [--device-name <name>]
190
+ `});var xo={};$e(xo,{runAgentcliCommand:()=>ih});async function ih(){return vo(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var To=O(()=>{"use strict";Eo()});import{execFileSync as xs}from"child_process";function lr(n){return xs("security",["add-generic-password","-U","-s",ar,"-a",cr,"-w",n]),`${ar}:${cr}`}function kt(){return xs("security",["find-generic-password","-s",ar,"-a",cr,"-w"]).toString().trim()}function Co(){xs("security",["delete-generic-password","-s",ar,"-a",cr])}var ar,cr,Yt=O(()=>{"use strict";ar="io.miomioos.mio-agent",cr="machine_token"});var Ts=K((Lw,Ro)=>{Ro.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var Po=K(($w,Oo)=>{var oh=Ts();function Ao(n){this.mode=oh.MODE_8BIT_BYTE,this.data=n}Ao.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)}};Oo.exports=Ao});var Cs=K((Dw,Io)=>{var je={glog:function(n){if(n<1)throw new Error("glog("+n+")");return je.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return je.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(ue=0;ue<8;ue++)je.EXP_TABLE[ue]=1<<ue;var ue;for(ue=8;ue<256;ue++)je.EXP_TABLE[ue]=je.EXP_TABLE[ue-4]^je.EXP_TABLE[ue-5]^je.EXP_TABLE[ue-6]^je.EXP_TABLE[ue-8];var ue;for(ue=0;ue<255;ue++)je.LOG_TABLE[je.EXP_TABLE[ue]]=ue;var ue;Io.exports=je});var Rs=K((Bw,No)=>{var It=Cs();function dr(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]}dr.prototype={get:function(n){return this.num[n]},getLength:function(){return this.num.length},multiply:function(n){for(var e=new Array(this.getLength()+n.getLength()-1),t=0;t<this.getLength();t++)for(var r=0;r<n.getLength();r++)e[t+r]^=It.gexp(It.glog(this.get(t))+It.glog(n.get(r)));return new dr(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=It.glog(this.get(0))-It.glog(n.get(0)),t=new Array(this.getLength()),r=0;r<this.getLength();r++)t[r]=this.get(r);for(var s=0;s<n.getLength();s++)t[s]^=It.gexp(It.glog(n.get(s))+e);return new dr(t,0).mod(n)}};No.exports=dr});var Lo=K((Uw,Mo)=>{Mo.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Bo=K((Fw,Do)=>{var Ue=Ts(),$o=Rs(),ah=Cs(),St=Lo(),_e={PATTERN_POSITION_TABLE:[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],G15:1335,G18:7973,G15_MASK:21522,getBCHTypeInfo:function(n){for(var e=n<<10;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15)>=0;)e^=_e.G15<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G15);return(n<<10|e)^_e.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18)>=0;)e^=_e.G18<<_e.getBCHDigit(e)-_e.getBCHDigit(_e.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return _e.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case St.PATTERN000:return(e+t)%2===0;case St.PATTERN001:return e%2===0;case St.PATTERN010:return t%3===0;case St.PATTERN011:return(e+t)%3===0;case St.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case St.PATTERN101:return e*t%2+e*t%3===0;case St.PATTERN110:return(e*t%2+e*t%3)%2===0;case St.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new $o([1],0),t=0;t<n;t++)e=e.multiply(new $o([1,ah.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case Ue.MODE_NUMBER:return 10;case Ue.MODE_ALPHA_NUM:return 9;case Ue.MODE_8BIT_BYTE:return 8;case Ue.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case Ue.MODE_NUMBER:return 12;case Ue.MODE_ALPHA_NUM:return 11;case Ue.MODE_8BIT_BYTE:return 16;case Ue.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case Ue.MODE_NUMBER:return 14;case Ue.MODE_ALPHA_NUM:return 13;case Ue.MODE_8BIT_BYTE:return 16;case Ue.MODE_KANJI:return 12;default:throw new Error("mode:"+n)}else throw new Error("type:"+e)},getLostPoint:function(n){var e=n.getModuleCount(),t=0,r=0,s=0;for(r=0;r<e;r++)for(s=0;s<e;s++){for(var i=0,o=n.isDark(r,s),a=-1;a<=1;a++)if(!(r+a<0||e<=r+a))for(var c=-1;c<=1;c++)s+c<0||e<=s+c||a===0&&c===0||o===n.isDark(r+a,s+c)&&i++;i>5&&(t+=3+i-5)}for(r=0;r<e-1;r++)for(s=0;s<e-1;s++){var d=0;n.isDark(r,s)&&d++,n.isDark(r+1,s)&&d++,n.isDark(r,s+1)&&d++,n.isDark(r+1,s+1)&&d++,(d===0||d===4)&&(t+=3)}for(r=0;r<e;r++)for(s=0;s<e-6;s++)n.isDark(r,s)&&!n.isDark(r,s+1)&&n.isDark(r,s+2)&&n.isDark(r,s+3)&&n.isDark(r,s+4)&&!n.isDark(r,s+5)&&n.isDark(r,s+6)&&(t+=40);for(s=0;s<e;s++)for(r=0;r<e-6;r++)n.isDark(r,s)&&!n.isDark(r+1,s)&&n.isDark(r+2,s)&&n.isDark(r+3,s)&&n.isDark(r+4,s)&&!n.isDark(r+5,s)&&n.isDark(r+6,s)&&(t+=40);var l=0;for(s=0;s<e;s++)for(r=0;r<e;r++)n.isDark(r,s)&&l++;var u=Math.abs(100*l/e/e-50)/5;return t+=u*10,t}};Do.exports=_e});var As=K((Hw,Uo)=>{Uo.exports={L:1,M:0,Q:3,H:2}});var Ho=K((qw,Fo)=>{var ur=As();function et(n,e){this.totalCount=n,this.dataCount=e}et.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]];et.getRSBlocks=function(n,e){var t=et.getRsBlockTable(n,e);if(t===void 0)throw new Error("bad rs block @ typeNumber:"+n+"/errorCorrectLevel:"+e);for(var r=t.length/3,s=[],i=0;i<r;i++)for(var o=t[i*3+0],a=t[i*3+1],c=t[i*3+2],d=0;d<o;d++)s.push(new et(a,c));return s};et.getRsBlockTable=function(n,e){switch(e){case ur.L:return et.RS_BLOCK_TABLE[(n-1)*4+0];case ur.M:return et.RS_BLOCK_TABLE[(n-1)*4+1];case ur.Q:return et.RS_BLOCK_TABLE[(n-1)*4+2];case ur.H:return et.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};Fo.exports=et});var Wo=K((Gw,Go)=>{function qo(){this.buffer=[],this.length=0}qo.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++}};Go.exports=qo});var Vo=K((Ww,Yo)=>{var ch=Po(),Et=Bo(),lh=Rs(),jo=Ho(),Jo=Wo();function tt(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}tt.prototype={addData:function(n){var e=new ch(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=jo.getRSBlocks(n,this.errorCorrectLevel),t=new Jo,r=0,s=0;s<e.length;s++)r+=e[s].dataCount;for(var i=0;i<this.dataList.length;i++){var o=this.dataList[i];t.put(o.mode,4),t.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(t)}if(t.getLengthInBits()<=r*8)break}this.typeNumber=n}this.makeImpl(!1,this.getBestMaskPattern())},makeImpl:function(n,e){this.moduleCount=this.typeNumber*4+17,this.modules=new Array(this.moduleCount);for(var t=0;t<this.moduleCount;t++){this.modules[t]=new Array(this.moduleCount);for(var r=0;r<this.moduleCount;r++)this.modules[t][r]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(n,e),this.typeNumber>=7&&this.setupTypeNumber(n),this.dataCache===null&&(this.dataCache=tt.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,e)},setupPositionProbePattern:function(n,e){for(var t=-1;t<=7;t++)if(!(n+t<=-1||this.moduleCount<=n+t))for(var r=-1;r<=7;r++)e+r<=-1||this.moduleCount<=e+r||(0<=t&&t<=6&&(r===0||r===6)||0<=r&&r<=6&&(t===0||t===6)||2<=t&&t<=4&&2<=r&&r<=4?this.modules[n+t][e+r]=!0:this.modules[n+t][e+r]=!1)},getBestMaskPattern:function(){for(var n=0,e=0,t=0;t<8;t++){this.makeImpl(!0,t);var r=Et.getLostPoint(this);(t===0||n>r)&&(n=r,e=t)}return e},createMovieClip:function(n,e,t){var r=n.createEmptyMovieClip(e,t),s=1;this.make();for(var i=0;i<this.modules.length;i++)for(var o=i*s,a=0;a<this.modules[i].length;a++){var c=a*s,d=this.modules[i][a];d&&(r.beginFill(0,100),r.moveTo(c,o),r.lineTo(c+s,o),r.lineTo(c+s,o+s),r.lineTo(c,o+s),r.endFill())}return r},setupTimingPattern:function(){for(var n=8;n<this.moduleCount-8;n++)this.modules[n][6]===null&&(this.modules[n][6]=n%2===0);for(var e=8;e<this.moduleCount-8;e++)this.modules[6][e]===null&&(this.modules[6][e]=e%2===0)},setupPositionAdjustPattern:function(){for(var n=Et.getPatternPosition(this.typeNumber),e=0;e<n.length;e++)for(var t=0;t<n.length;t++){var r=n[e],s=n[t];if(this.modules[r][s]===null)for(var i=-2;i<=2;i++)for(var o=-2;o<=2;o++)Math.abs(i)===2||Math.abs(o)===2||i===0&&o===0?this.modules[r+i][s+o]=!0:this.modules[r+i][s+o]=!1}},setupTypeNumber:function(n){for(var e=Et.getBCHTypeNumber(this.typeNumber),t,r=0;r<18;r++)t=!n&&(e>>r&1)===1,this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=t;for(var s=0;s<18;s++)t=!n&&(e>>s&1)===1,this.modules[s%3+this.moduleCount-8-3][Math.floor(s/3)]=t},setupTypeInfo:function(n,e){for(var t=this.errorCorrectLevel<<3|e,r=Et.getBCHTypeInfo(t),s,i=0;i<15;i++)s=!n&&(r>>i&1)===1,i<6?this.modules[i][8]=s:i<8?this.modules[i+1][8]=s:this.modules[this.moduleCount-15+i][8]=s;for(var o=0;o<15;o++)s=!n&&(r>>o&1)===1,o<8?this.modules[8][this.moduleCount-o-1]=s:o<9?this.modules[8][15-o-1+1]=s:this.modules[8][15-o-1]=s;this.modules[this.moduleCount-8][8]=!n},mapData:function(n,e){for(var t=-1,r=this.moduleCount-1,s=7,i=0,o=this.moduleCount-1;o>0;o-=2)for(o===6&&o--;;){for(var a=0;a<2;a++)if(this.modules[r][o-a]===null){var c=!1;i<n.length&&(c=(n[i]>>>s&1)===1);var d=Et.getMask(e,r,o-a);d&&(c=!c),this.modules[r][o-a]=c,s--,s===-1&&(i++,s=7)}if(r+=t,r<0||this.moduleCount<=r){r-=t,t=-t;break}}}};tt.PAD0=236;tt.PAD1=17;tt.createData=function(n,e,t){for(var r=jo.getRSBlocks(n,e),s=new Jo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Et.getLengthInBits(o.mode,n)),o.write(s)}for(var a=0,c=0;c<r.length;c++)a+=r[c].dataCount;if(s.getLengthInBits()>a*8)throw new Error("code length overflow. ("+s.getLengthInBits()+">"+a*8+")");for(s.getLengthInBits()+4<=a*8&&s.put(0,4);s.getLengthInBits()%8!==0;)s.putBit(!1);for(;!(s.getLengthInBits()>=a*8||(s.put(tt.PAD0,8),s.getLengthInBits()>=a*8));)s.put(tt.PAD1,8);return tt.createBytes(s,r)};tt.createBytes=function(n,e){for(var t=0,r=0,s=0,i=new Array(e.length),o=new Array(e.length),a=0;a<e.length;a++){var c=e[a].dataCount,d=e[a].totalCount-c;r=Math.max(r,c),s=Math.max(s,d),i[a]=new Array(c);for(var l=0;l<i[a].length;l++)i[a][l]=255&n.buffer[l+t];t+=c;var u=Et.getErrorCorrectPolynomial(d),m=new lh(i[a],u.getLength()-1),f=m.mod(u);o[a]=new Array(u.getLength()-1);for(var p=0;p<o[a].length;p++){var g=p+f.getLength()-o[a].length;o[a][p]=g>=0?f.get(g):0}}for(var y=0,E=0;E<e.length;E++)y+=e[E].totalCount;for(var w=new Array(y),_=0,k=0;k<r;k++)for(var P=0;P<e.length;P++)k<i[P].length&&(w[_++]=i[P][k]);for(var T=0;T<s;T++)for(var L=0;L<e.length;L++)T<o[L].length&&(w[_++]=o[L][T]);return w};Yo.exports=tt});var Ps=K((jw,Ko)=>{var dh=Vo(),zo=As(),uh="\x1B[40m \x1B[0m",fr="\x1B[47m \x1B[0m",fh=function(n){return n?uh:fr},Os=function(n){return{times:function(e){return new Array(e).join(n)}}},hh=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};Ko.exports={error:zo.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new dh(-1,this.error);r.addData(n),r.make();var s="";if(e&&e.small){var i=!0,o=!1,a=r.getModuleCount(),c=r.modules.slice(),d=a%2===1;d&&c.push(hh(a,o));var l={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=Os(l.BLACK_WHITE).times(a+3),m=Os(l.WHITE_BLACK).times(a+3);s+=u+`
191
+ `;for(var f=0;f<a;f+=2){s+=l.WHITE_ALL;for(var p=0;p<a;p++)c[f][p]===o&&c[f+1][p]===o?s+=l.WHITE_ALL:c[f][p]===o&&c[f+1][p]===i?s+=l.WHITE_BLACK:c[f][p]===i&&c[f+1][p]===o?s+=l.BLACK_WHITE:s+=l.BLACK_ALL;s+=l.WHITE_ALL+`
192
+ `}d||(s+=m)}else{var g=Os(fr).times(r.getModuleCount()+3);s+=g+`
193
+ `,r.modules.forEach(function(y){s+=fr,s+=y.map(fh).join(""),s+=fr+`
194
+ `}),s+=g}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=zo[n]||this.error}}});var ta={};$e(ta,{runLogin:()=>vh});import{parseArgs as ph}from"node:util";import kn from"node:os";import{mkdirSync as gh,writeFileSync as mh,existsSync as yh}from"node:fs";import{join as Xo}from"node:path";function wh(n){return new Promise(e=>setTimeout(e,n))}function ea(){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: ${Ps})
199
+ --server <url> MioServer base URL (default: ${Is})
200
200
  --device-name <name> Friendly name for this machine (default: hostname)
201
201
  --help Show this message
202
- `)}async function _h(n){let e;try{({values:e}=fh({args:n,options:{server:{type:"string",default:Ps},"device-name":{type:"string",default:kn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(_){let k=_ instanceof Error?_.message:String(_);return console.error(`Error: ${k}`),Zo(),1}if(e.help)return Zo(),0;let t=(e.server??Ps).replace(/\/+$/,""),r=e["device-name"]??kn.hostname(),s=kn.platform(),i=kn.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 k=_ instanceof Error?_.message:String(_);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(()=>te(Os(),1)).catch(()=>null),d=l?.default??l,u=typeof d?.generate=="function"?(_,k,P)=>d.generate(_,k,P):null;u?await new Promise(_=>{u(c,{small:!0},k=>{console.log(k),_()})}):console.log("(qrcode-terminal unavailable \u2014 paste the URL below into iOS Safari instead.)"),console.log(`(or paste this URL into Safari on iPhone: ${c})`),console.log(""),console.log(`Intent expires at ${o.expires_at}.`),console.log("Waiting for phone approval (up to 5 minutes)...");let m=Date.now(),f=Xo,p=null;for(;Date.now()-m<mh;){await yh(f);try{let _=await fetch(`${t}/api/v1/enrollment-intents/${o.intent_id}?code=${encodeURIComponent(o.opaque_code)}`,{method:"GET"});if(_.status===200){p=await _.json();break}if(_.status===202){f=Xo;continue}if(_.status===403)return console.error("Enrollment code became invalid (expired, canceled, or already consumed). Re-run `mio-agent login`."),1;f=Math.min(f*2,Qo);continue}catch{f=Math.min(f*2,Qo);continue}}if(!p)return console.error("Enrollment timed out (5 min). Re-run `mio-agent login` to retry."),1;let g=cr(p.machine_token),y=Ko(kn.homedir(),".mio");gh(y)||hh(y,{recursive:!0,mode:448});let E=Ko(y,"agent.json"),w={machine_id:p.machine_id,org_id:p.org_id,workroom_id:p.workroom_id,server_url:t,keychain_item_ref:g,runtimes:[],token_buffer:!1};return ph(E,JSON.stringify(w,null,2),{mode:384}),console.log(""),console.log(`Successfully enrolled as "${r}" in workroom ${p.workroom_id.slice(0,8)}.`),console.log("Config: ~/.mio/agent.json (0600)"),console.log(`Token: macOS Keychain (${g})`),console.log(""),console.log("Run `mio-agent doctor` to verify."),0}var Ps,Xo,Qo,mh,ta=O(()=>{"use strict";Yt();Ps="https://mio.wdao.chat",Xo=2e3,Qo=3e4,mh=300*1e3});var ra={};$e(ra,{runLogs:()=>kh});import{existsSync as Is}from"node:fs";import{homedir as wh}from"node:os";import{join as na}from"node:path";import{spawn as vh}from"node:child_process";function bh(){let n=wh(),e=na(n,".mio","logs","mio-agent.log"),t=na(n,".mio","logs","mio-agent-error.log"),r="/tmp/mio-agent.log",s=[];return Is(e)&&s.push(e),Is(t)&&s.push(t),s.length===0&&Is(r)&&s.push(r),s}async function kh(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=bh();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=vh("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 sa=O(()=>{"use strict"});function h(n,e,t,r){let s={time:new Date().toISOString(),level:n,component:e,message:t,...r};console.log(JSON.stringify(s))}function S(n,e,t){h("error",n,e,{error:t instanceof Error?t.message:String(t)})}var le=O(()=>{"use strict"});import{readFileSync as Sh,writeFileSync as Eh,mkdirSync as Ns,chmodSync as xh,existsSync as ia}from"fs";import{homedir as Th}from"os";import{join as Sn}from"path";function En(){Ns(pe,{recursive:!0,mode:448}),Ns(Ch,{recursive:!0,mode:448}),Ns(Nt,{recursive:!0,mode:448})}function aa(){return ia(Vt)}function Je(){if(!ia(Vt))throw new Error(`No config at ${Vt}. Run: mio-agent login`);return JSON.parse(Sh(Vt,"utf-8"))}function fr(n){En();let e=JSON.stringify(n,null,2);Eh(Vt,e,{encoding:"utf-8",mode:384}),xh(Vt,384)}var pe,Vt,Ch,Nt,nv,oa,Ye=O(()=>{"use strict";pe=Sn(Th(),".mio"),Vt=Sn(pe,"agent.json"),Ch=Sn(pe,"logs"),Nt=Sn(pe,"tmp"),nv=Sn(pe,"agent.sock"),oa=7878});import{readFileSync as Rh,writeFileSync as Ah,existsSync as Oh}from"fs";import{join as Ph}from"path";function ca(){if(!Oh(Ms))return{};try{return JSON.parse(Rh(Ms,"utf-8"))}catch{return{}}}function Ih(n){En(),Ah(Ms,JSON.stringify(n,null,2),{mode:384})}function da(){let n=ca();return new Map(Object.entries(n))}function la(n,e){let t=ca(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Ih(t))}var Ms,ua=O(()=>{"use strict";Ye();Ms=Ph(pe,"cursors.json")});async function ee(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 xn(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function ge(n){return{Authorization:`Bearer ${n}`}}async function fa(n,e){return ee(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:ge(e)})}async function ha(n,e,t){return ee(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function pa(n,e,t){await ee(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function ga(n,e,t=!1,r){await ee(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:ge(e),body:JSON.stringify(t?{going_offline:!0}:r?{usage:r}:{})})}async function ma(n,e,t,r){await ee(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:ge(r),body:JSON.stringify({status:t})})}async function ya(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return ee(s,{headers:ge(r)})}async function _a(n,e,t){return ee(`${n}/api/v1/actions/${e}`,{headers:ge(t)})}async function wa(n,e,t){return ee(`${n}/api/v1/approvals/${e}`,{headers:ge(t)})}async function va(n,e,t,r){let s=r?{approval_id:r}:{};return ee(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:ge(t),body:JSON.stringify(s)})}async function ba(n,e,t){await ee(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function ka(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 ee(c,{headers:ge(i)});return{messages:l.messages,hasMore:l.has_more}}async function zt(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),ee(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:ge(s),body:JSON.stringify(i)})}async function Sa(n,e,t){return(await ee(`${n}/api/v1/workrooms/${e}/members`,{headers:ge(t)})).members??[]}async function Ea(n,e,t){return ee(`${n}/api/v1/workrooms/${e}/roster`,{headers:ge(t)})}async function xa(n,e,t){return(await ee(`${n}/api/v1/workrooms/${e}/channels`,{headers:ge(t)})).channels??[]}async function Ta(n,e,t){return(await ee(`${n}/internal/agent-api/channels`,{headers:{...ge(e),"X-Mio-Agent-Id":t}})).channels??[]}async function Ca(n,e,t,r){return(await ee(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...ge(e),"X-Mio-Agent-Id":t}})).tasks??[]}function Fe(n,e){return{...ge(n),"X-Mio-Agent-Id":e}}async function Ra(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Aa(n,e,t){return(await ee(`${n}/internal/agent-api/reminders/list`,{headers:Fe(e,t)})).reminders??[]}async function Oa(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Pa(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Ia(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Na(n,e,t){return(await ee(`${n}/internal/agent-api/reminders/log`,{headers:Fe(e,t)})).events??[]}async function Ma(n,e,t,r){await ee(`${n}/internal/agent-api/typing`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function La(n,e,t,r){await ee(`${n}/internal/agent-api/status`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function $a(n,e,t,r){await ee(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})}async function Da(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 ee(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${a}`,{headers:Fe(e,t)})).messages??[]}async function Ba(n,e,t,r){return(await ee(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:Fe(e,t)})).message}async function Ua(n,e,t,r){return ee(`${n}/internal/agent-api/attachments/${r}`,{headers:Fe(e,t)})}var xn,hr=O(()=>{"use strict";xn=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 qa=K((dv,Ha)=>{var Kt=X("fs"),Fa=X("url"),Nh=X("child_process").spawn;Ha.exports=Ls;Ls.XMLHttpRequest=Ls;function Ls(n){"use strict";n=n||{};var e=this,t=X("http"),r=X("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,f=!1,p=!1,g={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var y=function(_){return a||_&&d.indexOf(_.toLowerCase())===-1},E=function(_){return _&&u.indexOf(_)===-1};this.open=function(_,k,P,T,L){if(this.abort(),f=!1,p=!1,!E(_))throw new Error("SecurityError: Request method not allowed");o={method:_,url:k.toString(),async:typeof P!="boolean"?!0:P,user:T||null,password:L||null},w(this.OPENED)},this.setDisableHeaderCheck=function(_){a=_},this.setRequestHeader=function(_,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 "'+_+'"'),!1;if(m)throw new Error("INVALID_STATE_ERR: send flag is true");return l[_]=k,!0},this.getResponseHeader=function(_){return typeof _=="string"&&this.readyState>this.OPENED&&i.headers[_.toLowerCase()]&&!f?i.headers[_.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||f)return"";var _="";for(var k in i.headers)k!=="set-cookie"&&k!=="set-cookie2"&&(_+=k+": "+i.headers[k]+`\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 k=!1,P=!1,T=Fa.parse(o.url),L;switch(T.protocol){case"https:":k=!0;case"http:":L=T.hostname;break;case"file:":P=!0;break;case void 0:case"":L="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)Kt.readFile(unescape(T.pathname),function(B,W){B?e.handleError(B,B.errno||-1):(e.status=200,e.responseText=W.toString("utf8"),e.response=W,w(e.DONE))});else try{this.response=Kt.readFileSync(unescape(T.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,w(e.DONE)}catch(B){this.handleError(B,B.errno||-1)}return}var F=T.port||(k?443:80),J=T.pathname+(T.search?T.search:"");if(l.Host=L,k&&F===443||F===80||(l.Host+=":"+T.port),o.user){typeof o.password>"u"&&(o.password="");var G=new Buffer(o.user+":"+o.password);l.Authorization="Basic "+G.toString("base64")}if(o.method==="GET"||o.method==="HEAD")_=null;else if(_){l["Content-Length"]=Buffer.isBuffer(_)?_.length:Buffer.byteLength(_);var Z=Object.keys(l);Z.some(function(B){return B.toLowerCase()==="content-type"})||(l["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(l["Content-Length"]=0);var ne=n.agent||!1,q={host:L,port:F,path:J,method:o.method,headers:l,agent:ne};if(k&&(q.pfx=n.pfx,q.key=n.key,q.passphrase=n.passphrase,q.cert=n.cert,q.ca=n.ca,q.ciphers=n.ciphers,q.rejectUnauthorized=n.rejectUnauthorized!==!1),f=!1,o.async){var se=k?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var ie=function(B){if(i=B,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var W=Fa.parse(o.url);L=W.hostname;var oe={hostname:W.hostname,port:W.port,path:W.path,method:i.statusCode===303?"GET":o.method,headers:l};k&&(oe.pfx=n.pfx,oe.key=n.key,oe.passphrase=n.passphrase,oe.cert=n.cert,oe.ca=n.ca,oe.ciphers=n.ciphers,oe.rejectUnauthorized=n.rejectUnauthorized!==!1),s=se(oe,ie).on("error",b),s.end();return}w(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(he){if(he){var $=Buffer.from(he);e.response=Buffer.concat([e.response,$])}m&&w(e.LOADING)}),i.on("end",function(){m&&(m=!1,w(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(he){e.handleError(he)})},b=function(B){if(s.reusedSocket&&B.code==="ECONNRESET")return se(q,ie).on("error",b);e.handleError(B)};s=se(q,ie).on("error",b),n.autoUnref&&s.on("socket",B=>{B.unref()}),_&&s.write(_),s.end(),e.dispatchEvent("loadstart")}else{var R=".node-xmlhttprequest-content-"+process.pid,x=".node-xmlhttprequest-sync-"+process.pid;Kt.writeFileSync(x,"","utf8");for(var A="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(k?"s":"")+".request;var options = "+JSON.stringify(q)+";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('"+R+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+x+"');});response.on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+x+"');});}).on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+x+"');});"+(_?"req.write('"+JSON.stringify(_).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",v=Nh(process.argv[0],["-e",A]),N;Kt.existsSync(x););if(e.responseText=Kt.readFileSync(R,"utf8"),v.stdin.end(),Kt.unlinkSync(R),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var I=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(I,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var C=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:C.data.headers},e.responseText=C.data.text,e.response=Buffer.from(C.data.data,"base64"),w(e.DONE,!0)}}},this.handleError=function(_,k){this.status=k||0,this.statusText=_,this.responseText=_.stack,f=!0,w(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),l=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),f=p=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||m)&&this.readyState!==this.DONE&&(m=!1,w(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(_,k){_ in g||(g[_]=[]),g[_].push(k)},this.removeEventListener=function(_,k){_ in g&&(g[_]=g[_].filter(function(P){return P!==k}))},this.dispatchEvent=function(_){if(typeof e["on"+_]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+_]()},0):e["on"+_]()),_ in g)for(let k=0,P=g[_].length;k<P;k++)this.readyState===this.DONE?setTimeout(function(){g[_][k].call(e)},0):g[_][k].call(e)};var w=function(_){if(!(e.readyState===_||e.readyState===e.UNSENT&&p)&&(e.readyState=_,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let k;p?k="abort":f?k="error":k="load",e.dispatchEvent(k),e.dispatchEvent("loadend")}}}});var Ve,Tn,Cn,pr=O(()=>{Ve=Object.create(null);Ve.open="0";Ve.close="1";Ve.ping="2";Ve.pong="3";Ve.message="4";Ve.upgrade="5";Ve.noop="6";Tn=Object.create(null);Object.keys(Ve).forEach(n=>{Tn[Ve[n]]=n});Cn={type:"error",data:"parser error"}});function Wa(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(Ga(n.data,!1));Rn(n,!0,t=>{$s||($s=new TextEncoder),e($s.encode(t))})}var Rn,Ga,$s,ja=O(()=>{pr();Rn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+Ga(e,!0).toString("base64")):r(Ve[n]+(e||"")),Ga=(n,e)=>Buffer.isBuffer(n)||n instanceof Uint8Array&&!e?n:n instanceof ArrayBuffer?Buffer.from(n):Buffer.from(n.buffer,n.byteOffset,n.byteLength)});var An,Ja,Ya=O(()=>{pr();An=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ja(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:Ja(r,e)}}return Tn[t]?n.length>1?{type:Tn[t],data:n.substring(1)}:{type:Tn[t]}:Cn},Ja=(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 Xa(){return new TransformStream({transform(n,e){Wa(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 gr(n){return n.reduce((e,t)=>e+t.length,0)}function mr(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 Qa(n,e){Ds||(Ds=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(gr(t)<1)break;let c=mr(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(gr(t)<2)break;let c=mr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(gr(t)<8)break;let c=mr(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),d=l.getUint32(0);if(d>Math.pow(2,21)-1){a.enqueue(Cn);break}s=d*Math.pow(2,32)+l.getUint32(4),r=3}else{if(gr(t)<s)break;let c=mr(t,s);a.enqueue(An(i?c:Ds.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(Cn);break}}}})}var Va,za,Ka,Ds,Bs,Xt=O(()=>{ja();Ya();pr();Va="",za=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Rn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(Va))})})},Ka=(n,e)=>{let t=n.split(Va),r=[];for(let s=0;s<t.length;s++){let i=An(t[s],e);if(r.push(i),i.type==="error")break}return r};Bs=4});var Mt=K(Za=>{Za.Emitter=Se;function Se(n){if(n)return Mh(n)}function Mh(n){for(var e in Se.prototype)n[e]=Se.prototype[e];return n}Se.prototype.on=Se.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Se.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Se.prototype.off=Se.prototype.removeListener=Se.prototype.removeAllListeners=Se.prototype.removeEventListener=function(n,e){if(this._callbacks=this._callbacks||{},arguments.length==0)return this._callbacks={},this;var t=this._callbacks["$"+n];if(!t)return this;if(arguments.length==1)return delete this._callbacks["$"+n],this;for(var r,s=0;s<t.length;s++)if(r=t[s],r===e||r.fn===e){t.splice(s,1);break}return t.length===0&&delete this._callbacks["$"+n],this};Se.prototype.emit=function(n){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),t=this._callbacks["$"+n],r=1;r<arguments.length;r++)e[r-1]=arguments[r];if(t){t=t.slice(0);for(var r=0,s=t.length;r<s;++r)t[r].apply(this,e)}return this};Se.prototype.emitReserved=Se.prototype.emit;Se.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Se.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function tc(){return new Us}function Lh(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 ct,Ee,ec,Us,Lt=O(()=>{ct=process.nextTick,Ee=global,ec="nodebuffer";Us=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=Lh(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 yr(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function dt(n,e){e.useNativeTimers?(n.setTimeoutFn=$h.bind(Ee),n.clearTimeoutFn=Dh.bind(Ee)):(n.setTimeoutFn=Ee.setTimeout.bind(Ee),n.clearTimeoutFn=Ee.clearTimeout.bind(Ee))}function nc(n){return typeof n=="string"?Uh(n):Math.ceil((n.byteLength||n.size)*Bh)}function Uh(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 _r(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var $h,Dh,Bh,$t=O(()=>{Lt();$h=Ee.setTimeout,Dh=Ee.clearTimeout;Bh=1.33});function rc(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function sc(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 Fs=O(()=>{});var oc=K((Ev,ic)=>{var Qt=1e3,Zt=Qt*60,en=Zt*60,Dt=en*24,Fh=Dt*7,Hh=Dt*365.25;ic.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return qh(n);if(t==="number"&&isFinite(n))return e.long?Wh(n):Gh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function qh(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*Hh;case"weeks":case"week":case"w":return t*Fh;case"days":case"day":case"d":return t*Dt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*en;case"minutes":case"minute":case"mins":case"min":case"m":return t*Zt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Qt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Gh(n){var e=Math.abs(n);return e>=Dt?Math.round(n/Dt)+"d":e>=en?Math.round(n/en)+"h":e>=Zt?Math.round(n/Zt)+"m":e>=Qt?Math.round(n/Qt)+"s":n+"ms"}function Wh(n){var e=Math.abs(n);return e>=Dt?wr(n,e,Dt,"day"):e>=en?wr(n,e,en,"hour"):e>=Zt?wr(n,e,Zt,"minute"):e>=Qt?wr(n,e,Qt,"second"):n+" ms"}function wr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Hs=K((xv,ac)=>{function jh(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=oc(),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,f,p;function g(...y){if(!g.enabled)return;let E=g,w=Number(new Date),_=w-(u||w);E.diff=_,E.prev=u,E.curr=w,u=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let k=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,L)=>{if(T==="%%")return"%";k++;let F=t.formatters[L];if(typeof F=="function"){let J=y[k];T=F.call(E,J),y.splice(k,1),k--}return T}),t.formatArgs.call(E,y),(E.log||t.log).apply(E,y)}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:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(d)),p),set:y=>{m=y}}),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,f=0,p=-1,g=0;for(;m<d.length;)if(f<u.length&&(u[f]===d[m]||u[f]==="*"))u[f]==="*"?(p=f,g=m,f++):(m++,f++);else if(p!==-1)f=p+1,g++,m=g;else return!1;for(;f<u.length&&u[f]==="*";)f++;return f===u.length}function o(){let 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}ac.exports=jh});var cc=K((Ae,vr)=>{Ae.formatArgs=Yh;Ae.save=Vh;Ae.load=zh;Ae.useColors=Jh;Ae.storage=Kh();Ae.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Ae.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Jh(){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 Yh(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+vr.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}Ae.log=console.debug||console.log||(()=>{});function Vh(n){try{n?Ae.storage.setItem("debug",n):Ae.storage.removeItem("debug")}catch{}}function zh(){let n;try{n=Ae.storage.getItem("debug")||Ae.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Kh(){try{return localStorage}catch{}}vr.exports=Hs()(Ae);var{formatters:Xh}=vr.exports;Xh.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var lc=K((me,kr)=>{var Qh=X("tty"),br=X("util");me.init=ip;me.log=np;me.formatArgs=ep;me.save=rp;me.load=sp;me.useColors=Zh;me.destroy=br.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");me.colors=[6,2,3,4,5,1];try{let n=X("supports-color");n&&(n.stderr||n).level>=2&&(me.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}me.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function Zh(){return"colors"in me.inspectOpts?!!me.inspectOpts.colors:Qh.isatty(process.stderr.fd)}function ep(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 vh(n){let e;try{({values:e}=ph({args:n,options:{server:{type:"string",default:Is},"device-name":{type:"string",default:kn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(_){let k=_ instanceof Error?_.message:String(_);return console.error(`Error: ${k}`),ea(),1}if(e.help)return ea(),0;let t=(e.server??Is).replace(/\/+$/,""),r=e["device-name"]??kn.hostname(),s=kn.platform(),i=kn.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 k=_ instanceof Error?_.message:String(_);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 d=await Promise.resolve().then(()=>te(Ps(),1)).catch(()=>null),l=d?.default??d,u=typeof l?.generate=="function"?(_,k,P)=>l.generate(_,k,P):null;u?await new Promise(_=>{u(c,{small:!0},k=>{console.log(k),_()})}):console.log("(qrcode-terminal unavailable \u2014 paste the URL below into iOS Safari instead.)"),console.log(`(or paste this URL into Safari on iPhone: ${c})`),console.log(""),console.log(`Intent expires at ${o.expires_at}.`),console.log("Waiting for phone approval (up to 5 minutes)...");let m=Date.now(),f=Qo,p=null;for(;Date.now()-m<_h;){await wh(f);try{let _=await fetch(`${t}/api/v1/enrollment-intents/${o.intent_id}?code=${encodeURIComponent(o.opaque_code)}`,{method:"GET"});if(_.status===200){p=await _.json();break}if(_.status===202){f=Qo;continue}if(_.status===403)return console.error("Enrollment code became invalid (expired, canceled, or already consumed). Re-run `mio-agent login`."),1;f=Math.min(f*2,Zo);continue}catch{f=Math.min(f*2,Zo);continue}}if(!p)return console.error("Enrollment timed out (5 min). Re-run `mio-agent login` to retry."),1;let g=lr(p.machine_token),y=Xo(kn.homedir(),".mio");yh(y)||gh(y,{recursive:!0,mode:448});let E=Xo(y,"agent.json"),w={machine_id:p.machine_id,org_id:p.org_id,workroom_id:p.workroom_id,server_url:t,keychain_item_ref:g,runtimes:[],token_buffer:!1};return mh(E,JSON.stringify(w,null,2),{mode:384}),console.log(""),console.log(`Successfully enrolled as "${r}" in workroom ${p.workroom_id.slice(0,8)}.`),console.log("Config: ~/.mio/agent.json (0600)"),console.log(`Token: macOS Keychain (${g})`),console.log(""),console.log("Run `mio-agent doctor` to verify."),0}var Is,Qo,Zo,_h,na=O(()=>{"use strict";Yt();Is="https://mio.wdao.chat",Qo=2e3,Zo=3e4,_h=300*1e3});var sa={};$e(sa,{runLogs:()=>Eh});import{existsSync as Ns}from"node:fs";import{homedir as bh}from"node:os";import{join as ra}from"node:path";import{spawn as kh}from"node:child_process";function Sh(){let n=bh(),e=ra(n,".mio","logs","mio-agent.log"),t=ra(n,".mio","logs","mio-agent-error.log"),r="/tmp/mio-agent.log",s=[];return Ns(e)&&s.push(e),Ns(t)&&s.push(t),s.length===0&&Ns(r)&&s.push(r),s}async function Eh(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=Sh();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=kh("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 ia=O(()=>{"use strict"});function h(n,e,t,r){let s={time:new Date().toISOString(),level:n,component:e,message:t,...r};console.log(JSON.stringify(s))}function S(n,e,t){h("error",n,e,{error:t instanceof Error?t.message:String(t)})}var de=O(()=>{"use strict"});import{readFileSync as xh,writeFileSync as Th,mkdirSync as Ms,chmodSync as Ch,existsSync as oa}from"fs";import{homedir as Rh}from"os";import{join as Sn}from"path";function En(){Ms(pe,{recursive:!0,mode:448}),Ms(Ah,{recursive:!0,mode:448}),Ms(Nt,{recursive:!0,mode:448})}function ca(){return oa(Vt)}function Je(){if(!oa(Vt))throw new Error(`No config at ${Vt}. Run: mio-agent login`);return JSON.parse(xh(Vt,"utf-8"))}function hr(n){En();let e=JSON.stringify(n,null,2);Th(Vt,e,{encoding:"utf-8",mode:384}),Ch(Vt,384)}var pe,Vt,Ah,Nt,iv,aa,Ye=O(()=>{"use strict";pe=Sn(Rh(),".mio"),Vt=Sn(pe,"agent.json"),Ah=Sn(pe,"logs"),Nt=Sn(pe,"tmp"),iv=Sn(pe,"agent.sock"),aa=7878});import{readFileSync as Oh,writeFileSync as Ph,existsSync as Ih}from"fs";import{join as Nh}from"path";function la(){if(!Ih(Ls))return{};try{return JSON.parse(Oh(Ls,"utf-8"))}catch{return{}}}function Mh(n){En(),Ph(Ls,JSON.stringify(n,null,2),{mode:384})}function da(){let n=la();return new Map(Object.entries(n))}function ua(n,e){let t=la(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Mh(t))}var Ls,fa=O(()=>{"use strict";Ye();Ls=Nh(pe,"cursors.json")});async function ee(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 xn(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function ge(n){return{Authorization:`Bearer ${n}`}}async function ha(n,e){return ee(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:ge(e)})}async function pa(n,e,t){return ee(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function ga(n,e,t){await ee(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function ma(n,e,t=!1,r){await ee(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:ge(e),body:JSON.stringify(t?{going_offline:!0}:r?{usage:r}:{})})}async function ya(n,e,t,r){await ee(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:ge(r),body:JSON.stringify({status:t})})}async function _a(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return ee(s,{headers:ge(r)})}async function wa(n,e,t){return ee(`${n}/api/v1/actions/${e}`,{headers:ge(t)})}async function va(n,e,t){return ee(`${n}/api/v1/approvals/${e}`,{headers:ge(t)})}async function ba(n,e,t,r){let s=r?{approval_id:r}:{};return ee(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:ge(t),body:JSON.stringify(s)})}async function ka(n,e,t){await ee(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function Sa(n,e,t,r,s,i){let o=new URLSearchParams;r!==void 0&&o.set("after_seq",r),s!==void 0&&o.set("limit",String(s));let a=o.toString()?`?${o.toString()}`:"",c=`${n}/api/v1/workrooms/${e}/channels/${t}/messages${a}`,d=await ee(c,{headers:ge(i)});return{messages:d.messages,hasMore:d.has_more}}async function zt(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),ee(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:ge(s),body:JSON.stringify(i)})}async function Ea(n,e,t){return(await ee(`${n}/api/v1/workrooms/${e}/members`,{headers:ge(t)})).members??[]}async function xa(n,e,t){return ee(`${n}/api/v1/workrooms/${e}/roster`,{headers:ge(t)})}async function Ta(n,e,t){return(await ee(`${n}/api/v1/workrooms/${e}/channels`,{headers:ge(t)})).channels??[]}async function Ca(n,e,t){return(await ee(`${n}/internal/agent-api/channels`,{headers:{...ge(e),"X-Mio-Agent-Id":t}})).channels??[]}async function Ra(n,e,t,r){return(await ee(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...ge(e),"X-Mio-Agent-Id":t}})).tasks??[]}function Fe(n,e){return{...ge(n),"X-Mio-Agent-Id":e}}async function Aa(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Oa(n,e,t){return(await ee(`${n}/internal/agent-api/reminders/list`,{headers:Fe(e,t)})).reminders??[]}async function Pa(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Ia(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Na(n,e,t,r){return(await ee(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})).reminder}async function Ma(n,e,t){return(await ee(`${n}/internal/agent-api/reminders/log`,{headers:Fe(e,t)})).events??[]}async function La(n,e,t,r){await ee(`${n}/internal/agent-api/typing`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function $a(n,e,t,r){await ee(`${n}/internal/agent-api/status`,{method:"POST",headers:Fe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Da(n,e,t,r){await ee(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:Fe(e,t),body:JSON.stringify(r)})}async function Ba(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 ee(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${a}`,{headers:Fe(e,t)})).messages??[]}async function Ua(n,e,t,r){return(await ee(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:Fe(e,t)})).message}async function Fa(n,e,t,r){return ee(`${n}/internal/agent-api/attachments/${r}`,{headers:Fe(e,t)})}var xn,pr=O(()=>{"use strict";xn=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 Ga=K((fv,qa)=>{var Kt=X("fs"),Ha=X("url"),Lh=X("child_process").spawn;qa.exports=$s;$s.XMLHttpRequest=$s;function $s(n){"use strict";n=n||{};var e=this,t=X("http"),r=X("https"),s,i,o={},a=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},c),l=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],u=["TRACE","TRACK","CONNECT"],m=!1,f=!1,p=!1,g={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var y=function(_){return a||_&&l.indexOf(_.toLowerCase())===-1},E=function(_){return _&&u.indexOf(_)===-1};this.open=function(_,k,P,T,L){if(this.abort(),f=!1,p=!1,!E(_))throw new Error("SecurityError: Request method not allowed");o={method:_,url:k.toString(),async:typeof P!="boolean"?!0:P,user:T||null,password:L||null},w(this.OPENED)},this.setDisableHeaderCheck=function(_){a=_},this.setRequestHeader=function(_,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 "'+_+'"'),!1;if(m)throw new Error("INVALID_STATE_ERR: send flag is true");return d[_]=k,!0},this.getResponseHeader=function(_){return typeof _=="string"&&this.readyState>this.OPENED&&i.headers[_.toLowerCase()]&&!f?i.headers[_.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||f)return"";var _="";for(var k in i.headers)k!=="set-cookie"&&k!=="set-cookie2"&&(_+=k+": "+i.headers[k]+`\r
204
+ `);return _.substr(0,_.length-2)},this.getRequestHeader=function(_){return typeof _=="string"&&d[_]?d[_]:""},this.send=function(_){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(m)throw new Error("INVALID_STATE_ERR: send has already been called");var k=!1,P=!1,T=Ha.parse(o.url),L;switch(T.protocol){case"https:":k=!0;case"http:":L=T.hostname;break;case"file:":P=!0;break;case void 0:case"":L="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)Kt.readFile(unescape(T.pathname),function(B,W){B?e.handleError(B,B.errno||-1):(e.status=200,e.responseText=W.toString("utf8"),e.response=W,w(e.DONE))});else try{this.response=Kt.readFileSync(unescape(T.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,w(e.DONE)}catch(B){this.handleError(B,B.errno||-1)}return}var F=T.port||(k?443:80),J=T.pathname+(T.search?T.search:"");if(d.Host=L,k&&F===443||F===80||(d.Host+=":"+T.port),o.user){typeof o.password>"u"&&(o.password="");var G=new Buffer(o.user+":"+o.password);d.Authorization="Basic "+G.toString("base64")}if(o.method==="GET"||o.method==="HEAD")_=null;else if(_){d["Content-Length"]=Buffer.isBuffer(_)?_.length:Buffer.byteLength(_);var Z=Object.keys(d);Z.some(function(B){return B.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(d["Content-Length"]=0);var ne=n.agent||!1,q={host:L,port:F,path:J,method:o.method,headers:d,agent:ne};if(k&&(q.pfx=n.pfx,q.key=n.key,q.passphrase=n.passphrase,q.cert=n.cert,q.ca=n.ca,q.ciphers=n.ciphers,q.rejectUnauthorized=n.rejectUnauthorized!==!1),f=!1,o.async){var ie=k?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var oe=function(B){if(i=B,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var W=Ha.parse(o.url);L=W.hostname;var ae={hostname:W.hostname,port:W.port,path:W.path,method:i.statusCode===303?"GET":o.method,headers:d};k&&(ae.pfx=n.pfx,ae.key=n.key,ae.passphrase=n.passphrase,ae.cert=n.cert,ae.ca=n.ca,ae.ciphers=n.ciphers,ae.rejectUnauthorized=n.rejectUnauthorized!==!1),s=ie(ae,oe).on("error",b),s.end();return}w(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(he){if(he){var $=Buffer.from(he);e.response=Buffer.concat([e.response,$])}m&&w(e.LOADING)}),i.on("end",function(){m&&(m=!1,w(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(he){e.handleError(he)})},b=function(B){if(s.reusedSocket&&B.code==="ECONNRESET")return ie(q,oe).on("error",b);e.handleError(B)};s=ie(q,oe).on("error",b),n.autoUnref&&s.on("socket",B=>{B.unref()}),_&&s.write(_),s.end(),e.dispatchEvent("loadstart")}else{var R=".node-xmlhttprequest-content-"+process.pid,x=".node-xmlhttprequest-sync-"+process.pid;Kt.writeFileSync(x,"","utf8");for(var A="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(k?"s":"")+".request;var options = "+JSON.stringify(q)+";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('"+R+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+x+"');});response.on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+x+"');});}).on('error', function(error) {fs.writeFileSync('"+R+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+x+"');});"+(_?"req.write('"+JSON.stringify(_).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",v=Lh(process.argv[0],["-e",A]),N;Kt.existsSync(x););if(e.responseText=Kt.readFileSync(R,"utf8"),v.stdin.end(),Kt.unlinkSync(R),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var I=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(I,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var C=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:C.data.headers},e.responseText=C.data.text,e.response=Buffer.from(C.data.data,"base64"),w(e.DONE,!0)}}},this.handleError=function(_,k){this.status=k||0,this.statusText=_,this.responseText=_.stack,f=!0,w(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),f=p=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||m)&&this.readyState!==this.DONE&&(m=!1,w(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(_,k){_ in g||(g[_]=[]),g[_].push(k)},this.removeEventListener=function(_,k){_ in g&&(g[_]=g[_].filter(function(P){return P!==k}))},this.dispatchEvent=function(_){if(typeof e["on"+_]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+_]()},0):e["on"+_]()),_ in g)for(let k=0,P=g[_].length;k<P;k++)this.readyState===this.DONE?setTimeout(function(){g[_][k].call(e)},0):g[_][k].call(e)};var w=function(_){if(!(e.readyState===_||e.readyState===e.UNSENT&&p)&&(e.readyState=_,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let k;p?k="abort":f?k="error":k="load",e.dispatchEvent(k),e.dispatchEvent("loadend")}}}});var Ve,Tn,Cn,gr=O(()=>{Ve=Object.create(null);Ve.open="0";Ve.close="1";Ve.ping="2";Ve.pong="3";Ve.message="4";Ve.upgrade="5";Ve.noop="6";Tn=Object.create(null);Object.keys(Ve).forEach(n=>{Tn[Ve[n]]=n});Cn={type:"error",data:"parser error"}});function ja(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(Wa(n.data,!1));Rn(n,!0,t=>{Ds||(Ds=new TextEncoder),e(Ds.encode(t))})}var Rn,Wa,Ds,Ja=O(()=>{gr();Rn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+Wa(e,!0).toString("base64")):r(Ve[n]+(e||"")),Wa=(n,e)=>Buffer.isBuffer(n)||n instanceof Uint8Array&&!e?n:n instanceof ArrayBuffer?Buffer.from(n):Buffer.from(n.buffer,n.byteOffset,n.byteLength)});var An,Ya,Va=O(()=>{gr();An=(n,e)=>{if(typeof n!="string")return{type:"message",data:Ya(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:Ya(r,e)}}return Tn[t]?n.length>1?{type:Tn[t],data:n.substring(1)}:{type:Tn[t]}:Cn},Ya=(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 Qa(){return new TransformStream({transform(n,e){ja(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 mr(n){return n.reduce((e,t)=>e+t.length,0)}function yr(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 Za(n,e){Bs||(Bs=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(mr(t)<1)break;let c=yr(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(mr(t)<2)break;let c=yr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(mr(t)<8)break;let c=yr(t,8),d=new DataView(c.buffer,c.byteOffset,c.length),l=d.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(Cn);break}s=l*Math.pow(2,32)+d.getUint32(4),r=3}else{if(mr(t)<s)break;let c=yr(t,s);a.enqueue(An(i?c:Bs.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(Cn);break}}}})}var za,Ka,Xa,Bs,Us,Xt=O(()=>{Ja();Va();gr();za="",Ka=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Rn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(za))})})},Xa=(n,e)=>{let t=n.split(za),r=[];for(let s=0;s<t.length;s++){let i=An(t[s],e);if(r.push(i),i.type==="error")break}return r};Us=4});var Mt=K(ec=>{ec.Emitter=Ee;function Ee(n){if(n)return $h(n)}function $h(n){for(var e in Ee.prototype)n[e]=Ee.prototype[e];return n}Ee.prototype.on=Ee.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Ee.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Ee.prototype.off=Ee.prototype.removeListener=Ee.prototype.removeAllListeners=Ee.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};Ee.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};Ee.prototype.emitReserved=Ee.prototype.emit;Ee.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Ee.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function nc(){return new Fs}function Dh(n){let e=n.split("; "),t=e[0].indexOf("=");if(t===-1)return;let r=e[0].substring(0,t).trim();if(!r.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:r,value:s};for(let o=1;o<e.length;o++){let a=e[o].split("=");if(a.length!==2)continue;let c=a[0].trim(),d=a[1].trim();switch(c){case"Expires":i.expires=new Date(d);break;case"Max-Age":let l=new Date;l.setUTCSeconds(l.getUTCSeconds()+parseInt(d,10)),i.expires=l;break;default:}}return i}var ct,xe,tc,Fs,Lt=O(()=>{ct=process.nextTick,xe=global,tc="nodebuffer";Fs=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=Dh(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 _r(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function lt(n,e){e.useNativeTimers?(n.setTimeoutFn=Bh.bind(xe),n.clearTimeoutFn=Uh.bind(xe)):(n.setTimeoutFn=xe.setTimeout.bind(xe),n.clearTimeoutFn=xe.clearTimeout.bind(xe))}function rc(n){return typeof n=="string"?Hh(n):Math.ceil((n.byteLength||n.size)*Fh)}function Hh(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 wr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Bh,Uh,Fh,$t=O(()=>{Lt();Bh=xe.setTimeout,Uh=xe.clearTimeout;Fh=1.33});function sc(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function ic(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 Hs=O(()=>{});var ac=K((Cv,oc)=>{var Qt=1e3,Zt=Qt*60,en=Zt*60,Dt=en*24,qh=Dt*7,Gh=Dt*365.25;oc.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return Wh(n);if(t==="number"&&isFinite(n))return e.long?Jh(n):jh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function Wh(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*Gh;case"weeks":case"week":case"w":return t*qh;case"days":case"day":case"d":return t*Dt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*en;case"minutes":case"minute":case"mins":case"min":case"m":return t*Zt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Qt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function jh(n){var e=Math.abs(n);return e>=Dt?Math.round(n/Dt)+"d":e>=en?Math.round(n/en)+"h":e>=Zt?Math.round(n/Zt)+"m":e>=Qt?Math.round(n/Qt)+"s":n+"ms"}function Jh(n){var e=Math.abs(n);return e>=Dt?vr(n,e,Dt,"day"):e>=en?vr(n,e,en,"hour"):e>=Zt?vr(n,e,Zt,"minute"):e>=Qt?vr(n,e,Qt,"second"):n+" ms"}function vr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var qs=K((Rv,cc)=>{function Yh(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=ac(),t.destroy=d,Object.keys(n).forEach(l=>{t[l]=n[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let u=0;for(let m=0;m<l.length;m++)u=(u<<5)-u+l.charCodeAt(m),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,m=null,f,p;function g(...y){if(!g.enabled)return;let E=g,w=Number(new Date),_=w-(u||w);E.diff=_,E.prev=u,E.curr=w,u=w,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let k=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,L)=>{if(T==="%%")return"%";k++;let F=t.formatters[L];if(typeof F=="function"){let J=y[k];T=F.call(E,J),y.splice(k,1),k--}return T}),t.formatArgs.call(E,y),(E.log||t.log).apply(E,y)}return g.namespace=l,g.useColors=t.useColors(),g.color=t.selectColor(l),g.extend=r,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(f!==t.namespaces&&(f=t.namespaces,p=t.enabled(l)),p),set:y=>{m=y}}),typeof t.init=="function"&&t.init(g),g}function r(l,u){let m=t(this.namespace+(typeof u>"u"?":":u)+l);return m.log=this.log,m}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let u=(typeof l=="string"?l:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of u)m[0]==="-"?t.skips.push(m.slice(1)):t.names.push(m)}function i(l,u){let m=0,f=0,p=-1,g=0;for(;m<l.length;)if(f<u.length&&(u[f]===l[m]||u[f]==="*"))u[f]==="*"?(p=f,g=m,f++):(m++,f++);else if(p!==-1)f=p+1,g++,m=g;else return!1;for(;f<u.length&&u[f]==="*";)f++;return f===u.length}function o(){let l=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),l}function a(l){for(let u of t.skips)if(i(l,u))return!1;for(let u of t.names)if(i(l,u))return!0;return!1}function c(l){return l instanceof Error?l.stack||l.message:l}function d(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}cc.exports=Yh});var lc=K((Oe,br)=>{Oe.formatArgs=zh;Oe.save=Kh;Oe.load=Xh;Oe.useColors=Vh;Oe.storage=Qh();Oe.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`."))}})();Oe.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 Vh(){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 zh(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+br.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)}Oe.log=console.debug||console.log||(()=>{});function Kh(n){try{n?Oe.storage.setItem("debug",n):Oe.storage.removeItem("debug")}catch{}}function Xh(){let n;try{n=Oe.storage.getItem("debug")||Oe.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Qh(){try{return localStorage}catch{}}br.exports=qs()(Oe);var{formatters:Zh}=br.exports;Zh.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var uc=K((me,Sr)=>{var ep=X("tty"),kr=X("util");me.init=ap;me.log=sp;me.formatArgs=np;me.save=ip;me.load=op;me.useColors=tp;me.destroy=kr.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");me.colors=[6,2,3,4,5,1];try{let n=X("supports-color");n&&(n.stderr||n).level>=2&&(me.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}me.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function tp(){return"colors"in me.inspectOpts?!!me.inspectOpts.colors:ep.isatty(process.stderr.fd)}function np(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+"+kr.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=tp()+e+" "+n[0]}function tp(){return me.inspectOpts.hideDate?"":new Date().toISOString()+" "}function np(...n){return process.stderr.write(br.formatWithOptions(me.inspectOpts,...n)+`
207
- `)}function rp(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function sp(){return process.env.DEBUG}function ip(n){n.inspectOpts={};let e=Object.keys(me.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=me.inspectOpts[e[t]]}kr.exports=Hs()(me);var{formatters:dc}=kr.exports;dc.o=function(n){return this.inspectOpts.colors=this.useColors,br.inspect(n,this.inspectOpts).split(`
208
- `).map(e=>e.trim()).join(" ")};dc.O=function(n){return this.inspectOpts.colors=this.useColors,br.inspect(n,this.inspectOpts)}});var He=K((Tv,qs)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?qs.exports=cc():qs.exports=lc()});var uc,fc,op,Sr,lt,On=O(()=>{Xt();uc=te(Mt(),1);$t();Fs();fc=te(He(),1),op=(0,fc.default)("engine.io-client:transport"),Sr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},lt=class extends uc.Emitter{constructor(e){super(),this.writable=!1,dt(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 Sr(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):op("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=An(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=rc(e);return t.length?"?"+t:""}}});var hc,ze,Pn,Gs=O(()=>{On();$t();Xt();hc=te(He(),1),ze=(0,hc.default)("engine.io-client:polling"),Pn=class extends lt{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{ze("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(ze("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){ze("pre-pause polling complete"),--r||t()})),this.writable||(ze("we are currently writing - waiting to pause"),r++,this.once("drain",function(){ze("pre-pause writing complete"),--r||t()}))}else t()}_poll(){ze("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){ze("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)};Ka(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():ze('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{ze("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(ze("transport open - closing"),e()):(ze("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,za(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]=_r()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var pc,gc,mc=O(()=>{pc=!1;try{pc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}gc=pc});function ap(){}function yc(){for(let n in ut.requests)ut.requests.hasOwnProperty(n)&&ut.requests[n].abort()}function cp(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||gc))return new XMLHttpRequest}catch{}if(!e)try{return new Ee[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var _c,wc,Ws,Er,ut,Fv,js=O(()=>{Gs();_c=te(Mt(),1);$t();Lt();mc();wc=te(He(),1),Ws=(0,wc.default)("engine.io-client:polling");Er=class extends Pn{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){Ws("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},ut=class n extends _c.Emitter{constructor(e,t,r){super(),this.createRequest=e,dt(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=yr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{Ws("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))},Ws("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=ap,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete n.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ut.requestsCount=0;ut.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",yc);else if(typeof addEventListener=="function"){let n="onpagehide"in Ee?"pagehide":"unload";addEventListener(n,yc,!1)}}Fv=(function(){let n=cp({xdomain:!1});return n&&n.responseType!==null})()});var Js,dp,tn,Ys=O(()=>{Js=te(qa(),1);js();dp=Js.default||Js,tn=class extends Er{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new ut(r=>new dp(r),this.uri(),e)}}});var ft=K((Wv,kc)=>{"use strict";var vc=["nodebuffer","arraybuffer","fragments"],bc=typeof Blob<"u";bc&&vc.push("blob");kc.exports={BINARY_TYPES:vc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:bc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var In=K((jv,xr)=>{"use strict";var{EMPTY_BUFFER:lp}=ft(),Vs=Buffer[Symbol.species];function up(n,e){if(n.length===0)return lp;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 Vs(t.buffer,t.byteOffset,r):t}function Sc(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Ec(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function fp(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function zs(n){if(zs.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Vs(n):ArrayBuffer.isView(n)?e=new Vs(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),zs.readOnly=!1),e}xr.exports={concat:up,mask:Sc,toArrayBuffer:fp,toBuffer:zs,unmask:Ec};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=X("bufferutil");xr.exports.mask=function(e,t,r,s,i){i<48?Sc(e,t,r,s,i):n.mask(e,t,r,s,i)},xr.exports.unmask=function(e,t){e.length<32?Ec(e,t):n.unmask(e,t)}}catch{}});var Cc=K((Jv,Tc)=>{"use strict";var xc=Symbol("kDone"),Ks=Symbol("kRun"),Xs=class{constructor(e){this[xc]=()=>{this.pending--,this[Ks]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ks]()}[Ks](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[xc])}}};Tc.exports=Xs});var sn=K((Yv,Pc)=>{"use strict";var Nn=X("zlib"),Rc=In(),hp=Cc(),{kStatusCode:Ac}=ft(),pp=Buffer[Symbol.species],gp=Buffer.from([0,0,255,255]),Cr=Symbol("permessage-deflate"),ht=Symbol("total-length"),nn=Symbol("callback"),xt=Symbol("buffers"),rn=Symbol("error"),Tr,Qs=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,!Tr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Tr=new hp(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[nn];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){Tr.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Tr.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Nn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Cr]=this,this._inflate[ht]=0,this._inflate[xt]=[],this._inflate.on("error",yp),this._inflate.on("data",Oc)}this._inflate[nn]=r,this._inflate.write(e),t&&this._inflate.write(gp),this._inflate.flush(()=>{let i=this._inflate[rn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Rc.concat(this._inflate[xt],this._inflate[ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ht]=0,this._inflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Nn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ht]=0,this._deflate[xt]=[],this._deflate.on("data",mp)}this._deflate[nn]=r,this._deflate.write(e),this._deflate.flush(Nn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Rc.concat(this._deflate[xt],this._deflate[ht]);t&&(i=new pp(i.buffer,i.byteOffset,i.length-4)),this._deflate[nn]=null,this._deflate[ht]=0,this._deflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Pc.exports=Qs;function mp(n){this[xt].push(n),this[ht]+=n.length}function Oc(n){if(this[ht]+=n.length,this[Cr]._maxPayload<1||this[ht]<=this[Cr]._maxPayload){this[xt].push(n);return}this[rn]=new RangeError("Max payload size exceeded"),this[rn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rn][Ac]=1009,this.removeListener("data",Oc),this.reset()}function yp(n){if(this[Cr]._inflate=null,this[rn]){this[nn](this[rn]);return}n[Ac]=1007,this[nn](n)}});var on=K((Vv,Rr)=>{"use strict";var{isUtf8:Ic}=X("buffer"),{hasBlob:_p}=ft(),wp=[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 vp(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Zs(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function bp(n){return _p&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Rr.exports={isBlob:bp,isValidStatusCode:vp,isValidUTF8:Zs,tokenChars:wp};if(Ic)Rr.exports.isValidUTF8=function(n){return n.length<24?Zs(n):Ic(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=X("utf-8-validate");Rr.exports.isValidUTF8=function(e){return e.length<32?Zs(e):n(e)}}catch{}});var si=K((zv,Uc)=>{"use strict";var{Writable:kp}=X("stream"),Nc=sn(),{BINARY_TYPES:Sp,EMPTY_BUFFER:Mc,kStatusCode:Ep,kWebSocket:xp}=ft(),{concat:ei,toArrayBuffer:Tp,unmask:Cp}=In(),{isValidStatusCode:Rp,isValidUTF8:Lc}=on(),Ar=Buffer[Symbol.species],qe=0,$c=1,Dc=2,Bc=3,ti=4,ni=5,Or=6,ri=class extends kp{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Sp[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[xp]=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=qe}_write(e,t,r){if(this._opcode===8&&this._state==qe)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 Ar(r.buffer,r.byteOffset+e,r.length-e),new Ar(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 Ar(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 qe:this.getInfo(e);break;case $c:this.getPayloadLength16(e);break;case Dc:this.getPayloadLength64(e);break;case Bc:this.getMask();break;case ti:this.getData(e);break;case ni:case Or: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[Nc.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=$c:this._payloadLength===127?this._state=Dc: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=Bc:this._state=ti}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ti}getData(e){let t=Mc;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&&Cp(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ni,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Nc.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===qe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=qe;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=ei(r,t):this._binaryType==="arraybuffer"?s=Tp(ei(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=qe):(this._state=Or,setImmediate(()=>{this.emit("message",s,!0),this._state=qe,this.startLoop(e)}))}else{let s=ei(r,t);if(!this._skipUTF8Validation&&!Lc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ni||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=qe):(this._state=Or,setImmediate(()=>{this.emit("message",s,!1),this._state=qe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Mc),this.end();else{let r=e.readUInt16BE(0);if(!Rp(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Ar(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Lc(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=qe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=qe):(this._state=Or,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=qe,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[Ep]=s,o}};Uc.exports=ri});var ai=K((Xv,qc)=>{"use strict";var{Duplex:Kv}=X("stream"),{randomFillSync:Ap}=X("crypto"),{types:{isUint8Array:Op}}=X("util"),Fc=sn(),{EMPTY_BUFFER:Pp,kWebSocket:Ip,NOOP:Np}=ft(),{isBlob:an,isValidStatusCode:Mp}=on(),{mask:Hc,toBuffer:Bt}=In(),Ge=Symbol("kByteLength"),Lp=Buffer.alloc(4),Pr=8*1024,Ut,cn=Pr,Ke=0,$p=1,Dp=2,ii=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=Ke,this.onerror=Np,this[Ip]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Lp,t.generateMask?t.generateMask(r):(cn===Pr&&(Ut===void 0&&(Ut=Buffer.alloc(Pr)),Ap(Ut,0,Pr),cn=0),r[0]=Ut[cn++],r[1]=Ut[cn++],r[2]=Ut[cn++],r[3]=Ut[cn++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Ge]!==void 0?a=t[Ge]:(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?(Hc(e,r,l,i,a),[l]):(Hc(e,r,e,0,a),[l,e])):[l,e]}close(e,t,r,s){let i;if(e===void 0)i=Pp;else{if(typeof e!="number"||!Mp(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(Op(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Ge]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ke?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):an(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};an(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ke?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):an(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};an(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ke?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Fc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):an(e)?(a=e.size,c=!1):(e=Bt(e),a=e.length,c=Bt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let l={[Ge]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};an(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ke?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[Ge],this._state=Dp,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(oi,this,a,s);return}this._bufferedBytes-=r[Ge];let o=Bt(i);t?this.dispatch(o,t,r,s):(this._state=Ke,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Bp,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Fc.extensionName];this._bufferedBytes+=r[Ge],this._state=$p,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");oi(this,c,s);return}this._bufferedBytes-=r[Ge],this._state=Ke,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Ke&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ge],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ge],this._queue.push(e)}sendFrame(e,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)}};qc.exports=ii;function oi(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 Bp(n,e,t){oi(n,e,t),n.onerror(e)}});var Xc=K((Qv,Kc)=>{"use strict";var{kForOnEventAttribute:Mn,kListener:ci}=ft(),Gc=Symbol("kCode"),Wc=Symbol("kData"),jc=Symbol("kError"),Jc=Symbol("kMessage"),Yc=Symbol("kReason"),dn=Symbol("kTarget"),Vc=Symbol("kType"),zc=Symbol("kWasClean"),pt=class{constructor(e){this[dn]=null,this[Vc]=e}get target(){return this[dn]}get type(){return this[Vc]}};Object.defineProperty(pt.prototype,"target",{enumerable:!0});Object.defineProperty(pt.prototype,"type",{enumerable:!0});var Ft=class extends pt{constructor(e,t={}){super(e),this[Gc]=t.code===void 0?0:t.code,this[Yc]=t.reason===void 0?"":t.reason,this[zc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Gc]}get reason(){return this[Yc]}get wasClean(){return this[zc]}};Object.defineProperty(Ft.prototype,"code",{enumerable:!0});Object.defineProperty(Ft.prototype,"reason",{enumerable:!0});Object.defineProperty(Ft.prototype,"wasClean",{enumerable:!0});var ln=class extends pt{constructor(e,t={}){super(e),this[jc]=t.error===void 0?null:t.error,this[Jc]=t.message===void 0?"":t.message}get error(){return this[jc]}get message(){return this[Jc]}};Object.defineProperty(ln.prototype,"error",{enumerable:!0});Object.defineProperty(ln.prototype,"message",{enumerable:!0});var Ln=class extends pt{constructor(e,t={}){super(e),this[Wc]=t.data===void 0?null:t.data}get data(){return this[Wc]}};Object.defineProperty(Ln.prototype,"data",{enumerable:!0});var Up={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Mn]&&s[ci]===e&&!s[Mn])return;let r;if(n==="message")r=function(i,o){let a=new Ln("message",{data:o?i:i.toString()});a[dn]=this,Ir(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ft("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[dn]=this,Ir(e,this,a)};else if(n==="error")r=function(i){let o=new ln("error",{error:i,message:i.message});o[dn]=this,Ir(e,this,o)};else if(n==="open")r=function(){let i=new pt("open");i[dn]=this,Ir(e,this,i)};else return;r[Mn]=!!t[Mn],r[ci]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[ci]===e&&!t[Mn]){this.removeListener(n,t);break}}};Kc.exports={CloseEvent:Ft,ErrorEvent:ln,Event:pt,EventTarget:Up,MessageEvent:Ln};function Ir(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Nr=K((Zv,Qc)=>{"use strict";var{tokenChars:$n}=on();function nt(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Fp(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&&$n[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 f=n.slice(c,d);l===44?(nt(e,f,t),t=Object.create(null)):o=f,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&$n[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),nt(t,n.slice(c,d),!0),l===44&&(nt(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($n[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if($n[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&&$n[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 f=n.slice(c,d);r&&(f=f.replace(/\\/g,""),r=!1),nt(t,a,f),l===44&&(nt(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?nt(e,m,t):(a===void 0?nt(t,m,!0):r?nt(t,a,m.replace(/\\/g,"")):nt(t,a,m),nt(e,o,t)),e}function Hp(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(", ")}Qc.exports={format:Hp,parse:Fp}});var Dr=K((nb,ld)=>{"use strict";var qp=X("events"),Gp=X("https"),Wp=X("http"),td=X("net"),jp=X("tls"),{randomBytes:Jp,createHash:Yp}=X("crypto"),{Duplex:eb,Readable:tb}=X("stream"),{URL:di}=X("url"),Tt=sn(),Vp=si(),zp=ai(),{isBlob:Kp}=on(),{BINARY_TYPES:Zc,CLOSE_TIMEOUT:Xp,EMPTY_BUFFER:Mr,GUID:Qp,kForOnEventAttribute:li,kListener:Zp,kStatusCode:eg,kWebSocket:ye,NOOP:nd}=ft(),{EventTarget:{addEventListener:tg,removeEventListener:ng}}=Xc(),{format:rg,parse:sg}=Nr(),{toBuffer:ig}=In(),rd=Symbol("kAborted"),ui=[8,13],gt=["CONNECTING","OPEN","CLOSING","CLOSED"],og=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ce=class n extends qp{constructor(e,t,r){super(),this._binaryType=Zc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Mr,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]),sd(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Zc.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 Vp({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new zp(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ye]=this,i[ye]=this,e[ye]=this,s.on("conclude",dg),s.on("drain",lg),s.on("error",ug),s.on("message",fg),s.on("ping",hg),s.on("pong",pg),i.onerror=gg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ad),e.on("data",$r),e.on("end",cd),e.on("error",dd),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Tt.extensionName]&&this._extensions[Tt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){De(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())}),od(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){fi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Mr,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){fi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Mr,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){fi(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Tt.extensionName]||(s.compress=!1),this._sender.send(e||Mr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){De(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(ce,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(ce.prototype,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(ce,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(ce.prototype,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(ce,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(ce.prototype,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(ce,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});Object.defineProperty(ce.prototype,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(ce.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(ce.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[li])return e[Zp];return null},set(e){for(let t of this.listeners(n))if(t[li]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[li]:!0})}})});ce.prototype.addEventListener=tg;ce.prototype.removeEventListener=ng;ld.exports=ce;function sd(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Xp,protocolVersion:ui[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,!ui.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${ui.join(", ")})`);let i;if(e instanceof di)i=e;else try{i=new di(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;Lr(n,g);return}let l=o?443:80,d=Jp(16).toString("base64"),u=o?Gp.request:Wp.request,m=new Set,f;if(s.createConnection=s.createConnection||(o?cg:ag),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&&(f=new Tt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=rg({[Tt.extensionName]:f.offer()})),t.length){for(let g of t){if(typeof g!="string"||!og.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let p;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[y,E]of Object.entries(g))r.headers[y.toLowerCase()]=E}else if(n.listenerCount("redirect")===0){let g=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!g||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,g||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=n._req=u(s),n._redirects&&n.emit("redirect",n.url,p)}else p=n._req=u(s);s.timeout&&p.on("timeout",()=>{De(n,p,"Opening handshake has timed out")}),p.on("error",g=>{p===null||p[rd]||(p=n._req=null,Lr(n,g))}),p.on("response",g=>{let y=g.headers.location,E=g.statusCode;if(y&&s.followRedirects&&E>=300&&E<400){if(++n._redirects>s.maxRedirects){De(n,p,"Maximum redirects exceeded");return}p.abort();let w;try{w=new di(y,e)}catch{let k=new SyntaxError(`Invalid URL: ${y}`);Lr(n,k);return}sd(n,w,t,r)}else n.emit("unexpected-response",p,g)||De(n,p,`Unexpected server response: ${g.statusCode}`)}),p.on("upgrade",(g,y,E)=>{if(n.emit("upgrade",g),n.readyState!==ce.CONNECTING)return;p=n._req=null;let w=g.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){De(n,y,"Invalid Upgrade header");return}let _=Yp("sha1").update(d+Qp).digest("base64");if(g.headers["sec-websocket-accept"]!==_){De(n,y,"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){De(n,y,P);return}k&&(n._protocol=k);let T=g.headers["sec-websocket-extensions"];if(T!==void 0){if(!f){De(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let L;try{L=sg(T)}catch{De(n,y,"Invalid Sec-WebSocket-Extensions header");return}let F=Object.keys(L);if(F.length!==1||F[0]!==Tt.extensionName){De(n,y,"Server indicated an extension that was not requested");return}try{f.accept(L[Tt.extensionName])}catch{De(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Tt.extensionName]=f}n.setSocket(y,E,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,n):p.end()}function Lr(n,e){n._readyState=ce.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function ag(n){return n.path=n.socketPath,td.connect(n)}function cg(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=td.isIP(n.host)?"":n.host),jp.connect(n)}function De(n,e,t){n._readyState=ce.CLOSING;let r=new Error(t);Error.captureStackTrace(r,De),e.setHeader?(e[rd]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Lr,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function fi(n,e,t){if(e){let r=Kp(e)?e.size:ig(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${gt[n.readyState]})`);process.nextTick(t,r)}}function dg(n,e){let t=this[ye];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ye]!==void 0&&(t._socket.removeListener("data",$r),process.nextTick(id,t._socket),n===1005?t.close():t.close(n,e))}function lg(){let n=this[ye];n.isPaused||n._socket.resume()}function ug(n){let e=this[ye];e._socket[ye]!==void 0&&(e._socket.removeListener("data",$r),process.nextTick(id,e._socket),e.close(n[eg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function ed(){this[ye].emitClose()}function fg(n,e){this[ye].emit("message",n,e)}function hg(n){let e=this[ye];e._autoPong&&e.pong(n,!this._isServer,nd),e.emit("ping",n)}function pg(n){this[ye].emit("pong",n)}function id(n){n.resume()}function gg(n){let e=this[ye];e.readyState!==ce.CLOSED&&(e.readyState===ce.OPEN&&(e._readyState=ce.CLOSING,od(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function od(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function ad(){let n=this[ye];if(this.removeListener("close",ad),this.removeListener("data",$r),this.removeListener("end",cd),n._readyState=ce.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ye]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",ed),n._receiver.on("finish",ed))}function $r(n){this[ye]._receiver.write(n)||this.pause()}function cd(){let n=this[ye];n._readyState=ce.CLOSING,n._receiver.end(),this.end()}function dd(){let n=this[ye];this.removeListener("error",dd),this.on("error",nd),n&&(n._readyState=ce.CLOSING,this.destroy())}});var pd=K((sb,hd)=>{"use strict";var rb=Dr(),{Duplex:mg}=X("stream");function ud(n){n.emit("close")}function yg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function fd(n){this.removeListener("error",fd),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function _g(n,e){let t=!0,r=new mg({...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(ud,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(ud,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",yg),r.on("error",fd),r}hd.exports=_g});var hi=K((ib,gd)=>{"use strict";var{tokenChars:wg}=on();function vg(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&&wg[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}gd.exports={parse:vg}});var kd=K((ab,bd)=>{"use strict";var bg=X("events"),Br=X("http"),{Duplex:ob}=X("stream"),{createHash:kg}=X("crypto"),md=Nr(),Ht=sn(),Sg=hi(),Eg=Dr(),{CLOSE_TIMEOUT:xg,GUID:Tg,kWebSocket:Cg}=ft(),Rg=/^[+/0-9A-Za-z]{22}==$/,yd=0,_d=1,vd=2,pi=class extends bg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:xg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Eg,...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=Br.createServer((r,s)=>{let i=Br.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=Ag(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=yd}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===vd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Dn,this);return}if(e&&this.once("close",e),this._state!==_d)if(this._state=_d,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Dn,this):process.nextTick(Dn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Dn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",wd);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Rg.test(i)){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Bn(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Sg.parse(c)}catch{qt(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 Ht({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=md.parse(d);f[Ht.extensionName]&&(m.accept(f[Ht.extensionName]),u[Ht.extensionName]=m)}catch{qt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,p,g,y)=>{if(!f)return Bn(t,p||401,g,y);this.completeUpgrade(u,i,l,e,t,r,s)});return}if(!this.options.verifyClient(m))return Bn(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[Cg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>yd)return Bn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${kg("sha1").update(t+Tg).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[Ht.extensionName]){let u=e[Ht.extensionName].params,m=md.format({[Ht.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+"+Sr.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=rp()+e+" "+n[0]}function rp(){return me.inspectOpts.hideDate?"":new Date().toISOString()+" "}function sp(...n){return process.stderr.write(kr.formatWithOptions(me.inspectOpts,...n)+`
207
+ `)}function ip(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function op(){return process.env.DEBUG}function ap(n){n.inspectOpts={};let e=Object.keys(me.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=me.inspectOpts[e[t]]}Sr.exports=qs()(me);var{formatters:dc}=Sr.exports;dc.o=function(n){return this.inspectOpts.colors=this.useColors,kr.inspect(n,this.inspectOpts).split(`
208
+ `).map(e=>e.trim()).join(" ")};dc.O=function(n){return this.inspectOpts.colors=this.useColors,kr.inspect(n,this.inspectOpts)}});var He=K((Av,Gs)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Gs.exports=lc():Gs.exports=uc()});var fc,hc,cp,Er,dt,On=O(()=>{Xt();fc=te(Mt(),1);$t();Hs();hc=te(He(),1),cp=(0,hc.default)("engine.io-client:transport"),Er=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},dt=class extends fc.Emitter{constructor(e){super(),this.writable=!1,lt(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new Er(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):cp("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=An(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){let e=this.opts.hostname;return e.indexOf(":")===-1?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(this.opts.port)!==443||!this.opts.secure&&Number(this.opts.port)!==80)?":"+this.opts.port:""}_query(e){let t=sc(e);return t.length?"?"+t:""}}});var pc,ze,Pn,Ws=O(()=>{On();$t();Xt();pc=te(He(),1),ze=(0,pc.default)("engine.io-client:polling"),Pn=class extends dt{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{ze("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(ze("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){ze("pre-pause polling complete"),--r||t()})),this.writable||(ze("we are currently writing - waiting to pause"),r++,this.once("drain",function(){ze("pre-pause writing complete"),--r||t()}))}else t()}_poll(){ze("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){ze("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)};Xa(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():ze('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{ze("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(ze("transport open - closing"),e()):(ze("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,Ka(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]=wr()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var gc,mc,yc=O(()=>{gc=!1;try{gc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}mc=gc});function lp(){}function _c(){for(let n in ut.requests)ut.requests.hasOwnProperty(n)&&ut.requests[n].abort()}function dp(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||mc))return new XMLHttpRequest}catch{}if(!e)try{return new xe[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var wc,vc,js,xr,ut,Gv,Js=O(()=>{Ws();wc=te(Mt(),1);$t();Lt();yc();vc=te(He(),1),js=(0,vc.default)("engine.io-client:polling");xr=class extends Pn{constructor(e){if(super(e),typeof location<"u"){let t=location.protocol==="https:",r=location.port;r||(r=t?"443":"80"),this.xd=typeof location<"u"&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){let r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(s,i)=>{this.onError("xhr post error",s,i)})}doPoll(){js("xhr poll");let e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(t,r)=>{this.onError("xhr poll error",t,r)}),this.pollXhr=e}},ut=class n extends wc.Emitter{constructor(e,t,r){super(),this.createRequest=e,lt(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=r.data!==void 0?r.data:null,this._create()}_create(){var e;let t=_r(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{js("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))},js("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=lp,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete n.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ut.requestsCount=0;ut.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",_c);else if(typeof addEventListener=="function"){let n="onpagehide"in xe?"pagehide":"unload";addEventListener(n,_c,!1)}}Gv=(function(){let n=dp({xdomain:!1});return n&&n.responseType!==null})()});var Ys,up,tn,Vs=O(()=>{Ys=te(Ga(),1);Js();up=Ys.default||Ys,tn=class extends xr{request(e={}){var t;return Object.assign(e,{xd:this.xd,cookieJar:(t=this.socket)===null||t===void 0?void 0:t._cookieJar},this.opts),new ut(r=>new up(r),this.uri(),e)}}});var ft=K((Yv,Sc)=>{"use strict";var bc=["nodebuffer","arraybuffer","fragments"],kc=typeof Blob<"u";kc&&bc.push("blob");Sc.exports={BINARY_TYPES:bc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:kc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var In=K((Vv,Tr)=>{"use strict";var{EMPTY_BUFFER:fp}=ft(),zs=Buffer[Symbol.species];function hp(n,e){if(n.length===0)return fp;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 zs(t.buffer,t.byteOffset,r):t}function Ec(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function xc(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function pp(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Ks(n){if(Ks.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new zs(n):ArrayBuffer.isView(n)?e=new zs(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Ks.readOnly=!1),e}Tr.exports={concat:hp,mask:Ec,toArrayBuffer:pp,toBuffer:Ks,unmask:xc};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=X("bufferutil");Tr.exports.mask=function(e,t,r,s,i){i<48?Ec(e,t,r,s,i):n.mask(e,t,r,s,i)},Tr.exports.unmask=function(e,t){e.length<32?xc(e,t):n.unmask(e,t)}}catch{}});var Rc=K((zv,Cc)=>{"use strict";var Tc=Symbol("kDone"),Xs=Symbol("kRun"),Qs=class{constructor(e){this[Tc]=()=>{this.pending--,this[Xs]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Xs]()}[Xs](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Tc])}}};Cc.exports=Qs});var sn=K((Kv,Ic)=>{"use strict";var Nn=X("zlib"),Ac=In(),gp=Rc(),{kStatusCode:Oc}=ft(),mp=Buffer[Symbol.species],yp=Buffer.from([0,0,255,255]),Rr=Symbol("permessage-deflate"),ht=Symbol("total-length"),nn=Symbol("callback"),xt=Symbol("buffers"),rn=Symbol("error"),Cr,Zs=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,!Cr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Cr=new gp(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[nn];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){Cr.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Cr.add(s=>{this._compress(e,t,(i,o)=>{s(),r(i,o)})})}_decompress(e,t,r){let s=this._isServer?"client":"server";if(!this._inflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Nn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Rr]=this,this._inflate[ht]=0,this._inflate[xt]=[],this._inflate.on("error",wp),this._inflate.on("data",Pc)}this._inflate[nn]=r,this._inflate.write(e),t&&this._inflate.write(yp),this._inflate.flush(()=>{let i=this._inflate[rn];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Ac.concat(this._inflate[xt],this._inflate[ht]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[ht]=0,this._inflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._inflate.reset()),r(null,o)})}_compress(e,t,r){let s=this._isServer?"server":"client";if(!this._deflate){let i=`${s}_max_window_bits`,o=typeof this.params[i]!="number"?Nn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Nn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[ht]=0,this._deflate[xt]=[],this._deflate.on("data",_p)}this._deflate[nn]=r,this._deflate.write(e),this._deflate.flush(Nn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Ac.concat(this._deflate[xt],this._deflate[ht]);t&&(i=new mp(i.buffer,i.byteOffset,i.length-4)),this._deflate[nn]=null,this._deflate[ht]=0,this._deflate[xt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Ic.exports=Zs;function _p(n){this[xt].push(n),this[ht]+=n.length}function Pc(n){if(this[ht]+=n.length,this[Rr]._maxPayload<1||this[ht]<=this[Rr]._maxPayload){this[xt].push(n);return}this[rn]=new RangeError("Max payload size exceeded"),this[rn].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[rn][Oc]=1009,this.removeListener("data",Pc),this.reset()}function wp(n){if(this[Rr]._inflate=null,this[rn]){this[nn](this[rn]);return}n[Oc]=1007,this[nn](n)}});var on=K((Xv,Ar)=>{"use strict";var{isUtf8:Nc}=X("buffer"),{hasBlob:vp}=ft(),bp=[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 kp(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function ei(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 Sp(n){return vp&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Ar.exports={isBlob:Sp,isValidStatusCode:kp,isValidUTF8:ei,tokenChars:bp};if(Nc)Ar.exports.isValidUTF8=function(n){return n.length<24?ei(n):Nc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=X("utf-8-validate");Ar.exports.isValidUTF8=function(e){return e.length<32?ei(e):n(e)}}catch{}});var ii=K((Qv,Fc)=>{"use strict";var{Writable:Ep}=X("stream"),Mc=sn(),{BINARY_TYPES:xp,EMPTY_BUFFER:Lc,kStatusCode:Tp,kWebSocket:Cp}=ft(),{concat:ti,toArrayBuffer:Rp,unmask:Ap}=In(),{isValidStatusCode:Op,isValidUTF8:$c}=on(),Or=Buffer[Symbol.species],qe=0,Dc=1,Bc=2,Uc=3,ni=4,ri=5,Pr=6,si=class extends Ep{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||xp[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Cp]=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=qe}_write(e,t,r){if(this._opcode===8&&this._state==qe)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 Or(r.buffer,r.byteOffset+e,r.length-e),new Or(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 Or(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 qe:this.getInfo(e);break;case Dc:this.getPayloadLength16(e);break;case Bc:this.getPayloadLength64(e);break;case Uc:this.getMask();break;case ni:this.getData(e);break;case ri:case Pr: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[Mc.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=Dc:this._payloadLength===127?this._state=Bc: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=Uc:this._state=ni}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ni}getData(e){let t=Lc;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&&Ap(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ri,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Mc.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===qe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=qe;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=ti(r,t):this._binaryType==="arraybuffer"?s=Rp(ti(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=qe):(this._state=Pr,setImmediate(()=>{this.emit("message",s,!0),this._state=qe,this.startLoop(e)}))}else{let s=ti(r,t);if(!this._skipUTF8Validation&&!$c(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ri||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=qe):(this._state=Pr,setImmediate(()=>{this.emit("message",s,!1),this._state=qe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Lc),this.end();else{let r=e.readUInt16BE(0);if(!Op(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Or(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!$c(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=qe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=qe):(this._state=Pr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=qe,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[Tp]=s,o}};Fc.exports=si});var ci=K((eb,Gc)=>{"use strict";var{Duplex:Zv}=X("stream"),{randomFillSync:Pp}=X("crypto"),{types:{isUint8Array:Ip}}=X("util"),Hc=sn(),{EMPTY_BUFFER:Np,kWebSocket:Mp,NOOP:Lp}=ft(),{isBlob:an,isValidStatusCode:$p}=on(),{mask:qc,toBuffer:Bt}=In(),Ge=Symbol("kByteLength"),Dp=Buffer.alloc(4),Ir=8*1024,Ut,cn=Ir,Ke=0,Bp=1,Up=2,oi=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=Ke,this.onerror=Lp,this[Mp]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Dp,t.generateMask?t.generateMask(r):(cn===Ir&&(Ut===void 0&&(Ut=Buffer.alloc(Ir)),Pp(Ut,0,Ir),cn=0),r[0]=Ut[cn++],r[1]=Ut[cn++],r[2]=Ut[cn++],r[3]=Ut[cn++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Ge]!==void 0?a=t[Ge]:(e=Buffer.from(e),a=e.length):(a=e.length,s=t.mask&&t.readOnly&&!o);let c=a;a>=65536?(i+=8,c=127):a>125&&(i+=2,c=126);let d=Buffer.allocUnsafe(s?a+i:i);return d[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(d[0]|=64),d[1]=c,c===126?d.writeUInt16BE(a,2):c===127&&(d[2]=d[3]=0,d.writeUIntBE(a,4,6)),t.mask?(d[1]|=128,d[i-4]=r[0],d[i-3]=r[1],d[i-2]=r[2],d[i-1]=r[3],o?[d,e]:s?(qc(e,r,d,i,a),[d]):(qc(e,r,e,0,a),[d,e])):[d,e]}close(e,t,r,s){let i;if(e===void 0)i=Np;else{if(typeof e!="number"||!$p(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(Ip(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Ge]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ke?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):an(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};an(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ke?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):an(e)?(s=e.size,i=!1):(e=Bt(e),s=e.length,i=Bt.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Ge]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};an(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ke?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[Hc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):an(e)?(a=e.size,c=!1):(e=Bt(e),a=e.length,c=Bt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&s&&s.params[s._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=s._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let d={[Ge]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};an(e)?this._state!==Ke?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==Ke?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[Ge],this._state=Up,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ai,this,a,s);return}this._bufferedBytes-=r[Ge];let o=Bt(i);t?this.dispatch(o,t,r,s):(this._state=Ke,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Fp,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[Hc.extensionName];this._bufferedBytes+=r[Ge],this._state=Bp,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ai(this,c,s);return}this._bufferedBytes-=r[Ge],this._state=Ke,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Ke&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Ge],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ge],this._queue.push(e)}sendFrame(e,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)}};Gc.exports=oi;function ai(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 Fp(n,e,t){ai(n,e,t),n.onerror(e)}});var Qc=K((tb,Xc)=>{"use strict";var{kForOnEventAttribute:Mn,kListener:li}=ft(),Wc=Symbol("kCode"),jc=Symbol("kData"),Jc=Symbol("kError"),Yc=Symbol("kMessage"),Vc=Symbol("kReason"),ln=Symbol("kTarget"),zc=Symbol("kType"),Kc=Symbol("kWasClean"),pt=class{constructor(e){this[ln]=null,this[zc]=e}get target(){return this[ln]}get type(){return this[zc]}};Object.defineProperty(pt.prototype,"target",{enumerable:!0});Object.defineProperty(pt.prototype,"type",{enumerable:!0});var Ft=class extends pt{constructor(e,t={}){super(e),this[Wc]=t.code===void 0?0:t.code,this[Vc]=t.reason===void 0?"":t.reason,this[Kc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Wc]}get reason(){return this[Vc]}get wasClean(){return this[Kc]}};Object.defineProperty(Ft.prototype,"code",{enumerable:!0});Object.defineProperty(Ft.prototype,"reason",{enumerable:!0});Object.defineProperty(Ft.prototype,"wasClean",{enumerable:!0});var dn=class extends pt{constructor(e,t={}){super(e),this[Jc]=t.error===void 0?null:t.error,this[Yc]=t.message===void 0?"":t.message}get error(){return this[Jc]}get message(){return this[Yc]}};Object.defineProperty(dn.prototype,"error",{enumerable:!0});Object.defineProperty(dn.prototype,"message",{enumerable:!0});var Ln=class extends pt{constructor(e,t={}){super(e),this[jc]=t.data===void 0?null:t.data}get data(){return this[jc]}};Object.defineProperty(Ln.prototype,"data",{enumerable:!0});var Hp={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Mn]&&s[li]===e&&!s[Mn])return;let r;if(n==="message")r=function(i,o){let a=new Ln("message",{data:o?i:i.toString()});a[ln]=this,Nr(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ft("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ln]=this,Nr(e,this,a)};else if(n==="error")r=function(i){let o=new dn("error",{error:i,message:i.message});o[ln]=this,Nr(e,this,o)};else if(n==="open")r=function(){let i=new pt("open");i[ln]=this,Nr(e,this,i)};else return;r[Mn]=!!t[Mn],r[li]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[li]===e&&!t[Mn]){this.removeListener(n,t);break}}};Xc.exports={CloseEvent:Ft,ErrorEvent:dn,Event:pt,EventTarget:Hp,MessageEvent:Ln};function Nr(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Mr=K((nb,Zc)=>{"use strict";var{tokenChars:$n}=on();function nt(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function qp(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,d=-1,l=-1,u=0;for(;u<n.length;u++)if(d=n.charCodeAt(u),o===void 0)if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(u!==0&&(d===32||d===9))l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let f=n.slice(c,l);d===44?(nt(e,f,t),t=Object.create(null)):o=f,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(d===32||d===9)l===-1&&c!==-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u),nt(t,n.slice(c,l),!0),d===44&&(nt(e,o,t),t=Object.create(null),o=void 0),c=l=-1}else if(d===61&&c!==-1&&l===-1)a=n.slice(c,u),c=l=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(s){if($n[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if($n[d]===1)c===-1&&(c=u);else if(d===34&&c!==-1)i=!1,l=u;else if(d===92)s=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(d===34&&n.charCodeAt(u-1)===61)i=!0;else if(l===-1&&$n[d]===1)c===-1&&(c=u);else if(c!==-1&&(d===32||d===9))l===-1&&(l=u);else if(d===59||d===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1&&(l=u);let f=n.slice(c,l);r&&(f=f.replace(/\\/g,""),r=!1),nt(t,a,f),d===44&&(nt(e,o,t),t=Object.create(null),o=void 0),a=void 0,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(c===-1||i||d===32||d===9)throw new SyntaxError("Unexpected end of input");l===-1&&(l=u);let m=n.slice(c,l);return o===void 0?nt(e,m,t):(a===void 0?nt(t,m,!0):r?nt(t,a,m.replace(/\\/g,"")):nt(t,a,m),nt(e,o,t)),e}function Gp(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(", ")}Zc.exports={format:Gp,parse:qp}});var Br=K((ib,ul)=>{"use strict";var Wp=X("events"),jp=X("https"),Jp=X("http"),nl=X("net"),Yp=X("tls"),{randomBytes:Vp,createHash:zp}=X("crypto"),{Duplex:rb,Readable:sb}=X("stream"),{URL:di}=X("url"),Tt=sn(),Kp=ii(),Xp=ci(),{isBlob:Qp}=on(),{BINARY_TYPES:el,CLOSE_TIMEOUT:Zp,EMPTY_BUFFER:Lr,GUID:eg,kForOnEventAttribute:ui,kListener:tg,kStatusCode:ng,kWebSocket:ye,NOOP:rl}=ft(),{EventTarget:{addEventListener:rg,removeEventListener:sg}}=Qc(),{format:ig,parse:og}=Mr(),{toBuffer:ag}=In(),sl=Symbol("kAborted"),fi=[8,13],gt=["CONNECTING","OPEN","CLOSING","CLOSED"],cg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,ce=class n extends Wp{constructor(e,t,r){super(),this._binaryType=el[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Lr,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]),il(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){el.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 Kp({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Xp(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[ye]=this,i[ye]=this,e[ye]=this,s.on("conclude",ug),s.on("drain",fg),s.on("error",hg),s.on("message",pg),s.on("ping",gg),s.on("pong",mg),i.onerror=yg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",cl),e.on("data",Dr),e.on("end",ll),e.on("error",dl),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[Tt.extensionName]&&this._extensions[Tt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){De(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())}),al(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){hi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Lr,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){hi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Lr,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){hi(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[Tt.extensionName]||(s.compress=!1),this._sender.send(e||Lr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){De(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(ce,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(ce.prototype,"CONNECTING",{enumerable:!0,value:gt.indexOf("CONNECTING")});Object.defineProperty(ce,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(ce.prototype,"OPEN",{enumerable:!0,value:gt.indexOf("OPEN")});Object.defineProperty(ce,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(ce.prototype,"CLOSING",{enumerable:!0,value:gt.indexOf("CLOSING")});Object.defineProperty(ce,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});Object.defineProperty(ce.prototype,"CLOSED",{enumerable:!0,value:gt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(ce.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(ce.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[ui])return e[tg];return null},set(e){for(let t of this.listeners(n))if(t[ui]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[ui]:!0})}})});ce.prototype.addEventListener=rg;ce.prototype.removeEventListener=sg;ul.exports=ce;function il(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Zp,protocolVersion:fi[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,!fi.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${fi.join(", ")})`);let i;if(e instanceof di)i=e;else try{i=new di(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;$r(n,g);return}let d=o?443:80,l=Vp(16).toString("base64"),u=o?jp.request:Jp.request,m=new Set,f;if(s.createConnection=s.createConnection||(o?dg:lg),s.defaultPort=s.defaultPort||d,s.port=i.port||d,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(f=new Tt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=ig({[Tt.extensionName]:f.offer()})),t.length){for(let g of t){if(typeof g!="string"||!cg.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let p;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[y,E]of Object.entries(g))r.headers[y.toLowerCase()]=E}else if(n.listenerCount("redirect")===0){let g=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!g||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,g||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),p=n._req=u(s),n._redirects&&n.emit("redirect",n.url,p)}else p=n._req=u(s);s.timeout&&p.on("timeout",()=>{De(n,p,"Opening handshake has timed out")}),p.on("error",g=>{p===null||p[sl]||(p=n._req=null,$r(n,g))}),p.on("response",g=>{let y=g.headers.location,E=g.statusCode;if(y&&s.followRedirects&&E>=300&&E<400){if(++n._redirects>s.maxRedirects){De(n,p,"Maximum redirects exceeded");return}p.abort();let w;try{w=new di(y,e)}catch{let k=new SyntaxError(`Invalid URL: ${y}`);$r(n,k);return}il(n,w,t,r)}else n.emit("unexpected-response",p,g)||De(n,p,`Unexpected server response: ${g.statusCode}`)}),p.on("upgrade",(g,y,E)=>{if(n.emit("upgrade",g),n.readyState!==ce.CONNECTING)return;p=n._req=null;let w=g.headers.upgrade;if(w===void 0||w.toLowerCase()!=="websocket"){De(n,y,"Invalid Upgrade header");return}let _=zp("sha1").update(l+eg).digest("base64");if(g.headers["sec-websocket-accept"]!==_){De(n,y,"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){De(n,y,P);return}k&&(n._protocol=k);let T=g.headers["sec-websocket-extensions"];if(T!==void 0){if(!f){De(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let L;try{L=og(T)}catch{De(n,y,"Invalid Sec-WebSocket-Extensions header");return}let F=Object.keys(L);if(F.length!==1||F[0]!==Tt.extensionName){De(n,y,"Server indicated an extension that was not requested");return}try{f.accept(L[Tt.extensionName])}catch{De(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[Tt.extensionName]=f}n.setSocket(y,E,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(p,n):p.end()}function $r(n,e){n._readyState=ce.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function lg(n){return n.path=n.socketPath,nl.connect(n)}function dg(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=nl.isIP(n.host)?"":n.host),Yp.connect(n)}function De(n,e,t){n._readyState=ce.CLOSING;let r=new Error(t);Error.captureStackTrace(r,De),e.setHeader?(e[sl]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick($r,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function hi(n,e,t){if(e){let r=Qp(e)?e.size:ag(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${gt[n.readyState]})`);process.nextTick(t,r)}}function ug(n,e){let t=this[ye];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ye]!==void 0&&(t._socket.removeListener("data",Dr),process.nextTick(ol,t._socket),n===1005?t.close():t.close(n,e))}function fg(){let n=this[ye];n.isPaused||n._socket.resume()}function hg(n){let e=this[ye];e._socket[ye]!==void 0&&(e._socket.removeListener("data",Dr),process.nextTick(ol,e._socket),e.close(n[ng])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function tl(){this[ye].emitClose()}function pg(n,e){this[ye].emit("message",n,e)}function gg(n){let e=this[ye];e._autoPong&&e.pong(n,!this._isServer,rl),e.emit("ping",n)}function mg(n){this[ye].emit("pong",n)}function ol(n){n.resume()}function yg(n){let e=this[ye];e.readyState!==ce.CLOSED&&(e.readyState===ce.OPEN&&(e._readyState=ce.CLOSING,al(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function al(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function cl(){let n=this[ye];if(this.removeListener("close",cl),this.removeListener("data",Dr),this.removeListener("end",ll),n._readyState=ce.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ye]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",tl),n._receiver.on("finish",tl))}function Dr(n){this[ye]._receiver.write(n)||this.pause()}function ll(){let n=this[ye];n._readyState=ce.CLOSING,n._receiver.end(),this.end()}function dl(){let n=this[ye];this.removeListener("error",dl),this.on("error",rl),n&&(n._readyState=ce.CLOSING,this.destroy())}});var gl=K((ab,pl)=>{"use strict";var ob=Br(),{Duplex:_g}=X("stream");function fl(n){n.emit("close")}function wg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function hl(n){this.removeListener("error",hl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function vg(n,e){let t=!0,r=new _g({...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(fl,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(fl,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",wg),r.on("error",hl),r}pl.exports=vg});var pi=K((cb,ml)=>{"use strict";var{tokenChars:bg}=on();function kg(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&&bg[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}ml.exports={parse:kg}});var Sl=K((db,kl)=>{"use strict";var Sg=X("events"),Ur=X("http"),{Duplex:lb}=X("stream"),{createHash:Eg}=X("crypto"),yl=Mr(),Ht=sn(),xg=pi(),Tg=Br(),{CLOSE_TIMEOUT:Cg,GUID:Rg,kWebSocket:Ag}=ft(),Og=/^[+/0-9A-Za-z]{22}==$/,_l=0,wl=1,bl=2,gi=class extends Sg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Cg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Tg,...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=Ur.createServer((r,s)=>{let i=Ur.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=Pg(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=_l}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===bl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Dn,this);return}if(e&&this.once("close",e),this._state!==wl)if(this._state=wl,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Dn,this):process.nextTick(Dn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Dn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,r,s){t.on("error",vl);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){qt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){qt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Og.test(i)){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){qt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Bn(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=xg.parse(c)}catch{qt(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let l=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&l!==void 0){let m=new Ht({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let f=yl.parse(l);f[Ht.extensionName]&&(m.accept(f[Ht.extensionName]),u[Ht.extensionName]=m)}catch{qt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(f,p,g,y)=>{if(!f)return Bn(t,p||401,g,y);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(m))return Bn(t,401)}this.completeUpgrade(u,i,d,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Ag])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>_l)return Bn(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Eg("sha1").update(t+Rg).digest("base64")}`],l=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;u&&(d.push(`Sec-WebSocket-Protocol: ${u}`),l._protocol=u)}if(e[Ht.extensionName]){let u=e[Ht.extensionName].params,m=yl.format({[Ht.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${m}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
209
209
  `).join(`\r
210
- `)),i.removeListener("error",wd),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(Dn,this)})),a(d,s)}};bd.exports=pi;function Ag(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function Dn(n){n._state=vd,n.emit("close")}function wd(){this.destroy()}function Bn(n,e,t,r){t=t||Br.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} ${Br.STATUS_CODES[e]}\r
210
+ `)),i.removeListener("error",vl),l.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Dn,this)})),a(l,s)}};kl.exports=gi;function Pg(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function Dn(n){n._state=bl,n.emit("close")}function vl(){this.destroy()}function Bn(n,e,t,r){t=t||Ur.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} ${Ur.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 qt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qt),n.emit("wsClientError",o,t,e)}else Bn(t,r,s,i)}});var Og,Pg,Ig,Ng,Mg,Lg,gi,$g,Sd=O(()=>{Og=te(pd(),1),Pg=te(Nr(),1),Ig=te(sn(),1),Ng=te(si(),1),Mg=te(ai(),1),Lg=te(hi(),1),gi=te(Dr(),1),$g=te(kd(),1)});var Ed,Bg,Ug,Ur,fb,mi=O(()=>{On();$t();Xt();Lt();Ed=te(He(),1),Bg=(0,Ed.default)("engine.io-client:websocket"),Ug=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Ur=class extends lt{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Ug?{}:yr(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;Rn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{Bg("websocket closed before onclose event")}s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=_r()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},fb=Ee.WebSocket||Ee.MozWebSocket});var un,yi=O(()=>{Sd();mi();un=class extends Ur{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 gi.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 xd,Un,fn,_i=O(()=>{On();Lt();Xt();xd=te(He(),1),Un=(0,xd.default)("engine.io-client:webtransport"),fn=class extends lt{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(()=>{Un("transport closed gracefully"),this.onClose()}).catch(e=>{Un("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Qa(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=Xa();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){Un("session is closed");return}Un("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{Un("an error occurred while reading: %s",a)})};i();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;this._writer.write(r).then(()=>{s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var wi,vi=O(()=>{Ys();yi();_i();wi={websocket:un,webtransport:fn,polling:tn}});function hn(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=Fg.exec(n||""),i={},o=14;for(;o--;)i[Hg[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=qg(i,i.path),i.queryKey=Gg(i,i.query),i}function qg(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 Gg(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var Fg,Hg,bi=O(()=>{Fg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Hg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var Td,Cd,re,ki,Fn,Gt,Fr,pn,Si=O(()=>{vi();$t();Fs();bi();Td=te(Mt(),1);Xt();Lt();Cd=te(He(),1),re=(0,Cd.default)("engine.io-client:socket"),ki=typeof addEventListener=="function"&&typeof removeEventListener=="function",Fn=[];ki&&addEventListener("offline",()=>{re("closing %d connection(s) because the network was lost",Fn.length),Fn.forEach(n=>n())},!1);Gt=class n extends Td.Emitter{constructor(e,t){if(super(),this.binaryType=ec,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=hn(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=hn(t.host).host);dt(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=sc(this.opts.query)),ki&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(re("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Fn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=tc()),this._open()}createTransport(e){re('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Bs,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 re("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){re("setting transport %s",e.name),this.transport&&(re("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(){re("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(re('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 re('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();re("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+=nc(s)),r>0&&t>this._maxPayload)return re("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return re("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&&(re("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,ct(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,s){if(typeof t=="function"&&(s=t,t=void 0),typeof r=="function"&&(s=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;let i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),re("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(re("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return re("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(re('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ki&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Fn.indexOf(this._offlineEventListener);r!==-1&&(re("removing listener for the 'offline' event"),Fn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Gt.protocol=Bs;Fr=class extends Gt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){re("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){re('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Gt.priorWebsocketSuccess=!1;let s=()=>{r||(re('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(re('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Gt.priorWebsocketSuccess=t.name==="websocket",re('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(re("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{re('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(),re('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&&(re('"%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}},pn=class extends Fr{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=>wi[s]).filter(s=>!!s)),super(e,r)}}});var Rd=O(()=>{Gs()});var Lb,Hr=O(()=>{Si();Si();On();vi();$t();bi();Lt();Rd();Ys();js();yi();mi();_i();Lb=pn.protocol});function Pd(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)||(Ad("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Ad("parse %s",n),r=hn(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 Od,Ad,Id=O(()=>{Hr();Od=te(He(),1),Ad=(0,Od.default)("socket.io-client:url")});function qn(n){return Yg&&(n instanceof ArrayBuffer||Vg(n))||zg&&n instanceof Blob||Kg&&n instanceof File}function Hn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Hn(n[t]))return!0;return!1}if(qn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Hn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Hn(n[t]))return!0;return!1}var Yg,Vg,Nd,zg,Kg,Ei=O(()=>{Yg=typeof ArrayBuffer=="function",Vg=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Nd=Object.prototype.toString,zg=typeof Blob=="function"||typeof Blob<"u"&&Nd.call(Blob)==="[object BlobConstructor]",Kg=typeof File=="function"||typeof File<"u"&&Nd.call(File)==="[object FileConstructor]"});function Md(n){let e=[],t=n.data,r=n;return r.data=xi(t,e),r.attachments=e.length,{packet:r,buffers:e}}function xi(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]=xi(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]=xi(n[r],e));return t}return n}function Ld(n,e){return n.data=Ti(n.data,e),delete n.attachments,n}function Ti(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]=Ti(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Ti(n[t],e));return n}var $d=O(()=>{Ei()});var Pi={};$e(Pi,{Decoder:()=>Ai,Encoder:()=>Ri,PacketType:()=>j,isPacketValid:()=>em,protocol:()=>Fd});function Xg(n){return typeof n=="string"}function Qg(n){return n===void 0||Hd(n)}function qr(n){return Object.prototype.toString.call(n)==="[object Object]"}function Zg(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"&&Ud.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 em(n){return Xg(n.nsp)&&Qg(n.id)&&Zg(n.type,n.data)}var Dd,Bd,Ci,Ud,Fd,j,Ri,Ai,Oi,Hd,Gr=O(()=>{Dd=te(Mt(),1);$d();Ei();Bd=te(He(),1),Ci=(0,Bd.default)("socket.io-parser"),Ud=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Fd=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={}));Ri=class{constructor(e){this.replacer=e}encode(e){return Ci("encoding packet %j",e),(e.type===j.EVENT||e.type===j.ACK)&&Hn(e)?this.encodeAsBinary({type:e.type===j.EVENT?j.BINARY_EVENT:j.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===j.BINARY_EVENT||e.type===j.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Ci("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=Md(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},Ai=class n extends Dd.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 Oi(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(!Hd(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 Ci("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"&&Ud.indexOf(t[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Oi=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=Ld(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};Hd=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function Be(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Ii=O(()=>{});var qd,Gd,fe,tm,gn,Ni=O(()=>{Gr();Ii();qd=te(Mt(),1),Gd=te(He(),1),fe=(0,Gd.default)("socket.io-client:socket"),tm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),gn=class extends qd.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=[Be(e,"open",this.onopen.bind(this)),Be(e,"packet",this.onpacket.bind(this)),Be(e,"error",this.onerror.bind(this)),Be(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(tm.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++;fe("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?fe("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&&(fe("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));fe("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]?fe("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(fe("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(fe("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(fe("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){fe("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,fe("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(){fe("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){fe("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||[];fe("emitting event %j",t),e.id!=null&&(fe("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,fe("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"){fe("bad ack %s",e.id);return}delete this.acks[e.id],fe("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){fe("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(){fe("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&&(fe("performing disconnect (%s)",this.nsp),this.packet({type:j.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}}});function Wt(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}var Wd=O(()=>{Wt.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=(Math.floor(e*10)&1)==0?n-t:n+t}return Math.min(n,this.max)|0};Wt.prototype.reset=function(){this.attempts=0};Wt.prototype.setMin=function(n){this.ms=n};Wt.prototype.setMax=function(n){this.max=n};Wt.prototype.setJitter=function(n){this.jitter=n}});var jd,Jd,we,mn,Yd=O(()=>{Hr();Ni();Gr();Ii();Wd();jd=te(Mt(),1),Jd=te(He(),1),we=(0,Jd.default)("socket.io-client:manager"),mn=class extends jd.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,dt(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Wt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||Pi;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(we("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;we("opening %s",this.uri),this.engine=new pn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Be(t,"open",function(){r.onopen(),e&&e()}),i=a=>{we("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Be(t,"error",i);if(this._timeout!==!1){let a=this._timeout;we("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{we("connect attempt timed out after %d",a),s(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(s),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){we("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Be(e,"ping",this.onping.bind(this)),Be(e,"data",this.ondata.bind(this)),Be(e,"error",this.onerror.bind(this)),Be(e,"close",this.onclose.bind(this)),Be(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){ct(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){we("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new gn(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active){we("socket %s is still active, skipping close",r);return}this._close()}_packet(e){we("writing packet %j",e);let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){we("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){we("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;we("closed due to %s",e),this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)we("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();we("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(we("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(we("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(we("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}});function Wn(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=Pd(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Gn[s]&&i in Gn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(Vd("ignoring socket cache for %s",r),c=new mn(r,e)):(Gn[s]||(Vd("new io instance for %s",r),Gn[s]=new mn(r,e)),c=Gn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var zd,Vd,Gn,Kd=O(()=>{Id();Yd();Ni();zd=te(He(),1);Gr();Hr();Vd=(0,zd.default)("socket.io-client"),Gn={};Object.assign(Wn,{Manager:mn,Socket:gn,io:Wn,connect:Wn})});var rt,nm,Wr,Xd=O(()=>{"use strict";Kd();le();rt="wsClient",nm=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),Wr=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",rt,"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=>{S(rt,"catch-up handler threw",o)})}}destroy(){this.destroyed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null)}_connect(){if(this.destroyed||this.authFailed)return;let e=Wn(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",rt,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{S(rt,"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=>{S(rt,"event handler threw",i)})});for(let t of nm)e.on(t,r=>{h("error",rt,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",rt,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",rt,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{S(rt,"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",rt,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var Xe,jr,Qd=O(()=>{"use strict";Yt();ua();hr();Xd();le();Xe="serverGateway",jr=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=kt(),h("info",Xe,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new Wr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>la(t,r)});let e=da();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",Xe,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",Xe,`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",Xe,"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",Xe,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return ha(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await pa(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await ga(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await ma(this.config.server_url,e,t,this._getToken())}async getAction(e){return _a(this.config.server_url,e,this._getToken())}async getApproval(e){return wa(this.config.server_url,e,this._getToken())}async fireAction(e,t){return va(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await ba(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return ka(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return zt(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return Sa(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return xa(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return Ta(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return Ea(this.config.server_url,e,this._getToken())}async getTasks(e,t){return Ca(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return Ra(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return Aa(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return Oa(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return Pa(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Ia(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return Na(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await $a(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await Ma(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 La(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return Da(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Ba(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",Xe,"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 ya(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",Xe,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",Xe,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){S(Xe,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=kt(),t=await fa(this.config.server_url,e);cr(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",Xe,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){S(Xe,"token refresh failed",e)}}_getToken(){return this.token||(this.token=kt()),this.token}}});import{execFile as rm}from"node:child_process";import{promisify as sm}from"node:util";import{readFileSync as im,readdirSync as Jr,statSync as Mi,openSync as om,readSync as am,closeSync as cm}from"node:fs";import{join as jt}from"node:path";import{homedir as Zd}from"node:os";async function dm(){try{if(process.platform==="darwin"){let{stdout:n}=await el("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=im(jt(Zd(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function lm(){let n=await dm();if(!n)return null;try{let{stdout:e}=await el("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 um(n,e){let t=[];try{for(let r of Jr(n).sort().reverse().slice(0,2)){let s=jt(n,r);for(let i of Jr(s).sort().reverse().slice(0,2)){let o=jt(s,i);for(let a of Jr(o).sort().reverse().slice(0,7)){let c=jt(o,a);for(let l of Jr(c)){if(!l.endsWith(".jsonl"))continue;let d=jt(c,l);try{t.push({path:d,mtime:Mi(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 fm(n,e){let t=om(n,"r");try{let r=Mi(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return am(t,i,0,s,r-s),i.toString("utf-8")}finally{cm(t)}}function hm(){let n=process.env.CODEX_HOME??jt(Zd(),".codex");for(let e of um(jt(n,"sessions"),5))try{let t=fm(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(Mi(e).mtimeMs).toISOString()}}catch{}}catch{}return null}async function tl(){let[n,e]=await Promise.all([lm(),Promise.resolve().then(hm)]);return{sampled_at:new Date().toISOString(),claude:n,codex:e}}var el,nl=O(()=>{"use strict";el=sm(rm)});function sl(n,e){jn.set(`${n}:${e}`,Date.now())}function Li(n){let e=`${n}:`;for(let t of jn.keys())t.startsWith(e)&&jn.delete(t)}function il(n,e){let t=`${n}:${e}`,r=jn.get(t);if(r===void 0||(jn.delete(t),Date.now()-r>gm))return!1;let s=rl.get(e)??0;return Date.now()-s<pm?!1:(rl.set(e,Date.now()),!0)}var jn,rl,pm,gm,$i=O(()=>{"use strict";jn=new Map,rl=new Map,pm=600*1e3,gm=1800*1e3});var Ct,ol,Yr,al=O(()=>{"use strict";le();Ct="sessionManager",ol=3e4,Yr=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},ol),h("info",Ct,`Heartbeat timer started (every ${ol/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=>{S(Ct,`Failed to mark session ${t.sessionId} disconnected`,r)}))),h("info",Ct,`SessionManager stopped, ${e.length} sessions marked disconnected`)}async createSession(e){let r={sessionId:(await this.gateway.createSession(e)).id,workroomId:e,status:"idle"};return this.sessions.set(r.sessionId,r),h("info",Ct,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){h("warn",Ct,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,h("info",Ct,"Session status updated",{sessionId:e,status:t})}getSession(e){return this.sessions.get(e)}getAllSessions(){return[...this.sessions.values()]}async _sendHeartbeats(){let e=[...this.sessions.values()].filter(t=>t.status!=="completed"&&t.status!=="failed"&&t.status!=="disconnected");await Promise.all(e.map(t=>this.gateway.sessionHeartbeat(t.sessionId).catch(r=>{S(Ct,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&h("debug",Ct,`Sent ${e.length} heartbeat(s)`)}}});var mt,Vr,cl=O(()=>{"use strict";le();mt="workroomCoordinator",Vr=class{constructor(e,t){this.sessionManager=e;this.actionGate=t}sessionManager;actionGate;workroomRegistry=new Map;shuttingDown=!1;async openWorkroom(e){if(this.shuttingDown)return h("warn",mt,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return h("info",mt,"openWorkroom: workroom already open \u2014 reusing session",{workroomId:e,sessionId:t.sessionId}),t;let r;try{r=await this.sessionManager.createSession(e)}catch(s){return S(mt,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return S(mt,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{S(mt,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),h("info",mt,"workroom opened successfully",{workroomId:e,sessionId:r.sessionId,openCount:this.workroomRegistry.size}),r}shutdownAll(){this.shuttingDown=!0;for(let e of this.workroomRegistry.keys())try{this.actionGate.deregisterWorkroom(e),h("info",mt,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){S(mt,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),h("info",mt,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as Bi,unlink as mm,readdir as ym,stat as _m}from"fs/promises";import{join as zr}from"path";import{randomBytes as Ui}from"crypto";async function ll(n,e){let t=Ui(8).toString("hex"),r=zr(Nt,`action-${n}-${t}${dl}`),s;try{s=await Bi(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return h("info",yt,"secret file written",{actionId:n,filePath:r}),r}async function Jn(n){try{await mm(n),h("info",yt,"secret file deleted",{filePath:n})}catch(e){if(Di(e))return;S(yt,"failed to delete secret file (best-effort)",e)}}async function ul(){let n;try{n=await ym(Nt)}catch(s){if(Di(s))return;S(yt,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(dl)),r=0;for(let s of t){let i=zr(Nt,s);try{let o=await _m(i),a=e-o.mtimeMs;a>=wm&&(await Jn(i),r++,h("info",yt,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(Di(o))continue;S(yt,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&h("info",yt,"TTL scan complete",{scanned:t.length,purged:r})}async function fl(n){let e=Date.now(),t=Ui(4).toString("hex"),r=zr(Nt,`drain-evidence-${e}-${t}.json`),s;try{s=await Bi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",yt,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function hl(n){let e=Date.now(),t=Ui(4).toString("hex"),r=zr(Nt,`response-lost-${e}-${t}.json`),s;try{s=await Bi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",yt,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function Di(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var yt,wm,dl,Kr=O(()=>{"use strict";Ye();le();yt="secretManager",wm=600*1e3,dl=".secret"});import{spawn as vm}from"child_process";import{stat as bm}from"fs/promises";async function pl(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return h("warn",Jt,"no enabled runtime found for kind",{kind:n.kind,actionId:n.actionId,availableKinds:n.runtimes.map(i=>i.kind)}),{ok:!1,reason_code:"RUNTIME_NOT_FOUND"};try{await bm(e.path)}catch{return h("warn",Jt,"runtime binary not accessible",{kind:n.kind,actionId:n.actionId}),{ok:!1,reason_code:"RUNTIME_NOT_FOUND"}}let t={PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,TMPDIR:process.env.TMPDIR,LANG:process.env.LANG,MIO_ACTION_ID:n.actionId,MIO_SESSION_ID:n.sessionId,MIO_WORKROOM_ID:n.workroomId,MIO_ACTION_KIND:n.kind,MIO_IPC_SOCKET:n.ipcSocketPath,...n.serverUrl?{MIO_SERVER_URL:n.serverUrl}:{},MIO_RUNTIME_MODE:n.mode??"controlled-delegated",...process.env.MIO_CLAUDE_CONFIG_DIR?{MIO_CLAUDE_CONFIG_DIR:process.env.MIO_CLAUDE_CONFIG_DIR}:{}},r;if(n.secretContent)try{r=await ll(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return S(Jt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=vm(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return S(Jt,"spawn failed",i),r&&Jn(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{h("info",Jt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&Jn(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{S(Jt,"subprocess error after spawn",i),r&&Jn(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),h("info",Jt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var Jt,gl=O(()=>{"use strict";le();Kr();Jt="runtimeAdapter"});var H,ml,Yn,yl,Vn,_l,km,Xr,Fi=O(()=>{"use strict";hr();le();gl();Kr();H="actionGate",ml=new Set(["proposed","approved"]),Yn=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),yl="irreversible_no_abort",Vn=new Set(["transmission_complete","succeeded","canceled","failed"]),_l=15,km=8e3,Xr=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",H,"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",H,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,h("info",H,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=km){if(this.inFlightIrreversible.size===0){h("info",H,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return h("warn",H,"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);S(H,"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 fl({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",H,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){S(H,"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)&&Vn.has(r)&&this.gateway.getAction(t).then(s=>{Vn.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):h("warn",H,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{S(H,"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",H,"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",H,"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",H,"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=>{Vn.has(s.status)?(h("info",H,"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",H,"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=>{S(H,"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){S(H,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){h("info",H,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){h("warn",H,"action.created: missing action_id in payload \u2014 ignoring");return}h("info",H,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(Yn.has(r.status)){h("info",H,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!ml.has(r.status)){h("info",H,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===yl?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",H,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&h("info",H,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),h("info",H,"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",H,"approval.decided: missing required fields \u2014 ignoring");return}if(h("info",H,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),h("info",H,"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),Yn.has(i.status)){h("info",H,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!ml.has(i.status)){h("warn",H,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){h("warn",H,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){h("warn",H,"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",H,"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&&Yn.has(r),a=i&&Vn.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&Yn.has(c.status)&&(this.pendingApproval.delete(t),h("info",H,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&Vn.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",H,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let d=await this.gateway.fireAction(r,t);h("info",H,"action fired",{actionId:r,fired_at:d.fired_at}),a=d.action_token,o=!0}catch(d){if(d instanceof xn&&d.isDefinitiveRejection){S(H,`fire definitively rejected (${d.statusCode} ${d.errorCode}) \u2014 re-querying before cancel`,d);let m=await this.gateway.getAction(r).catch(()=>null);if(!m||Yn.has(m.status)){h("info",H,"action already in non-cancelable state after rejected fire \u2014 skipping cancel (concurrent winner?)",{actionId:r,currentStatus:m?.status});return}await this.gateway.cancelAction(r).catch(f=>{S(H,"cancel after rejected fire also failed",f)});return}S(H,"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",H,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let m=u.fired_at??new Date().toISOString();await hl({schema_version:1,reason:"fire_response_lost_token_unrecoverable",action_id:r,workroom_id:i,session_id:s,fired_at:m,operator_note:"The fire HTTP response was lost before the action_token was received. The raw token is unrecoverable (server stores only hash). The subprocess was NOT spawned. Verify action status on the server manually.",server_todo:'Server reconcile endpoint implemented (Phase 5C). POST /api/v1/actions/:id/reconcile with { reason: "fire_response_lost_token_unrecoverable", evidence_id: "<this-file-uuid>" }. Auth: machine_token bearer. Remove this file after reconcile confirms needs_human status.'}).catch(f=>{S(H,"failed to write response-lost evidence (CRITICAL)",f)});return}else{h("warn",H,"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===yl;c&&this._registerInFlight(e);let l=await pl({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",H,"spawn returned not-ok",{actionId:r,reason_code:l.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as Sm}from"net";import{chmod as Em}from"fs/promises";var st,Qr,wl=O(()=>{"use strict";le();st="ipcServer",Qr=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=Sm(s=>{this._handleConnection(s)}),this.server.once("error",s=>{S(st,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Em(e,384)}catch(s){S(st,"Failed to chmod IPC socket",s)}h("info",st,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",st,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){h("debug",st,"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=>{S(st,"IPC socket connection error",r)}),e.on("close",()=>{h("debug",st,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{h("warn",st,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){h("warn",st,"IPC message missing required `type` field \u2014 ignored");return}h("debug",st,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as xm}from"http";var Hi,Tm,Cm,Zr,vl=O(()=>{"use strict";le();Hi="healthServer",Tm="127.0.0.1",Cm=7878,Zr=class{constructor(e){this.version=e}version;server=null;startTime=Date.now();async listen(e=Tm,t=Cm){return new Promise((r,s)=>{this.server=xm((i,o)=>this._handleRequest(i,o)),this.server.once("error",i=>{S(Hi,"Health server startup error",i),s(i)}),this.server.listen(t,e,()=>{h("info",Hi,`Health server listening on ${e}:${t}`),r()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",Hi,"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 bl,mkdir as kl}from"node:fs/promises";import{homedir as Rm}from"node:os";import{dirname as Am,join as Sl}from"node:path";function Om(){return es||(es=kl(El,{recursive:!0}).then(()=>{},n=>{throw es=null,n})),es}function ts(n){return n&&n.replace(/-/g,"").slice(0,8)||"unknown"}function Pm(n){return Sl(El,`agent-${ts(n)}.jsonl`)}function Q(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=${ts(n)} kind=${e}: ${i.message}
218
- `);return}let s=Pm(n);Om().then(()=>bl(s,r,{encoding:"utf8"})).catch(i=>{if(i.code==="ENOENT"){let o=Am(s);kl(o,{recursive:!0}).then(()=>bl(s,r,{encoding:"utf8"})).catch(a=>{process.stderr.write(`[agentTrace] append failed agent=${ts(n)} kind=${e}: ${a.message}
219
- `)});return}process.stderr.write(`[agentTrace] append failed agent=${ts(n)} kind=${e}: ${i.message}
220
- `)})}var El,es,Rt=O(()=>{"use strict";El=Sl(Rm(),".mio","logs"),es=null});import{readFileSync as Im,writeFileSync as Nm,existsSync as Mm}from"fs";import{join as Lm}from"path";function xl(){return Lm(pe,"agent-inbox-cursor.json")}function Tl(){let n=xl();if(!Mm(n))return{};try{return JSON.parse(Im(n,"utf-8"))}catch{return{}}}function $m(n){En(),Nm(xl(),JSON.stringify(n,null,2),{mode:384})}function Cl(n,e){return Tl()[`${n}:${e}`]??"0"}function _t(n,e,t){let r=Tl(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,$m(r))}var qi=O(()=>{"use strict";Ye()});import{createServer as Dm}from"http";import{randomBytes as Bm,timingSafeEqual as Um}from"crypto";function Oe(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Wm(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 ns);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function jm(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Um(t,r)}async function xe(n,e,t){let r=new AbortController,s=setTimeout(()=>r.abort(),t);try{return await fetch(n,{...e,signal:r.signal})}finally{clearTimeout(s)}}async function Rl(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??qm,c=i instanceof Set?i:new Set(i),l=Bm(32).toString("hex");async function d(g,y){if(g.method!=="POST"||g.url!=="/act"){y.writeHead(404),y.end();return}let E=g.headers.authorization??"",w=`Bearer ${l}`;if(!jm(E,w)){Oe(y,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let _;try{_=await Wm(g,Hm)}catch(G){if(G instanceof ns){Oe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Oe(y,400,{ok:!1,code:"INVALID_JSON"});return}let k;try{k=JSON.parse(_)}catch{Oe(y,400,{ok:!1,code:"INVALID_JSON"});return}let P=k.action,T=k.payload!=null&&typeof k.payload=="object"?k.payload:{};if(P!=="attachment"&&Buffer.byteLength(_)>Fm){Oe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(P)){Oe(y,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let L=Gm[P];if(!c.has(L)){Oe(y,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let F={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 G=T,Z=null;if(o)try{let ie=o.get(e);ie&&typeof T.context_message_id!="string"&&(G={...T,context_message_id:ie},Z=ie)}catch(ie){S(At,"contextTracker.get threw (non-fatal)",ie)}let ne=typeof T.target=="string"?T.target:null,q=typeof T.parent_message_id=="string"?T.parent_message_id:null,se=typeof T.content=="string"?T.content.slice(0,120):null;h("info",At,"forward send",{agentId:e,target:ne,parent_message_id:q,stamped_context:Z!==null,context_message_id:Z}),Q(e,"outbound",{action:"send",target:ne,parent_message_id:q,context_message_id:Z,context_message_id_short:Z?Z.replace(/-/g,"").slice(0,8):null,content_preview:se,content_bytes:typeof T.content=="string"?T.content.length:0}),await Jm(y,r,F,G,a),y.statusCode<300&&Li(e),Q(e,"outbound_done",{action:"send",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="reply"){let G=typeof T.target=="string"?T.target:null,Z=typeof T.parent_message_id=="string"?T.parent_message_id:null,ne=typeof T.content=="string"?T.content.slice(0,120):null;Q(e,"outbound",{action:"reply",target:G,parent_message_id:Z,parent_message_id_short:Z?Z.replace(/-/g,"").slice(0,8):null,content_preview:ne}),await Ym(y,r,F,T,a),y.statusCode<300&&Li(e),Q(e,"outbound_done",{action:"reply",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="history")await Vm(y,r,F,T,a);else if(P==="task"){let G=typeof T.op=="string"?T.op:null;Q(e,"task",{action:G,task_id:typeof T.task_id=="string"?T.task_id:null,number:typeof T.number=="number"?T.number:null,title:typeof T.title=="string"?T.title.slice(0,200):null,status:typeof T.status=="string"?T.status:null,channel:typeof T.channel=="string"?T.channel:null}),await Km(y,r,F,T,a),Q(e,"task_done",{action:G,status:y.statusCode,duration_ms:Date.now()-J})}else P==="reminder"?await Qm(y,r,F,T,a):P==="action"?await ey(y,r,F,T,a):P==="react"?await ty(y,r,F,T,a):P==="attachment"?await ny(y,r,F,T,a):P==="profile"?await ry(y,r,F,T,a):await sy(y,r,F,e,T,a)}catch(G){S(At,"upstream forwarding error",G);let Z=G instanceof Error&&G.name==="AbortError";Oe(y,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:Z?`upstream timed out after ${a}ms`:String(G)})}}let u=Dm((g,y)=>{d(g,y).catch(E=>{S(At,"unhandled request error",E),y.writeHead(500),y.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((g,y)=>{u.once("error",E=>{S(At,"agent proxy startup error",E),y(E)}),u.listen(0,"127.0.0.1",()=>{let E=u.address(),w=typeof E=="object"&&E?E.port:0;h("info",At,"agent proxy listening",{agentId:e,launchId:t,port:w}),g(w)})})}`,proxyToken:l,close:()=>new Promise(g=>{u.close(()=>{h("info",At,"agent proxy stopped",{agentId:e,launchId:t}),g()})})}}async function Jm(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function Ym(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function Vm(n,e,t,r,s){let i=iy(r),o=await xe(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Te(n,o)}async function Km(n,e,t,r,s){let i=String(r.op??""),o=zm[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_TASK_OP",message:`Unknown task op: ${i}`});return}let a=`${e}/internal/agent-api/tasks/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let l=c.toString(),d=await xe(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Te(n,d)}else{let{op:c,...l}=r,d=await xe(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Te(n,d)}}async function Qm(n,e,t,r,s){let i=String(r.op??""),o=Xm[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_REMINDER_OP",message:`Unknown reminder op: ${i}`});return}let a=`${e}/internal/agent-api/reminders/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let l=c.toString(),d=await xe(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Te(n,d)}else{let{op:c,...l}=r,d=await xe(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Te(n,d)}}async function ey(n,e,t,r,s){let i=String(r.op??""),o=Zm[i];if(!o){Oe(n,400,{ok:!1,code:"UNKNOWN_ACTION_OP",message:`Unknown action op: ${i}`});return}let a=`${e}/internal/agent-api/actions/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let l=c.toString(),d=await xe(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Te(n,d)}else{let{op:c,...l}=r,d=await xe(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Te(n,d)}}async function ty(n,e,t,r,s){let i=await xe(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Te(n,i)}async function ny(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await xe(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Te(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await xe(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Te(n,a);return}Oe(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function ry(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 xe(c,{method:"GET",headers:t},s);await Te(n,l);return}if(i==="update"){let{op:o,...a}=r,c=await xe(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Te(n,c);return}Oe(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function sy(n,e,t,r,s,i){let o=String(s.channel??""),a=Cl(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),l=await xe(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!l.ok){await Te(n,l);return}let d=await l.json(),u=d.messages??[];if(u.length>0){let f=u.reduce((p,g)=>{let y=0n;try{y=BigInt(String(g.seq??"0"))}catch{S(At,"bad seq from upstream",{seq:g.seq}),y=0n}return y>p?y:p},0n);f>0n&&_t(r,o,f.toString())}let m=JSON.stringify(d);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Te(n,e){if(e.ok){let i=await e.text();n.writeHead(e.status,{"Content-Type":"application/json"}),n.end(i);return}let t=await e.text().catch(()=>""),r=e.status>=500?"SERVER_5XX":"UPSTREAM_ERROR",s=t;try{let i=JSON.parse(t);r=i?.error?.code??r,s=i?.error?.message??s}catch{}Oe(n,e.status,{ok:!1,code:r,message:s})}function iy(n){let e=new URLSearchParams;n.channel!==void 0&&e.set("channel",String(n.channel)),n.after_seq!==void 0&&e.set("after_seq",String(n.after_seq)),n.limit!==void 0&&e.set("limit",String(n.limit)),n.around!==void 0&&e.set("around",String(n.around));let t=e.toString();return t?`?${t}`:""}var At,Fm,Hm,qm,Gm,ns,zm,Xm,Zm,Al=O(()=>{"use strict";$i();le();Rt();qi();At="agentProxy",Fm=1024*1024,Hm=12*1024*1024,qm=15e3,Gm={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};ns=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};zm={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"}};Xm={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"}};Zm={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as Ol,writeFile as Gi,chmod as Pl}from"fs/promises";import{existsSync as Il}from"fs";import{join as zn,resolve as oy,dirname as ay}from"path";import{spawnSync as cy}from"child_process";import{fileURLToPath as dy}from"url";function Kn(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Ot(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function ly(n){let e=ay(dy(import.meta.url))+"/../..",t=n?.localTsxPath??oy(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Il(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??uy)();return i||"tsx"}function uy(){let e=cy("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Il(e)?e:null}function Wi(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:ly(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function Nl(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??Wi(),c=zn(r,".mio");await Ol(c,{recursive:!0,mode:493});let l=await Rl({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:d,proxyToken:u}=l;try{let m=Kn(e),f=Kn(t),p=zn(pe,"agent-proxy-tokens",m),g=zn(p,`${f}.token`);await Ol(p,{recursive:!0,mode:448}),await Gi(g,u,{encoding:"utf8",mode:384}),await Pl(g,384);let y=o.join(","),E=fy({execContext:a,proxyUrl:d,tokenFile:g,capabilityStr:y}),w=zn(c,"mio");await Gi(w,E,{encoding:"utf8",mode:493}),await Pl(w,493),await Gi(zn(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let _={...process.env},k=_.PATH??"";return _.PATH=k?`${c}:${k}`:c,delete _.CLAUDECODE,{mioDir:c,spawnEnv:_,proxyHandle:l}}catch(m){throw await l.close().catch(()=>{}),m}}function fy(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${Ot(t)} MIO_AGENT_PROXY_TOKEN_FILE=${Ot(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${Ot(s)}`,o;return e.mode==="npm"?o=`exec ${Ot(e.nodePath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${Ot(e.tsxPath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:o=`exec ${Ot(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
221
- `)}var Ml=O(()=>{"use strict";Ye();Al()});function Ll(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 hy,py,gy,my,yy,_y,$l,Dl=O(()=>{"use strict";hy=`## Role: Product Manager
214
+ `+t)}function qt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,qt),n.emit("wsClientError",o,t,e)}else Bn(t,r,s,i)}});var Ig,Ng,Mg,Lg,$g,Dg,mi,Bg,El=O(()=>{Ig=te(gl(),1),Ng=te(Mr(),1),Mg=te(sn(),1),Lg=te(ii(),1),$g=te(ci(),1),Dg=te(pi(),1),mi=te(Br(),1),Bg=te(Sl(),1)});var xl,Fg,Hg,Fr,gb,yi=O(()=>{On();$t();Xt();Lt();xl=te(He(),1),Fg=(0,xl.default)("engine.io-client:websocket"),Hg=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Fr=class extends dt{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Hg?{}:_r(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(s){return this.emitReserved("error",s)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;Rn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{Fg("websocket closed before onclose event")}s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){typeof this.ws<"u"&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){let e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=wr()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},gb=xe.WebSocket||xe.MozWebSocket});var un,_i=O(()=>{El();yi();un=class extends Fr{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 mi.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 Tl,Un,fn,wi=O(()=>{On();Lt();Xt();Tl=te(He(),1),Un=(0,Tl.default)("engine.io-client:webtransport"),fn=class extends dt{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(e){return this.emitReserved("error",e)}this._transport.closed.then(()=>{Un("transport closed gracefully"),this.onClose()}).catch(e=>{Un("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Za(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=Qa();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){Un("session is closed");return}Un("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{Un("an error occurred while reading: %s",a)})};i();let o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){let r=e[t],s=t===e.length-1;this._writer.write(r).then(()=>{s&&ct(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var vi,bi=O(()=>{Vs();_i();wi();vi={websocket:un,webtransport:fn,polling:tn}});function hn(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=qg.exec(n||""),i={},o=14;for(;o--;)i[Gg[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=Wg(i,i.path),i.queryKey=jg(i,i.query),i}function Wg(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 jg(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var qg,Gg,ki=O(()=>{qg=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Gg=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var Cl,Rl,se,Si,Fn,Gt,Hr,pn,Ei=O(()=>{bi();$t();Hs();ki();Cl=te(Mt(),1);Xt();Lt();Rl=te(He(),1),se=(0,Rl.default)("engine.io-client:socket"),Si=typeof addEventListener=="function"&&typeof removeEventListener=="function",Fn=[];Si&&addEventListener("offline",()=>{se("closing %d connection(s) because the network was lost",Fn.length),Fn.forEach(n=>n())},!1);Gt=class n extends Cl.Emitter{constructor(e,t){if(super(),this.binaryType=tc,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=hn(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=hn(t.host).host);lt(this,t),this.secure=t.secure!=null?t.secure:typeof location<"u"&&location.protocol==="https:",t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||(typeof location<"u"?location.hostname:"localhost"),this.port=t.port||(typeof location<"u"&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(r=>{let s=r.prototype.name;this.transports.push(s),this._transportsByName[s]=r}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),typeof this.opts.query=="string"&&(this.opts.query=ic(this.opts.query)),Si&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(se("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Fn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=nc()),this._open()}createTransport(e){se('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Us,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return se("options: %j",r),new this._transportsByName[e](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){se("setting transport %s",e.name),this.transport&&(se("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){se("socket open"),this.readyState="open",n.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(se('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else se('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();se("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let s=this.writeBuffer[r].data;if(s&&(t+=rc(s)),r>0&&t>this._maxPayload)return se("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return se("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(se("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,ct(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,s){if(typeof t=="function"&&(s=t,t=void 0),typeof r=="function"&&(s=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;let i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),se("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(se("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return se("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(se('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Si&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Fn.indexOf(this._offlineEventListener);r!==-1&&(se("removing listener for the 'offline' event"),Fn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Gt.protocol=Us;Hr=class extends Gt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){se("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){se('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Gt.priorWebsocketSuccess=!1;let s=()=>{r||(se('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(se('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Gt.priorWebsocketSuccess=t.name==="websocket",se('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(se("changing transport and sending upgrade packet"),l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{se('probe transport "%s" failed',e);let m=new Error("probe error");m.transport=t.name,this.emitReserved("upgradeError",m)}}))};function i(){r||(r=!0,l(),t.close(),t=null)}let o=u=>{let m=new Error("probe error: "+u);m.transport=t.name,i(),se('probe transport "%s" failed because of error: %s',e,u),this.emitReserved("upgradeError",m)};function a(){o("transport closed")}function c(){o("socket closed")}function d(u){t&&u.name!==t.name&&(se('"%s" works - aborting "%s"',u.name,t.name),i())}let l=()=>{t.removeListener("open",s),t.removeListener("error",o),t.removeListener("close",a),this.off("close",c),this.off("upgrading",d)};t.once("open",s),t.once("error",o),t.once("close",a),this.once("close",c),this.once("upgrading",d),this._upgrades.indexOf("webtransport")!==-1&&e!=="webtransport"?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){let t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}},pn=class extends Hr{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=>vi[s]).filter(s=>!!s)),super(e,r)}}});var Al=O(()=>{Ws()});var Bb,qr=O(()=>{Ei();Ei();On();bi();$t();ki();Lt();Al();Vs();Js();_i();yi();wi();Bb=pn.protocol});function Il(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)||(Ol("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Ol("parse %s",n),r=hn(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 Pl,Ol,Nl=O(()=>{qr();Pl=te(He(),1),Ol=(0,Pl.default)("socket.io-client:url")});function qn(n){return zg&&(n instanceof ArrayBuffer||Kg(n))||Xg&&n instanceof Blob||Qg&&n instanceof File}function Hn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Hn(n[t]))return!0;return!1}if(qn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Hn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Hn(n[t]))return!0;return!1}var zg,Kg,Ml,Xg,Qg,xi=O(()=>{zg=typeof ArrayBuffer=="function",Kg=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Ml=Object.prototype.toString,Xg=typeof Blob=="function"||typeof Blob<"u"&&Ml.call(Blob)==="[object BlobConstructor]",Qg=typeof File=="function"||typeof File<"u"&&Ml.call(File)==="[object FileConstructor]"});function Ll(n){let e=[],t=n.data,r=n;return r.data=Ti(t,e),r.attachments=e.length,{packet:r,buffers:e}}function Ti(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]=Ti(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]=Ti(n[r],e));return t}return n}function $l(n,e){return n.data=Ci(n.data,e),delete n.attachments,n}function Ci(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]=Ci(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Ci(n[t],e));return n}var Dl=O(()=>{xi()});var Ii={};$e(Ii,{Decoder:()=>Oi,Encoder:()=>Ai,PacketType:()=>j,isPacketValid:()=>nm,protocol:()=>Hl});function Zg(n){return typeof n=="string"}function em(n){return n===void 0||ql(n)}function Gr(n){return Object.prototype.toString.call(n)==="[object Object]"}function tm(n,e){switch(n){case j.CONNECT:return e===void 0||Gr(e);case j.DISCONNECT:return e===void 0;case j.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Fl.indexOf(e[0])===-1);case j.ACK:return Array.isArray(e);case j.CONNECT_ERROR:return typeof e=="string"||Gr(e);default:return!1}}function nm(n){return Zg(n.nsp)&&em(n.id)&&tm(n.type,n.data)}var Bl,Ul,Ri,Fl,Hl,j,Ai,Oi,Pi,ql,Wr=O(()=>{Bl=te(Mt(),1);Dl();xi();Ul=te(He(),1),Ri=(0,Ul.default)("socket.io-parser"),Fl=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],Hl=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={}));Ai=class{constructor(e){this.replacer=e}encode(e){return Ri("encoding packet %j",e),(e.type===j.EVENT||e.type===j.ACK)&&Hn(e)?this.encodeAsBinary({type:e.type===j.EVENT?j.BINARY_EVENT:j.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===j.BINARY_EVENT||e.type===j.BINARY_ACK)&&(t+=e.attachments+"-"),e.nsp&&e.nsp!=="/"&&(t+=e.nsp+","),e.id!=null&&(t+=e.id),e.data!=null&&(t+=JSON.stringify(e.data,this.replacer)),Ri("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=Ll(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},Oi=class n extends Bl.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 Pi(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(!ql(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 Ri("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 Gr(t);case j.DISCONNECT:return t===void 0;case j.CONNECT_ERROR:return typeof t=="string"||Gr(t);case j.EVENT:case j.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Fl.indexOf(t[0])===-1);case j.ACK:case j.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Pi=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=$l(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};ql=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function Be(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Ni=O(()=>{});var Gl,Wl,fe,rm,gn,Mi=O(()=>{Wr();Ni();Gl=te(Mt(),1),Wl=te(He(),1),fe=(0,Wl.default)("socket.io-client:socket"),rm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),gn=class extends Gl.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=[Be(e,"open",this.onopen.bind(this)),Be(e,"packet",this.onpacket.bind(this)),Be(e,"error",this.onerror.bind(this)),Be(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(rm.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let o={type:j.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let l=this.ids++;fe("emitting packet with ack id %d",l);let u=t.pop();this._registerAckCallback(l,u),o.id=l}let a=(s=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||s===void 0?void 0:s.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a?fe("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&&(fe("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));fe("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]?fe("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(fe("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(fe("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(fe("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){fe("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,fe("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(){fe("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){fe("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||[];fe("emitting event %j",t),e.id!=null&&(fe("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,fe("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"){fe("bad ack %s",e.id);return}delete this.acks[e.id],fe("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){fe("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(){fe("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&&(fe("performing disconnect (%s)",this.nsp),this.packet({type:j.DISCONNECT})),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){let t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){let t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){let t=this._anyOutgoingListeners.slice();for(let r of t)r.apply(this,e.data)}}}});function Wt(n){n=n||{},this.ms=n.min||100,this.max=n.max||1e4,this.factor=n.factor||2,this.jitter=n.jitter>0&&n.jitter<=1?n.jitter:0,this.attempts=0}var jl=O(()=>{Wt.prototype.duration=function(){var n=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var e=Math.random(),t=Math.floor(e*this.jitter*n);n=(Math.floor(e*10)&1)==0?n-t:n+t}return Math.min(n,this.max)|0};Wt.prototype.reset=function(){this.attempts=0};Wt.prototype.setMin=function(n){this.ms=n};Wt.prototype.setMax=function(n){this.max=n};Wt.prototype.setJitter=function(n){this.jitter=n}});var Jl,Yl,we,mn,Vl=O(()=>{qr();Mi();Wr();Ni();jl();Jl=te(Mt(),1),Yl=te(He(),1),we=(0,Yl.default)("socket.io-client:manager"),mn=class extends Jl.Emitter{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&typeof e=="object"&&(t=e,e=void 0),t=t||{},t.path=t.path||"/socket.io",this.opts=t,lt(this,t),this.reconnection(t.reconnection!==!1),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor((r=t.randomizationFactor)!==null&&r!==void 0?r:.5),this.backoff=new Wt({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||Ii;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(we("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;we("opening %s",this.uri),this.engine=new pn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Be(t,"open",function(){r.onopen(),e&&e()}),i=a=>{we("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Be(t,"error",i);if(this._timeout!==!1){let a=this._timeout;we("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{we("connect attempt timed out after %d",a),s(),i(new Error("timeout")),t.close()},a);this.opts.autoUnref&&c.unref(),this.subs.push(()=>{this.clearTimeoutFn(c)})}return this.subs.push(s),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){we("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Be(e,"ping",this.onping.bind(this)),Be(e,"data",this.ondata.bind(this)),Be(e,"error",this.onerror.bind(this)),Be(e,"close",this.onclose.bind(this)),Be(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(t){this.onclose("parse error",t)}}ondecoded(e){ct(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){we("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new gn(this,e,t),this.nsps[e]=r),r}_destroy(e){let t=Object.keys(this.nsps);for(let r of t)if(this.nsps[r].active){we("socket %s is still active, skipping close",r);return}this._close()}_packet(e){we("writing packet %j",e);let t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){we("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){we("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;we("closed due to %s",e),this.cleanup(),(r=this.engine)===null||r===void 0||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;let e=this;if(this.backoff.attempts>=this._reconnectionAttempts)we("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();we("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(we("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(we("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(we("reconnect success"),e.onreconnect())}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){let e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}});function Wn(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=Il(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Gn[s]&&i in Gn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(zl("ignoring socket cache for %s",r),c=new mn(r,e)):(Gn[s]||(zl("new io instance for %s",r),Gn[s]=new mn(r,e)),c=Gn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var Kl,zl,Gn,Xl=O(()=>{Nl();Vl();Mi();Kl=te(He(),1);Wr();qr();zl=(0,Kl.default)("socket.io-client"),Gn={};Object.assign(Wn,{Manager:mn,Socket:gn,io:Wn,connect:Wn})});var rt,sm,jr,Ql=O(()=>{"use strict";Xl();de();rt="wsClient",sm=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),jr=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",rt,"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=>{S(rt,"catch-up handler threw",o)})}}destroy(){this.destroyed=!0,this.reconnectTimer&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null),this.socket&&(this.socket.removeAllListeners(),this.socket.disconnect(),this.socket=null)}_connect(){if(this.destroyed||this.authFailed)return;let e=Wn(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",rt,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{S(rt,"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=>{S(rt,"event handler threw",i)})});for(let t of sm)e.on(t,r=>{h("error",rt,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",rt,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",rt,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{S(rt,"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",rt,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var Xe,Jr,Zl=O(()=>{"use strict";Yt();fa();pr();Ql();de();Xe="serverGateway",Jr=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=kt(),h("info",Xe,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new jr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>ua(t,r)});let e=da();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",Xe,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",Xe,`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",Xe,"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",Xe,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return pa(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await ga(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await ma(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await ya(this.config.server_url,e,t,this._getToken())}async getAction(e){return wa(this.config.server_url,e,this._getToken())}async getApproval(e){return va(this.config.server_url,e,this._getToken())}async fireAction(e,t){return ba(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await ka(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return Sa(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return zt(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return Ea(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return Ta(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return Ca(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return xa(this.config.server_url,e,this._getToken())}async getTasks(e,t){return Ra(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return Aa(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return Oa(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return Pa(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return Ia(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Na(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return Ma(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await Da(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await La(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 $a(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return Ba(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Ua(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",Xe,"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 _a(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",Xe,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",Xe,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){S(Xe,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=kt(),t=await ha(this.config.server_url,e);lr(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",Xe,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){S(Xe,"token refresh failed",e)}}_getToken(){return this.token||(this.token=kt()),this.token}}});import{execFile as im}from"node:child_process";import{promisify as om}from"node:util";import{readFileSync as am,readdirSync as Yr,statSync as Li,openSync as cm,readSync as lm,closeSync as dm}from"node:fs";import{join as jt}from"node:path";import{homedir as ed}from"node:os";async function um(){try{if(process.platform==="darwin"){let{stdout:n}=await td("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=am(jt(ed(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function fm(){let n=await um();if(!n)return null;try{let{stdout:e}=await td("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 hm(n,e){let t=[];try{for(let r of Yr(n).sort().reverse().slice(0,2)){let s=jt(n,r);for(let i of Yr(s).sort().reverse().slice(0,2)){let o=jt(s,i);for(let a of Yr(o).sort().reverse().slice(0,7)){let c=jt(o,a);for(let d of Yr(c)){if(!d.endsWith(".jsonl"))continue;let l=jt(c,d);try{t.push({path:l,mtime:Li(l).mtimeMs})}catch{}}}if(t.length>=e*4)break}if(t.length>=e*4)break}}catch{}return t.sort((r,s)=>s.mtime-r.mtime).slice(0,e).map(r=>r.path)}function pm(n,e){let t=cm(n,"r");try{let r=Li(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return lm(t,i,0,s,r-s),i.toString("utf-8")}finally{dm(t)}}function gm(){let n=process.env.CODEX_HOME??jt(ed(),".codex");for(let e of hm(jt(n,"sessions"),5))try{let t=pm(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(Li(e).mtimeMs).toISOString()}}catch{}}catch{}return null}async function nd(){let[n,e]=await Promise.all([fm(),Promise.resolve().then(gm)]);return{sampled_at:new Date().toISOString(),claude:n,codex:e}}var td,rd=O(()=>{"use strict";td=om(im)});function od(n,e,t){if(t){let r=`${n}:${t}`;if(jn.has(r))return;if(jn.set(r,Date.now()),jn.size>500){let s=Date.now()-36e5;for(let[i,o]of jn)o<s&&jn.delete(i)}}Jn.set(`${n}:${e}`,Date.now())}function $i(n){id.set(n,Date.now());let e=`${n}:`;for(let t of Jn.keys())t.startsWith(e)&&Jn.delete(t)}function ad(n,e){let t=`${n}:${e}`,r=Jn.get(t);if(r===void 0||(Jn.delete(t),Date.now()-r>_m))return!1;let s=id.get(n)??0;if(Date.now()-s<mm)return!1;let i=sd.get(e)??0;return Date.now()-i<ym?!1:(sd.set(e,Date.now()),!0)}var Jn,sd,id,jn,mm,ym,_m,Di=O(()=>{"use strict";Jn=new Map,sd=new Map,id=new Map,jn=new Map,mm=180*1e3,ym=600*1e3,_m=1800*1e3});var Ct,cd,Vr,ld=O(()=>{"use strict";de();Ct="sessionManager",cd=3e4,Vr=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},cd),h("info",Ct,`Heartbeat timer started (every ${cd/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=>{S(Ct,`Failed to mark session ${t.sessionId} disconnected`,r)}))),h("info",Ct,`SessionManager stopped, ${e.length} sessions marked disconnected`)}async createSession(e){let r={sessionId:(await this.gateway.createSession(e)).id,workroomId:e,status:"idle"};return this.sessions.set(r.sessionId,r),h("info",Ct,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){h("warn",Ct,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,h("info",Ct,"Session status updated",{sessionId:e,status:t})}getSession(e){return this.sessions.get(e)}getAllSessions(){return[...this.sessions.values()]}async _sendHeartbeats(){let e=[...this.sessions.values()].filter(t=>t.status!=="completed"&&t.status!=="failed"&&t.status!=="disconnected");await Promise.all(e.map(t=>this.gateway.sessionHeartbeat(t.sessionId).catch(r=>{S(Ct,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&h("debug",Ct,`Sent ${e.length} heartbeat(s)`)}}});var mt,zr,dd=O(()=>{"use strict";de();mt="workroomCoordinator",zr=class{constructor(e,t){this.sessionManager=e;this.actionGate=t}sessionManager;actionGate;workroomRegistry=new Map;shuttingDown=!1;async openWorkroom(e){if(this.shuttingDown)return h("warn",mt,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return h("info",mt,"openWorkroom: workroom already open \u2014 reusing session",{workroomId:e,sessionId:t.sessionId}),t;let r;try{r=await this.sessionManager.createSession(e)}catch(s){return S(mt,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return S(mt,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{S(mt,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),h("info",mt,"workroom opened successfully",{workroomId:e,sessionId:r.sessionId,openCount:this.workroomRegistry.size}),r}shutdownAll(){this.shuttingDown=!0;for(let e of this.workroomRegistry.keys())try{this.actionGate.deregisterWorkroom(e),h("info",mt,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){S(mt,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),h("info",mt,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as Ui,unlink as wm,readdir as vm,stat as bm}from"fs/promises";import{join as Kr}from"path";import{randomBytes as Fi}from"crypto";async function fd(n,e){let t=Fi(8).toString("hex"),r=Kr(Nt,`action-${n}-${t}${ud}`),s;try{s=await Ui(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return h("info",yt,"secret file written",{actionId:n,filePath:r}),r}async function Yn(n){try{await wm(n),h("info",yt,"secret file deleted",{filePath:n})}catch(e){if(Bi(e))return;S(yt,"failed to delete secret file (best-effort)",e)}}async function hd(){let n;try{n=await vm(Nt)}catch(s){if(Bi(s))return;S(yt,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(ud)),r=0;for(let s of t){let i=Kr(Nt,s);try{let o=await bm(i),a=e-o.mtimeMs;a>=km&&(await Yn(i),r++,h("info",yt,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(Bi(o))continue;S(yt,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&h("info",yt,"TTL scan complete",{scanned:t.length,purged:r})}async function pd(n){let e=Date.now(),t=Fi(4).toString("hex"),r=Kr(Nt,`drain-evidence-${e}-${t}.json`),s;try{s=await Ui(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",yt,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function gd(n){let e=Date.now(),t=Fi(4).toString("hex"),r=Kr(Nt,`response-lost-${e}-${t}.json`),s;try{s=await Ui(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",yt,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function Bi(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var yt,km,ud,Xr=O(()=>{"use strict";Ye();de();yt="secretManager",km=600*1e3,ud=".secret"});import{spawn as Sm}from"child_process";import{stat as Em}from"fs/promises";async function md(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return h("warn",Jt,"no enabled runtime found for kind",{kind:n.kind,actionId:n.actionId,availableKinds:n.runtimes.map(i=>i.kind)}),{ok:!1,reason_code:"RUNTIME_NOT_FOUND"};try{await Em(e.path)}catch{return h("warn",Jt,"runtime binary not accessible",{kind:n.kind,actionId:n.actionId}),{ok:!1,reason_code:"RUNTIME_NOT_FOUND"}}let t={PATH:process.env.PATH,HOME:process.env.HOME,USER:process.env.USER,TMPDIR:process.env.TMPDIR,LANG:process.env.LANG,MIO_ACTION_ID:n.actionId,MIO_SESSION_ID:n.sessionId,MIO_WORKROOM_ID:n.workroomId,MIO_ACTION_KIND:n.kind,MIO_IPC_SOCKET:n.ipcSocketPath,...n.serverUrl?{MIO_SERVER_URL:n.serverUrl}:{},MIO_RUNTIME_MODE:n.mode??"controlled-delegated",...process.env.MIO_CLAUDE_CONFIG_DIR?{MIO_CLAUDE_CONFIG_DIR:process.env.MIO_CLAUDE_CONFIG_DIR}:{}},r;if(n.secretContent)try{r=await fd(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return S(Jt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=Sm(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return S(Jt,"spawn failed",i),r&&Yn(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{h("info",Jt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&Yn(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{S(Jt,"subprocess error after spawn",i),r&&Yn(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),h("info",Jt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var Jt,yd=O(()=>{"use strict";de();Xr();Jt="runtimeAdapter"});var H,_d,Vn,wd,zn,vd,xm,Qr,Hi=O(()=>{"use strict";pr();de();yd();Xr();H="actionGate",_d=new Set(["proposed","approved"]),Vn=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),wd="irreversible_no_abort",zn=new Set(["transmission_complete","succeeded","canceled","failed"]),vd=15,xm=8e3,Qr=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",H,"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",H,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,h("info",H,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=xm){if(this.inFlightIrreversible.size===0){h("info",H,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return h("warn",H,"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);S(H,"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 pd({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",H,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){S(H,"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)&&zn.has(r)&&this.gateway.getAction(t).then(s=>{zn.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):h("warn",H,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{S(H,"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",H,"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",H,"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",H,"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=>{zn.has(s.status)?(h("info",H,"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",H,"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=>{S(H,"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){S(H,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){h("info",H,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){h("warn",H,"action.created: missing action_id in payload \u2014 ignoring");return}h("info",H,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(Vn.has(r.status)){h("info",H,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!_d.has(r.status)){h("info",H,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===wd?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",H,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&h("info",H,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),h("info",H,"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",H,"approval.decided: missing required fields \u2014 ignoring");return}if(h("info",H,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),h("info",H,"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),Vn.has(i.status)){h("info",H,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!_d.has(i.status)){h("warn",H,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){h("warn",H,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){h("warn",H,"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",H,"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&&Vn.has(r),a=i&&zn.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&Vn.has(c.status)&&(this.pendingApproval.delete(t),h("info",H,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&zn.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",H,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let l=await this.gateway.fireAction(r,t);h("info",H,"action fired",{actionId:r,fired_at:l.fired_at}),a=l.action_token,o=!0}catch(l){if(l instanceof xn&&l.isDefinitiveRejection){S(H,`fire definitively rejected (${l.statusCode} ${l.errorCode}) \u2014 re-querying before cancel`,l);let m=await this.gateway.getAction(r).catch(()=>null);if(!m||Vn.has(m.status)){h("info",H,"action already in non-cancelable state after rejected fire \u2014 skipping cancel (concurrent winner?)",{actionId:r,currentStatus:m?.status});return}await this.gateway.cancelAction(r).catch(f=>{S(H,"cancel after rejected fire also failed",f)});return}S(H,"fire failed with uncertain error \u2014 reconciling action state",l);let u=await this.gateway.getAction(r).catch(()=>null);if(u?.status==="fired"){h("warn",H,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let m=u.fired_at??new Date().toISOString();await gd({schema_version:1,reason:"fire_response_lost_token_unrecoverable",action_id:r,workroom_id:i,session_id:s,fired_at:m,operator_note:"The fire HTTP response was lost before the action_token was received. The raw token is unrecoverable (server stores only hash). The subprocess was NOT spawned. Verify action status on the server manually.",server_todo:'Server reconcile endpoint implemented (Phase 5C). POST /api/v1/actions/:id/reconcile with { reason: "fire_response_lost_token_unrecoverable", evidence_id: "<this-file-uuid>" }. Auth: machine_token bearer. Remove this file after reconcile confirms needs_human status.'}).catch(f=>{S(H,"failed to write response-lost evidence (CRITICAL)",f)});return}else{h("warn",H,"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===wd;c&&this._registerInFlight(e);let d=await md({actionId:r,sessionId:s,workroomId:i,kind:e.kind,reversibility:e.reversibility,runtimes:this.gateConfig.runtimes,ipcSocketPath:this.gateConfig.ipcSocketPath,secretContent:a,serverUrl:this.gateConfig.serverUrl,onSubprocessExit:c?(l,u)=>this._onSubprocessExitForDrain(r,l,u):void 0});d.ok||(h("warn",H,"spawn returned not-ok",{actionId:r,reason_code:d.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as Tm}from"net";import{chmod as Cm}from"fs/promises";var st,Zr,bd=O(()=>{"use strict";de();st="ipcServer",Zr=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=Tm(s=>{this._handleConnection(s)}),this.server.once("error",s=>{S(st,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Cm(e,384)}catch(s){S(st,"Failed to chmod IPC socket",s)}h("info",st,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",st,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){h("debug",st,"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=>{S(st,"IPC socket connection error",r)}),e.on("close",()=>{h("debug",st,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{h("warn",st,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){h("warn",st,"IPC message missing required `type` field \u2014 ignored");return}h("debug",st,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as Rm}from"http";var qi,Am,Om,es,kd=O(()=>{"use strict";de();qi="healthServer",Am="127.0.0.1",Om=7878,es=class{constructor(e){this.version=e}version;server=null;startTime=Date.now();async listen(e=Am,t=Om){return new Promise((r,s)=>{this.server=Rm((i,o)=>this._handleRequest(i,o)),this.server.once("error",i=>{S(qi,"Health server startup error",i),s(i)}),this.server.listen(t,e,()=>{h("info",qi,`Health server listening on ${e}:${t}`),r()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",qi,"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 Sd,mkdir as Ed}from"node:fs/promises";import{homedir as Pm}from"node:os";import{dirname as Im,join as xd}from"node:path";function Nm(){return ts||(ts=Ed(Td,{recursive:!0}).then(()=>{},n=>{throw ts=null,n})),ts}function ns(n){return n&&n.replace(/-/g,"").slice(0,8)||"unknown"}function Mm(n){return xd(Td,`agent-${ns(n)}.jsonl`)}function Q(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=${ns(n)} kind=${e}: ${i.message}
218
+ `);return}let s=Mm(n);Nm().then(()=>Sd(s,r,{encoding:"utf8"})).catch(i=>{if(i.code==="ENOENT"){let o=Im(s);Ed(o,{recursive:!0}).then(()=>Sd(s,r,{encoding:"utf8"})).catch(a=>{process.stderr.write(`[agentTrace] append failed agent=${ns(n)} kind=${e}: ${a.message}
219
+ `)});return}process.stderr.write(`[agentTrace] append failed agent=${ns(n)} kind=${e}: ${i.message}
220
+ `)})}var Td,ts,Rt=O(()=>{"use strict";Td=xd(Pm(),".mio","logs"),ts=null});import{readFileSync as Lm,writeFileSync as $m,existsSync as Dm}from"fs";import{join as Bm}from"path";function Cd(){return Bm(pe,"agent-inbox-cursor.json")}function Rd(){let n=Cd();if(!Dm(n))return{};try{return JSON.parse(Lm(n,"utf-8"))}catch{return{}}}function Um(n){En(),$m(Cd(),JSON.stringify(n,null,2),{mode:384})}function Ad(n,e){return Rd()[`${n}:${e}`]??"0"}function _t(n,e,t){let r=Rd(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,Um(r))}var Gi=O(()=>{"use strict";Ye()});import{createServer as Fm}from"http";import{randomBytes as Hm,timingSafeEqual as qm}from"crypto";function Pe(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Ym(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 rs);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function Vm(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:qm(t,r)}async function Te(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 Od(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??jm,c=i instanceof Set?i:new Set(i),d=Hm(32).toString("hex");async function l(g,y){if(g.method!=="POST"||g.url!=="/act"){y.writeHead(404),y.end();return}let E=g.headers.authorization??"",w=`Bearer ${d}`;if(!Vm(E,w)){Pe(y,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let _;try{_=await Ym(g,Wm)}catch(G){if(G instanceof rs){Pe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Pe(y,400,{ok:!1,code:"INVALID_JSON"});return}let k;try{k=JSON.parse(_)}catch{Pe(y,400,{ok:!1,code:"INVALID_JSON"});return}let P=k.action,T=k.payload!=null&&typeof k.payload=="object"?k.payload:{};if(P!=="attachment"&&Buffer.byteLength(_)>Gm){Pe(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(P)){Pe(y,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let L=Jm[P];if(!c.has(L)){Pe(y,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let F={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 G=T,Z=null;if(o)try{let oe=o.get(e);oe&&typeof T.context_message_id!="string"&&(G={...T,context_message_id:oe},Z=oe)}catch(oe){S(At,"contextTracker.get threw (non-fatal)",oe)}let ne=typeof T.target=="string"?T.target:null,q=typeof T.parent_message_id=="string"?T.parent_message_id:null,ie=typeof T.content=="string"?T.content.slice(0,120):null;h("info",At,"forward send",{agentId:e,target:ne,parent_message_id:q,stamped_context:Z!==null,context_message_id:Z}),Q(e,"outbound",{action:"send",target:ne,parent_message_id:q,context_message_id:Z,context_message_id_short:Z?Z.replace(/-/g,"").slice(0,8):null,content_preview:ie,content_bytes:typeof T.content=="string"?T.content.length:0}),await zm(y,r,F,G,a),y.statusCode<300&&$i(e),Q(e,"outbound_done",{action:"send",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="reply"){let G=typeof T.target=="string"?T.target:null,Z=typeof T.parent_message_id=="string"?T.parent_message_id:null,ne=typeof T.content=="string"?T.content.slice(0,120):null;Q(e,"outbound",{action:"reply",target:G,parent_message_id:Z,parent_message_id_short:Z?Z.replace(/-/g,"").slice(0,8):null,content_preview:ne}),await Km(y,r,F,T,a),y.statusCode<300&&$i(e),Q(e,"outbound_done",{action:"reply",status:y.statusCode,duration_ms:Date.now()-J})}else if(P==="history")await Xm(y,r,F,T,a);else if(P==="task"){let G=typeof T.op=="string"?T.op:null;Q(e,"task",{action:G,task_id:typeof T.task_id=="string"?T.task_id:null,number:typeof T.number=="number"?T.number:null,title:typeof T.title=="string"?T.title.slice(0,200):null,status:typeof T.status=="string"?T.status:null,channel:typeof T.channel=="string"?T.channel:null}),await Zm(y,r,F,T,a),Q(e,"task_done",{action:G,status:y.statusCode,duration_ms:Date.now()-J})}else P==="reminder"?await ty(y,r,F,T,a):P==="action"?await ry(y,r,F,T,a):P==="react"?await sy(y,r,F,T,a):P==="attachment"?await iy(y,r,F,T,a):P==="profile"?await oy(y,r,F,T,a):await ay(y,r,F,e,T,a)}catch(G){S(At,"upstream forwarding error",G);let Z=G instanceof Error&&G.name==="AbortError";Pe(y,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:Z?`upstream timed out after ${a}ms`:String(G)})}}let u=Fm((g,y)=>{l(g,y).catch(E=>{S(At,"unhandled request error",E),y.writeHead(500),y.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((g,y)=>{u.once("error",E=>{S(At,"agent proxy startup error",E),y(E)}),u.listen(0,"127.0.0.1",()=>{let E=u.address(),w=typeof E=="object"&&E?E.port:0;h("info",At,"agent proxy listening",{agentId:e,launchId:t,port:w}),g(w)})})}`,proxyToken:d,close:()=>new Promise(g=>{u.close(()=>{h("info",At,"agent proxy stopped",{agentId:e,launchId:t}),g()})})}}async function zm(n,e,t,r,s){let i=await Te(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ce(n,i)}async function Km(n,e,t,r,s){let i=await Te(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ce(n,i)}async function Xm(n,e,t,r,s){let i=cy(r),o=await Te(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Ce(n,o)}async function Zm(n,e,t,r,s){let i=String(r.op??""),o=Qm[i];if(!o){Pe(n,400,{ok:!1,code:"UNKNOWN_TASK_OP",message:`Unknown task op: ${i}`});return}let a=`${e}/internal/agent-api/tasks/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await Te(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Ce(n,l)}else{let{op:c,...d}=r,l=await Te(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Ce(n,l)}}async function ty(n,e,t,r,s){let i=String(r.op??""),o=ey[i];if(!o){Pe(n,400,{ok:!1,code:"UNKNOWN_REMINDER_OP",message:`Unknown reminder op: ${i}`});return}let a=`${e}/internal/agent-api/reminders/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await Te(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Ce(n,l)}else{let{op:c,...d}=r,l=await Te(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Ce(n,l)}}async function ry(n,e,t,r,s){let i=String(r.op??""),o=ny[i];if(!o){Pe(n,400,{ok:!1,code:"UNKNOWN_ACTION_OP",message:`Unknown action op: ${i}`});return}let a=`${e}/internal/agent-api/actions/${o.path}`;if(o.method==="GET"){let c=new URLSearchParams;for(let[u,m]of Object.entries(r))u!=="op"&&m!==void 0&&c.set(u,String(m));let d=c.toString(),l=await Te(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Ce(n,l)}else{let{op:c,...d}=r,l=await Te(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Ce(n,l)}}async function sy(n,e,t,r,s){let i=await Te(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ce(n,i)}async function iy(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await Te(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Ce(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await Te(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Ce(n,a);return}Pe(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function oy(n,e,t,r,s){let i=String(r.op??"");if(i==="show"){let o=`${e}/internal/agent-api/profile`,a=r.handle,c=a!==void 0?`${o}?handle=${encodeURIComponent(String(a))}`:o,d=await Te(c,{method:"GET",headers:t},s);await Ce(n,d);return}if(i==="update"){let{op:o,...a}=r,c=await Te(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Ce(n,c);return}Pe(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function ay(n,e,t,r,s,i){let o=String(s.channel??""),a=Ad(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),d=await Te(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!d.ok){await Ce(n,d);return}let l=await d.json(),u=l.messages??[];if(u.length>0){let f=u.reduce((p,g)=>{let y=0n;try{y=BigInt(String(g.seq??"0"))}catch{S(At,"bad seq from upstream",{seq:g.seq}),y=0n}return y>p?y:p},0n);f>0n&&_t(r,o,f.toString())}let m=JSON.stringify(l);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Ce(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{}Pe(n,e.status,{ok:!1,code:r,message:s})}function cy(n){let e=new URLSearchParams;n.channel!==void 0&&e.set("channel",String(n.channel)),n.after_seq!==void 0&&e.set("after_seq",String(n.after_seq)),n.limit!==void 0&&e.set("limit",String(n.limit)),n.around!==void 0&&e.set("around",String(n.around));let t=e.toString();return t?`?${t}`:""}var At,Gm,Wm,jm,Jm,rs,Qm,ey,ny,Pd=O(()=>{"use strict";Di();de();Rt();Gi();At="agentProxy",Gm=1024*1024,Wm=12*1024*1024,jm=15e3,Jm={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};rs=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};Qm={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"}};ey={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"}};ny={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as Id,writeFile as Wi,chmod as Nd}from"fs/promises";import{existsSync as Md}from"fs";import{join as Kn,resolve as ly,dirname as dy}from"path";import{spawnSync as uy}from"child_process";import{fileURLToPath as fy}from"url";function Xn(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Ot(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function hy(n){let e=dy(fy(import.meta.url))+"/../..",t=n?.localTsxPath??ly(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Md(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??py)();return i||"tsx"}function py(){let e=uy("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Md(e)?e:null}function ji(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:hy(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function Ld(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??ji(),c=Kn(r,".mio");await Id(c,{recursive:!0,mode:493});let d=await Od({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:l,proxyToken:u}=d;try{let m=Xn(e),f=Xn(t),p=Kn(pe,"agent-proxy-tokens",m),g=Kn(p,`${f}.token`);await Id(p,{recursive:!0,mode:448}),await Wi(g,u,{encoding:"utf8",mode:384}),await Nd(g,384);let y=o.join(","),E=gy({execContext:a,proxyUrl:l,tokenFile:g,capabilityStr:y}),w=Kn(c,"mio");await Wi(w,E,{encoding:"utf8",mode:493}),await Nd(w,493),await Wi(Kn(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let _={...process.env},k=_.PATH??"";return _.PATH=k?`${c}:${k}`:c,delete _.CLAUDECODE,{mioDir:c,spawnEnv:_,proxyHandle:d}}catch(m){throw await d.close().catch(()=>{}),m}}function gy(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${Ot(t)} MIO_AGENT_PROXY_TOKEN_FILE=${Ot(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${Ot(s)}`,o;return e.mode==="npm"?o=`exec ${Ot(e.nodePath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${Ot(e.tsxPath)} ${Ot(e.cliEntryPath)} agentcli "$@"`:o=`exec ${Ot(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
221
+ `)}var $d=O(()=>{"use strict";Ye();Pd()});function Dd(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 my,yy,_y,wy,vy,by,Bd,Ud=O(()=>{"use strict";my=`## Role: Product Manager
222
222
 
223
223
  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
224
 
@@ -253,7 +253,7 @@ Deliberative on scope, decisive on next step. Default to "let's get one concrete
253
253
  - Bundle everything into one giant announcement. One concrete deliverable per message = one task.
254
254
 
255
255
  ### 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.`,py=`## Role: Engineer
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.`,yy=`## Role: Engineer
257
257
 
258
258
  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
259
 
@@ -287,7 +287,7 @@ Pragmatic. Prefer the boring correct solution. When two approaches are roughly e
287
287
  - Apologise for limitations. Just state what's done and what's left.
288
288
 
289
289
  ### 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.`,gy=`## Role: Designer
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.`,_y=`## Role: Designer
291
291
 
292
292
  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
293
 
@@ -320,7 +320,7 @@ Reference-driven. When in doubt, point to a precedent \u2014 either in this prod
320
320
  - Design the happy path only.
321
321
 
322
322
  ### 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.`,my=`## Role: Researcher
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.`,wy=`## Role: Researcher
324
324
 
325
325
  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
326
 
@@ -353,7 +353,7 @@ Evidence-led. Form an opinion only after you've seen the data; revise the opinio
353
353
  - Recommend an action without separating it from the evidence ("the data shows X; my read is therefore Y").
354
354
 
355
355
  ### 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.`,yy=`## Role: Ops / SRE
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.`,vy=`## Role: Ops / SRE
357
357
 
358
358
  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
359
 
@@ -386,7 +386,7 @@ Cautious by default \u2014 production systems are real. Move faster on reversibl
386
386
  - Treat a fix as done until you've watched it stay healthy for at least one cycle.
387
387
 
388
388
  ### 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.`,_y=`## Role: Generalist
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.`,by=`## Role: Generalist
390
390
 
391
391
  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
392
 
@@ -417,12 +417,12 @@ Take initiative on small, reversible things. Escalate to a human or specialist f
417
417
  - Stretch one request into a sprawling project. Stay scoped.
418
418
 
419
419
  ### Posting cadence
420
- Match the cadence of whoever you're talking to. When in doubt: send each logical step as its own short message.`,$l={product_manager:hy,engineer:py,designer:gy,researcher:my,ops:yy,general:_y}});function Cy(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 Ry(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 ${Cy(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(`
420
+ Match the cadence of whoever you're talking to. When in doubt: send each logical step as its own short message.`,Bd={product_manager:my,engineer:yy,designer:_y,researcher:wy,ops:vy,general:by}});function Oy(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 Py(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 ${Oy(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
421
  `);return`${e.channelName?`## In #${e.channelName} right now`:"## In this channel right now"}
422
422
 
423
423
  ${r}
424
424
 
425
- For teammates in other channels, load the \`mio-team\` skill.`}function Bl(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??Ll(r,`${i??""} ${s}`),m=$l[u],f=s&&s.trim()?`## Additional context from your operator
425
+ For teammates in other channels, load the \`mio-team\` skill.`}function Fd(n){let{agentId:e,handle:t,displayName:r,description:s,role:i,serverId:o,computer:a,hostname:c,os:d,workspace:l}=n,u=n.presetRole??Dd(r,`${i??""} ${s}`),m=Bd[u],f=s&&s.trim()?`## Additional context from your operator
426
426
 
427
427
  ${s.trim()}`:"",p=`## Runtime context
428
428
 
@@ -434,83 +434,83 @@ This is authoritative \u2014 do NOT infer your identity, host, or workspace from
434
434
  - Server ID: ${o}
435
435
  - Computer: ${a}
436
436
  - Hostname: ${c}
437
- - OS: ${l}
438
- - Workspace: ${d}
437
+ - OS: ${d}
438
+ - Workspace: ${l}
439
439
 
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\`.`,y=Ry(n),E=500,w=n.persona?n.persona.trim():"",_=w.length>E?w.slice(0,E).replace(/\s+\S*$/,"")+"\u2026":w,k=_.length>0?`## What I've learned (from past interactions)
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\`.`,y=Py(n),E=500,w=n.persona?n.persona.trim():"",_=w.length>E?w.slice(0,E).replace(/\s+\S*$/,"")+"\u2026":w,k=_.length>0?`## What I've learned (from past interactions)
441
441
 
442
- ${_}`:"";return[g,wy,by,ky,Sy,m,f,p,y,k,Ty,Ey,n.runtime==="codex"?xy:"",vy].filter(T=>T&&T.length>0).join(`
442
+ ${_}`:"";return[g,ky,Ey,xy,Ty,m,f,p,y,k,Ay,Cy,n.runtime==="codex"?Ry:"",Sy].filter(T=>T&&T.length>0).join(`
443
443
 
444
444
  `)+`
445
- `}var wy,vy,by,ky,Sy,Ey,xy,Ty,Ul=O(()=>{"use strict";Dl();wy='## 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.',vy='## Reminder \u2014 hard constraints (reinforced)\n\nBefore you send anything to a human, check:\n\n- Are you about to paste a `mio` command, an endpoint, a UUID, a raw message ID, or any internal plumbing? STOP. Translate it.\n- Are you about to say "CLI", "command", "API", "tool", "endpoint", "proxy", "agent-api", or any other internal-mechanism word \u2014 even as a bare concept ("CLI \u6CA1\u6709\u8FD9\u4E2A\u547D\u4EE4", "\u5DE5\u5177\u4E0D\u652F\u6301")? STOP. Rephrase as a human teammate would: describe what you CAN do, or say "\u6211\u6CA1\u6CD5\u76F4\u63A5\u505A\u8FD9\u4E2A" without naming the mechanism.\n- Are you about to echo the `@handle` or the `[target=... msg=...]` header? STOP. Drop it.\n- Is this message inside a thread (`[thread context \u2026]`)? Then normal task discussion goes to `mio message reply --parent \u2026`, not `mio message send`. Exception: if you are coordinating and splitting separate independent work for other teammates, send fresh main-channel one-line @handoffs with `mio message send`, one handoff per task.\n- The server-side classifier auto-creates tasks from actionable main-channel messages \u2014 you do NOT call `mio task create` for delegation. To delegate work, send separate short main-channel messages tagging one assignee each (e.g. `@Backend \u5B9E\u73B0 X`); the classifier converts each one to a task and wakes them. A task assigned TO you is born already owned + already `in_progress` \u2014 do NOT list, claim, or set `in_progress`; just start it. `mio task claim #N` is ONLY for picking up an UNASSIGNED `todo` task that has no owner.\n- **Wrong-person handoff.** If someone addresses YOU with work that clearly belongs to another teammate\'s role (check the roster\'s roles/descriptions above), do NOT attempt it yourself and do NOT just refuse. Hand it off: send one short main-channel message `@<the right teammate> <one-line of what\'s needed>`, and tell the human in natural language that you\'ve passed it to that teammate (name them by name, never by @handle-echo). Pick the teammate whose described role best fits the request. Only take it on yourself if it genuinely fits YOUR role. If no teammate fits, say so plainly and suggest the closest option.\n- Are you 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"',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 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`.",ky=`## System-event wakes
445
+ `}var ky,Sy,Ey,xy,Ty,Cy,Ry,Ay,Hd=O(()=>{"use strict";Ud();ky='## 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.',Sy='## Reminder \u2014 hard constraints (reinforced)\n\nBefore you send anything to a human, check:\n\n- Are you about to paste a `mio` command, an endpoint, a UUID, a raw message ID, or any internal plumbing? STOP. Translate it.\n- Are you about to say "CLI", "command", "API", "tool", "endpoint", "proxy", "agent-api", or any other internal-mechanism word \u2014 even as a bare concept ("CLI \u6CA1\u6709\u8FD9\u4E2A\u547D\u4EE4", "\u5DE5\u5177\u4E0D\u652F\u6301")? STOP. Rephrase as a human teammate would: describe what you CAN do, or say "\u6211\u6CA1\u6CD5\u76F4\u63A5\u505A\u8FD9\u4E2A" without naming the mechanism.\n- Are you about to echo the `@handle` or the `[target=... msg=...]` header? STOP. Drop it.\n- Is this message inside a thread (`[thread context \u2026]`)? Then normal task discussion goes to `mio message reply --parent \u2026`, not `mio message send`. Exception: if you are coordinating and splitting separate independent work for other teammates, send fresh main-channel one-line @handoffs with `mio message send`, one handoff per task.\n- The server-side classifier auto-creates tasks from actionable main-channel messages \u2014 you do NOT call `mio task create` for delegation. To delegate work, send separate short main-channel messages tagging one assignee each (e.g. `@Backend \u5B9E\u73B0 X`); the classifier converts each one to a task and wakes them. A task assigned TO you is born already owned + already `in_progress` \u2014 do NOT list, claim, or set `in_progress`; just start it. `mio task claim #N` is ONLY for picking up an UNASSIGNED `todo` task that has no owner.\n- **Wrong-person handoff.** If someone addresses YOU with work that clearly belongs to another teammate\'s role (check the roster\'s roles/descriptions above), do NOT attempt it yourself and do NOT just refuse. Hand it off: send one short main-channel message `@<the right teammate> <one-line of what\'s needed>`, and tell the human in natural language that you\'ve passed it to that teammate (name them by name, never by @handle-echo). Pick the teammate whose described role best fits the request. Only take it on yourself if it genuinely fits YOUR role. If no teammate fits, say so plainly and suggest the closest option.\n- Are you 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"',Ey="## 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`.",xy=`## System-event wakes
446
446
 
447
447
  A \`[system event: ...]\` wake = task status changed / assigned / new in channel.
448
448
  Post a brief status only if something meaningful actually changed worth telling
449
449
  the team. Otherwise stay silent. Never re-ack the same event twice; never fake
450
- activity.`,Sy=`## Posting cadence
450
+ activity.`,Ty=`## Posting cadence
451
451
 
452
452
  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.
453
453
 
454
- 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.`,Ey="## 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",xy='## 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]`.',Ty=`## Startup and memory
454
+ 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.`,Cy="## 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",Ry='## 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]`.',Ay=`## Startup and memory
455
455
 
456
456
  1. On every startup, read \`MEMORY.md\` in your cwd first. It is your recovery point after context compression or sleep.
457
457
  2. If this turn includes an incoming message, decide whether it needs a reply and handle it.
458
458
  3. If there is no incoming message, stop and wait. New messages may be delivered automatically.
459
459
  4. Complete ALL your work before stopping \u2014 don't leave a half-finished thought.
460
460
 
461
- 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 Fl(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,f=typeof u=="string"&&u.trim()?u:typeof m=="string"&&m.trim()?m:typeof c.subtype=="string"?String(c.subtype):"turn failed";r(n.onResultError,"<onResultError>",f)}r(n.onBoundary,"<onBoundary>");return}}}return{feed(i){try{if(e.length+i.length>1048576){e="",n.onError?.(new Error("line-buffer overflow \u2014 buffer reset"),"<buffer>");return}e+=i;let o=e.split(`
462
- `),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var Hl=O(()=>{"use strict"});import{existsSync as yn}from"node:fs";import{execFileSync as rs}from"node:child_process";import{homedir as Ay}from"node:os";function _n(){let n=process.env.MIO_CLAUDE_PATH;if(n&&yn(n))return n;for(let e of Oy)if(yn(e))return e;try{let e=rs("/usr/bin/which",["claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&yn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=rs(e,["-lc","command -v claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&yn(t))return t}catch{}try{let e=rs("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/claude`;if(yn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=rs("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/claude`;if(yn(s))return s}}catch{}return null}function ql(){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(`
463
- `)}var ji,Oy,ss=O(()=>{"use strict";ji=Ay(),Oy=["/Applications/cmux.app/Contents/Resources/bin/claude",`${ji}/.local/bin/claude`,`${ji}/.claude/local/claude`,`${ji}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as Py}from"child_process";function Gl(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=Py,maxRestarts:c=5,presenceTracker:l,agentId:d}=n;function u(x){if(!(!l||!d))try{l.set(d,x)}catch(A){process.stderr.write(`[claudeStreamHost] presence(${x}) error: ${A.message}
464
- `)}}function m(x,A){d&&Q(d,x,A)}let f=0,p=n.claudeCommand??_n()??"claude",g=null,y=n.sessionId,E=!1,w=[],_=!1,k=0,P,T,L,F,J,G,Z;function ne(x){let A=["--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",t,"--disallowed-tools",Iy,"--append-system-prompt-file",r,"--mcp-config",s,"--setting-sources","user,project,local","--chrome"];return x&&A.push("--resume",x),A}function q(x,A){let v={type:"user",message:{role:"user",content:[{type:"text",text:x}]}};return A!==void 0&&(v.session_id=A),JSON.stringify(v)+`
465
- `}function se(x,A){if(!g||!g.stdin)return;let v=q(x,A);h("debug","claudeStreamHost","injected user turn",{bytes:v.length}),m("inject",{bytes:v.length,content_bytes:x.length,resume:A!==void 0}),u("thinking");try{g.stdin.write(v)}catch(N){process.stderr.write(`[claudeStreamHost] stdin write error (will restart): ${N.message}
466
- `);return}Z?.(x)}function ie(){k=0,m("boundary",{pending_queue_len:w.length});try{P?.()}catch(x){process.stderr.write(`[claudeStreamHost] onBoundary callback error: ${x.message}
461
+ 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 qd(n){let e="",t=new Set;function r(i,o,...a){if(i)try{i(...a)}catch(c){n.onError?.(c instanceof Error?c:new Error(String(c)),o)}}function s(i){let o=i.replace(/\r$/,"");if(o.trim()==="")return;let a;try{a=JSON.parse(o)}catch(l){n.onError&&n.onError(l instanceof Error?l:new Error(String(l)),o);return}if(typeof a!="object"||a===null)return;let c=a,d=c.type;if(typeof d=="string"){if(d==="system"&&c.subtype==="compact_boundary"){r(n.onCompact,"<onCompact>");return}if(d==="system"&&c.subtype==="init"){let l=c.session_id;typeof l=="string"&&l.length>0&&(t.has(l)||(t.add(l),r(n.onSessionId,"<onSessionId>",l)));return}if(d==="result"){let l=c.usage;if(n.onUsage&&l&&typeof l=="object"){let u=l,m={inputTokens:typeof u.input_tokens=="number"?u.input_tokens:void 0,outputTokens:typeof u.output_tokens=="number"?u.output_tokens:void 0,cacheReadTokens:typeof u.cache_read_input_tokens=="number"?u.cache_read_input_tokens:void 0,cacheCreationTokens:typeof u.cache_creation_input_tokens=="number"?u.cache_creation_input_tokens:void 0,durationMs:typeof c.duration_ms=="number"?c.duration_ms:void 0,totalCostUsd:typeof c.total_cost_usd=="number"?c.total_cost_usd:void 0};r(n.onUsage,"<onUsage>",m)}if(n.onResultError&&c.is_error===!0){let u=c.result,m=c.error,f=typeof u=="string"&&u.trim()?u:typeof m=="string"&&m.trim()?m:typeof c.subtype=="string"?String(c.subtype):"turn failed";r(n.onResultError,"<onResultError>",f)}r(n.onBoundary,"<onBoundary>");return}}}return{feed(i){try{if(e.length+i.length>1048576){e="",n.onError?.(new Error("line-buffer overflow \u2014 buffer reset"),"<buffer>");return}e+=i;let o=e.split(`
462
+ `),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var Gd=O(()=>{"use strict"});import{existsSync as yn}from"node:fs";import{execFileSync as ss}from"node:child_process";import{homedir as Iy}from"node:os";function _n(){let n=process.env.MIO_CLAUDE_PATH;if(n&&yn(n))return n;for(let e of Ny)if(yn(e))return e;try{let e=ss("/usr/bin/which",["claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&yn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=ss(e,["-lc","command -v claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&yn(t))return t}catch{}try{let e=ss("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/claude`;if(yn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=ss("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/claude`;if(yn(s))return s}}catch{}return null}function Wd(){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(`
463
+ `)}var Ji,Ny,is=O(()=>{"use strict";Ji=Iy(),Ny=["/Applications/cmux.app/Contents/Resources/bin/claude",`${Ji}/.local/bin/claude`,`${Ji}/.claude/local/claude`,`${Ji}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as My}from"child_process";function jd(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=My,maxRestarts:c=5,presenceTracker:d,agentId:l}=n;function u(x){if(!(!d||!l))try{d.set(l,x)}catch(A){process.stderr.write(`[claudeStreamHost] presence(${x}) error: ${A.message}
464
+ `)}}function m(x,A){l&&Q(l,x,A)}let f=0,p=n.claudeCommand??_n()??"claude",g=null,y=n.sessionId,E=!1,w=[],_=!1,k=0,P,T,L,F,J,G,Z;function ne(x){let A=["--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",t,"--disallowed-tools",Ly,"--append-system-prompt-file",r,"--mcp-config",s,"--setting-sources","user,project,local","--chrome"];return x&&A.push("--resume",x),A}function q(x,A){let v={type:"user",message:{role:"user",content:[{type:"text",text:x}]}};return A!==void 0&&(v.session_id=A),JSON.stringify(v)+`
465
+ `}function ie(x,A){if(!g||!g.stdin)return;let v=q(x,A);h("debug","claudeStreamHost","injected user turn",{bytes:v.length}),m("inject",{bytes:v.length,content_bytes:x.length,resume:A!==void 0}),u("thinking");try{g.stdin.write(v)}catch(N){process.stderr.write(`[claudeStreamHost] stdin write error (will restart): ${N.message}
466
+ `);return}Z?.(x)}function oe(){k=0,m("boundary",{pending_queue_len:w.length});try{P?.()}catch(x){process.stderr.write(`[claudeStreamHost] onBoundary callback error: ${x.message}
467
467
  `)}if(w.length>0){let x=w.length,A=w.splice(0,w.length).join(`
468
- `);m("coalesce_flush",{coalesced_count:x,bytes:A.length}),se(A,y)}else E=!1,u("idle")}function b(x){let A=ne(x);h("info","claudeStreamHost","spawning claude",{command:p,argsCount:A.length,cwd:e,resume:!!x}),f=Date.now(),m("spawn",{command:p,args_count:A.length,resume:!!x,resume_session_id:x??null,restart_count:k}),u("starting"),g&&(g.stdout?.removeAllListeners(),g.stderr?.removeAllListeners());let v=a(p,A,{cwd:e,env:i,stdio:["pipe","pipe","pipe"]});g=v,v.stdin?.on("error",C=>{v===g&&process.stderr.write(`[claudeStreamHost] stdin error (will restart): ${C.message}
469
- `)});let N=Fl({onSessionId:C=>{if(v!==g)return;y=C;let B=f?Date.now()-f:null;h("info","claudeStreamHost","session id captured",{sessionId:C,duration_ms:B}),m("session_ready",{session_id:C,spawn_duration_ms:B}),u("idle");try{L?.(C)}catch(W){process.stderr.write(`[claudeStreamHost] onSessionId callback error: ${W.message}
468
+ `);m("coalesce_flush",{coalesced_count:x,bytes:A.length}),ie(A,y)}else E=!1,u("idle")}function b(x){let A=ne(x);h("info","claudeStreamHost","spawning claude",{command:p,argsCount:A.length,cwd:e,resume:!!x}),f=Date.now(),m("spawn",{command:p,args_count:A.length,resume:!!x,resume_session_id:x??null,restart_count:k}),u("starting"),g&&(g.stdout?.removeAllListeners(),g.stderr?.removeAllListeners());let v=a(p,A,{cwd:e,env:i,stdio:["pipe","pipe","pipe"]});g=v,v.stdin?.on("error",C=>{v===g&&process.stderr.write(`[claudeStreamHost] stdin error (will restart): ${C.message}
469
+ `)});let N=qd({onSessionId:C=>{if(v!==g)return;y=C;let B=f?Date.now()-f:null;h("info","claudeStreamHost","session id captured",{sessionId:C,duration_ms:B}),m("session_ready",{session_id:C,spawn_duration_ms:B}),u("idle");try{L?.(C)}catch(W){process.stderr.write(`[claudeStreamHost] onSessionId callback error: ${W.message}
470
470
  `)}},onResultError:C=>{if(v===g){h("warn","claudeStreamHost","turn ended with error",{message:C.slice(0,120)});try{T?.(C)}catch(B){process.stderr.write(`[claudeStreamHost] onTurnError callback error: ${B.message}
471
471
  `)}}},onCompact:()=>{if(v===g){h("info","claudeStreamHost","context auto-compacted (compact_boundary)");try{F?.()}catch(C){process.stderr.write(`[claudeStreamHost] onCompact callback error: ${C.message}
472
- `)}}},onUsage:C=>{if(v===g){try{J?.({inputTokens:C.inputTokens??0,outputTokens:C.outputTokens??0,cacheReadTokens:C.cacheReadTokens??0,cacheCreationTokens:C.cacheCreationTokens??0})}catch{}m("usage",{runtime:"claude",model:t,input_tokens:C.inputTokens??null,output_tokens:C.outputTokens??null,cache_read_tokens:C.cacheReadTokens??null,cache_creation_tokens:C.cacheCreationTokens??null,duration_ms:C.durationMs??null,total_cost_usd:C.totalCostUsd??null})}},onBoundary:()=>{v===g&&(h("debug","claudeStreamHost","turn boundary",{}),ie())},onError:(C,B)=>{process.stderr.write(`[claudeStreamHost] parser error on "${B}": ${C.message}
472
+ `)}}},onUsage:C=>{if(v===g){try{J?.({inputTokens:C.inputTokens??0,outputTokens:C.outputTokens??0,cacheReadTokens:C.cacheReadTokens??0,cacheCreationTokens:C.cacheCreationTokens??0})}catch{}m("usage",{runtime:"claude",model:t,input_tokens:C.inputTokens??null,output_tokens:C.outputTokens??null,cache_read_tokens:C.cacheReadTokens??null,cache_creation_tokens:C.cacheCreationTokens??null,duration_ms:C.durationMs??null,total_cost_usd:C.totalCostUsd??null})}},onBoundary:()=>{v===g&&(h("debug","claudeStreamHost","turn boundary",{}),oe())},onError:(C,B)=>{process.stderr.write(`[claudeStreamHost] parser error on "${B}": ${C.message}
473
473
  `)}});v.stdout?.on("data",C=>{v===g&&N.feed(typeof C=="string"?C:C.toString("utf8"))});let I="";v.stderr?.on("data",C=>{if(v!==g)return;I+=typeof C=="string"?C:C.toString("utf8");let B;for(;(B=I.indexOf(`
474
474
  `))!==-1;){let W=I.slice(0,B).trimEnd();I=I.slice(B+1),W.length>0&&h("warn","claudeStreamHost","claude stderr",{line:W})}}),v.on("exit",C=>{v===g&&R(C)}),v.on("error",C=>{process.stderr.write(`[claudeStreamHost] spawn error: ${C.message}
475
475
  `)})}function R(x){if(!_){if(k++,k>c){S("claudeStreamHost","giving up after max restarts",{restartCount:k}),process.stderr.write(`[claudeStreamHost] gave up after ${c} restarts (code=${x})
476
476
  `);try{G?.(x)}catch(A){process.stderr.write(`[claudeStreamHost] onExit callback error: ${A.message}
477
477
  `)}return}if(h("warn","claudeStreamHost","claude exited",{code:x,willRestart:!0,restartCount:k}),m("exit",{code:x,will_restart:!0,restart_count:k}),process.stderr.write(`[claudeStreamHost] unexpected exit (code=${x}), restarting (attempt ${k}/${c})...
478
478
  `),E=!1,b(y),w.length>0){let A=w.splice(0,w.length).join(`
479
- `);E=!0,se(A,y)}}}return{start(){b(y),E=!0,se(o,y)},enqueueUserTurn(x){E?w.push(x):(E=!0,se(x,y))},stop(){if(_=!0,g){try{g.stdin?.end()}catch{}let x=setTimeout(()=>{try{g?.kill()}catch{}},2e3);x.unref&&x.unref()}},onTurnError(x){T=x},onBoundary(x){P=x},onSessionId(x){L=x},onCompact(x){F=x},onTurnUsage(x){J=x},onExit(x){G=x},onInjected(x){Z=x}}}var Iy,Wl=O(()=>{"use strict";Hl();le();Rt();ss();Iy=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(",")});import{existsSync as wn}from"node:fs";import{execFileSync as is}from"node:child_process";import{homedir as Ny}from"node:os";function os(){let n=process.env.MIO_CODEX_PATH;if(n&&wn(n))return n;for(let e of My)if(wn(e))return e;try{let e=is("/usr/bin/which",["codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&wn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=is(e,["-lc","command -v codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&wn(t))return t}catch{}try{let e=is("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/codex`;if(wn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=is("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/codex`;if(wn(s))return s}}catch{}return null}function Jl(){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(`
480
- `)}var jl,My,Ji=O(()=>{"use strict";jl=Ny(),My=["/opt/homebrew/bin/codex","/usr/local/bin/codex",`${jl}/.npm-global/bin/codex`,`${jl}/.codex/bin/codex`]});import{spawn as Ly}from"node:child_process";function Yl(n){let e=n.spawnFn??Dy,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(f){if(!(!i||!s.stdin))try{s.stdin.write(JSON.stringify(f)+`
481
- `)}catch(p){t("warn","appServerClient stdin write failed",{err:p.message})}}function d(f){for(let[,p]of c)clearTimeout(p.timer),p.reject(new Error(f));c.clear()}function u(f){let p=f.id!==void 0&&f.id!==null,g=typeof f.method=="string";if(p&&!g){let y=f.id,E=c.get(y);if(!E){t("debug","appServerClient response for unknown id",{id:y});return}c.delete(y),clearTimeout(E.timer),f.error!==void 0?E.reject(new Error(`app-server error: ${JSON.stringify(f.error)}`)):E.resolve(f.result);return}if(g&&p){let y=f.id,E=f.method;Promise.resolve().then(()=>n.onServerRequest?n.onServerRequest(E,f.params):void 0).then(w=>l({id:y,result:w??{}})).catch(w=>{t("warn","onServerRequest handler threw",{method:E,err:w.message}),l({id:y,error:{code:-32e3,message:String(w.message)}})});return}if(g){try{n.onNotification(f.method,f.params)}catch(y){t("warn","onNotification handler threw",{method:f.method,err:y.message})}return}t("debug","appServerClient unrecognized message",{keys:Object.keys(f)})}function m(f){if(a+=typeof f=="string"?f:f.toString("utf8"),a.length>$y){t("warn","appServerClient buffer overflow \u2014 clearing",{bytes:a.length}),a="";return}let p;for(;(p=a.indexOf(`
482
- `))>=0;){let g=a.slice(0,p).replace(/\r$/,"");if(a=a.slice(p+1),!g.trim())continue;let y;try{y=JSON.parse(g)}catch{t("debug","appServerClient non-JSON line",{preview:g.slice(0,120)});continue}y&&typeof y=="object"&&u(y)}}return s.stdout?.on("data",m),s.stderr?.on("data",f=>{let p=typeof f=="string"?f:f.toString("utf8");n.onStderr&&n.onStderr(p)}),s.on("error",f=>{t("warn","appServerClient spawn error",{err:f.message}),i=!1,d(`app-server spawn error: ${f.message}`),n.onExit?.(null)}),s.on("exit",f=>{t("info","appServerClient exited",{code:f}),i=!1,d(`app-server exited (code=${f})`),n.onExit?.(f)}),{request(f,p){if(!i)return Promise.reject(new Error("app-server not alive"));let g=o++;return new Promise((y,E)=>{let w=setTimeout(()=>{c.delete(g),E(new Error(`app-server request '${f}' timed out after ${r}ms`))},r);w.unref?.(),c.set(g,{resolve:y,reject:E,timer:w}),l({method:f,id:g,params:p})})},notify(f,p){l({method:f,params:p})},isAlive(){return i},close(){if(i){i=!1,d("app-server client closed");try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}var $y,Dy,Vl=O(()=>{"use strict";$y=4*1048576,Dy=(n,e,t)=>Ly(n,e,{cwd:t.cwd,env:t.env,stdio:["pipe","pipe","pipe"]})});import{readFileSync as By}from"node:fs";function Uy(n){let e=n?.trim();return e==="read-only"||e==="workspace-write"||e==="danger-full-access"?e:"danger-full-access"}function Fy(n){let e=n?.trim();if(e&&e!=="gpt-5-codex")return e}function zl(n){let e=n.codexCommand??os()??"codex",t=(process.env.MIO_CODEX_MODEL_REASONING||n.reasoningEffort||"medium").trim(),r=Fy((process.env.MIO_CODEX_MODEL||n.spawnEnv.MIO_CODEX_MODEL||"").trim()||n.model),s=Uy(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,f=[],p,g="",y,E,w,_,k,P;function T(b,R){o&&Q(o,b,{runtime:"codex-app-server",...R})}function L(b){if(!(!n.presenceTracker||!o))try{n.presenceTracker.set(o,b)}catch(R){process.stderr.write(`[${be}] presence(${b}) error: ${R.message}
483
- `)}}function F(){try{return By(n.systemPromptPath,"utf8")}catch(b){return S(be,`failed to read system prompt at ${n.systemPromptPath}`,b),""}}function J(b,R){return h("debug",be,"auto-approving server request",{method:b}),{decision:"approved"}}function G(b){let R=b.content;return Array.isArray(R)?R.map(x=>x&&typeof x=="object"&&typeof x.text=="string"?x.text:"").join(""):typeof b.text=="string"?b.text:""}function Z(b,R){let x=R??{};switch(b){case"thread/started":{let v=x.thread?.id;if(v&&v!==c){c=v;try{E?.(v)}catch(N){S(be,"onSessionId cb error",N)}T("spawn",{thread_id:v})}break}case"turn/started":l=!0,L("thinking");break;case"item/agentMessage/delta":{let A=x.delta??x.text;typeof A=="string"&&(g+=A);break}case"item/started":T("runtime_command",{phase:"started"});break;case"item/completed":{let A=x.item;if(!A)break;let v=A.type;if(v==="agentMessage"||v==="assistantMessage"){let N=G(A).trim();N&&T("runtime_message",{chars:N.length,preview:N.slice(0,240)})}else(v==="commandExecution"||v==="localShellCall")&&T("runtime_command",{phase:"completed"});break}case"thread/tokenUsage/updated":{let A=x.tokenUsage?.last;if(A){let v=Number(A.inputTokens??0),N=Number(A.cachedInputTokens??0);try{P?.({inputTokens:v,outputTokens:Number(A.outputTokens??0),cacheReadTokens:N,cacheCreationTokens:0})}catch{}T("usage",{input_tokens:v,output_tokens:Number(A.outputTokens??0),cache_read_tokens:N,total_tokens:Number(A.totalTokens??0)})}break}case"turn/completed":{let A=x.turn,v=A?.status;if(v&&v!=="completed"){h("warn",be,"turn ended non-completed",{status:v,error:A?.error});let N=A?.error,I=typeof N=="string"?N:N&&typeof N.message=="string"?N.message:`codex turn ${v}`;try{k?.(I)}catch(C){S(be,"onTurnError cb error",C)}}g="",l=!1,L("idle");try{y?.()}catch(N){S(be,"onBoundary cb error",N)}q();break}default:break}}function ne(b){if(!a||!a.isAlive()||!c){f.push(b);return}l=!0,L("thinking"),g="",T("inbound",{chars:b.length});try{_?.(b)}catch(R){S(be,"onInjected cb error",R)}a.request("turn/start",{threadId:c,input:[{type:"text",text:b,text_elements:[]}]}).catch(R=>{h("warn",be,"turn/start failed",{err:R.message}),l=!1,L("idle");try{y?.()}catch{}q()})}function q(){if(l||f.length===0)return;let b=f.splice(0).join(`
479
+ `);E=!0,ie(A,y)}}}return{start(){b(y),E=!0,ie(o,y)},enqueueUserTurn(x){E?w.push(x):(E=!0,ie(x,y))},stop(){if(_=!0,g){try{g.stdin?.end()}catch{}let x=setTimeout(()=>{try{g?.kill()}catch{}},2e3);x.unref&&x.unref()}},onTurnError(x){T=x},onBoundary(x){P=x},onSessionId(x){L=x},onCompact(x){F=x},onTurnUsage(x){J=x},onExit(x){G=x},onInjected(x){Z=x}}}var Ly,Jd=O(()=>{"use strict";Gd();de();Rt();is();Ly=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(",")});import{existsSync as wn}from"node:fs";import{execFileSync as os}from"node:child_process";import{homedir as $y}from"node:os";function as(){let n=process.env.MIO_CODEX_PATH;if(n&&wn(n))return n;for(let e of Dy)if(wn(e))return e;try{let e=os("/usr/bin/which",["codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&wn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=os(e,["-lc","command -v codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&wn(t))return t}catch{}try{let e=os("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/codex`;if(wn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=os("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/codex`;if(wn(s))return s}}catch{}return null}function Vd(){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(`
480
+ `)}var Yd,Dy,Yi=O(()=>{"use strict";Yd=$y(),Dy=["/opt/homebrew/bin/codex","/usr/local/bin/codex",`${Yd}/.npm-global/bin/codex`,`${Yd}/.codex/bin/codex`]});import{spawn as By}from"node:child_process";function zd(n){let e=n.spawnFn??Fy,t=n.log??(()=>{}),r=n.requestTimeoutMs??6e4,s=e(n.command,n.args,{cwd:n.cwd,env:n.env}),i=!0,o=1,a="",c=new Map;function d(f){if(!(!i||!s.stdin))try{s.stdin.write(JSON.stringify(f)+`
481
+ `)}catch(p){t("warn","appServerClient stdin write failed",{err:p.message})}}function l(f){for(let[,p]of c)clearTimeout(p.timer),p.reject(new Error(f));c.clear()}function u(f){let p=f.id!==void 0&&f.id!==null,g=typeof f.method=="string";if(p&&!g){let y=f.id,E=c.get(y);if(!E){t("debug","appServerClient response for unknown id",{id:y});return}c.delete(y),clearTimeout(E.timer),f.error!==void 0?E.reject(new Error(`app-server error: ${JSON.stringify(f.error)}`)):E.resolve(f.result);return}if(g&&p){let y=f.id,E=f.method;Promise.resolve().then(()=>n.onServerRequest?n.onServerRequest(E,f.params):void 0).then(w=>d({id:y,result:w??{}})).catch(w=>{t("warn","onServerRequest handler threw",{method:E,err:w.message}),d({id:y,error:{code:-32e3,message:String(w.message)}})});return}if(g){try{n.onNotification(f.method,f.params)}catch(y){t("warn","onNotification handler threw",{method:f.method,err:y.message})}return}t("debug","appServerClient unrecognized message",{keys:Object.keys(f)})}function m(f){if(a+=typeof f=="string"?f:f.toString("utf8"),a.length>Uy){t("warn","appServerClient buffer overflow \u2014 clearing",{bytes:a.length}),a="";return}let p;for(;(p=a.indexOf(`
482
+ `))>=0;){let g=a.slice(0,p).replace(/\r$/,"");if(a=a.slice(p+1),!g.trim())continue;let y;try{y=JSON.parse(g)}catch{t("debug","appServerClient non-JSON line",{preview:g.slice(0,120)});continue}y&&typeof y=="object"&&u(y)}}return s.stdout?.on("data",m),s.stderr?.on("data",f=>{let p=typeof f=="string"?f:f.toString("utf8");n.onStderr&&n.onStderr(p)}),s.on("error",f=>{t("warn","appServerClient spawn error",{err:f.message}),i=!1,l(`app-server spawn error: ${f.message}`),n.onExit?.(null)}),s.on("exit",f=>{t("info","appServerClient exited",{code:f}),i=!1,l(`app-server exited (code=${f})`),n.onExit?.(f)}),{request(f,p){if(!i)return Promise.reject(new Error("app-server not alive"));let g=o++;return new Promise((y,E)=>{let w=setTimeout(()=>{c.delete(g),E(new Error(`app-server request '${f}' timed out after ${r}ms`))},r);w.unref?.(),c.set(g,{resolve:y,reject:E,timer:w}),d({method:f,id:g,params:p})})},notify(f,p){d({method:f,params:p})},isAlive(){return i},close(){if(i){i=!1,l("app-server client closed");try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}var Uy,Fy,Kd=O(()=>{"use strict";Uy=4*1048576,Fy=(n,e,t)=>By(n,e,{cwd:t.cwd,env:t.env,stdio:["pipe","pipe","pipe"]})});import{readFileSync as Hy}from"node:fs";function qy(n){let e=n?.trim();return e==="read-only"||e==="workspace-write"||e==="danger-full-access"?e:"danger-full-access"}function Gy(n){let e=n?.trim();if(e&&e!=="gpt-5-codex")return e}function Xd(n){let e=n.codexCommand??as()??"codex",t=(process.env.MIO_CODEX_MODEL_REASONING||n.reasoningEffort||"medium").trim(),r=Gy((process.env.MIO_CODEX_MODEL||n.spawnEnv.MIO_CODEX_MODEL||"").trim()||n.model),s=qy(process.env.MIO_CODEX_SANDBOX||n.spawnEnv.MIO_CODEX_SANDBOX),i=n.maxRestarts??5,o=n.agentId,a=null,c=n.sessionId,d=!1,l=!1,u=!1,m=0,f=[],p,g="",y,E,w,_,k,P;function T(b,R){o&&Q(o,b,{runtime:"codex-app-server",...R})}function L(b){if(!(!n.presenceTracker||!o))try{n.presenceTracker.set(o,b)}catch(R){process.stderr.write(`[${be}] presence(${b}) error: ${R.message}
483
+ `)}}function F(){try{return Hy(n.systemPromptPath,"utf8")}catch(b){return S(be,`failed to read system prompt at ${n.systemPromptPath}`,b),""}}function J(b,R){return h("debug",be,"auto-approving server request",{method:b}),{decision:"approved"}}function G(b){let R=b.content;return Array.isArray(R)?R.map(x=>x&&typeof x=="object"&&typeof x.text=="string"?x.text:"").join(""):typeof b.text=="string"?b.text:""}function Z(b,R){let x=R??{};switch(b){case"thread/started":{let v=x.thread?.id;if(v&&v!==c){c=v;try{E?.(v)}catch(N){S(be,"onSessionId cb error",N)}T("spawn",{thread_id:v})}break}case"turn/started":d=!0,L("thinking");break;case"item/agentMessage/delta":{let A=x.delta??x.text;typeof A=="string"&&(g+=A);break}case"item/started":T("runtime_command",{phase:"started"});break;case"item/completed":{let A=x.item;if(!A)break;let v=A.type;if(v==="agentMessage"||v==="assistantMessage"){let N=G(A).trim();N&&T("runtime_message",{chars:N.length,preview:N.slice(0,240)})}else(v==="commandExecution"||v==="localShellCall")&&T("runtime_command",{phase:"completed"});break}case"thread/tokenUsage/updated":{let A=x.tokenUsage?.last;if(A){let v=Number(A.inputTokens??0),N=Number(A.cachedInputTokens??0);try{P?.({inputTokens:v,outputTokens:Number(A.outputTokens??0),cacheReadTokens:N,cacheCreationTokens:0})}catch{}T("usage",{input_tokens:v,output_tokens:Number(A.outputTokens??0),cache_read_tokens:N,total_tokens:Number(A.totalTokens??0)})}break}case"turn/completed":{let A=x.turn,v=A?.status;if(v&&v!=="completed"){h("warn",be,"turn ended non-completed",{status:v,error:A?.error});let N=A?.error,I=typeof N=="string"?N:N&&typeof N.message=="string"?N.message:`codex turn ${v}`;try{k?.(I)}catch(C){S(be,"onTurnError cb error",C)}}g="",d=!1,L("idle");try{y?.()}catch(N){S(be,"onBoundary cb error",N)}q();break}default:break}}function ne(b){if(!a||!a.isAlive()||!c){f.push(b);return}d=!0,L("thinking"),g="",T("inbound",{chars:b.length});try{_?.(b)}catch(R){S(be,"onInjected cb error",R)}a.request("turn/start",{threadId:c,input:[{type:"text",text:b,text_elements:[]}]}).catch(R=>{h("warn",be,"turn/start failed",{err:R.message}),d=!1,L("idle");try{y?.()}catch{}q()})}function q(){if(d||f.length===0)return;let b=f.splice(0).join(`
484
484
 
485
- `);ne(b)}async function se(b){let R={...n.spawnEnv},x=["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=Yl({command:e,args:x,cwd:n.workingDirectory,env:R,onNotification:Z,onServerRequest:J,onStderr:v=>{v.trim()&&h("debug",be,"app-server stderr",{snippet:v.slice(0,200)})},onExit:ie,log:(v,N,I)=>h(v,be,N,I),...n.appServerSpawnFn?{spawnFn:n.appServerSpawnFn}:{}});let A=c!==void 0;try{if(await a.request("initialize",{clientInfo:{name:"mio-agent",title:null,version:"1"},capabilities:null}),A)await a.request("thread/resume",{threadId:c}),h("info",be,"resumed thread",{threadId:c,viaRespawn:b});else{let v=F()||void 0,I=(await a.request("thread/start",{cwd:n.workingDirectory,sandbox:s,sandbox_mode:s,approvalPolicy:"never",...r?{model:r}:{},...v?{baseInstructions:v}:{}}))?.thread?.id;if(I){c=I;try{E?.(I)}catch(C){S(be,"onSessionId cb error",C)}}}}catch(v){S(be,"handshake failed",v);return}if(!A&&p!==void 0){let v=p;p=void 0,ne(v)}else l=!1,q()}function ie(b){if(d){try{w?.(b)}catch{}return}if(m>=i){h("warn",be,"max restarts reached \u2014 giving up",{restartCount:m});try{w?.(b)}catch{}return}m++,l=!1,h("info",be,"app-server exited \u2014 respawning",{code:b,restartCount:m,threadId:c}),T("boundary",{reason:"respawn",code:b}),se(!0)}return{start(){u||(u=!0,L("starting"),p=n.firstTurnText,se(!1))},enqueueUserTurn(b){if(l||!a||!a.isAlive()||!c){f.push(b);return}ne(b)},stop(){d=!0;try{a?.close()}catch{}},onBoundary(b){y=b},onSessionId(b){E=b},onExit(b){w=b},onInjected(b){_=b},onTurnError(b){k=b},onTurnUsage(b){P=b}}}var be,Kl=O(()=>{"use strict";le();Rt();Ji();Vl();be="codexAppServerHost"});import{readFileSync as Hy,writeFileSync as qy,mkdirSync as Gy}from"node:fs";import{join as Wy}from"node:path";function Xl(n,e){return Wy(n,e?`runtime-session-${e.slice(0,8)}.json`:"runtime-session.json")}function Ql(n,e,t){try{let r=JSON.parse(Hy(Xl(n,t),"utf-8"));if(r&&r.runtime===e&&typeof r.sessionId=="string"&&r.sessionId.length>0)return r.sessionId}catch{}}function Zl(n,e,t,r){if(t)try{Gy(n,{recursive:!0});let s={runtime:e,sessionId:t,savedAt:new Date().toISOString()};qy(Xl(n,r),JSON.stringify(s,null,2),"utf-8")}catch{}}var eu=O(()=>{"use strict"});function tu(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Xn(n){return typeof n=="boolean"?n:void 0}function Xy(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.floor(n);return e>0?e:void 0}function Qy(n){return Math.max(1,Math.min(6,Math.floor(n)))}function ru(n){let e=n.role??"",t=`${n.displayName??""} ${n.description??""} ${e}`,r={...Qn};zy(t)&&!Ky(t)&&(r.deliverBroadcastMessages=!1,r.deliverThreadBroadcastMessages=!1,r.wakeOnChannelTaskCreated=!1,r.wakeOnChannelTaskStatus=!1,r.threadReplyLimit=3);let s=tu(n.capabilities),i=tu(s?.context_policy);return i&&(r.deliverBroadcastMessages=Xn(i.deliver_broadcast_messages)??r.deliverBroadcastMessages,r.deliverSystemMessages=Xn(i.deliver_system_messages)??r.deliverSystemMessages,r.deliverThreadBroadcastMessages=Xn(i.deliver_thread_broadcast_messages)??r.deliverThreadBroadcastMessages,r.wakeOnChannelTaskCreated=Xn(i.wake_on_channel_task_created)??r.wakeOnChannelTaskCreated,r.wakeOnChannelTaskStatus=Xn(i.wake_on_channel_task_status)??r.wakeOnChannelTaskStatus,r.threadReplyLimit=Qy(Xy(i.thread_reply_limit)??r.threadReplyLimit)),r}function su(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 Qn,jy,Jy,Yy,Vy,nu,zy,Ky,as=O(()=>{"use strict";Qn={deliverBroadcastMessages:!0,deliverSystemMessages:!1,deliverThreadBroadcastMessages:!0,wakeOnChannelTaskCreated:!0,wakeOnChannelTaskStatus:!1,threadReplyLimit:6},jy=/\b(engineer|backend|frontend|ui|designer|design|executor|implement|coder|tester|qa|reviewer|operator|ops)\b/i,Jy=/\b(pm|product|planner|coordinator|researcher|research|market|analyst|analysis)\b/i,Yy=["\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"],Vy=["\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"],nu=(n,e)=>e.some(t=>n.includes(t)),zy=n=>jy.test(n)||nu(n,Yy),Ky=n=>Jy.test(n)||nu(n,Vy)});import{writeFileSync as Zy,mkdirSync as e_}from"node:fs";import{join as iu}from"node:path";function cs(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 t_(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: ${cs(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(` ${cs(u,r)}`)}return l.push("incoming:"),l.push(cs(n,r)),s&&l.push(`(reply with: mio message reply --parent ${s} --target "#${r}")`),l.join(`
486
- `)}function ou(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:f,contextPolicy:p=Qn,mioDir:g,downloadAttachment:y}=n,E=/^image\//;async function w(v){let N=v.attachment_ids??[];if(N.length===0||!g||!y)return"";let I=iu(g,"inbound"),C=[];for(let B of N.slice(0,10))try{let W=await y(B);if(!E.test(W.mime_type))continue;try{e_(I,{recursive:!0})}catch{}let oe=(W.filename||`${B}.png`).replace(/[^\w.\-]/g,"_").slice(-60),he=iu(I,`${v.id.slice(0,8)}-${oe}`);Zy(he,Buffer.from(W.data_base64,"base64")),C.push(he)}catch(W){S(z,"inbound attachment download failed (skipping)",W)}return C.length===0?"":`
485
+ `);ne(b)}async function ie(b){let R={...n.spawnEnv},x=["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=zd({command:e,args:x,cwd:n.workingDirectory,env:R,onNotification:Z,onServerRequest:J,onStderr:v=>{v.trim()&&h("debug",be,"app-server stderr",{snippet:v.slice(0,200)})},onExit:oe,log:(v,N,I)=>h(v,be,N,I),...n.appServerSpawnFn?{spawnFn:n.appServerSpawnFn}:{}});let A=c!==void 0;try{if(await a.request("initialize",{clientInfo:{name:"mio-agent",title:null,version:"1"},capabilities:null}),A)await a.request("thread/resume",{threadId:c}),h("info",be,"resumed thread",{threadId:c,viaRespawn:b});else{let v=F()||void 0,I=(await a.request("thread/start",{cwd:n.workingDirectory,sandbox:s,sandbox_mode:s,approvalPolicy:"never",...r?{model:r}:{},...v?{baseInstructions:v}:{}}))?.thread?.id;if(I){c=I;try{E?.(I)}catch(C){S(be,"onSessionId cb error",C)}}}}catch(v){S(be,"handshake failed",v);return}if(!A&&p!==void 0){let v=p;p=void 0,ne(v)}else d=!1,q()}function oe(b){if(l){try{w?.(b)}catch{}return}if(m>=i){h("warn",be,"max restarts reached \u2014 giving up",{restartCount:m});try{w?.(b)}catch{}return}m++,d=!1,h("info",be,"app-server exited \u2014 respawning",{code:b,restartCount:m,threadId:c}),T("boundary",{reason:"respawn",code:b}),ie(!0)}return{start(){u||(u=!0,L("starting"),p=n.firstTurnText,ie(!1))},enqueueUserTurn(b){if(d||!a||!a.isAlive()||!c){f.push(b);return}ne(b)},stop(){l=!0;try{a?.close()}catch{}},onBoundary(b){y=b},onSessionId(b){E=b},onExit(b){w=b},onInjected(b){_=b},onTurnError(b){k=b},onTurnUsage(b){P=b}}}var be,Qd=O(()=>{"use strict";de();Rt();Yi();Kd();be="codexAppServerHost"});import{readFileSync as Wy,writeFileSync as jy,mkdirSync as Jy}from"node:fs";import{join as Yy}from"node:path";function Zd(n,e){return Yy(n,e?`runtime-session-${e.slice(0,8)}.json`:"runtime-session.json")}function eu(n,e,t){try{let r=JSON.parse(Wy(Zd(n,t),"utf-8"));if(r&&r.runtime===e&&typeof r.sessionId=="string"&&r.sessionId.length>0)return r.sessionId}catch{}}function tu(n,e,t,r){if(t)try{Jy(n,{recursive:!0});let s={runtime:e,sessionId:t,savedAt:new Date().toISOString()};jy(Zd(n,r),JSON.stringify(s,null,2),"utf-8")}catch{}}var nu=O(()=>{"use strict"});function ru(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Qn(n){return typeof n=="boolean"?n:void 0}function e_(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.floor(n);return e>0?e:void 0}function t_(n){return Math.max(1,Math.min(6,Math.floor(n)))}function iu(n){let e=n.role??"",t=`${n.displayName??""} ${n.description??""} ${e}`,r={...Zn};Qy(t)&&!Zy(t)&&(r.deliverBroadcastMessages=!1,r.deliverThreadBroadcastMessages=!1,r.wakeOnChannelTaskCreated=!1,r.wakeOnChannelTaskStatus=!1,r.threadReplyLimit=3);let s=ru(n.capabilities),i=ru(s?.context_policy);return i&&(r.deliverBroadcastMessages=Qn(i.deliver_broadcast_messages)??r.deliverBroadcastMessages,r.deliverSystemMessages=Qn(i.deliver_system_messages)??r.deliverSystemMessages,r.deliverThreadBroadcastMessages=Qn(i.deliver_thread_broadcast_messages)??r.deliverThreadBroadcastMessages,r.wakeOnChannelTaskCreated=Qn(i.wake_on_channel_task_created)??r.wakeOnChannelTaskCreated,r.wakeOnChannelTaskStatus=Qn(i.wake_on_channel_task_status)??r.wakeOnChannelTaskStatus,r.threadReplyLimit=t_(e_(i.thread_reply_limit)??r.threadReplyLimit)),r}function ou(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 Zn,Vy,zy,Ky,Xy,su,Qy,Zy,cs=O(()=>{"use strict";Zn={deliverBroadcastMessages:!0,deliverSystemMessages:!1,deliverThreadBroadcastMessages:!0,wakeOnChannelTaskCreated:!0,wakeOnChannelTaskStatus:!1,threadReplyLimit:6},Vy=/\b(engineer|backend|frontend|ui|designer|design|executor|implement|coder|tester|qa|reviewer|operator|ops)\b/i,zy=/\b(pm|product|planner|coordinator|researcher|research|market|analyst|analysis)\b/i,Ky=["\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"],Xy=["\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"],su=(n,e)=>e.some(t=>n.includes(t)),Qy=n=>Vy.test(n)||su(n,Ky),Zy=n=>zy.test(n)||su(n,Xy)});import{writeFileSync as n_,mkdirSync as r_}from"node:fs";import{join as au}from"node:path";function ls(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 s_(n,e,t,r){let s=n.parent_message_id??"",i=s.replace(/-/g,"").slice(0,8),o=e?.attached_task??null,a=[];o&&a.push(`task #${o.task_number} "${o.title}" status=${o.status}`),a.push(`channel=#${r}`),i&&a.push(`parent=${i}`);let d=[`[thread context, ${a.join(", ")}]`];e?d.push(`parent: ${ls(e,r)}`):n.parent_message_id&&d.push(`parent: (unavailable \u2014 parent message id ${i||s})`);let l=t.filter(u=>u.id!==n.id);if(l.length>0){d.push("recent replies:");for(let u of l)d.push(` ${ls(u,r)}`)}return d.push("incoming:"),d.push(ls(n,r)),s&&d.push(`(reply with: mio message reply --parent ${s} --target "#${r}")`),d.join(`
486
+ `)}function cu(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:d,onInjected:l,reminderCache:u,onInboundMessage:m,contextTracker:f,contextPolicy:p=Zn,mioDir:g,downloadAttachment:y}=n,E=/^image\//;async function w(v){let N=v.attachment_ids??[];if(N.length===0||!g||!y)return"";let I=au(g,"inbound"),C=[];for(let B of N.slice(0,10))try{let W=await y(B);if(!E.test(W.mime_type))continue;try{r_(I,{recursive:!0})}catch{}let ae=(W.filename||`${B}.png`).replace(/[^\w.\-]/g,"_").slice(-60),he=au(I,`${v.id.slice(0,8)}-${ae}`);n_(he,Buffer.from(W.data_base64,"base64")),C.push(he)}catch(W){S(z,"inbound attachment download failed (skipping)",W)}return C.length===0?"":`
487
487
 
488
488
  [\u9644\u4EF6] \u7528\u6237\u5728\u8FD9\u6761\u6D88\u606F\u91CC\u53D1\u4E86 ${C.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
489
489
  `+C.map(B=>` - ${B}`).join(`
490
- `)}let _=a??e.getChannelMessages.bind(e),k=new Map;async function P(v){let N=await e.getWorkroomChannels(o);for(let I of N)I.id&&I.name&&k.set(I.id,I.name);return k.get(v)}let T=c??P;async function L(v){let N=k.get(v);if(N!==void 0)return N;let I=await T(v);return I!==void 0&&k.set(v,I),I}let F=l??(async()=>new Set((await e.getAgentChannels(r)).map(v=>v.id))),J=null,G=new Set,Z=250,ne=5e3,q=Z,se=v=>new Promise(N=>{let I=setTimeout(N,v);typeof I.unref=="function"&&I.unref()});function ie(){let v=F().then(N=>(q=Z,N)).catch(N=>{S(z,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",N);let I=q;return q=Math.min(q*2,ne),J===v&&(J=se(I).then(()=>(ie(),J??new Set))),new Set});J=v}let b=n.hostFor??(()=>t),R;t.onInjected(v=>{R?.(v)}),d&&(R=d);async function x(v){if(v.topic==="reminder.upserted"||v.topic==="reminder.canceled"){if(u){let Y=v.payload;if(v.topic==="reminder.upserted")if(Y.reminder){if(Y.reminder.agentId!==r)return;u.upsert(Y.reminder)}else h("warn",z,"reminder.upserted event missing reminder payload",{payload:v.payload});else if(Y.reminderId){if(Y.agentId!==r)return;u.cancel(Y.reminderId,Y.version)}else h("warn",z,"reminder.canceled event missing reminderId",{payload:v.payload})}return}if(v.topic==="channel.member_added"||v.topic==="channel.member_removed"||v.topic==="roster.member_added"||v.topic==="roster.member_removed"){let Y=v.payload;Y.member_id===r&&(h("info",z,"membership changed for self \u2014 invalidating membership cache",{topic:v.topic,channelId:Y.channel_id}),G.clear(),ie());return}if(v.topic!=="message.created"&&v.topic!=="thread.reply")return;let N=v.payload,I=N.channel_id,C=N.seq,B=N.message_id,W=N.parent_message_id;if(!I||!C){h("warn",z,"message.created event missing channel_id or seq",{payload:N});return}Q(r,"event_received",{topic:v.topic,channel_id:I,seq:C,message_id:B??null,parent_message_id:W??null});let he=(await(J??Promise.resolve(new Set))).has(I);if(!he&&!G.has(I)){h("info",z,"re-verifying membership for unknown channel before skip",{channelId:I,seq:C});try{let Y=await F();J=Promise.resolve(Y),q=Z,he=Y.has(I),he?h("info",z,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:I,seq:C}):G.add(I)}catch(Y){S(z,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",Y)}}if(!he){h("debug",z,"skip not-a-member channel",{channelId:I,seq:C,topic:v.topic}),Q(r,"skip",{reason:"not_a_member",channel_id:I,seq:C,topic:v.topic});return}if(N.sender_id&&N.sender_id===r){h("debug",z,"skip self-authored message (pre-fetch)",{seq:C,sender_id:N.sender_id}),Q(r,"skip",{reason:"self_authored_prefetch",channel_id:I,seq:C,message_id:B??null});return}let $,vt;if(v.topic==="thread.reply"){if(!W){h("warn",z,"thread.reply event missing parent_message_id",{payload:N});return}if(!e.getThreadReplies){h("warn",z,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:I,messageSeq:C});return}try{let Y=(BigInt(C)>31n?BigInt(C)-31n:0n).toString(),Ce=await e.getThreadReplies(r,W,50,Y);vt=Ce,$=B&&Ce.find(Re=>Re.id===B)||Ce.find(Re=>Re.seq===C),$&&!$.parent_message_id&&($={...$,parent_message_id:W})}catch(Y){S(z,"failed to fetch thread replies after thread.reply event",Y);return}}else{let Y=(BigInt(C)-1n).toString();try{$=(await _(o,I,Y,1)).messages.find(Re=>Re.seq===C)}catch(Ce){S(z,"failed to fetch message after message.created event",Ce);return}}if(!$){h("warn",z,"message not found in GET response",{channelId:I,messageSeq:C,topic:v.topic});return}if($.sender_id===r){h("debug",z,"skip self-authored message",{seq:C,sender_id:$.sender_id}),Q(r,"skip",{reason:"self_authored",channel_id:I,seq:C,message_id:$.id});return}let Ie=su($.content,s,i),Pt=!!$.parent_message_id;if($.sender_kind==="system"&&!p.deliverSystemMessages){h("debug",z,"skip system message by context policy",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"context_policy_system_message",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}let ot=N.wake_agent_ids;if(!Pt&&$.sender_kind!=="system"){if(Array.isArray(ot)){if(!(ot.includes(r)||Ie)){h("debug",z,"skip: not in server wake set",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"not_in_wake_set",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}}else if(!p.deliverBroadcastMessages&&!Ie){h("debug",z,"skip broadcast message by context policy",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"context_policy_broadcast_message",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}}if(Pt&&$.sender_kind!=="system"&&Array.isArray(ot)){if(!(ot.includes(r)||Ie)){h("debug",z,"skip thread reply: not in server wake set",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"thread_not_in_wake_set",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}}else if(Pt&&$.sender_kind!=="system"&&!p.deliverThreadBroadcastMessages&&!Ie){h("debug",z,"skip thread broadcast message by context policy",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}let We;try{We=await L(I)}catch(Y){S(z,"failed to resolve channel name \u2014 dropping message",Y);return}if(!We){h("warn",z,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:I,messageSeq:C});return}let Ne;if($.parent_message_id){let Y,Ce=[],Re=!1;if(e.getMessageById)try{Y=await e.getMessageById(r,$.parent_message_id)}catch(Ze){Re=!0,h("warn",z,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:$.parent_message_id,err:Ze instanceof Error?Ze.message:String(Ze)})}else Re=!0;if(vt&&$.parent_message_id===W)Ce=vt.slice(0,p.threadReplyLimit);else if(e.getThreadReplies)try{Ce=await e.getThreadReplies(r,$.parent_message_id,p.threadReplyLimit)}catch(Ze){Re=!0,h("warn",z,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:$.parent_message_id,err:Ze instanceof Error?Ze.message:String(Ze)})}else Re=!0;Ne=t_($,Y,Ce,We),Re&&h("info",z,"thread context degraded (parent or replies missing)",{channelId:I,parent_message_id:$.parent_message_id})}else Ne=cs($,We);let nr=$.parent_message_id?[{name:"thread_context",bytes:Ne.length,reply_limit:p.threadReplyLimit},{name:"incoming",bytes:$.content.length}]:[{name:"inbound_message",bytes:Ne.length}];if(Q(r,"context_injection",{topic:v.topic,channel_id:I,channel_name:We,message_id:$.id,parent_message_id:$.parent_message_id??null,sender_kind:$.sender_kind,mode:$.parent_message_id?"thread":"main",explicitly_mentioned:Ie,policy:{deliver_broadcast_messages:p.deliverBroadcastMessages,deliver_system_messages:p.deliverSystemMessages,deliver_thread_broadcast_messages:p.deliverThreadBroadcastMessages,thread_reply_limit:p.threadReplyLimit},sections:nr,rendered_bytes:Ne.length}),!$.parent_message_id&&$.sender_kind!=="system"&&Array.isArray(N.wake_agent_ids)&&N.wake_agent_ids.includes(r)&&!Ie&&(Ne+=`
490
+ `)}let _=a??e.getChannelMessages.bind(e),k=new Map;async function P(v){let N=await e.getWorkroomChannels(o);for(let I of N)I.id&&I.name&&k.set(I.id,I.name);return k.get(v)}let T=c??P;async function L(v){let N=k.get(v);if(N!==void 0)return N;let I=await T(v);return I!==void 0&&k.set(v,I),I}let F=d??(async()=>new Set((await e.getAgentChannels(r)).map(v=>v.id))),J=null,G=new Set,Z=250,ne=5e3,q=Z,ie=v=>new Promise(N=>{let I=setTimeout(N,v);typeof I.unref=="function"&&I.unref()});function oe(){let v=F().then(N=>(q=Z,N)).catch(N=>{S(z,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",N);let I=q;return q=Math.min(q*2,ne),J===v&&(J=ie(I).then(()=>(oe(),J??new Set))),new Set});J=v}let b=n.hostFor??(()=>t),R;t.onInjected(v=>{R?.(v)}),l&&(R=l);async function x(v){if(v.topic==="reminder.upserted"||v.topic==="reminder.canceled"){if(u){let Y=v.payload;if(v.topic==="reminder.upserted")if(Y.reminder){if(Y.reminder.agentId!==r)return;u.upsert(Y.reminder)}else h("warn",z,"reminder.upserted event missing reminder payload",{payload:v.payload});else if(Y.reminderId){if(Y.agentId!==r)return;u.cancel(Y.reminderId,Y.version)}else h("warn",z,"reminder.canceled event missing reminderId",{payload:v.payload})}return}if(v.topic==="channel.member_added"||v.topic==="channel.member_removed"||v.topic==="roster.member_added"||v.topic==="roster.member_removed"){let Y=v.payload;Y.member_id===r&&(h("info",z,"membership changed for self \u2014 invalidating membership cache",{topic:v.topic,channelId:Y.channel_id}),G.clear(),oe());return}if(v.topic!=="message.created"&&v.topic!=="thread.reply")return;let N=v.payload,I=N.channel_id,C=N.seq,B=N.message_id,W=N.parent_message_id;if(!I||!C){h("warn",z,"message.created event missing channel_id or seq",{payload:N});return}Q(r,"event_received",{topic:v.topic,channel_id:I,seq:C,message_id:B??null,parent_message_id:W??null});let he=(await(J??Promise.resolve(new Set))).has(I);if(!he&&!G.has(I)){h("info",z,"re-verifying membership for unknown channel before skip",{channelId:I,seq:C});try{let Y=await F();J=Promise.resolve(Y),q=Z,he=Y.has(I),he?h("info",z,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:I,seq:C}):G.add(I)}catch(Y){S(z,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",Y)}}if(!he){h("debug",z,"skip not-a-member channel",{channelId:I,seq:C,topic:v.topic}),Q(r,"skip",{reason:"not_a_member",channel_id:I,seq:C,topic:v.topic});return}if(N.sender_id&&N.sender_id===r){h("debug",z,"skip self-authored message (pre-fetch)",{seq:C,sender_id:N.sender_id}),Q(r,"skip",{reason:"self_authored_prefetch",channel_id:I,seq:C,message_id:B??null});return}let $,vt;if(v.topic==="thread.reply"){if(!W){h("warn",z,"thread.reply event missing parent_message_id",{payload:N});return}if(!e.getThreadReplies){h("warn",z,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:I,messageSeq:C});return}try{let Y=(BigInt(C)>31n?BigInt(C)-31n:0n).toString(),Re=await e.getThreadReplies(r,W,50,Y);vt=Re,$=B&&Re.find(Ae=>Ae.id===B)||Re.find(Ae=>Ae.seq===C),$&&!$.parent_message_id&&($={...$,parent_message_id:W})}catch(Y){S(z,"failed to fetch thread replies after thread.reply event",Y);return}}else{let Y=(BigInt(C)-1n).toString();try{$=(await _(o,I,Y,1)).messages.find(Ae=>Ae.seq===C)}catch(Re){S(z,"failed to fetch message after message.created event",Re);return}}if(!$){h("warn",z,"message not found in GET response",{channelId:I,messageSeq:C,topic:v.topic});return}if($.sender_id===r){h("debug",z,"skip self-authored message",{seq:C,sender_id:$.sender_id}),Q(r,"skip",{reason:"self_authored",channel_id:I,seq:C,message_id:$.id});return}let Ne=ou($.content,s,i),Pt=!!$.parent_message_id;if($.sender_kind==="system"&&!p.deliverSystemMessages){h("debug",z,"skip system message by context policy",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"context_policy_system_message",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}let ot=N.wake_agent_ids;if(!Pt&&$.sender_kind!=="system"){if(Array.isArray(ot)){if(!(ot.includes(r)||Ne)){h("debug",z,"skip: not in server wake set",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"not_in_wake_set",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}}else if(!p.deliverBroadcastMessages&&!Ne){h("debug",z,"skip broadcast message by context policy",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"context_policy_broadcast_message",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}}if(Pt&&$.sender_kind!=="system"&&Array.isArray(ot)){if(!(ot.includes(r)||Ne)){h("debug",z,"skip thread reply: not in server wake set",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"thread_not_in_wake_set",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}}else if(Pt&&$.sender_kind!=="system"&&!p.deliverThreadBroadcastMessages&&!Ne){h("debug",z,"skip thread broadcast message by context policy",{seq:C,message_id:$.id}),Q(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:I,seq:C,message_id:$.id}),_t(r,I,$.seq);return}let We;try{We=await L(I)}catch(Y){S(z,"failed to resolve channel name \u2014 dropping message",Y);return}if(!We){h("warn",z,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:I,messageSeq:C});return}let Me;if($.parent_message_id){let Y,Re=[],Ae=!1;if(e.getMessageById)try{Y=await e.getMessageById(r,$.parent_message_id)}catch(Ze){Ae=!0,h("warn",z,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:$.parent_message_id,err:Ze instanceof Error?Ze.message:String(Ze)})}else Ae=!0;if(vt&&$.parent_message_id===W)Re=vt.slice(0,p.threadReplyLimit);else if(e.getThreadReplies)try{Re=await e.getThreadReplies(r,$.parent_message_id,p.threadReplyLimit)}catch(Ze){Ae=!0,h("warn",z,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:$.parent_message_id,err:Ze instanceof Error?Ze.message:String(Ze)})}else Ae=!0;Me=s_($,Y,Re,We),Ae&&h("info",z,"thread context degraded (parent or replies missing)",{channelId:I,parent_message_id:$.parent_message_id})}else Me=ls($,We);let rr=$.parent_message_id?[{name:"thread_context",bytes:Me.length,reply_limit:p.threadReplyLimit},{name:"incoming",bytes:$.content.length}]:[{name:"inbound_message",bytes:Me.length}];if(Q(r,"context_injection",{topic:v.topic,channel_id:I,channel_name:We,message_id:$.id,parent_message_id:$.parent_message_id??null,sender_kind:$.sender_kind,mode:$.parent_message_id?"thread":"main",explicitly_mentioned:Ne,policy:{deliver_broadcast_messages:p.deliverBroadcastMessages,deliver_system_messages:p.deliverSystemMessages,deliver_thread_broadcast_messages:p.deliverThreadBroadcastMessages,thread_reply_limit:p.threadReplyLimit},sections:rr,rendered_bytes:Me.length}),!$.parent_message_id&&$.sender_kind!=="system"&&Array.isArray(N.wake_agent_ids)&&N.wake_agent_ids.includes(r)&&!Ne&&(Me+=`
491
491
 
492
- [routing] No teammate was @-named in this message \u2014 you have been chosen to handle it. Answer it directly. If it truly belongs to another teammate's role, hand it off by @-mentioning them in one short line instead.`),Ne+=await w($),!$.parent_message_id&&$.sender_kind!=="system"&&(Ne+=`
493
- (\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${We}" \u2014\u2014 \u4F60\u7684\u7EAF\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u9001\u8FBE\u4EFB\u4F55\u4EBA)`),b(I).enqueueUserTurn(Ne),f&&$.sender_kind!=="system")try{f.set(r,$.id)}catch(Y){S(z,"contextTracker.set threw (non-fatal)",Y)}if(m)try{m(I)}catch(Y){S(z,"onInboundMessage callback threw (non-fatal)",Y)}_t(r,I,$.seq),h("info",z,"enqueued inbound message",{channelId:I,channelName:We,seq:$.seq,sender_id:$.sender_id}),Q(r,"inbound",{topic:v.topic,channel_id:I,channel_name:We,seq:$.seq,message_id:$.id,message_id_short:$.id.replace(/-/g,"").slice(0,8),parent_message_id:$.parent_message_id??null,sender_id:$.sender_id,sender_kind:$.sender_kind,sender_display_name:$.sender_display_name??null,content_preview:$.content.slice(0,120),rendered_bytes:Ne.length})}let A=v=>x(v).catch(N=>{S(z,"unhandled error in handleEvent",N)});return{start(){ie(),e.subscribe(o,A),h("info",z,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,A),h("info",z,"InboxCoordinator stopped",{workroomId:o})},onInjected(v){R=v}}}var z,au=O(()=>{"use strict";qi();le();Rt();as();z="inboxDelivery"});var cu,ds,du=O(()=>{"use strict";le();cu="typingNotifier",ds=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",cu,"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",cu,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var Zn,ls,lu=O(()=>{"use strict";le();Rt();Zn="agentPresence",ls=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",Zn,"presence transition deduped",{agentId:e,state:t,channelId:r});return}if(this.current.set(e,t),h("info",Zn,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),Q(e,"presence",{state:t,prev:s??null,channel_id:r??null}),!this.gateway.notifyAgentStatus){h("warn",Zn,"gateway.notifyAgentStatus MISSING \u2014 presence not sent to server",{agentId:e,state:t});return}h("debug",Zn,"notifyAgentStatus \u2192",{agentId:e,state:t}),this.gateway.notifyAgentStatus(e,r,t).catch(i=>{h("warn",Zn,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function uu(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,f=i.get(d);f!==void 0&&f>=m||(i.set(d,m),Promise.resolve().then(()=>t(u.reminder)).catch(p=>{S(n_,`onFire callback failed for reminder ${d} (agent ${e})`,p)}))}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),f=r(),p=Math.max(0,m-f);if(m<=f){s.set(d.id,{reminder:d,timer:null}),c(d.id);return}let g=setTimeout(()=>c(d.id),p);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 n_,fu=O(()=>{"use strict";le();n_="reminderCache"});function hu(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",Yi,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),Q(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",Yi,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),h("debug",Yi,"context get expired",{agentId:r,messageId:s.id}),Q(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var Yi,pu=O(()=>{"use strict";le();Rt();Yi="contextTracker"});import{readFileSync as r_,writeFileSync as s_,existsSync as i_,mkdirSync as o_}from"fs";import{dirname as a_}from"path";function mu(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function yu(){return{version:1,entities:{},relations:{},observations:[],obs_seq:0}}function Vi(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 gu,us,_u=O(()=>{"use strict";gu=500;us=class{constructor(e){this.path=e;if(i_(e))try{let t=r_(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=yu()}else this.file=yu(),o_(a_(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[mu(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[mu(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>gu&&this.file.observations.splice(0,this.file.observations.length-gu),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&&(s_(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 Qe(n){return n.replace(/-/g,"").slice(0,8)}function vn(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+Qe(e)}function er(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+Qe(e)}function wu(n){let{subscribe:e,unsubscribe:t,host:r,hostFor:s,selfAgentId:i,workroomId:o,companion:a,quietSeconds:c,maxRepliesPerWindow:l,windowSeconds:d,contextPolicy:u=Qn,now:m=()=>Date.now()}=n,f=[],p=new Map,g=3e4,y=new Set;function E(b=m()){f.push(b);let R=b-d*1e3;for(;f.length>0&&f[0]<R;)f.shift()}function w(b){return f.length===0?Number.POSITIVE_INFINITY:b-f[f.length-1]}function _(b){let R=b-d*1e3;for(;f.length>0&&f[0]<R;)f.shift();return f.length}function k(b){return b?a.listChannelMembers(b).some(x=>x.id===i):!1}function P(b){let R=m();for(let[x,A]of p)R-A>g&&p.delete(x);return p.has(b)?!1:(p.set(b,R),!0)}function T(b){return`assigned:${b}:${i}`}function L(b,R){let x=m(),A=w(x);if(A<c*1e3)return h("debug",it,"wake skipped: quiet_seconds gate",{reason:b,taskId:R,sinceMs:A,quietSeconds:c}),!1;let v=_(x);return v>=l?(h("debug",it,"wake skipped: max_replies_per_window gate",{reason:b,taskId:R,count:v,max:l,windowSeconds:d}),!1):!0}function F(b,R,x,A){h("info",it,"poking agent with system event",{reason:R,taskId:x,channelId:A}),Q(i,"wake",{reason:R,task_id:x,task_id_short:Qe(x),bytes:b.length}),(A&&s?s(A):r).enqueueUserTurn(b)}function J(b){let R=b.task_id,x=b.channel_id,A=b.title,v=b.created_by,N=b.owner_id??b.assignee_id;if(!R||v===i||N===i)return;if(!(u.wakeOnChannelTaskCreated&&k(x))){h("debug",it,"task.created not relevant \u2014 skip",{taskId:R});return}if(!P(`created:${R}`)||!L("task-created",R))return;let C=vn(a,v),B=er(a,x),W=`[system event: task #${Qe(R)} was just created in your channel ${B}]
492
+ [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.`),Me+=await w($),!$.parent_message_id&&$.sender_kind!=="system"&&(Me+=`
493
+ (\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${We}" \u2014\u2014 \u4F60\u7684\u7EAF\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u9001\u8FBE\u4EFB\u4F55\u4EBA)`),b(I).enqueueUserTurn(Me),f&&$.sender_kind!=="system")try{f.set(r,$.id)}catch(Y){S(z,"contextTracker.set threw (non-fatal)",Y)}if(m)try{m(I)}catch(Y){S(z,"onInboundMessage callback threw (non-fatal)",Y)}_t(r,I,$.seq),h("info",z,"enqueued inbound message",{channelId:I,channelName:We,seq:$.seq,sender_id:$.sender_id}),Q(r,"inbound",{topic:v.topic,channel_id:I,channel_name:We,seq:$.seq,message_id:$.id,message_id_short:$.id.replace(/-/g,"").slice(0,8),parent_message_id:$.parent_message_id??null,sender_id:$.sender_id,sender_kind:$.sender_kind,sender_display_name:$.sender_display_name??null,content_preview:$.content.slice(0,120),rendered_bytes:Me.length})}let A=v=>x(v).catch(N=>{S(z,"unhandled error in handleEvent",N)});return{start(){oe(),e.subscribe(o,A),h("info",z,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,A),h("info",z,"InboxCoordinator stopped",{workroomId:o})},onInjected(v){R=v}}}var z,lu=O(()=>{"use strict";Gi();de();Rt();cs();z="inboxDelivery"});var du,ds,uu=O(()=>{"use strict";de();du="typingNotifier",ds=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",du,"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",du,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var er,us,fu=O(()=>{"use strict";de();Rt();er="agentPresence",us=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",er,"presence transition deduped",{agentId:e,state:t,channelId:r});return}if(this.current.set(e,t),h("info",er,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),Q(e,"presence",{state:t,prev:s??null,channel_id:r??null}),!this.gateway.notifyAgentStatus){h("warn",er,"gateway.notifyAgentStatus MISSING \u2014 presence not sent to server",{agentId:e,state:t});return}h("debug",er,"notifyAgentStatus \u2192",{agentId:e,state:t}),this.gateway.notifyAgentStatus(e,r,t).catch(i=>{h("warn",er,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function hu(n){let{agentId:e,onFire:t,clock:r=()=>Date.now()}=n,s=new Map,i=new Map;function o(l){let u=s.get(l);u?.timer&&clearTimeout(u.timer),s.delete(l)}function a(){for(let l of s.values())l.timer&&clearTimeout(l.timer);s.clear()}function c(l){let u=s.get(l);if(!u)return;let m=u.reminder.version,f=i.get(l);f!==void 0&&f>=m||(i.set(l,m),Promise.resolve().then(()=>t(u.reminder)).catch(p=>{S(i_,`onFire callback failed for reminder ${l} (agent ${e})`,p)}))}function d(l){let u=s.get(l.id);if(u&&u.reminder.version>=l.version)return;u?.timer&&clearTimeout(u.timer);let m=Date.parse(l.fireAt),f=r(),p=Math.max(0,m-f);if(m<=f){s.set(l.id,{reminder:l,timer:null}),c(l.id);return}let g=setTimeout(()=>c(l.id),p);typeof g.unref=="function"&&g.unref(),s.set(l.id,{reminder:l,timer:g})}return{upsert:d,cancel(l,u){o(l)},snapshot(l){a();for(let u of l)d(u)},clear(){a()},stop(){a(),i.clear()}}}var i_,pu=O(()=>{"use strict";de();i_="reminderCache"});function gu(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",Vi,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),Q(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",Vi,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),h("debug",Vi,"context get expired",{agentId:r,messageId:s.id}),Q(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var Vi,mu=O(()=>{"use strict";de();Rt();Vi="contextTracker"});import{readFileSync as o_,writeFileSync as a_,existsSync as c_,mkdirSync as l_}from"fs";import{dirname as d_}from"path";function _u(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function wu(){return{version:1,entities:{},relations:{},observations:[],obs_seq:0}}function zi(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 yu,fs,vu=O(()=>{"use strict";yu=500;fs=class{constructor(e){this.path=e;if(c_(e))try{let t=o_(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=wu()}else this.file=wu(),l_(d_(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[_u(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[_u(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>yu&&this.file.observations.splice(0,this.file.observations.length-yu),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&&(a_(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 Qe(n){return n.replace(/-/g,"").slice(0,8)}function vn(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+Qe(e)}function tr(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+Qe(e)}function bu(n){let{subscribe:e,unsubscribe:t,host:r,hostFor:s,selfAgentId:i,workroomId:o,companion:a,quietSeconds:c,maxRepliesPerWindow:d,windowSeconds:l,contextPolicy:u=Zn,now:m=()=>Date.now()}=n,f=[],p=new Map,g=3e4,y=new Set;function E(b=m()){f.push(b);let R=b-l*1e3;for(;f.length>0&&f[0]<R;)f.shift()}function w(b){return f.length===0?Number.POSITIVE_INFINITY:b-f[f.length-1]}function _(b){let R=b-l*1e3;for(;f.length>0&&f[0]<R;)f.shift();return f.length}function k(b){return b?a.listChannelMembers(b).some(x=>x.id===i):!1}function P(b){let R=m();for(let[x,A]of p)R-A>g&&p.delete(x);return p.has(b)?!1:(p.set(b,R),!0)}function T(b){return`assigned:${b}:${i}`}function L(b,R){let x=m(),A=w(x);if(A<c*1e3)return h("debug",it,"wake skipped: quiet_seconds gate",{reason:b,taskId:R,sinceMs:A,quietSeconds:c}),!1;let v=_(x);return v>=d?(h("debug",it,"wake skipped: max_replies_per_window gate",{reason:b,taskId:R,count:v,max:d,windowSeconds:l}),!1):!0}function F(b,R,x,A){h("info",it,"poking agent with system event",{reason:R,taskId:x,channelId:A}),Q(i,"wake",{reason:R,task_id:x,task_id_short:Qe(x),bytes:b.length}),(A&&s?s(A):r).enqueueUserTurn(b)}function J(b){let R=b.task_id,x=b.channel_id,A=b.title,v=b.created_by,N=b.owner_id??b.assignee_id;if(!R||v===i||N===i)return;if(!(u.wakeOnChannelTaskCreated&&k(x))){h("debug",it,"task.created not relevant \u2014 skip",{taskId:R});return}if(!P(`created:${R}`)||!L("task-created",R))return;let C=vn(a,v),B=tr(a,x),W=`[system event: task #${Qe(R)} was just created in your channel ${B}]
494
494
  Title: ${A?`"${A}"`:"(no title)"}
495
495
  Created by ${C}.${N?` Assigned to ${vn(a,N)}.`:" No assignee yet."}
496
- You may want to volunteer for it, acknowledge, or skip.`;F(W,"task-created",R,x)}function G(b){let{taskId:R,channelId:x,parentMessageId:A,assignerId:v,reason:N,dedupeAlreadyReserved:I}=b;if(!I){if(y.has(T(R)))return h("debug",it,"assigned wake suppressed: boot-scoped self-heal reservation",{taskId:R,reason:N}),!1;if(!P(T(R)))return!1}if(!L(N,R))return!1;let C=er(a,x),B=v?` by ${vn(a,v)}`:"",W=A?`
496
+ You may want to volunteer for it, acknowledge, or skip.`;F(W,"task-created",R,x)}function G(b){let{taskId:R,channelId:x,parentMessageId:A,assignerId:v,reason:N,dedupeAlreadyReserved:I}=b;if(!I){if(y.has(T(R)))return h("debug",it,"assigned wake suppressed: boot-scoped self-heal reservation",{taskId:R,reason:N}),!1;if(!P(T(R)))return!1}if(!L(N,R))return!1;let C=tr(a,x),B=v?` by ${vn(a,v)}`:"",W=A?`
497
497
 
498
498
  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:
499
499
  mio message reply --parent ${A} --target ${C} <<'EOF'
500
500
  \u2026
501
501
  EOF
502
- If you are coordinating and need to split out separate independent work for another teammate, do that as a fresh main-channel one-line @handoff with \`mio message send\`; one main-channel @handoff per separate task.`:"",oe=`[system event: task #${Qe(R)} was assigned to you${B}]
502
+ 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.`:"",ae=`[system event: task #${Qe(R)} was assigned to you${B}]
503
503
  Channel: ${C}
504
- 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 #${Qe(R)} --status done\`. Briefly acknowledge then begin.`+W;return F(oe,N,R,x),!0}function Z(b){let R=b.task_id,x=b.channel_id,A=b.assignee_id,v=b.assigner_id,N=b.parent_message_id;if(R&&v!==i){if(A!==i){h("debug",it,"task.assigned not to self \u2014 skip",{taskId:R,assigneeId:A});return}G({taskId:R,channelId:x,parentMessageId:N,assignerId:v,reason:"task-assigned"})}}function ne(b){let R=b.task_id,x=b.channel_id,A=b.from,v=b.to,N=b.actor_id,I=b.assignee_id;if(!R||N===i)return;if(!(I===i||u.wakeOnChannelTaskStatus&&k(x))){h("debug",it,"task.status_changed not relevant \u2014 skip",{taskId:R});return}let B=b.review_verdict,W=b.review_feedback;if(B==="bounce"&&I===i){if(!P(`bounce:${R}`))return;let vt=vn(a,N),Ie=er(a,x),Pt=W&&W.trim()?W.trim():"(see the task thread)",ot=`[system event: your task #${Qe(R)} was BOUNCED back for rework by ${vt} after independent review]
505
- Channel: ${Ie}.
504
+ 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 #${Qe(R)} --status done\`. Briefly acknowledge then begin.`+W;return F(ae,N,R,x),!0}function Z(b){let R=b.task_id,x=b.channel_id,A=b.assignee_id,v=b.assigner_id,N=b.parent_message_id;if(R&&v!==i){if(A!==i){h("debug",it,"task.assigned not to self \u2014 skip",{taskId:R,assigneeId:A});return}G({taskId:R,channelId:x,parentMessageId:N,assignerId:v,reason:"task-assigned"})}}function ne(b){let R=b.task_id,x=b.channel_id,A=b.from,v=b.to,N=b.actor_id,I=b.assignee_id;if(!R||N===i)return;if(!(I===i||u.wakeOnChannelTaskStatus&&k(x))){h("debug",it,"task.status_changed not relevant \u2014 skip",{taskId:R});return}let B=b.review_verdict,W=b.review_feedback;if(B==="bounce"&&I===i){if(!P(`bounce:${R}`))return;let vt=vn(a,N),Ne=tr(a,x),Pt=W&&W.trim()?W.trim():"(see the task thread)",ot=`[system event: your task #${Qe(R)} was BOUNCED back for rework by ${vt} after independent review]
505
+ Channel: ${Ne}.
506
506
  Reviewer feedback: ${Pt}
507
- Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${Qe(R)} --channel ${Ie} --status done\` again \u2014 it auto-closes after this one rework, no second review. This is NOT optional; do not stay silent.`;F(ot,"task-bounce",R,x);return}if(!P(`status:${R}:${v}`)||!L("task-status",R))return;let oe=vn(a,N),he=er(a,x),$=`[system event: task #${Qe(R)} status changed from ${A??"?"} to ${v??"?"} by ${oe}]
507
+ Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${Qe(R)} --channel ${Ne} --status done\` again \u2014 it auto-closes after this one rework, no second review. This is NOT optional; do not stay silent.`;F(ot,"task-bounce",R,x);return}if(!P(`status:${R}:${v}`)||!L("task-status",R))return;let ae=vn(a,N),he=tr(a,x),$=`[system event: task #${Qe(R)} status changed from ${A??"?"} to ${v??"?"} by ${ae}]
508
508
  Channel: ${he}.
509
- Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;F($,"task-status",R,x)}function q(b){let R=b.task_id,x=b.channel_id,A=b.reviewer_id,v=b.owner_id,N=b.parent_message_id,I=b.title,C=b.number;if(!R)return;if(A!==i){h("debug",it,"review_requested not for self \u2014 skip",{taskId:R,reviewerId:A});return}if(!P(`review:${R}`))return;let B=vn(a,v),W=er(a,x),oe=C!==void 0?`#${C}`:`#${Qe(R)}`,he=N?`
509
+ Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;F($,"task-status",R,x)}function q(b){let R=b.task_id,x=b.channel_id,A=b.reviewer_id,v=b.owner_id,N=b.parent_message_id,I=b.title,C=b.number;if(!R)return;if(A!==i){h("debug",it,"review_requested not for self \u2014 skip",{taskId:R,reviewerId:A});return}if(!P(`review:${R}`))return;let B=vn(a,v),W=tr(a,x),ae=C!==void 0?`#${C}`:`#${Qe(R)}`,he=N?`
510
510
  Get the surrounding context, then inspect the ACTUAL deliverable (its files \u2014 build it, run its tests), not just the chat:
511
511
  mio message read --channel ${W} --around ${Qe(N)}
512
512
  Post your review findings in the task thread:
513
- mio message reply --parent ${N} --target ${W}`:"",$=`[system event: task ${oe} "${I??""}" by ${B} is awaiting YOUR independent review]
513
+ mio message reply --parent ${N} --target ${W}`:"",$=`[system event: task ${ae} "${I??""}" by ${B} is awaiting YOUR independent review]
514
514
  Channel: ${W}.${he}
515
515
 
516
516
  You are the INDEPENDENT reviewer. Do an adversarial / mutation audit of the ACTUAL deliverable \u2014 do not take the author's word that it works:
@@ -520,12 +520,12 @@ You are the INDEPENDENT reviewer. Do an adversarial / mutation audit of the ACTU
520
520
 
521
521
  Then submit your verdict:
522
522
  \u2022 Everything works AND every claimed feature has a test that fails when broken \u2192
523
- mio task review ${oe} --channel ${W} --pass
523
+ mio task review ${ae} --channel ${W} --pass
524
524
  \u2022 A feature is unprotected (mutation stayed green), or you found a real bug \u2192
525
- mio task review ${oe} --channel ${W} --bounce --feedback "<exactly what is untested/broken>"
526
- A bounce sends it back to ${B} to add the missing test/fix; after their rework it closes without a second review.`;F($,"task-review",R,x)}function se(b){b.sender_id===i&&E()}let ie=b=>{try{let R=b.payload??{};switch(b.topic){case"task.created":J(R);break;case"task.assigned":Z(R);break;case"task.status_changed":ne(R);break;case"task.review_requested":q(R);break;case"message.created":se(R);break;default:break}}catch(R){h("warn",it,"task wake handler error (non-fatal)",{err:String(R)})}};return{start(){e(o,ie),h("info",it,"task wake router started",{workroomId:o,selfAgentId:i,quietSeconds:c,maxRepliesPerWindow:l,windowSeconds:d})},stop(){try{t(o,ie)}catch{}},noteSelfPost:E,synthesizeAssignedWake(b){return b.task_id?G({taskId:b.task_id,channelId:b.channel_id,parentMessageId:b.parent_message_id,reason:"task-assigned-selfheal",dedupeAlreadyReserved:!0}):!1},reserveAssignedDedupeKeys(b){for(let R of b)R&&(P(T(R)),y.add(T(R)))}}}var it,vu=O(()=>{"use strict";le();Rt();as();it="taskWakeRouter"});import{spawn as c_}from"node:child_process";import{readFileSync as fs,writeFileSync as bu,existsSync as hs,renameSync as d_,statSync as l_,unlinkSync as u_}from"node:fs";import{join as ps}from"node:path";function Tu(n){let e=ps(n.mioDir,"persona-counter.json"),t=ps(n.mioDir,"persona.md"),r=t+".tmp",s=n.claudeCommand??_n()??"claude",i=!1,o=0,a=!1,c=l();function l(){if(hs(e))try{let p=fs(e,"utf8"),g=JSON.parse(p);if(g&&typeof g.messages_since_last_extract=="number")return{version:1,messages_since_last_extract:g.messages_since_last_extract,last_extract_at:g.last_extract_at??null}}catch{}return{version:1,messages_since_last_extract:0,last_extract_at:null}}function d(){try{bu(e,JSON.stringify(c,null,2),{encoding:"utf8",mode:384})}catch(p){S(ke,"persona-counter write failed (non-fatal)",p)}}function u(){let p=Date.now();if(i)return{go:!1,reason:"already running"};if(p-o<n.quietSeconds*1e3)return{go:!1,reason:"within quietSeconds"};if(c.messages_since_last_extract>=ku)return{go:!0,reason:`message threshold (${c.messages_since_last_extract})`};if(c.last_extract_at){let g=Date.parse(c.last_extract_at);if(!Number.isNaN(g)&&p-g>=f_)return{go:!0,reason:"elapsed 24h"}}return{go:!1,reason:"no trigger"}}async function m(p){if(!i&&!a){i=!0,o=Date.now();try{h("info",ke,"persona extraction starting",{agentId:n.agentId,reason:p});let g=[];if(n.channelId)try{g=(await n.gateway.getChannelMessages(n.workroomId,n.channelId,void 0,Eu)).messages.slice(-Eu).map(J=>({sender:J.sender_display_name||`${J.sender_kind}:${J.sender_id.slice(0,8)}`,content:J.content,at:J.created_at}))}catch(L){S(ke,"getChannelMessages failed (continuing with empty messages)",L)}let y=[];try{let L=ps(n.mioDir,"companion.json");if(hs(L)){let F=fs(L,"utf8"),J=JSON.parse(F);y=(Array.isArray(J.observations)?J.observations:[]).slice(-h_)}}catch(L){S(ke,"companion.json read failed (continuing without observations)",L)}let E=[];try{n.channelId&&(E=n.companion.listChannelMembers(n.channelId).map(L=>({id:L.id,name:L.display_name??L.id,role:L.role??"",description:L.description??""}))),E.length===0&&(E=n.companion.listWorkroomEntities(n.workroomId).map(L=>({id:L.id,name:L.display_name??L.id,role:L.role??"",description:L.description??""})))}catch(L){S(ke,"roster derivation failed",L)}let w="";if(hs(t))try{w=fs(t,"utf8")}catch{}let _=p_(n.displayName,n.handle,n.role),k=g_({existingPersona:w,messages:g,observations:y,roster:E}),P=await m_(s,_,k,n.workspace,n.spawnEnv);if(!P||P.trim().length===0){h("warn",ke,"persona extraction produced empty output (keeping prior persona)",{agentId:n.agentId});return}let T=P.trim();T.startsWith("<!-- mio:persona v1 -->")||(T=`<!-- mio:persona v1 -->
525
+ mio task review ${ae} --channel ${W} --bounce --feedback "<exactly what is untested/broken>"
526
+ A bounce sends it back to ${B} to add the missing test/fix; after their rework it closes without a second review.`;F($,"task-review",R,x)}function ie(b){b.sender_id===i&&E()}let oe=b=>{try{let R=b.payload??{};switch(b.topic){case"task.created":J(R);break;case"task.assigned":Z(R);break;case"task.status_changed":ne(R);break;case"task.review_requested":q(R);break;case"message.created":ie(R);break;default:break}}catch(R){h("warn",it,"task wake handler error (non-fatal)",{err:String(R)})}};return{start(){e(o,oe),h("info",it,"task wake router started",{workroomId:o,selfAgentId:i,quietSeconds:c,maxRepliesPerWindow:d,windowSeconds:l})},stop(){try{t(o,oe)}catch{}},noteSelfPost:E,synthesizeAssignedWake(b){return b.task_id?G({taskId:b.task_id,channelId:b.channel_id,parentMessageId:b.parent_message_id,reason:"task-assigned-selfheal",dedupeAlreadyReserved:!0}):!1},reserveAssignedDedupeKeys(b){for(let R of b)R&&(P(T(R)),y.add(T(R)))}}}var it,ku=O(()=>{"use strict";de();Rt();cs();it="taskWakeRouter"});import{spawn as u_}from"node:child_process";import{readFileSync as hs,writeFileSync as Su,existsSync as ps,renameSync as f_,statSync as h_,unlinkSync as p_}from"node:fs";import{join as gs}from"node:path";function Ru(n){let e=gs(n.mioDir,"persona-counter.json"),t=gs(n.mioDir,"persona.md"),r=t+".tmp",s=n.claudeCommand??_n()??"claude",i=!1,o=0,a=!1,c=d();function d(){if(ps(e))try{let p=hs(e,"utf8"),g=JSON.parse(p);if(g&&typeof g.messages_since_last_extract=="number")return{version:1,messages_since_last_extract:g.messages_since_last_extract,last_extract_at:g.last_extract_at??null}}catch{}return{version:1,messages_since_last_extract:0,last_extract_at:null}}function l(){try{Su(e,JSON.stringify(c,null,2),{encoding:"utf8",mode:384})}catch(p){S(ke,"persona-counter write failed (non-fatal)",p)}}function u(){let p=Date.now();if(i)return{go:!1,reason:"already running"};if(p-o<n.quietSeconds*1e3)return{go:!1,reason:"within quietSeconds"};if(c.messages_since_last_extract>=Eu)return{go:!0,reason:`message threshold (${c.messages_since_last_extract})`};if(c.last_extract_at){let g=Date.parse(c.last_extract_at);if(!Number.isNaN(g)&&p-g>=g_)return{go:!0,reason:"elapsed 24h"}}return{go:!1,reason:"no trigger"}}async function m(p){if(!i&&!a){i=!0,o=Date.now();try{h("info",ke,"persona extraction starting",{agentId:n.agentId,reason:p});let g=[];if(n.channelId)try{g=(await n.gateway.getChannelMessages(n.workroomId,n.channelId,void 0,Tu)).messages.slice(-Tu).map(J=>({sender:J.sender_display_name||`${J.sender_kind}:${J.sender_id.slice(0,8)}`,content:J.content,at:J.created_at}))}catch(L){S(ke,"getChannelMessages failed (continuing with empty messages)",L)}let y=[];try{let L=gs(n.mioDir,"companion.json");if(ps(L)){let F=hs(L,"utf8"),J=JSON.parse(F);y=(Array.isArray(J.observations)?J.observations:[]).slice(-m_)}}catch(L){S(ke,"companion.json read failed (continuing without observations)",L)}let E=[];try{n.channelId&&(E=n.companion.listChannelMembers(n.channelId).map(L=>({id:L.id,name:L.display_name??L.id,role:L.role??"",description:L.description??""}))),E.length===0&&(E=n.companion.listWorkroomEntities(n.workroomId).map(L=>({id:L.id,name:L.display_name??L.id,role:L.role??"",description:L.description??""})))}catch(L){S(ke,"roster derivation failed",L)}let w="";if(ps(t))try{w=hs(t,"utf8")}catch{}let _=y_(n.displayName,n.handle,n.role),k=__({existingPersona:w,messages:g,observations:y,roster:E}),P=await w_(s,_,k,n.workspace,n.spawnEnv);if(!P||P.trim().length===0){h("warn",ke,"persona extraction produced empty output (keeping prior persona)",{agentId:n.agentId});return}let T=P.trim();T.startsWith("<!-- mio:persona v1 -->")||(T=`<!-- mio:persona v1 -->
527
527
 
528
- ${T}`),T=y_(T);try{bu(r,T,{encoding:"utf8",mode:384}),d_(r,t)}catch(L){S(ke,"persona.md atomic write failed",L);try{u_(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),d(),h("info",ke,"persona extraction completed",{agentId:n.agentId,bytes:T.length,reason:p})}catch(g){S(ke,"persona extraction failed (keeping prior persona)",g)}finally{i=!1}}}function f(p){let{go:g,reason:y}=u();if(!g){h("debug",ke,"extraction skipped",{agentId:n.agentId,reason:p,gate:y});return}m(p)}return{noteMessage(){a||(c.messages_since_last_extract+=1,d(),c.messages_since_last_extract>=ku&&f("threshold"))},kick(p="kick"){if(a)return;let g=Date.now();if(i){h("debug",ke,"kick ignored: already running",{agentId:n.agentId});return}if(g-o<n.quietSeconds*1e3){h("debug",ke,"kick ignored: within quietSeconds",{agentId:n.agentId});return}m(p)},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}).
528
+ ${T}`),T=v_(T);try{Su(r,T,{encoding:"utf8",mode:384}),f_(r,t)}catch(L){S(ke,"persona.md atomic write failed",L);try{p_(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),l(),h("info",ke,"persona extraction completed",{agentId:n.agentId,bytes:T.length,reason:p})}catch(g){S(ke,"persona extraction failed (keeping prior persona)",g)}finally{i=!1}}}function f(p){let{go:g,reason:y}=u();if(!g){h("debug",ke,"extraction skipped",{agentId:n.agentId,reason:p,gate:y});return}m(p)}return{noteMessage(){a||(c.messages_since_last_extract+=1,l(),c.messages_since_last_extract>=Eu&&f("threshold"))},kick(p="kick"){if(a)return;let g=Date.now();if(i){h("debug",ke,"kick ignored: already running",{agentId:n.agentId});return}if(g-o<n.quietSeconds*1e3){h("debug",ke,"kick ignored: within quietSeconds",{agentId:n.agentId});return}m(p)},stop(){a=!0}}}function y_(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}).
529
529
 
530
530
  Below you'll see:
531
531
  - The agent's existing persona.md (their cumulative knowledge so far)
@@ -551,26 +551,26 @@ Constraints:
551
551
  - NEVER include UUIDs, internal IDs, mio CLI commands, or implementation details
552
552
  - NEVER include speculation; only facts you can point to evidence for
553
553
 
554
- Output the persona.md now.`}function g_(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(`
555
- `)}function m_(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=c_(n,o,{cwd:r,env:a,stdio:["pipe","pipe","pipe"]}),m=setTimeout(()=>{if(!d){d=!0;try{u.kill("SIGTERM")}catch{}S(ke,"one-shot claude timed out",{timeoutMs:Su,stderrSnippet:l.slice(0,200)}),i("")}},Su);m.unref?.(),u.stdout?.on("data",f=>{c+=typeof f=="string"?f:f.toString("utf8")}),u.stderr?.on("data",f=>{l+=typeof f=="string"?f:f.toString("utf8")}),u.on("error",f=>{d||(d=!0,clearTimeout(m),S(ke,"one-shot claude spawn error",f),i(""))}),u.on("exit",f=>{if(!d){if(d=!0,clearTimeout(m),f!==0){h("warn",ke,"one-shot claude exited non-zero",{code:f,stderrSnippet:l.slice(0,400),stdoutSnippet:c.slice(0,400)}),i("");return}i(c)}});try{u.stdin?.write(t),u.stdin?.end()}catch(f){S(ke,"one-shot claude stdin write failed",f)}})}function y_(n){if(n.length<=xu)return n;let e=n.split(`
556
- `),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(p=>d.header.includes(p)),f=i.findIndex(p=>u.header.includes(p));return(m===-1?99:m)-(f===-1?99:f)}),a=[...r],c=xu-a.join(`
557
- `).length,l=new Set;for(let d of o){let u=d.header.length+1+d.body.join(`
558
- `).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(`
554
+ Output the persona.md now.`}function __(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(`
555
+ `)}function w_(n,e,t,r,s){return new Promise(i=>{let o=["-p","--output-format","text","--append-system-prompt",e,"--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--permission-mode","bypassPermissions","--setting-sources","project,local"],a={...s??process.env};delete a.CLAUDECODE;let c="",d="",l=!1,u=u_(n,o,{cwd:r,env:a,stdio:["pipe","pipe","pipe"]}),m=setTimeout(()=>{if(!l){l=!0;try{u.kill("SIGTERM")}catch{}S(ke,"one-shot claude timed out",{timeoutMs:xu,stderrSnippet:d.slice(0,200)}),i("")}},xu);m.unref?.(),u.stdout?.on("data",f=>{c+=typeof f=="string"?f:f.toString("utf8")}),u.stderr?.on("data",f=>{d+=typeof f=="string"?f:f.toString("utf8")}),u.on("error",f=>{l||(l=!0,clearTimeout(m),S(ke,"one-shot claude spawn error",f),i(""))}),u.on("exit",f=>{if(!l){if(l=!0,clearTimeout(m),f!==0){h("warn",ke,"one-shot claude exited non-zero",{code:f,stderrSnippet:d.slice(0,400),stdoutSnippet:c.slice(0,400)}),i("");return}i(c)}});try{u.stdin?.write(t),u.stdin?.end()}catch(f){S(ke,"one-shot claude stdin write failed",f)}})}function v_(n){if(n.length<=Cu)return n;let e=n.split(`
556
+ `),t=[],r=[],s=null;for(let l of e)l.startsWith("## ")?(s&&t.push(s),s={header:l,body:[]}):s?s.body.push(l):r.push(l);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((l,u)=>{let m=i.findIndex(p=>l.header.includes(p)),f=i.findIndex(p=>u.header.includes(p));return(m===-1?99:m)-(f===-1?99:f)}),a=[...r],c=Cu-a.join(`
557
+ `).length,d=new Set;for(let l of o){let u=l.header.length+1+l.body.join(`
558
+ `).length+1;u<=c&&(d.add(l),c-=u)}for(let l of t)d.has(l)&&(a.push(l.header),a.push(...l.body));return a.join(`
559
559
  `).trim()+`
560
- `}function Cu(n){let e=ps(n,"persona.md");if(!hs(e))return null;try{let t=l_(e);if(!t.isFile()||t.size===0)return null;let s=fs(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var ke,ku,f_,Su,Eu,h_,xu,Ru=O(()=>{"use strict";ss();le();ke="personaCrystallizer",ku=50,f_=1440*60*1e3,Su=6e4,Eu=50,h_=50;xu=4e3});var Du={};$e(Du,{bootAgentSpine:()=>$u,deriveAgentWorkspace:()=>Mu,normalizeRuntime:()=>Lu,runDaemon:()=>Qi,snapshotLiveSessions:()=>Xi,startAgentSpine:()=>Iu});import{join as Pe,dirname as __}from"path";import{fileURLToPath as w_}from"url";import{homedir as v_,hostname as Au,arch as b_}from"os";import{unlink as k_,writeFile as Ou,mkdir as Ki,readdir as S_,copyFile as E_,readFile as x_}from"fs/promises";import{readFileSync as T_}from"node:fs";import{existsSync as C_}from"fs";import{spawnSync as R_}from"child_process";import{randomUUID as gs}from"crypto";function Xi(){return[...tr.values()]}async function Iu(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:f,model:p,runtime:g="claude",reasoningEffort:y,contextTracker:E,presenceTracker:w,contextPolicy:_}=n,k=n.execContext??Wi(),P=_??ru({role:d,displayName:c,description:l,capabilities:n.serverCapabilities}),T=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:L,spawnEnv:F,proxyHandle:J}=await Nl({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:T,execContext:k,...E?{contextTracker:E}:{}}),G=null,Z=Pe(L,"companion.json"),ne=new us(Z),q=null,se=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{q=await s.getWorkroomRoster(se),Vi(ne,q),h("info",D,"CompanionGraph hydrated from roster",{agentId:i,channels:q.channels.length,members:q.members.length})}catch(x){S(D,"CompanionGraph hydrate failed (continuing with empty graph)",x)}let ie;if(q){let A=q.channels.filter(v=>v.member_ids.includes(i))[0]??q.channels[0];if(A){let v=new Map(q.members.map(B=>[B.id,B])),N=A.member_ids.map(B=>v.get(B)).filter(B=>!!B),I=new Set(A.member_ids),C=q.members.filter(B=>!I.has(B.id));ie={channelId:A.id,channelName:A.name,inChannel:N,otherInWorkroom:C}}}try{let Ne=function(){try{let M=T_(Pe(r,"MEMORY.md"),"utf-8").trim();return M?`
560
+ `}function Au(n){let e=gs(n,"persona.md");if(!ps(e))return null;try{let t=h_(e);if(!t.isFile()||t.size===0)return null;let s=hs(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var ke,Eu,g_,xu,Tu,m_,Cu,Ou=O(()=>{"use strict";is();de();ke="personaCrystallizer",Eu=50,g_=1440*60*1e3,xu=6e4,Tu=50,m_=50;Cu=4e3});var Uu={};$e(Uu,{bootAgentSpine:()=>Bu,deriveAgentWorkspace:()=>$u,normalizeRuntime:()=>Du,runDaemon:()=>Zi,snapshotLiveSessions:()=>Qi,startAgentSpine:()=>Mu});import{join as Ie,dirname as b_}from"path";import{fileURLToPath as k_}from"url";import{homedir as S_,hostname as Pu,arch as E_}from"os";import{unlink as x_,writeFile as Iu,mkdir as Xi,readdir as T_,copyFile as C_,readFile as R_}from"fs/promises";import{readFileSync as A_}from"node:fs";import{existsSync as O_}from"fs";import{spawnSync as P_}from"child_process";import{randomUUID as ms}from"crypto";function Qi(){return[...nr.values()]}async function Mu(n){let{config:e,machineToken:t,workingDirectory:r,gateway:s,agentId:i,launchId:o,agentHandle:a,displayName:c,description:d,role:l,spawnFn:u,claudeCommand:m,codexCommand:f,model:p,runtime:g="claude",reasoningEffort:y,contextTracker:E,presenceTracker:w,contextPolicy:_}=n,k=n.execContext??ji(),P=_??iu({role:l,displayName:c,description:d,capabilities:n.serverCapabilities}),T=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:L,spawnEnv:F,proxyHandle:J}=await Ld({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:T,execContext:k,...E?{contextTracker:E}:{}}),G=null,Z=Ie(L,"companion.json"),ne=new fs(Z),q=null,ie=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{q=await s.getWorkroomRoster(ie),zi(ne,q),h("info",D,"CompanionGraph hydrated from roster",{agentId:i,channels:q.channels.length,members:q.members.length})}catch(x){S(D,"CompanionGraph hydrate failed (continuing with empty graph)",x)}let oe;if(q){let A=q.channels.filter(v=>v.member_ids.includes(i))[0]??q.channels[0];if(A){let v=new Map(q.members.map(B=>[B.id,B])),N=A.member_ids.map(B=>v.get(B)).filter(B=>!!B),I=new Set(A.member_ids),C=q.members.filter(B=>!I.has(B.id));oe={channelId:A.id,channelName:A.name,inChannel:N,otherInWorkroom:C}}}try{let Me=function(){try{let M=A_(Ie(r,"MEMORY.md"),"utf-8").trim();return M?`
561
561
 
562
562
  [\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]
563
563
  ${M.length>6e3?M.slice(0,6e3)+`
564
- \u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:M}`:""}catch{return""}},nr=function(M){let V=Ql(L,g,M);h("info",D,V?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:g,channelId:M,...V?{sessionId:V}:{}});let bt=Pt(M),Me={workingDirectory:r,systemPromptPath:v,mcpConfigPath:N,spawnEnv:F,firstTurnText:V?I:I+Ne(),...V?{sessionId:V}:{},...u?{spawnFn:u}:{},...bt?{presenceTracker:bt,agentId:i}:{}},ve=g==="codex"?zl({...Me,model:p??"gpt-5-codex",...y?{reasoningEffort:y}:{},...f?{codexCommand:f}:{}}):Gl({...Me,model:p??"sonnet",...m?{claudeCommand:m}:{}});ve.onSessionId(ae=>{h("info",D,"agent session id",{agentId:i,runtime:g,channelId:M,sessionId:ae}),Zl(L,g,ae,M)});let sr=`${i}:${M}`;return tr.set(sr,{agent_id:i,agent_name:c,channel_id:M,runtime:g,model:p??null,started_at:new Date().toISOString(),turns:0,input_tokens:0,output_tokens:0,cache_read_tokens:0}),ve.onTurnUsage?.(ae=>{let Le=tr.get(sr);Le&&(Le.turns+=1,Le.input_tokens+=ae.inputTokens,Le.output_tokens+=ae.outputTokens,Le.cache_read_tokens+=ae.cacheReadTokens,Le.last_turn_at=new Date().toISOString())}),ve.onInjected(ae=>{ae.includes("type=human]")&&sl(i,M);for(let Le of he)try{Le(ae)}catch{}}),ve.onBoundary(()=>{il(i,M)&&zt(e.server_url,C,M,{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:gs(),agentId:i},t).catch(ae=>S("run","silent-turn notice failed",ae));for(let ae of $)try{ae()}catch{}}),ve.onExit(ae=>{for(let Le of vt)try{Le(ae)}catch{}}),ve.onTurnError?.(ae=>{let Le=Date.now();if(ae===We&&Le-ot<6e4)return;We=ae,ot=Le;let cf=/usage limit/i.test(ae)?"\u7528\u91CF\u5DF2\u8FBE\u4E0A\u9650,\u8BF7\u5145\u503C\u6216\u7A0D\u540E\u518D\u8BD5":/unauthor|auth|401|403/i.test(ae)?"\u8BA4\u8BC1\u5931\u8D25,\u8BF7\u68C0\u67E5\u767B\u5F55/\u5BC6\u94A5":ae.slice(0,160);zt(e.server_url,C,M,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${cf})`,clientIdempotencyKey:gs(),agentId:i},t).catch(df=>S("run","post turn-error notice failed",df))}),ve.onCompact?.(()=>{zt(e.server_url,C,M,{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:gs(),agentId:i},t).catch(ae=>S("run","post compact notice failed",ae))}),ve.start(),ve};var b=Ne,R=nr;let x={agentId:i,handle:a,displayName:c,description:l,role:d,serverId:e.org_id,computer:`${Au()} (${e.machine_id})`,hostname:Au(),os:`${process.platform} ${b_()}`,workspace:r,runtime:g,capabilities:T,roster:ie,persona:Cu(L)??void 0},A=Bl(x),v=Pe(L,"system-prompt.md");if(await Ou(v,A,{encoding:"utf8",mode:384}),g==="claude")try{let M=Pe(r,".claude","skills");await Ki(M,{recursive:!0});let V=__(w_(import.meta.url)),bt=Pe(V,"..","..","runtimes","skills"),Me=(await S_(bt)).filter(ve=>ve.endsWith(".md"));for(let ve of Me){let sr=ve.replace(/\.md$/,""),ae=Pe(M,sr);await Ki(ae,{recursive:!0}),await E_(Pe(bt,ve),Pe(ae,"SKILL.md"))}h("info",D,"Materialised Claude skills",{count:Me.length,destRoot:M})}catch(M){S(D,"Failed to materialise Claude skills (continuing without)",M)}let N=Pe(L,"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.",C=e.autonomous_agent.workroom_id,B,W=q?.channels.find(M=>M.member_ids.includes(i))?.id,oe=new Map,he=[],$=[],vt=[],Ie=new Map,Pt=M=>{if(w)return{set:(V,bt)=>{Ie.set(M,bt);let Me=[...Ie.values()].some(ve=>ve!=="idle");w.set(V,Me?"thinking":"idle")}}},ot=0,We="",Y=M=>{let V=oe.get(M);return V||(V=nr(M),oe.set(M,V)),V};G={start(){},enqueueUserTurn(M){Y(B??W??"__default").enqueueUserTurn(M)},stop(){for(let M of oe.values())try{M.stop()}catch{}for(let M of oe.keys())tr.delete(`${i}:${M}`)},stopChannel(M){let V=oe.get(M);if(!V)return!1;try{V.stop()}catch{}return oe.delete(M),Ie.delete(M),tr.delete(`${i}:${M}`),!0},onBoundary(M){$.push(M)},onSessionId(M){},onExit(M){vt.push(M)},onInjected(M){he.push(M)},onTurnError(M){},onCompact(M){}},Y(W??"__default");let Ce=uu({agentId:i,onFire:async M=>{G.enqueueUserTurn(`[reminder fired] ${M.title}`);try{await s.reminderFire(i,M.id,M.version)}catch(V){S(D,`reminder report-fire failed (agent ${i}, reminder ${M.id}) \u2014 local wake already happened; will retry on next sync`,V)}}}),Re=new ds(s),Ze=ou({gateway:s,host:G,hostFor:Y,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:C,reminderCache:Ce,onInboundMessage:M=>{B=M,Re.start(i,M)},...E?{contextTracker:E}:{},contextPolicy:P,mioDir:L,downloadAttachment:M=>Ua(e.server_url,t,i,M).then(V=>({filename:V.filename,mime_type:V.mime_type,data_base64:V.data_base64}))});Ze.start(),G.onBoundary(()=>{Re.stop(i)});let rr=e.autonomous_agent,ws=wu({subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:G,hostFor:Y,selfAgentId:i,workroomId:C,companion:ne,quietSeconds:rr.quiet_seconds,maxRepliesPerWindow:rr.max_replies_per_window,windowSeconds:rr.window_seconds,contextPolicy:P});ws.start();let af=ie?.channelId??q?.channels.find(M=>M.member_ids.includes(i))?.id,lo=Tu({workspace:r,mioDir:L,agentId:i,displayName:c,handle:a,role:d,workroomId:se,channelId:af,gateway:s,companion:ne,quietSeconds:rr.quiet_seconds,spawnEnv:F,...m?{claudeCommand:m}:{}}),uo=M=>{try{let V=M.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(M.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(se).then(Me=>Vi(ne,Me)).catch(Me=>S(D,`roster refetch failed for ${M.topic}`,Me)),V.channel_id&&V.member_id&&ne.logObservation({channel_id:V.channel_id,entity_id:V.member_id,kind:M.topic})),M.topic==="message.created"&&V.sender_id&&V.channel_id){ne.logObservation({entity_id:V.sender_id,channel_id:V.channel_id,kind:"sent_message"});try{lo.noteMessage()}catch(Me){S(D,"personaCrystallizer.noteMessage error (non-fatal)",Me)}}}catch(V){S(D,"companionWsHandler error (non-fatal)",V)}};return s.subscribe(se,uo),s.listReminders(i).then(M=>Ce.snapshot(M)).catch(M=>S(D,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,M)),L_({gateway:s,agentId:i,taskWakeRouter:ws,bootRoster:q,mioDir:L}).catch(M=>S(D,`cold-start task self-heal failed for agent ${i} (non-fatal)`,M)),h("info",D,"Agentic spine started",{agentId:i,workroomId:C,mioDir:L}),P_(Ze,G,J,i,Ce,{companion:ne,gateway:s,workroomId:se,companionWsHandler:uo,taskWakeRouter:ws,personaCrystallizer:lo})}catch(x){try{G?.stop()}catch{}try{ne.close()}catch{}throw await J.close().catch(()=>{}),x}}function P_(n,e,t,r,s,i){e.onExit(c=>{h("warn",D,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",D,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){S(D,"coord.stop() error",c)}try{s.stop()}catch(c){S(D,"reminderCache.stop() error",c)}try{e.stop()}catch(c){S(D,"host.stop() error",c)}try{await t.close()}catch(c){S(D,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){S(D,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){S(D,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){S(D,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){S(D,"companion.close() error",c)}}h("info",D,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function N_(n){try{let e=await x_(Pe(n,Nu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function M_(n,e){try{await Ou(Pe(n,Nu),JSON.stringify([...e]),"utf8")}catch(t){S(D,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function L_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",D,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(p=>p.member_ids.includes(t)).map(p=>p.name).filter(p=>!!p)),o.length===0)try{o=(await e.getAgentChannels(t)).map(g=>g.name).filter(g=>!!g)}catch(p){S(D,`self-heal: getAgentChannels failed for agent ${t}`,p);return}if(o.length===0){h("debug",D,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],l=await Promise.allSettled(o.map(p=>a(t,p.startsWith("#")?p:`#${p}`)));for(let p of l)if(p.status==="fulfilled")for(let g of p.value)g.assignee_id===t&&g.status==="in_progress"&&c.push(g);else S(D,`self-heal: getTasks failed for a channel (agent ${t})`,p.reason);if(c.length===0){h("debug",D,"self-heal: no owned in_progress tasks",{agentId:t});return}let d=p=>{let g=p.updated_at??p.created_at,y=g?Date.parse(g):NaN;return Number.isFinite(y)?y:0};c.sort((p,g)=>d(g)-d(p));let u=await N_(i),m=c.filter(p=>!u.has(p.id)).slice(0,I_);if(m.length===0){h("debug",D,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(p=>p.id));let f=0;try{for(let p of m){let g=!1;if(p.parent_message_id&&e.getThreadReplies)try{g=(await e.getThreadReplies(t,p.parent_message_id,50)).some(E=>E.sender_id===t)}catch(y){S(D,`self-heal: getThreadReplies failed for task ${p.id} (agent ${t}) \u2014 treating as no activity`,y)}if(u.add(p.id),g){h("debug",D,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:p.id});continue}try{r.synthesizeAssignedWake({task_id:p.id,...p.channel_id?{channel_id:p.channel_id}:{},...p.parent_message_id?{parent_message_id:p.parent_message_id}:{}})&&(f+=1)}catch(y){S(D,`self-heal: synthesizeAssignedWake threw for task ${p.id} (agent ${t}) \u2014 task already marked seen, continuing`,y)}}}finally{await M_(i,u)}h("info",D,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:f})}function Mu(n,e,t){let r=Kn(n.replace(/^@/,"").toLowerCase()),s=Kn(e),i=`${r}-${s}`,o=Pe(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function Lu(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 $_(n){try{let t=R_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&C_(t)}catch{return!1}}async function $u(n){let{config:e,gateway:t,retrieveTokenFn:r=kt,mkdirFn:s=w=>Ki(w,{recursive:!0,mode:448}),startSpineFn:i=Iu,mioDir:o=Pu,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=$_}=n,l=e.autonomous_agent;if(!l?.enabled)return;let d,u;try{d=r(),u=await a(l.workroom_id)}catch(w){S(D,"Failed to start agentic spine \u2014 daemon continues without spine",w);return}let m=u.filter(w=>w.kind==="agent"&&w.machine_id===e.machine_id);if(m.length===0){h("error",D,`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 f=hu(),p=new ls(t),g=[],y=async w=>{let _=w.handle??"@"+w.display_name,P=_.replace(/^@/,"").toLowerCase().replace(/[^a-zA-Z0-9-]/g,"").length>0?_:`a${w.id.replace(/-/g,"").slice(0,8)}`,{selected:T,raw:L}=Lu(w.runtime);if(T==="codex"){if(!c("codex"))return h("error",D,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:w.id,handle:_}),!1}else if(T==="unsupported")return h("warn",D,`runtime '${L}' not supported; spine not started for this agent ${w.id}`,{agentId:w.id,handle:_,runtime:L}),!1;if(T==="claude"&&!c("claude"))return h("error",D,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:w.id,handle:_}),!1;try{let F=w.id,{workingDirectory:J}=Mu(P,e.machine_id,o);await s(J);let G=w.display_name||_.replace(/^@/,""),Z=w.description||"An AI agent running on this machine.",ne=T==="codex"?"gpt-5-codex":"sonnet",q={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},se=w.model||ne,ie=q[se.trim().toLowerCase()]??se,b;if(T==="codex"){let x=w.capabilities;if(x&&typeof x=="object"){let A=x.reasoning_effort;typeof A=="string"&&(A==="low"||A==="medium"||A==="high")&&(b=A)}b=b??"medium"}let R=await i({config:e,machineToken:d,workingDirectory:J,gateway:t,agentId:F,launchId:gs(),agentHandle:_,displayName:G,description:Z,role:w.role,serverCapabilities:w.capabilities,model:ie,runtime:T,...b?{reasoningEffort:b}:{},contextTracker:f,presenceTracker:p});return g.push(R),h("info",D,"Agentic spine started",{agentId:F,workroomId:l.workroom_id}),!0}catch(F){return S(D,`Failed to start spine for agent ${w.id} \u2014 continuing`,F),!1}return!0};for(let w of m)await y(w);if(g.length===0)return;let E=!1;return{handles:g,async stop(){E||(E=!0,await Promise.allSettled(g.map(w=>w.stop())))},async addAgentById(w){if(E)return!1;if(g.some(P=>P.agentId===w))return h("info",D,"hot-add skipped \u2014 spine already running",{agentId:w}),!1;let k=(await a(l.workroom_id)).find(P=>P.kind==="agent"&&P.id===w&&P.machine_id===e.machine_id);return k?y(k):(h("warn",D,"hot-add: agent not found on this machine",{agentId:w}),!1)},async removeAgentById(w){let _=g.findIndex(P=>P.agentId===w);if(_<0)return!1;let[k]=g.splice(_,1);return await k.stop().catch(()=>{}),!0},dropChannel(w){for(let _ of g)_.host.stopChannel?.(w)}}}async function Qi(){h("info",D,"Starting mio-agent daemon");let n=Je();h("info",D,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await ul();let e=new Qr;await k_(zi).catch(()=>{}),await e.listen(zi);let t=new Zr("0.1.0");await t.listen(A_,O_);let r=new jr(n);await r.start();let s=new Yr(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>tl().then(E=>{a=E}).catch(()=>{}),l=()=>a?{...a,sessions:Xi()}:{sampled_at:new Date().toISOString(),sessions:Xi()};c().then(()=>r.machineHeartbeat(!1,l()).catch(E=>S(D,"Initial machine heartbeat failed (non-fatal)",E)));let d=setInterval(()=>{c()},o),u=setInterval(()=>{r.machineHeartbeat(!1,l()).catch(E=>S(D,"Machine heartbeat failed (non-fatal)",E))},i),m=new Xr(r,{runtimes:n.runtimes,ipcSocketPath:zi}),f=new Vr(s,m),p=await $u({config:n,gateway:r,getWorkroomMembersFn:E=>r.getWorkroomMembers(E)});if(p&&n.autonomous_agent?.enabled){let E=n.autonomous_agent.workroom_id;r.subscribe(E,w=>{let _=w.payload??{};if(w.topic==="agent.created"){if(_.machine_id!==n.machine_id)return;let k=_.agent_id;if(typeof k!="string")return;h("info",D,"agent.created for this machine \u2014 hot-starting spine",{agentId:k}),p.addAgentById(k).then(P=>h("info",D,P?"hot-added agent spine \u2713":"hot-add no-op",{agentId:k})).catch(P=>S(D,"hot-add failed",P));return}if(w.topic==="agent.status"){if(!("machine_id"in _)||_.machine_id!==null||!_.disabled_by)return;let k=_.agent_id;if(typeof k!="string")return;p.removeAgentById(k).then(P=>{P&&h("info",D,"agent deleted \u2014 spine stopped, runtime processes reaped \u2713",{agentId:k})}).catch(P=>S(D,"hot-remove failed",P));return}if(w.topic==="channel.deleted"){let k=_.channel_id;if(typeof k!="string")return;p.dropChannel(k),h("info",D,"channel deleted \u2014 per-channel hosts reaped",{channelId:k})}})}e.onMessage(E=>{if(h("info",D,"IPC message from subprocess",{type:E.type}),m.onIpcMessage(E),E.type==="kick_persona"){let w=E.agent_id,_=E.reason??"ipc_kick";if(!p){h("warn",D,"IPC kick_persona: no spine running \u2014 ignoring");return}let k=0;for(let P of p.handles)if(!(w&&P.agentId!==w))try{P.personaCrystallizer?.kick(_),k+=1}catch(T){S(D,"IPC kick_persona: kick failed",T)}h("info",D,"IPC kick_persona dispatched",{kicked:k,targetAgent:w,reason:_});return}if(E.type==="join_workroom"){let w=E.workroom_id;if(!w){h("warn",D,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}f.openWorkroom(w).then(_=>{_?h("info",D,"IPC join_workroom: workroom opened",{workroomId:w,sessionId:_.sessionId}):h("warn",D,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:w})}).catch(_=>{S(D,"IPC join_workroom: unexpected error (should not happen)",_)})}}),h("info",D,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let g=!1;async function y(E){if(!g){g=!0,h("info",D,`${E} received \u2014 initiating graceful shutdown`);try{clearInterval(u),clearInterval(d),await r.machineHeartbeat(!0).catch(w=>S(D,"Going-offline heartbeat failed (non-fatal)",w)),m.beginShutdown(),await m.drainIrreversible(),f.shutdownAll(),await s.stop(),p&&await p.stop(),await r.stop(),await e.stop(),await t.stop(),h("info",D,"Graceful shutdown complete")}catch(w){S(D,"Error during shutdown",w)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{y("SIGTERM")}),process.on("SIGINT",()=>{y("SIGINT")}),await new Promise(()=>{})}var D,Pu,zi,A_,O_,tr,I_,Nu,Zi=O(()=>{"use strict";Ye();Yt();le();Qd();nl();$i();al();cl();Fi();wl();vl();Kr();Ml();Ul();Wl();Kl();eu();au();du();lu();fu();pu();_u();vu();Ru();as();hr();D="daemon",Pu=Pe(v_(),".mio"),zi=Pe(Pu,"agent.sock"),A_="127.0.0.1",O_=7878,tr=new Map;I_=5,Nu="self-heal-seen.json"});var eo={};$e(eo,{runStart:()=>D_});async function D_(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 Qi()}var to=O(()=>{"use strict";le();Zi()});import{createHash as B_}from"crypto";import{mkdtempSync as U_,rmSync as Bu,readFileSync as F_,copyFileSync as H_,chmodSync as q_,renameSync as G_,existsSync as Uu}from"fs";import{execFileSync as bn}from"child_process";import{tmpdir as W_,platform as j_}from"os";import{join as ms}from"path";function z_(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function K_(n){return`https://github.com/${J_}/${Y_}/releases/download/v${n}/`}function Fu(n,e){try{return bn("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function X_(n,e){for(let t of n.split(`
565
- `)){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 Hu(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=z_(),i=n._baseUrl??K_(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(Fu(i+c,"release manifest"))}catch(p){throw new Error(`Release manifest fetch/parse failed: ${p.message}`)}let d=new Set(l.required_fixes??[]),u=V_.filter(p=>!d.has(p));if(u.length>0)throw new Error(`Release v${e} is missing required fixes: ${u.join(", ")}. This release is too old to install safely \u2014 bump the pinned version.`);r("Fetching release checksum...");let m=X_(Fu(i+"SHASUMS256.txt","SHASUMS256.txt"),o);if(!m)throw new Error(`SHA-256 entry for '${o}' not found in SHASUMS256.txt`);let f=U_(ms(W_(),"mio-agent-install-"));try{r(`Downloading mio-agent ${e}...`);let p=ms(f,o);try{bn("curl",["-fSL",i+o,"-o",p])}catch(_){throw new Error(`Binary download failed: ${_.message}`)}r("Verifying checksum...");let g=B_("sha256").update(F_(p)).digest("hex");if(g!==m)throw new Error(`Checksum mismatch \u2014 expected ${m.slice(0,12)}\u2026, got ${g.slice(0,12)}\u2026`);r("Extracting binary...");let y=ms(f,"extract");bn("mkdir",["-p",y]),bn("tar",["-xzf",p,"-C",y]);let E=ms(y,a);if(!Uu(E))throw new Error(`mio-agent binary '${a}' not found inside the downloaded tarball`);r("Installing mio-agent...");let w=`${t}.staging`;Uu(w)&&Bu(w,{force:!0}),H_(E,w),q_(w,493),j_()==="darwin"&&!n._skipSign&&(bn("codesign",["--force","--sign","-",w]),bn("xattr",["-dr","com.apple.quarantine",w])),G_(w,t)}finally{Bu(f,{recursive:!0,force:!0})}}var J_,Y_,V_,qu=O(()=>{"use strict";J_="MioMioOS",Y_="mio-agent",V_=["machine-api-v1-prefix","socketio-control-path"]});var Ju={};$e(Ju,{runInstall:()=>io});import{mkdirSync as Gu,writeFileSync as Q_}from"fs";import{execFileSync as Z_}from"child_process";import{homedir as Wu}from"os";import{join as ys}from"path";async function io(n){if(!n.background){console.log("Starting daemon in foreground (use --background --version <semver> for LaunchAgent)");let{runStart:i}=await Promise.resolve().then(()=>(to(),eo));await i({background:!1});return}n.version||(console.error("Error: --background requires --version <semver>"),process.exit(1));let e=Je(),t=n.version;console.log(`Installing mio-agent ${t} as LaunchAgent...`),Gu(ys(pe,"bin"),{recursive:!0,mode:448}),Hu({version:t,destPath:ro,onProgress:i=>console.log(i)}),e.pinned_version=t,fr(e),Gu(ju,{recursive:!0});let r=Wu(),s=`<?xml version="1.0" encoding="UTF-8"?>
564
+ \u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:M}`:""}catch{return""}},rr=function(M){let V=eu(L,g,M);h("info",D,V?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:g,channelId:M,...V?{sessionId:V}:{}});let bt=Pt(M),Le={workingDirectory:r,systemPromptPath:v,mcpConfigPath:N,spawnEnv:F,firstTurnText:V?I:I+Me(),...V?{sessionId:V}:{},...u?{spawnFn:u}:{},...bt?{presenceTracker:bt,agentId:i}:{}},ve=g==="codex"?Xd({...Le,model:p??"gpt-5-codex",...y?{reasoningEffort:y}:{},...f?{codexCommand:f}:{}}):jd({...Le,model:p??"sonnet",...m?{claudeCommand:m}:{}});ve.onSessionId(re=>{h("info",D,"agent session id",{agentId:i,runtime:g,channelId:M,sessionId:re}),tu(L,g,re,M)});let ir=`${i}:${M}`;return nr.set(ir,{agent_id:i,agent_name:c,channel_id:M,runtime:g,model:p??null,started_at:new Date().toISOString(),turns:0,input_tokens:0,output_tokens:0,cache_read_tokens:0}),ve.onTurnUsage?.(re=>{let Se=nr.get(ir);Se&&(Se.turns+=1,Se.input_tokens+=re.inputTokens,Se.output_tokens+=re.outputTokens,Se.cache_read_tokens+=re.cacheReadTokens,Se.last_turn_at=new Date().toISOString())}),ve.onInjected(re=>{if(re.includes("type=human]")){let Se=/\bmsg=([0-9a-f]{8})/.exec(re);od(i,M,Se?.[1])}for(let Se of he)try{Se(re)}catch{}}),ve.onBoundary(()=>{ad(i,M)&&zt(e.server_url,C,M,{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:ms(),agentId:i},t).catch(re=>S("run","silent-turn notice failed",re));for(let re of $)try{re()}catch{}}),ve.onExit(re=>{for(let Se of vt)try{Se(re)}catch{}}),ve.onTurnError?.(re=>{let Se=Date.now();if(re===We&&Se-ot<6e4)return;We=re,ot=Se;let df=/usage limit/i.test(re)?"\u7528\u91CF\u5DF2\u8FBE\u4E0A\u9650,\u8BF7\u5145\u503C\u6216\u7A0D\u540E\u518D\u8BD5":/unauthor|auth|401|403/i.test(re)?"\u8BA4\u8BC1\u5931\u8D25,\u8BF7\u68C0\u67E5\u767B\u5F55/\u5BC6\u94A5":re.slice(0,160);zt(e.server_url,C,M,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${df})`,clientIdempotencyKey:ms(),agentId:i},t).catch(uf=>S("run","post turn-error notice failed",uf))}),ve.onCompact?.(()=>{zt(e.server_url,C,M,{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:ms(),agentId:i},t).catch(re=>S("run","post compact notice failed",re))}),ve.start(),ve};var b=Me,R=rr;let x={agentId:i,handle:a,displayName:c,description:d,role:l,serverId:e.org_id,computer:`${Pu()} (${e.machine_id})`,hostname:Pu(),os:`${process.platform} ${E_()}`,workspace:r,runtime:g,capabilities:T,roster:oe,persona:Au(L)??void 0},A=Fd(x),v=Ie(L,"system-prompt.md");if(await Iu(v,A,{encoding:"utf8",mode:384}),g==="claude")try{let M=Ie(r,".claude","skills");await Xi(M,{recursive:!0});let V=b_(k_(import.meta.url)),bt=Ie(V,"..","..","runtimes","skills"),Le=(await T_(bt)).filter(ve=>ve.endsWith(".md"));for(let ve of Le){let ir=ve.replace(/\.md$/,""),re=Ie(M,ir);await Xi(re,{recursive:!0}),await C_(Ie(bt,ve),Ie(re,"SKILL.md"))}h("info",D,"Materialised Claude skills",{count:Le.length,destRoot:M})}catch(M){S(D,"Failed to materialise Claude skills (continuing without)",M)}let N=Ie(L,"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.",C=e.autonomous_agent.workroom_id,B,W=q?.channels.find(M=>M.member_ids.includes(i))?.id,ae=new Map,he=[],$=[],vt=[],Ne=new Map,Pt=M=>{if(w)return{set:(V,bt)=>{Ne.set(M,bt);let Le=[...Ne.values()].some(ve=>ve!=="idle");w.set(V,Le?"thinking":"idle")}}},ot=0,We="",Y=M=>{let V=ae.get(M);return V||(V=rr(M),ae.set(M,V)),V};G={start(){},enqueueUserTurn(M){Y(B??W??"__default").enqueueUserTurn(M)},stop(){for(let M of ae.values())try{M.stop()}catch{}for(let M of ae.keys())nr.delete(`${i}:${M}`)},stopChannel(M){let V=ae.get(M);if(!V)return!1;try{V.stop()}catch{}return ae.delete(M),Ne.delete(M),nr.delete(`${i}:${M}`),!0},onBoundary(M){$.push(M)},onSessionId(M){},onExit(M){vt.push(M)},onInjected(M){he.push(M)},onTurnError(M){},onCompact(M){}},Y(W??"__default");let Re=hu({agentId:i,onFire:async M=>{G.enqueueUserTurn(`[reminder fired] ${M.title}`);try{await s.reminderFire(i,M.id,M.version)}catch(V){S(D,`reminder report-fire failed (agent ${i}, reminder ${M.id}) \u2014 local wake already happened; will retry on next sync`,V)}}}),Ae=new ds(s),Ze=cu({gateway:s,host:G,hostFor:Y,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:C,reminderCache:Re,onInboundMessage:M=>{B=M,Ae.start(i,M)},...E?{contextTracker:E}:{},contextPolicy:P,mioDir:L,downloadAttachment:M=>Fa(e.server_url,t,i,M).then(V=>({filename:V.filename,mime_type:V.mime_type,data_base64:V.data_base64}))});Ze.start(),G.onBoundary(()=>{Ae.stop(i)});let sr=e.autonomous_agent,vs=bu({subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:G,hostFor:Y,selfAgentId:i,workroomId:C,companion:ne,quietSeconds:sr.quiet_seconds,maxRepliesPerWindow:sr.max_replies_per_window,windowSeconds:sr.window_seconds,contextPolicy:P});vs.start();let lf=oe?.channelId??q?.channels.find(M=>M.member_ids.includes(i))?.id,uo=Ru({workspace:r,mioDir:L,agentId:i,displayName:c,handle:a,role:l,workroomId:ie,channelId:lf,gateway:s,companion:ne,quietSeconds:sr.quiet_seconds,spawnEnv:F,...m?{claudeCommand:m}:{}}),fo=M=>{try{let V=M.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(M.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(ie).then(Le=>zi(ne,Le)).catch(Le=>S(D,`roster refetch failed for ${M.topic}`,Le)),V.channel_id&&V.member_id&&ne.logObservation({channel_id:V.channel_id,entity_id:V.member_id,kind:M.topic})),M.topic==="message.created"&&V.sender_id&&V.channel_id){ne.logObservation({entity_id:V.sender_id,channel_id:V.channel_id,kind:"sent_message"});try{uo.noteMessage()}catch(Le){S(D,"personaCrystallizer.noteMessage error (non-fatal)",Le)}}}catch(V){S(D,"companionWsHandler error (non-fatal)",V)}};return s.subscribe(ie,fo),s.listReminders(i).then(M=>Re.snapshot(M)).catch(M=>S(D,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,M)),B_({gateway:s,agentId:i,taskWakeRouter:vs,bootRoster:q,mioDir:L}).catch(M=>S(D,`cold-start task self-heal failed for agent ${i} (non-fatal)`,M)),h("info",D,"Agentic spine started",{agentId:i,workroomId:C,mioDir:L}),M_(Ze,G,J,i,Re,{companion:ne,gateway:s,workroomId:ie,companionWsHandler:fo,taskWakeRouter:vs,personaCrystallizer:uo})}catch(x){try{G?.stop()}catch{}try{ne.close()}catch{}throw await J.close().catch(()=>{}),x}}function M_(n,e,t,r,s,i){e.onExit(c=>{h("warn",D,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",D,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){S(D,"coord.stop() error",c)}try{s.stop()}catch(c){S(D,"reminderCache.stop() error",c)}try{e.stop()}catch(c){S(D,"host.stop() error",c)}try{await t.close()}catch(c){S(D,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){S(D,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){S(D,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){S(D,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){S(D,"companion.close() error",c)}}h("info",D,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function $_(n){try{let e=await R_(Ie(n,Lu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function D_(n,e){try{await Iu(Ie(n,Lu),JSON.stringify([...e]),"utf8")}catch(t){S(D,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function B_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",D,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(p=>p.member_ids.includes(t)).map(p=>p.name).filter(p=>!!p)),o.length===0)try{o=(await e.getAgentChannels(t)).map(g=>g.name).filter(g=>!!g)}catch(p){S(D,`self-heal: getAgentChannels failed for agent ${t}`,p);return}if(o.length===0){h("debug",D,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],d=await Promise.allSettled(o.map(p=>a(t,p.startsWith("#")?p:`#${p}`)));for(let p of d)if(p.status==="fulfilled")for(let g of p.value)g.assignee_id===t&&g.status==="in_progress"&&c.push(g);else S(D,`self-heal: getTasks failed for a channel (agent ${t})`,p.reason);if(c.length===0){h("debug",D,"self-heal: no owned in_progress tasks",{agentId:t});return}let l=p=>{let g=p.updated_at??p.created_at,y=g?Date.parse(g):NaN;return Number.isFinite(y)?y:0};c.sort((p,g)=>l(g)-l(p));let u=await $_(i),m=c.filter(p=>!u.has(p.id)).slice(0,L_);if(m.length===0){h("debug",D,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(p=>p.id));let f=0;try{for(let p of m){let g=!1;if(p.parent_message_id&&e.getThreadReplies)try{g=(await e.getThreadReplies(t,p.parent_message_id,50)).some(E=>E.sender_id===t)}catch(y){S(D,`self-heal: getThreadReplies failed for task ${p.id} (agent ${t}) \u2014 treating as no activity`,y)}if(u.add(p.id),g){h("debug",D,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:p.id});continue}try{r.synthesizeAssignedWake({task_id:p.id,...p.channel_id?{channel_id:p.channel_id}:{},...p.parent_message_id?{parent_message_id:p.parent_message_id}:{}})&&(f+=1)}catch(y){S(D,`self-heal: synthesizeAssignedWake threw for task ${p.id} (agent ${t}) \u2014 task already marked seen, continuing`,y)}}}finally{await D_(i,u)}h("info",D,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:f})}function $u(n,e,t){let r=Xn(n.replace(/^@/,"").toLowerCase()),s=Xn(e),i=`${r}-${s}`,o=Ie(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function Du(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 U_(n){try{let t=P_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&O_(t)}catch{return!1}}async function Bu(n){let{config:e,gateway:t,retrieveTokenFn:r=kt,mkdirFn:s=w=>Xi(w,{recursive:!0,mode:448}),startSpineFn:i=Mu,mioDir:o=Nu,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=U_}=n,d=e.autonomous_agent;if(!d?.enabled)return;let l,u;try{l=r(),u=await a(d.workroom_id)}catch(w){S(D,"Failed to start agentic spine \u2014 daemon continues without spine",w);return}let m=u.filter(w=>w.kind==="agent"&&w.machine_id===e.machine_id);if(m.length===0){h("error",D,`No agent for this machine in workroom ${d.workroom_id} \u2014 create one first (daemon continues without spine)`,{machine_id:e.machine_id,workroom_id:d.workroom_id});return}let f=gu(),p=new us(t),g=[],y=async w=>{let _=w.handle??"@"+w.display_name,P=_.replace(/^@/,"").toLowerCase().replace(/[^a-zA-Z0-9-]/g,"").length>0?_:`a${w.id.replace(/-/g,"").slice(0,8)}`,{selected:T,raw:L}=Du(w.runtime);if(T==="codex"){if(!c("codex"))return h("error",D,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:w.id,handle:_}),!1}else if(T==="unsupported")return h("warn",D,`runtime '${L}' not supported; spine not started for this agent ${w.id}`,{agentId:w.id,handle:_,runtime:L}),!1;if(T==="claude"&&!c("claude"))return h("error",D,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:w.id,handle:_}),!1;try{let F=w.id,{workingDirectory:J}=$u(P,e.machine_id,o);await s(J);let G=w.display_name||_.replace(/^@/,""),Z=w.description||"An AI agent running on this machine.",ne=T==="codex"?"gpt-5-codex":"sonnet",q={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},ie=w.model||ne,oe=q[ie.trim().toLowerCase()]??ie,b;if(T==="codex"){let x=w.capabilities;if(x&&typeof x=="object"){let A=x.reasoning_effort;typeof A=="string"&&(A==="low"||A==="medium"||A==="high")&&(b=A)}b=b??"medium"}let R=await i({config:e,machineToken:l,workingDirectory:J,gateway:t,agentId:F,launchId:ms(),agentHandle:_,displayName:G,description:Z,role:w.role,serverCapabilities:w.capabilities,model:oe,runtime:T,...b?{reasoningEffort:b}:{},contextTracker:f,presenceTracker:p});return g.push(R),h("info",D,"Agentic spine started",{agentId:F,workroomId:d.workroom_id}),!0}catch(F){return S(D,`Failed to start spine for agent ${w.id} \u2014 continuing`,F),!1}return!0};for(let w of m)await y(w);if(g.length===0)return;let E=!1;return{handles:g,async stop(){E||(E=!0,await Promise.allSettled(g.map(w=>w.stop())))},async addAgentById(w){if(E)return!1;if(g.some(P=>P.agentId===w))return h("info",D,"hot-add skipped \u2014 spine already running",{agentId:w}),!1;let k=(await a(d.workroom_id)).find(P=>P.kind==="agent"&&P.id===w&&P.machine_id===e.machine_id);return k?y(k):(h("warn",D,"hot-add: agent not found on this machine",{agentId:w}),!1)},async removeAgentById(w){let _=g.findIndex(P=>P.agentId===w);if(_<0)return!1;let[k]=g.splice(_,1);return await k.stop().catch(()=>{}),!0},dropChannel(w){for(let _ of g)_.host.stopChannel?.(w)}}}async function Zi(){h("info",D,"Starting mio-agent daemon");let n=Je();h("info",D,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await hd();let e=new Zr;await x_(Ki).catch(()=>{}),await e.listen(Ki);let t=new es("0.1.0");await t.listen(I_,N_);let r=new Jr(n);await r.start();let s=new Vr(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>nd().then(E=>{a=E}).catch(()=>{}),d=()=>a?{...a,sessions:Qi()}:{sampled_at:new Date().toISOString(),sessions:Qi()};c().then(()=>r.machineHeartbeat(!1,d()).catch(E=>S(D,"Initial machine heartbeat failed (non-fatal)",E)));let l=setInterval(()=>{c()},o),u=setInterval(()=>{r.machineHeartbeat(!1,d()).catch(E=>S(D,"Machine heartbeat failed (non-fatal)",E))},i),m=new Qr(r,{runtimes:n.runtimes,ipcSocketPath:Ki}),f=new zr(s,m),p=await Bu({config:n,gateway:r,getWorkroomMembersFn:E=>r.getWorkroomMembers(E)});if(p&&n.autonomous_agent?.enabled){let E=n.autonomous_agent.workroom_id;r.subscribe(E,w=>{let _=w.payload??{};if(w.topic==="agent.created"){if(_.machine_id!==n.machine_id)return;let k=_.agent_id;if(typeof k!="string")return;h("info",D,"agent.created for this machine \u2014 hot-starting spine",{agentId:k}),p.addAgentById(k).then(P=>h("info",D,P?"hot-added agent spine \u2713":"hot-add no-op",{agentId:k})).catch(P=>S(D,"hot-add failed",P));return}if(w.topic==="agent.status"){if(!("machine_id"in _)||_.machine_id!==null||!_.disabled_by)return;let k=_.agent_id;if(typeof k!="string")return;p.removeAgentById(k).then(P=>{P&&h("info",D,"agent deleted \u2014 spine stopped, runtime processes reaped \u2713",{agentId:k})}).catch(P=>S(D,"hot-remove failed",P));return}if(w.topic==="channel.deleted"){let k=_.channel_id;if(typeof k!="string")return;p.dropChannel(k),h("info",D,"channel deleted \u2014 per-channel hosts reaped",{channelId:k})}})}e.onMessage(E=>{if(h("info",D,"IPC message from subprocess",{type:E.type}),m.onIpcMessage(E),E.type==="kick_persona"){let w=E.agent_id,_=E.reason??"ipc_kick";if(!p){h("warn",D,"IPC kick_persona: no spine running \u2014 ignoring");return}let k=0;for(let P of p.handles)if(!(w&&P.agentId!==w))try{P.personaCrystallizer?.kick(_),k+=1}catch(T){S(D,"IPC kick_persona: kick failed",T)}h("info",D,"IPC kick_persona dispatched",{kicked:k,targetAgent:w,reason:_});return}if(E.type==="join_workroom"){let w=E.workroom_id;if(!w){h("warn",D,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}f.openWorkroom(w).then(_=>{_?h("info",D,"IPC join_workroom: workroom opened",{workroomId:w,sessionId:_.sessionId}):h("warn",D,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:w})}).catch(_=>{S(D,"IPC join_workroom: unexpected error (should not happen)",_)})}}),h("info",D,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let g=!1;async function y(E){if(!g){g=!0,h("info",D,`${E} received \u2014 initiating graceful shutdown`);try{clearInterval(u),clearInterval(l),await r.machineHeartbeat(!0).catch(w=>S(D,"Going-offline heartbeat failed (non-fatal)",w)),m.beginShutdown(),await m.drainIrreversible(),f.shutdownAll(),await s.stop(),p&&await p.stop(),await r.stop(),await e.stop(),await t.stop(),h("info",D,"Graceful shutdown complete")}catch(w){S(D,"Error during shutdown",w)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{y("SIGTERM")}),process.on("SIGINT",()=>{y("SIGINT")}),await new Promise(()=>{})}var D,Nu,Ki,I_,N_,nr,L_,Lu,eo=O(()=>{"use strict";Ye();Yt();de();Zl();rd();Di();ld();dd();Hi();bd();kd();Xr();$d();Hd();Jd();Qd();nu();lu();uu();fu();pu();mu();vu();ku();Ou();cs();pr();D="daemon",Nu=Ie(S_(),".mio"),Ki=Ie(Nu,"agent.sock"),I_="127.0.0.1",N_=7878,nr=new Map;L_=5,Lu="self-heal-seen.json"});var to={};$e(to,{runStart:()=>F_});async function F_(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 Zi()}var no=O(()=>{"use strict";de();eo()});import{createHash as H_}from"crypto";import{mkdtempSync as q_,rmSync as Fu,readFileSync as G_,copyFileSync as W_,chmodSync as j_,renameSync as J_,existsSync as Hu}from"fs";import{execFileSync as bn}from"child_process";import{tmpdir as Y_,platform as V_}from"os";import{join as ys}from"path";function Q_(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function Z_(n){return`https://github.com/${z_}/${K_}/releases/download/v${n}/`}function qu(n,e){try{return bn("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function ew(n,e){for(let t of n.split(`
565
+ `)){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 Gu(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=Q_(),i=n._baseUrl??Z_(e),o=`mio-agent-${e}-${s}.tar.gz`,a=`mio-agent-${e}-${s}`,c=`mio-agent-${e}-manifest.json`;r("Verifying release manifest...");let d;try{d=JSON.parse(qu(i+c,"release manifest"))}catch(p){throw new Error(`Release manifest fetch/parse failed: ${p.message}`)}let l=new Set(d.required_fixes??[]),u=X_.filter(p=>!l.has(p));if(u.length>0)throw new Error(`Release v${e} is missing required fixes: ${u.join(", ")}. This release is too old to install safely \u2014 bump the pinned version.`);r("Fetching release checksum...");let m=ew(qu(i+"SHASUMS256.txt","SHASUMS256.txt"),o);if(!m)throw new Error(`SHA-256 entry for '${o}' not found in SHASUMS256.txt`);let f=q_(ys(Y_(),"mio-agent-install-"));try{r(`Downloading mio-agent ${e}...`);let p=ys(f,o);try{bn("curl",["-fSL",i+o,"-o",p])}catch(_){throw new Error(`Binary download failed: ${_.message}`)}r("Verifying checksum...");let g=H_("sha256").update(G_(p)).digest("hex");if(g!==m)throw new Error(`Checksum mismatch \u2014 expected ${m.slice(0,12)}\u2026, got ${g.slice(0,12)}\u2026`);r("Extracting binary...");let y=ys(f,"extract");bn("mkdir",["-p",y]),bn("tar",["-xzf",p,"-C",y]);let E=ys(y,a);if(!Hu(E))throw new Error(`mio-agent binary '${a}' not found inside the downloaded tarball`);r("Installing mio-agent...");let w=`${t}.staging`;Hu(w)&&Fu(w,{force:!0}),W_(E,w),j_(w,493),V_()==="darwin"&&!n._skipSign&&(bn("codesign",["--force","--sign","-",w]),bn("xattr",["-dr","com.apple.quarantine",w])),J_(w,t)}finally{Fu(f,{recursive:!0,force:!0})}}var z_,K_,X_,Wu=O(()=>{"use strict";z_="MioMioOS",K_="mio-agent",X_=["machine-api-v1-prefix","socketio-control-path"]});var Vu={};$e(Vu,{runInstall:()=>oo});import{mkdirSync as ju,writeFileSync as tw}from"fs";import{execFileSync as nw}from"child_process";import{homedir as Ju}from"os";import{join as _s}from"path";async function oo(n){if(!n.background){console.log("Starting daemon in foreground (use --background --version <semver> for LaunchAgent)");let{runStart:i}=await Promise.resolve().then(()=>(no(),to));await i({background:!1});return}n.version||(console.error("Error: --background requires --version <semver>"),process.exit(1));let e=Je(),t=n.version;console.log(`Installing mio-agent ${t} as LaunchAgent...`),ju(_s(pe,"bin"),{recursive:!0,mode:448}),Gu({version:t,destPath:so,onProgress:i=>console.log(i)}),e.pinned_version=t,hr(e),ju(Yu,{recursive:!0});let r=Ju(),s=`<?xml version="1.0" encoding="UTF-8"?>
566
566
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
567
567
  <plist version="1.0">
568
568
  <dict>
569
569
  <key>Label</key>
570
- <string>${so}</string>
570
+ <string>${io}</string>
571
571
  <key>ProgramArguments</key>
572
572
  <array>
573
- <string>${ro}</string>
573
+ <string>${so}</string>
574
574
  <string>run</string>
575
575
  </array>
576
576
  <key>RunAtLoad</key>
@@ -578,20 +578,20 @@ ${M.length>6e3?M.slice(0,6e3)+`
578
578
  <key>KeepAlive</key>
579
579
  <true/>
580
580
  <key>ExitTimeOut</key>
581
- <integer>${_l}</integer>
581
+ <integer>${vd}</integer>
582
582
  <key>StandardOutPath</key>
583
583
  <string>${r}/.mio/logs/mio-agent.log</string>
584
584
  <key>StandardErrorPath</key>
585
585
  <string>${r}/.mio/logs/mio-agent-error.log</string>
586
586
  </dict>
587
- </plist>`;Q_(no,s,{encoding:"utf-8",mode:420}),Z_("launchctl",["bootstrap",`gui/${process.getuid()}`,no]),console.log(`
588
- mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${ro}`),console.log(` Plist: ${no}`),console.log(` Label: ${so}`),console.log(`
589
- Run: mio-agent doctor \u2014 to verify health`)}var so,ju,no,ro,oo=O(()=>{"use strict";Ye();Fi();qu();so="io.miomioos.mio-agent",ju=ys(Wu(),"Library","LaunchAgents"),no=ys(ju,`${so}.plist`),ro=ys(pe,"bin","mio-agent")});var ao={};$e(ao,{runUpgrade:()=>nw,runUpgradeCheck:()=>tw});import{execFileSync as ew}from"child_process";async function tw(){let e=Je().pinned_version??"unknown (foreground/dev mode)",t=ew("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.":`
590
- To upgrade: mio-agent upgrade --version ${t}`)}async function nw(n){let e=Je();e.pinned_version=n.version,fr(e),console.log(`Pinned version updated to ${n.version} in config.`),await io({background:!0,version:n.version})}var co=O(()=>{"use strict";Ye();oo()});var Yu={};$e(Yu,{runStop:()=>iw});import{execFileSync as rw}from"child_process";async function iw(){try{rw("launchctl",["stop",sw]),console.log("Daemon stopped.")}catch{console.log("Daemon was not running or stop signal sent.")}}var sw,Vu=O(()=>{"use strict";sw="io.miomioos.mio-agent"});var Xu={};$e(Xu,{runUninstall:()=>lw});import{execFileSync as ow}from"child_process";import{rmSync as zu,existsSync as Ku}from"fs";import{join as aw}from"path";import{homedir as cw}from"os";async function lw(){console.log("Uninstalling mio-agent...");try{ow("launchctl",["bootout",`gui/${process.getuid()}`,_s]),console.log(" LaunchAgent unregistered.")}catch{console.log(" LaunchAgent was not registered (skipped).")}Ku(_s)&&(zu(_s),console.log(` Deleted: ${_s}`));try{To(),console.log(" Keychain entry deleted.")}catch{console.log(" No Keychain entry found (skipped).")}Ku(pe)&&(zu(pe,{recursive:!0,force:!0}),console.log(` Deleted: ${pe}`)),console.log(`
591
- mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var dw,_s,Qu=O(()=>{"use strict";Yt();Ye();dw="io.miomioos.mio-agent",_s=aw(cw(),"Library","LaunchAgents",`${dw}.plist`)});var ef={};$e(ef,{runDoctor:()=>hw});import{execFileSync as uw,spawnSync as Zu}from"child_process";import{existsSync as fw}from"fs";function wt(n,e,t){let r=e?"\u2705":"\u274C",s=t?`${r} ${n}: ${t}`:`${r} ${n}`;console.log(s)}async function hw(){console.log(`mio-agent doctor
592
- `);let n=aa();if(wt("Config (~/.mio/agent.json)",n,n?"found":"missing \u2014 run: mio-agent login"),!n)return;let e=Je(),t=!1;try{uw("security",["find-generic-password","-s","io.miomioos.mio-agent","-a","machine_token"],{stdio:"ignore"}),t=!0}catch{}wt("Keychain (machine_token)",t,t?"found":"missing \u2014 run: mio-agent login");let r=!1;try{r=Zu("curl",["-fsS","--max-time","3",`${e.server_url}/health`]).status===0}catch{}wt("Server connectivity",r,r?e.server_url:`unreachable: ${e.server_url}`);let s=!1;try{s=Zu("curl",["-fsS","--max-time","1",`http://127.0.0.1:${oa}/health`]).status===0}catch{}wt("Daemon (127.0.0.1:7878)",s,s?"running":"not running"),console.log(""),console.log("Runtimes:");let i=_n();if(i)wt(" claude",!0,i);else{wt(" claude",!1,"not found");for(let c of ql().split(`
593
- `))console.log(` ${c}`)}let o=os();if(o){let c=(process.env.MIO_CODEX_MODEL||"").trim();wt(" codex",!0,c?`${o} (model override: ${c})`:`${o} (model: local default)`)}else{wt(" codex",!1,"not found");for(let c of Jl().split(`
594
- `))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>fw(c));wt(" opencode",!!a,a??"not found in PATH"),console.log("")}var tf=O(()=>{"use strict";Ye();ss();Ji()});var rf={};$e(rf,{buildPairingDeeplink:()=>nf,runPairPhone:()=>mw});function nf(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 gw(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 mw(n){n||(console.error("Usage: mio-agent pair-phone <workroom_id>"),process.exit(1));let e=Je(),t;try{t=kt()}catch{console.error("No machine_token in Keychain. Run: mio-agent login"),process.exit(1);return}let r=`${e.server_url}/api/v1/machines/${e.machine_id}/pairings`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({workroom_id:n})});if(!s.ok){console.error(`Pairing failed: ${s.status} \u2014 ${gw(s.status)}`),process.exit(1);return}let i=await s.json(),o=nf(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(()=>te(Os(),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 sf=O(()=>{"use strict";Ye();Yt()});import{parseArgs as yw}from"util";import{fileURLToPath as _w}from"url";import{realpathSync as of}from"fs";function ww(n){return n[0]==="agentcli"}function vw(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(()=>(po(),ho));console.log(i()),process.exit(0)}if(ww(n)){let{runAgentcliCommand:i}=await Promise.resolve().then(()=>(xo(),Eo));process.exit(await i())}if(vw(n)){let{runLogin:i}=await Promise.resolve().then(()=>(ta(),ea));process.exit(await i(process.argv.slice(3)))}if(n[0]==="logs"){let{runLogs:i}=await Promise.resolve().then(()=>(sa(),ra));process.exit(await i(process.argv.slice(3)))}let{values:e,positionals:t}=yw({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(()=>(to(),eo));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(()=>(oo(),Ju));await i({background:e.background??!1,version:e.version});break}case"upgrade":{if(e.check){let{runUpgradeCheck:i}=await Promise.resolve().then(()=>(co(),ao));await i()}else if(e.version){let{runUpgrade:i}=await Promise.resolve().then(()=>(co(),ao));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(()=>(Zi(),Du));await i();break}case"stop":{let{runStop:i}=await Promise.resolve().then(()=>(Vu(),Yu));await i();break}case"uninstall":{let{runUninstall:i}=await Promise.resolve().then(()=>(Qu(),Xu));await i();break}case"doctor":{let{runDoctor:i}=await Promise.resolve().then(()=>(tf(),ef));await i();break}case"pair-phone":{let{runPairPhone:i}=await Promise.resolve().then(()=>(sf(),rf));await i(s[0]);break}default:console.log(`Mio Agent \u2014 background AI worker daemon
587
+ </plist>`;tw(ro,s,{encoding:"utf-8",mode:420}),nw("launchctl",["bootstrap",`gui/${process.getuid()}`,ro]),console.log(`
588
+ mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${so}`),console.log(` Plist: ${ro}`),console.log(` Label: ${io}`),console.log(`
589
+ Run: mio-agent doctor \u2014 to verify health`)}var io,Yu,ro,so,ao=O(()=>{"use strict";Ye();Hi();Wu();io="io.miomioos.mio-agent",Yu=_s(Ju(),"Library","LaunchAgents"),ro=_s(Yu,`${io}.plist`),so=_s(pe,"bin","mio-agent")});var co={};$e(co,{runUpgrade:()=>iw,runUpgradeCheck:()=>sw});import{execFileSync as rw}from"child_process";async function sw(){let e=Je().pinned_version??"unknown (foreground/dev mode)",t=rw("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.":`
590
+ To upgrade: mio-agent upgrade --version ${t}`)}async function iw(n){let e=Je();e.pinned_version=n.version,hr(e),console.log(`Pinned version updated to ${n.version} in config.`),await oo({background:!0,version:n.version})}var lo=O(()=>{"use strict";Ye();ao()});var zu={};$e(zu,{runStop:()=>cw});import{execFileSync as ow}from"child_process";async function cw(){try{ow("launchctl",["stop",aw]),console.log("Daemon stopped.")}catch{console.log("Daemon was not running or stop signal sent.")}}var aw,Ku=O(()=>{"use strict";aw="io.miomioos.mio-agent"});var Zu={};$e(Zu,{runUninstall:()=>hw});import{execFileSync as lw}from"child_process";import{rmSync as Xu,existsSync as Qu}from"fs";import{join as dw}from"path";import{homedir as uw}from"os";async function hw(){console.log("Uninstalling mio-agent...");try{lw("launchctl",["bootout",`gui/${process.getuid()}`,ws]),console.log(" LaunchAgent unregistered.")}catch{console.log(" LaunchAgent was not registered (skipped).")}Qu(ws)&&(Xu(ws),console.log(` Deleted: ${ws}`));try{Co(),console.log(" Keychain entry deleted.")}catch{console.log(" No Keychain entry found (skipped).")}Qu(pe)&&(Xu(pe,{recursive:!0,force:!0}),console.log(` Deleted: ${pe}`)),console.log(`
591
+ mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var fw,ws,ef=O(()=>{"use strict";Yt();Ye();fw="io.miomioos.mio-agent",ws=dw(uw(),"Library","LaunchAgents",`${fw}.plist`)});var nf={};$e(nf,{runDoctor:()=>mw});import{execFileSync as pw,spawnSync as tf}from"child_process";import{existsSync as gw}from"fs";function wt(n,e,t){let r=e?"\u2705":"\u274C",s=t?`${r} ${n}: ${t}`:`${r} ${n}`;console.log(s)}async function mw(){console.log(`mio-agent doctor
592
+ `);let n=ca();if(wt("Config (~/.mio/agent.json)",n,n?"found":"missing \u2014 run: mio-agent login"),!n)return;let e=Je(),t=!1;try{pw("security",["find-generic-password","-s","io.miomioos.mio-agent","-a","machine_token"],{stdio:"ignore"}),t=!0}catch{}wt("Keychain (machine_token)",t,t?"found":"missing \u2014 run: mio-agent login");let r=!1;try{r=tf("curl",["-fsS","--max-time","3",`${e.server_url}/health`]).status===0}catch{}wt("Server connectivity",r,r?e.server_url:`unreachable: ${e.server_url}`);let s=!1;try{s=tf("curl",["-fsS","--max-time","1",`http://127.0.0.1:${aa}/health`]).status===0}catch{}wt("Daemon (127.0.0.1:7878)",s,s?"running":"not running"),console.log(""),console.log("Runtimes:");let i=_n();if(i)wt(" claude",!0,i);else{wt(" claude",!1,"not found");for(let c of Wd().split(`
593
+ `))console.log(` ${c}`)}let o=as();if(o){let c=(process.env.MIO_CODEX_MODEL||"").trim();wt(" codex",!0,c?`${o} (model override: ${c})`:`${o} (model: local default)`)}else{wt(" codex",!1,"not found");for(let c of Vd().split(`
594
+ `))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>gw(c));wt(" opencode",!!a,a??"not found in PATH"),console.log("")}var rf=O(()=>{"use strict";Ye();is();Yi()});var of={};$e(of,{buildPairingDeeplink:()=>sf,runPairPhone:()=>ww});function sf(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 yw(n){let e=new Date(n).getTime()-Date.now();return`${Math.max(0,Math.round(e/6e4))} min`}function _w(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 ww(n){n||(console.error("Usage: mio-agent pair-phone <workroom_id>"),process.exit(1));let e=Je(),t;try{t=kt()}catch{console.error("No machine_token in Keychain. Run: mio-agent login"),process.exit(1);return}let r=`${e.server_url}/api/v1/machines/${e.machine_id}/pairings`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({workroom_id:n})});if(!s.ok){console.error(`Pairing failed: ${s.status} \u2014 ${_w(s.status)}`),process.exit(1);return}let i=await s.json(),o=sf(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 ${yw(i.expires_at)} (${i.expires_at})`),console.log(` Pairing: ${i.pairing_id}`),console.log("");let a=!1;try{let c=await Promise.resolve().then(()=>te(Ps(),1)).catch(()=>null),d=c?.default??c;typeof d?.generate=="function"&&(d.generate(o,{small:!0},l=>console.log(l)),a=!0)}catch{}a||console.log(" Render this payload as a QR (MioIsland shows it on screen; or paste into any QR tool):"),console.log(` ${o}`),console.log(""),console.log(" The raw operator token is NOT in this code \u2014 the phone mints it securely on redeem."),console.log(" To cancel/regenerate, re-run pair-phone (old code stays valid until it expires unless canceled in MioIsland)."),console.log("")}var af=O(()=>{"use strict";Ye();Yt()});import{parseArgs as vw}from"util";import{fileURLToPath as bw}from"url";import{realpathSync as cf}from"fs";function kw(n){return n[0]==="agentcli"}function Sw(n){return n[0]==="login"}async function Ew(){let n=process.argv.slice(2);if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){let{getPackageVersion:i}=await Promise.resolve().then(()=>(go(),po));console.log(i()),process.exit(0)}if(kw(n)){let{runAgentcliCommand:i}=await Promise.resolve().then(()=>(To(),xo));process.exit(await i())}if(Sw(n)){let{runLogin:i}=await Promise.resolve().then(()=>(na(),ta));process.exit(await i(process.argv.slice(3)))}if(n[0]==="logs"){let{runLogs:i}=await Promise.resolve().then(()=>(ia(),sa));process.exit(await i(process.argv.slice(3)))}let{values:e,positionals:t}=vw({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(()=>(no(),to));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(()=>(ao(),Vu));await i({background:e.background??!1,version:e.version});break}case"upgrade":{if(e.check){let{runUpgradeCheck:i}=await Promise.resolve().then(()=>(lo(),co));await i()}else if(e.version){let{runUpgrade:i}=await Promise.resolve().then(()=>(lo(),co));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(()=>(eo(),Uu));await i();break}case"stop":{let{runStop:i}=await Promise.resolve().then(()=>(Ku(),zu));await i();break}case"uninstall":{let{runUninstall:i}=await Promise.resolve().then(()=>(ef(),Zu));await i();break}case"doctor":{let{runDoctor:i}=await Promise.resolve().then(()=>(rf(),nf));await i();break}case"pair-phone":{let{runPairPhone:i}=await Promise.resolve().then(()=>(af(),of));await i(s[0]);break}default:console.log(`Mio Agent \u2014 background AI worker daemon
595
595
 
596
596
  Global flags:
597
597
  --version, -v Print version and exit
@@ -610,7 +610,7 @@ Commands:
610
610
  logs [-n N] [-f] Tail daemon logs (~/.mio/logs/, or /tmp/mio-agent.log in dev mode)
611
611
  agentcli <subcommand> Agent-facing CLI (message check/send/read); use --help for details
612
612
  run Internal: launched by launchd (do not call directly)
613
- `),process.exit(r?1:0)}}function kw(){try{let n=X("node:sea");return typeof n.isSea=="function"&&n.isSea()}catch{return!1}}function Sw(){if(kw())return!0;let n=process.argv[1];if(!n)return!1;try{return of(_w(import.meta.url))===of(n)}catch{return!1}}Sw()&&bw().catch(n=>{console.error("Fatal:",n.message),process.exit(1)});export{ww as isAgentcliInvocation,vw as isLoginInvocation};
613
+ `),process.exit(r?1:0)}}function xw(){try{let n=X("node:sea");return typeof n.isSea=="function"&&n.isSea()}catch{return!1}}function Tw(){if(xw())return!0;let n=process.argv[1];if(!n)return!1;try{return cf(bw(import.meta.url))===cf(n)}catch{return!1}}Tw()&&Ew().catch(n=>{console.error("Fatal:",n.message),process.exit(1)});export{kw as isAgentcliInvocation,Sw as isLoginInvocation};
614
614
  /*! Bundled license information:
615
615
 
616
616
  xmlhttprequest-ssl/lib/XMLHttpRequest.js: