@miomioos/mio-agent 0.3.12 → 0.3.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/index.js +187 -187
- 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
|
|
3
|
+
var yf=Object.create;var xs=Object.defineProperty;var _f=Object.getOwnPropertyDescriptor;var wf=Object.getOwnPropertyNames;var vf=Object.getPrototypeOf,bf=Object.prototype.hasOwnProperty;var te=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var A=(n,e)=>()=>(n&&(e=n(n=0)),e);var Z=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Be=(n,e)=>{for(var t in e)xs(n,t,{get:e[t],enumerable:!0})},kf=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wf(e))!bf.call(n,s)&&s!==t&&xs(n,s,{get:()=>e[s],enumerable:!(r=_f(e,s))||r.enumerable});return n};var oe=(n,e,t)=>(t=n!=null?yf(vf(n)):{},kf(e||!n||!n.__esModule?xs(t,"default",{value:n,enumerable:!0}):t,n));var wo={};Be(wo,{MIO_AGENT_VERSION:()=>_o,getPackageVersion:()=>Sf});function Sf(){return _o}var _o,vo=A(()=>{"use strict";_o="0.2.1"});import{readFileSync as So,writeFileSync as Ef}from"fs";import{basename as xf,extname as Tf}from"path";import{randomUUID as Eo}from"crypto";async function xo(n,e={}){let t=e.stdout??process.stdout,r=e.stderr??process.stderr,s=e.stdin??process.stdin;if(n.length===0||n[0]==="--help"||n[0]==="-h")return t.write(dh),0;let i=process.env.MIO_AGENT_PROXY_URL;if(!i)return r.write(JSON.stringify({ok:!1,code:"MISSING_PROXY_URL",message:"MIO_AGENT_PROXY_URL is not set"})+`
|
|
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=
|
|
5
|
+
`),1;let a;try{a=So(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,d
|
|
8
|
-
`),1)}async function
|
|
9
|
-
`),1}}async function
|
|
10
|
-
`),1;let o=await ue(e,t,"check",{channel:i});return o.ok?(
|
|
11
|
-
`),1)}async function
|
|
7
|
+
`),1;let[c,l,...d]=n;return c==="message"?Cf(l,d,i,a,s,t,r):c==="task"?Nf(l,d,i,a,t,r):c==="reminder"?Ff(l,d,i,a,t,r):c==="action"?Xf(l,d,i,a,t,r):c==="attachment"?nh(l,d,i,a,t,r):c==="profile"?ih(l,d,i,a,t,r):(r.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown command: ${n.join(" ")}`})+`
|
|
8
|
+
`),1)}async function Cf(n,e,t,r,s,i,o){switch(n){case"check":return Rf(e,t,r,i,o);case"send":return Af(e,t,r,s,i,o);case"read":return Of(e,t,r,i,o);case"react":return Pf(e,t,r,i,o);case"reply":return If(e,t,r,s,i,o);default:return o.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown message subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
9
|
+
`),1}}async function Rf(n,e,t,r,s){let i=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 ue(e,t,"check",{channel:i});return o.ok?(Co(o.data,r),0):(s.write(JSON.stringify(o.error)+`
|
|
11
|
+
`),1)}async function Af(n,e,t,r,s,i){if(n.includes("--help")||n.includes("-h"))return s.write(`\u7528\u6CD5: mio message send --target "#\u9891\u9053\u540D" <<EOF
|
|
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
|
|
18
|
-
`),1;let c=
|
|
19
|
-
`),1;
|
|
20
|
-
`),1;let m=u.data,p=String(m.id??""),f=String(m.short_id??m.shortId??"").slice(0,8),g=m.seq!==void 0?`seq=${m.seq} `:"",
|
|
21
|
-
`),0}async function
|
|
22
|
-
`),1;let o={channel:i},a=U(n,"--after"),c=U(n,"--around"),
|
|
23
|
-
`),1;if(a&&(o.after_seq=a),c&&(o.around=c),
|
|
24
|
-
`),1;o.limit=p}let m=await ue(e,t,"history",o);return m.ok?(
|
|
25
|
-
`),1)}async function
|
|
17
|
+
`),1;let a=await Ro(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=Eo(),l=lr(n,"--attachment");for(let y of lr(n,"--attach-file")){let S=await Rs(y,o,e,t);if(!S.ok)return i.write(JSON.stringify(S.error)+`
|
|
19
|
+
`),1;l.push(S.id)}let d={target:o,content:a,clientIdempotencyKey:c};l.length>0&&(d.attachment_ids=l);let u=await ue(e,t,"send",d);if(!u.ok)return i.write(JSON.stringify(u.error)+`
|
|
20
|
+
`),1;let m=u.data,p=String(m.id??""),f=String(m.short_id??m.shortId??"").slice(0,8),g=m.seq!==void 0?`seq=${m.seq} `:"",_=typeof m.routed_to=="string"?m.routed_to:"",E=typeof m.task_number=="number"?m.task_number:null,v="";return _==="thread"&&E!==null&&(v=` (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=${p} ${f?`short=${f} `:""}${g}target=${o}${v}
|
|
21
|
+
`),0}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 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(p=>p!==void 0).length>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --after, --around, --before may be provided"})+`
|
|
23
|
+
`),1;if(a&&(o.after_seq=a),c&&(o.around=c),l&&(o.around=l),d!==void 0){let p=Number(d);if(!Number.isInteger(p)||p<=0)return s.write(JSON.stringify({ok:!1,code:"INVALID_LIMIT",message:`--limit must be a positive integer, got: ${d}`})+`
|
|
24
|
+
`),1;o.limit=p}let m=await ue(e,t,"history",o);return m.ok?(Co(m.data,r),0):(s.write(JSON.stringify(m.error)+`
|
|
25
|
+
`),1)}async function Pf(n,e,t,r,s){let i=dt(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",
|
|
29
|
-
`),0):(s.write(JSON.stringify(
|
|
30
|
-
`),1)}async function
|
|
28
|
+
`),1;let c=n.includes("--remove")?"remove":"add",l=await ue(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 If(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
|
|
34
|
-
`),1;let
|
|
35
|
-
`),1;
|
|
36
|
-
`),1;let p=m.data,f=String(p.id??""),g=String(p.short_id??p.shortId??"").slice(0,8),
|
|
37
|
-
`),0}async function
|
|
38
|
-
`),1}}async function
|
|
33
|
+
`),1;let c=await Ro(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=Eo(),d=lr(n,"--attachment");for(let E of lr(n,"--attach-file")){let v=await Rs(E,a,e,t);if(!v.ok)return i.write(JSON.stringify(v.error)+`
|
|
35
|
+
`),1;d.push(v.id)}let u={target:a,parent_message_id:o,content:c,clientIdempotencyKey:l};d.length>0&&(u.attachment_ids=d);let m=await ue(e,t,"reply",u);if(!m.ok)return i.write(JSON.stringify(m.error)+`
|
|
36
|
+
`),1;let p=m.data,f=String(p.id??""),g=String(p.short_id??p.shortId??"").slice(0,8),_=p.seq!==void 0?`seq=${p.seq} `:"";return s.write(`replied: id=${f} ${g?`short=${g} `:""}${_}parent=${o} target=${a}
|
|
37
|
+
`),0}async function Nf(n,e,t,r,s,i){switch(n){case"list":return Lf(e,t,r,s,i);case"create":return $f(e,t,r,s,i);case"claim":return bo("claim",e,t,r,s,i);case"unclaim":return bo("unclaim",e,t,r,s,i);case"update":return Df(e,t,r,s,i);case"review":return Mf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown task subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
38
|
+
`),1}}async function Mf(n,e,t,r,s){let i=Ts(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
|
|
41
|
+
`),1;let l=a?"pass":"bounce",d=U(n,"--feedback")??"",u=await ue(e,t,"task",{op:"review",channel:o,number:i,verdict:l,feedback:d});return u.ok?(r.write(`Reviewed task #${i} \u2192 ${l==="pass"?"passed (done)":"bounced back for rework"}
|
|
42
42
|
`),0):(s.write(JSON.stringify(u.error)+`
|
|
43
|
-
`),1)}async function
|
|
44
|
-
`),1;let o=await ue(e,t,"task",{op:"list",channel:i});return o.ok?(
|
|
45
|
-
`),1)}async function
|
|
43
|
+
`),1)}async function Lf(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 ue(e,t,"task",{op:"list",channel:i});return o.ok?(Uf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
|
|
45
|
+
`),1)}async function $f(n,e,t,r,s){let i=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),n.includes("--self")&&(c.self=!0);let
|
|
48
|
-
`),1;let
|
|
49
|
-
`),0}async function
|
|
47
|
+
`),1;let a=U(n,"--attach"),c={op:"create",channel:i,title:o};a!==void 0&&a!==""&&(c.attach_to_message_id=a),n.includes("--self")&&(c.self=!0);let l=await ue(e,t,"task",c);if(!l.ok)return s.write(JSON.stringify(l.error)+`
|
|
48
|
+
`),1;let d=Bf(l.data),u=d?.number!==void 0?`#${d.number}`:"(new)";return r.write(`Created task ${u}: ${o}
|
|
49
|
+
`),0}async function bo(n,e,t,r,s,i){let o=Ts(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
51
|
`),1;let c=await ue(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
|
|
53
|
+
`),1)}async function Df(n,e,t,r,s){let i=Ts(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
56
|
`),1;let c=await ue(e,t,"task",{op:"update",channel:o,number:i,status:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
|
|
57
|
-
`),1;let
|
|
58
|
-
`);else{let
|
|
59
|
-
`)}return 0}function
|
|
60
|
-
`);return}for(let s of r){let i=`#${s.number??"?"}`,o=s.status??"unknown",a=s.title??"",c=s.assignee??s.assignee_id,
|
|
61
|
-
`)}}async function
|
|
62
|
-
`),1}}async function
|
|
63
|
-
`),1;let o=U(n,"--in"),a=U(n,"--at"),c=U(n,"--cadence"),
|
|
64
|
-
`),1;if(
|
|
65
|
-
`),1;let
|
|
66
|
-
`),1;let f=
|
|
67
|
-
`),0}async function
|
|
68
|
-
`),1)}async function
|
|
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 Ts(n){let e=dt(n);if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;if(!(t===""||!/^\d+$/.test(t)))return Number(t)}function dt(n){for(let e=0;e<n.length;e++){let t=n[e];if(t.startsWith("--")){e++;continue}return t}}function Bf(n){let e=n;return(Array.isArray(e?.tasks)?e.tasks:[])[0]}function Uf(n,e){let t=n,r=Array.isArray(t?.tasks)?t.tasks:[];if(r.length===0){e.write(`(no tasks)
|
|
60
|
+
`);return}for(let s of r){let i=`#${s.number??"?"}`,o=s.status??"unknown",a=s.title??"",c=s.assignee??s.assignee_id,l=c?`@${c}`:"unassigned";e.write(`${i} ${o} ${a} ${l}
|
|
61
|
+
`)}}async function Ff(n,e,t,r,s,i){switch(n){case"schedule":return Hf(e,t,r,s,i);case"list":return qf(e,t,r,s,i);case"snooze":return Gf(e,t,r,s,i);case"update":return Wf(e,t,r,s,i);case"cancel":return jf(e,t,r,s,i);case"log":return Jf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown reminder subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
62
|
+
`),1}}async function Hf(n,e,t,r,s){let i=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 p=await ue(e,t,"reminder",m);if(!p.ok)return s.write(JSON.stringify(p.error)+`
|
|
66
|
+
`),1;let f=Yf(p.data),g=f?.id??"(new)",_=f?.fireAt?` fireAt=${f.fireAt}`:"";return r.write(`Scheduled reminder ${g}: ${i}${_}
|
|
67
|
+
`),0}async function qf(n,e,t,r,s){let i=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 ue(e,t,"reminder",a);return c.ok?(zf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
|
|
68
|
+
`),1)}async function Gf(n,e,t,r,s){let i=dt(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(f=>f!==void 0).length;if(c===0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"one of --in <dur> or --until <ISO> is required for reminder snooze"})+`
|
|
70
70
|
`),1;if(c>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --until may be provided"})+`
|
|
71
|
-
`),1;let
|
|
72
|
-
`),1;let m=
|
|
73
|
-
`),0}async function
|
|
74
|
-
`),1;let o=U(n,"--title"),a=U(n,"--cadence"),c=U(n,"--in"),
|
|
75
|
-
`),1;if(c!==void 0&&
|
|
76
|
-
`),1;let
|
|
71
|
+
`),1;let l=await Cs(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 ue(e,t,"reminder",d);if(!u.ok)return s.write(JSON.stringify(u.error)+`
|
|
72
|
+
`),1;let m=Vf(u.data),p=m?.fireAt?` \u2192 ${m.fireAt}`:"";return r.write(`Snoozed reminder ${i}${p}
|
|
73
|
+
`),0}async function Wf(n,e,t,r,s){let i=dt(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(p=>p===void 0))return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"at least one of --title, --cadence, --in, --at is required for reminder update"})+`
|
|
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 Cs(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 ue(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
|
|
79
|
-
`),1;let o=await
|
|
78
|
+
`),1)}async function jf(n,e,t,r,s){let i=dt(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 Cs(i,e,t,s);if(o===void 0)return 1;let a=await ue(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
|
|
82
|
-
`),1;let o=await ue(e,t,"reminder",{op:"log",id:i});return o.ok?(
|
|
83
|
-
`),1)}function
|
|
81
|
+
`),1)}async function Jf(n,e,t,r,s){let i=dt(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 ue(e,t,"reminder",{op:"log",id:i});return o.ok?(Kf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
|
|
83
|
+
`),1)}function Yf(n){let e=n;return e?.reminder?e.reminder:(Array.isArray(e?.reminders)?e.reminders:[])[0]}function Vf(n){return n?.reminder}async function Cs(n,e,t,r){let s=await ue(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
|
|
87
|
-
`);return}for(let s of r){let i=s.id??"?",o=s.fireAt??"?",a=s.status??"unknown",c=s.title??"",
|
|
88
|
-
`)}}function
|
|
86
|
+
`);return}return a.version}function zf(n,e){let t=n,r=Array.isArray(t?.reminders)?t.reminders:[];if(r.length===0){e.write(`(no reminders)
|
|
87
|
+
`);return}for(let s of r){let i=s.id??"?",o=s.fireAt??"?",a=s.status??"unknown",c=s.title??"",l=s.cadence?` cadence=${s.cadence}`:"";e.write(`${i} ${o} ${a} ${c}${l}
|
|
88
|
+
`)}}function Kf(n,e){let t=n,r=Array.isArray(t?.events)?t.events:[];if(r.length===0){e.write(`(no events)
|
|
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
|
|
91
|
-
`),1}}async function
|
|
90
|
+
`)}}async function Xf(n,e,t,r,s,i){switch(n){case"prepare":return Qf(e,t,r,s,i);case"list":return Zf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown action subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
91
|
+
`),1}}async function Qf(n,e,t,r,s){let i=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"),p=U(n,"--member-id");if(m===void 0&&p===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--member <@handle> (or --member-id <id>) is required for action prepare --type channel:add_member"})+`
|
|
96
96
|
`),1;a={channel:u},m!==void 0&&(a.member_handle=m),p!==void 0&&(a.member_id=p)}else return s.write(JSON.stringify({ok:!1,code:"INVALID_TYPE",message:`Unknown action type: ${o}. Supported: channel:create, channel:add_member`})+`
|
|
97
97
|
`),1;let c=await ue(e,t,"action",{op:"prepare",target:i,type:o,params:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
|
|
98
|
-
`),1;let
|
|
99
|
-
`),0}async function
|
|
100
|
-
`),1)}function
|
|
98
|
+
`),1;let d=eh(c.data)?.id??"(new)";return r.write(`Proposed action ${d}: ${o} (target=${i}) \u2014 awaiting human approval
|
|
99
|
+
`),0}async function Zf(n,e,t,r,s){let i=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 ue(e,t,"action",a);return c.ok?(th(c.data,r),0):(s.write(JSON.stringify(c.error)+`
|
|
100
|
+
`),1)}function eh(n){let e=n;return e?.action?e.action:(Array.isArray(e?.actions)?e.actions:[])[0]}function th(n,e){let t=n,r=Array.isArray(t?.actions)?t.actions:[];if(r.length===0){e.write(`(no actions)
|
|
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
|
|
103
|
-
`),1}}async function
|
|
102
|
+
`)}}async function nh(n,e,t,r,s,i){switch(n){case"upload":return rh(e,t,r,s,i);case"view":return sh(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown attachment subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
103
|
+
`),1}}async function Rs(n,e,t,r){let s=Tf(n).toLowerCase(),i=ko[s];if(!i){let u=Object.keys(ko).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=So(n).toString("base64")}catch(u){let m=u instanceof Error?u.message:String(u);return{ok:!1,error:{ok:!1,code:"FILE_READ_ERROR",message:`Cannot read file ${n}: ${m}`}}}let a=xf(n),c=await ue(t,r,"attachment",{op:"upload",filename:a,mime_type:i,data_base64:o,target:e});if(!c.ok)return{ok:!1,error:c.error};let l=c.data;return{ok:!0,id:String(l.attachment_id??l.id??""),filename:a,mimeType:i}}async function rh(n,e,t,r,s){let i=dt(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
|
|
105
|
+
`),1;let a=await Rs(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
|
|
107
|
+
`),1)}async function sh(n,e,t,r,s){let i=dt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"an attachment id is required for attachment view"})+`
|
|
108
108
|
`),1;let o=U(n,"--out"),a=await ue(e,t,"attachment",{op:"view",attachment_id:i});if(!a.ok)return s.write(JSON.stringify(a.error)+`
|
|
109
|
-
`),1;let c=a.data,
|
|
109
|
+
`),1;let c=a.data,l=String(c.filename??""),d=String(c.mime_type??""),u=c.size_bytes;if(o!==void 0){let p=c.data_base64;if(typeof p!="string")return s.write(JSON.stringify({ok:!1,code:"NO_ATTACHMENT_DATA",message:`attachment ${i} response did not include data_base64 bytes to save`})+`
|
|
110
110
|
`),1;let f=Buffer.from(p,"base64");if(u!==void 0){let g=Number(u);if(!Number.isNaN(g)&&f.length!==g)return s.write(JSON.stringify({ok:!1,code:"SIZE_MISMATCH",message:`attachment ${i} byte length mismatch: server reported size_bytes=${g} but decoded ${f.length} bytes \u2014 not writing ${o}`})+`
|
|
111
|
-
`),1}try{
|
|
111
|
+
`),1}try{Ef(o,f)}catch(g){let _=g instanceof Error?g.message:String(g);return s.write(JSON.stringify({ok:!1,code:"FILE_WRITE_ERROR",message:`Cannot write to ${o}: ${_}`})+`
|
|
112
112
|
`),1}return r.write(`saved: ${o} (${f.length} bytes)
|
|
113
|
-
`),0}let m=u!==void 0?String(u):"?";return r.write(`attachment ${i}: filename=${
|
|
113
|
+
`),0}let m=u!==void 0?String(u):"?";return r.write(`attachment ${i}: filename=${l} mime_type=${d} size_bytes=${m}
|
|
114
114
|
`),r.write(`(pass --out <path> to save the decoded bytes to a file)
|
|
115
|
-
`),0}async function
|
|
116
|
-
`),1}}async function
|
|
117
|
-
`),1)}async function
|
|
118
|
-
`),1;let a={op:"update"};i!==void 0&&(a.display_name=i),o!==void 0&&(a.description=o);let c=await ue(e,t,"profile",a);return c.ok?(
|
|
119
|
-
`),1)}function
|
|
115
|
+
`),0}async function ih(n,e,t,r,s,i){switch(n){case"show":return oh(e,t,r,s,i);case"update":return ah(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown profile subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
116
|
+
`),1}}async function oh(n,e,t,r,s){let i=dt(n),o={op:"show"};i!==void 0&&(o.handle=i);let a=await ue(e,t,"profile",o);return a.ok?(To(a.data,r),0):(s.write(JSON.stringify(a.error)+`
|
|
117
|
+
`),1)}async function ah(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 ue(e,t,"profile",a);return c.ok?(To(c.data,r),0):(s.write(JSON.stringify(c.error)+`
|
|
119
|
+
`),1)}function To(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 ue(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
|
|
126
|
-
`);return}for(let s of r)e.write(
|
|
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 lr(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
|
|
125
|
+
`)}}async function ue(n,e,t,r){let s;try{s=await fetch(`${n}/act`,{method:"POST",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify({action:t,payload:r})})}catch(a){let c=a instanceof Error?a.message:String(a);return{ok:!1,error:{ok:!1,code:"PROXY_UNREACHABLE",message:`Cannot reach proxy at ${n}: ${c}`}}}let i=await s.text().catch(()=>"");if(s.ok){let a=i;try{a=JSON.parse(i)}catch{}return{ok:!0,data:a}}let o;try{if(o=JSON.parse(i),typeof o.code!="string")throw new Error("no code")}catch{o={ok:!1,code:"PROXY_ERROR",message:i||`HTTP ${s.status}`}}return{ok:!1,error:o}}function ch(n){let e=n.channel??"",t=String(n.short_id??n.id??"").slice(0,8),r=n.created_at??"",s=n.type??"human",i=n.display_name??n.sender_id??"unknown",o=n.content??"";return`[target=${e} msg=${t} time=${r} type=${s}] @${i}: ${o}`}function Co(n,e){let t=n,r=Array.isArray(t?.messages)?t.messages:[];if(r.length===0){e.write(`(no messages)
|
|
126
|
+
`);return}for(let s of r)e.write(ch(s)+`
|
|
127
|
+
`)}function 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 lr(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 Ro(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 ko,dh,Ao=A(()=>{"use strict";ko={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".heic":"image/heic",".webp":"image/webp",".gif":"image/gif"};dh=`mio-agent agentcli \u2014 agent-facing message CLI (Slice 1)
|
|
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 Co={};Be(Co,{runAgentcliCommand:()=>oh});async function oh(){return ko(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var Ro=R(()=>{"use strict";To()});import{execFileSync as Cs}from"child_process";function fr(n){return Cs("security",["add-generic-password","-U","-s",dr,"-a",ur,"-w",n]),`${dr}:${ur}`}function xt(){return Cs("security",["find-generic-password","-s",dr,"-a",ur,"-w"]).toString().trim()}function Ao(){Cs("security",["delete-generic-password","-s",dr,"-a",ur])}var dr,ur,Kt=R(()=>{"use strict";dr="io.miomioos.mio-agent",ur="machine_token"});var Rs=Z((Dw,Oo)=>{Oo.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var No=Z((Bw,Io)=>{var ah=Rs();function Po(n){this.mode=ah.MODE_8BIT_BYTE,this.data=n}Po.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)}};Io.exports=Po});var As=Z((Uw,Mo)=>{var ze={glog:function(n){if(n<1)throw new Error("glog("+n+")");return ze.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return ze.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(he=0;he<8;he++)ze.EXP_TABLE[he]=1<<he;var he;for(he=8;he<256;he++)ze.EXP_TABLE[he]=ze.EXP_TABLE[he-4]^ze.EXP_TABLE[he-5]^ze.EXP_TABLE[he-6]^ze.EXP_TABLE[he-8];var he;for(he=0;he<255;he++)ze.LOG_TABLE[ze.EXP_TABLE[he]]=he;var he;Mo.exports=ze});var Os=Z((Fw,Lo)=>{var Lt=As();function hr(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]}hr.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]^=Lt.gexp(Lt.glog(this.get(t))+Lt.glog(n.get(r)));return new hr(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=Lt.glog(this.get(0))-Lt.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]^=Lt.gexp(Lt.glog(n.get(s))+e);return new hr(t,0).mod(n)}};Lo.exports=hr});var Do=Z((Hw,$o)=>{$o.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Fo=Z((qw,Uo)=>{var He=Rs(),Bo=Os(),ch=As(),Tt=Do(),we={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;we.getBCHDigit(e)-we.getBCHDigit(we.G15)>=0;)e^=we.G15<<we.getBCHDigit(e)-we.getBCHDigit(we.G15);return(n<<10|e)^we.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;we.getBCHDigit(e)-we.getBCHDigit(we.G18)>=0;)e^=we.G18<<we.getBCHDigit(e)-we.getBCHDigit(we.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return we.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case Tt.PATTERN000:return(e+t)%2===0;case Tt.PATTERN001:return e%2===0;case Tt.PATTERN010:return t%3===0;case Tt.PATTERN011:return(e+t)%3===0;case Tt.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case Tt.PATTERN101:return e*t%2+e*t%3===0;case Tt.PATTERN110:return(e*t%2+e*t%3)%2===0;case Tt.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new Bo([1],0),t=0;t<n;t++)e=e.multiply(new Bo([1,ch.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case He.MODE_NUMBER:return 10;case He.MODE_ALPHA_NUM:return 9;case He.MODE_8BIT_BYTE:return 8;case He.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case He.MODE_NUMBER:return 12;case He.MODE_ALPHA_NUM:return 11;case He.MODE_8BIT_BYTE:return 16;case He.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case He.MODE_NUMBER:return 14;case He.MODE_ALPHA_NUM:return 13;case He.MODE_8BIT_BYTE:return 16;case He.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}};Uo.exports=we});var Ps=Z((Gw,Ho)=>{Ho.exports={L:1,M:0,Q:3,H:2}});var Go=Z((Ww,qo)=>{var gr=Ps();function rt(n,e){this.totalCount=n,this.dataCount=e}rt.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]];rt.getRSBlocks=function(n,e){var t=rt.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 rt(a,c));return s};rt.getRsBlockTable=function(n,e){switch(e){case gr.L:return rt.RS_BLOCK_TABLE[(n-1)*4+0];case gr.M:return rt.RS_BLOCK_TABLE[(n-1)*4+1];case gr.Q:return rt.RS_BLOCK_TABLE[(n-1)*4+2];case gr.H:return rt.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};qo.exports=rt});var Jo=Z((jw,jo)=>{function Wo(){this.buffer=[],this.length=0}Wo.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++}};jo.exports=Wo});var Ko=Z((Jw,zo)=>{var lh=No(),Ct=Fo(),dh=Os(),Yo=Go(),Vo=Jo();function st(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}st.prototype={addData:function(n){var e=new lh(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=Yo.getRSBlocks(n,this.errorCorrectLevel),t=new Vo,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(),Ct.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=st.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=Ct.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=Ct.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=Ct.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=Ct.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=Ct.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}}}};st.PAD0=236;st.PAD1=17;st.createData=function(n,e,t){for(var r=Yo.getRSBlocks(n,e),s=new Vo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Ct.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(st.PAD0,8),s.getLengthInBits()>=a*8));)s.put(st.PAD1,8);return st.createBytes(s,r)};st.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=Ct.getErrorCorrectPolynomial(d),m=new dh(i[a],u.getLength()-1),p=m.mod(u);o[a]=new Array(u.getLength()-1);for(var f=0;f<o[a].length;f++){var g=f+p.getLength()-o[a].length;o[a][f]=g>=0?p.get(g):0}}for(var w=0,E=0;E<e.length;E++)w+=e[E].totalCount;for(var v=new Array(w),_=0,S=0;S<r;S++)for(var N=0;N<e.length;N++)S<i[N].length&&(v[_++]=i[N][S]);for(var T=0;T<s;T++)for(var I=0;I<e.length;I++)T<o[I].length&&(v[_++]=o[I][T]);return v};zo.exports=st});var Ns=Z((Yw,Qo)=>{var uh=Ko(),Xo=Ps(),fh="\x1B[40m \x1B[0m",pr="\x1B[47m \x1B[0m",hh=function(n){return n?fh:pr},Is=function(n){return{times:function(e){return new Array(e).join(n)}}},gh=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};Qo.exports={error:Xo.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new uh(-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(gh(a,o));var l={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=Is(l.BLACK_WHITE).times(a+3),m=Is(l.WHITE_BLACK).times(a+3);s+=u+`
|
|
191
|
-
`;for(var p=0;p<a;p+=2){s+=
|
|
192
|
-
`}
|
|
193
|
-
`,r.modules.forEach(function(
|
|
194
|
-
`}),s+=g}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=
|
|
190
|
+
`});var Oo={};Be(Oo,{runAgentcliCommand:()=>lh});async function lh(){return xo(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var Po=A(()=>{"use strict";Ao()});import{execFileSync as As}from"child_process";function hr(n){return As("security",["add-generic-password","-U","-s",ur,"-a",fr,"-w",n]),`${ur}:${fr}`}function xt(){return As("security",["find-generic-password","-s",ur,"-a",fr,"-w"]).toString().trim()}function Io(){As("security",["delete-generic-password","-s",ur,"-a",fr])}var ur,fr,Kt=A(()=>{"use strict";ur="io.miomioos.mio-agent",fr="machine_token"});var Os=Z((Hw,No)=>{No.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var $o=Z((qw,Lo)=>{var uh=Os();function Mo(n){this.mode=uh.MODE_8BIT_BYTE,this.data=n}Mo.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)}};Lo.exports=Mo});var Ps=Z((Gw,Do)=>{var Ve={glog:function(n){if(n<1)throw new Error("glog("+n+")");return Ve.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return Ve.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(he=0;he<8;he++)Ve.EXP_TABLE[he]=1<<he;var he;for(he=8;he<256;he++)Ve.EXP_TABLE[he]=Ve.EXP_TABLE[he-4]^Ve.EXP_TABLE[he-5]^Ve.EXP_TABLE[he-6]^Ve.EXP_TABLE[he-8];var he;for(he=0;he<255;he++)Ve.LOG_TABLE[Ve.EXP_TABLE[he]]=he;var he;Do.exports=Ve});var Is=Z((Ww,Bo)=>{var Lt=Ps();function gr(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]}gr.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]^=Lt.gexp(Lt.glog(this.get(t))+Lt.glog(n.get(r)));return new gr(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=Lt.glog(this.get(0))-Lt.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]^=Lt.gexp(Lt.glog(n.get(s))+e);return new gr(t,0).mod(n)}};Bo.exports=gr});var Fo=Z((jw,Uo)=>{Uo.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var Go=Z((Jw,qo)=>{var He=Os(),Ho=Is(),fh=Ps(),Tt=Fo(),we={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;we.getBCHDigit(e)-we.getBCHDigit(we.G15)>=0;)e^=we.G15<<we.getBCHDigit(e)-we.getBCHDigit(we.G15);return(n<<10|e)^we.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;we.getBCHDigit(e)-we.getBCHDigit(we.G18)>=0;)e^=we.G18<<we.getBCHDigit(e)-we.getBCHDigit(we.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return we.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case Tt.PATTERN000:return(e+t)%2===0;case Tt.PATTERN001:return e%2===0;case Tt.PATTERN010:return t%3===0;case Tt.PATTERN011:return(e+t)%3===0;case Tt.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case Tt.PATTERN101:return e*t%2+e*t%3===0;case Tt.PATTERN110:return(e*t%2+e*t%3)%2===0;case Tt.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new Ho([1],0),t=0;t<n;t++)e=e.multiply(new Ho([1,fh.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case He.MODE_NUMBER:return 10;case He.MODE_ALPHA_NUM:return 9;case He.MODE_8BIT_BYTE:return 8;case He.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case He.MODE_NUMBER:return 12;case He.MODE_ALPHA_NUM:return 11;case He.MODE_8BIT_BYTE:return 16;case He.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case He.MODE_NUMBER:return 14;case He.MODE_ALPHA_NUM:return 13;case He.MODE_8BIT_BYTE:return 16;case He.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}};qo.exports=we});var Ns=Z((Yw,Wo)=>{Wo.exports={L:1,M:0,Q:3,H:2}});var Jo=Z((Vw,jo)=>{var pr=Ns();function rt(n,e){this.totalCount=n,this.dataCount=e}rt.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]];rt.getRSBlocks=function(n,e){var t=rt.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 rt(a,c));return s};rt.getRsBlockTable=function(n,e){switch(e){case pr.L:return rt.RS_BLOCK_TABLE[(n-1)*4+0];case pr.M:return rt.RS_BLOCK_TABLE[(n-1)*4+1];case pr.Q:return rt.RS_BLOCK_TABLE[(n-1)*4+2];case pr.H:return rt.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};jo.exports=rt});var zo=Z((zw,Vo)=>{function Yo(){this.buffer=[],this.length=0}Yo.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++}};Vo.exports=Yo});var Zo=Z((Kw,Qo)=>{var hh=$o(),Ct=Go(),gh=Is(),Ko=Jo(),Xo=zo();function st(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}st.prototype={addData:function(n){var e=new hh(n);this.dataList.push(e),this.dataCache=null},isDark:function(n,e){if(n<0||this.moduleCount<=n||e<0||this.moduleCount<=e)throw new Error(n+","+e);return this.modules[n][e]},getModuleCount:function(){return this.moduleCount},make:function(){if(this.typeNumber<1){var n=1;for(n=1;n<40;n++){for(var e=Ko.getRSBlocks(n,this.errorCorrectLevel),t=new Xo,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(),Ct.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=st.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=Ct.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=Ct.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=Ct.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=Ct.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=Ct.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}}}};st.PAD0=236;st.PAD1=17;st.createData=function(n,e,t){for(var r=Ko.getRSBlocks(n,e),s=new Xo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),Ct.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(st.PAD0,8),s.getLengthInBits()>=a*8));)s.put(st.PAD1,8);return st.createBytes(s,r)};st.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=Ct.getErrorCorrectPolynomial(l),m=new gh(i[a],u.getLength()-1),p=m.mod(u);o[a]=new Array(u.getLength()-1);for(var f=0;f<o[a].length;f++){var g=f+p.getLength()-o[a].length;o[a][f]=g>=0?p.get(g):0}}for(var _=0,E=0;E<e.length;E++)_+=e[E].totalCount;for(var v=new Array(_),y=0,S=0;S<r;S++)for(var N=0;N<e.length;N++)S<i[N].length&&(v[y++]=i[N][S]);for(var T=0;T<s;T++)for(var I=0;I<e.length;I++)T<o[I].length&&(v[y++]=o[I][T]);return v};Qo.exports=st});var Ls=Z((Xw,ta)=>{var ph=Zo(),ea=Ns(),mh="\x1B[40m \x1B[0m",mr="\x1B[47m \x1B[0m",yh=function(n){return n?mh:mr},Ms=function(n){return{times:function(e){return new Array(e).join(n)}}},_h=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};ta.exports={error:ea.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new ph(-1,this.error);r.addData(n),r.make();var s="";if(e&&e.small){var i=!0,o=!1,a=r.getModuleCount(),c=r.modules.slice(),l=a%2===1;l&&c.push(_h(a,o));var d={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=Ms(d.BLACK_WHITE).times(a+3),m=Ms(d.WHITE_BLACK).times(a+3);s+=u+`
|
|
191
|
+
`;for(var p=0;p<a;p+=2){s+=d.WHITE_ALL;for(var f=0;f<a;f++)c[p][f]===o&&c[p+1][f]===o?s+=d.WHITE_ALL:c[p][f]===o&&c[p+1][f]===i?s+=d.WHITE_BLACK:c[p][f]===i&&c[p+1][f]===o?s+=d.BLACK_WHITE:s+=d.BLACK_ALL;s+=d.WHITE_ALL+`
|
|
192
|
+
`}l||(s+=m)}else{var g=Ms(mr).times(r.getModuleCount()+3);s+=g+`
|
|
193
|
+
`,r.modules.forEach(function(_){s+=mr,s+=_.map(yh).join(""),s+=mr+`
|
|
194
|
+
`}),s+=g}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=ea[n]||this.error}}});var oa={};Be(oa,{runLogin:()=>xh});import{parseArgs as wh}from"node:util";import Tn from"node:os";import{mkdirSync as vh,writeFileSync as bh,existsSync as kh}from"node:fs";import{join as na}from"node:path";function Eh(n){return new Promise(e=>setTimeout(e,n))}function ia(){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: ${
|
|
199
|
+
--server <url> MioServer base URL (default: ${$s})
|
|
200
200
|
--device-name <name> Friendly name for this machine (default: hostname)
|
|
201
201
|
--help Show this message
|
|
202
|
-
`)}async function
|
|
203
|
-
`);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=
|
|
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 S=!1,N=!1,T=qa.parse(o.url),I;switch(T.protocol){case"https:":S=!0;case"http:":I=T.hostname;break;case"file:":N=!0;break;case void 0:case"":I="localhost";break;default:throw new Error("Protocol not supported.")}if(N){if(o.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(o.async)Zt.readFile(unescape(T.pathname),function(A,O){A?e.handleError(A,A.errno||-1):(e.status=200,e.responseText=O.toString("utf8"),e.response=O,v(e.DONE))});else try{this.response=Zt.readFileSync(unescape(T.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,v(e.DONE)}catch(A){this.handleError(A,A.errno||-1)}return}var q=T.port||(S?443:80),W=T.pathname+(T.search?T.search:"");if(d.Host=I,S&&q===443||q===80||(d.Host+=":"+T.port),o.user){typeof o.password>"u"&&(o.password="");var J=new Buffer(o.user+":"+o.password);d.Authorization="Basic "+J.toString("base64")}if(o.method==="GET"||o.method==="HEAD")_=null;else if(_){d["Content-Length"]=Buffer.isBuffer(_)?_.length:Buffer.byteLength(_);var re=Object.keys(d);re.some(function(A){return A.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(d["Content-Length"]=0);var X=n.agent||!1,j={host:I,port:q,path:W,method:o.method,headers:d,agent:X};if(S&&(j.pfx=n.pfx,j.key=n.key,j.passphrase=n.passphrase,j.cert=n.cert,j.ca=n.ca,j.ciphers=n.ciphers,j.rejectUnauthorized=n.rejectUnauthorized!==!1),p=!1,o.async){var ie=S?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var de=function(A){if(i=A,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var O=qa.parse(o.url);I=O.hostname;var M={hostname:O.hostname,port:O.port,path:O.path,method:i.statusCode===303?"GET":o.method,headers:d};S&&(M.pfx=n.pfx,M.key=n.key,M.passphrase=n.passphrase,M.cert=n.cert,M.ca=n.ca,M.ciphers=n.ciphers,M.rejectUnauthorized=n.rejectUnauthorized!==!1),s=ie(M,de).on("error",D),s.end();return}v(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(Y){if(Y){var ee=Buffer.from(Y);e.response=Buffer.concat([e.response,ee])}m&&v(e.LOADING)}),i.on("end",function(){m&&(m=!1,v(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(Y){e.handleError(Y)})},D=function(A){if(s.reusedSocket&&A.code==="ECONNRESET")return ie(j,de).on("error",D);e.handleError(A)};s=ie(j,de).on("error",D),n.autoUnref&&s.on("socket",A=>{A.unref()}),_&&s.write(_),s.end(),e.dispatchEvent("loadstart")}else{var Q=".node-xmlhttprequest-content-"+process.pid,y=".node-xmlhttprequest-sync-"+process.pid;Zt.writeFileSync(y,"","utf8");for(var b="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(S?"s":"")+".request;var options = "+JSON.stringify(j)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+Q+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+y+"');});response.on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+y+"');});}).on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+y+"');});"+(_?"req.write('"+JSON.stringify(_).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",C=$h(process.argv[0],["-e",b]),B;Zt.existsSync(y););if(e.responseText=Zt.readFileSync(Q,"utf8"),C.stdin.end(),Zt.unlinkSync(Q),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var F=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(F,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var k=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:k.data.headers},e.responseText=k.data.text,e.response=Buffer.from(k.data.data,"base64"),v(e.DONE,!0)}}},this.handleError=function(_,S){this.status=S||0,this.statusText=_,this.responseText=_.stack,p=!0,v(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),p=f=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||m)&&this.readyState!==this.DONE&&(m=!1,v(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(_,S){_ in g||(g[_]=[]),g[_].push(S)},this.removeEventListener=function(_,S){_ in g&&(g[_]=g[_].filter(function(N){return N!==S}))},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 S=0,N=g[_].length;S<N;S++)this.readyState===this.DONE?setTimeout(function(){g[_][S].call(e)},0):g[_][S].call(e)};var v=function(_){if(!(e.readyState===_||e.readyState===e.UNSENT&&f)&&(e.readyState=_,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let S;f?S="abort":p?S="error":S="load",e.dispatchEvent(S),e.dispatchEvent("loadend")}}}});var Qe,Pn,In,_r=R(()=>{Qe=Object.create(null);Qe.open="0";Qe.close="1";Qe.ping="2";Qe.pong="3";Qe.message="4";Qe.upgrade="5";Qe.noop="6";Pn=Object.create(null);Object.keys(Qe).forEach(n=>{Pn[Qe[n]]=n});In={type:"error",data:"parser error"}});function Ja(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(ja(n.data,!1));Nn(n,!0,t=>{Us||(Us=new TextEncoder),e(Us.encode(t))})}var Nn,ja,Us,Ya=R(()=>{_r();Nn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+ja(e,!0).toString("base64")):r(Qe[n]+(e||"")),ja=(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 Mn,Va,za=R(()=>{_r();Mn=(n,e)=>{if(typeof n!="string")return{type:"message",data:Va(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:Va(r,e)}}return Pn[t]?n.length>1?{type:Pn[t],data:n.substring(1)}:{type:Pn[t]}:In},Va=(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 Za(){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 wr(n){return n.reduce((e,t)=>e+t.length,0)}function vr(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 ec(n,e){Fs||(Fs=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(wr(t)<1)break;let c=vr(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(wr(t)<2)break;let c=vr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(wr(t)<8)break;let c=vr(t,8),d=new DataView(c.buffer,c.byteOffset,c.length),l=d.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(In);break}s=l*Math.pow(2,32)+d.getUint32(4),r=3}else{if(wr(t)<s)break;let c=vr(t,s);a.enqueue(Mn(i?c:Fs.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(In);break}}}})}var Ka,Xa,Qa,Fs,Hs,en=R(()=>{Ya();za();_r();Ka="",Xa=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Nn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(Ka))})})},Qa=(n,e)=>{let t=n.split(Ka),r=[];for(let s=0;s<t.length;s++){let i=Mn(t[s],e);if(r.push(i),i.type==="error")break}return r};Hs=4});var Dt=Z(tc=>{tc.Emitter=Re;function Re(n){if(n)return Dh(n)}function Dh(n){for(var e in Re.prototype)n[e]=Re.prototype[e];return n}Re.prototype.on=Re.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Re.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Re.prototype.off=Re.prototype.removeListener=Re.prototype.removeAllListeners=Re.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};Re.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};Re.prototype.emitReserved=Re.prototype.emit;Re.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Re.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function rc(){return new qs}function Bh(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 ut,Ae,nc,qs,Bt=R(()=>{ut=process.nextTick,Ae=global,nc="nodebuffer";qs=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=Bh(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 br(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function ft(n,e){e.useNativeTimers?(n.setTimeoutFn=Uh.bind(Ae),n.clearTimeoutFn=Fh.bind(Ae)):(n.setTimeoutFn=Ae.setTimeout.bind(Ae),n.clearTimeoutFn=Ae.clearTimeout.bind(Ae))}function sc(n){return typeof n=="string"?qh(n):Math.ceil((n.byteLength||n.size)*Hh)}function qh(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 kr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Uh,Fh,Hh,Ut=R(()=>{Bt();Uh=Ae.setTimeout,Fh=Ae.clearTimeout;Hh=1.33});function ic(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function oc(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 Gs=R(()=>{});var cc=Z((Av,ac)=>{var tn=1e3,nn=tn*60,rn=nn*60,Ft=rn*24,Gh=Ft*7,Wh=Ft*365.25;ac.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return jh(n);if(t==="number"&&isFinite(n))return e.long?Yh(n):Jh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function jh(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*Wh;case"weeks":case"week":case"w":return t*Gh;case"days":case"day":case"d":return t*Ft;case"hours":case"hour":case"hrs":case"hr":case"h":return t*rn;case"minutes":case"minute":case"mins":case"min":case"m":return t*nn;case"seconds":case"second":case"secs":case"sec":case"s":return t*tn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Jh(n){var e=Math.abs(n);return e>=Ft?Math.round(n/Ft)+"d":e>=rn?Math.round(n/rn)+"h":e>=nn?Math.round(n/nn)+"m":e>=tn?Math.round(n/tn)+"s":n+"ms"}function Yh(n){var e=Math.abs(n);return e>=Ft?Sr(n,e,Ft,"day"):e>=rn?Sr(n,e,rn,"hour"):e>=nn?Sr(n,e,nn,"minute"):e>=tn?Sr(n,e,tn,"second"):n+" ms"}function Sr(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Ws=Z((Ov,lc)=>{function Vh(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=cc(),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,p,f;function g(...w){if(!g.enabled)return;let E=g,v=Number(new Date),_=v-(u||v);E.diff=_,E.prev=u,E.curr=v,u=v,w[0]=t.coerce(w[0]),typeof w[0]!="string"&&w.unshift("%O");let S=0;w[0]=w[0].replace(/%([a-zA-Z%])/g,(T,I)=>{if(T==="%%")return"%";S++;let q=t.formatters[I];if(typeof q=="function"){let W=w[S];T=q.call(E,W),w.splice(S,1),S--}return T}),t.formatArgs.call(E,w),(E.log||t.log).apply(E,w)}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:(p!==t.namespaces&&(p=t.namespaces,f=t.enabled(l)),f),set:w=>{m=w}}),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,p=0,f=-1,g=0;for(;m<l.length;)if(p<u.length&&(u[p]===l[m]||u[p]==="*"))u[p]==="*"?(f=p,g=m,p++):(m++,p++);else if(f!==-1)p=f+1,g++,m=g;else return!1;for(;p<u.length&&u[p]==="*";)p++;return p===u.length}function o(){let 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}lc.exports=Vh});var dc=Z((Ne,Er)=>{Ne.formatArgs=Kh;Ne.save=Xh;Ne.load=Qh;Ne.useColors=zh;Ne.storage=Zh();Ne.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`."))}})();Ne.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function zh(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function Kh(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+Er.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)}Ne.log=console.debug||console.log||(()=>{});function Xh(n){try{n?Ne.storage.setItem("debug",n):Ne.storage.removeItem("debug")}catch{}}function Qh(){let n;try{n=Ne.storage.getItem("debug")||Ne.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function Zh(){try{return localStorage}catch{}}Er.exports=Ws()(Ne);var{formatters:eg}=Er.exports;eg.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var fc=Z((ye,Tr)=>{var tg=te("tty"),xr=te("util");ye.init=cg;ye.log=ig;ye.formatArgs=rg;ye.save=og;ye.load=ag;ye.useColors=ng;ye.destroy=xr.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ye.colors=[6,2,3,4,5,1];try{let n=te("supports-color");n&&(n.stderr||n).level>=2&&(ye.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{}ye.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 ng(){return"colors"in ye.inspectOpts?!!ye.inspectOpts.colors:tg.isatty(process.stderr.fd)}function rg(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 xh(n){let e;try{({values:e}=wh({args:n,options:{server:{type:"string",default:$s},"device-name":{type:"string",default:Tn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(y){let S=y instanceof Error?y.message:String(y);return console.error(`Error: ${S}`),ia(),1}if(e.help)return ia(),0;let t=(e.server??$s).replace(/\/+$/,""),r=e["device-name"]??Tn.hostname(),s=Tn.platform(),i=Tn.arch(),o;try{let y=await fetch(`${t}/api/v1/enrollment-intents`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_name:r,platform:s,arch:i})});if(!y.ok)return console.error(`Failed to create enrollment intent (HTTP ${y.status}). Check --server (currently ${t}).`),1;o=await y.json()}catch(y){let S=y instanceof Error?y.message:String(y);return console.error(`Network error contacting ${t}: ${S}`),1}let a=new URLSearchParams({code:o.opaque_code,server:t,name:r,platform:s,arch:i}),c=`mio://enroll/${o.intent_id}?${a.toString()}`;console.log("Open CodeLight on your phone and scan the QR (or use iOS Camera):"),console.log("");let l=await Promise.resolve().then(()=>oe(Ls(),1)).catch(()=>null),d=l?.default??l,u=typeof d?.generate=="function"?(y,S,N)=>d.generate(y,S,N):null;u?await new Promise(y=>{u(c,{small:!0},S=>{console.log(S),y()})}):console.log("(qrcode-terminal unavailable \u2014 paste the URL below into iOS Safari instead.)"),console.log(`(or paste this URL into Safari on iPhone: ${c})`),console.log(""),console.log(`Intent expires at ${o.expires_at}.`),console.log("Waiting for phone approval (up to 5 minutes)...");let m=Date.now(),p=ra,f=null;for(;Date.now()-m<Sh;){await Eh(p);try{let y=await fetch(`${t}/api/v1/enrollment-intents/${o.intent_id}?code=${encodeURIComponent(o.opaque_code)}`,{method:"GET"});if(y.status===200){f=await y.json();break}if(y.status===202){p=ra;continue}if(y.status===403)return console.error("Enrollment code became invalid (expired, canceled, or already consumed). Re-run `mio-agent login`."),1;p=Math.min(p*2,sa);continue}catch{p=Math.min(p*2,sa);continue}}if(!f)return console.error("Enrollment timed out (5 min). Re-run `mio-agent login` to retry."),1;let g=hr(f.machine_token),_=na(Tn.homedir(),".mio");kh(_)||vh(_,{recursive:!0,mode:448});let E=na(_,"agent.json"),v={machine_id:f.machine_id,org_id:f.org_id,workroom_id:f.workroom_id,server_url:t,keychain_item_ref:g,runtimes:[],token_buffer:!1};return bh(E,JSON.stringify(v,null,2),{mode:384}),console.log(""),console.log(`Successfully enrolled as "${r}" in workroom ${f.workroom_id.slice(0,8)}.`),console.log("Config: ~/.mio/agent.json (0600)"),console.log(`Token: macOS Keychain (${g})`),console.log(""),console.log("Run `mio-agent doctor` to verify."),0}var $s,ra,sa,Sh,aa=A(()=>{"use strict";Kt();$s="https://mio.wdao.chat",ra=2e3,sa=3e4,Sh=300*1e3});var da={};Be(da,{runLogs:()=>Ah});import{existsSync as Ds}from"node:fs";import{homedir as Th}from"node:os";import{join as ca}from"node:path";import{spawn as Ch}from"node:child_process";function Rh(){let n=Th(),e=ca(n,".mio","logs","mio-agent.log"),t=ca(n,".mio","logs","mio-agent-error.log"),r="/tmp/mio-agent.log",s=[];return Ds(e)&&s.push(e),Ds(t)&&s.push(t),s.length===0&&Ds(r)&&s.push(r),s}async function Ah(n){let e=!0,t=50;for(let o=0;o<n.length;o++){let a=n[o];if(a==="-f"||a==="--follow")e=!0;else if(a==="--no-follow")e=!1;else if(a==="-n"&&n[o+1]){let c=parseInt(n[++o],10);isNaN(c)||(t=c)}}let r=Rh();if(r.length===0)return console.error("No log file found."),console.error(" Looked for: ~/.mio/logs/mio-agent.log and /tmp/mio-agent.log"),console.error(" Run `mio-agent start` or `mio-agent install --background --version <v>` first."),1;console.error(`# tailing: ${r.join(", ")}
|
|
203
|
+
`);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=Ch("tail",s,{stdio:"inherit"});return await new Promise(o=>{i.on("exit",c=>o(c??0)),i.on("error",c=>{console.error(`Failed to spawn tail: ${c.message}`),o(1)});let a=()=>i.kill("SIGINT");process.on("SIGINT",a),process.on("SIGTERM",a)})}var la=A(()=>{"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 x(n,e,t){h("error",n,e,{error:t instanceof Error?t.message:String(t)})}var fe=A(()=>{"use strict"});import{readFileSync as Oh,writeFileSync as Ph,mkdirSync as Bs,chmodSync as Ih,existsSync as ua}from"fs";import{homedir as Nh}from"os";import{join as Cn}from"path";function Rn(){Bs(pe,{recursive:!0,mode:448}),Bs(Mh,{recursive:!0,mode:448}),Bs($t,{recursive:!0,mode:448})}function ha(){return ua(Xt)}function ze(){if(!ua(Xt))throw new Error(`No config at ${Xt}. Run: mio-agent login`);return JSON.parse(Oh(Xt,"utf-8"))}function yr(n){Rn();let e=JSON.stringify(n,null,2);Ph(Xt,e,{encoding:"utf-8",mode:384}),Ih(Xt,384)}var pe,Xt,Mh,$t,uv,fa,Ke=A(()=>{"use strict";pe=Cn(Nh(),".mio"),Xt=Cn(pe,"agent.json"),Mh=Cn(pe,"logs"),$t=Cn(pe,"tmp"),uv=Cn(pe,"agent.sock"),fa=7878});import{readFileSync as Lh,writeFileSync as $h,existsSync as Dh}from"fs";import{join as Bh}from"path";function ga(){if(!Dh(Us))return{};try{return JSON.parse(Lh(Us,"utf-8"))}catch{return{}}}function Uh(n){Rn(),$h(Us,JSON.stringify(n,null,2),{mode:384})}function pa(){let n=ga();return new Map(Object.entries(n))}function ma(n,e){let t=ga(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Uh(t))}var Us,ya=A(()=>{"use strict";Ke();Us=Bh(pe,"cursors.json")});async function se(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 An(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function me(n){return{Authorization:`Bearer ${n}`}}async function _a(n,e){return se(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:me(e)})}async function wa(n,e,t){return se(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:me(t),body:JSON.stringify({})})}async function va(n,e,t){await se(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:me(t),body:JSON.stringify({})})}async function ba(n,e,t=!1,r){await se(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:me(e),body:JSON.stringify(t?{going_offline:!0}:r?{usage:r}:{})})}async function ka(n,e,t,r){await se(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:me(r),body:JSON.stringify({status:t})})}async function Sa(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return se(s,{headers:me(r)})}async function Ea(n,e,t){return se(`${n}/api/v1/actions/${e}`,{headers:me(t)})}async function xa(n,e,t){return se(`${n}/api/v1/approvals/${e}`,{headers:me(t)})}async function Ta(n,e,t,r){let s=r?{approval_id:r}:{};return se(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:me(t),body:JSON.stringify(s)})}async function Ca(n,e,t){await se(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:me(t),body:JSON.stringify({})})}async function Ra(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 se(c,{headers:me(i)});return{messages:l.messages,hasMore:l.has_more}}async function Qt(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),se(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:me(s),body:JSON.stringify(i)})}async function Aa(n,e,t){return(await se(`${n}/api/v1/workrooms/${e}/members`,{headers:me(t)})).members??[]}async function Oa(n,e,t){return se(`${n}/api/v1/workrooms/${e}/roster`,{headers:me(t)})}async function Pa(n,e,t){return(await se(`${n}/api/v1/workrooms/${e}/channels`,{headers:me(t)})).channels??[]}async function Ia(n,e,t){return(await se(`${n}/internal/agent-api/channels`,{headers:{...me(e),"X-Mio-Agent-Id":t}})).channels??[]}async function _r(n,e,t,r){return(await se(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...me(e),"X-Mio-Agent-Id":t}})).tasks??[]}function qe(n,e){return{...me(n),"X-Mio-Agent-Id":e}}async function Na(n,e,t,r){return(await se(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:qe(e,t),body:JSON.stringify(r)})).reminder}async function Ma(n,e,t){return(await se(`${n}/internal/agent-api/reminders/list`,{headers:qe(e,t)})).reminders??[]}async function La(n,e,t,r){return(await se(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:qe(e,t),body:JSON.stringify(r)})).reminder}async function $a(n,e,t,r){return(await se(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:qe(e,t),body:JSON.stringify(r)})).reminder}async function Da(n,e,t,r){return(await se(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:qe(e,t),body:JSON.stringify(r)})).reminder}async function Ba(n,e,t){return(await se(`${n}/internal/agent-api/reminders/log`,{headers:qe(e,t)})).events??[]}async function Ua(n,e,t,r){await se(`${n}/internal/agent-api/typing`,{method:"POST",headers:qe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Fa(n,e,t,r){await se(`${n}/internal/agent-api/status`,{method:"POST",headers:qe(e,t),body:JSON.stringify({agent_id:t,...r})})}async function Ha(n,e,t,r){await se(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:qe(e,t),body:JSON.stringify(r)})}async function qa(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 se(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${a}`,{headers:qe(e,t)})).messages??[]}async function Ga(n,e,t,r){return(await se(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:qe(e,t)})).message}async function Wa(n,e,t,r){return se(`${n}/internal/agent-api/attachments/${r}`,{headers:qe(e,t)})}var An,On=A(()=>{"use strict";An=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 Ya=Z((_v,Ja)=>{var Zt=te("fs"),ja=te("url"),Fh=te("child_process").spawn;Ja.exports=Fs;Fs.XMLHttpRequest=Fs;function Fs(n){"use strict";n=n||{};var e=this,t=te("http"),r=te("https"),s,i,o={},a=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},l=Object.assign({},c),d=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],u=["TRACE","TRACK","CONNECT"],m=!1,p=!1,f=!1,g={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var _=function(y){return a||y&&d.indexOf(y.toLowerCase())===-1},E=function(y){return y&&u.indexOf(y)===-1};this.open=function(y,S,N,T,I){if(this.abort(),p=!1,f=!1,!E(y))throw new Error("SecurityError: Request method not allowed");o={method:y,url:S.toString(),async:typeof N!="boolean"?!0:N,user:T||null,password:I||null},v(this.OPENED)},this.setDisableHeaderCheck=function(y){a=y},this.setRequestHeader=function(y,S){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!_(y))return console.warn('Refused to set unsafe header "'+y+'"'),!1;if(m)throw new Error("INVALID_STATE_ERR: send flag is true");return l[y]=S,!0},this.getResponseHeader=function(y){return typeof y=="string"&&this.readyState>this.OPENED&&i.headers[y.toLowerCase()]&&!p?i.headers[y.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||p)return"";var y="";for(var S in i.headers)S!=="set-cookie"&&S!=="set-cookie2"&&(y+=S+": "+i.headers[S]+`\r
|
|
204
|
+
`);return y.substr(0,y.length-2)},this.getRequestHeader=function(y){return typeof y=="string"&&l[y]?l[y]:""},this.send=function(y){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(m)throw new Error("INVALID_STATE_ERR: send has already been called");var S=!1,N=!1,T=ja.parse(o.url),I;switch(T.protocol){case"https:":S=!0;case"http:":I=T.hostname;break;case"file:":N=!0;break;case void 0:case"":I="localhost";break;default:throw new Error("Protocol not supported.")}if(N){if(o.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(o.async)Zt.readFile(unescape(T.pathname),function(P,R){P?e.handleError(P,P.errno||-1):(e.status=200,e.responseText=R.toString("utf8"),e.response=R,v(e.DONE))});else try{this.response=Zt.readFileSync(unescape(T.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,v(e.DONE)}catch(P){this.handleError(P,P.errno||-1)}return}var q=T.port||(S?443:80),j=T.pathname+(T.search?T.search:"");if(l.Host=I,S&&q===443||q===80||(l.Host+=":"+T.port),o.user){typeof o.password>"u"&&(o.password="");var Y=new Buffer(o.user+":"+o.password);l.Authorization="Basic "+Y.toString("base64")}if(o.method==="GET"||o.method==="HEAD")y=null;else if(y){l["Content-Length"]=Buffer.isBuffer(y)?y.length:Buffer.byteLength(y);var re=Object.keys(l);re.some(function(P){return P.toLowerCase()==="content-type"})||(l["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(l["Content-Length"]=0);var X=n.agent||!1,J={host:I,port:q,path:j,method:o.method,headers:l,agent:X};if(S&&(J.pfx=n.pfx,J.key=n.key,J.passphrase=n.passphrase,J.cert=n.cert,J.ca=n.ca,J.ciphers=n.ciphers,J.rejectUnauthorized=n.rejectUnauthorized!==!1),p=!1,o.async){var ie=S?r.request:t.request;m=!0,e.dispatchEvent("readystatechange");var le=function(P){if(i=P,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var R=ja.parse(o.url);I=R.hostname;var $={hostname:R.hostname,port:R.port,path:R.path,method:i.statusCode===303?"GET":o.method,headers:l};S&&($.pfx=n.pfx,$.key=n.key,$.passphrase=n.passphrase,$.cert=n.cert,$.ca=n.ca,$.ciphers=n.ciphers,$.rejectUnauthorized=n.rejectUnauthorized!==!1),s=ie($,le).on("error",D),s.end();return}v(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(G){if(G){var ee=Buffer.from(G);e.response=Buffer.concat([e.response,ee])}m&&v(e.LOADING)}),i.on("end",function(){m&&(m=!1,v(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(G){e.handleError(G)})},D=function(P){if(s.reusedSocket&&P.code==="ECONNRESET")return ie(J,le).on("error",D);e.handleError(P)};s=ie(J,le).on("error",D),n.autoUnref&&s.on("socket",P=>{P.unref()}),y&&s.write(y),s.end(),e.dispatchEvent("loadstart")}else{var Q=".node-xmlhttprequest-content-"+process.pid,w=".node-xmlhttprequest-sync-"+process.pid;Zt.writeFileSync(w,"","utf8");for(var b="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(S?"s":"")+".request;var options = "+JSON.stringify(J)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+Q+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+w+"');});response.on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+w+"');});}).on('error', function(error) {fs.writeFileSync('"+Q+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+w+"');});"+(y?"req.write('"+JSON.stringify(y).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",C=Fh(process.argv[0],["-e",b]),B;Zt.existsSync(w););if(e.responseText=Zt.readFileSync(Q,"utf8"),C.stdin.end(),Zt.unlinkSync(Q),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var H=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(H,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var k=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:k.data.headers},e.responseText=k.data.text,e.response=Buffer.from(k.data.data,"base64"),v(e.DONE,!0)}}},this.handleError=function(y,S){this.status=S||0,this.statusText=y,this.responseText=y.stack,p=!0,v(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),l=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),p=f=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||m)&&this.readyState!==this.DONE&&(m=!1,v(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(y,S){y in g||(g[y]=[]),g[y].push(S)},this.removeEventListener=function(y,S){y in g&&(g[y]=g[y].filter(function(N){return N!==S}))},this.dispatchEvent=function(y){if(typeof e["on"+y]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+y]()},0):e["on"+y]()),y in g)for(let S=0,N=g[y].length;S<N;S++)this.readyState===this.DONE?setTimeout(function(){g[y][S].call(e)},0):g[y][S].call(e)};var v=function(y){if(!(e.readyState===y||e.readyState===e.UNSENT&&f)&&(e.readyState=y,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let S;f?S="abort":p?S="error":S="load",e.dispatchEvent(S),e.dispatchEvent("loadend")}}}});var Xe,Pn,In,wr=A(()=>{Xe=Object.create(null);Xe.open="0";Xe.close="1";Xe.ping="2";Xe.pong="3";Xe.message="4";Xe.upgrade="5";Xe.noop="6";Pn=Object.create(null);Object.keys(Xe).forEach(n=>{Pn[Xe[n]]=n});In={type:"error",data:"parser error"}});function za(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(Va(n.data,!1));Nn(n,!0,t=>{Hs||(Hs=new TextEncoder),e(Hs.encode(t))})}var Nn,Va,Hs,Ka=A(()=>{wr();Nn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+Va(e,!0).toString("base64")):r(Xe[n]+(e||"")),Va=(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 Mn,Xa,Qa=A(()=>{wr();Mn=(n,e)=>{if(typeof n!="string")return{type:"message",data:Xa(n,e)};let t=n.charAt(0);if(t==="b"){let r=Buffer.from(n.substring(1),"base64");return{type:"message",data:Xa(r,e)}}return Pn[t]?n.length>1?{type:Pn[t],data:n.substring(1)}:{type:Pn[t]}:In},Xa=(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 nc(){return new TransformStream({transform(n,e){za(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 vr(n){return n.reduce((e,t)=>e+t.length,0)}function br(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 rc(n,e){qs||(qs=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(vr(t)<1)break;let c=br(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(vr(t)<2)break;let c=br(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(vr(t)<8)break;let c=br(t,8),l=new DataView(c.buffer,c.byteOffset,c.length),d=l.getUint32(0);if(d>Math.pow(2,21)-1){a.enqueue(In);break}s=d*Math.pow(2,32)+l.getUint32(4),r=3}else{if(vr(t)<s)break;let c=br(t,s);a.enqueue(Mn(i?c:qs.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(In);break}}}})}var Za,ec,tc,qs,Gs,en=A(()=>{Ka();Qa();wr();Za="",ec=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{Nn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(Za))})})},tc=(n,e)=>{let t=n.split(Za),r=[];for(let s=0;s<t.length;s++){let i=Mn(t[s],e);if(r.push(i),i.type==="error")break}return r};Gs=4});var Dt=Z(sc=>{sc.Emitter=Ce;function Ce(n){if(n)return Hh(n)}function Hh(n){for(var e in Ce.prototype)n[e]=Ce.prototype[e];return n}Ce.prototype.on=Ce.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};Ce.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};Ce.prototype.off=Ce.prototype.removeListener=Ce.prototype.removeAllListeners=Ce.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};Ce.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};Ce.prototype.emitReserved=Ce.prototype.emit;Ce.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};Ce.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function oc(){return new Ws}function qh(n){let e=n.split("; "),t=e[0].indexOf("=");if(t===-1)return;let r=e[0].substring(0,t).trim();if(!r.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:r,value:s};for(let o=1;o<e.length;o++){let a=e[o].split("=");if(a.length!==2)continue;let c=a[0].trim(),l=a[1].trim();switch(c){case"Expires":i.expires=new Date(l);break;case"Max-Age":let d=new Date;d.setUTCSeconds(d.getUTCSeconds()+parseInt(l,10)),i.expires=d;break;default:}}return i}var lt,Re,ic,Ws,Bt=A(()=>{lt=process.nextTick,Re=global,ic="nodebuffer";Ws=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=qh(t);r&&this._cookies.set(r.name,r)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,r)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(r)}),this._cookies.entries()}addCookies(e){let t=[];for(let[r,s]of this.cookies)t.push(`${r}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,r]of this.cookies)e.append("cookie",`${t}=${r.value}`)}}});function kr(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function ut(n,e){e.useNativeTimers?(n.setTimeoutFn=Gh.bind(Re),n.clearTimeoutFn=Wh.bind(Re)):(n.setTimeoutFn=Re.setTimeout.bind(Re),n.clearTimeoutFn=Re.clearTimeout.bind(Re))}function ac(n){return typeof n=="string"?Jh(n):Math.ceil((n.byteLength||n.size)*jh)}function Jh(n){let e=0,t=0;for(let r=0,s=n.length;r<s;r++)e=n.charCodeAt(r),e<128?t+=1:e<2048?t+=2:e<55296||e>=57344?t+=3:(r++,t+=4);return t}function Sr(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Gh,Wh,jh,Ut=A(()=>{Bt();Gh=Re.setTimeout,Wh=Re.clearTimeout;jh=1.33});function cc(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function dc(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 js=A(()=>{});var uc=Z((Nv,lc)=>{var tn=1e3,nn=tn*60,rn=nn*60,Ft=rn*24,Yh=Ft*7,Vh=Ft*365.25;lc.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return zh(n);if(t==="number"&&isFinite(n))return e.long?Xh(n):Kh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function zh(n){if(n=String(n),!(n.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(n);if(e){var t=parseFloat(e[1]),r=(e[2]||"ms").toLowerCase();switch(r){case"years":case"year":case"yrs":case"yr":case"y":return t*Vh;case"weeks":case"week":case"w":return t*Yh;case"days":case"day":case"d":return t*Ft;case"hours":case"hour":case"hrs":case"hr":case"h":return t*rn;case"minutes":case"minute":case"mins":case"min":case"m":return t*nn;case"seconds":case"second":case"secs":case"sec":case"s":return t*tn;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function Kh(n){var e=Math.abs(n);return e>=Ft?Math.round(n/Ft)+"d":e>=rn?Math.round(n/rn)+"h":e>=nn?Math.round(n/nn)+"m":e>=tn?Math.round(n/tn)+"s":n+"ms"}function Xh(n){var e=Math.abs(n);return e>=Ft?Er(n,e,Ft,"day"):e>=rn?Er(n,e,rn,"hour"):e>=nn?Er(n,e,nn,"minute"):e>=tn?Er(n,e,tn,"second"):n+" ms"}function Er(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Js=Z((Mv,fc)=>{function Qh(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=uc(),t.destroy=l,Object.keys(n).forEach(d=>{t[d]=n[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let u=0;for(let m=0;m<d.length;m++)u=(u<<5)-u+d.charCodeAt(m),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(d){let u,m=null,p,f;function g(..._){if(!g.enabled)return;let E=g,v=Number(new Date),y=v-(u||v);E.diff=y,E.prev=u,E.curr=v,u=v,_[0]=t.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let S=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(T,I)=>{if(T==="%%")return"%";S++;let q=t.formatters[I];if(typeof q=="function"){let j=_[S];T=q.call(E,j),_.splice(S,1),S--}return T}),t.formatArgs.call(E,_),(E.log||t.log).apply(E,_)}return g.namespace=d,g.useColors=t.useColors(),g.color=t.selectColor(d),g.extend=r,g.destroy=t.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(p!==t.namespaces&&(p=t.namespaces,f=t.enabled(d)),f),set:_=>{m=_}}),typeof t.init=="function"&&t.init(g),g}function r(d,u){let m=t(this.namespace+(typeof u>"u"?":":u)+d);return m.log=this.log,m}function s(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let u=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let m of u)m[0]==="-"?t.skips.push(m.slice(1)):t.names.push(m)}function i(d,u){let m=0,p=0,f=-1,g=0;for(;m<d.length;)if(p<u.length&&(u[p]===d[m]||u[p]==="*"))u[p]==="*"?(f=p,g=m,p++):(m++,p++);else if(f!==-1)p=f+1,g++,m=g;else return!1;for(;p<u.length&&u[p]==="*";)p++;return p===u.length}function o(){let d=[...t.names,...t.skips.map(u=>"-"+u)].join(",");return t.enable(""),d}function a(d){for(let u of t.skips)if(i(d,u))return!1;for(let u of t.names)if(i(d,u))return!0;return!1}function c(d){return d instanceof Error?d.stack||d.message:d}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}fc.exports=Qh});var hc=Z((Me,xr)=>{Me.formatArgs=eg;Me.save=tg;Me.load=ng;Me.useColors=Zh;Me.storage=rg();Me.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`."))}})();Me.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function Zh(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let n;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(n=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(n[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function eg(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+xr.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)}Me.log=console.debug||console.log||(()=>{});function tg(n){try{n?Me.storage.setItem("debug",n):Me.storage.removeItem("debug")}catch{}}function ng(){let n;try{n=Me.storage.getItem("debug")||Me.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function rg(){try{return localStorage}catch{}}xr.exports=Js()(Me);var{formatters:sg}=xr.exports;sg.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var pc=Z((ye,Cr)=>{var ig=te("tty"),Tr=te("util");ye.init=fg;ye.log=dg;ye.formatArgs=ag;ye.save=lg;ye.load=ug;ye.useColors=og;ye.destroy=Tr.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");ye.colors=[6,2,3,4,5,1];try{let n=te("supports-color");n&&(n.stderr||n).level>=2&&(ye.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{}ye.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function og(){return"colors"in ye.inspectOpts?!!ye.inspectOpts.colors:ig.isatty(process.stderr.fd)}function ag(n){let{namespace:e,useColors:t}=this;if(t){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${s};1m${e} \x1B[0m`;n[0]=i+n[0].split(`
|
|
205
205
|
`).join(`
|
|
206
|
-
`+i),n.push(s+"m+"+
|
|
207
|
-
`)}function
|
|
208
|
-
`).map(e=>e.trim()).join(" ")};uc.O=function(n){return this.inspectOpts.colors=this.useColors,xr.inspect(n,this.inspectOpts)}});var Ge=Z((Pv,js)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?js.exports=dc():js.exports=fc()});var hc,gc,lg,Cr,ht,Ln=R(()=>{en();hc=oe(Dt(),1);Ut();Gs();gc=oe(Ge(),1),lg=(0,gc.default)("engine.io-client:transport"),Cr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},ht=class extends hc.Emitter{constructor(e){super(),this.writable=!1,ft(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 Cr(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):lg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Mn(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=ic(e);return t.length?"?"+t:""}}});var pc,Ze,$n,Js=R(()=>{Ln();Ut();en();pc=oe(Ge(),1),Ze=(0,pc.default)("engine.io-client:polling"),$n=class extends ht{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)};Qa(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,Xa(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]=kr()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var mc,yc,_c=R(()=>{mc=!1;try{mc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}yc=mc});function dg(){}function wc(){for(let n in gt.requests)gt.requests.hasOwnProperty(n)&>.requests[n].abort()}function ug(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||yc))return new XMLHttpRequest}catch{}if(!e)try{return new Ae[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var vc,bc,Ys,Rr,gt,jv,Vs=R(()=>{Js();vc=oe(Dt(),1);Ut();Bt();_c();bc=oe(Ge(),1),Ys=(0,bc.default)("engine.io-client:polling");Rr=class extends $n{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(){Ys("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}},gt=class n extends vc.Emitter{constructor(e,t,r){super(),this.createRequest=e,ft(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=br(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{Ys("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))},Ys("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=dg,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()}};gt.requestsCount=0;gt.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",wc);else if(typeof addEventListener=="function"){let n="onpagehide"in Ae?"pagehide":"unload";addEventListener(n,wc,!1)}}jv=(function(){let n=ug({xdomain:!1});return n&&n.responseType!==null})()});var zs,fg,sn,Ks=R(()=>{zs=oe(Wa(),1);Vs();fg=zs.default||zs,sn=class extends Rr{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 gt(r=>new fg(r),this.uri(),e)}}});var pt=Z((zv,Ec)=>{"use strict";var kc=["nodebuffer","arraybuffer","fragments"],Sc=typeof Blob<"u";Sc&&kc.push("blob");Ec.exports={BINARY_TYPES:kc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Sc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Dn=Z((Kv,Ar)=>{"use strict";var{EMPTY_BUFFER:hg}=pt(),Xs=Buffer[Symbol.species];function gg(n,e){if(n.length===0)return hg;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 Xs(t.buffer,t.byteOffset,r):t}function xc(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Tc(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function pg(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Qs(n){if(Qs.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Xs(n):ArrayBuffer.isView(n)?e=new Xs(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Qs.readOnly=!1),e}Ar.exports={concat:gg,mask:xc,toArrayBuffer:pg,toBuffer:Qs,unmask:Tc};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=te("bufferutil");Ar.exports.mask=function(e,t,r,s,i){i<48?xc(e,t,r,s,i):n.mask(e,t,r,s,i)},Ar.exports.unmask=function(e,t){e.length<32?Tc(e,t):n.unmask(e,t)}}catch{}});var Ac=Z((Xv,Rc)=>{"use strict";var Cc=Symbol("kDone"),Zs=Symbol("kRun"),ei=class{constructor(e){this[Cc]=()=>{this.pending--,this[Zs]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Zs]()}[Zs](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Cc])}}};Rc.exports=ei});var cn=Z((Qv,Nc)=>{"use strict";var Bn=te("zlib"),Oc=Dn(),mg=Ac(),{kStatusCode:Pc}=pt(),yg=Buffer[Symbol.species],_g=Buffer.from([0,0,255,255]),Pr=Symbol("permessage-deflate"),mt=Symbol("total-length"),on=Symbol("callback"),Rt=Symbol("buffers"),an=Symbol("error"),Or,ti=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,!Or){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Or=new mg(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[on];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){Or.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Or.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"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Bn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Pr]=this,this._inflate[mt]=0,this._inflate[Rt]=[],this._inflate.on("error",vg),this._inflate.on("data",Ic)}this._inflate[on]=r,this._inflate.write(e),t&&this._inflate.write(_g),this._inflate.flush(()=>{let i=this._inflate[an];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Oc.concat(this._inflate[Rt],this._inflate[mt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[mt]=0,this._inflate[Rt]=[],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"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Bn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[mt]=0,this._deflate[Rt]=[],this._deflate.on("data",wg)}this._deflate[on]=r,this._deflate.write(e),this._deflate.flush(Bn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Oc.concat(this._deflate[Rt],this._deflate[mt]);t&&(i=new yg(i.buffer,i.byteOffset,i.length-4)),this._deflate[on]=null,this._deflate[mt]=0,this._deflate[Rt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};Nc.exports=ti;function wg(n){this[Rt].push(n),this[mt]+=n.length}function Ic(n){if(this[mt]+=n.length,this[Pr]._maxPayload<1||this[mt]<=this[Pr]._maxPayload){this[Rt].push(n);return}this[an]=new RangeError("Max payload size exceeded"),this[an].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[an][Pc]=1009,this.removeListener("data",Ic),this.reset()}function vg(n){if(this[Pr]._inflate=null,this[an]){this[on](this[an]);return}n[Pc]=1007,this[on](n)}});var ln=Z((Zv,Ir)=>{"use strict";var{isUtf8:Mc}=te("buffer"),{hasBlob:bg}=pt(),kg=[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 Sg(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function ni(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 Eg(n){return bg&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Ir.exports={isBlob:Eg,isValidStatusCode:Sg,isValidUTF8:ni,tokenChars:kg};if(Mc)Ir.exports.isValidUTF8=function(n){return n.length<24?ni(n):Mc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=te("utf-8-validate");Ir.exports.isValidUTF8=function(e){return e.length<32?ni(e):n(e)}}catch{}});var ai=Z((eb,Hc)=>{"use strict";var{Writable:xg}=te("stream"),Lc=cn(),{BINARY_TYPES:Tg,EMPTY_BUFFER:$c,kStatusCode:Cg,kWebSocket:Rg}=pt(),{concat:ri,toArrayBuffer:Ag,unmask:Og}=Dn(),{isValidStatusCode:Pg,isValidUTF8:Dc}=ln(),Nr=Buffer[Symbol.species],We=0,Bc=1,Uc=2,Fc=3,si=4,ii=5,Mr=6,oi=class extends xg{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Tg[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Rg]=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=We}_write(e,t,r){if(this._opcode===8&&this._state==We)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 Nr(r.buffer,r.byteOffset+e,r.length-e),new Nr(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 Nr(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 We:this.getInfo(e);break;case Bc:this.getPayloadLength16(e);break;case Uc:this.getPayloadLength64(e);break;case Fc:this.getMask();break;case si:this.getData(e);break;case ii:case Mr: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[Lc.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=Bc:this._payloadLength===127?this._state=Uc: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=Fc:this._state=si}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=si}getData(e){let t=$c;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&&Og(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ii,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Lc.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===We&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=We;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=ri(r,t):this._binaryType==="arraybuffer"?s=Ag(ri(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=We):(this._state=Mr,setImmediate(()=>{this.emit("message",s,!0),this._state=We,this.startLoop(e)}))}else{let s=ri(r,t);if(!this._skipUTF8Validation&&!Dc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ii||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=We):(this._state=Mr,setImmediate(()=>{this.emit("message",s,!1),this._state=We,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,$c),this.end();else{let r=e.readUInt16BE(0);if(!Pg(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Nr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Dc(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=We;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=We):(this._state=Mr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=We,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[Cg]=s,o}};Hc.exports=oi});var di=Z((nb,Wc)=>{"use strict";var{Duplex:tb}=te("stream"),{randomFillSync:Ig}=te("crypto"),{types:{isUint8Array:Ng}}=te("util"),qc=cn(),{EMPTY_BUFFER:Mg,kWebSocket:Lg,NOOP:$g}=pt(),{isBlob:dn,isValidStatusCode:Dg}=ln(),{mask:Gc,toBuffer:Ht}=Dn(),je=Symbol("kByteLength"),Bg=Buffer.alloc(4),Lr=8*1024,qt,un=Lr,et=0,Ug=1,Fg=2,ci=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=et,this.onerror=$g,this[Lg]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Bg,t.generateMask?t.generateMask(r):(un===Lr&&(qt===void 0&&(qt=Buffer.alloc(Lr)),Ig(qt,0,Lr),un=0),r[0]=qt[un++],r[1]=qt[un++],r[2]=qt[un++],r[3]=qt[un++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[je]!==void 0?a=t[je]:(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?(Gc(e,r,d,i,a),[d]):(Gc(e,r,e,0,a),[d,e])):[d,e]}close(e,t,r,s){let i;if(e===void 0)i=Mg;else{if(typeof e!="number"||!Dg(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(Ng(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[je]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==et?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):dn(e)?(s=e.size,i=!1):(e=Ht(e),s=e.length,i=Ht.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[je]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};dn(e)?this._state!==et?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==et?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):dn(e)?(s=e.size,i=!1):(e=Ht(e),s=e.length,i=Ht.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[je]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};dn(e)?this._state!==et?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==et?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[qc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):dn(e)?(a=e.size,c=!1):(e=Ht(e),a=e.length,c=Ht.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={[je]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};dn(e)?this._state!==et?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==et?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[je],this._state=Fg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(li,this,a,s);return}this._bufferedBytes-=r[je];let o=Ht(i);t?this.dispatch(o,t,r,s):(this._state=et,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Hg,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[qc.extensionName];this._bufferedBytes+=r[je],this._state=Ug,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");li(this,c,s);return}this._bufferedBytes-=r[je],this._state=et,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===et&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][je],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][je],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)}};Wc.exports=ci;function li(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 Hg(n,e,t){li(n,e,t),n.onerror(e)}});var Zc=Z((rb,Qc)=>{"use strict";var{kForOnEventAttribute:Un,kListener:ui}=pt(),jc=Symbol("kCode"),Jc=Symbol("kData"),Yc=Symbol("kError"),Vc=Symbol("kMessage"),zc=Symbol("kReason"),fn=Symbol("kTarget"),Kc=Symbol("kType"),Xc=Symbol("kWasClean"),yt=class{constructor(e){this[fn]=null,this[Kc]=e}get target(){return this[fn]}get type(){return this[Kc]}};Object.defineProperty(yt.prototype,"target",{enumerable:!0});Object.defineProperty(yt.prototype,"type",{enumerable:!0});var Gt=class extends yt{constructor(e,t={}){super(e),this[jc]=t.code===void 0?0:t.code,this[zc]=t.reason===void 0?"":t.reason,this[Xc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[jc]}get reason(){return this[zc]}get wasClean(){return this[Xc]}};Object.defineProperty(Gt.prototype,"code",{enumerable:!0});Object.defineProperty(Gt.prototype,"reason",{enumerable:!0});Object.defineProperty(Gt.prototype,"wasClean",{enumerable:!0});var hn=class extends yt{constructor(e,t={}){super(e),this[Yc]=t.error===void 0?null:t.error,this[Vc]=t.message===void 0?"":t.message}get error(){return this[Yc]}get message(){return this[Vc]}};Object.defineProperty(hn.prototype,"error",{enumerable:!0});Object.defineProperty(hn.prototype,"message",{enumerable:!0});var Fn=class extends yt{constructor(e,t={}){super(e),this[Jc]=t.data===void 0?null:t.data}get data(){return this[Jc]}};Object.defineProperty(Fn.prototype,"data",{enumerable:!0});var qg={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Un]&&s[ui]===e&&!s[Un])return;let r;if(n==="message")r=function(i,o){let a=new Fn("message",{data:o?i:i.toString()});a[fn]=this,$r(e,this,a)};else if(n==="close")r=function(i,o){let a=new Gt("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[fn]=this,$r(e,this,a)};else if(n==="error")r=function(i){let o=new hn("error",{error:i,message:i.message});o[fn]=this,$r(e,this,o)};else if(n==="open")r=function(){let i=new yt("open");i[fn]=this,$r(e,this,i)};else return;r[Un]=!!t[Un],r[ui]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[ui]===e&&!t[Un]){this.removeListener(n,t);break}}};Qc.exports={CloseEvent:Gt,ErrorEvent:hn,Event:yt,EventTarget:qg,MessageEvent:Fn};function $r(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Dr=Z((sb,el)=>{"use strict";var{tokenChars:Hn}=ln();function it(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Gg(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&&Hn[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 p=n.slice(c,l);d===44?(it(e,p,t),t=Object.create(null)):o=p,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&Hn[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),it(t,n.slice(c,l),!0),d===44&&(it(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(Hn[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(Hn[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&&Hn[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 p=n.slice(c,l);r&&(p=p.replace(/\\/g,""),r=!1),it(t,a,p),d===44&&(it(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?it(e,m,t):(a===void 0?it(t,m,!0):r?it(t,a,m.replace(/\\/g,"")):it(t,a,m),it(e,o,t)),e}function Wg(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(", ")}el.exports={format:Wg,parse:Gg}});var Hr=Z((ab,fl)=>{"use strict";var jg=te("events"),Jg=te("https"),Yg=te("http"),rl=te("net"),Vg=te("tls"),{randomBytes:zg,createHash:Kg}=te("crypto"),{Duplex:ib,Readable:ob}=te("stream"),{URL:fi}=te("url"),At=cn(),Xg=ai(),Qg=di(),{isBlob:Zg}=ln(),{BINARY_TYPES:tl,CLOSE_TIMEOUT:ep,EMPTY_BUFFER:Br,GUID:tp,kForOnEventAttribute:hi,kListener:np,kStatusCode:rp,kWebSocket:_e,NOOP:sl}=pt(),{EventTarget:{addEventListener:sp,removeEventListener:ip}}=Zc(),{format:op,parse:ap}=Dr(),{toBuffer:cp}=Dn(),il=Symbol("kAborted"),gi=[8,13],_t=["CONNECTING","OPEN","CLOSING","CLOSED"],lp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,le=class n extends jg{constructor(e,t,r){super(),this._binaryType=tl[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Br,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]),ol(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){tl.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 Xg({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new Qg(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[_e]=this,i[_e]=this,e[_e]=this,s.on("conclude",fp),s.on("drain",hp),s.on("error",gp),s.on("message",pp),s.on("ping",mp),s.on("pong",yp),i.onerror=_p,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",ll),e.on("data",Fr),e.on("end",dl),e.on("error",ul),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[At.extensionName]&&this._extensions[At.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){Ue(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())}),cl(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){pi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Br,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){pi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Br,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){pi(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[At.extensionName]||(s.compress=!1),this._sender.send(e||Br,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ue(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(le,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(le.prototype,"CONNECTING",{enumerable:!0,value:_t.indexOf("CONNECTING")});Object.defineProperty(le,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(le.prototype,"OPEN",{enumerable:!0,value:_t.indexOf("OPEN")});Object.defineProperty(le,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(le.prototype,"CLOSING",{enumerable:!0,value:_t.indexOf("CLOSING")});Object.defineProperty(le,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});Object.defineProperty(le.prototype,"CLOSED",{enumerable:!0,value:_t.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(le.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(le.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[hi])return e[np];return null},set(e){for(let t of this.listeners(n))if(t[hi]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[hi]:!0})}})});le.prototype.addEventListener=sp;le.prototype.removeEventListener=ip;fl.exports=le;function ol(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:ep,protocolVersion:gi[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,!gi.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${gi.join(", ")})`);let i;if(e instanceof fi)i=e;else try{i=new fi(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;Ur(n,g);return}let d=o?443:80,l=zg(16).toString("base64"),u=o?Jg.request:Yg.request,m=new Set,p;if(s.createConnection=s.createConnection||(o?up:dp),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&&(p=new At({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=op({[At.extensionName]:p.offer()})),t.length){for(let g of t){if(typeof g!="string"||!lp.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let f;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[w,E]of Object.entries(g))r.headers[w.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")),f=n._req=u(s),n._redirects&&n.emit("redirect",n.url,f)}else f=n._req=u(s);s.timeout&&f.on("timeout",()=>{Ue(n,f,"Opening handshake has timed out")}),f.on("error",g=>{f===null||f[il]||(f=n._req=null,Ur(n,g))}),f.on("response",g=>{let w=g.headers.location,E=g.statusCode;if(w&&s.followRedirects&&E>=300&&E<400){if(++n._redirects>s.maxRedirects){Ue(n,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new fi(w,e)}catch{let S=new SyntaxError(`Invalid URL: ${w}`);Ur(n,S);return}ol(n,v,t,r)}else n.emit("unexpected-response",f,g)||Ue(n,f,`Unexpected server response: ${g.statusCode}`)}),f.on("upgrade",(g,w,E)=>{if(n.emit("upgrade",g),n.readyState!==le.CONNECTING)return;f=n._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Ue(n,w,"Invalid Upgrade header");return}let _=Kg("sha1").update(l+tp).digest("base64");if(g.headers["sec-websocket-accept"]!==_){Ue(n,w,"Invalid Sec-WebSocket-Accept header");return}let S=g.headers["sec-websocket-protocol"],N;if(S!==void 0?m.size?m.has(S)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":m.size&&(N="Server sent no subprotocol"),N){Ue(n,w,N);return}S&&(n._protocol=S);let T=g.headers["sec-websocket-extensions"];if(T!==void 0){if(!p){Ue(n,w,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let I;try{I=ap(T)}catch{Ue(n,w,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys(I);if(q.length!==1||q[0]!==At.extensionName){Ue(n,w,"Server indicated an extension that was not requested");return}try{p.accept(I[At.extensionName])}catch{Ue(n,w,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[At.extensionName]=p}n.setSocket(w,E,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(f,n):f.end()}function Ur(n,e){n._readyState=le.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function dp(n){return n.path=n.socketPath,rl.connect(n)}function up(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=rl.isIP(n.host)?"":n.host),Vg.connect(n)}function Ue(n,e,t){n._readyState=le.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Ue),e.setHeader?(e[il]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Ur,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function pi(n,e,t){if(e){let r=Zg(e)?e.size:cp(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${_t[n.readyState]})`);process.nextTick(t,r)}}function fp(n,e){let t=this[_e];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[_e]!==void 0&&(t._socket.removeListener("data",Fr),process.nextTick(al,t._socket),n===1005?t.close():t.close(n,e))}function hp(){let n=this[_e];n.isPaused||n._socket.resume()}function gp(n){let e=this[_e];e._socket[_e]!==void 0&&(e._socket.removeListener("data",Fr),process.nextTick(al,e._socket),e.close(n[rp])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function nl(){this[_e].emitClose()}function pp(n,e){this[_e].emit("message",n,e)}function mp(n){let e=this[_e];e._autoPong&&e.pong(n,!this._isServer,sl),e.emit("ping",n)}function yp(n){this[_e].emit("pong",n)}function al(n){n.resume()}function _p(n){let e=this[_e];e.readyState!==le.CLOSED&&(e.readyState===le.OPEN&&(e._readyState=le.CLOSING,cl(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function cl(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function ll(){let n=this[_e];if(this.removeListener("close",ll),this.removeListener("data",Fr),this.removeListener("end",dl),n._readyState=le.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[_e]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",nl),n._receiver.on("finish",nl))}function Fr(n){this[_e]._receiver.write(n)||this.pause()}function dl(){let n=this[_e];n._readyState=le.CLOSING,n._receiver.end(),this.end()}function ul(){let n=this[_e];this.removeListener("error",ul),this.on("error",sl),n&&(n._readyState=le.CLOSING,this.destroy())}});var ml=Z((lb,pl)=>{"use strict";var cb=Hr(),{Duplex:wp}=te("stream");function hl(n){n.emit("close")}function vp(){!this.destroyed&&this._writableState.finished&&this.destroy()}function gl(n){this.removeListener("error",gl),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function bp(n,e){let t=!0,r=new wp({...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(hl,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(hl,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",vp),r.on("error",gl),r}pl.exports=bp});var mi=Z((db,yl)=>{"use strict";var{tokenChars:kp}=ln();function Sp(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&&kp[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}yl.exports={parse:Sp}});var El=Z((fb,Sl)=>{"use strict";var Ep=te("events"),qr=te("http"),{Duplex:ub}=te("stream"),{createHash:xp}=te("crypto"),_l=Dr(),Wt=cn(),Tp=mi(),Cp=Hr(),{CLOSE_TIMEOUT:Rp,GUID:Ap,kWebSocket:Op}=pt(),Pp=/^[+/0-9A-Za-z]{22}==$/,wl=0,vl=1,kl=2,yi=class extends Ep{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Rp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Cp,...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=qr.createServer((r,s)=>{let i=qr.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=Ip(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=wl}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===kl){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(qn,this);return}if(e&&this.once("close",e),this._state!==vl)if(this._state=vl,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(qn,this):process.nextTick(qn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{qn(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",bl);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){jt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){jt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Pp.test(i)){jt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){jt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Gn(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=Tp.parse(c)}catch{jt(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 Wt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=_l.parse(l);p[Wt.extensionName]&&(m.accept(p[Wt.extensionName]),u[Wt.extensionName]=m)}catch{jt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(p,f,g,w)=>{if(!p)return Gn(t,f||401,g,w);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(m))return Gn(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[Op])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>wl)return Gn(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${xp("sha1").update(t+Ap).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[Wt.extensionName]){let u=e[Wt.extensionName].params,m=_l.format({[Wt.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${m}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
206
|
+
`+i),n.push(s+"m+"+Cr.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=cg()+e+" "+n[0]}function cg(){return ye.inspectOpts.hideDate?"":new Date().toISOString()+" "}function dg(...n){return process.stderr.write(Tr.formatWithOptions(ye.inspectOpts,...n)+`
|
|
207
|
+
`)}function lg(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function ug(){return process.env.DEBUG}function fg(n){n.inspectOpts={};let e=Object.keys(ye.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=ye.inspectOpts[e[t]]}Cr.exports=Js()(ye);var{formatters:gc}=Cr.exports;gc.o=function(n){return this.inspectOpts.colors=this.useColors,Tr.inspect(n,this.inspectOpts).split(`
|
|
208
|
+
`).map(e=>e.trim()).join(" ")};gc.O=function(n){return this.inspectOpts.colors=this.useColors,Tr.inspect(n,this.inspectOpts)}});var Ge=Z((Lv,Ys)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Ys.exports=hc():Ys.exports=pc()});var mc,yc,hg,Rr,ft,Ln=A(()=>{en();mc=oe(Dt(),1);Ut();js();yc=oe(Ge(),1),hg=(0,yc.default)("engine.io-client:transport"),Rr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},ft=class extends mc.Emitter{constructor(e){super(),this.writable=!1,ut(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 Rr(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return(this.readyState==="opening"||this.readyState==="open")&&(this.doClose(),this.onClose()),this}send(e){this.readyState==="open"?this.write(e):hg("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=Mn(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=cc(e);return t.length?"?"+t:""}}});var _c,Qe,$n,Vs=A(()=>{Ln();Ut();en();_c=oe(Ge(),1),Qe=(0,_c.default)("engine.io-client:polling"),$n=class extends ft{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Qe("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(Qe("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){Qe("pre-pause polling complete"),--r||t()})),this.writable||(Qe("we are currently writing - waiting to pause"),r++,this.once("drain",function(){Qe("pre-pause writing complete"),--r||t()}))}else t()}_poll(){Qe("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Qe("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)};tc(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Qe('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Qe("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Qe("transport open - closing"),e()):(Qe("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,ec(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]=Sr()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var wc,vc,bc=A(()=>{wc=!1;try{wc=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}vc=wc});function gg(){}function kc(){for(let n in ht.requests)ht.requests.hasOwnProperty(n)&&ht.requests[n].abort()}function pg(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||vc))return new XMLHttpRequest}catch{}if(!e)try{return new Re[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Sc,Ec,zs,Ar,ht,zv,Ks=A(()=>{Vs();Sc=oe(Dt(),1);Ut();Bt();bc();Ec=oe(Ge(),1),zs=(0,Ec.default)("engine.io-client:polling");Ar=class extends $n{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(){zs("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}},ht=class n extends Sc.Emitter{constructor(e,t,r){super(),this.createRequest=e,ut(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=kr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{zs("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))},zs("xhr data %s",this._data),r.send(this._data)}catch(s){this.setTimeoutFn(()=>{this._onError(s)},0);return}typeof document<"u"&&(this._index=n.requestsCount++,n.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(e){if(!(typeof this._xhr>"u"||this._xhr===null)){if(this._xhr.onreadystatechange=gg,e)try{this._xhr.abort()}catch{}typeof document<"u"&&delete n.requests[this._index],this._xhr=null}}_onLoad(){let e=this._xhr.responseText;e!==null&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};ht.requestsCount=0;ht.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",kc);else if(typeof addEventListener=="function"){let n="onpagehide"in Re?"pagehide":"unload";addEventListener(n,kc,!1)}}zv=(function(){let n=pg({xdomain:!1});return n&&n.responseType!==null})()});var Xs,mg,sn,Qs=A(()=>{Xs=oe(Ya(),1);Ks();mg=Xs.default||Xs,sn=class extends Ar{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 ht(r=>new mg(r),this.uri(),e)}}});var gt=Z((Zv,Cc)=>{"use strict";var xc=["nodebuffer","arraybuffer","fragments"],Tc=typeof Blob<"u";Tc&&xc.push("blob");Cc.exports={BINARY_TYPES:xc,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Tc,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Dn=Z((eb,Or)=>{"use strict";var{EMPTY_BUFFER:yg}=gt(),Zs=Buffer[Symbol.species];function _g(n,e){if(n.length===0)return yg;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),r=0;for(let s=0;s<n.length;s++){let i=n[s];t.set(i,r),r+=i.length}return r<e?new Zs(t.buffer,t.byteOffset,r):t}function Rc(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Ac(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function wg(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function ei(n){if(ei.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),ei.readOnly=!1),e}Or.exports={concat:_g,mask:Rc,toArrayBuffer:wg,toBuffer:ei,unmask:Ac};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=te("bufferutil");Or.exports.mask=function(e,t,r,s,i){i<48?Rc(e,t,r,s,i):n.mask(e,t,r,s,i)},Or.exports.unmask=function(e,t){e.length<32?Ac(e,t):n.unmask(e,t)}}catch{}});var Ic=Z((tb,Pc)=>{"use strict";var Oc=Symbol("kDone"),ti=Symbol("kRun"),ni=class{constructor(e){this[Oc]=()=>{this.pending--,this[ti]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ti]()}[ti](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Oc])}}};Pc.exports=ni});var cn=Z((nb,$c)=>{"use strict";var Bn=te("zlib"),Nc=Dn(),vg=Ic(),{kStatusCode:Mc}=gt(),bg=Buffer[Symbol.species],kg=Buffer.from([0,0,255,255]),Ir=Symbol("permessage-deflate"),pt=Symbol("total-length"),on=Symbol("callback"),Rt=Symbol("buffers"),an=Symbol("error"),Pr,ri=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,!Pr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Pr=new vg(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[on];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){Pr.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){Pr.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"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=Bn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[Ir]=this,this._inflate[pt]=0,this._inflate[Rt]=[],this._inflate.on("error",Eg),this._inflate.on("data",Lc)}this._inflate[on]=r,this._inflate.write(e),t&&this._inflate.write(kg),this._inflate.flush(()=>{let i=this._inflate[an];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=Nc.concat(this._inflate[Rt],this._inflate[pt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[pt]=0,this._inflate[Rt]=[],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"?Bn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=Bn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[pt]=0,this._deflate[Rt]=[],this._deflate.on("data",Sg)}this._deflate[on]=r,this._deflate.write(e),this._deflate.flush(Bn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Nc.concat(this._deflate[Rt],this._deflate[pt]);t&&(i=new bg(i.buffer,i.byteOffset,i.length-4)),this._deflate[on]=null,this._deflate[pt]=0,this._deflate[Rt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};$c.exports=ri;function Sg(n){this[Rt].push(n),this[pt]+=n.length}function Lc(n){if(this[pt]+=n.length,this[Ir]._maxPayload<1||this[pt]<=this[Ir]._maxPayload){this[Rt].push(n);return}this[an]=new RangeError("Max payload size exceeded"),this[an].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[an][Mc]=1009,this.removeListener("data",Lc),this.reset()}function Eg(n){if(this[Ir]._inflate=null,this[an]){this[on](this[an]);return}n[Mc]=1007,this[on](n)}});var dn=Z((rb,Nr)=>{"use strict";var{isUtf8:Dc}=te("buffer"),{hasBlob:xg}=gt(),Tg=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Cg(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function si(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function Rg(n){return xg&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}Nr.exports={isBlob:Rg,isValidStatusCode:Cg,isValidUTF8:si,tokenChars:Tg};if(Dc)Nr.exports.isValidUTF8=function(n){return n.length<24?si(n):Dc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=te("utf-8-validate");Nr.exports.isValidUTF8=function(e){return e.length<32?si(e):n(e)}}catch{}});var di=Z((sb,Wc)=>{"use strict";var{Writable:Ag}=te("stream"),Bc=cn(),{BINARY_TYPES:Og,EMPTY_BUFFER:Uc,kStatusCode:Pg,kWebSocket:Ig}=gt(),{concat:ii,toArrayBuffer:Ng,unmask:Mg}=Dn(),{isValidStatusCode:Lg,isValidUTF8:Fc}=dn(),Mr=Buffer[Symbol.species],We=0,Hc=1,qc=2,Gc=3,oi=4,ai=5,Lr=6,ci=class extends Ag{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Og[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Ig]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=We}_write(e,t,r){if(this._opcode===8&&this._state==We)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 Mr(r.buffer,r.byteOffset+e,r.length-e),new Mr(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 Mr(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 We:this.getInfo(e);break;case Hc:this.getPayloadLength16(e);break;case qc:this.getPayloadLength64(e);break;case Gc:this.getMask();break;case oi:this.getData(e);break;case ai:case Lr: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[Bc.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=Hc:this._payloadLength===127?this._state=qc: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=Gc:this._state=oi}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=oi}getData(e){let t=Uc;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Mg(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=ai,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Bc.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===We&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=We;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=ii(r,t):this._binaryType==="arraybuffer"?s=Ng(ii(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=We):(this._state=Lr,setImmediate(()=>{this.emit("message",s,!0),this._state=We,this.startLoop(e)}))}else{let s=ii(r,t);if(!this._skipUTF8Validation&&!Fc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===ai||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=We):(this._state=Lr,setImmediate(()=>{this.emit("message",s,!1),this._state=We,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Uc),this.end();else{let r=e.readUInt16BE(0);if(!Lg(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new Mr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Fc(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=We;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=We):(this._state=Lr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=We,this.startLoop(t)}))}createError(e,t,r,s,i){this._loop=!1,this._errored=!0;let o=new e(r?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[Pg]=s,o}};Wc.exports=ci});var fi=Z((ob,Yc)=>{"use strict";var{Duplex:ib}=te("stream"),{randomFillSync:$g}=te("crypto"),{types:{isUint8Array:Dg}}=te("util"),jc=cn(),{EMPTY_BUFFER:Bg,kWebSocket:Ug,NOOP:Fg}=gt(),{isBlob:ln,isValidStatusCode:Hg}=dn(),{mask:Jc,toBuffer:Ht}=Dn(),je=Symbol("kByteLength"),qg=Buffer.alloc(4),$r=8*1024,qt,un=$r,Ze=0,Gg=1,Wg=2,li=class n{constructor(e,t,r){this._extensions=t||{},r&&(this._generateMask=r,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Ze,this.onerror=Fg,this[Ug]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||qg,t.generateMask?t.generateMask(r):(un===$r&&(qt===void 0&&(qt=Buffer.alloc($r)),$g(qt,0,$r),un=0),r[0]=qt[un++],r[1]=qt[un++],r[2]=qt[un++],r[3]=qt[un++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[je]!==void 0?a=t[je]:(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?(Jc(e,r,l,i,a),[l]):(Jc(e,r,e,0,a),[l,e])):[l,e]}close(e,t,r,s){let i;if(e===void 0)i=Bg;else{if(typeof e!="number"||!Hg(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");if(i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string")i.write(t,2);else if(Dg(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[je]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ze?this.enqueue([this.dispatch,i,!1,o,s]):this.sendFrame(n.frame(i,o),s)}ping(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ln(e)?(s=e.size,i=!1):(e=Ht(e),s=e.length,i=Ht.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[je]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ln(e)?this._state!==Ze?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ze?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}pong(e,t,r){let s,i;if(typeof e=="string"?(s=Buffer.byteLength(e),i=!1):ln(e)?(s=e.size,i=!1):(e=Ht(e),s=e.length,i=Ht.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[je]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ln(e)?this._state!==Ze?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==Ze?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[jc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):ln(e)?(a=e.size,c=!1):(e=Ht(e),a=e.length,c=Ht.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={[je]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};ln(e)?this._state!==Ze?this.enqueue([this.getBlobData,e,this._compress,l,r]):this.getBlobData(e,this._compress,l,r):this._state!==Ze?this.enqueue([this.dispatch,e,this._compress,l,r]):this.dispatch(e,this._compress,l,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[je],this._state=Wg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(ui,this,a,s);return}this._bufferedBytes-=r[je];let o=Ht(i);t?this.dispatch(o,t,r,s):(this._state=Ze,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(jg,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[jc.extensionName];this._bufferedBytes+=r[je],this._state=Gg,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");ui(this,c,s);return}this._bufferedBytes-=r[je],this._state=Ze,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===Ze&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][je],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][je],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)}};Yc.exports=li;function ui(n,e,t){typeof t=="function"&&t(e);for(let r=0;r<n._queue.length;r++){let s=n._queue[r],i=s[s.length-1];typeof i=="function"&&i(e)}}function jg(n,e,t){ui(n,e,t),n.onerror(e)}});var nd=Z((ab,td)=>{"use strict";var{kForOnEventAttribute:Un,kListener:hi}=gt(),Vc=Symbol("kCode"),zc=Symbol("kData"),Kc=Symbol("kError"),Xc=Symbol("kMessage"),Qc=Symbol("kReason"),fn=Symbol("kTarget"),Zc=Symbol("kType"),ed=Symbol("kWasClean"),mt=class{constructor(e){this[fn]=null,this[Zc]=e}get target(){return this[fn]}get type(){return this[Zc]}};Object.defineProperty(mt.prototype,"target",{enumerable:!0});Object.defineProperty(mt.prototype,"type",{enumerable:!0});var Gt=class extends mt{constructor(e,t={}){super(e),this[Vc]=t.code===void 0?0:t.code,this[Qc]=t.reason===void 0?"":t.reason,this[ed]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Vc]}get reason(){return this[Qc]}get wasClean(){return this[ed]}};Object.defineProperty(Gt.prototype,"code",{enumerable:!0});Object.defineProperty(Gt.prototype,"reason",{enumerable:!0});Object.defineProperty(Gt.prototype,"wasClean",{enumerable:!0});var hn=class extends mt{constructor(e,t={}){super(e),this[Kc]=t.error===void 0?null:t.error,this[Xc]=t.message===void 0?"":t.message}get error(){return this[Kc]}get message(){return this[Xc]}};Object.defineProperty(hn.prototype,"error",{enumerable:!0});Object.defineProperty(hn.prototype,"message",{enumerable:!0});var Fn=class extends mt{constructor(e,t={}){super(e),this[zc]=t.data===void 0?null:t.data}get data(){return this[zc]}};Object.defineProperty(Fn.prototype,"data",{enumerable:!0});var Jg={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[Un]&&s[hi]===e&&!s[Un])return;let r;if(n==="message")r=function(i,o){let a=new Fn("message",{data:o?i:i.toString()});a[fn]=this,Dr(e,this,a)};else if(n==="close")r=function(i,o){let a=new Gt("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[fn]=this,Dr(e,this,a)};else if(n==="error")r=function(i){let o=new hn("error",{error:i,message:i.message});o[fn]=this,Dr(e,this,o)};else if(n==="open")r=function(){let i=new mt("open");i[fn]=this,Dr(e,this,i)};else return;r[Un]=!!t[Un],r[hi]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[hi]===e&&!t[Un]){this.removeListener(n,t);break}}};td.exports={CloseEvent:Gt,ErrorEvent:hn,Event:mt,EventTarget:Jg,MessageEvent:Fn};function Dr(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Br=Z((cb,rd)=>{"use strict";var{tokenChars:Hn}=dn();function it(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Yg(n){let e=Object.create(null),t=Object.create(null),r=!1,s=!1,i=!1,o,a,c=-1,l=-1,d=-1,u=0;for(;u<n.length;u++)if(l=n.charCodeAt(u),o===void 0)if(d===-1&&Hn[l]===1)c===-1&&(c=u);else if(u!==0&&(l===32||l===9))d===-1&&c!==-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(c,d);l===44?(it(e,p,t),t=Object.create(null)):o=p,c=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&Hn[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),it(t,n.slice(c,d),!0),l===44&&(it(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(Hn[l]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(Hn[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&&Hn[l]===1)c===-1&&(c=u);else if(c!==-1&&(l===32||l===9))d===-1&&(d=u);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(c,d);r&&(p=p.replace(/\\/g,""),r=!1),it(t,a,p),l===44&&(it(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?it(e,m,t):(a===void 0?it(t,m,!0):r?it(t,a,m.replace(/\\/g,"")):it(t,a,m),it(e,o,t)),e}function Vg(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(r=>[e].concat(Object.keys(r).map(s=>{let i=r[s];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?s:`${s}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}rd.exports={format:Vg,parse:Yg}});var qr=Z((ub,pd)=>{"use strict";var zg=te("events"),Kg=te("https"),Xg=te("http"),od=te("net"),Qg=te("tls"),{randomBytes:Zg,createHash:ep}=te("crypto"),{Duplex:db,Readable:lb}=te("stream"),{URL:gi}=te("url"),At=cn(),tp=di(),np=fi(),{isBlob:rp}=dn(),{BINARY_TYPES:sd,CLOSE_TIMEOUT:sp,EMPTY_BUFFER:Ur,GUID:ip,kForOnEventAttribute:pi,kListener:op,kStatusCode:ap,kWebSocket:_e,NOOP:ad}=gt(),{EventTarget:{addEventListener:cp,removeEventListener:dp}}=nd(),{format:lp,parse:up}=Br(),{toBuffer:fp}=Dn(),cd=Symbol("kAborted"),mi=[8,13],yt=["CONNECTING","OPEN","CLOSING","CLOSED"],hp=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,de=class n extends zg{constructor(e,t,r){super(),this._binaryType=sd[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ur,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]),dd(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){sd.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,r){let s=new tp({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new np(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[_e]=this,i[_e]=this,e[_e]=this,s.on("conclude",mp),s.on("drain",yp),s.on("error",_p),s.on("message",wp),s.on("ping",vp),s.on("pong",bp),i.onerror=kp,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",fd),e.on("data",Hr),e.on("end",hd),e.on("error",gd),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[At.extensionName]&&this._extensions[At.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){Ue(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())}),ud(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){yi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ur,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){yi(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ur,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){yi(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[At.extensionName]||(s.compress=!1),this._sender.send(e||Ur,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Ue(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(de,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(de.prototype,"CONNECTING",{enumerable:!0,value:yt.indexOf("CONNECTING")});Object.defineProperty(de,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(de.prototype,"OPEN",{enumerable:!0,value:yt.indexOf("OPEN")});Object.defineProperty(de,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(de.prototype,"CLOSING",{enumerable:!0,value:yt.indexOf("CLOSING")});Object.defineProperty(de,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});Object.defineProperty(de.prototype,"CLOSED",{enumerable:!0,value:yt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(de.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(de.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[pi])return e[op];return null},set(e){for(let t of this.listeners(n))if(t[pi]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[pi]:!0})}})});de.prototype.addEventListener=cp;de.prototype.removeEventListener=dp;pd.exports=de;function dd(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:sp,protocolVersion:mi[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,!mi.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${mi.join(", ")})`);let i;if(e instanceof gi)i=e;else try{i=new gi(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;Fr(n,g);return}let l=o?443:80,d=Zg(16).toString("base64"),u=o?Kg.request:Xg.request,m=new Set,p;if(s.createConnection=s.createConnection||(o?pp:gp),s.defaultPort=s.defaultPort||l,s.port=i.port||l,s.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,s.headers={...s.headers,"Sec-WebSocket-Version":s.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},s.path=i.pathname+i.search,s.timeout=s.handshakeTimeout,s.perMessageDeflate&&(p=new At({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=lp({[At.extensionName]:p.offer()})),t.length){for(let g of t){if(typeof g!="string"||!hp.test(g)||m.has(g))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(g)}s.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(s.origin&&(s.protocolVersion<13?s.headers["Sec-WebSocket-Origin"]=s.origin:s.headers.Origin=s.origin),(i.username||i.password)&&(s.auth=`${i.username}:${i.password}`),a){let g=s.path.split(":");s.socketPath=g[0],s.path=g[1]}let f;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let g=r&&r.headers;if(r={...r,headers:{}},g)for(let[_,E]of Object.entries(g))r.headers[_.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")),f=n._req=u(s),n._redirects&&n.emit("redirect",n.url,f)}else f=n._req=u(s);s.timeout&&f.on("timeout",()=>{Ue(n,f,"Opening handshake has timed out")}),f.on("error",g=>{f===null||f[cd]||(f=n._req=null,Fr(n,g))}),f.on("response",g=>{let _=g.headers.location,E=g.statusCode;if(_&&s.followRedirects&&E>=300&&E<400){if(++n._redirects>s.maxRedirects){Ue(n,f,"Maximum redirects exceeded");return}f.abort();let v;try{v=new gi(_,e)}catch{let S=new SyntaxError(`Invalid URL: ${_}`);Fr(n,S);return}dd(n,v,t,r)}else n.emit("unexpected-response",f,g)||Ue(n,f,`Unexpected server response: ${g.statusCode}`)}),f.on("upgrade",(g,_,E)=>{if(n.emit("upgrade",g),n.readyState!==de.CONNECTING)return;f=n._req=null;let v=g.headers.upgrade;if(v===void 0||v.toLowerCase()!=="websocket"){Ue(n,_,"Invalid Upgrade header");return}let y=ep("sha1").update(d+ip).digest("base64");if(g.headers["sec-websocket-accept"]!==y){Ue(n,_,"Invalid Sec-WebSocket-Accept header");return}let S=g.headers["sec-websocket-protocol"],N;if(S!==void 0?m.size?m.has(S)||(N="Server sent an invalid subprotocol"):N="Server sent a subprotocol but none was requested":m.size&&(N="Server sent no subprotocol"),N){Ue(n,_,N);return}S&&(n._protocol=S);let T=g.headers["sec-websocket-extensions"];if(T!==void 0){if(!p){Ue(n,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let I;try{I=up(T)}catch{Ue(n,_,"Invalid Sec-WebSocket-Extensions header");return}let q=Object.keys(I);if(q.length!==1||q[0]!==At.extensionName){Ue(n,_,"Server indicated an extension that was not requested");return}try{p.accept(I[At.extensionName])}catch{Ue(n,_,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[At.extensionName]=p}n.setSocket(_,E,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(f,n):f.end()}function Fr(n,e){n._readyState=de.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function gp(n){return n.path=n.socketPath,od.connect(n)}function pp(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=od.isIP(n.host)?"":n.host),Qg.connect(n)}function Ue(n,e,t){n._readyState=de.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Ue),e.setHeader?(e[cd]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Fr,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function yi(n,e,t){if(e){let r=rp(e)?e.size:fp(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${yt[n.readyState]})`);process.nextTick(t,r)}}function mp(n,e){let t=this[_e];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[_e]!==void 0&&(t._socket.removeListener("data",Hr),process.nextTick(ld,t._socket),n===1005?t.close():t.close(n,e))}function yp(){let n=this[_e];n.isPaused||n._socket.resume()}function _p(n){let e=this[_e];e._socket[_e]!==void 0&&(e._socket.removeListener("data",Hr),process.nextTick(ld,e._socket),e.close(n[ap])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function id(){this[_e].emitClose()}function wp(n,e){this[_e].emit("message",n,e)}function vp(n){let e=this[_e];e._autoPong&&e.pong(n,!this._isServer,ad),e.emit("ping",n)}function bp(n){this[_e].emit("pong",n)}function ld(n){n.resume()}function kp(n){let e=this[_e];e.readyState!==de.CLOSED&&(e.readyState===de.OPEN&&(e._readyState=de.CLOSING,ud(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function ud(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function fd(){let n=this[_e];if(this.removeListener("close",fd),this.removeListener("data",Hr),this.removeListener("end",hd),n._readyState=de.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[_e]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",id),n._receiver.on("finish",id))}function Hr(n){this[_e]._receiver.write(n)||this.pause()}function hd(){let n=this[_e];n._readyState=de.CLOSING,n._receiver.end(),this.end()}function gd(){let n=this[_e];this.removeListener("error",gd),this.on("error",ad),n&&(n._readyState=de.CLOSING,this.destroy())}});var wd=Z((hb,_d)=>{"use strict";var fb=qr(),{Duplex:Sp}=te("stream");function md(n){n.emit("close")}function Ep(){!this.destroyed&&this._writableState.finished&&this.destroy()}function yd(n){this.removeListener("error",yd),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function xp(n,e){let t=!0,r=new Sp({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(md,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(md,r)}),t&&n.terminate()},r._final=function(s){if(n.readyState===n.CONNECTING){n.once("open",function(){r._final(s)});return}n._socket!==null&&(n._socket._writableState.finished?(s(),r._readableState.endEmitted&&r.destroy()):(n._socket.once("finish",function(){s()}),n.close()))},r._read=function(){n.isPaused&&n.resume()},r._write=function(s,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){r._write(s,i,o)});return}n.send(s,o)},r.on("end",Ep),r.on("error",yd),r}_d.exports=xp});var _i=Z((gb,vd)=>{"use strict";var{tokenChars:Tp}=dn();function Cp(n){let e=new Set,t=-1,r=-1,s=0;for(s;s<n.length;s++){let o=n.charCodeAt(s);if(r===-1&&Tp[o]===1)t===-1&&(t=s);else if(s!==0&&(o===32||o===9))r===-1&&t!==-1&&(r=s);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${s}`);r===-1&&(r=s);let a=n.slice(t,r);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=r=-1}else throw new SyntaxError(`Unexpected character at index ${s}`)}if(t===-1||r!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,s);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}vd.exports={parse:Cp}});var Cd=Z((mb,Td)=>{"use strict";var Rp=te("events"),Gr=te("http"),{Duplex:pb}=te("stream"),{createHash:Ap}=te("crypto"),bd=Br(),Wt=cn(),Op=_i(),Pp=qr(),{CLOSE_TIMEOUT:Ip,GUID:Np,kWebSocket:Mp}=gt(),Lp=/^[+/0-9A-Za-z]{22}==$/,kd=0,Sd=1,xd=2,wi=class extends Rp{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Ip,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Pp,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Gr.createServer((r,s)=>{let i=Gr.STATUS_CODES[426];s.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),s.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let r=this.emit.bind(this,"connection");this._removeListeners=$p(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(s,i,o)=>{this.handleUpgrade(s,i,o,r)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=kd}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===xd){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(qn,this);return}if(e&&this.once("close",e),this._state!==Sd)if(this._state=Sd,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(qn,this):process.nextTick(qn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{qn(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",Ed);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){jt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){jt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Lp.test(i)){jt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){jt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){Gn(t,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=Op.parse(c)}catch{jt(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 Wt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=bd.parse(d);p[Wt.extensionName]&&(m.accept(p[Wt.extensionName]),u[Wt.extensionName]=m)}catch{jt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(p,f,g,_)=>{if(!p)return Gn(t,f||401,g,_);this.completeUpgrade(u,i,l,e,t,r,s)});return}if(!this.options.verifyClient(m))return Gn(t,401)}this.completeUpgrade(u,i,l,e,t,r,s)}completeUpgrade(e,t,r,s,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Mp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>kd)return Gn(i,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Ap("sha1").update(t+Np).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(r.size){let u=this.options.handleProtocols?this.options.handleProtocols(r,s):r.values().next().value;u&&(l.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Wt.extensionName]){let u=e[Wt.extensionName].params,m=bd.format({[Wt.extensionName]:[u]});l.push(`Sec-WebSocket-Extensions: ${m}`),d._extensions=e}this.emit("headers",l,s),i.write(l.concat(`\r
|
|
209
209
|
`).join(`\r
|
|
210
|
-
`)),i.removeListener("error",
|
|
210
|
+
`)),i.removeListener("error",Ed),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(qn,this)})),a(d,s)}};Td.exports=wi;function $p(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let r of Object.keys(e))n.removeListener(r,e[r])}}function qn(n){n._state=xd,n.emit("close")}function Ed(){this.destroy()}function Gn(n,e,t,r){t=t||Gr.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} ${Gr.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 jt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,jt),n.emit("wsClientError",o,t,e)}else Gn(t,r,s,i)}});var Np,Mp,Lp,$p,Dp,Bp,_i,Up,xl=R(()=>{Np=oe(ml(),1),Mp=oe(Dr(),1),Lp=oe(cn(),1),$p=oe(ai(),1),Dp=oe(di(),1),Bp=oe(mi(),1),_i=oe(Hr(),1),Up=oe(El(),1)});var Tl,Hp,qp,Gr,yb,wi=R(()=>{Ln();Ut();en();Bt();Tl=oe(Ge(),1),Hp=(0,Tl.default)("engine.io-client:websocket"),qp=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Gr=class extends ht{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=qp?{}:br(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;Nn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{Hp("websocket closed before onclose event")}s&&ut(()=>{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]=kr()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},yb=Ae.WebSocket||Ae.MozWebSocket});var gn,vi=R(()=>{xl();wi();gn=class extends Gr{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 _i.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 Cl,Wn,pn,bi=R(()=>{Ln();Bt();en();Cl=oe(Ge(),1),Wn=(0,Cl.default)("engine.io-client:webtransport"),pn=class extends ht{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(()=>{Wn("transport closed gracefully"),this.onClose()}).catch(e=>{Wn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=ec(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=Za();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){Wn("session is closed");return}Wn("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{Wn("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&&ut(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var ki,Si=R(()=>{Ks();vi();bi();ki={websocket:gn,webtransport:pn,polling:sn}});function mn(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=Gp.exec(n||""),i={},o=14;for(;o--;)i[Wp[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=jp(i,i.path),i.queryKey=Jp(i,i.query),i}function jp(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 Jp(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var Gp,Wp,Ei=R(()=>{Gp=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Wp=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var Rl,Al,ce,xi,jn,Jt,Wr,yn,Ti=R(()=>{Si();Ut();Gs();Ei();Rl=oe(Dt(),1);en();Bt();Al=oe(Ge(),1),ce=(0,Al.default)("engine.io-client:socket"),xi=typeof addEventListener=="function"&&typeof removeEventListener=="function",jn=[];xi&&addEventListener("offline",()=>{ce("closing %d connection(s) because the network was lost",jn.length),jn.forEach(n=>n())},!1);Jt=class n extends Rl.Emitter{constructor(e,t){if(super(),this.binaryType=nc,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=mn(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=mn(t.host).host);ft(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=oc(this.opts.query)),xi&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(ce("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},jn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=rc()),this._open()}createTransport(e){ce('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Hs,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 ce("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){ce("setting transport %s",e.name),this.transport&&(ce("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(){ce("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(ce('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 ce('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();ce("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+=sc(s)),r>0&&t>this._maxPayload)return ce("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return ce("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&&(ce("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,ut(()=>{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"),ce("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(ce("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return ce("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(ce('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),xi&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=jn.indexOf(this._offlineEventListener);r!==-1&&(ce("removing listener for the 'offline' event"),jn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Jt.protocol=Hs;Wr=class extends Jt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){ce("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){ce('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Jt.priorWebsocketSuccess=!1;let s=()=>{r||(ce('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(ce('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Jt.priorWebsocketSuccess=t.name==="websocket",ce('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(ce("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{ce('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(),ce('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&&(ce('"%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}},yn=class extends Wr{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=>ki[s]).filter(s=>!!s)),super(e,r)}}});var Ol=R(()=>{Js()});var Fb,jr=R(()=>{Ti();Ti();Ln();Si();Ut();Ei();Bt();Ol();Ks();Vs();vi();wi();bi();Fb=yn.protocol});function Nl(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)||(Pl("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Pl("parse %s",n),r=mn(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 Il,Pl,Ml=R(()=>{jr();Il=oe(Ge(),1),Pl=(0,Il.default)("socket.io-client:url")});function Yn(n){return Kp&&(n instanceof ArrayBuffer||Xp(n))||Qp&&n instanceof Blob||Zp&&n instanceof File}function Jn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Jn(n[t]))return!0;return!1}if(Yn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Jn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Jn(n[t]))return!0;return!1}var Kp,Xp,Ll,Qp,Zp,Ci=R(()=>{Kp=typeof ArrayBuffer=="function",Xp=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Ll=Object.prototype.toString,Qp=typeof Blob=="function"||typeof Blob<"u"&&Ll.call(Blob)==="[object BlobConstructor]",Zp=typeof File=="function"||typeof File<"u"&&Ll.call(File)==="[object FileConstructor]"});function $l(n){let e=[],t=n.data,r=n;return r.data=Ri(t,e),r.attachments=e.length,{packet:r,buffers:e}}function Ri(n,e){if(!n)return n;if(Yn(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]=Ri(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]=Ri(n[r],e));return t}return n}function Dl(n,e){return n.data=Ai(n.data,e),delete n.attachments,n}function Ai(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]=Ai(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Ai(n[t],e));return n}var Bl=R(()=>{Ci()});var Mi={};Be(Mi,{Decoder:()=>Ii,Encoder:()=>Pi,PacketType:()=>G,isPacketValid:()=>rm,protocol:()=>ql});function em(n){return typeof n=="string"}function tm(n){return n===void 0||Gl(n)}function Jr(n){return Object.prototype.toString.call(n)==="[object Object]"}function nm(n,e){switch(n){case G.CONNECT:return e===void 0||Jr(e);case G.DISCONNECT:return e===void 0;case G.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Hl.indexOf(e[0])===-1);case G.ACK:return Array.isArray(e);case G.CONNECT_ERROR:return typeof e=="string"||Jr(e);default:return!1}}function rm(n){return em(n.nsp)&&tm(n.id)&&nm(n.type,n.data)}var Ul,Fl,Oi,Hl,ql,G,Pi,Ii,Ni,Gl,Yr=R(()=>{Ul=oe(Dt(),1);Bl();Ci();Fl=oe(Ge(),1),Oi=(0,Fl.default)("socket.io-parser"),Hl=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],ql=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"})(G||(G={}));Pi=class{constructor(e){this.replacer=e}encode(e){return Oi("encoding packet %j",e),(e.type===G.EVENT||e.type===G.ACK)&&Jn(e)?this.encodeAsBinary({type:e.type===G.EVENT?G.BINARY_EVENT:G.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===G.BINARY_EVENT||e.type===G.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)),Oi("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=$l(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},Ii=class n extends Ul.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===G.BINARY_EVENT;r||t.type===G.BINARY_ACK?(t.type=r?G.EVENT:G.ACK,this.reconstructor=new Ni(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Yn(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(G[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===G.BINARY_EVENT||r.type===G.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(!Gl(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 Oi("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 G.CONNECT:return Jr(t);case G.DISCONNECT:return t===void 0;case G.CONNECT_ERROR:return typeof t=="string"||Jr(t);case G.EVENT:case G.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Hl.indexOf(t[0])===-1);case G.ACK:case G.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Ni=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=Dl(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};Gl=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function Fe(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Li=R(()=>{});var Wl,jl,ge,sm,_n,$i=R(()=>{Yr();Li();Wl=oe(Dt(),1),jl=oe(Ge(),1),ge=(0,jl.default)("socket.io-client:socket"),sm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),_n=class extends Wl.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=[Fe(e,"open",this.onopen.bind(this)),Fe(e,"packet",this.onpacket.bind(this)),Fe(e,"error",this.onerror.bind(this)),Fe(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(sm.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:G.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let l=this.ids++;ge("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?ge("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&&(ge("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));ge("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]?ge("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(ge("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(ge("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(ge("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ge("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ge("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(){ge("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:G.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){ge("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 G.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 G.EVENT:case G.BINARY_EVENT:this.onevent(e);break;case G.ACK:case G.BINARY_ACK:this.onack(e);break;case G.DISCONNECT:this.ondisconnect();break;case G.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||[];ge("emitting event %j",t),e.id!=null&&(ge("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,ge("sending ack %j",s),t.packet({type:G.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ge("bad ack %s",e.id);return}delete this.acks[e.id],ge("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ge("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(){ge("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&&(ge("performing disconnect (%s)",this.nsp),this.packet({type:G.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 Yt(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=R(()=>{Yt.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};Yt.prototype.reset=function(){this.attempts=0};Yt.prototype.setMin=function(n){this.ms=n};Yt.prototype.setMax=function(n){this.max=n};Yt.prototype.setJitter=function(n){this.jitter=n}});var Yl,Vl,ve,wn,zl=R(()=>{jr();$i();Yr();Li();Jl();Yl=oe(Dt(),1),Vl=oe(Ge(),1),ve=(0,Vl.default)("socket.io-client:manager"),wn=class extends Yl.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,ft(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 Yt({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||Mi;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(ve("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ve("opening %s",this.uri),this.engine=new yn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Fe(t,"open",function(){r.onopen(),e&&e()}),i=a=>{ve("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Fe(t,"error",i);if(this._timeout!==!1){let a=this._timeout;ve("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{ve("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(){ve("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Fe(e,"ping",this.onping.bind(this)),Fe(e,"data",this.ondata.bind(this)),Fe(e,"error",this.onerror.bind(this)),Fe(e,"close",this.onclose.bind(this)),Fe(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){ut(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ve("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new _n(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){ve("socket %s is still active, skipping close",r);return}this._close()}_packet(e){ve("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(){ve("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ve("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;ve("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)ve("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ve("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(ve("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(ve("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(ve("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 zn(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=Nl(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Vn[s]&&i in Vn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(Kl("ignoring socket cache for %s",r),c=new wn(r,e)):(Vn[s]||(Kl("new io instance for %s",r),Vn[s]=new wn(r,e)),c=Vn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var Xl,Kl,Vn,Ql=R(()=>{Ml();zl();$i();Xl=oe(Ge(),1);Yr();jr();Kl=(0,Xl.default)("socket.io-client"),Vn={};Object.assign(zn,{Manager:wn,Socket:_n,io:zn,connect:zn})});var ot,im,Vr,Zl=R(()=>{"use strict";Ql();fe();ot="wsClient",im=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),Vr=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",ot,"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=>{x(ot,"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=zn(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",ot,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{x(ot,"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=>{x(ot,"event handler threw",i)})});for(let t of im)e.on(t,r=>{h("error",ot,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",ot,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",ot,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{x(ot,"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",ot,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var tt,zr,ed=R(()=>{"use strict";Kt();ga();On();Zl();fe();tt="serverGateway",zr=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=xt(),h("info",tt,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new Vr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>ha(t,r)});let e=fa();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",tt,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",tt,`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",tt,"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",tt,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return ma(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await ya(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await _a(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await wa(this.config.server_url,e,t,this._getToken())}async getAction(e){return ba(this.config.server_url,e,this._getToken())}async getApproval(e){return ka(this.config.server_url,e,this._getToken())}async fireAction(e,t){return Sa(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await Ea(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return xa(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return Qt(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return Ta(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return Ra(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return Aa(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return Ca(this.config.server_url,e,this._getToken())}async getTasks(e,t){return yr(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return Oa(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return Pa(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return Ia(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return Na(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Ma(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return La(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await Ba(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await $a(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 Da(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return Ua(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Fa(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",tt,"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 va(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",tt,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",tt,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){x(tt,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=xt(),t=await pa(this.config.server_url,e);fr(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",tt,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){x(tt,"token refresh failed",e)}}_getToken(){return this.token||(this.token=xt()),this.token}}});import{execFile as om}from"node:child_process";import{promisify as am}from"node:util";import{readFileSync as cm,readdirSync as Kr,statSync as Di,openSync as lm,readSync as dm,closeSync as um}from"node:fs";import{join as Vt}from"node:path";import{homedir as td}from"node:os";async function fm(){try{if(process.platform==="darwin"){let{stdout:n}=await nd("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=cm(Vt(td(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function hm(){let n=await fm();if(!n)return null;try{let{stdout:e}=await nd("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 gm(n,e){let t=[];try{for(let r of Kr(n).sort().reverse().slice(0,2)){let s=Vt(n,r);for(let i of Kr(s).sort().reverse().slice(0,2)){let o=Vt(s,i);for(let a of Kr(o).sort().reverse().slice(0,7)){let c=Vt(o,a);for(let d of Kr(c)){if(!d.endsWith(".jsonl"))continue;let l=Vt(c,d);try{t.push({path:l,mtime:Di(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=lm(n,"r");try{let r=Di(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return dm(t,i,0,s,r-s),i.toString("utf-8")}finally{um(t)}}function mm(){let n=process.env.CODEX_HOME??Vt(td(),".codex");for(let e of gm(Vt(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(Di(e).mtimeMs).toISOString()}}catch{}}catch{}return null}async function rd(){let[n,e]=await Promise.all([hm(),Promise.resolve().then(mm)]);return{sampled_at:new Date().toISOString(),claude:n,codex:e}}var nd,sd=R(()=>{"use strict";nd=am(om)});function ad(n,e,t){if(t){let r=`${n}:${t}`;if(Kn.has(r))return;if(Kn.set(r,Date.now()),Kn.size>500){let s=Date.now()-36e5;for(let[i,o]of Kn)o<s&&Kn.delete(i)}}Xn.set(`${n}:${e}`,Date.now())}function Bi(n){od.set(n,Date.now());let e=`${n}:`;for(let t of Xn.keys())t.startsWith(e)&&Xn.delete(t)}function cd(n,e){let t=`${n}:${e}`,r=Xn.get(t);if(r===void 0||(Xn.delete(t),Date.now()-r>wm))return!1;let s=od.get(n)??0;if(Date.now()-s<ym)return!1;let i=id.get(e)??0;return Date.now()-i<_m?!1:(id.set(e,Date.now()),!0)}var Xn,id,od,Kn,ym,_m,wm,Ui=R(()=>{"use strict";Xn=new Map,id=new Map,od=new Map,Kn=new Map,ym=180*1e3,_m=600*1e3,wm=1800*1e3});var Ot,ld,Xr,dd=R(()=>{"use strict";fe();Ot="sessionManager",ld=3e4,Xr=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},ld),h("info",Ot,`Heartbeat timer started (every ${ld/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=>{x(Ot,`Failed to mark session ${t.sessionId} disconnected`,r)}))),h("info",Ot,`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",Ot,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){h("warn",Ot,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,h("info",Ot,"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=>{x(Ot,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&h("debug",Ot,`Sent ${e.length} heartbeat(s)`)}}});var wt,Qr,ud=R(()=>{"use strict";fe();wt="workroomCoordinator",Qr=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",wt,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return h("info",wt,"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 x(wt,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return x(wt,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{x(wt,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),h("info",wt,"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",wt,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){x(wt,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),h("info",wt,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as Hi,unlink as vm,readdir as bm,stat as km}from"fs/promises";import{join as Zr}from"path";import{randomBytes as qi}from"crypto";async function hd(n,e){let t=qi(8).toString("hex"),r=Zr($t,`action-${n}-${t}${fd}`),s;try{s=await Hi(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return h("info",vt,"secret file written",{actionId:n,filePath:r}),r}async function Qn(n){try{await vm(n),h("info",vt,"secret file deleted",{filePath:n})}catch(e){if(Fi(e))return;x(vt,"failed to delete secret file (best-effort)",e)}}async function gd(){let n;try{n=await bm($t)}catch(s){if(Fi(s))return;x(vt,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(fd)),r=0;for(let s of t){let i=Zr($t,s);try{let o=await km(i),a=e-o.mtimeMs;a>=Sm&&(await Qn(i),r++,h("info",vt,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(Fi(o))continue;x(vt,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&h("info",vt,"TTL scan complete",{scanned:t.length,purged:r})}async function pd(n){let e=Date.now(),t=qi(4).toString("hex"),r=Zr($t,`drain-evidence-${e}-${t}.json`),s;try{s=await Hi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",vt,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function md(n){let e=Date.now(),t=qi(4).toString("hex"),r=Zr($t,`response-lost-${e}-${t}.json`),s;try{s=await Hi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",vt,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function Fi(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var vt,Sm,fd,es=R(()=>{"use strict";Xe();fe();vt="secretManager",Sm=600*1e3,fd=".secret"});import{spawn as Em}from"child_process";import{stat as xm}from"fs/promises";async function yd(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return h("warn",zt,"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 xm(e.path)}catch{return h("warn",zt,"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 hd(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return x(zt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=Em(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return x(zt,"spawn failed",i),r&&Qn(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{h("info",zt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&Qn(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{x(zt,"subprocess error after spawn",i),r&&Qn(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),h("info",zt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var zt,_d=R(()=>{"use strict";fe();es();zt="runtimeAdapter"});var H,wd,Zn,vd,er,bd,Tm,ts,Gi=R(()=>{"use strict";On();fe();_d();es();H="actionGate",wd=new Set(["proposed","approved"]),Zn=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),vd="irreversible_no_abort",er=new Set(["transmission_complete","succeeded","canceled","failed"]),bd=15,Tm=8e3,ts=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=Tm){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);x(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){x(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)&&er.has(r)&&this.gateway.getAction(t).then(s=>{er.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=>{x(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=>{er.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=>{x(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){x(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(Zn.has(r.status)){h("info",H,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!wd.has(r.status)){h("info",H,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===vd?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),Zn.has(i.status)){h("info",H,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!wd.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&&Zn.has(r),a=i&&er.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&Zn.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&&er.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 An&&l.isDefinitiveRejection){x(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||Zn.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(p=>{x(H,"cancel after rejected fire also failed",p)});return}x(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 md({schema_version:1,reason:"fire_response_lost_token_unrecoverable",action_id:r,workroom_id:i,session_id:s,fired_at:m,operator_note:"The fire HTTP response was lost before the action_token was received. The raw token is unrecoverable (server stores only hash). The subprocess was NOT spawned. Verify action status on the server manually.",server_todo:'Server reconcile endpoint implemented (Phase 5C). POST /api/v1/actions/:id/reconcile with { reason: "fire_response_lost_token_unrecoverable", evidence_id: "<this-file-uuid>" }. Auth: machine_token bearer. Remove this file after reconcile confirms needs_human status.'}).catch(p=>{x(H,"failed to write response-lost evidence (CRITICAL)",p)});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===vd;c&&this._registerInFlight(e);let d=await yd({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 Cm}from"net";import{chmod as Rm}from"fs/promises";var at,ns,kd=R(()=>{"use strict";fe();at="ipcServer",ns=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=Cm(s=>{this._handleConnection(s)}),this.server.once("error",s=>{x(at,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Rm(e,384)}catch(s){x(at,"Failed to chmod IPC socket",s)}h("info",at,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",at,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){h("debug",at,"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=>{x(at,"IPC socket connection error",r)}),e.on("close",()=>{h("debug",at,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{h("warn",at,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){h("warn",at,"IPC message missing required `type` field \u2014 ignored");return}h("debug",at,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as
|
|
217
|
-
`}catch(i){process.stderr.write(`[agentTrace] serialize error agent=${
|
|
218
|
-
`);return}let s=
|
|
219
|
-
`)});return}process.stderr.write(`[agentTrace] append failed agent=${
|
|
220
|
-
`)})}var Cd,ss,Pt=R(()=>{"use strict";Cd=Td(Im(),".mio","logs"),ss=null});import{readFileSync as $m,writeFileSync as Dm,existsSync as Bm}from"fs";import{join as Um}from"path";function Rd(){return Um(pe,"agent-inbox-cursor.json")}function Ad(){let n=Rd();if(!Bm(n))return{};try{return JSON.parse($m(n,"utf-8"))}catch{return{}}}function Fm(n){Rn(),Dm(Rd(),JSON.stringify(n,null,2),{mode:384})}function Od(n,e){return Ad()[`${n}:${e}`]??"0"}function bt(n,e,t){let r=Ad(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,Fm(r))}var ji=R(()=>{"use strict";Xe()});import{createServer as Hm}from"http";import{randomBytes as qm,timingSafeEqual as Gm}from"crypto";function Me(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Vm(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 os);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function zm(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Gm(t,r)}async function Oe(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 Pd(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=qm(32).toString("hex");async function l(g,w){if(g.method!=="POST"||g.url!=="/act"){w.writeHead(404),w.end();return}let E=g.headers.authorization??"",v=`Bearer ${d}`;if(!zm(E,v)){Me(w,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let _;try{_=await Vm(g,jm)}catch(J){if(J instanceof os){Me(w,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Me(w,400,{ok:!1,code:"INVALID_JSON"});return}let S;try{S=JSON.parse(_)}catch{Me(w,400,{ok:!1,code:"INVALID_JSON"});return}let N=S.action,T=S.payload!=null&&typeof S.payload=="object"?S.payload:{};if(N!=="attachment"&&Buffer.byteLength(_)>Wm){Me(w,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(N)){Me(w,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let I=Ym[N];if(!c.has(I)){Me(w,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let q={Authorization:`Bearer ${s}`,"X-Perf-Caller-Context":"agent_originated","X-Mio-Agent-Id":e,"Content-Type":"application/json"},W=Date.now();try{if(N==="send"){let J=T,re=null;if(o)try{let de=o.get(e);de&&typeof T.context_message_id!="string"&&(J={...T,context_message_id:de},re=de)}catch(de){x(It,"contextTracker.get threw (non-fatal)",de)}let X=typeof T.target=="string"?T.target:null,j=typeof T.parent_message_id=="string"?T.parent_message_id:null,ie=typeof T.content=="string"?T.content.slice(0,120):null;h("info",It,"forward send",{agentId:e,target:X,parent_message_id:j,stamped_context:re!==null,context_message_id:re}),ne(e,"outbound",{action:"send",target:X,parent_message_id:j,context_message_id:re,context_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:ie,content_bytes:typeof T.content=="string"?T.content.length:0}),await Km(w,r,q,J,a),w.statusCode<300&&Bi(e),ne(e,"outbound_done",{action:"send",status:w.statusCode,duration_ms:Date.now()-W})}else if(N==="reply"){let J=typeof T.target=="string"?T.target:null,re=typeof T.parent_message_id=="string"?T.parent_message_id:null,X=typeof T.content=="string"?T.content.slice(0,120):null;ne(e,"outbound",{action:"reply",target:J,parent_message_id:re,parent_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:X}),await Xm(w,r,q,T,a),w.statusCode<300&&Bi(e),ne(e,"outbound_done",{action:"reply",status:w.statusCode,duration_ms:Date.now()-W})}else if(N==="history")await Qm(w,r,q,T,a);else if(N==="task"){let J=typeof T.op=="string"?T.op:null;ne(e,"task",{action:J,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 ey(w,r,q,T,a),ne(e,"task_done",{action:J,status:w.statusCode,duration_ms:Date.now()-W})}else N==="reminder"?await ny(w,r,q,T,a):N==="action"?await sy(w,r,q,T,a):N==="react"?await iy(w,r,q,T,a):N==="attachment"?await oy(w,r,q,T,a):N==="profile"?await ay(w,r,q,T,a):await cy(w,r,q,e,T,a)}catch(J){x(It,"upstream forwarding error",J);let re=J instanceof Error&&J.name==="AbortError";Me(w,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:re?`upstream timed out after ${a}ms`:String(J)})}}let u=Hm((g,w)=>{l(g,w).catch(E=>{x(It,"unhandled request error",E),w.writeHead(500),w.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((g,w)=>{u.once("error",E=>{x(It,"agent proxy startup error",E),w(E)}),u.listen(0,"127.0.0.1",()=>{let E=u.address(),v=typeof E=="object"&&E?E.port:0;h("info",It,"agent proxy listening",{agentId:e,launchId:t,port:v}),g(v)})})}`,proxyToken:d,close:()=>new Promise(g=>{u.close(()=>{h("info",It,"agent proxy stopped",{agentId:e,launchId:t}),g()})})}}async function Km(n,e,t,r,s){let i=await Oe(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Pe(n,i)}async function Xm(n,e,t,r,s){let i=await Oe(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Pe(n,i)}async function Qm(n,e,t,r,s){let i=ly(r),o=await Oe(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Pe(n,o)}async function ey(n,e,t,r,s){let i=String(r.op??""),o=Zm[i];if(!o){Me(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 Oe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Pe(n,l)}else{let{op:c,...d}=r,l=await Oe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Pe(n,l)}}async function ny(n,e,t,r,s){let i=String(r.op??""),o=ty[i];if(!o){Me(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 Oe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Pe(n,l)}else{let{op:c,...d}=r,l=await Oe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Pe(n,l)}}async function sy(n,e,t,r,s){let i=String(r.op??""),o=ry[i];if(!o){Me(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 Oe(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Pe(n,l)}else{let{op:c,...d}=r,l=await Oe(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Pe(n,l)}}async function iy(n,e,t,r,s){let i=await Oe(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Pe(n,i)}async function oy(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await Oe(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Pe(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await Oe(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Pe(n,a);return}Me(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function ay(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 Oe(c,{method:"GET",headers:t},s);await Pe(n,d);return}if(i==="update"){let{op:o,...a}=r,c=await Oe(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Pe(n,c);return}Me(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function cy(n,e,t,r,s,i){let o=String(s.channel??""),a=Od(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),d=await Oe(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!d.ok){await Pe(n,d);return}let l=await d.json(),u=l.messages??[];if(u.length>0){let p=u.reduce((f,g)=>{let w=0n;try{w=BigInt(String(g.seq??"0"))}catch{x(It,"bad seq from upstream",{seq:g.seq}),w=0n}return w>f?w:f},0n);p>0n&&bt(r,o,p.toString())}let m=JSON.stringify(l);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Pe(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{}Me(n,e.status,{ok:!1,code:r,message:s})}function ly(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 It,Wm,jm,Jm,Ym,os,Zm,ty,ry,Id=R(()=>{"use strict";Ui();fe();Pt();ji();It="agentProxy",Wm=1024*1024,jm=12*1024*1024,Jm=15e3,Ym={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};os=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"}};ty={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"}};ry={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as Nd,writeFile as Ji,chmod as Md}from"fs/promises";import{existsSync as Ld}from"fs";import{join as tr,resolve as dy,dirname as uy}from"path";import{spawnSync as fy}from"child_process";import{fileURLToPath as hy}from"url";function nr(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Nt(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function gy(n){let e=uy(hy(import.meta.url))+"/../..",t=n?.localTsxPath??dy(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Ld(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=fy("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Ld(e)?e:null}function Yi(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:gy(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function $d(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??Yi(),c=tr(r,".mio");await Nd(c,{recursive:!0,mode:493});let d=await Pd({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:l,proxyToken:u}=d;try{let m=nr(e),p=nr(t),f=tr(pe,"agent-proxy-tokens",m),g=tr(f,`${p}.token`);await Nd(f,{recursive:!0,mode:448}),await Ji(g,u,{encoding:"utf8",mode:384}),await Md(g,384);let w=o.join(","),E=my({execContext:a,proxyUrl:l,tokenFile:g,capabilityStr:w}),v=tr(c,"mio");await Ji(v,E,{encoding:"utf8",mode:493}),await Md(v,493),await Ji(tr(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let _={...process.env},S=_.PATH??"";return _.PATH=S?`${c}:${S}`:c,delete _.CLAUDECODE,{mioDir:c,spawnEnv:_,proxyHandle:d}}catch(m){throw await d.close().catch(()=>{}),m}}function my(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${Nt(t)} MIO_AGENT_PROXY_TOKEN_FILE=${Nt(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${Nt(s)}`,o;return e.mode==="npm"?o=`exec ${Nt(e.nodePath)} ${Nt(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${Nt(e.tsxPath)} ${Nt(e.cliEntryPath)} agentcli "$@"`:o=`exec ${Nt(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
|
|
221
|
-
`)}var
|
|
214
|
+
`+t)}function jt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,jt),n.emit("wsClientError",o,t,e)}else Gn(t,r,s,i)}});var Dp,Bp,Up,Fp,Hp,qp,vi,Gp,Rd=A(()=>{Dp=oe(wd(),1),Bp=oe(Br(),1),Up=oe(cn(),1),Fp=oe(di(),1),Hp=oe(fi(),1),qp=oe(_i(),1),vi=oe(qr(),1),Gp=oe(Cd(),1)});var Ad,jp,Jp,Wr,bb,bi=A(()=>{Ln();Ut();en();Bt();Ad=oe(Ge(),1),jp=(0,Ad.default)("engine.io-client:websocket"),Jp=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",Wr=class extends ft{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Jp?{}:kr(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;Nn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{jp("websocket closed before onclose event")}s&<(()=>{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]=Sr()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},bb=Re.WebSocket||Re.MozWebSocket});var gn,ki=A(()=>{Rd();bi();gn=class extends Wr{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 vi.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 Od,Wn,pn,Si=A(()=>{Ln();Bt();en();Od=oe(Ge(),1),Wn=(0,Od.default)("engine.io-client:webtransport"),pn=class extends ft{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(()=>{Wn("transport closed gracefully"),this.onClose()}).catch(e=>{Wn("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=rc(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=nc();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){Wn("session is closed");return}Wn("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{Wn("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&<(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var Ei,xi=A(()=>{Qs();ki();Si();Ei={websocket:gn,webtransport:pn,polling:sn}});function mn(n){if(n.length>8e3)throw"URI too long";let e=n,t=n.indexOf("["),r=n.indexOf("]");t!=-1&&r!=-1&&(n=n.substring(0,t)+n.substring(t,r).replace(/:/g,";")+n.substring(r,n.length));let s=Yp.exec(n||""),i={},o=14;for(;o--;)i[Vp[o]]=s[o]||"";return t!=-1&&r!=-1&&(i.source=e,i.host=i.host.substring(1,i.host.length-1).replace(/;/g,":"),i.authority=i.authority.replace("[","").replace("]","").replace(/;/g,":"),i.ipv6uri=!0),i.pathNames=zp(i,i.path),i.queryKey=Kp(i,i.query),i}function zp(n,e){let t=/\/{2,9}/g,r=e.replace(t,"/").split("/");return(e.slice(0,1)=="/"||e.length===0)&&r.splice(0,1),e.slice(-1)=="/"&&r.splice(r.length-1,1),r}function Kp(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var Yp,Vp,Ti=A(()=>{Yp=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Vp=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var Pd,Id,ce,Ci,jn,Jt,jr,yn,Ri=A(()=>{xi();Ut();js();Ti();Pd=oe(Dt(),1);en();Bt();Id=oe(Ge(),1),ce=(0,Id.default)("engine.io-client:socket"),Ci=typeof addEventListener=="function"&&typeof removeEventListener=="function",jn=[];Ci&&addEventListener("offline",()=>{ce("closing %d connection(s) because the network was lost",jn.length),jn.forEach(n=>n())},!1);Jt=class n extends Pd.Emitter{constructor(e,t){if(super(),this.binaryType=ic,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=mn(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=mn(t.host).host);ut(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=dc(this.opts.query)),Ci&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(ce("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},jn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=oc()),this._open()}createTransport(e){ce('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=Gs,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 ce("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){ce("setting transport %s",e.name),this.transport&&(ce("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(){ce("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(ce('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 ce('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();ce("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+=ac(s)),r>0&&t>this._maxPayload)return ce("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return ce("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&&(ce("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,lt(()=>{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"),ce("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(ce("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return ce("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(ce('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),Ci&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=jn.indexOf(this._offlineEventListener);r!==-1&&(ce("removing listener for the 'offline' event"),jn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Jt.protocol=Gs;jr=class extends Jt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){ce("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){ce('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Jt.priorWebsocketSuccess=!1;let s=()=>{r||(ce('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(ce('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Jt.priorWebsocketSuccess=t.name==="websocket",ce('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(ce("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{ce('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(),ce('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&&(ce('"%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}},yn=class extends jr{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=>Ei[s]).filter(s=>!!s)),super(e,r)}}});var Nd=A(()=>{Vs()});var Wb,Jr=A(()=>{Ri();Ri();Ln();xi();Ut();Ti();Bt();Nd();Qs();Ks();ki();bi();Si();Wb=yn.protocol});function $d(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)||(Md("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),Md("parse %s",n),r=mn(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 Ld,Md,Dd=A(()=>{Jr();Ld=oe(Ge(),1),Md=(0,Ld.default)("socket.io-client:url")});function Yn(n){return em&&(n instanceof ArrayBuffer||tm(n))||nm&&n instanceof Blob||rm&&n instanceof File}function Jn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Jn(n[t]))return!0;return!1}if(Yn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Jn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Jn(n[t]))return!0;return!1}var em,tm,Bd,nm,rm,Ai=A(()=>{em=typeof ArrayBuffer=="function",tm=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,Bd=Object.prototype.toString,nm=typeof Blob=="function"||typeof Blob<"u"&&Bd.call(Blob)==="[object BlobConstructor]",rm=typeof File=="function"||typeof File<"u"&&Bd.call(File)==="[object FileConstructor]"});function Ud(n){let e=[],t=n.data,r=n;return r.data=Oi(t,e),r.attachments=e.length,{packet:r,buffers:e}}function Oi(n,e){if(!n)return n;if(Yn(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]=Oi(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]=Oi(n[r],e));return t}return n}function Fd(n,e){return n.data=Pi(n.data,e),delete n.attachments,n}function Pi(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]=Pi(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=Pi(n[t],e));return n}var Hd=A(()=>{Ai()});var $i={};Be($i,{Decoder:()=>Mi,Encoder:()=>Ni,PacketType:()=>W,isPacketValid:()=>am,protocol:()=>jd});function sm(n){return typeof n=="string"}function im(n){return n===void 0||Jd(n)}function Yr(n){return Object.prototype.toString.call(n)==="[object Object]"}function om(n,e){switch(n){case W.CONNECT:return e===void 0||Yr(e);case W.DISCONNECT:return e===void 0;case W.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&Wd.indexOf(e[0])===-1);case W.ACK:return Array.isArray(e);case W.CONNECT_ERROR:return typeof e=="string"||Yr(e);default:return!1}}function am(n){return sm(n.nsp)&&im(n.id)&&om(n.type,n.data)}var qd,Gd,Ii,Wd,jd,W,Ni,Mi,Li,Jd,Vr=A(()=>{qd=oe(Dt(),1);Hd();Ai();Gd=oe(Ge(),1),Ii=(0,Gd.default)("socket.io-parser"),Wd=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],jd=5;(function(n){n[n.CONNECT=0]="CONNECT",n[n.DISCONNECT=1]="DISCONNECT",n[n.EVENT=2]="EVENT",n[n.ACK=3]="ACK",n[n.CONNECT_ERROR=4]="CONNECT_ERROR",n[n.BINARY_EVENT=5]="BINARY_EVENT",n[n.BINARY_ACK=6]="BINARY_ACK"})(W||(W={}));Ni=class{constructor(e){this.replacer=e}encode(e){return Ii("encoding packet %j",e),(e.type===W.EVENT||e.type===W.ACK)&&Jn(e)?this.encodeAsBinary({type:e.type===W.EVENT?W.BINARY_EVENT:W.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===W.BINARY_EVENT||e.type===W.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)),Ii("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=Ud(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},Mi=class n extends qd.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===W.BINARY_EVENT;r||t.type===W.BINARY_ACK?(t.type=r?W.EVENT:W.ACK,this.reconstructor=new Li(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Yn(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(W[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===W.BINARY_EVENT||r.type===W.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(!Jd(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 Ii("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 W.CONNECT:return Yr(t);case W.DISCONNECT:return t===void 0;case W.CONNECT_ERROR:return typeof t=="string"||Yr(t);case W.EVENT:case W.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&Wd.indexOf(t[0])===-1);case W.ACK:case W.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},Li=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=Fd(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};Jd=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function Fe(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var Di=A(()=>{});var Yd,Vd,ge,cm,_n,Bi=A(()=>{Vr();Di();Yd=oe(Dt(),1),Vd=oe(Ge(),1),ge=(0,Vd.default)("socket.io-client:socket"),cm=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),_n=class extends Yd.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=[Fe(e,"open",this.onopen.bind(this)),Fe(e,"packet",this.onpacket.bind(this)),Fe(e,"error",this.onerror.bind(this)),Fe(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected?this:(this.subEvents(),this.io._reconnecting||this.io.open(),this.io._readyState==="open"&&this.onopen(),this)}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,s,i;if(cm.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;let o={type:W.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let d=this.ids++;ge("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?ge("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&&(ge("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));ge("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]?ge("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(ge("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(ge("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(ge("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ge("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ge("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(){ge("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:W.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){ge("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 W.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 W.EVENT:case W.BINARY_EVENT:this.onevent(e);break;case W.ACK:case W.BINARY_ACK:this.onack(e);break;case W.DISCONNECT:this.ondisconnect();break;case W.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||[];ge("emitting event %j",t),e.id!=null&&(ge("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,ge("sending ack %j",s),t.packet({type:W.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ge("bad ack %s",e.id);return}delete this.acks[e.id],ge("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ge("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(){ge("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&&(ge("performing disconnect (%s)",this.nsp),this.packet({type:W.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 Yt(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 zd=A(()=>{Yt.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};Yt.prototype.reset=function(){this.attempts=0};Yt.prototype.setMin=function(n){this.ms=n};Yt.prototype.setMax=function(n){this.max=n};Yt.prototype.setJitter=function(n){this.jitter=n}});var Kd,Xd,ve,wn,Qd=A(()=>{Jr();Bi();Vr();Di();zd();Kd=oe(Dt(),1),Xd=oe(Ge(),1),ve=(0,Xd.default)("socket.io-client:manager"),wn=class extends Kd.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,ut(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 Yt({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||$i;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(ve("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;ve("opening %s",this.uri),this.engine=new yn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Fe(t,"open",function(){r.onopen(),e&&e()}),i=a=>{ve("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Fe(t,"error",i);if(this._timeout!==!1){let a=this._timeout;ve("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{ve("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(){ve("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Fe(e,"ping",this.onping.bind(this)),Fe(e,"data",this.ondata.bind(this)),Fe(e,"error",this.onerror.bind(this)),Fe(e,"close",this.onclose.bind(this)),Fe(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){lt(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){ve("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new _n(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){ve("socket %s is still active, skipping close",r);return}this._close()}_packet(e){ve("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(){ve("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){ve("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;ve("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)ve("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();ve("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(ve("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(ve("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(ve("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 zn(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=$d(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Vn[s]&&i in Vn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(Zd("ignoring socket cache for %s",r),c=new wn(r,e)):(Vn[s]||(Zd("new io instance for %s",r),Vn[s]=new wn(r,e)),c=Vn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var el,Zd,Vn,tl=A(()=>{Dd();Qd();Bi();el=oe(Ge(),1);Vr();Jr();Zd=(0,el.default)("socket.io-client"),Vn={};Object.assign(zn,{Manager:wn,Socket:_n,io:zn,connect:zn})});var ot,dm,zr,nl=A(()=>{"use strict";tl();fe();ot="wsClient",dm=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),zr=class{constructor(e){this.opts=e;this.token=e.token}opts;socket=null;handlers=new Map;lastSeenSeq=new Map;reconnectAttempt=0;reconnectTimer=null;destroyed=!1;authFailed=!1;token;connect(){this.socket||this._connect()}subscribe(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t),this.socket?.connected&&this._emitSubscribe(e)}unsubscribe(e,t){let r=this.handlers.get(e);r&&(r.delete(t),r.size===0&&(this.handlers.delete(e),this.socket?.connected&&this.socket.emit("unsubscribe",{workroom_id:e})))}updateToken(e){this.token=e,h("info",ot,"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=>{x(ot,"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=zn(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{h("info",ot,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{x(ot,"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=>{x(ot,"event handler threw",i)})});for(let t of dm)e.on(t,r=>{h("error",ot,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,h("error",ot,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{h("warn",ot,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{x(ot,"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",ot,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var et,Kr,rl=A(()=>{"use strict";Kt();ya();On();nl();fe();et="serverGateway",Kr=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=xt(),h("info",et,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new zr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>ma(t,r)});let e=pa();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),h("info",et,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),h("info",et,`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",et,"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",et,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return wa(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await va(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1,t){await ba(this.config.server_url,this._getToken(),e,t)}async updateSessionStatus(e,t){await ka(this.config.server_url,e,t,this._getToken())}async getAction(e){return Ea(this.config.server_url,e,this._getToken())}async getApproval(e){return xa(this.config.server_url,e,this._getToken())}async fireAction(e,t){return Ta(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await Ca(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return Ra(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return Qt(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return Aa(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return Pa(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return Ia(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return Oa(this.config.server_url,e,this._getToken())}async getTasks(e,t){return _r(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return Na(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return Ma(this.config.server_url,this._getToken(),e)}async snoozeReminder(e,t){return La(this.config.server_url,this._getToken(),e,t)}async updateReminder(e,t){return $a(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return Da(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return Ba(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await Ha(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await Ua(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 Fa(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r,s){return qa(this.config.server_url,this._getToken(),e,t,r,s)}async getMessageById(e,t){return Ga(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){h("info",et,"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 Sa(this.config.server_url,e,t,this._getToken());if(r.seq_expired){h("warn",et,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}h("info",et,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){x(et,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=xt(),t=await _a(this.config.server_url,e);hr(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),h("info",et,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){x(et,"token refresh failed",e)}}_getToken(){return this.token||(this.token=xt()),this.token}}});import{execFile as lm}from"node:child_process";import{promisify as um}from"node:util";import{readFileSync as fm,readdirSync as Xr,statSync as Ui,openSync as hm,readSync as gm,closeSync as pm}from"node:fs";import{join as Vt}from"node:path";import{homedir as sl}from"node:os";async function mm(){try{if(process.platform==="darwin"){let{stdout:n}=await il("security",["find-generic-password","-s","Claude Code-credentials","-w"]),e=JSON.parse(n).claudeAiOauth?.accessToken;if(e)return e}}catch{}try{let n=fm(Vt(sl(),".claude",".credentials.json"),"utf-8");return JSON.parse(n).claudeAiOauth?.accessToken??null}catch{return null}}async function ym(){let n=await mm();if(!n)return null;try{let{stdout:e}=await il("curl",["-s","--max-time","10","-H",`Authorization: Bearer ${n}`,"-H","anthropic-beta: oauth-2025-04-20","https://api.anthropic.com/api/oauth/usage"]),t=JSON.parse(e);return typeof t.five_hour?.utilization!="number"?null:{five_hour_pct:t.five_hour.utilization,seven_day_pct:t.seven_day?.utilization??0,five_hour_resets_at:t.five_hour.resets_at??null,seven_day_resets_at:t.seven_day?.resets_at??null}}catch{return null}}function _m(n,e){let t=[];try{for(let r of Xr(n).sort().reverse().slice(0,2)){let s=Vt(n,r);for(let i of Xr(s).sort().reverse().slice(0,2)){let o=Vt(s,i);for(let a of Xr(o).sort().reverse().slice(0,7)){let c=Vt(o,a);for(let l of Xr(c)){if(!l.endsWith(".jsonl"))continue;let d=Vt(c,l);try{t.push({path:d,mtime:Ui(d).mtimeMs})}catch{}}}if(t.length>=e*4)break}if(t.length>=e*4)break}}catch{}return t.sort((r,s)=>s.mtime-r.mtime).slice(0,e).map(r=>r.path)}function wm(n,e){let t=hm(n,"r");try{let r=Ui(n).size,s=Math.min(e,r),i=Buffer.alloc(s);return gm(t,i,0,s,r-s),i.toString("utf-8")}finally{pm(t)}}function vm(){let n=process.env.CODEX_HOME??Vt(sl(),".codex");for(let e of _m(Vt(n,"sessions"),5))try{let t=wm(e,262144).split(`
|
|
215
|
+
`).filter(r=>r.includes('"rate_limits"'));for(let r=t.length-1;r>=0;r--)try{let s=JSON.parse(t[r]),i=s.payload?.rate_limits;if(!i?.primary)continue;let o=a=>a?new Date(a*1e3).toISOString():null;return{five_hour_pct:i.primary.used_percent??0,seven_day_pct:i.secondary?.used_percent??0,five_hour_resets_at:o(i.primary.resets_at),seven_day_resets_at:o(i.secondary?.resets_at),plan:i.plan_type??null,observed_at:s.timestamp??new Date(Ui(e).mtimeMs).toISOString()}}catch{}}catch{}return null}async function ol(){let[n,e]=await Promise.all([ym(),Promise.resolve().then(vm)]);return{sampled_at:new Date().toISOString(),claude:n,codex:e}}var il,al=A(()=>{"use strict";il=um(lm)});function ll(n,e,t){if(t){let r=`${n}:${t}`;if(Kn.has(r))return;if(Kn.set(r,Date.now()),Kn.size>500){let s=Date.now()-36e5;for(let[i,o]of Kn)o<s&&Kn.delete(i)}}Xn.set(`${n}:${e}`,Date.now())}function Fi(n){dl.set(n,Date.now());let e=`${n}:`;for(let t of Xn.keys())t.startsWith(e)&&Xn.delete(t)}function ul(n,e){let t=`${n}:${e}`,r=Xn.get(t);if(r===void 0||(Xn.delete(t),Date.now()-r>Sm))return!1;let s=dl.get(n)??0;if(Date.now()-s<bm)return!1;let i=cl.get(e)??0;return Date.now()-i<km?!1:(cl.set(e,Date.now()),!0)}var Xn,cl,dl,Kn,bm,km,Sm,Hi=A(()=>{"use strict";Xn=new Map,cl=new Map,dl=new Map,Kn=new Map,bm=180*1e3,km=600*1e3,Sm=1800*1e3});var Ot,fl,Qr,hl=A(()=>{"use strict";fe();Ot="sessionManager",fl=3e4,Qr=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},fl),h("info",Ot,`Heartbeat timer started (every ${fl/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=>{x(Ot,`Failed to mark session ${t.sessionId} disconnected`,r)}))),h("info",Ot,`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",Ot,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){h("warn",Ot,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,h("info",Ot,"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=>{x(Ot,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&h("debug",Ot,`Sent ${e.length} heartbeat(s)`)}}});var _t,Zr,gl=A(()=>{"use strict";fe();_t="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",_t,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return h("info",_t,"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 x(_t,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return x(_t,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{x(_t,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),h("info",_t,"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",_t,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){x(_t,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),h("info",_t,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as Gi,unlink as Em,readdir as xm,stat as Tm}from"fs/promises";import{join as es}from"path";import{randomBytes as Wi}from"crypto";async function ml(n,e){let t=Wi(8).toString("hex"),r=es($t,`action-${n}-${t}${pl}`),s;try{s=await Gi(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return h("info",wt,"secret file written",{actionId:n,filePath:r}),r}async function Qn(n){try{await Em(n),h("info",wt,"secret file deleted",{filePath:n})}catch(e){if(qi(e))return;x(wt,"failed to delete secret file (best-effort)",e)}}async function yl(){let n;try{n=await xm($t)}catch(s){if(qi(s))return;x(wt,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(pl)),r=0;for(let s of t){let i=es($t,s);try{let o=await Tm(i),a=e-o.mtimeMs;a>=Cm&&(await Qn(i),r++,h("info",wt,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(qi(o))continue;x(wt,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&h("info",wt,"TTL scan complete",{scanned:t.length,purged:r})}async function _l(n){let e=Date.now(),t=Wi(4).toString("hex"),r=es($t,`drain-evidence-${e}-${t}.json`),s;try{s=await Gi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",wt,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function wl(n){let e=Date.now(),t=Wi(4).toString("hex"),r=es($t,`response-lost-${e}-${t}.json`),s;try{s=await Gi(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return h("info",wt,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function qi(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var wt,Cm,pl,ts=A(()=>{"use strict";Ke();fe();wt="secretManager",Cm=600*1e3,pl=".secret"});import{spawn as Rm}from"child_process";import{stat as Am}from"fs/promises";async function vl(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return h("warn",zt,"no enabled runtime found for kind",{kind:n.kind,actionId:n.actionId,availableKinds:n.runtimes.map(i=>i.kind)}),{ok:!1,reason_code:"RUNTIME_NOT_FOUND"};try{await Am(e.path)}catch{return h("warn",zt,"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 ml(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return x(zt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=Rm(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return x(zt,"spawn failed",i),r&&Qn(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{h("info",zt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&Qn(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{x(zt,"subprocess error after spawn",i),r&&Qn(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),h("info",zt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var zt,bl=A(()=>{"use strict";fe();ts();zt="runtimeAdapter"});var F,kl,Zn,Sl,er,El,Om,ns,ji=A(()=>{"use strict";On();fe();bl();ts();F="actionGate",kl=new Set(["proposed","approved"]),Zn=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),Sl="irreversible_no_abort",er=new Set(["transmission_complete","succeeded","canceled","failed"]),El=15,Om=8e3,ns=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",F,"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",F,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,h("info",F,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=Om){if(this.inFlightIrreversible.size===0){h("info",F,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return h("warn",F,"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);x(F,"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 _l({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",F,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){x(F,"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)&&er.has(r)&&this.gateway.getAction(t).then(s=>{er.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):h("warn",F,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{x(F,"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",F,"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",F,"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",F,"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=>{er.has(s.status)?(h("info",F,"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",F,"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=>{x(F,"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){x(F,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){h("info",F,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){h("warn",F,"action.created: missing action_id in payload \u2014 ignoring");return}h("info",F,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(Zn.has(r.status)){h("info",F,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!kl.has(r.status)){h("info",F,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===Sl?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",F,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&h("info",F,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),h("info",F,"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",F,"approval.decided: missing required fields \u2014 ignoring");return}if(h("info",F,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),h("info",F,"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),Zn.has(i.status)){h("info",F,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!kl.has(i.status)){h("warn",F,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){h("warn",F,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){h("warn",F,"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",F,"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&&Zn.has(r),a=i&&er.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&Zn.has(c.status)&&(this.pendingApproval.delete(t),h("info",F,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&er.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",F,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let d=await this.gateway.fireAction(r,t);h("info",F,"action fired",{actionId:r,fired_at:d.fired_at}),a=d.action_token,o=!0}catch(d){if(d instanceof An&&d.isDefinitiveRejection){x(F,`fire definitively rejected (${d.statusCode} ${d.errorCode}) \u2014 re-querying before cancel`,d);let m=await this.gateway.getAction(r).catch(()=>null);if(!m||Zn.has(m.status)){h("info",F,"action already in non-cancelable state after rejected fire \u2014 skipping cancel (concurrent winner?)",{actionId:r,currentStatus:m?.status});return}await this.gateway.cancelAction(r).catch(p=>{x(F,"cancel after rejected fire also failed",p)});return}x(F,"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",F,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let m=u.fired_at??new Date().toISOString();await wl({schema_version:1,reason:"fire_response_lost_token_unrecoverable",action_id:r,workroom_id:i,session_id:s,fired_at:m,operator_note:"The fire HTTP response was lost before the action_token was received. The raw token is unrecoverable (server stores only hash). The subprocess was NOT spawned. Verify action status on the server manually.",server_todo:'Server reconcile endpoint implemented (Phase 5C). POST /api/v1/actions/:id/reconcile with { reason: "fire_response_lost_token_unrecoverable", evidence_id: "<this-file-uuid>" }. Auth: machine_token bearer. Remove this file after reconcile confirms needs_human status.'}).catch(p=>{x(F,"failed to write response-lost evidence (CRITICAL)",p)});return}else{h("warn",F,"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===Sl;c&&this._registerInFlight(e);let l=await vl({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",F,"spawn returned not-ok",{actionId:r,reason_code:l.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as Pm}from"net";import{chmod as Im}from"fs/promises";var at,rs,xl=A(()=>{"use strict";fe();at="ipcServer",rs=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=Pm(s=>{this._handleConnection(s)}),this.server.once("error",s=>{x(at,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Im(e,384)}catch(s){x(at,"Failed to chmod IPC socket",s)}h("info",at,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",at,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){h("debug",at,"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=>{x(at,"IPC socket connection error",r)}),e.on("close",()=>{h("debug",at,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{h("warn",at,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){h("warn",at,"IPC message missing required `type` field \u2014 ignored");return}h("debug",at,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as Nm}from"http";var Ji,Mm,Lm,ss,Tl=A(()=>{"use strict";fe();Ji="healthServer",Mm="127.0.0.1",Lm=7878,ss=class{constructor(e){this.version=e}version;server=null;startTime=Date.now();async listen(e=Mm,t=Lm){return new Promise((r,s)=>{this.server=Nm((i,o)=>this._handleRequest(i,o)),this.server.once("error",i=>{x(Ji,"Health server startup error",i),s(i)}),this.server.listen(t,e,()=>{h("info",Ji,`Health server listening on ${e}:${t}`),r()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{h("info",Ji,"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 Cl,mkdir as Rl}from"node:fs/promises";import{homedir as $m}from"node:os";import{dirname as Dm,join as Al}from"node:path";function Bm(){return is||(is=Rl(Ol,{recursive:!0}).then(()=>{},n=>{throw is=null,n})),is}function os(n){return n&&n.replace(/-/g,"").slice(0,8)||"unknown"}function Um(n){return Al(Ol,`agent-${os(n)}.jsonl`)}function ne(n,e,t){let r;try{let i={ts:new Date().toISOString(),agent_id:n,kind:e,...t};r=JSON.stringify(i)+`
|
|
217
|
+
`}catch(i){process.stderr.write(`[agentTrace] serialize error agent=${os(n)} kind=${e}: ${i.message}
|
|
218
|
+
`);return}let s=Um(n);Bm().then(()=>Cl(s,r,{encoding:"utf8"})).catch(i=>{if(i.code==="ENOENT"){let o=Dm(s);Rl(o,{recursive:!0}).then(()=>Cl(s,r,{encoding:"utf8"})).catch(a=>{process.stderr.write(`[agentTrace] append failed agent=${os(n)} kind=${e}: ${a.message}
|
|
219
|
+
`)});return}process.stderr.write(`[agentTrace] append failed agent=${os(n)} kind=${e}: ${i.message}
|
|
220
|
+
`)})}var Ol,is,Pt=A(()=>{"use strict";Ol=Al($m(),".mio","logs"),is=null});import{readFileSync as Fm,writeFileSync as Hm,existsSync as qm}from"fs";import{join as Gm}from"path";function Pl(){return Gm(pe,"agent-inbox-cursor.json")}function Il(){let n=Pl();if(!qm(n))return{};try{return JSON.parse(Fm(n,"utf-8"))}catch{return{}}}function Wm(n){Rn(),Hm(Pl(),JSON.stringify(n,null,2),{mode:384})}function Nl(n,e){return Il()[`${n}:${e}`]??"0"}function vt(n,e,t){let r=Il(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,Wm(r))}var Yi=A(()=>{"use strict";Ke()});import{createServer as jm}from"http";import{randomBytes as Jm,timingSafeEqual as Ym}from"crypto";function Le(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Qm(n,e){return new Promise((t,r)=>{let s=[],i=0;n.on("data",o=>{if(i+=o.length,i>e){n.destroy(),r(new as);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function Zm(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Ym(t,r)}async function Ae(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 Ml(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??Km,c=i instanceof Set?i:new Set(i),l=Jm(32).toString("hex");async function d(g,_){if(g.method!=="POST"||g.url!=="/act"){_.writeHead(404),_.end();return}let E=g.headers.authorization??"",v=`Bearer ${l}`;if(!Zm(E,v)){Le(_,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let y;try{y=await Qm(g,zm)}catch(Y){if(Y instanceof as){Le(_,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Le(_,400,{ok:!1,code:"INVALID_JSON"});return}let S;try{S=JSON.parse(y)}catch{Le(_,400,{ok:!1,code:"INVALID_JSON"});return}let N=S.action,T=S.payload!=null&&typeof S.payload=="object"?S.payload:{};if(N!=="attachment"&&Buffer.byteLength(y)>Vm){Le(_,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(N)){Le(_,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let I=Xm[N];if(!c.has(I)){Le(_,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let q={Authorization:`Bearer ${s}`,"X-Perf-Caller-Context":"agent_originated","X-Mio-Agent-Id":e,"Content-Type":"application/json"},j=Date.now();try{if(N==="send"){let Y=T,re=null;if(o)try{let le=o.get(e);le&&typeof T.context_message_id!="string"&&(Y={...T,context_message_id:le},re=le)}catch(le){x(It,"contextTracker.get threw (non-fatal)",le)}let X=typeof T.target=="string"?T.target:null,J=typeof T.parent_message_id=="string"?T.parent_message_id:null,ie=typeof T.content=="string"?T.content.slice(0,120):null;h("info",It,"forward send",{agentId:e,target:X,parent_message_id:J,stamped_context:re!==null,context_message_id:re}),ne(e,"outbound",{action:"send",target:X,parent_message_id:J,context_message_id:re,context_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:ie,content_bytes:typeof T.content=="string"?T.content.length:0}),await ey(_,r,q,Y,a),_.statusCode<300&&Fi(e),ne(e,"outbound_done",{action:"send",status:_.statusCode,duration_ms:Date.now()-j})}else if(N==="reply"){let Y=typeof T.target=="string"?T.target:null,re=typeof T.parent_message_id=="string"?T.parent_message_id:null,X=typeof T.content=="string"?T.content.slice(0,120):null;ne(e,"outbound",{action:"reply",target:Y,parent_message_id:re,parent_message_id_short:re?re.replace(/-/g,"").slice(0,8):null,content_preview:X}),await ty(_,r,q,T,a),_.statusCode<300&&Fi(e),ne(e,"outbound_done",{action:"reply",status:_.statusCode,duration_ms:Date.now()-j})}else if(N==="history")await ny(_,r,q,T,a);else if(N==="task"){let Y=typeof T.op=="string"?T.op:null;ne(e,"task",{action:Y,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 sy(_,r,q,T,a),ne(e,"task_done",{action:Y,status:_.statusCode,duration_ms:Date.now()-j})}else N==="reminder"?await oy(_,r,q,T,a):N==="action"?await cy(_,r,q,T,a):N==="react"?await dy(_,r,q,T,a):N==="attachment"?await ly(_,r,q,T,a):N==="profile"?await uy(_,r,q,T,a):await fy(_,r,q,e,T,a)}catch(Y){x(It,"upstream forwarding error",Y);let re=Y instanceof Error&&Y.name==="AbortError";Le(_,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:re?`upstream timed out after ${a}ms`:String(Y)})}}let u=jm((g,_)=>{d(g,_).catch(E=>{x(It,"unhandled request error",E),_.writeHead(500),_.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((g,_)=>{u.once("error",E=>{x(It,"agent proxy startup error",E),_(E)}),u.listen(0,"127.0.0.1",()=>{let E=u.address(),v=typeof E=="object"&&E?E.port:0;h("info",It,"agent proxy listening",{agentId:e,launchId:t,port:v}),g(v)})})}`,proxyToken:l,close:()=>new Promise(g=>{u.close(()=>{h("info",It,"agent proxy stopped",{agentId:e,launchId:t}),g()})})}}async function ey(n,e,t,r,s){let i=await Ae(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Oe(n,i)}async function ty(n,e,t,r,s){let i=await Ae(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Oe(n,i)}async function ny(n,e,t,r,s){let i=hy(r),o=await Ae(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Oe(n,o)}async function sy(n,e,t,r,s){let i=String(r.op??""),o=ry[i];if(!o){Le(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 Ae(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Oe(n,d)}else{let{op:c,...l}=r,d=await Ae(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Oe(n,d)}}async function oy(n,e,t,r,s){let i=String(r.op??""),o=iy[i];if(!o){Le(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 Ae(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Oe(n,d)}else{let{op:c,...l}=r,d=await Ae(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Oe(n,d)}}async function cy(n,e,t,r,s){let i=String(r.op??""),o=ay[i];if(!o){Le(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 Ae(l?`${a}?${l}`:a,{method:"GET",headers:t},s);await Oe(n,d)}else{let{op:c,...l}=r,d=await Ae(a,{method:"POST",headers:t,body:JSON.stringify(l)},s);await Oe(n,d)}}async function dy(n,e,t,r,s){let i=await Ae(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Oe(n,i)}async function ly(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await Ae(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Oe(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await Ae(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Oe(n,a);return}Le(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function uy(n,e,t,r,s){let i=String(r.op??"");if(i==="show"){let o=`${e}/internal/agent-api/profile`,a=r.handle,c=a!==void 0?`${o}?handle=${encodeURIComponent(String(a))}`:o,l=await Ae(c,{method:"GET",headers:t},s);await Oe(n,l);return}if(i==="update"){let{op:o,...a}=r,c=await Ae(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Oe(n,c);return}Le(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function fy(n,e,t,r,s,i){let o=String(s.channel??""),a=Nl(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),l=await Ae(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!l.ok){await Oe(n,l);return}let d=await l.json(),u=d.messages??[];if(u.length>0){let p=u.reduce((f,g)=>{let _=0n;try{_=BigInt(String(g.seq??"0"))}catch{x(It,"bad seq from upstream",{seq:g.seq}),_=0n}return _>f?_:f},0n);p>0n&&vt(r,o,p.toString())}let m=JSON.stringify(d);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(m)}),n.end(m)}async function Oe(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{}Le(n,e.status,{ok:!1,code:r,message:s})}function hy(n){let e=new URLSearchParams;n.channel!==void 0&&e.set("channel",String(n.channel)),n.after_seq!==void 0&&e.set("after_seq",String(n.after_seq)),n.limit!==void 0&&e.set("limit",String(n.limit)),n.around!==void 0&&e.set("around",String(n.around));let t=e.toString();return t?`?${t}`:""}var It,Vm,zm,Km,Xm,as,ry,iy,ay,Ll=A(()=>{"use strict";Hi();fe();Pt();Yi();It="agentProxy",Vm=1024*1024,zm=12*1024*1024,Km=15e3,Xm={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};as=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};ry={list:{method:"GET",path:"list"},create:{method:"POST",path:"create"},claim:{method:"POST",path:"claim"},unclaim:{method:"POST",path:"unclaim"},update:{method:"POST",path:"update-status"},review:{method:"POST",path:"review"}};iy={schedule:{method:"POST",path:"schedule"},list:{method:"GET",path:"list"},snooze:{method:"POST",path:"snooze"},update:{method:"POST",path:"update"},cancel:{method:"POST",path:"cancel"},log:{method:"GET",path:"log"}};ay={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as $l,writeFile as Vi,chmod as Dl}from"fs/promises";import{existsSync as Bl}from"fs";import{join as tr,resolve as gy,dirname as py}from"path";import{spawnSync as my}from"child_process";import{fileURLToPath as yy}from"url";function nr(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function Nt(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function _y(n){let e=py(yy(import.meta.url))+"/../..",t=n?.localTsxPath??gy(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Bl(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??wy)();return i||"tsx"}function wy(){let e=my("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Bl(e)?e:null}function zi(n){let e=n!==void 0?n.execPath:process.execPath,t=n!==void 0?n.argv1:process.argv[1];return t===void 0||t===e?{mode:"sea",seaBinaryPath:e}:t.endsWith(".ts")?{mode:"tsx-source",tsxPath:_y(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function Ul(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??zi(),c=tr(r,".mio");await $l(c,{recursive:!0,mode:493});let l=await Ml({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:d,proxyToken:u}=l;try{let m=nr(e),p=nr(t),f=tr(pe,"agent-proxy-tokens",m),g=tr(f,`${p}.token`);await $l(f,{recursive:!0,mode:448}),await Vi(g,u,{encoding:"utf8",mode:384}),await Dl(g,384);let _=o.join(","),E=vy({execContext:a,proxyUrl:d,tokenFile:g,capabilityStr:_}),v=tr(c,"mio");await Vi(v,E,{encoding:"utf8",mode:493}),await Dl(v,493),await Vi(tr(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let y={...process.env},S=y.PATH??"";return y.PATH=S?`${c}:${S}`:c,delete y.CLAUDECODE,{mioDir:c,spawnEnv:y,proxyHandle:l}}catch(m){throw await l.close().catch(()=>{}),m}}function vy(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${Nt(t)} MIO_AGENT_PROXY_TOKEN_FILE=${Nt(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${Nt(s)}`,o;return e.mode==="npm"?o=`exec ${Nt(e.nodePath)} ${Nt(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${Nt(e.tsxPath)} ${Nt(e.cliEntryPath)} agentcli "$@"`:o=`exec ${Nt(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
|
|
221
|
+
`)}var Fl=A(()=>{"use strict";Ke();Ll()});function Hl(n,e){let t=`${n} ${e}`.toLowerCase();return/(\bdesigner\b|\bdesign\b|\bui\b|\bux\b|设计师|设计)/.test(t)?"designer":/(\bpm\b|\bproduct manager\b|项目经理|产品经理|product owner|\bpo\b)/.test(t)?"product_manager":/(\bresearch(er)?\b|\banalyst\b|market\s+research|调研|分析师|研究员)/.test(t)?"researcher":/(\bops\b|\bsre\b|\bdevops\b|\bplatform engineer\b|运维)/.test(t)?"ops":/(\bengineer\b|\bdeveloper\b|\bdev\b|工程师|后端|前端|全栈|\bbackend\b|\bfrontend\b|\bfullstack\b|\bfull[- ]stack\b)/.test(t)?"engineer":"general"}var by,ky,Sy,Ey,xy,Ty,ql,Gl=A(()=>{"use strict";by=`## 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.`,
|
|
256
|
+
When delegating, post each \`@Assignee <deliverable>\` line as its own standalone message before any context dump. Status updates on owned tasks should be one line each, never combined.`,ky=`## Role: Engineer
|
|
257
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.`,
|
|
290
|
+
During implementation, send three-beat updates: "starting on X", "found Y / decided Z mid-way", "done with X" or "blocked on W". Never describe what you did at the end as a wall of bullets.`,Sy=`## Role: Designer
|
|
291
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.`,
|
|
323
|
+
When iterating between options, send each option as its own message so teammates can react to each. Don't put 3 design directions in one message.`,Ey=`## Role: Researcher
|
|
324
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.`,
|
|
356
|
+
When investigating, surface a finding as soon as you have it \u2014 don't wait to assemble a full report. Each finding is its own message; the synthesis comes at the end.`,xy=`## Role: Ops / SRE
|
|
357
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.`,
|
|
389
|
+
During a procedure (deploy / rollback / incident), post each step as it happens: "starting maintenance window", "pm2 restarted", "health check passing". Real-time visibility matters more than tidy summary.`,Ty=`## Role: Generalist
|
|
390
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.`,
|
|
420
|
+
Match the cadence of whoever you're talking to. When in doubt: send each logical step as its own short message.`,ql={product_manager:by,engineer:ky,designer:Sy,researcher:Ey,ops:xy,general:Ty}});function $y(n){if(!n)return"\u2014";let e=n.trim();if(!e)return"\u2014";let t=e.match(/^[\s\S]{1,240}?[.!?。!?\n]/);return t?t[0].replace(/\s+$/,""):e.slice(0,140)}function Dy(n){let e=n.roster;if(!e||e.inChannel.length===0&&e.otherInWorkroom.length===0)return"";let t=(i,o)=>{let a="@"+(i.display_name||i.id);return`- ${o?`${a} (you, ${i.kind}, ${i.role})`:`${a} (${i.kind}, ${i.role})`} \u2014 ${$y(i.description)}`},r=e.inChannel.length===0?"- (no other members recorded in this channel yet)":e.inChannel.map(i=>t(i,i.id===n.agentId)).join(`
|
|
421
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
|
|
425
|
+
For teammates in other channels, load the \`mio-team\` skill.`}function Wl(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??Hl(r,`${i??""} ${s}`),m=ql[u],p=s&&s.trim()?`## Additional context from your operator
|
|
426
426
|
|
|
427
427
|
${s.trim()}`:"",f=`## Runtime context
|
|
428
428
|
|
|
@@ -434,15 +434,15 @@ 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: ${
|
|
438
|
-
- Workspace: ${
|
|
437
|
+
- OS: ${l}
|
|
438
|
+
- Workspace: ${d}
|
|
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\`.`,
|
|
440
|
+
When someone writes ${t} they are addressing YOU.`,g=`You are **${r}**, an AI teammate on a Mio team. Your stable @mention handle is \`${t}\`. You collaborate with humans and other AI agents over a shared messaging platform; you persist across sessions through your workspace and \`MEMORY.md\`.`,_=Dy(n),E=500,v=n.persona?n.persona.trim():"",y=v.length>E?v.slice(0,E).replace(/\s+\S*$/,"")+"\u2026":v,S=y.length>0?`## What I've learned (from past interactions)
|
|
441
441
|
|
|
442
|
-
${
|
|
442
|
+
${y}`:"";return[g,Cy,Oy,Ay,Py,Iy,m,p,f,_,S,Ly,Ny,n.runtime==="codex"?My:"",Ry].filter(T=>T&&T.length>0).join(`
|
|
443
443
|
|
|
444
444
|
`)+`
|
|
445
|
-
`}var
|
|
445
|
+
`}var Cy,Ry,Ay,Oy,Py,Iy,Ny,My,Ly,jl=A(()=>{"use strict";Gl();Cy='## Hard constraints (these are absolute)\n\n- You MUST speak to humans in natural language. You MUST NEVER paste `mio` CLI commands, API endpoints, UUIDs, raw message IDs, tokens, file paths from your tooling, or any internal implementation detail into a user-facing reply.\n- You MUST NEVER mention the words `mio`, `CLI`, `command`, `API`, `tool`, `endpoint`, `token`, `UUID`, `proxy`, `agent-api`, or any other internal-mechanism term in a user-facing reply \u2014 not even as a bare concept. Don\'t describe what you CAN\'T do "via your CLI / tools / commands"; describe limitations in user terms, as if you were a human teammate with the same constraint.\n\n \u274C "CLI \u6CA1\u6709\u76F4\u63A5\u6307\u6D3E\u7ED9\u4ED6\u4EBA\u7684\u547D\u4EE4\uFF0C\u53EA\u80FD\u7531\u672C\u4EBA claim\u3002"\n \u2713 "\u6211\u6CA1\u6CD5\u76F4\u63A5\u5E2E\u4ED6\u8BA4\u9886\uFF0C\u5F97\u4ED6\u81EA\u5DF1\u63A5\u624B \u2014 \u6211\u5DF2\u7ECF @ \u4ED6\u4E86\u3002"\n\n \u274C "\u6211\u7528 mio task create \u5EFA\u4E86\u4E00\u4E2A\u4EFB\u52A1\u3002"\n \u2713 "\u5EFA\u597D\u4E86\u3002"\n\n \u274C "\u6211\u7684 agent proxy \u6CA1\u627E\u5230\u8FD9\u4E2A\u7AEF\u70B9\u3002"\n \u2713 "\u6211\u624B\u5934\u67E5\u4E0D\u5230\u8FD9\u4E2A\u6570\u636E\uFF0C\u5F97\u8BF7\u64CD\u4F5C\u5458\u770B\u770B\u3002"\n\n When you find yourself about to explain HOW you did something or WHY a tool limitation exists, STOP. Either do it silently and report the outcome in user terms, or describe the limitation as a human teammate would ("\u6211\u6CA1\u6CD5\u76F4\u63A5\u505A\u8FD9\u4E2A\uFF0C\u4E0D\u8FC7\u6211\u53EF\u4EE5\u2026").\n\n- You MUST NEVER repeat the sender\'s `@handle` or the RFC-style header (e.g. `[target=#... msg=... time=... type=...]`) back to them when replying. Reply as a human teammate would.\n- When asked something whose answer requires looking up data, silently use your skills and tools, then translate the result into a natural reply. The user does NOT care how you got the answer.\n- Be concise *per message*. Multiple short messages can express more than one long one \u2014 see Posting cadence below. NEVER hedge, NEVER apologise for limitations, NEVER add "I\'m an AI" disclaimers, NEVER restate the user\'s question back to them.\n- If you don\'t know, say so plainly in one sentence and (if appropriate) say what you\'ll do to find out.',Ry='## Reminder \u2014 hard constraints (reinforced)\n\nBefore you send anything to a human, check:\n\n- Are you about to paste a `mio` command, an endpoint, a UUID, a raw message ID, or any internal plumbing? STOP. Translate it.\n- Are you about to say "CLI", "command", "API", "tool", "endpoint", "proxy", "agent-api", or any other internal-mechanism word \u2014 even as a bare concept ("CLI \u6CA1\u6709\u8FD9\u4E2A\u547D\u4EE4", "\u5DE5\u5177\u4E0D\u652F\u6301")? STOP. Rephrase as a human teammate would: describe what you CAN do, or say "\u6211\u6CA1\u6CD5\u76F4\u63A5\u505A\u8FD9\u4E2A" without naming the mechanism.\n- Are you about to echo the `@handle` or the `[target=... msg=...]` header? STOP. Drop it.\n- Is this message inside a thread (`[thread context \u2026]`)? Then normal task discussion goes to `mio message reply --parent \u2026`, not `mio message send`. Exception: if you are coordinating and splitting separate independent work for other teammates, send fresh main-channel one-line @handoffs with `mio message send`, one handoff per task.\n- Work assigned TO YOU by a human: create the task yourself with `mio task create \u2026 --self --attach <msg id>` (see Task protocol). To DELEGATE to a teammate, send a short main-channel message tagging exactly one assignee (`@Backend \u5B9E\u73B0 X`) \u2014 the handoff pipeline converts it to a task and wakes them. `mio task claim #N` is ONLY for picking up an UNASSIGNED todo task.\n- **Wrong-person handoff.** If someone addresses YOU with work that clearly belongs to another teammate\'s role (check the roster\'s roles/descriptions above), do NOT attempt it yourself and do NOT just refuse. Hand it off: send one short main-channel message `@<the right teammate> <one-line of what\'s needed>`, and tell the human in natural language that you\'ve passed it to that teammate (name them by name, never by @handle-echo). Pick the teammate whose described role best fits the request. Only take it on yourself if it genuinely fits YOUR role. If no teammate fits, say so plainly and suggest the closest option.\n- Is the message you are answering FROM THE MAIN CHANNEL (its envelope has NO [thread context])? Then your reply MUST go to the main channel via `mio message send` \u2014 NEVER into a task thread. Humans watch the main channel; an answer posted into a thread is invisible to them (07-08: PM answered a main-channel question inside an unrelated task thread and the human never saw it).\n- Are you about to END your turn on a promise ("\u6211\u6765\u505AX" / "\u63A5\u4E0B\u6765\u6211\u4F1A\u2026" / "\u6211\u9A6C\u4E0A\u5F00\u59CB") without having actually started? STOP. Nothing will re-wake you \u2014 do the first concrete step NOW and report it, or state precisely what input you are blocked on.\n- Are you hedging, apologising, disclaiming, or restating the question? STOP. Just answer.\n\nThe user sees natural language only. The mechanism is YOURS to manage, never theirs to hear about.\n\n\u274C "CLI \u6CA1\u6709\u76F4\u63A5\u6307\u6D3E\u7ED9\u4ED6\u4EBA\u7684\u547D\u4EE4" / "\u6211\u7684\u5DE5\u5177\u4E0D\u652F\u6301\u8FD9\u4E2A" / "API \u6CA1\u6709\u8FD9\u4E2A\u7AEF\u70B9"\n\u2713 "\u6211\u6CA1\u6CD5\u76F4\u63A5\u5E2E\u4ED6\u8BA4\u9886\uFF0C\u5F97\u4ED6\u81EA\u5DF1\u63A5\u624B" / "\u8FD9\u4EF6\u4E8B\u6211\u505A\u4E0D\u4E86\uFF0C\u5F97\u8BF7\u64CD\u4F5C\u5458" / "\u6211\u624B\u5934\u67E5\u4E0D\u5230"',Ay=`## Task protocol (how you manage your own work)
|
|
446
446
|
|
|
447
447
|
Server no longer auto-creates tasks from human messages \u2014 YOU decide. When a human message assigns you concrete work (build/fix/change/run something with a deliverable):
|
|
448
448
|
|
|
@@ -452,79 +452,79 @@ Server no longer auto-creates tasks from human messages \u2014 YOU decide. When
|
|
|
452
452
|
- New work UNRELATED to #M \u2192 same: create it --self, tell the human "\u5148\u505A\u5B8C #M,#N \u6392\u5728\u540E\u9762" \u2014 you will be woken automatically when #M closes. NEVER silently absorb a request; every assignment gets an explicit one-line decision reply in the MAIN channel.
|
|
453
453
|
3. **Closing discipline**: finishing the work IS NOT the end of the turn \u2014 run \`mio task update #N --channel <chan> --status done\` in the SAME turn you deliver. A task left in_progress after delivery is a bug you caused (07-07: #5-#8 stranded for a day).
|
|
454
454
|
4. **Stale tasks in your panel** (marked \u6EDE\u7559): either finish+close them or say in their thread why they are blocked. Never ignore them.
|
|
455
|
-
5. **Waiting on the human**: if you asked a question and cannot proceed, say so in the task thread ("\u7B49\u4F60\u786E\u8BA4 X \u624D\u80FD\u7EE7\u7EED") \u2014 and repeat the ask if the human's next message ignores it.`,
|
|
455
|
+
5. **Waiting on the human**: if you asked a question and cannot proceed, say so in the task thread ("\u7B49\u4F60\u786E\u8BA4 X \u624D\u80FD\u7EE7\u7EED") \u2014 and repeat the ask if the human's next message ignores it.`,Oy="## How threads work\n\nEvery message you receive is either in the **main channel** or in a **thread**. A thread is a focused side-conversation hanging off a single main-channel message (its \"parent\").\n\n**You do NOT decide whether something becomes a task.** The platform runs a classifier on every message that gets posted and automatically creates a task + thread when the message is an actionable single-deliverable request. You will see this happen through `[system event: task.created]` / `[system event: task.assigned to you]` wake-ups \u2014 that is your signal to act on a task.\n\n**When the incoming message is in the MAIN channel:**\n\n- Just respond naturally. If it's chit-chat, reply short. If it's a status report or a question to you, answer. If it looks actionable, the platform has already turned it into a task; you'll get the assignment wake separately. Don't pre-empt it by calling `mio task create` yourself.\n- The only time you yourself send a fresh main-channel message that the classifier might pick up as a task is when you (as PM) are reformulating a user's fuzzy goal into a clean deliverable to delegate. Then send the short `@<assignee> <one-line title>` message and the classifier will form the task and wake the assignee \u2014 you do NOT need to call `mio task create`.\n\n**When the incoming message is inside a THREAD (the context block is marked `[thread context \u2026]`):**\n\n- You are working on the task that owns this thread. Reply with `mio message reply --parent <full-uuid-from-id-field>` for discussion about this task. Use the parent's full UUID from the `id=...` field of the inbound header.\n- The main channel should not see your back-and-forth on this task.\n- Do NOT pretend the thread spawns sub-tasks. Threads do not nest \u2014 one task = one thread, full stop. If new, separate work emerges or you are PM/coordinator splitting a user's goal into deliverables, go back to the main channel and send fresh one-line `@<assignee> <deliverable>` announcements, one per task; the classifier will pick them up as new tasks.\n\n**Inbound header reference:** Each incoming line looks like `[target=#chan msg=<short-8-hex> id=<full-uuid> time=... type=...] @sender: ...`. The `msg=` field is just an at-a-glance handle for humans; the `id=` field is the canonical UUID \u2014 always use the full `id=` value (never the short `msg=`) when you reply inside a thread with `--parent`.",Py=`## System-event wakes
|
|
456
456
|
|
|
457
457
|
A \`[system event: ...]\` wake = task status changed / assigned / new in channel.
|
|
458
458
|
Post a brief status only if something meaningful actually changed worth telling
|
|
459
459
|
the team. Otherwise stay silent. Never re-ack the same event twice; never fake
|
|
460
|
-
activity.`,
|
|
460
|
+
activity.`,Iy=`## Posting cadence
|
|
461
461
|
|
|
462
462
|
Multi-step work = multiple short messages at natural breakpoints (1\u20133 sentences each), NOT one bundled report at the end. One message per logical step. Final outcome (done / blocked / needs decision) is its own message. Don't post unless real progress happened.
|
|
463
463
|
|
|
464
|
-
NEVER announce future work and then stop ("\u63A5\u4E0B\u6765\u6211\u4F1A\u8C03 X" and end the turn). Nothing re-wakes you after your turn ends \u2014 a promise without action simply evaporates and the human waits forever. Either DO the work in this turn (then report the result), or if it genuinely must wait, say exactly what you need to proceed (a file, a decision, an @mention when ready). "\u6211\u9A6C\u4E0A\u5F00\u59CB" as a turn-ending line is forbidden.`,
|
|
464
|
+
NEVER announce future work and then stop ("\u63A5\u4E0B\u6765\u6211\u4F1A\u8C03 X" and end the turn). Nothing re-wakes you after your turn ends \u2014 a promise without action simply evaporates and the human waits forever. Either DO the work in this turn (then report the result), or if it genuinely must wait, say exactly what you need to proceed (a file, a decision, an @mention when ready). "\u6211\u9A6C\u4E0A\u5F00\u59CB" as a turn-ending line is forbidden.`,Ny="## Your skills (load via the Skill tool when needed; don't pre-load)\n\n- `mio-messaging` \u2014 read/send/reply messages\n- `mio-tasks` \u2014 list/claim/update tasks (the board forms tasks automatically)\n- `mio-reminders` \u2014 schedule/snooze/cancel reminders\n- `mio-attachments` \u2014 upload/download files\n- `mio-profile` \u2014 view/update profile\n- `mio-team` \u2014 roster lookup (channel + workroom)\n- `mio-memory` \u2014 MEMORY.md, persona.md, companion graph",My='## Codex runtime Mio guide\n\nCodex cannot load Claude skills. Use these commands directly when you need to communicate or update the board. Run them silently; user-facing messages must stay natural and never mention commands.\n\n### Messages\n\nMain-channel message:\n\n```bash\nmio message send --target "#channel-name" <<\'EOF\'\n\u77ED\u6D88\u606F\u6B63\u6587\nEOF\n```\n\nThread reply. Use this whenever the inbound context includes `[thread context ...]` or the work belongs to an assigned task:\n\n```bash\nmio message reply --parent <full-parent-message-uuid> --target "#channel-name" <<\'EOF\'\n\u77ED\u6D88\u606F\u6B63\u6587\nEOF\n```\n\nUse the full `id=...` UUID from the inbound header for `--parent`, not the short `msg=...` value.\n\n### Tasks\n\n```bash\nmio task list --channel "#channel-name"\nmio task claim #5 --channel "#channel-name" # ONLY for an UNASSIGNED todo task you voluntarily pick up\nmio task update #5 --channel "#channel-name" --status done\n```\n\nA task assigned TO you is born already owned by you and already `in_progress`. When you get the `[system event: task #N assigned to you]` wake, do NOT list, claim, or set `in_progress` \u2014 that is your start signal. Just begin: post progress in its thread, do the work, post the result, then mark it `done`. (On a deliverable, the platform may route your `done` through a quick independent review before it closes \u2014 that\'s automatic; if it bounces back with feedback, fix it and set `done` again. You may also be woken to review a teammate\'s task \u2014 the wake explains how.) `claim` is ONLY for an UNASSIGNED `todo` task (no owner) that you choose to pick up. When you are PM/coordinator delegating work, send separate short main-channel `@Assignee deliverable title` messages, one per independent task; the platform creates the tasks automatically.\n\n### Attachments (images, files)\n\nTo share a file (image, avatar, diagram, SVG), attach it directly IN the send with `--attach-file` \u2014 ONE command that uploads AND displays it together:\n\n```bash\nmio message send --target "#channel-name" --attach-file ./avatar.png <<\'EOF\'\n\u8FD9\u662F\u4F60\u8981\u7684\u5934\u50CF\u3002\nEOF\n```\n\nIn a task thread, reply with it: `mio message reply --parent <full-message-uuid> --target "#channel-name" --attach-file ./avatar.png <<\'EOF\' \u2026 EOF`. `--attach-file` is repeatable. Supported images: jpg/jpeg/png/heic/webp/gif.\n\n**Do NOT use `mio attachment upload` by itself to share a file** \u2014 uploading alone does NOT display anything; the file stays invisible to everyone. That is the #1 mistake. Only `--attach-file` (or `--attachment <id>` with an id you already hold) actually shows it. Never say "\u5DF2\u53D1\u4E0A\u6765 / done / \u53D1\u6765\u4E86" about a file unless that send command succeeded. To inspect an existing one: `mio attachment view <attachment_id> [--out ./file.png]`.',Ly=`## Startup and memory
|
|
465
465
|
|
|
466
466
|
1. On every startup, read \`MEMORY.md\` in your cwd first. It is your recovery point after context compression or sleep.
|
|
467
467
|
2. If this turn includes an incoming message, decide whether it needs a reply and handle it.
|
|
468
468
|
3. If there is no incoming message, stop and wait. New messages may be delivered automatically.
|
|
469
469
|
4. Complete ALL your work before stopping \u2014 don't leave a half-finished thought.
|
|
470
470
|
|
|
471
|
-
Your cwd is your **persistent, agent-owned workspace** \u2014 files you create here survive across sessions. Use it for memory, notes, artifacts, and work files. Keep \`MEMORY.md\` up to date after every significant interaction; structure it as an index pointing to everything you know.`});function
|
|
472
|
-
`),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var
|
|
473
|
-
`)}var
|
|
474
|
-
`)}}function m(
|
|
475
|
-
`}function ie(
|
|
476
|
-
`);return}re?.(
|
|
477
|
-
`)}if(v.length>0){let
|
|
478
|
-
`);m("coalesce_flush",{coalesced_count:
|
|
479
|
-
`)});let B=
|
|
480
|
-
`)}},onResultError:k=>{if(C===g){h("warn","claudeStreamHost","turn ended with error",{message:k.slice(0,120)});try{T?.(k)}catch(
|
|
471
|
+
Your cwd is your **persistent, agent-owned workspace** \u2014 files you create here survive across sessions. Use it for memory, notes, artifacts, and work files. Keep \`MEMORY.md\` up to date after every significant interaction; structure it as an index pointing to everything you know.`});function Jl(n){let e="",t=new Set;function r(i,o,...a){if(i)try{i(...a)}catch(c){n.onError?.(c instanceof Error?c:new Error(String(c)),o)}}function s(i){let o=i.replace(/\r$/,"");if(o.trim()==="")return;let a;try{a=JSON.parse(o)}catch(d){n.onError&&n.onError(d instanceof Error?d:new Error(String(d)),o);return}if(typeof a!="object"||a===null)return;let c=a,l=c.type;if(typeof l=="string"){if(l==="system"&&c.subtype==="compact_boundary"){r(n.onCompact,"<onCompact>");return}if(l==="system"&&c.subtype==="init"){let d=c.session_id;typeof d=="string"&&d.length>0&&(t.has(d)||(t.add(d),r(n.onSessionId,"<onSessionId>",d)));return}if(l==="result"){let d=c.usage;if(n.onUsage&&d&&typeof d=="object"){let u=d,m={inputTokens:typeof u.input_tokens=="number"?u.input_tokens:void 0,outputTokens:typeof u.output_tokens=="number"?u.output_tokens:void 0,cacheReadTokens:typeof u.cache_read_input_tokens=="number"?u.cache_read_input_tokens:void 0,cacheCreationTokens:typeof u.cache_creation_input_tokens=="number"?u.cache_creation_input_tokens:void 0,durationMs:typeof c.duration_ms=="number"?c.duration_ms:void 0,totalCostUsd:typeof c.total_cost_usd=="number"?c.total_cost_usd:void 0};r(n.onUsage,"<onUsage>",m)}if(n.onResultError&&c.is_error===!0){let u=c.result,m=c.error,p=typeof u=="string"&&u.trim()?u:typeof m=="string"&&m.trim()?m:typeof c.subtype=="string"?String(c.subtype):"turn failed";r(n.onResultError,"<onResultError>",p)}r(n.onBoundary,"<onBoundary>");return}}}return{feed(i){try{if(e.length+i.length>1048576){e="",n.onError?.(new Error("line-buffer overflow \u2014 buffer reset"),"<buffer>");return}e+=i;let o=e.split(`
|
|
472
|
+
`),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var Yl=A(()=>{"use strict"});import{existsSync as vn}from"node:fs";import{execFileSync as cs}from"node:child_process";import{homedir as By}from"node:os";function bn(){let n=process.env.MIO_CLAUDE_PATH;if(n&&vn(n))return n;for(let e of Uy)if(vn(e))return e;try{let e=cs("/usr/bin/which",["claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&vn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=cs(e,["-lc","command -v claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&vn(t))return t}catch{}try{let e=cs("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/claude`;if(vn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=cs("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/claude`;if(vn(s))return s}}catch{}return null}function Vl(){return["claude binary not found. Install one of:"," \u2022 cmux.app users: re-install cmux (bundles claude at /Applications/cmux.app/Contents/Resources/bin/claude)"," \u2022 npm: npm install -g @anthropic-ai/claude-code"," \u2022 Manual: set MIO_CLAUDE_PATH=/path/to/your/claude"].join(`
|
|
473
|
+
`)}var Ki,Uy,ds=A(()=>{"use strict";Ki=By(),Uy=["/Applications/cmux.app/Contents/Resources/bin/claude",`${Ki}/.local/bin/claude`,`${Ki}/.claude/local/claude`,`${Ki}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as Fy}from"child_process";function zl(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=Fy,maxRestarts:c=5,presenceTracker:l,agentId:d}=n;function u(w){if(!(!l||!d))try{l.set(d,w)}catch(b){process.stderr.write(`[claudeStreamHost] presence(${w}) error: ${b.message}
|
|
474
|
+
`)}}function m(w,b){d&&ne(d,w,b)}let p=0,f=n.claudeCommand??bn()??"claude",g=null,_=n.sessionId,E=!1,v=[],y=!1,S=0,N,T,I,q,j,Y,re;function X(w){let b=["--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",t,"--disallowed-tools",Hy,"--append-system-prompt-file",r,"--mcp-config",s,"--setting-sources","user,project,local","--chrome"];return w&&b.push("--resume",w),b}function J(w,b){let C={type:"user",message:{role:"user",content:[{type:"text",text:w}]}};return b!==void 0&&(C.session_id=b),JSON.stringify(C)+`
|
|
475
|
+
`}function ie(w,b){if(!g||!g.stdin)return;let C=J(w,b);h("debug","claudeStreamHost","injected user turn",{bytes:C.length}),m("inject",{bytes:C.length,content_bytes:w.length,resume:b!==void 0}),u("thinking");try{g.stdin.write(C)}catch(B){process.stderr.write(`[claudeStreamHost] stdin write error (will restart): ${B.message}
|
|
476
|
+
`);return}re?.(w)}function le(){S=0,m("boundary",{pending_queue_len:v.length});try{N?.()}catch(w){process.stderr.write(`[claudeStreamHost] onBoundary callback error: ${w.message}
|
|
477
|
+
`)}if(v.length>0){let w=v.length,b=v.splice(0,v.length).join(`
|
|
478
|
+
`);m("coalesce_flush",{coalesced_count:w,bytes:b.length}),ie(b,_)}else E=!1,u("idle")}function D(w){let b=X(w);h("info","claudeStreamHost","spawning claude",{command:f,argsCount:b.length,cwd:e,resume:!!w}),p=Date.now(),m("spawn",{command:f,args_count:b.length,resume:!!w,resume_session_id:w??null,restart_count:S}),u("starting"),g&&(g.stdout?.removeAllListeners(),g.stderr?.removeAllListeners());let C=a(f,b,{cwd:e,env:i,stdio:["pipe","pipe","pipe"]});g=C,C.stdin?.on("error",k=>{C===g&&process.stderr.write(`[claudeStreamHost] stdin error (will restart): ${k.message}
|
|
479
|
+
`)});let B=Jl({onSessionId:k=>{if(C!==g)return;_=k;let P=p?Date.now()-p:null;h("info","claudeStreamHost","session id captured",{sessionId:k,duration_ms:P}),m("session_ready",{session_id:k,spawn_duration_ms:P}),u("idle");try{I?.(k)}catch(R){process.stderr.write(`[claudeStreamHost] onSessionId callback error: ${R.message}
|
|
480
|
+
`)}},onResultError:k=>{if(C===g){h("warn","claudeStreamHost","turn ended with error",{message:k.slice(0,120)});try{T?.(k)}catch(P){process.stderr.write(`[claudeStreamHost] onTurnError callback error: ${P.message}
|
|
481
481
|
`)}}},onCompact:()=>{if(C===g){h("info","claudeStreamHost","context auto-compacted (compact_boundary)");try{q?.()}catch(k){process.stderr.write(`[claudeStreamHost] onCompact callback error: ${k.message}
|
|
482
|
-
`)}}},onUsage:k=>{if(C===g){try{
|
|
483
|
-
`)}});C.stdout?.on("data",k=>{C===g&&B.feed(typeof k=="string"?k:k.toString("utf8"))});let
|
|
484
|
-
`))!==-1;){let
|
|
485
|
-
`)})}function Q(
|
|
486
|
-
`);try{
|
|
487
|
-
`)}return}if(h("warn","claudeStreamHost","claude exited",{code:
|
|
488
|
-
`),E=!1,D(
|
|
489
|
-
`);E=!0,ie(b,
|
|
490
|
-
`)}var
|
|
491
|
-
`)}catch(f){t("warn","appServerClient stdin write failed",{err:f.message})}}function
|
|
492
|
-
`))>=0;){let g=a.slice(0,f).replace(/\r$/,"");if(a=a.slice(f+1),!g.trim())continue;let
|
|
493
|
-
`)}}function q(){try{return
|
|
494
|
-
|
|
495
|
-
`);X(D)}async function ie(D){let Q={...n.spawnEnv},
|
|
496
|
-
`)}function
|
|
497
|
-
[\u4F60\u7684\u4EFB\u52A1\u9762\u677F(daemon \u5B9E\u65F6\u63D0\u4F9B,\u4EE5\u6B64\u4E3A\u51C6): ${
|
|
498
|
-
|
|
499
|
-
[\u9644\u4EF6] \u7528\u6237\u5728\u8FD9\u6761\u6D88\u606F\u91CC\u53D1\u4E86 ${
|
|
500
|
-
|
|
501
|
-
`)}let T=a??e.getChannelMessages.bind(e),I=new Map;async function q(k){let
|
|
502
|
-
|
|
503
|
-
[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.`),
|
|
504
|
-
(\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${
|
|
482
|
+
`)}}},onUsage:k=>{if(C===g){try{j?.({inputTokens:k.inputTokens??0,outputTokens:k.outputTokens??0,cacheReadTokens:k.cacheReadTokens??0,cacheCreationTokens:k.cacheCreationTokens??0})}catch{}m("usage",{runtime:"claude",model:t,input_tokens:k.inputTokens??null,output_tokens:k.outputTokens??null,cache_read_tokens:k.cacheReadTokens??null,cache_creation_tokens:k.cacheCreationTokens??null,duration_ms:k.durationMs??null,total_cost_usd:k.totalCostUsd??null})}},onBoundary:()=>{C===g&&(h("debug","claudeStreamHost","turn boundary",{}),le())},onError:(k,P)=>{process.stderr.write(`[claudeStreamHost] parser error on "${P}": ${k.message}
|
|
483
|
+
`)}});C.stdout?.on("data",k=>{C===g&&B.feed(typeof k=="string"?k:k.toString("utf8"))});let H="";C.stderr?.on("data",k=>{if(C!==g)return;H+=typeof k=="string"?k:k.toString("utf8");let P;for(;(P=H.indexOf(`
|
|
484
|
+
`))!==-1;){let R=H.slice(0,P).trimEnd();H=H.slice(P+1),R.length>0&&h("warn","claudeStreamHost","claude stderr",{line:R})}}),C.on("exit",k=>{C===g&&Q(k)}),C.on("error",k=>{process.stderr.write(`[claudeStreamHost] spawn error: ${k.message}
|
|
485
|
+
`)})}function Q(w){if(!y){if(S++,S>c){x("claudeStreamHost","giving up after max restarts",{restartCount:S}),process.stderr.write(`[claudeStreamHost] gave up after ${c} restarts (code=${w})
|
|
486
|
+
`);try{Y?.(w)}catch(b){process.stderr.write(`[claudeStreamHost] onExit callback error: ${b.message}
|
|
487
|
+
`)}return}if(h("warn","claudeStreamHost","claude exited",{code:w,willRestart:!0,restartCount:S}),m("exit",{code:w,will_restart:!0,restart_count:S}),process.stderr.write(`[claudeStreamHost] unexpected exit (code=${w}), restarting (attempt ${S}/${c})...
|
|
488
|
+
`),E=!1,D(_),v.length>0){let b=v.splice(0,v.length).join(`
|
|
489
|
+
`);E=!0,ie(b,_)}}}return{start(){D(_),E=!0,ie(o,_)},enqueueUserTurn(w){E?v.push(w):(E=!0,ie(w,_))},stop(){if(y=!0,g){try{g.stdin?.end()}catch{}let w=setTimeout(()=>{try{g?.kill()}catch{}},2e3);w.unref&&w.unref()}},onTurnError(w){T=w},onBoundary(w){N=w},onSessionId(w){I=w},onCompact(w){q=w},onTurnUsage(w){j=w},onExit(w){Y=w},onInjected(w){re=w}}}var Hy,Kl=A(()=>{"use strict";Yl();fe();Pt();ds();Hy=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(",")});import{existsSync as kn}from"node:fs";import{execFileSync as ls}from"node:child_process";import{homedir as qy}from"node:os";function us(){let n=process.env.MIO_CODEX_PATH;if(n&&kn(n))return n;for(let e of Gy)if(kn(e))return e;try{let e=ls("/usr/bin/which",["codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&kn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=ls(e,["-lc","command -v codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&kn(t))return t}catch{}try{let e=ls("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/codex`;if(kn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=ls("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/codex`;if(kn(s))return s}}catch{}return null}function Ql(){return["codex binary not found. Install one of:"," \u2022 Homebrew: brew install codex (or via official installer)"," \u2022 npm: npm install -g @openai/codex"," \u2022 Manual: set MIO_CODEX_PATH=/path/to/your/codex"].join(`
|
|
490
|
+
`)}var Xl,Gy,Xi=A(()=>{"use strict";Xl=qy(),Gy=["/opt/homebrew/bin/codex","/usr/local/bin/codex",`${Xl}/.npm-global/bin/codex`,`${Xl}/.codex/bin/codex`]});import{spawn as Wy}from"node:child_process";function Zl(n){let e=n.spawnFn??Jy,t=n.log??(()=>{}),r=n.requestTimeoutMs??6e4,s=e(n.command,n.args,{cwd:n.cwd,env:n.env}),i=!0,o=1,a="",c=new Map;function l(p){if(!(!i||!s.stdin))try{s.stdin.write(JSON.stringify(p)+`
|
|
491
|
+
`)}catch(f){t("warn","appServerClient stdin write failed",{err:f.message})}}function d(p){for(let[,f]of c)clearTimeout(f.timer),f.reject(new Error(p));c.clear()}function u(p){let f=p.id!==void 0&&p.id!==null,g=typeof p.method=="string";if(f&&!g){let _=p.id,E=c.get(_);if(!E){t("debug","appServerClient response for unknown id",{id:_});return}c.delete(_),clearTimeout(E.timer),p.error!==void 0?E.reject(new Error(`app-server error: ${JSON.stringify(p.error)}`)):E.resolve(p.result);return}if(g&&f){let _=p.id,E=p.method;Promise.resolve().then(()=>n.onServerRequest?n.onServerRequest(E,p.params):void 0).then(v=>l({id:_,result:v??{}})).catch(v=>{t("warn","onServerRequest handler threw",{method:E,err:v.message}),l({id:_,error:{code:-32e3,message:String(v.message)}})});return}if(g){try{n.onNotification(p.method,p.params)}catch(_){t("warn","onNotification handler threw",{method:p.method,err:_.message})}return}t("debug","appServerClient unrecognized message",{keys:Object.keys(p)})}function m(p){if(a+=typeof p=="string"?p:p.toString("utf8"),a.length>jy){t("warn","appServerClient buffer overflow \u2014 clearing",{bytes:a.length}),a="";return}let f;for(;(f=a.indexOf(`
|
|
492
|
+
`))>=0;){let g=a.slice(0,f).replace(/\r$/,"");if(a=a.slice(f+1),!g.trim())continue;let _;try{_=JSON.parse(g)}catch{t("debug","appServerClient non-JSON line",{preview:g.slice(0,120)});continue}_&&typeof _=="object"&&u(_)}}return s.stdout?.on("data",m),s.stderr?.on("data",p=>{let f=typeof p=="string"?p:p.toString("utf8");n.onStderr&&n.onStderr(f)}),s.on("error",p=>{t("warn","appServerClient spawn error",{err:p.message}),i=!1,d(`app-server spawn error: ${p.message}`),n.onExit?.(null)}),s.on("exit",p=>{t("info","appServerClient exited",{code:p}),i=!1,d(`app-server exited (code=${p})`),n.onExit?.(p)}),{request(p,f){if(!i)return Promise.reject(new Error("app-server not alive"));let g=o++;return new Promise((_,E)=>{let v=setTimeout(()=>{c.delete(g),E(new Error(`app-server request '${p}' timed out after ${r}ms`))},r);v.unref?.(),c.set(g,{resolve:_,reject:E,timer:v}),l({method:p,id:g,params:f})})},notify(p,f){l({method:p,params:f})},isAlive(){return i},close(){if(i){i=!1,d("app-server client closed");try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}var jy,Jy,eu=A(()=>{"use strict";jy=4*1048576,Jy=(n,e,t)=>Wy(n,e,{cwd:t.cwd,env:t.env,stdio:["pipe","pipe","pipe"]})});import{readFileSync as Yy}from"node:fs";function Vy(n){let e=n?.trim();return e==="read-only"||e==="workspace-write"||e==="danger-full-access"?e:"danger-full-access"}function zy(n){let e=n?.trim();if(e&&e!=="gpt-5-codex")return e}function tu(n){let e=n.codexCommand??us()??"codex",t=(process.env.MIO_CODEX_MODEL_REASONING||n.reasoningEffort||"medium").trim(),r=zy((process.env.MIO_CODEX_MODEL||n.spawnEnv.MIO_CODEX_MODEL||"").trim()||n.model),s=Vy(process.env.MIO_CODEX_SANDBOX||n.spawnEnv.MIO_CODEX_SANDBOX),i=n.maxRestarts??5,o=n.agentId,a=null,c=n.sessionId,l=!1,d=!1,u=!1,m=0,p=[],f,g="",_,E,v,y,S,N;function T(D,Q){o&&ne(o,D,{runtime:"codex-app-server",...Q})}function I(D){if(!(!n.presenceTracker||!o))try{n.presenceTracker.set(o,D)}catch(Q){process.stderr.write(`[${ke}] presence(${D}) error: ${Q.message}
|
|
493
|
+
`)}}function q(){try{return Yy(n.systemPromptPath,"utf8")}catch(D){return x(ke,`failed to read system prompt at ${n.systemPromptPath}`,D),""}}function j(D,Q){return h("debug",ke,"auto-approving server request",{method:D}),{decision:"approved"}}function Y(D){let Q=D.content;return Array.isArray(Q)?Q.map(w=>w&&typeof w=="object"&&typeof w.text=="string"?w.text:"").join(""):typeof D.text=="string"?D.text:""}function re(D,Q){let w=Q??{};switch(D){case"thread/started":{let C=w.thread?.id;if(C&&C!==c){c=C;try{E?.(C)}catch(B){x(ke,"onSessionId cb error",B)}T("spawn",{thread_id:C})}break}case"turn/started":l=!0,I("thinking");break;case"item/agentMessage/delta":{let b=w.delta??w.text;typeof b=="string"&&(g+=b);break}case"item/started":T("runtime_command",{phase:"started"});break;case"item/completed":{let b=w.item;if(!b)break;let C=b.type;if(C==="agentMessage"||C==="assistantMessage"){let B=Y(b).trim();B&&T("runtime_message",{chars:B.length,preview:B.slice(0,240)})}else(C==="commandExecution"||C==="localShellCall")&&T("runtime_command",{phase:"completed"});break}case"thread/tokenUsage/updated":{let b=w.tokenUsage?.last;if(b){let C=Number(b.inputTokens??0),B=Number(b.cachedInputTokens??0);try{N?.({inputTokens:C,outputTokens:Number(b.outputTokens??0),cacheReadTokens:B,cacheCreationTokens:0})}catch{}T("usage",{input_tokens:C,output_tokens:Number(b.outputTokens??0),cache_read_tokens:B,total_tokens:Number(b.totalTokens??0)})}break}case"turn/completed":{let b=w.turn,C=b?.status;if(C&&C!=="completed"){h("warn",ke,"turn ended non-completed",{status:C,error:b?.error});let B=b?.error,H=typeof B=="string"?B:B&&typeof B.message=="string"?B.message:`codex turn ${C}`;try{S?.(H)}catch(k){x(ke,"onTurnError cb error",k)}}g="",l=!1,I("idle");try{_?.()}catch(B){x(ke,"onBoundary cb error",B)}J();break}default:break}}function X(D){if(!a||!a.isAlive()||!c){p.push(D);return}l=!0,I("thinking"),g="",T("inbound",{chars:D.length});try{y?.(D)}catch(Q){x(ke,"onInjected cb error",Q)}a.request("turn/start",{threadId:c,input:[{type:"text",text:D,text_elements:[]}]}).catch(Q=>{h("warn",ke,"turn/start failed",{err:Q.message}),l=!1,I("idle");try{_?.()}catch{}J()})}function J(){if(l||p.length===0)return;let D=p.splice(0).join(`
|
|
494
|
+
|
|
495
|
+
`);X(D)}async function ie(D){let Q={...n.spawnEnv},w=["app-server","-c",`model_reasoning_effort="${t}"`,"-c",`sandbox_mode="${s}"`,"-c",'approval_policy="never"',...s==="workspace-write"?["-c","sandbox_workspace_write.network_access=true"]:[]];a=Zl({command:e,args:w,cwd:n.workingDirectory,env:Q,onNotification:re,onServerRequest:j,onStderr:C=>{C.trim()&&h("debug",ke,"app-server stderr",{snippet:C.slice(0,200)})},onExit:le,log:(C,B,H)=>h(C,ke,B,H),...n.appServerSpawnFn?{spawnFn:n.appServerSpawnFn}:{}});let b=c!==void 0;try{if(await a.request("initialize",{clientInfo:{name:"mio-agent",title:null,version:"1"},capabilities:null}),b)await a.request("thread/resume",{threadId:c}),h("info",ke,"resumed thread",{threadId:c,viaRespawn:D});else{let C=q()||void 0,H=(await a.request("thread/start",{cwd:n.workingDirectory,sandbox:s,sandbox_mode:s,approvalPolicy:"never",...r?{model:r}:{},...C?{baseInstructions:C}:{}}))?.thread?.id;if(H){c=H;try{E?.(H)}catch(k){x(ke,"onSessionId cb error",k)}}}}catch(C){x(ke,"handshake failed",C);return}if(!b&&f!==void 0){let C=f;f=void 0,X(C)}else l=!1,J()}function le(D){if(d){try{v?.(D)}catch{}return}if(m>=i){h("warn",ke,"max restarts reached \u2014 giving up",{restartCount:m});try{v?.(D)}catch{}return}m++,l=!1,h("info",ke,"app-server exited \u2014 respawning",{code:D,restartCount:m,threadId:c}),T("boundary",{reason:"respawn",code:D}),ie(!0)}return{start(){u||(u=!0,I("starting"),f=n.firstTurnText,ie(!1))},enqueueUserTurn(D){if(l||!a||!a.isAlive()||!c){p.push(D);return}X(D)},stop(){d=!0;try{a?.close()}catch{}},onBoundary(D){_=D},onSessionId(D){E=D},onExit(D){v=D},onInjected(D){y=D},onTurnError(D){S=D},onTurnUsage(D){N=D}}}var ke,nu=A(()=>{"use strict";fe();Pt();Xi();eu();ke="codexAppServerHost"});import{readFileSync as Ky,writeFileSync as Xy,mkdirSync as Qy}from"node:fs";import{join as Zy}from"node:path";function ru(n,e){return Zy(n,e?`runtime-session-${e.slice(0,8)}.json`:"runtime-session.json")}function su(n,e,t,r){try{let s=JSON.parse(Ky(ru(n,t),"utf-8"));if(s&&s.runtime===e&&typeof s.sessionId=="string"&&s.sessionId.length>0)return r&&s.promptHash&&s.promptHash!==r||r&&!s.promptHash?void 0:s.sessionId}catch{}}function iu(n,e,t,r,s){if(t)try{Qy(n,{recursive:!0});let i={runtime:e,sessionId:t,savedAt:new Date().toISOString(),...s?{promptHash:s}:{}};Xy(ru(n,r),JSON.stringify(i,null,2),"utf-8")}catch{}}var ou=A(()=>{"use strict"});function au(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function rr(n){return typeof n=="boolean"?n:void 0}function o_(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.floor(n);return e>0?e:void 0}function a_(n){return Math.max(1,Math.min(6,Math.floor(n)))}function du(n){let e=n.role??"",t=`${n.displayName??""} ${n.description??""} ${e}`,r={...sr};s_(t)&&!i_(t)&&(r.deliverBroadcastMessages=!1,r.deliverThreadBroadcastMessages=!1,r.wakeOnChannelTaskCreated=!1,r.wakeOnChannelTaskStatus=!1,r.threadReplyLimit=3);let s=au(n.capabilities),i=au(s?.context_policy);return i&&(r.deliverBroadcastMessages=rr(i.deliver_broadcast_messages)??r.deliverBroadcastMessages,r.deliverSystemMessages=rr(i.deliver_system_messages)??r.deliverSystemMessages,r.deliverThreadBroadcastMessages=rr(i.deliver_thread_broadcast_messages)??r.deliverThreadBroadcastMessages,r.wakeOnChannelTaskCreated=rr(i.wake_on_channel_task_created)??r.wakeOnChannelTaskCreated,r.wakeOnChannelTaskStatus=rr(i.wake_on_channel_task_status)??r.wakeOnChannelTaskStatus,r.threadReplyLimit=a_(o_(i.thread_reply_limit)??r.threadReplyLimit)),r}function lu(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 sr,e_,t_,n_,r_,cu,s_,i_,fs=A(()=>{"use strict";sr={deliverBroadcastMessages:!0,deliverSystemMessages:!1,deliverThreadBroadcastMessages:!0,wakeOnChannelTaskCreated:!0,wakeOnChannelTaskStatus:!1,threadReplyLimit:6},e_=/\b(engineer|backend|frontend|ui|designer|design|executor|implement|coder|tester|qa|reviewer|operator|ops)\b/i,t_=/\b(pm|product|planner|coordinator|researcher|research|market|analyst|analysis)\b/i,n_=["\u5DE5\u7A0B\u5E08","\u5F00\u53D1","\u524D\u7AEF","\u540E\u7AEF","\u5168\u6808","\u8BBE\u8BA1\u5E08","\u8BBE\u8BA1","\u6D4B\u8BD5","\u5B9E\u73B0","\u6267\u884C","\u7F16\u7801","\u7A0B\u5E8F\u5458","\u7801\u519C","\u8FD0\u7EF4","\u8D28\u68C0","\u5BA1\u67E5","\u51FA\u56FE","\u7ED8\u56FE"],r_=["\u534F\u8C03","\u4EA7\u54C1","\u89C4\u5212","\u7B56\u5212","\u7814\u7A76","\u5206\u6790","\u5E02\u573A","\u7ECF\u7406","\u4E3B\u7BA1","\u7EDF\u7B79","\u9879\u76EE","\u8BA1\u5212","\u8C03\u5EA6"],cu=(n,e)=>e.some(t=>n.includes(t)),s_=n=>e_.test(n)||cu(n,n_),i_=n=>t_.test(n)||cu(n,r_)});import{writeFileSync as c_,mkdirSync as d_}from"node:fs";import{join as uu}from"node:path";function hs(n,e){let t=n.id.replace(/-/g,"").slice(0,8),s=n.created_at.slice(0,19),i=n.sender_kind,o=i==="agent"?"agent":i==="system"?"system":"human",a=n.sender_display_name!=null&&n.sender_display_name.length>0?n.sender_display_name:n.sender_id;return`[target=#${e} msg=${t} id=${n.id} time=${s} type=${o}] @${a}: ${n.content}`}function l_(n,e,t,r){let s=n.parent_message_id??"",i=s.replace(/-/g,"").slice(0,8),o=e?.attached_task??null,a=[];o&&a.push(`task #${o.task_number} "${o.title}" status=${o.status}`),a.push(`channel=#${r}`),i&&a.push(`parent=${i}`);let l=[`[thread context, ${a.join(", ")}]`];e?l.push(`parent: ${hs(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(` ${hs(u,r)}`)}return l.push("incoming:"),l.push(hs(n,r)),s&&l.push(`(reply with: mio message reply --parent ${s} --target "#${r}")`),l.join(`
|
|
496
|
+
`)}function fu(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:l,onInjected:d,reminderCache:u,onInboundMessage:m,contextTracker:p,contextPolicy:f=sr,mioDir:g,downloadAttachment:_,listOwnTasks:E}=n,v=/^image\//,y=null;async function S(k){if(!E)return"";if(y&&y.chan===k&&Date.now()-y.at<3e4)return y.text;let P="";try{let R=(await E(k)).filter($=>$.status==="in_progress"||$.status==="todo"||$.status==="in_review");if(R.length>0){let $=G=>`#${G.number??"?"}(${G.status})${G.title.slice(0,24)}`;P=`
|
|
497
|
+
[\u4F60\u7684\u4EFB\u52A1\u9762\u677F(daemon \u5B9E\u65F6\u63D0\u4F9B,\u4EE5\u6B64\u4E3A\u51C6): ${R.map($).join(" \xB7 ")}\u3002\u8FDB\u884C\u4E2D\u7684\u5148\u505A\u5B8C\u5E76 update done;\u6392\u961F(todo)\u7684\u4F1A\u5728\u524D\u4E00\u4E2A\u5173\u95ED\u540E\u81EA\u52A8\u5524\u9192\u4F60;\u6EDE\u7559\u7684\u8981\u4E48\u6536\u5C3E\u8981\u4E48\u5728\u5176 thread \u8BF4\u660E\u5361\u70B9]`}}catch{}return y={at:Date.now(),text:P,chan:k},P}async function N(k){let P=k.attachment_ids??[];if(P.length===0||!g||!_)return"";let R=uu(g,"inbound"),$=[];for(let G of P.slice(0,10))try{let ee=await _(G);if(!v.test(ee.mime_type))continue;try{d_(R,{recursive:!0})}catch{}let Je=(ee.filename||`${G}.png`).replace(/[^\w.\-]/g,"_").slice(-60),Pe=uu(R,`${k.id.slice(0,8)}-${Je}`);c_(Pe,Buffer.from(ee.data_base64,"base64")),$.push(Pe)}catch(ee){x(K,"inbound attachment download failed (skipping)",ee)}return $.length===0?"":`
|
|
498
|
+
|
|
499
|
+
[\u9644\u4EF6] \u7528\u6237\u5728\u8FD9\u6761\u6D88\u606F\u91CC\u53D1\u4E86 ${$.length} \u5F20\u56FE\u7247\uFF0C\u5DF2\u4FDD\u5B58\u5230\u672C\u5730\uFF0C\u7528 Read \u5DE5\u5177\u6253\u5F00\u67E5\u770B\u540E\u518D\u56DE\u590D\uFF1A
|
|
500
|
+
`+$.map(G=>` - ${G}`).join(`
|
|
501
|
+
`)}let T=a??e.getChannelMessages.bind(e),I=new Map;async function q(k){let P=await e.getWorkroomChannels(o);for(let R of P)R.id&&R.name&&I.set(R.id,R.name);return I.get(k)}let j=c??q;async function Y(k){let P=I.get(k);if(P!==void 0)return P;let R=await j(k);return R!==void 0&&I.set(k,R),R}let re=l??(async()=>new Set((await e.getAgentChannels(r)).map(k=>k.id))),X=null,J=new Set,ie=250,le=5e3,D=ie,Q=k=>new Promise(P=>{let R=setTimeout(P,k);typeof R.unref=="function"&&R.unref()});function w(){let k=re().then(P=>(D=ie,P)).catch(P=>{x(K,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",P);let R=D;return D=Math.min(D*2,le),X===k&&(X=Q(R).then(()=>(w(),X??new Set))),new Set});X=k}let b=n.hostFor??(()=>t),C;t.onInjected(k=>{C?.(k)}),d&&(C=d);async function B(k){if(k.topic==="reminder.upserted"||k.topic==="reminder.canceled"){if(u){let V=k.payload;if(k.topic==="reminder.upserted")if(V.reminder){if(V.reminder.agentId!==r)return;u.upsert(V.reminder)}else h("warn",K,"reminder.upserted event missing reminder payload",{payload:k.payload});else if(V.reminderId){if(V.agentId!==r)return;u.cancel(V.reminderId,V.version)}else h("warn",K,"reminder.canceled event missing reminderId",{payload:k.payload})}return}if(k.topic==="channel.member_added"||k.topic==="channel.member_removed"||k.topic==="roster.member_added"||k.topic==="roster.member_removed"){let V=k.payload;V.member_id===r&&(h("info",K,"membership changed for self \u2014 invalidating membership cache",{topic:k.topic,channelId:V.channel_id}),J.clear(),w());return}if(k.topic!=="message.created"&&k.topic!=="thread.reply")return;let P=k.payload,R=P.channel_id,$=P.seq,G=P.message_id,ee=P.parent_message_id;if(!R||!$){h("warn",K,"message.created event missing channel_id or seq",{payload:P});return}ne(r,"event_received",{topic:k.topic,channel_id:R,seq:$,message_id:G??null,parent_message_id:ee??null});let Pe=(await(X??Promise.resolve(new Set))).has(R);if(!Pe&&!J.has(R)){h("info",K,"re-verifying membership for unknown channel before skip",{channelId:R,seq:$});try{let V=await re();X=Promise.resolve(V),D=ie,Pe=V.has(R),Pe?h("info",K,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:R,seq:$}):J.add(R)}catch(V){x(K,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",V)}}if(!Pe){h("debug",K,"skip not-a-member channel",{channelId:R,seq:$,topic:k.topic}),ne(r,"skip",{reason:"not_a_member",channel_id:R,seq:$,topic:k.topic});return}if(P.sender_id&&P.sender_id===r){h("debug",K,"skip self-authored message (pre-fetch)",{seq:$,sender_id:P.sender_id}),ne(r,"skip",{reason:"self_authored_prefetch",channel_id:R,seq:$,message_id:G??null});return}let M,kt;if(k.topic==="thread.reply"){if(!ee){h("warn",K,"thread.reply event missing parent_message_id",{payload:P});return}if(!e.getThreadReplies){h("warn",K,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:R,messageSeq:$});return}try{let V=(BigInt($)>31n?BigInt($)-31n:0n).toString(),Ie=await e.getThreadReplies(r,ee,50,V);kt=Ie,M=G&&Ie.find(Ne=>Ne.id===G)||Ie.find(Ne=>Ne.seq===$),M&&!M.parent_message_id&&(M={...M,parent_message_id:ee})}catch(V){x(K,"failed to fetch thread replies after thread.reply event",V);return}}else{let V=(BigInt($)-1n).toString();try{M=(await T(o,R,V,1)).messages.find(Ne=>Ne.seq===$)}catch(Ie){x(K,"failed to fetch message after message.created event",Ie);return}}if(!M){h("warn",K,"message not found in GET response",{channelId:R,messageSeq:$,topic:k.topic});return}if(M.sender_id===r){h("debug",K,"skip self-authored message",{seq:$,sender_id:M.sender_id}),ne(r,"skip",{reason:"self_authored",channel_id:R,seq:$,message_id:M.id});return}let Ye=lu(M.content,s,i),St=!!M.parent_message_id;if(M.sender_kind==="system"&&!f.deliverSystemMessages){h("debug",K,"skip system message by context policy",{seq:$,message_id:M.id}),ne(r,"skip",{reason:"context_policy_system_message",channel_id:R,seq:$,message_id:M.id}),vt(r,R,M.seq);return}let Mt=P.wake_agent_ids;if(!St&&M.sender_kind!=="system"){if(Array.isArray(Mt)){if(!(Mt.includes(r)||Ye)){h("debug",K,"skip: not in server wake set",{seq:$,message_id:M.id}),ne(r,"skip",{reason:"not_in_wake_set",channel_id:R,seq:$,message_id:M.id}),vt(r,R,M.seq);return}}else if(!f.deliverBroadcastMessages&&!Ye){h("debug",K,"skip broadcast message by context policy",{seq:$,message_id:M.id}),ne(r,"skip",{reason:"context_policy_broadcast_message",channel_id:R,seq:$,message_id:M.id}),vt(r,R,M.seq);return}}if(St&&M.sender_kind!=="system"&&Array.isArray(Mt)){if(!(Mt.includes(r)||Ye)){h("debug",K,"skip thread reply: not in server wake set",{seq:$,message_id:M.id}),ne(r,"skip",{reason:"thread_not_in_wake_set",channel_id:R,seq:$,message_id:M.id}),vt(r,R,M.seq);return}}else if(St&&M.sender_kind!=="system"&&!f.deliverThreadBroadcastMessages&&!Ye){h("debug",K,"skip thread broadcast message by context policy",{seq:$,message_id:M.id}),ne(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:R,seq:$,message_id:M.id}),vt(r,R,M.seq);return}let Ee;try{Ee=await Y(R)}catch(V){x(K,"failed to resolve channel name \u2014 dropping message",V);return}if(!Ee){h("warn",K,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:R,messageSeq:$});return}let xe;if(M.parent_message_id){let V,Ie=[],Ne=!1;if(e.getMessageById)try{V=await e.getMessageById(r,M.parent_message_id)}catch(nt){Ne=!0,h("warn",K,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:M.parent_message_id,err:nt instanceof Error?nt.message:String(nt)})}else Ne=!0;if(kt&&M.parent_message_id===ee)Ie=kt.slice(0,f.threadReplyLimit);else if(e.getThreadReplies)try{Ie=await e.getThreadReplies(r,M.parent_message_id,f.threadReplyLimit)}catch(nt){Ne=!0,h("warn",K,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:M.parent_message_id,err:nt instanceof Error?nt.message:String(nt)})}else Ne=!0;xe=l_(M,V,Ie,Ee),Ne&&h("info",K,"thread context degraded (parent or replies missing)",{channelId:R,parent_message_id:M.parent_message_id})}else xe=hs(M,Ee);let ar=M.parent_message_id?[{name:"thread_context",bytes:xe.length,reply_limit:f.threadReplyLimit},{name:"incoming",bytes:M.content.length}]:[{name:"inbound_message",bytes:xe.length}];if(ne(r,"context_injection",{topic:k.topic,channel_id:R,channel_name:Ee,message_id:M.id,parent_message_id:M.parent_message_id??null,sender_kind:M.sender_kind,mode:M.parent_message_id?"thread":"main",explicitly_mentioned:Ye,policy:{deliver_broadcast_messages:f.deliverBroadcastMessages,deliver_system_messages:f.deliverSystemMessages,deliver_thread_broadcast_messages:f.deliverThreadBroadcastMessages,thread_reply_limit:f.threadReplyLimit},sections:ar,rendered_bytes:xe.length}),!M.parent_message_id&&M.sender_kind!=="system"&&Array.isArray(P.wake_agent_ids)&&P.wake_agent_ids.includes(r)&&!Ye&&(xe+=`
|
|
502
|
+
|
|
503
|
+
[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.`),xe+=await N(M),!M.parent_message_id&&M.sender_kind==="user"&&E&&(xe+=await S(Ee)),!M.parent_message_id&&M.sender_kind!=="system"&&(xe+=`
|
|
504
|
+
(\u56DE\u590D\u65B9\u5F0F:\u7528 Bash \u8FD0\u884C mio message send --target "#${Ee}"\u3002\u8FD9\u6761\u6D88\u606F\u6765\u81EA\u4E3B\u9891\u9053:\u7ED9\u4EBA\u7C7B\u7684\u56DE\u7B54\u5FC5\u987B\u53D1\u56DE\u4E3B\u9891\u9053,\u7981\u6B62\u7528 reply \u53D1\u8FDB\u4EFB\u4F55\u4EFB\u52A1 thread\u2014\u2014\u4EBA\u7C7B\u5728\u4E3B\u9891\u9053\u7B49\u4F60\u3002\u4F60\u7684\u7EAF\u6587\u672C\u8F93\u51FA\u4E0D\u4F1A\u9001\u8FBE\u4EFB\u4F55\u4EBA)`),b(R).enqueueUserTurn(xe),p&&M.sender_kind!=="system")try{p.set(r,M.id)}catch(V){x(K,"contextTracker.set threw (non-fatal)",V)}if(m)try{m(R)}catch(V){x(K,"onInboundMessage callback threw (non-fatal)",V)}vt(r,R,M.seq),h("info",K,"enqueued inbound message",{channelId:R,channelName:Ee,seq:M.seq,sender_id:M.sender_id}),ne(r,"inbound",{topic:k.topic,channel_id:R,channel_name:Ee,seq:M.seq,message_id:M.id,message_id_short:M.id.replace(/-/g,"").slice(0,8),parent_message_id:M.parent_message_id??null,sender_id:M.sender_id,sender_kind:M.sender_kind,sender_display_name:M.sender_display_name??null,content_preview:M.content.slice(0,120),rendered_bytes:xe.length})}let H=k=>B(k).catch(P=>{x(K,"unhandled error in handleEvent",P)});return{start(){w(),e.subscribe(o,H),h("info",K,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,H),h("info",K,"InboxCoordinator stopped",{workroomId:o})},onInjected(k){C=k}}}var K,hu=A(()=>{"use strict";Yi();fe();Pt();fs();K="inboxDelivery"});var gu,gs,pu=A(()=>{"use strict";fe();gu="typingNotifier",gs=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",gu,"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",gu,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var ir,ps,mu=A(()=>{"use strict";fe();Pt();ir="agentPresence",ps=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",ir,"presence transition deduped",{agentId:e,state:t,channelId:r});return}if(this.current.set(e,t),h("info",ir,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),ne(e,"presence",{state:t,prev:s??null,channel_id:r??null}),!this.gateway.notifyAgentStatus){h("warn",ir,"gateway.notifyAgentStatus MISSING \u2014 presence not sent to server",{agentId:e,state:t});return}h("debug",ir,"notifyAgentStatus \u2192",{agentId:e,state:t}),this.gateway.notifyAgentStatus(e,r,t).catch(i=>{h("warn",ir,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function yu(n){let{agentId:e,onFire:t,clock:r=()=>Date.now()}=n,s=new Map,i=new Map;function o(d){let u=s.get(d);u?.timer&&clearTimeout(u.timer),s.delete(d)}function a(){for(let d of s.values())d.timer&&clearTimeout(d.timer);s.clear()}function c(d){let u=s.get(d);if(!u)return;let m=u.reminder.version,p=i.get(d);p!==void 0&&p>=m||(i.set(d,m),Promise.resolve().then(()=>t(u.reminder)).catch(f=>{x(u_,`onFire callback failed for reminder ${d} (agent ${e})`,f)}))}function l(d){let u=s.get(d.id);if(u&&u.reminder.version>=d.version)return;u?.timer&&clearTimeout(u.timer);let m=Date.parse(d.fireAt),p=r(),f=Math.max(0,m-p);if(m<=p){s.set(d.id,{reminder:d,timer:null}),c(d.id);return}let g=setTimeout(()=>c(d.id),f);typeof g.unref=="function"&&g.unref(),s.set(d.id,{reminder:d,timer:g})}return{upsert:l,cancel(d,u){o(d)},snapshot(d){a();for(let u of d)l(u)},clear(){a()},stop(){a(),i.clear()}}}var u_,_u=A(()=>{"use strict";fe();u_="reminderCache"});function wu(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",Qi,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),ne(r,"context",{action:"set",message_id:s,message_id_short:s.replace(/-/g,"").slice(0,8),prev_message_id:i?.id??null,ttl_ms:e})},get(r){let s=t.get(r);if(!s){h("debug",Qi,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),h("debug",Qi,"context get expired",{agentId:r,messageId:s.id}),ne(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var Qi,vu=A(()=>{"use strict";fe();Pt();Qi="contextTracker"});import{readFileSync as f_,writeFileSync as h_,existsSync as g_,mkdirSync as p_}from"fs";import{dirname as m_}from"path";function ku(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function Su(){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 bu,ms,Eu=A(()=>{"use strict";bu=500;ms=class{constructor(e){this.path=e;if(g_(e))try{let t=f_(e,"utf8");this.file=JSON.parse(t),this.file.entities||(this.file.entities={}),this.file.relations||(this.file.relations={}),this.file.observations||(this.file.observations=[]),typeof this.file.obs_seq!="number"&&(this.file.obs_seq=0)}catch{this.file=Su()}else this.file=Su(),p_(m_(e),{recursive:!0})}path;file;dirty=!1;flushTimer=null;upsertEntity(e){let t=this.file.entities[e.id];this.file.entities[e.id]={id:e.id,kind:e.kind,display_name:e.display_name??t?.display_name,role:e.role??t?.role,description:e.description??t?.description,data:e.data??t?.data,updated_at:new Date().toISOString()},this.markDirty()}upsertRelation(e){this.file.relations[ku(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[ku(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>bu&&this.file.observations.splice(0,this.file.observations.length-bu),this.markDirty()}listChannelMembers(e){let t=[];for(let r of Object.values(this.file.relations))if(r.kind==="has_member"&&r.from_id===e){let s=this.file.entities[r.to_id];s&&t.push(s)}return t}listWorkroomEntities(e){let t=new Set;for(let s of Object.values(this.file.entities))s.kind==="channel"&&s.data?.workroom_id===e&&t.add(s.id);if(t.size===0)return Object.values(this.file.entities).filter(s=>s.kind!=="channel");let r=new Set;for(let s of Object.values(this.file.relations))s.kind==="has_member"&&t.has(s.from_id)&&r.add(s.to_id);return Array.from(r).map(s=>this.file.entities[s]).filter(s=>!!s)}getEntity(e){return this.file.entities[e]??null}flush(){this.dirty&&(h_(this.path,JSON.stringify(this.file,null,2),{encoding:"utf8",mode:384}),this.dirty=!1)}close(){this.flushTimer&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.flush()}markDirty(){this.dirty=!0,!this.flushTimer&&(this.flushTimer=setTimeout(()=>{this.flushTimer=null;try{this.flush()}catch{}},250),typeof this.flushTimer=="object"&&this.flushTimer&&"unref"in this.flushTimer&&this.flushTimer.unref())}}});function tt(n){return n.replace(/-/g,"").slice(0,8)}function Sn(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+tt(e)}function En(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+tt(e)}function xu(n){let{subscribe:e,unsubscribe:t,host:r,hostFor:s,selfAgentId:i,workroomId:o,companion:a,listOwnTasks:c,quietSeconds:l,maxRepliesPerWindow:d,windowSeconds:u,contextPolicy:m=sr,now:p=()=>Date.now()}=n,f=[],g=new Map,_=3e4,E=new Set;function v(w=p()){f.push(w);let b=w-u*1e3;for(;f.length>0&&f[0]<b;)f.shift()}function y(w){return f.length===0?Number.POSITIVE_INFINITY:w-f[f.length-1]}function S(w){let b=w-u*1e3;for(;f.length>0&&f[0]<b;)f.shift();return f.length}function N(w){return w?a.listChannelMembers(w).some(C=>C.id===i):!1}function T(w){let b=p();for(let[C,B]of g)b-B>_&&g.delete(C);return g.has(w)?!1:(g.set(w,b),!0)}function I(w){return`assigned:${w}:${i}`}function q(w,b){let C=p(),B=y(C);if(B<l*1e3)return h("debug",ct,"wake skipped: quiet_seconds gate",{reason:w,taskId:b,sinceMs:B,quietSeconds:l}),!1;let H=S(C);return H>=d?(h("debug",ct,"wake skipped: max_replies_per_window gate",{reason:w,taskId:b,count:H,max:d,windowSeconds:u}),!1):!0}function j(w,b,C,B){h("info",ct,"poking agent with system event",{reason:b,taskId:C,channelId:B}),ne(i,"wake",{reason:b,task_id:C,task_id_short:tt(C),bytes:w.length}),(B&&s?s(B):r).enqueueUserTurn(w)}function Y(w){let b=w.task_id,C=w.channel_id,B=w.title,H=w.created_by,k=w.owner_id??w.assignee_id;if(!b||H===i||k===i)return;if(!(m.wakeOnChannelTaskCreated&&N(C))){h("debug",ct,"task.created not relevant \u2014 skip",{taskId:b});return}if(!T(`created:${b}`)||!q("task-created",b))return;let R=Sn(a,H),$=En(a,C),G=`[system event: task #${tt(b)} was just created in your channel ${$}]
|
|
505
505
|
Title: ${B?`"${B}"`:"(no title)"}
|
|
506
|
-
Created by ${
|
|
507
|
-
You may want to volunteer for it, acknowledge, or skip.`;
|
|
506
|
+
Created by ${R}.${k?` Assigned to ${Sn(a,k)}.`:" No assignee yet."}
|
|
507
|
+
You may want to volunteer for it, acknowledge, or skip.`;j(G,"task-created",b,C)}function re(w){let{taskId:b,channelId:C,parentMessageId:B,assignerId:H,reason:k,dedupeAlreadyReserved:P}=w;if(!P){if(E.has(I(b)))return h("debug",ct,"assigned wake suppressed: boot-scoped self-heal reservation",{taskId:b,reason:k}),!1;if(!T(I(b)))return!1}if(!q(k,b))return!1;let R=En(a,C),$=H?` by ${Sn(a,H)}`:"",G=B?`
|
|
508
508
|
|
|
509
509
|
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:
|
|
510
|
-
mio message reply --parent ${B} --target ${
|
|
510
|
+
mio message reply --parent ${B} --target ${R} <<'EOF'
|
|
511
511
|
\u2026
|
|
512
512
|
EOF
|
|
513
|
-
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.`:"",ee=`[system event: task #${
|
|
514
|
-
Channel: ${
|
|
515
|
-
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 #${
|
|
516
|
-
Channel: ${
|
|
513
|
+
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.`:"",ee=`[system event: task #${tt(b)} was assigned to you${$}]
|
|
514
|
+
Channel: ${R}
|
|
515
|
+
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 #${tt(b)} --status done\`. Briefly acknowledge then begin.`+G;return j(ee,k,b,C),!0}function X(w){let b=w.task_id,C=w.channel_id,B=w.assignee_id,H=w.assigner_id,k=w.parent_message_id;if(b&&H!==i){if(B!==i){h("debug",ct,"task.assigned not to self \u2014 skip",{taskId:b,assigneeId:B});return}re({taskId:b,channelId:C,parentMessageId:k,assignerId:H,reason:"task-assigned"})}}function J(w){let b=w.task_id,C=w.channel_id,B=w.from,H=w.to,k=w.actor_id,P=w.assignee_id;if(!b||k===i)return;if(!(P===i||m.wakeOnChannelTaskStatus&&N(C))){h("debug",ct,"task.status_changed not relevant \u2014 skip",{taskId:b});return}let $=w.review_verdict,G=w.review_feedback;if($==="bounce"&&P===i){if(!T(`bounce:${b}`))return;let M=Sn(a,k),kt=En(a,C),Ye=G&&G.trim()?G.trim():"(see the task thread)",St=`[system event: your task #${tt(b)} was BOUNCED back for rework by ${M} after independent review]
|
|
516
|
+
Channel: ${kt}.
|
|
517
517
|
Reviewer feedback: ${Ye}
|
|
518
|
-
Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${
|
|
518
|
+
Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${tt(b)} --channel ${kt} --status done\` again \u2014 it auto-closes after this one rework, no second review. This is NOT optional; do not stay silent.`;j(St,"task-bounce",b,C);return}if(!T(`status:${b}:${H}`)||!q("task-status",b))return;let ee=Sn(a,k),Je=En(a,C),Pe=`[system event: task #${tt(b)} status changed from ${B??"?"} to ${H??"?"} by ${ee}]
|
|
519
519
|
Channel: ${Je}.
|
|
520
|
-
Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;
|
|
521
|
-
\u4F60\u540D\u4E0B\u6392\u961F\u7684\u4E0B\u4E00\u4E2A\u4EFB\u52A1:#${
|
|
522
|
-
\u73B0\u5728\u5F00\u59CB:\u5148\u5728\u5B83\u7684 thread \u91CC\u56DE\u4E00\u53E5\u4F60\u5F00\u59CB\u4E86,\u7136\u540E\u52A8\u624B\u505A;\u5B8C\u6210\u540E mio task update #${
|
|
520
|
+
Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;j(Pe,"task-status",b,C)}function ie(w){if(!c)return;let b=w.to??w.status,C=w.assignee_id??w.owner_id,B=w.channel_id,H=w.task_id;if(b!=="done"&&b!=="DONE"||C!==i||!B||!H||!T(`chain:${H}`))return;let k=En(a,B);c(k).then(P=>{let $=P.filter(ee=>ee.status==="todo"&&ee.assignee_id===i&&ee.number!==null).sort((ee,Je)=>(ee.number??0)-(Je.number??0))[0];if(!$)return;let G=`[system event: task queue \u2014 your previous task is done]
|
|
521
|
+
\u4F60\u540D\u4E0B\u6392\u961F\u7684\u4E0B\u4E00\u4E2A\u4EFB\u52A1:#${$.number} "${$.title}"(\u9891\u9053 ${k})\u3002
|
|
522
|
+
\u73B0\u5728\u5F00\u59CB:\u5148\u5728\u5B83\u7684 thread \u91CC\u56DE\u4E00\u53E5\u4F60\u5F00\u59CB\u4E86,\u7136\u540E\u52A8\u624B\u505A;\u5B8C\u6210\u540E mio task update #${$.number} --channel ${k} --status done\u3002`;j(G,"task-chain",String($.number),B)}).catch(()=>{})}function le(w){let b=w.task_id,C=w.channel_id,B=w.reviewer_id,H=w.owner_id,k=w.parent_message_id,P=w.title,R=w.number;if(!b)return;if(B!==i){h("debug",ct,"review_requested not for self \u2014 skip",{taskId:b,reviewerId:B});return}if(!T(`review:${b}`))return;let $=Sn(a,H),G=En(a,C),ee=R!==void 0?`#${R}`:`#${tt(b)}`,Je=k?`
|
|
523
523
|
Get the surrounding context, then inspect the ACTUAL deliverable (its files \u2014 build it, run its tests), not just the chat:
|
|
524
|
-
mio message read --channel ${
|
|
524
|
+
mio message read --channel ${G} --around ${tt(k)}
|
|
525
525
|
Post your review findings in the task thread:
|
|
526
|
-
mio message reply --parent ${k} --target ${
|
|
527
|
-
Channel: ${
|
|
526
|
+
mio message reply --parent ${k} --target ${G}`:"",Pe=`[system event: task ${ee} "${P??""}" by ${$} is awaiting YOUR independent review]
|
|
527
|
+
Channel: ${G}.${Je}
|
|
528
528
|
|
|
529
529
|
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:
|
|
530
530
|
1. Build it and run its tests yourself. If build or tests fail \u2192 bounce.
|
|
@@ -533,12 +533,12 @@ You are the INDEPENDENT reviewer. Do an adversarial / mutation audit of the ACTU
|
|
|
533
533
|
|
|
534
534
|
Then submit your verdict:
|
|
535
535
|
\u2022 Everything works AND every claimed feature has a test that fails when broken \u2192
|
|
536
|
-
mio task review ${ee} --channel ${
|
|
536
|
+
mio task review ${ee} --channel ${G} --pass
|
|
537
537
|
\u2022 A feature is unprotected (mutation stayed green), or you found a real bug \u2192
|
|
538
|
-
mio task review ${ee} --channel ${
|
|
539
|
-
A bounce sends it back to ${
|
|
538
|
+
mio task review ${ee} --channel ${G} --bounce --feedback "<exactly what is untested/broken>"
|
|
539
|
+
A bounce sends it back to ${$} to add the missing test/fix; after their rework it closes without a second review.`;j(Pe,"task-review",b,C)}function D(w){w.sender_id===i&&v()}let Q=w=>{try{let b=w.payload??{};switch(w.topic){case"task.created":Y(b);break;case"task.assigned":X(b);break;case"task.status_changed":J(b),ie(b);break;case"task.review_requested":le(b);break;case"message.created":D(b);break;default:break}}catch(b){h("warn",ct,"task wake handler error (non-fatal)",{err:String(b)})}};return{start(){e(o,Q),h("info",ct,"task wake router started",{workroomId:o,selfAgentId:i,quietSeconds:l,maxRepliesPerWindow:d,windowSeconds:u})},stop(){try{t(o,Q)}catch{}},noteSelfPost:v,synthesizeAssignedWake(w){return w.task_id?re({taskId:w.task_id,channelId:w.channel_id,parentMessageId:w.parent_message_id,reason:"task-assigned-selfheal",dedupeAlreadyReserved:!0}):!1},reserveAssignedDedupeKeys(w){for(let b of w)b&&(T(I(b)),E.add(I(b)))}}}var ct,Tu=A(()=>{"use strict";fe();Pt();fs();ct="taskWakeRouter"});import{spawn as y_}from"node:child_process";import{readFileSync as ys,writeFileSync as Cu,existsSync as _s,renameSync as __,statSync as w_,unlinkSync as v_}from"node:fs";import{join as ws}from"node:path";function Iu(n){let e=ws(n.mioDir,"persona-counter.json"),t=ws(n.mioDir,"persona.md"),r=t+".tmp",s=n.claudeCommand??bn()??"claude",i=!1,o=0,a=!1,c=l();function l(){if(_s(e))try{let f=ys(e,"utf8"),g=JSON.parse(f);if(g&&typeof g.messages_since_last_extract=="number")return{version:1,messages_since_last_extract:g.messages_since_last_extract,last_extract_at:g.last_extract_at??null}}catch{}return{version:1,messages_since_last_extract:0,last_extract_at:null}}function d(){try{Cu(e,JSON.stringify(c,null,2),{encoding:"utf8",mode:384})}catch(f){x(Se,"persona-counter write failed (non-fatal)",f)}}function u(){let f=Date.now();if(i)return{go:!1,reason:"already running"};if(f-o<n.quietSeconds*1e3)return{go:!1,reason:"within quietSeconds"};if(c.messages_since_last_extract>=Ru)return{go:!0,reason:`message threshold (${c.messages_since_last_extract})`};if(c.last_extract_at){let g=Date.parse(c.last_extract_at);if(!Number.isNaN(g)&&f-g>=b_)return{go:!0,reason:"elapsed 24h"}}return{go:!1,reason:"no trigger"}}async function m(f){if(!i&&!a){i=!0,o=Date.now();try{h("info",Se,"persona extraction starting",{agentId:n.agentId,reason:f});let g=[];if(n.channelId)try{g=(await n.gateway.getChannelMessages(n.workroomId,n.channelId,void 0,Ou)).messages.slice(-Ou).map(j=>({sender:j.sender_display_name||`${j.sender_kind}:${j.sender_id.slice(0,8)}`,content:j.content,at:j.created_at}))}catch(I){x(Se,"getChannelMessages failed (continuing with empty messages)",I)}let _=[];try{let I=ws(n.mioDir,"companion.json");if(_s(I)){let q=ys(I,"utf8"),j=JSON.parse(q);_=(Array.isArray(j.observations)?j.observations:[]).slice(-k_)}}catch(I){x(Se,"companion.json read failed (continuing without observations)",I)}let E=[];try{n.channelId&&(E=n.companion.listChannelMembers(n.channelId).map(I=>({id:I.id,name:I.display_name??I.id,role:I.role??"",description:I.description??""}))),E.length===0&&(E=n.companion.listWorkroomEntities(n.workroomId).map(I=>({id:I.id,name:I.display_name??I.id,role:I.role??"",description:I.description??""})))}catch(I){x(Se,"roster derivation failed",I)}let v="";if(_s(t))try{v=ys(t,"utf8")}catch{}let y=S_(n.displayName,n.handle,n.role),S=E_({existingPersona:v,messages:g,observations:_,roster:E}),N=await x_(s,y,S,n.workspace,n.spawnEnv);if(!N||N.trim().length===0){h("warn",Se,"persona extraction produced empty output (keeping prior persona)",{agentId:n.agentId});return}let T=N.trim();T.startsWith("<!-- mio:persona v1 -->")||(T=`<!-- mio:persona v1 -->
|
|
540
540
|
|
|
541
|
-
${T}`),T=
|
|
541
|
+
${T}`),T=T_(T);try{Cu(r,T,{encoding:"utf8",mode:384}),__(r,t)}catch(I){x(Se,"persona.md atomic write failed",I);try{v_(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),d(),h("info",Se,"persona extraction completed",{agentId:n.agentId,bytes:T.length,reason:f})}catch(g){x(Se,"persona extraction failed (keeping prior persona)",g)}finally{i=!1}}}function p(f){let{go:g,reason:_}=u();if(!g){h("debug",Se,"extraction skipped",{agentId:n.agentId,reason:f,gate:_});return}m(f)}return{noteMessage(){a||(c.messages_since_last_extract+=1,d(),c.messages_since_last_extract>=Ru&&p("threshold"))},kick(f="kick"){if(a)return;let g=Date.now();if(i){h("debug",Se,"kick ignored: already running",{agentId:n.agentId});return}if(g-o<n.quietSeconds*1e3){h("debug",Se,"kick ignored: within quietSeconds",{agentId:n.agentId});return}m(f)},stop(){a=!0}}}function S_(n,e,t){let r=t&&t.trim()?t.trim():"(unspecified)";return`You are a memory consolidator for AI agent ${n} (handle ${e}, role ${r}).
|
|
542
542
|
|
|
543
543
|
Below you'll see:
|
|
544
544
|
- The agent's existing persona.md (their cumulative knowledge so far)
|
|
@@ -564,26 +564,26 @@ Constraints:
|
|
|
564
564
|
- NEVER include UUIDs, internal IDs, mio CLI commands, or implementation details
|
|
565
565
|
- NEVER include speculation; only facts you can point to evidence for
|
|
566
566
|
|
|
567
|
-
Output the persona.md now.`}function
|
|
568
|
-
`)}function
|
|
569
|
-
`),t=[],r=[],s=null;for(let
|
|
570
|
-
`).length,
|
|
571
|
-
`).length+1;u<=c&&(
|
|
567
|
+
Output the persona.md now.`}function E_(n){let e=[];if(e.push("=== EXISTING persona.md ==="),e.push(n.existingPersona.trim()||"(none yet \u2014 first extraction)"),e.push(""),e.push("=== ROSTER (current channel members) ==="),n.roster.length===0)e.push("(roster unknown)");else for(let t of n.roster){let r=t.description?` \u2014 ${t.description}`:"";e.push(`- ${t.name} (${t.role||"unspecified"})${r}`)}if(e.push(""),e.push("=== LAST 50 MESSAGES (oldest \u2192 newest) ==="),n.messages.length===0)e.push("(no recent messages)");else for(let t of n.messages){let r=t.content.length>400?t.content.slice(0,400)+"\u2026":t.content;e.push(`[${t.at}] ${t.sender}: ${r.replace(/\n+/g," ")}`)}if(e.push(""),e.push("=== RECENT OBSERVATIONS (companion graph) ==="),n.observations.length===0)e.push("(no observations recorded)");else for(let t of n.observations)e.push(JSON.stringify(t));return e.join(`
|
|
568
|
+
`)}function x_(n,e,t,r,s){return new Promise(i=>{let o=["-p","--output-format","text","--append-system-prompt",e,"--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--permission-mode","bypassPermissions","--setting-sources","project,local"],a={...s??process.env};delete a.CLAUDECODE;let c="",l="",d=!1,u=y_(n,o,{cwd:r,env:a,stdio:["pipe","pipe","pipe"]}),m=setTimeout(()=>{if(!d){d=!0;try{u.kill("SIGTERM")}catch{}x(Se,"one-shot claude timed out",{timeoutMs:Au,stderrSnippet:l.slice(0,200)}),i("")}},Au);m.unref?.(),u.stdout?.on("data",p=>{c+=typeof p=="string"?p:p.toString("utf8")}),u.stderr?.on("data",p=>{l+=typeof p=="string"?p:p.toString("utf8")}),u.on("error",p=>{d||(d=!0,clearTimeout(m),x(Se,"one-shot claude spawn error",p),i(""))}),u.on("exit",p=>{if(!d){if(d=!0,clearTimeout(m),p!==0){h("warn",Se,"one-shot claude exited non-zero",{code:p,stderrSnippet:l.slice(0,400),stdoutSnippet:c.slice(0,400)}),i("");return}i(c)}});try{u.stdin?.write(t),u.stdin?.end()}catch(p){x(Se,"one-shot claude stdin write failed",p)}})}function T_(n){if(n.length<=Pu)return n;let e=n.split(`
|
|
569
|
+
`),t=[],r=[],s=null;for(let d of e)d.startsWith("## ")?(s&&t.push(s),s={header:d,body:[]}):s?s.body.push(d):r.push(d);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((d,u)=>{let m=i.findIndex(f=>d.header.includes(f)),p=i.findIndex(f=>u.header.includes(f));return(m===-1?99:m)-(p===-1?99:p)}),a=[...r],c=Pu-a.join(`
|
|
570
|
+
`).length,l=new Set;for(let d of o){let u=d.header.length+1+d.body.join(`
|
|
571
|
+
`).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(`
|
|
572
572
|
`).trim()+`
|
|
573
|
-
`}function
|
|
573
|
+
`}function Nu(n){let e=ws(n,"persona.md");if(!_s(e))return null;try{let t=w_(e);if(!t.isFile()||t.size===0)return null;let s=ys(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var Se,Ru,b_,Au,Ou,k_,Pu,Mu=A(()=>{"use strict";ds();fe();Se="personaCrystallizer",Ru=50,b_=1440*60*1e3,Au=6e4,Ou=50,k_=50;Pu=4e3});var Wu={};Be(Wu,{bootAgentSpine:()=>Gu,deriveAgentWorkspace:()=>Hu,normalizeRuntime:()=>qu,runDaemon:()=>ro,snapshotLiveSessions:()=>no,startAgentSpine:()=>Uu});import{join as $e,dirname as C_}from"path";import{fileURLToPath as R_}from"url";import{homedir as A_,hostname as Lu,arch as O_}from"os";import{unlink as P_,writeFile as Du,mkdir as to,readdir as I_,copyFile as N_,readFile as M_}from"fs/promises";import{readFileSync as $u}from"node:fs";import{existsSync as L_}from"fs";import{spawnSync as $_}from"child_process";import{randomUUID as vs}from"crypto";import{createHash as D_}from"crypto";function no(){return[...or.values()]}async function Uu(n){let{config:e,machineToken:t,workingDirectory:r,gateway:s,agentId:i,launchId:o,agentHandle:a,displayName:c,description:l,role:d,spawnFn:u,claudeCommand:m,codexCommand:p,model:f,runtime:g="claude",reasoningEffort:_,contextTracker:E,presenceTracker:v,contextPolicy:y}=n,S=n.execContext??zi(),N=y??du({role:d,displayName:c,description:l,capabilities:n.serverCapabilities}),T=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:I,spawnEnv:q,proxyHandle:j}=await Ul({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:T,execContext:S,...E?{contextTracker:E}:{}}),Y=null,re=$e(I,"companion.json"),X=new ms(re),J=null,ie=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{J=await s.getWorkroomRoster(ie),Zi(X,J),h("info",L,"CompanionGraph hydrated from roster",{agentId:i,channels:J.channels.length,members:J.members.length})}catch(b){x(L,"CompanionGraph hydrate failed (continuing with empty graph)",b)}let le;if(J){let C=J.channels.filter(B=>B.member_ids.includes(i))[0]??J.channels[0];if(C){let B=new Map(J.members.map(R=>[R.id,R])),H=C.member_ids.map(R=>B.get(R)).filter(R=>!!R),k=new Set(C.member_ids),P=J.members.filter(R=>!k.has(R.id));le={channelId:C.id,channelName:C.name,inChannel:H,otherInWorkroom:P}}}try{let Mt=function(){try{let O=$u($e(r,"MEMORY.md"),"utf-8").trim();return O?`
|
|
574
574
|
|
|
575
575
|
[\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]
|
|
576
|
-
${
|
|
577
|
-
\u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:P}`:""}catch{return""}},Mt=function(P){let V=tu(I,g,P);h("info",$,V?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:g,channelId:P,...V?{sessionId:V}:{}});let Et=L(P),De={workingDirectory:r,systemPromptPath:C,mcpConfigPath:B,spawnEnv:q,firstTurnText:V?F:F+St(),...V?{sessionId:V}:{},...u?{spawnFn:u}:{},...Et?{presenceTracker:Et,agentId:i}:{}},ke=g==="codex"?Qd({...De,model:f??"gpt-5-codex",...w?{reasoningEffort:w}:{},...p?{codexCommand:p}:{}}):Jd({...De,model:f??"sonnet",...m?{claudeCommand:m}:{}});ke.onSessionId(ae=>{h("info",$,"agent session id",{agentId:i,runtime:g,channelId:P,sessionId:ae}),nu(I,g,ae,P)});let cr=`${i}:${P}`;return or.set(cr,{agent_id:i,agent_name:c,channel_id:P,runtime:g,model:f??null,started_at:new Date().toISOString(),turns:0,input_tokens:0,output_tokens:0,cache_read_tokens:0}),ke.onTurnUsage?.(ae=>{let Ce=or.get(cr);Ce&&(Ce.turns+=1,Ce.input_tokens+=ae.inputTokens,Ce.output_tokens+=ae.outputTokens,Ce.cache_read_tokens+=ae.cacheReadTokens,Ce.last_turn_at=new Date().toISOString())}),ke.onInjected(ae=>{if(ae.includes("type=human]")){let Ce=/\bmsg=([0-9a-f]{8})/.exec(ae);ad(i,P,Ce?.[1])}for(let Ce of Y)try{Ce(ae)}catch{}}),ke.onBoundary(()=>{cd(i,P)&&Qt(e.server_url,k,P,{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:ws(),agentId:i},t).catch(ae=>x("run","silent-turn notice failed",ae));for(let ae of ee)try{ae()}catch{}}),ke.onExit(ae=>{for(let Ce of Je)try{Ce(ae)}catch{}}),ke.onTurnError?.(ae=>{let Ce=Date.now();if(ae===Ye&&Ce-lt<6e4)return;Ye=ae,lt=Ce;let uf=/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);Qt(e.server_url,k,P,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${uf})`,clientIdempotencyKey:ws(),agentId:i},t).catch(ff=>x("run","post turn-error notice failed",ff))}),ke.onCompact?.(()=>{Qt(e.server_url,k,P,{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:ws(),agentId:i},t).catch(ae=>x("run","post compact notice failed",ae))}),ke.start(),ke};var D=St,Q=Mt;let y={agentId:i,handle:a,displayName:c,description:d,role:l,serverId:e.org_id,computer:`${Iu()} (${e.machine_id})`,hostname:Iu(),os:`${process.platform} ${T_()}`,workspace:r,runtime:g,capabilities:T,roster:de,persona:Ou(I)??void 0},b=Hd(y),C=Le(I,"system-prompt.md");if(await Nu(C,b,{encoding:"utf8",mode:384}),g==="claude")try{let P=Le(r,".claude","skills");await Zi(P,{recursive:!0});let V=S_(E_(import.meta.url)),Et=Le(V,"..","..","runtimes","skills"),De=(await R_(Et)).filter(ke=>ke.endsWith(".md"));for(let ke of De){let cr=ke.replace(/\.md$/,""),ae=Le(P,cr);await Zi(ae,{recursive:!0}),await A_(Le(Et,ke),Le(ae,"SKILL.md"))}h("info",$,"Materialised Claude skills",{count:De.length,destRoot:P})}catch(P){x($,"Failed to materialise Claude skills (continuing without)",P)}let B=Le(I,"mcp-config.json"),F="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.",k=e.autonomous_agent.workroom_id,A,O=j?.channels.find(P=>P.member_ids.includes(i))?.id,M=new Map,Y=[],ee=[],Je=[],xe=new Map,L=P=>{if(v)return{set:(V,Et)=>{xe.set(P,Et);let De=[...xe.values()].some(ke=>ke!=="idle");v.set(V,De?"thinking":"idle")}}},lt=0,Ye="",Ie=P=>{let V=M.get(P);return V||(V=Mt(P),M.set(P,V)),V};J={start(){},enqueueUserTurn(P){Ie(A??O??"__default").enqueueUserTurn(P)},stop(){for(let P of M.values())try{P.stop()}catch{}for(let P of M.keys())or.delete(`${i}:${P}`)},stopChannel(P){let V=M.get(P);if(!V)return!1;try{V.stop()}catch{}return M.delete(P),xe.delete(P),or.delete(`${i}:${P}`),!0},onBoundary(P){ee.push(P)},onSessionId(P){},onExit(P){Je.push(P)},onInjected(P){Y.push(P)},onTurnError(P){},onCompact(P){}},Ie(O??"__default");let Te=gu({agentId:i,onFire:async P=>{J.enqueueUserTurn(`[reminder fired] ${P.title}`);try{await s.reminderFire(i,P.id,P.version)}catch(V){x($,`reminder report-fire failed (agent ${i}, reminder ${P.id}) \u2014 local wake already happened; will retry on next sync`,V)}}}),ar=new hs(s),z=P=>yr(e.server_url,t,i,P.startsWith("#")?P:"#"+P),$e=lu({listOwnTasks:z,gateway:s,host:J,hostFor:Ie,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:k,reminderCache:Te,onInboundMessage:P=>{A=P,ar.start(i,P)},...E?{contextTracker:E}:{},contextPolicy:N,mioDir:I,downloadAttachment:P=>Ha(e.server_url,t,i,P).then(V=>({filename:V.filename,mime_type:V.mime_type,data_base64:V.data_base64}))});$e.start(),J.onBoundary(()=>{ar.stop(i)});let be=e.autonomous_agent,Ve=ku({listOwnTasks:z,subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:J,hostFor:Ie,selfAgentId:i,workroomId:k,companion:X,quietSeconds:be.quiet_seconds,maxRepliesPerWindow:be.max_replies_per_window,windowSeconds:be.window_seconds,contextPolicy:N});Ve.start();let df=de?.channelId??j?.channels.find(P=>P.member_ids.includes(i))?.id,ho=Au({workspace:r,mioDir:I,agentId:i,displayName:c,handle:a,role:l,workroomId:ie,channelId:df,gateway:s,companion:X,quietSeconds:be.quiet_seconds,spawnEnv:q,...m?{claudeCommand:m}:{}}),go=P=>{try{let V=P.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(P.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(ie).then(De=>Xi(X,De)).catch(De=>x($,`roster refetch failed for ${P.topic}`,De)),V.channel_id&&V.member_id&&X.logObservation({channel_id:V.channel_id,entity_id:V.member_id,kind:P.topic})),P.topic==="message.created"&&V.sender_id&&V.channel_id){X.logObservation({entity_id:V.sender_id,channel_id:V.channel_id,kind:"sent_message"});try{ho.noteMessage()}catch(De){x($,"personaCrystallizer.noteMessage error (non-fatal)",De)}}}catch(V){x($,"companionWsHandler error (non-fatal)",V)}};return s.subscribe(ie,go),s.listReminders(i).then(P=>Te.snapshot(P)).catch(P=>x($,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,P)),F_({gateway:s,agentId:i,taskWakeRouter:Ve,bootRoster:j,mioDir:I}).catch(P=>x($,`cold-start task self-heal failed for agent ${i} (non-fatal)`,P)),h("info",$,"Agentic spine started",{agentId:i,workroomId:k,mioDir:I}),$_($e,J,W,i,Te,{companion:X,gateway:s,workroomId:ie,companionWsHandler:go,taskWakeRouter:Ve,personaCrystallizer:ho})}catch(y){try{J?.stop()}catch{}try{X.close()}catch{}throw await W.close().catch(()=>{}),y}}function $_(n,e,t,r,s,i){e.onExit(c=>{h("warn",$,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",$,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){x($,"coord.stop() error",c)}try{s.stop()}catch(c){x($,"reminderCache.stop() error",c)}try{e.stop()}catch(c){x($,"host.stop() error",c)}try{await t.close()}catch(c){x($,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){x($,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){x($,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){x($,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){x($,"companion.close() error",c)}}h("info",$,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function B_(n){try{let e=await O_(Le(n,$u),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function U_(n,e){try{await Nu(Le(n,$u),JSON.stringify([...e]),"utf8")}catch(t){x($,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function F_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",$,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(f=>f.member_ids.includes(t)).map(f=>f.name).filter(f=>!!f)),o.length===0)try{o=(await e.getAgentChannels(t)).map(g=>g.name).filter(g=>!!g)}catch(f){x($,`self-heal: getAgentChannels failed for agent ${t}`,f);return}if(o.length===0){h("debug",$,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],d=await Promise.allSettled(o.map(f=>a(t,f.startsWith("#")?f:`#${f}`)));for(let f of d)if(f.status==="fulfilled")for(let g of f.value)g.assignee_id===t&&g.status==="in_progress"&&c.push(g);else x($,`self-heal: getTasks failed for a channel (agent ${t})`,f.reason);if(c.length===0){h("debug",$,"self-heal: no owned in_progress tasks",{agentId:t});return}let l=f=>{let g=f.updated_at??f.created_at,w=g?Date.parse(g):NaN;return Number.isFinite(w)?w:0};c.sort((f,g)=>l(g)-l(f));let u=await B_(i),m=c.filter(f=>!u.has(f.id)).slice(0,D_);if(m.length===0){h("debug",$,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(f=>f.id));let p=0;try{for(let f of m){let g=!1;if(f.parent_message_id&&e.getThreadReplies)try{g=(await e.getThreadReplies(t,f.parent_message_id,50)).some(E=>E.sender_id===t)}catch(w){x($,`self-heal: getThreadReplies failed for task ${f.id} (agent ${t}) \u2014 treating as no activity`,w)}if(u.add(f.id),g){h("debug",$,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:f.id});continue}try{r.synthesizeAssignedWake({task_id:f.id,...f.channel_id?{channel_id:f.channel_id}:{},...f.parent_message_id?{parent_message_id:f.parent_message_id}:{}})&&(p+=1)}catch(w){x($,`self-heal: synthesizeAssignedWake threw for task ${f.id} (agent ${t}) \u2014 task already marked seen, continuing`,w)}}}finally{await U_(i,u)}h("info",$,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:p})}function Du(n,e,t){let r=nr(n.replace(/^@/,"").toLowerCase()),s=nr(e),i=`${r}-${s}`,o=Le(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function Bu(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 H_(n){try{let t=N_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&I_(t)}catch{return!1}}async function Uu(n){let{config:e,gateway:t,retrieveTokenFn:r=xt,mkdirFn:s=v=>Zi(v,{recursive:!0,mode:448}),startSpineFn:i=Lu,mioDir:o=Mu,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=H_}=n,d=e.autonomous_agent;if(!d?.enabled)return;let l,u;try{l=r(),u=await a(d.workroom_id)}catch(v){x($,"Failed to start agentic spine \u2014 daemon continues without spine",v);return}let m=u.filter(v=>v.kind==="agent"&&v.machine_id===e.machine_id);if(m.length===0){h("error",$,`No agent for this machine in workroom ${d.workroom_id} \u2014 create one first (daemon continues without spine)`,{machine_id:e.machine_id,workroom_id:d.workroom_id});return}let p=mu(),f=new gs(t),g=[],w=async v=>{let _=v.handle??"@"+v.display_name,N=_.replace(/^@/,"").toLowerCase().replace(/[^a-zA-Z0-9-]/g,"").length>0?_:`a${v.id.replace(/-/g,"").slice(0,8)}`,{selected:T,raw:I}=Bu(v.runtime);if(T==="codex"){if(!c("codex"))return h("error",$,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:v.id,handle:_}),!1}else if(T==="unsupported")return h("warn",$,`runtime '${I}' not supported; spine not started for this agent ${v.id}`,{agentId:v.id,handle:_,runtime:I}),!1;if(T==="claude"&&!c("claude"))return h("error",$,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:v.id,handle:_}),!1;try{let q=v.id,{workingDirectory:W}=Du(N,e.machine_id,o);await s(W);let J=v.display_name||_.replace(/^@/,""),re=v.description||"An AI agent running on this machine.",X=T==="codex"?"gpt-5-codex":"sonnet",j={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},ie=v.model||X,de=j[ie.trim().toLowerCase()]??ie,D;if(T==="codex"){let y=v.capabilities;if(y&&typeof y=="object"){let b=y.reasoning_effort;typeof b=="string"&&(b==="low"||b==="medium"||b==="high")&&(D=b)}D=D??"medium"}let Q=await i({config:e,machineToken:l,workingDirectory:W,gateway:t,agentId:q,launchId:ws(),agentHandle:_,displayName:J,description:re,role:v.role,serverCapabilities:v.capabilities,model:de,runtime:T,...D?{reasoningEffort:D}:{},contextTracker:p,presenceTracker:f});return g.push(Q),h("info",$,"Agentic spine started",{agentId:q,workroomId:d.workroom_id}),!0}catch(q){return x($,`Failed to start spine for agent ${v.id} \u2014 continuing`,q),!1}return!0};for(let v of m)await w(v);if(g.length===0)return;let E=!1;return{handles:g,async stop(){E||(E=!0,await Promise.allSettled(g.map(v=>v.stop())))},async addAgentById(v){if(E)return!1;if(g.some(N=>N.agentId===v))return h("info",$,"hot-add skipped \u2014 spine already running",{agentId:v}),!1;let S=(await a(d.workroom_id)).find(N=>N.kind==="agent"&&N.id===v&&N.machine_id===e.machine_id);return S?w(S):(h("warn",$,"hot-add: agent not found on this machine",{agentId:v}),!1)},async removeAgentById(v){let _=g.findIndex(N=>N.agentId===v);if(_<0)return!1;let[S]=g.splice(_,1);return await S.stop().catch(()=>{}),!0},dropChannel(v){for(let _ of g)_.host.stopChannel?.(v)}}}async function to(){h("info",$,"Starting mio-agent daemon");let n=Ke();h("info",$,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await gd();let e=new ns;await C_(Qi).catch(()=>{}),await e.listen(Qi);let t=new rs("0.1.0");await t.listen(M_,L_);let r=new zr(n);await r.start();let s=new Xr(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>rd().then(E=>{a=E}).catch(()=>{}),d=()=>a?{...a,sessions:eo()}:{sampled_at:new Date().toISOString(),sessions:eo()};c().then(()=>r.machineHeartbeat(!1,d()).catch(E=>x($,"Initial machine heartbeat failed (non-fatal)",E)));let l=setInterval(()=>{c()},o),u=setInterval(()=>{r.machineHeartbeat(!1,d()).catch(E=>x($,"Machine heartbeat failed (non-fatal)",E))},i),m=new ts(r,{runtimes:n.runtimes,ipcSocketPath:Qi}),p=new Qr(s,m),f=await Uu({config:n,gateway:r,getWorkroomMembersFn:E=>r.getWorkroomMembers(E)});if(f&&n.autonomous_agent?.enabled){let E=n.autonomous_agent.workroom_id;r.subscribe(E,v=>{let _=v.payload??{};if(v.topic==="agent.created"){if(_.machine_id!==n.machine_id)return;let S=_.agent_id;if(typeof S!="string")return;h("info",$,"agent.created for this machine \u2014 hot-starting spine",{agentId:S}),f.addAgentById(S).then(N=>h("info",$,N?"hot-added agent spine \u2713":"hot-add no-op",{agentId:S})).catch(N=>x($,"hot-add failed",N));return}if(v.topic==="agent.status"){if(!("machine_id"in _)||_.machine_id!==null||!_.disabled_by)return;let S=_.agent_id;if(typeof S!="string")return;f.removeAgentById(S).then(N=>{N&&h("info",$,"agent deleted \u2014 spine stopped, runtime processes reaped \u2713",{agentId:S})}).catch(N=>x($,"hot-remove failed",N));return}if(v.topic==="channel.deleted"){let S=_.channel_id;if(typeof S!="string")return;f.dropChannel(S),h("info",$,"channel deleted \u2014 per-channel hosts reaped",{channelId:S})}})}e.onMessage(E=>{if(h("info",$,"IPC message from subprocess",{type:E.type}),m.onIpcMessage(E),E.type==="kick_persona"){let v=E.agent_id,_=E.reason??"ipc_kick";if(!f){h("warn",$,"IPC kick_persona: no spine running \u2014 ignoring");return}let S=0;for(let N of f.handles)if(!(v&&N.agentId!==v))try{N.personaCrystallizer?.kick(_),S+=1}catch(T){x($,"IPC kick_persona: kick failed",T)}h("info",$,"IPC kick_persona dispatched",{kicked:S,targetAgent:v,reason:_});return}if(E.type==="join_workroom"){let v=E.workroom_id;if(!v){h("warn",$,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}p.openWorkroom(v).then(_=>{_?h("info",$,"IPC join_workroom: workroom opened",{workroomId:v,sessionId:_.sessionId}):h("warn",$,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:v})}).catch(_=>{x($,"IPC join_workroom: unexpected error (should not happen)",_)})}}),h("info",$,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let g=!1;async function w(E){if(!g){g=!0,h("info",$,`${E} received \u2014 initiating graceful shutdown`);try{clearInterval(u),clearInterval(l),await r.machineHeartbeat(!0).catch(v=>x($,"Going-offline heartbeat failed (non-fatal)",v)),m.beginShutdown(),await m.drainIrreversible(),p.shutdownAll(),await s.stop(),f&&await f.stop(),await r.stop(),await e.stop(),await t.stop(),h("info",$,"Graceful shutdown complete")}catch(v){x($,"Error during shutdown",v)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{w("SIGTERM")}),process.on("SIGINT",()=>{w("SIGINT")}),await new Promise(()=>{})}var $,Mu,Qi,M_,L_,or,D_,$u,no=R(()=>{"use strict";Xe();Kt();fe();ed();sd();Ui();dd();ud();Gi();kd();Sd();es();Dd();qd();Yd();Zd();ru();du();fu();hu();pu();yu();bu();Su();Pu();us();On();On();$="daemon",Mu=Le(x_(),".mio"),Qi=Le(Mu,"agent.sock"),M_="127.0.0.1",L_=7878,or=new Map;D_=5,$u="self-heal-seen.json"});var ro={};Be(ro,{runStart:()=>q_});async function q_(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 to()}var so=R(()=>{"use strict";fe();no()});import{createHash as G_}from"crypto";import{mkdtempSync as W_,rmSync as Hu,readFileSync as j_,copyFileSync as J_,chmodSync as Y_,renameSync as V_,existsSync as qu}from"fs";import{execFileSync as xn}from"child_process";import{tmpdir as z_,platform as K_}from"os";import{join as vs}from"path";function ew(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function tw(n){return`https://github.com/${X_}/${Q_}/releases/download/v${n}/`}function Gu(n,e){try{return xn("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function nw(n,e){for(let t of n.split(`
|
|
578
|
-
`)){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
|
|
576
|
+
${O.length>6e3?O.slice(0,6e3)+`
|
|
577
|
+
\u2026(\u622A\u65AD,\u5B8C\u6574\u5185\u5BB9 Read MEMORY.md)`:O}`:""}catch{return""}},xe=function(){if(g==="codex"){if(Ee)return Ee;try{Ee=D_("sha1").update($u(B)).digest("hex").slice(0,16)}catch{Ee=void 0}return Ee}},ar=function(O){let z=su(I,g,O,xe());h("info",L,z?"resuming per-channel session":"starting fresh per-channel session",{agentId:i,runtime:g,channelId:O,...z?{sessionId:z}:{}});let Et=kt(O),De={workingDirectory:r,systemPromptPath:B,mcpConfigPath:H,spawnEnv:q,firstTurnText:z?k:k+Mt(),...z?{sessionId:z}:{},...u?{spawnFn:u}:{},...Et?{presenceTracker:Et,agentId:i}:{}},be=g==="codex"?tu({...De,model:f??"gpt-5-codex",..._?{reasoningEffort:_}:{},...p?{codexCommand:p}:{}}):zl({...De,model:f??"sonnet",...m?{claudeCommand:m}:{}});be.onSessionId(ae=>{h("info",L,"agent session id",{agentId:i,runtime:g,channelId:O,sessionId:ae}),iu(I,g,ae,O,xe())});let dr=`${i}:${O}`;return or.set(dr,{agent_id:i,agent_name:c,channel_id:O,runtime:g,model:f??null,started_at:new Date().toISOString(),turns:0,input_tokens:0,output_tokens:0,cache_read_tokens:0}),be.onTurnUsage?.(ae=>{let Te=or.get(dr);Te&&(Te.turns+=1,Te.input_tokens+=ae.inputTokens,Te.output_tokens+=ae.outputTokens,Te.cache_read_tokens+=ae.cacheReadTokens,Te.last_turn_at=new Date().toISOString())}),be.onInjected(ae=>{if(ae.includes("type=human]")){let Te=/\bmsg=([0-9a-f]{8})/.exec(ae);ll(i,O,Te?.[1])}for(let Te of ee)try{Te(ae)}catch{}}),be.onBoundary(()=>{ul(i,O)&&Qt(e.server_url,P,O,{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:vs(),agentId:i},t).catch(ae=>x("run","silent-turn notice failed",ae));for(let ae of Je)try{ae()}catch{}}),be.onExit(ae=>{for(let Te of Pe)try{Te(ae)}catch{}}),be.onTurnError?.(ae=>{let Te=Date.now();if(ae===St&&Te-Ye<6e4)return;St=ae,Ye=Te;let pf=/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);Qt(e.server_url,P,O,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${pf})`,clientIdempotencyKey:vs(),agentId:i},t).catch(mf=>x("run","post turn-error notice failed",mf))}),be.onCompact?.(()=>{Qt(e.server_url,P,O,{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:vs(),agentId:i},t).catch(ae=>x("run","post compact notice failed",ae))}),be.start(),be};var D=Mt,Q=xe,w=ar;let b={agentId:i,handle:a,displayName:c,description:l,role:d,serverId:e.org_id,computer:`${Lu()} (${e.machine_id})`,hostname:Lu(),os:`${process.platform} ${O_()}`,workspace:r,runtime:g,capabilities:T,roster:le,persona:Nu(I)??void 0},C=Wl(b),B=$e(I,"system-prompt.md");if(await Du(B,C,{encoding:"utf8",mode:384}),g==="claude")try{let O=$e(r,".claude","skills");await to(O,{recursive:!0});let z=C_(R_(import.meta.url)),Et=$e(z,"..","..","runtimes","skills"),De=(await I_(Et)).filter(be=>be.endsWith(".md"));for(let be of De){let dr=be.replace(/\.md$/,""),ae=$e(O,dr);await to(ae,{recursive:!0}),await N_($e(Et,be),$e(ae,"SKILL.md"))}h("info",L,"Materialised Claude skills",{count:De.length,destRoot:O})}catch(O){x(L,"Failed to materialise Claude skills (continuing without)",O)}let H=$e(I,"mcp-config.json"),k="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.",P=e.autonomous_agent.workroom_id,R,$=J?.channels.find(O=>O.member_ids.includes(i))?.id,G=new Map,ee=[],Je=[],Pe=[],M=new Map,kt=O=>{if(v)return{set:(z,Et)=>{M.set(O,Et);let De=[...M.values()].some(be=>be!=="idle");v.set(z,De?"thinking":"idle")}}},Ye=0,St="",Ee,V=O=>{let z=G.get(O);return z||(z=ar(O),G.set(O,z)),z};Y={start(){},enqueueUserTurn(O){V(R??$??"__default").enqueueUserTurn(O)},stop(){for(let O of G.values())try{O.stop()}catch{}for(let O of G.keys())or.delete(`${i}:${O}`)},stopChannel(O){let z=G.get(O);if(!z)return!1;try{z.stop()}catch{}return G.delete(O),M.delete(O),or.delete(`${i}:${O}`),!0},onBoundary(O){Je.push(O)},onSessionId(O){},onExit(O){Pe.push(O)},onInjected(O){ee.push(O)},onTurnError(O){},onCompact(O){}},V($??"__default");let Ie=yu({agentId:i,onFire:async O=>{Y.enqueueUserTurn(`[reminder fired] ${O.title}`);try{await s.reminderFire(i,O.id,O.version)}catch(z){x(L,`reminder report-fire failed (agent ${i}, reminder ${O.id}) \u2014 local wake already happened; will retry on next sync`,z)}}}),Ne=new gs(s),nt=O=>_r(e.server_url,t,i,O.startsWith("#")?O:"#"+O),po=fu({listOwnTasks:nt,gateway:s,host:Y,hostFor:V,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:P,reminderCache:Ie,onInboundMessage:O=>{R=O,Ne.start(i,O)},...E?{contextTracker:E}:{},contextPolicy:N,mioDir:I,downloadAttachment:O=>Wa(e.server_url,t,i,O).then(z=>({filename:z.filename,mime_type:z.mime_type,data_base64:z.data_base64}))});po.start(),Y.onBoundary(()=>{Ne.stop(i)});let cr=e.autonomous_agent,Es=xu({listOwnTasks:nt,subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:Y,hostFor:V,selfAgentId:i,workroomId:P,companion:X,quietSeconds:cr.quiet_seconds,maxRepliesPerWindow:cr.max_replies_per_window,windowSeconds:cr.window_seconds,contextPolicy:N});Es.start();let gf=le?.channelId??J?.channels.find(O=>O.member_ids.includes(i))?.id,mo=Iu({workspace:r,mioDir:I,agentId:i,displayName:c,handle:a,role:d,workroomId:ie,channelId:gf,gateway:s,companion:X,quietSeconds:cr.quiet_seconds,spawnEnv:q,...m?{claudeCommand:m}:{}}),yo=O=>{try{let z=O.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(O.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(ie).then(De=>Zi(X,De)).catch(De=>x(L,`roster refetch failed for ${O.topic}`,De)),z.channel_id&&z.member_id&&X.logObservation({channel_id:z.channel_id,entity_id:z.member_id,kind:O.topic})),O.topic==="message.created"&&z.sender_id&&z.channel_id){X.logObservation({entity_id:z.sender_id,channel_id:z.channel_id,kind:"sent_message"});try{mo.noteMessage()}catch(De){x(L,"personaCrystallizer.noteMessage error (non-fatal)",De)}}}catch(z){x(L,"companionWsHandler error (non-fatal)",z)}};return s.subscribe(ie,yo),s.listReminders(i).then(O=>Ie.snapshot(O)).catch(O=>x(L,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,O)),W_({gateway:s,agentId:i,taskWakeRouter:Es,bootRoster:J,mioDir:I}).catch(O=>x(L,`cold-start task self-heal failed for agent ${i} (non-fatal)`,O)),h("info",L,"Agentic spine started",{agentId:i,workroomId:P,mioDir:I}),F_(po,Y,j,i,Ie,{companion:X,gateway:s,workroomId:ie,companionWsHandler:yo,taskWakeRouter:Es,personaCrystallizer:mo})}catch(b){try{Y?.stop()}catch{}try{X.close()}catch{}throw await j.close().catch(()=>{}),b}}function F_(n,e,t,r,s,i){e.onExit(c=>{h("warn",L,"agent claude host exited",{agentId:r,code:c})}),n.onInjected(c=>{h("info",L,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){x(L,"coord.stop() error",c)}try{s.stop()}catch(c){x(L,"reminderCache.stop() error",c)}try{e.stop()}catch(c){x(L,"host.stop() error",c)}try{await t.close()}catch(c){x(L,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){x(L,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){x(L,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){x(L,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){x(L,"companion.close() error",c)}}h("info",L,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function q_(n){try{let e=await M_($e(n,Fu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function G_(n,e){try{await Du($e(n,Fu),JSON.stringify([...e]),"utf8")}catch(t){x(L,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function W_(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){h("debug",L,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(f=>f.member_ids.includes(t)).map(f=>f.name).filter(f=>!!f)),o.length===0)try{o=(await e.getAgentChannels(t)).map(g=>g.name).filter(g=>!!g)}catch(f){x(L,`self-heal: getAgentChannels failed for agent ${t}`,f);return}if(o.length===0){h("debug",L,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],l=await Promise.allSettled(o.map(f=>a(t,f.startsWith("#")?f:`#${f}`)));for(let f of l)if(f.status==="fulfilled")for(let g of f.value)g.assignee_id===t&&g.status==="in_progress"&&c.push(g);else x(L,`self-heal: getTasks failed for a channel (agent ${t})`,f.reason);if(c.length===0){h("debug",L,"self-heal: no owned in_progress tasks",{agentId:t});return}let d=f=>{let g=f.updated_at??f.created_at,_=g?Date.parse(g):NaN;return Number.isFinite(_)?_:0};c.sort((f,g)=>d(g)-d(f));let u=await q_(i),m=c.filter(f=>!u.has(f.id)).slice(0,H_);if(m.length===0){h("debug",L,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(m.map(f=>f.id));let p=0;try{for(let f of m){let g=!1;if(f.parent_message_id&&e.getThreadReplies)try{g=(await e.getThreadReplies(t,f.parent_message_id,50)).some(E=>E.sender_id===t)}catch(_){x(L,`self-heal: getThreadReplies failed for task ${f.id} (agent ${t}) \u2014 treating as no activity`,_)}if(u.add(f.id),g){h("debug",L,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:f.id});continue}try{r.synthesizeAssignedWake({task_id:f.id,...f.channel_id?{channel_id:f.channel_id}:{},...f.parent_message_id?{parent_message_id:f.parent_message_id}:{}})&&(p+=1)}catch(_){x(L,`self-heal: synthesizeAssignedWake threw for task ${f.id} (agent ${t}) \u2014 task already marked seen, continuing`,_)}}}finally{await G_(i,u)}h("info",L,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:m.length,healed:p})}function Hu(n,e,t){let r=nr(n.replace(/^@/,"").toLowerCase()),s=nr(e),i=`${r}-${s}`,o=$e(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function qu(n){let e=typeof n=="string"?n.trim():"";return e===""||e==="claude"?{selected:"claude",raw:"claude"}:e==="codex"?{selected:"codex",raw:e}:{selected:"unsupported",raw:e}}function j_(n){try{let t=$_("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&L_(t)}catch{return!1}}async function Gu(n){let{config:e,gateway:t,retrieveTokenFn:r=xt,mkdirFn:s=v=>to(v,{recursive:!0,mode:448}),startSpineFn:i=Uu,mioDir:o=Bu,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=j_}=n,l=e.autonomous_agent;if(!l?.enabled)return;let d,u;try{d=r(),u=await a(l.workroom_id)}catch(v){x(L,"Failed to start agentic spine \u2014 daemon continues without spine",v);return}let m=u.filter(v=>v.kind==="agent"&&v.machine_id===e.machine_id);if(m.length===0){h("error",L,`No agent for this machine in workroom ${l.workroom_id} \u2014 create one first (daemon continues without spine)`,{machine_id:e.machine_id,workroom_id:l.workroom_id});return}let p=wu(),f=new ps(t),g=[],_=async v=>{let y=v.handle??"@"+v.display_name,N=y.replace(/^@/,"").toLowerCase().replace(/[^a-zA-Z0-9-]/g,"").length>0?y:`a${v.id.replace(/-/g,"").slice(0,8)}`,{selected:T,raw:I}=qu(v.runtime);if(T==="codex"){if(!c("codex"))return h("error",L,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:v.id,handle:y}),!1}else if(T==="unsupported")return h("warn",L,`runtime '${I}' not supported; spine not started for this agent ${v.id}`,{agentId:v.id,handle:y,runtime:I}),!1;if(T==="claude"&&!c("claude"))return h("error",L,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:v.id,handle:y}),!1;try{let q=v.id,{workingDirectory:j}=Hu(N,e.machine_id,o);await s(j);let Y=v.display_name||y.replace(/^@/,""),re=v.description||"An AI agent running on this machine.",X=T==="codex"?"gpt-5-codex":"sonnet",J={"claude opus":"opus","claude fable":"fable","claude sonnet":"sonnet","claude haiku":"haiku","gpt-5.5 codex":"gpt-5-codex"},ie=v.model||X,le=J[ie.trim().toLowerCase()]??ie,D;if(T==="codex"){let w=v.capabilities;if(w&&typeof w=="object"){let b=w.reasoning_effort;typeof b=="string"&&(b==="low"||b==="medium"||b==="high")&&(D=b)}D=D??"medium"}let Q=await i({config:e,machineToken:d,workingDirectory:j,gateway:t,agentId:q,launchId:vs(),agentHandle:y,displayName:Y,description:re,role:v.role,serverCapabilities:v.capabilities,model:le,runtime:T,...D?{reasoningEffort:D}:{},contextTracker:p,presenceTracker:f});return g.push(Q),h("info",L,"Agentic spine started",{agentId:q,workroomId:l.workroom_id}),!0}catch(q){return x(L,`Failed to start spine for agent ${v.id} \u2014 continuing`,q),!1}return!0};for(let v of m)await _(v);if(g.length===0)return;let E=!1;return{handles:g,async stop(){E||(E=!0,await Promise.allSettled(g.map(v=>v.stop())))},async addAgentById(v){if(E)return!1;if(g.some(N=>N.agentId===v))return h("info",L,"hot-add skipped \u2014 spine already running",{agentId:v}),!1;let S=(await a(l.workroom_id)).find(N=>N.kind==="agent"&&N.id===v&&N.machine_id===e.machine_id);return S?_(S):(h("warn",L,"hot-add: agent not found on this machine",{agentId:v}),!1)},async removeAgentById(v){let y=g.findIndex(N=>N.agentId===v);if(y<0)return!1;let[S]=g.splice(y,1);return await S.stop().catch(()=>{}),!0},dropChannel(v){for(let y of g)y.host.stopChannel?.(v)}}}async function ro(){h("info",L,"Starting mio-agent daemon");let n=ze();h("info",L,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await yl();let e=new rs;await P_(eo).catch(()=>{}),await e.listen(eo);let t=new ss("0.1.0");await t.listen(B_,U_);let r=new Kr(n);await r.start();let s=new Qr(r);s.startHeartbeats();let i=45e3,o=3e5,a,c=()=>ol().then(E=>{a=E}).catch(()=>{}),l=()=>a?{...a,sessions:no()}:{sampled_at:new Date().toISOString(),sessions:no()};c().then(()=>r.machineHeartbeat(!1,l()).catch(E=>x(L,"Initial machine heartbeat failed (non-fatal)",E)));let d=setInterval(()=>{c()},o),u=setInterval(()=>{r.machineHeartbeat(!1,l()).catch(E=>x(L,"Machine heartbeat failed (non-fatal)",E))},i),m=new ns(r,{runtimes:n.runtimes,ipcSocketPath:eo}),p=new Zr(s,m),f=await Gu({config:n,gateway:r,getWorkroomMembersFn:E=>r.getWorkroomMembers(E)});if(f&&n.autonomous_agent?.enabled){let E=n.autonomous_agent.workroom_id;r.subscribe(E,v=>{let y=v.payload??{};if(v.topic==="agent.created"){if(y.machine_id!==n.machine_id)return;let S=y.agent_id;if(typeof S!="string")return;h("info",L,"agent.created for this machine \u2014 hot-starting spine",{agentId:S}),f.addAgentById(S).then(N=>h("info",L,N?"hot-added agent spine \u2713":"hot-add no-op",{agentId:S})).catch(N=>x(L,"hot-add failed",N));return}if(v.topic==="agent.status"){if(!("machine_id"in y)||y.machine_id!==null||!y.disabled_by)return;let S=y.agent_id;if(typeof S!="string")return;f.removeAgentById(S).then(N=>{N&&h("info",L,"agent deleted \u2014 spine stopped, runtime processes reaped \u2713",{agentId:S})}).catch(N=>x(L,"hot-remove failed",N));return}if(v.topic==="channel.deleted"){let S=y.channel_id;if(typeof S!="string")return;f.dropChannel(S),h("info",L,"channel deleted \u2014 per-channel hosts reaped",{channelId:S})}})}e.onMessage(E=>{if(h("info",L,"IPC message from subprocess",{type:E.type}),m.onIpcMessage(E),E.type==="kick_persona"){let v=E.agent_id,y=E.reason??"ipc_kick";if(!f){h("warn",L,"IPC kick_persona: no spine running \u2014 ignoring");return}let S=0;for(let N of f.handles)if(!(v&&N.agentId!==v))try{N.personaCrystallizer?.kick(y),S+=1}catch(T){x(L,"IPC kick_persona: kick failed",T)}h("info",L,"IPC kick_persona dispatched",{kicked:S,targetAgent:v,reason:y});return}if(E.type==="join_workroom"){let v=E.workroom_id;if(!v){h("warn",L,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}p.openWorkroom(v).then(y=>{y?h("info",L,"IPC join_workroom: workroom opened",{workroomId:v,sessionId:y.sessionId}):h("warn",L,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:v})}).catch(y=>{x(L,"IPC join_workroom: unexpected error (should not happen)",y)})}}),h("info",L,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let g=!1;async function _(E){if(!g){g=!0,h("info",L,`${E} received \u2014 initiating graceful shutdown`);try{clearInterval(u),clearInterval(d),await r.machineHeartbeat(!0).catch(v=>x(L,"Going-offline heartbeat failed (non-fatal)",v)),m.beginShutdown(),await m.drainIrreversible(),p.shutdownAll(),await s.stop(),f&&await f.stop(),await r.stop(),await e.stop(),await t.stop(),h("info",L,"Graceful shutdown complete")}catch(v){x(L,"Error during shutdown",v)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{_("SIGTERM")}),process.on("SIGINT",()=>{_("SIGINT")}),await new Promise(()=>{})}var L,Bu,eo,B_,U_,or,H_,Fu,so=A(()=>{"use strict";Ke();Kt();fe();rl();al();Hi();hl();gl();ji();xl();Tl();ts();Fl();jl();Kl();nu();ou();hu();pu();mu();_u();vu();Eu();Tu();Mu();fs();On();On();L="daemon",Bu=$e(A_(),".mio"),eo=$e(Bu,"agent.sock"),B_="127.0.0.1",U_=7878,or=new Map;H_=5,Fu="self-heal-seen.json"});var io={};Be(io,{runStart:()=>J_});async function J_(n){if(n.background){let{execFileSync:e}=await import("child_process");try{e("launchctl",["start","io.miomioos.mio-agent"]),console.log("Daemon started via LaunchAgent.")}catch{console.error("LaunchAgent not installed. Run: mio-agent install --background --version <semver>"),process.exit(1)}return}h("info","start","Starting mio-agent in foreground (dev mode, latest OK)"),await ro()}var oo=A(()=>{"use strict";fe();so()});import{createHash as Y_}from"crypto";import{mkdtempSync as V_,rmSync as ju,readFileSync as z_,copyFileSync as K_,chmodSync as X_,renameSync as Q_,existsSync as Ju}from"fs";import{execFileSync as xn}from"child_process";import{tmpdir as Z_,platform as ew}from"os";import{join as bs}from"path";function sw(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function iw(n){return`https://github.com/${tw}/${nw}/releases/download/v${n}/`}function Yu(n,e){try{return xn("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function ow(n,e){for(let t of n.split(`
|
|
578
|
+
`)){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 Vu(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=sw(),i=n._baseUrl??iw(e),o=`mio-agent-${e}-${s}.tar.gz`,a=`mio-agent-${e}-${s}`,c=`mio-agent-${e}-manifest.json`;r("Verifying release manifest...");let l;try{l=JSON.parse(Yu(i+c,"release manifest"))}catch(f){throw new Error(`Release manifest fetch/parse failed: ${f.message}`)}let d=new Set(l.required_fixes??[]),u=rw.filter(f=>!d.has(f));if(u.length>0)throw new Error(`Release v${e} is missing required fixes: ${u.join(", ")}. This release is too old to install safely \u2014 bump the pinned version.`);r("Fetching release checksum...");let m=ow(Yu(i+"SHASUMS256.txt","SHASUMS256.txt"),o);if(!m)throw new Error(`SHA-256 entry for '${o}' not found in SHASUMS256.txt`);let p=V_(bs(Z_(),"mio-agent-install-"));try{r(`Downloading mio-agent ${e}...`);let f=bs(p,o);try{xn("curl",["-fSL",i+o,"-o",f])}catch(y){throw new Error(`Binary download failed: ${y.message}`)}r("Verifying checksum...");let g=Y_("sha256").update(z_(f)).digest("hex");if(g!==m)throw new Error(`Checksum mismatch \u2014 expected ${m.slice(0,12)}\u2026, got ${g.slice(0,12)}\u2026`);r("Extracting binary...");let _=bs(p,"extract");xn("mkdir",["-p",_]),xn("tar",["-xzf",f,"-C",_]);let E=bs(_,a);if(!Ju(E))throw new Error(`mio-agent binary '${a}' not found inside the downloaded tarball`);r("Installing mio-agent...");let v=`${t}.staging`;Ju(v)&&ju(v,{force:!0}),K_(E,v),X_(v,493),ew()==="darwin"&&!n._skipSign&&(xn("codesign",["--force","--sign","-",v]),xn("xattr",["-dr","com.apple.quarantine",v])),Q_(v,t)}finally{ju(p,{recursive:!0,force:!0})}}var tw,nw,rw,zu=A(()=>{"use strict";tw="MioMioOS",nw="mio-agent",rw=["machine-api-v1-prefix","socketio-control-path"]});var Zu={};Be(Zu,{runInstall:()=>uo});import{mkdirSync as Ku,writeFileSync as aw}from"fs";import{execFileSync as cw}from"child_process";import{homedir as Xu}from"os";import{join as ks}from"path";async function uo(n){if(!n.background){console.log("Starting daemon in foreground (use --background --version <semver> for LaunchAgent)");let{runStart:i}=await Promise.resolve().then(()=>(oo(),io));await i({background:!1});return}n.version||(console.error("Error: --background requires --version <semver>"),process.exit(1));let e=ze(),t=n.version;console.log(`Installing mio-agent ${t} as LaunchAgent...`),Ku(ks(pe,"bin"),{recursive:!0,mode:448}),Vu({version:t,destPath:co,onProgress:i=>console.log(i)}),e.pinned_version=t,yr(e),Ku(Qu,{recursive:!0});let r=Xu(),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
579
579
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
580
580
|
<plist version="1.0">
|
|
581
581
|
<dict>
|
|
582
582
|
<key>Label</key>
|
|
583
|
-
<string>${
|
|
583
|
+
<string>${lo}</string>
|
|
584
584
|
<key>ProgramArguments</key>
|
|
585
585
|
<array>
|
|
586
|
-
<string>${
|
|
586
|
+
<string>${co}</string>
|
|
587
587
|
<string>run</string>
|
|
588
588
|
</array>
|
|
589
589
|
<key>RunAtLoad</key>
|
|
@@ -591,20 +591,20 @@ ${P.length>6e3?P.slice(0,6e3)+`
|
|
|
591
591
|
<key>KeepAlive</key>
|
|
592
592
|
<true/>
|
|
593
593
|
<key>ExitTimeOut</key>
|
|
594
|
-
<integer>${
|
|
594
|
+
<integer>${El}</integer>
|
|
595
595
|
<key>StandardOutPath</key>
|
|
596
596
|
<string>${r}/.mio/logs/mio-agent.log</string>
|
|
597
597
|
<key>StandardErrorPath</key>
|
|
598
598
|
<string>${r}/.mio/logs/mio-agent-error.log</string>
|
|
599
599
|
</dict>
|
|
600
|
-
</plist>`;
|
|
601
|
-
mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${
|
|
602
|
-
Run: mio-agent doctor \u2014 to verify health`)}var
|
|
603
|
-
To upgrade: mio-agent upgrade --version ${t}`)}async function
|
|
604
|
-
mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var
|
|
605
|
-
`);let n=
|
|
606
|
-
`))console.log(` ${c}`)}let o=
|
|
607
|
-
`))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>
|
|
600
|
+
</plist>`;aw(ao,s,{encoding:"utf-8",mode:420}),cw("launchctl",["bootstrap",`gui/${process.getuid()}`,ao]),console.log(`
|
|
601
|
+
mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${co}`),console.log(` Plist: ${ao}`),console.log(` Label: ${lo}`),console.log(`
|
|
602
|
+
Run: mio-agent doctor \u2014 to verify health`)}var lo,Qu,ao,co,fo=A(()=>{"use strict";Ke();ji();zu();lo="io.miomioos.mio-agent",Qu=ks(Xu(),"Library","LaunchAgents"),ao=ks(Qu,`${lo}.plist`),co=ks(pe,"bin","mio-agent")});var ho={};Be(ho,{runUpgrade:()=>uw,runUpgradeCheck:()=>lw});import{execFileSync as dw}from"child_process";async function lw(){let e=ze().pinned_version??"unknown (foreground/dev mode)",t=dw("npm",["view","@miomioos/mio-agent","version"],{encoding:"utf-8"}).trim();console.log(`Current pinned: ${e}`),console.log(`Latest on npm: ${t}`),console.log(e===t?"Already on latest pinned version.":`
|
|
603
|
+
To upgrade: mio-agent upgrade --version ${t}`)}async function uw(n){let e=ze();e.pinned_version=n.version,yr(e),console.log(`Pinned version updated to ${n.version} in config.`),await uo({background:!0,version:n.version})}var go=A(()=>{"use strict";Ke();fo()});var ef={};Be(ef,{runStop:()=>gw});import{execFileSync as fw}from"child_process";async function gw(){try{fw("launchctl",["stop",hw]),console.log("Daemon stopped.")}catch{console.log("Daemon was not running or stop signal sent.")}}var hw,tf=A(()=>{"use strict";hw="io.miomioos.mio-agent"});var sf={};Be(sf,{runUninstall:()=>ww});import{execFileSync as pw}from"child_process";import{rmSync as nf,existsSync as rf}from"fs";import{join as mw}from"path";import{homedir as yw}from"os";async function ww(){console.log("Uninstalling mio-agent...");try{pw("launchctl",["bootout",`gui/${process.getuid()}`,Ss]),console.log(" LaunchAgent unregistered.")}catch{console.log(" LaunchAgent was not registered (skipped).")}rf(Ss)&&(nf(Ss),console.log(` Deleted: ${Ss}`));try{Io(),console.log(" Keychain entry deleted.")}catch{console.log(" No Keychain entry found (skipped).")}rf(pe)&&(nf(pe,{recursive:!0,force:!0}),console.log(` Deleted: ${pe}`)),console.log(`
|
|
604
|
+
mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var _w,Ss,of=A(()=>{"use strict";Kt();Ke();_w="io.miomioos.mio-agent",Ss=mw(yw(),"Library","LaunchAgents",`${_w}.plist`)});var cf={};Be(cf,{runDoctor:()=>kw});import{execFileSync as vw,spawnSync as af}from"child_process";import{existsSync as bw}from"fs";function bt(n,e,t){let r=e?"\u2705":"\u274C",s=t?`${r} ${n}: ${t}`:`${r} ${n}`;console.log(s)}async function kw(){console.log(`mio-agent doctor
|
|
605
|
+
`);let n=ha();if(bt("Config (~/.mio/agent.json)",n,n?"found":"missing \u2014 run: mio-agent login"),!n)return;let e=ze(),t=!1;try{vw("security",["find-generic-password","-s","io.miomioos.mio-agent","-a","machine_token"],{stdio:"ignore"}),t=!0}catch{}bt("Keychain (machine_token)",t,t?"found":"missing \u2014 run: mio-agent login");let r=!1;try{r=af("curl",["-fsS","--max-time","3",`${e.server_url}/health`]).status===0}catch{}bt("Server connectivity",r,r?e.server_url:`unreachable: ${e.server_url}`);let s=!1;try{s=af("curl",["-fsS","--max-time","1",`http://127.0.0.1:${fa}/health`]).status===0}catch{}bt("Daemon (127.0.0.1:7878)",s,s?"running":"not running"),console.log(""),console.log("Runtimes:");let i=bn();if(i)bt(" claude",!0,i);else{bt(" claude",!1,"not found");for(let c of Vl().split(`
|
|
606
|
+
`))console.log(` ${c}`)}let o=us();if(o){let c=(process.env.MIO_CODEX_MODEL||"").trim();bt(" codex",!0,c?`${o} (model override: ${c})`:`${o} (model: local default)`)}else{bt(" codex",!1,"not found");for(let c of Ql().split(`
|
|
607
|
+
`))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>bw(c));bt(" opencode",!!a,a??"not found in PATH"),console.log("")}var df=A(()=>{"use strict";Ke();ds();Xi()});var uf={};Be(uf,{buildPairingDeeplink:()=>lf,runPairPhone:()=>xw});function lf(n,e){return`codelight://pair?${new URLSearchParams({v:"1",base:n,pid:e.pairing_id,code:e.code,wr:e.workroom_display,scope:e.scope_label,exp:e.expires_at}).toString()}`}function Sw(n){let e=new Date(n).getTime()-Date.now();return`${Math.max(0,Math.round(e/6e4))} min`}function Ew(n){switch(n){case 401:return"Machine token invalid or expired. Run: mio-agent login";case 403:return"This machine cannot grant access (token / machine mismatch).";case 409:return"This machine is not bound to an org. Finish Mac setup first.";case 404:return"Workroom not found for this machine's org.";case 400:return"Invalid request (check workroom_id / ttl).";default:return"Unexpected error."}}async function xw(n){n||(console.error("Usage: mio-agent pair-phone <workroom_id>"),process.exit(1));let e=ze(),t;try{t=xt()}catch{console.error("No machine_token in Keychain. Run: mio-agent login"),process.exit(1);return}let r=`${e.server_url}/api/v1/machines/${e.machine_id}/pairings`,s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify({workroom_id:n})});if(!s.ok){console.error(`Pairing failed: ${s.status} \u2014 ${Ew(s.status)}`),process.exit(1);return}let i=await s.json(),o=lf(e.server_url,i);console.log(""),console.log("=== Pair CodeLight on your phone ==="),console.log(` Workroom: ${i.workroom_display}`),console.log(` Scope: ${i.scope_label}`),console.log(` Server: ${i.server_host??e.server_url}`),console.log(` Expires: in ${Sw(i.expires_at)} (${i.expires_at})`),console.log(` Pairing: ${i.pairing_id}`),console.log("");let a=!1;try{let c=await Promise.resolve().then(()=>oe(Ls(),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 ff=A(()=>{"use strict";Ke();Kt()});import{parseArgs as Tw}from"util";import{fileURLToPath as Cw}from"url";import{realpathSync as hf}from"fs";function Rw(n){return n[0]==="agentcli"}function Aw(n){return n[0]==="login"}async function Ow(){let n=process.argv.slice(2);if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){let{getPackageVersion:i}=await Promise.resolve().then(()=>(vo(),wo));console.log(i()),process.exit(0)}if(Rw(n)){let{runAgentcliCommand:i}=await Promise.resolve().then(()=>(Po(),Oo));process.exit(await i())}if(Aw(n)){let{runLogin:i}=await Promise.resolve().then(()=>(aa(),oa));process.exit(await i(process.argv.slice(3)))}if(n[0]==="logs"){let{runLogs:i}=await Promise.resolve().then(()=>(la(),da));process.exit(await i(process.argv.slice(3)))}let{values:e,positionals:t}=Tw({args:n,options:{version:{type:"string"},background:{type:"boolean",default:!1},check:{type:"boolean",default:!1},help:{type:"boolean",default:!1}},allowPositionals:!0}),[r,...s]=t;switch(r){case"start":{let{runStart:i}=await Promise.resolve().then(()=>(oo(),io));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(()=>(fo(),Zu));await i({background:e.background??!1,version:e.version});break}case"upgrade":{if(e.check){let{runUpgradeCheck:i}=await Promise.resolve().then(()=>(go(),ho));await i()}else if(e.version){let{runUpgrade:i}=await Promise.resolve().then(()=>(go(),ho));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(()=>(so(),Wu));await i();break}case"stop":{let{runStop:i}=await Promise.resolve().then(()=>(tf(),ef));await i();break}case"uninstall":{let{runUninstall:i}=await Promise.resolve().then(()=>(of(),sf));await i();break}case"doctor":{let{runDoctor:i}=await Promise.resolve().then(()=>(df(),cf));await i();break}case"pair-phone":{let{runPairPhone:i}=await Promise.resolve().then(()=>(ff(),uf));await i(s[0]);break}default:console.log(`Mio Agent \u2014 background AI worker daemon
|
|
608
608
|
|
|
609
609
|
Global flags:
|
|
610
610
|
--version, -v Print version and exit
|
|
@@ -623,7 +623,7 @@ Commands:
|
|
|
623
623
|
logs [-n N] [-f] Tail daemon logs (~/.mio/logs/, or /tmp/mio-agent.log in dev mode)
|
|
624
624
|
agentcli <subcommand> Agent-facing CLI (message check/send/read); use --help for details
|
|
625
625
|
run Internal: launched by launchd (do not call directly)
|
|
626
|
-
`),process.exit(r?1:0)}}function
|
|
626
|
+
`),process.exit(r?1:0)}}function Pw(){try{let n=te("node:sea");return typeof n.isSea=="function"&&n.isSea()}catch{return!1}}function Iw(){if(Pw())return!0;let n=process.argv[1];if(!n)return!1;try{return hf(Cw(import.meta.url))===hf(n)}catch{return!1}}Iw()&&Ow().catch(n=>{console.error("Fatal:",n.message),process.exit(1)});export{Rw as isAgentcliInvocation,Aw as isLoginInvocation};
|
|
627
627
|
/*! Bundled license information:
|
|
628
628
|
|
|
629
629
|
xmlhttprequest-ssl/lib/XMLHttpRequest.js:
|