@miomioos/mio-agent 0.2.2 → 0.2.4
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 +192 -185
- package/package.json +1 -1
package/dist/cli/index.js
CHANGED
|
@@ -1,126 +1,126 @@
|
|
|
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 Ou=Object.create;var rs=Object.defineProperty;var Au=Object.getOwnPropertyDescriptor;var Pu=Object.getOwnPropertyNames;var Iu=Object.getPrototypeOf,Nu=Object.prototype.hasOwnProperty;var Q=(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),Ce=(n,e)=>{for(var t in e)rs(n,t,{get:e[t],enumerable:!0})},Mu=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pu(e))!Nu.call(n,s)&&s!==t&&rs(n,s,{get:()=>e[s],enumerable:!(r=Au(e,s))||r.enumerable});return n};var te=(n,e,t)=>(t=n!=null?Ou(Iu(n)):{},Mu(e||!n||!n.__esModule?rs(t,"default",{value:n,enumerable:!0}):t,n));var ji={};Ce(ji,{MIO_AGENT_VERSION:()=>Wi,getPackageVersion:()=>Lu});function Lu(){return Wi}var Wi,Ji=A(()=>{"use strict";Wi="0.2.1"});import{readFileSync as zi,writeFileSync as $u}from"fs";import{basename as Du,extname as Bu}from"path";import{randomUUID as Ki}from"crypto";async function Xi(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(kf),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=zi(o,"utf8").trim()}catch(u){let f=u instanceof Error?u.message:String(u);return r.write(JSON.stringify({ok:!1,code:"MISSING_PROXY_TOKEN",message:`Cannot read proxy token file: ${f}`})+`
|
|
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,...l]=n;return c==="message"?
|
|
8
|
-
`),1)}async function
|
|
9
|
-
`),1}}async function
|
|
10
|
-
`),1;let o=await
|
|
11
|
-
`),1)}async function
|
|
7
|
+
`),1;let[c,d,...l]=n;return c==="message"?Fu(d,l,i,a,s,t,r):c==="task"?ju(d,l,i,a,t,r):c==="reminder"?Qu(d,l,i,a,t,r):c==="action"?df(d,l,i,a,t,r):c==="attachment"?pf(d,l,i,a,t,r):c==="profile"?_f(d,l,i,a,t,r):(r.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown command: ${n.join(" ")}`})+`
|
|
8
|
+
`),1)}async function Fu(n,e,t,r,s,i,o){switch(n){case"check":return Uu(e,t,r,i,o);case"send":return Hu(e,t,r,s,i,o);case"read":return qu(e,t,r,i,o);case"react":return Gu(e,t,r,i,o);case"reply":return Wu(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 Uu(n,e,t,r,s){let i=B(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 ae(e,t,"check",{channel:i});return o.ok?(Zi(o.data,r),0):(s.write(JSON.stringify(o.error)+`
|
|
11
|
+
`),1)}async function Hu(n,e,t,r,s,i){let o=B(n,"--target");if(!o)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for message send"})+`
|
|
12
12
|
`),1;if(r.isTTY)return i.write(JSON.stringify({ok:!1,code:"NO_STDIN",message:'message body must be piped on stdin, e.g. mio message send --target "#x" <<EOF'})+`
|
|
13
|
-
`),1;let a=await
|
|
14
|
-
`),1;let c=
|
|
15
|
-
`),1;d.push(S.id)}let l={target:o,content:a,clientIdempotencyKey:c};d.length>0&&(l.attachment_ids=d);let u=await
|
|
16
|
-
`),1;let f=u.data,
|
|
17
|
-
`),0}async function
|
|
18
|
-
`),1;let o={channel:i},a=
|
|
19
|
-
`),1;if(a&&(o.after_seq=a),c&&(o.around=c),d&&(o.around=d),l!==void 0){let
|
|
20
|
-
`),1;o.limit=
|
|
21
|
-
`),1)}async function
|
|
22
|
-
`),1;let o=
|
|
23
|
-
`),1;let a=
|
|
24
|
-
`),1;let c=n.includes("--remove")?"remove":"add",d=await
|
|
13
|
+
`),1;let a=await eo(r);if(a.trim()==="")return i.write(JSON.stringify({ok:!1,code:"EMPTY_MESSAGE",message:"message body is empty \u2014 nothing to send"})+`
|
|
14
|
+
`),1;let c=Ki(),d=Wn(n,"--attachment");for(let v of Wn(n,"--attach-file")){let S=await os(v,o,e,t);if(!S.ok)return i.write(JSON.stringify(S.error)+`
|
|
15
|
+
`),1;d.push(S.id)}let l={target:o,content:a,clientIdempotencyKey:c};d.length>0&&(l.attachment_ids=d);let u=await ae(e,t,"send",l);if(!u.ok)return i.write(JSON.stringify(u.error)+`
|
|
16
|
+
`),1;let f=u.data,h=String(f.id??""),g=String(f.short_id??f.shortId??"").slice(0,8),m=f.seq!==void 0?`seq=${f.seq} `:"",y=typeof f.routed_to=="string"?f.routed_to:"",b=typeof f.task_number=="number"?f.task_number:null,x="";return y==="thread"&&b!==null&&(x=` (auto-routed to thread of task #${b} \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=${h} ${g?`short=${g} `:""}${m}target=${o}${x}
|
|
17
|
+
`),0}async function qu(n,e,t,r,s){let i=B(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for message read"})+`
|
|
18
|
+
`),1;let o={channel:i},a=B(n,"--after"),c=B(n,"--around"),d=B(n,"--before"),l=B(n,"--limit");if([a,c,d].filter(h=>h!==void 0).length>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --after, --around, --before may be provided"})+`
|
|
19
|
+
`),1;if(a&&(o.after_seq=a),c&&(o.around=c),d&&(o.around=d),l!==void 0){let h=Number(l);if(!Number.isInteger(h)||h<=0)return s.write(JSON.stringify({ok:!1,code:"INVALID_LIMIT",message:`--limit must be a positive integer, got: ${l}`})+`
|
|
20
|
+
`),1;o.limit=h}let f=await ae(e,t,"history",o);return f.ok?(Zi(f.data,r),0):(s.write(JSON.stringify(f.error)+`
|
|
21
|
+
`),1)}async function Gu(n,e,t,r,s){let i=tt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a message id is required for message react"})+`
|
|
22
|
+
`),1;let o=B(n,"--target");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#channel> is required for message react"})+`
|
|
23
|
+
`),1;let a=B(n,"--emoji");if(!a)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--emoji <emoji> is required for message react"})+`
|
|
24
|
+
`),1;let c=n.includes("--remove")?"remove":"add",d=await ae(e,t,"react",{target:o,message_id:i,emoji:a,op:c});return d.ok?(r.write(`reacted: ${c} ${a} on msg=${i} in ${o}
|
|
25
25
|
`),0):(s.write(JSON.stringify(d.error)+`
|
|
26
|
-
`),1)}async function
|
|
27
|
-
`),1;let a=
|
|
26
|
+
`),1)}async function Wu(n,e,t,r,s,i){let o=B(n,"--parent");if(!o)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--parent <message-id> is required for message reply"})+`
|
|
27
|
+
`),1;let a=B(n,"--target");if(!a)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for message reply"})+`
|
|
28
28
|
`),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'})+`
|
|
29
|
-
`),1;let c=await
|
|
30
|
-
`),1;let d=
|
|
31
|
-
`),1;l.push(
|
|
32
|
-
`),1;let
|
|
33
|
-
`),0}async function
|
|
34
|
-
`),1}}async function
|
|
35
|
-
`),1;let o=
|
|
29
|
+
`),1;let c=await eo(r);if(c.trim()==="")return i.write(JSON.stringify({ok:!1,code:"EMPTY_MESSAGE",message:"reply body is empty \u2014 nothing to send"})+`
|
|
30
|
+
`),1;let d=Ki(),l=Wn(n,"--attachment");for(let b of Wn(n,"--attach-file")){let x=await os(b,a,e,t);if(!x.ok)return i.write(JSON.stringify(x.error)+`
|
|
31
|
+
`),1;l.push(x.id)}let u={target:a,parent_message_id:o,content:c,clientIdempotencyKey:d};l.length>0&&(u.attachment_ids=l);let f=await ae(e,t,"reply",u);if(!f.ok)return i.write(JSON.stringify(f.error)+`
|
|
32
|
+
`),1;let h=f.data,g=String(h.id??""),m=String(h.short_id??h.shortId??"").slice(0,8),y=h.seq!==void 0?`seq=${h.seq} `:"";return s.write(`replied: id=${g} ${m?`short=${m} `:""}${y}parent=${o} target=${a}
|
|
33
|
+
`),0}async function ju(n,e,t,r,s,i){switch(n){case"list":return Yu(e,t,r,s,i);case"create":return Vu(e,t,r,s,i);case"claim":return Yi("claim",e,t,r,s,i);case"unclaim":return Yi("unclaim",e,t,r,s,i);case"update":return zu(e,t,r,s,i);case"review":return Ju(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown task subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
34
|
+
`),1}}async function Ju(n,e,t,r,s){let i=ss(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a task number (e.g. #5 or 5) is required for task review"})+`
|
|
35
|
+
`),1;let o=B(n,"--channel");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task review"})+`
|
|
36
36
|
`),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"})+`
|
|
37
|
-
`),1;let d=a?"pass":"bounce",l=
|
|
37
|
+
`),1;let d=a?"pass":"bounce",l=B(n,"--feedback")??"",u=await ae(e,t,"task",{op:"review",channel:o,number:i,verdict:d,feedback:l});return u.ok?(r.write(`Reviewed task #${i} \u2192 ${d==="pass"?"passed (done)":"bounced back for rework"}
|
|
38
38
|
`),0):(s.write(JSON.stringify(u.error)+`
|
|
39
|
-
`),1)}async function
|
|
40
|
-
`),1;let o=await
|
|
41
|
-
`),1)}async function
|
|
42
|
-
`),1;let o=
|
|
43
|
-
`),1;let a=
|
|
44
|
-
`),1;let l=
|
|
45
|
-
`),0}async function
|
|
46
|
-
`),1;let a=
|
|
47
|
-
`),1;let c=await
|
|
39
|
+
`),1)}async function Yu(n,e,t,r,s){let i=B(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task list"})+`
|
|
40
|
+
`),1;let o=await ae(e,t,"task",{op:"list",channel:i});return o.ok?(Xu(o.data,r),0):(s.write(JSON.stringify(o.error)+`
|
|
41
|
+
`),1)}async function Vu(n,e,t,r,s){let i=B(n,"--channel");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task create"})+`
|
|
42
|
+
`),1;let o=B(n,"--title");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--title <text> is required for task create"})+`
|
|
43
|
+
`),1;let a=B(n,"--attach"),c={op:"create",channel:i,title:o};a!==void 0&&a!==""&&(c.attach_to_message_id=a);let d=await ae(e,t,"task",c);if(!d.ok)return s.write(JSON.stringify(d.error)+`
|
|
44
|
+
`),1;let l=Ku(d.data),u=l?.number!==void 0?`#${l.number}`:"(new)";return r.write(`Created task ${u}: ${o}
|
|
45
|
+
`),0}async function Yi(n,e,t,r,s,i){let o=ss(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}`})+`
|
|
46
|
+
`),1;let a=B(e,"--channel");if(!a)return i.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:`--channel <#name> is required for task ${n}`})+`
|
|
47
|
+
`),1;let c=await ae(t,r,"task",{op:n,channel:a,number:o});return c.ok?(s.write(`${n==="claim"?"Claimed":"Unclaimed"} task #${o}
|
|
48
48
|
`),0):(i.write(JSON.stringify(c.error)+`
|
|
49
|
-
`),1)}async function
|
|
50
|
-
`),1;let o=
|
|
51
|
-
`),1;let a=
|
|
52
|
-
`),1;let c=await
|
|
49
|
+
`),1)}async function zu(n,e,t,r,s){let i=ss(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"})+`
|
|
50
|
+
`),1;let o=B(n,"--channel");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--channel <#name> is required for task update"})+`
|
|
51
|
+
`),1;let a=B(n,"--status");if(!a)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--status <state> is required for task update"})+`
|
|
52
|
+
`),1;let c=await ae(e,t,"task",{op:"update",channel:o,number:i,status:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
|
|
53
53
|
`),1;let d=c.data??{};if(a==="done"&&d.diverted_to_review===!0)r.write(`Submitted task #${i} for independent review \u2014 it is now in_review and will close once a teammate audits your work. If it bounces back, you'll be pinged to address the feedback and re-submit \`done\`.
|
|
54
54
|
`);else{let l=typeof d.status=="string"?d.status:a;r.write(`Updated task #${i} \u2192 ${l}
|
|
55
|
-
`)}return 0}function
|
|
55
|
+
`)}return 0}function ss(n){let e=tt(n);if(e===void 0)return;let t=e.startsWith("#")?e.slice(1):e;if(!(t===""||!/^\d+$/.test(t)))return Number(t)}function tt(n){for(let e=0;e<n.length;e++){let t=n[e];if(t.startsWith("--")){e++;continue}return t}}function Ku(n){let e=n;return(Array.isArray(e?.tasks)?e.tasks:[])[0]}function Xu(n,e){let t=n,r=Array.isArray(t?.tasks)?t.tasks:[];if(r.length===0){e.write(`(no tasks)
|
|
56
56
|
`);return}for(let s of r){let i=`#${s.number??"?"}`,o=s.status??"unknown",a=s.title??"",c=s.assignee??s.assignee_id,d=c?`@${c}`:"unassigned";e.write(`${i} ${o} ${a} ${d}
|
|
57
|
-
`)}}async function
|
|
58
|
-
`),1}}async function
|
|
59
|
-
`),1;let o=
|
|
57
|
+
`)}}async function Qu(n,e,t,r,s,i){switch(n){case"schedule":return Zu(e,t,r,s,i);case"list":return ef(e,t,r,s,i);case"snooze":return tf(e,t,r,s,i);case"update":return nf(e,t,r,s,i);case"cancel":return rf(e,t,r,s,i);case"log":return sf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown reminder subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
58
|
+
`),1}}async function Zu(n,e,t,r,s){let i=B(n,"--title");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:'--title "<text>" is required for reminder schedule'})+`
|
|
59
|
+
`),1;let o=B(n,"--in"),a=B(n,"--at"),c=B(n,"--cadence"),d=[o,a,c].filter(b=>b!==void 0).length;if(d===0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"one of --in <dur>, --at <ISO>, or --cadence <rule> is required for reminder schedule"})+`
|
|
60
60
|
`),1;if(d>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --at, --cadence may be provided"})+`
|
|
61
|
-
`),1;let l=
|
|
62
|
-
`),1;let
|
|
63
|
-
`),0}async function
|
|
64
|
-
`),1)}async function
|
|
65
|
-
`),1;let o=
|
|
61
|
+
`),1;let l=B(n,"--channel"),u=B(n,"--message-id"),f={op:"schedule",title:i};o!==void 0&&(f.in=o),a!==void 0&&(f.at=a),c!==void 0&&(f.cadence=c),l!==void 0&&(f.channel=l),u!==void 0&&(f.message_id=u);let h=await ae(e,t,"reminder",f);if(!h.ok)return s.write(JSON.stringify(h.error)+`
|
|
62
|
+
`),1;let g=of(h.data),m=g?.id??"(new)",y=g?.fireAt?` fireAt=${g.fireAt}`:"";return r.write(`Scheduled reminder ${m}: ${i}${y}
|
|
63
|
+
`),0}async function ef(n,e,t,r,s){let i=B(n,"--channel"),o=B(n,"--status"),a={op:"list"};i!==void 0&&(a.channel=i),o!==void 0&&(a.status=o);let c=await ae(e,t,"reminder",a);return c.ok?(cf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
|
|
64
|
+
`),1)}async function tf(n,e,t,r,s){let i=tt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder snooze"})+`
|
|
65
|
+
`),1;let o=B(n,"--in"),a=B(n,"--until"),c=[o,a].filter(g=>g!==void 0).length;if(c===0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"one of --in <dur> or --until <ISO> is required for reminder snooze"})+`
|
|
66
66
|
`),1;if(c>1)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --until may be provided"})+`
|
|
67
|
-
`),1;let d=await
|
|
68
|
-
`),1;let f=
|
|
69
|
-
`),0}async function
|
|
70
|
-
`),1;let o=
|
|
67
|
+
`),1;let d=await is(i,e,t,s);if(d===void 0)return 1;let l={op:"snooze",id:i,version:d};o!==void 0&&(l.in=o),a!==void 0&&(l.until=a);let u=await ae(e,t,"reminder",l);if(!u.ok)return s.write(JSON.stringify(u.error)+`
|
|
68
|
+
`),1;let f=af(u.data),h=f?.fireAt?` \u2192 ${f.fireAt}`:"";return r.write(`Snoozed reminder ${i}${h}
|
|
69
|
+
`),0}async function nf(n,e,t,r,s){let i=tt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder update"})+`
|
|
70
|
+
`),1;let o=B(n,"--title"),a=B(n,"--cadence"),c=B(n,"--in"),d=B(n,"--at");if([o,a,c,d].every(h=>h===void 0))return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"at least one of --title, --cadence, --in, --at is required for reminder update"})+`
|
|
71
71
|
`),1;if(c!==void 0&&d!==void 0)return s.write(JSON.stringify({ok:!1,code:"CONFLICTING_ANCHORS",message:"only one of --in, --at may be provided"})+`
|
|
72
|
-
`),1;let l=await
|
|
72
|
+
`),1;let l=await is(i,e,t,s);if(l===void 0)return 1;let u={op:"update",id:i,version:l};o!==void 0&&(u.title=o),a!==void 0&&(u.cadence=a),c!==void 0&&(u.in=c),d!==void 0&&(u.at=d);let f=await ae(e,t,"reminder",u);return f.ok?(r.write(`Updated reminder ${i}
|
|
73
73
|
`),0):(s.write(JSON.stringify(f.error)+`
|
|
74
|
-
`),1)}async function
|
|
75
|
-
`),1;let o=await
|
|
74
|
+
`),1)}async function rf(n,e,t,r,s){let i=tt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder cancel"})+`
|
|
75
|
+
`),1;let o=await is(i,e,t,s);if(o===void 0)return 1;let a=await ae(e,t,"reminder",{op:"cancel",id:i,version:o});return a.ok?(r.write(`Canceled reminder ${i}
|
|
76
76
|
`),0):(s.write(JSON.stringify(a.error)+`
|
|
77
|
-
`),1)}async function
|
|
78
|
-
`),1;let o=await
|
|
79
|
-
`),1)}function
|
|
77
|
+
`),1)}async function sf(n,e,t,r,s){let i=tt(n);if(i===void 0)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a reminder id is required for reminder log"})+`
|
|
78
|
+
`),1;let o=await ae(e,t,"reminder",{op:"log",id:i});return o.ok?(lf(o.data,r),0):(s.write(JSON.stringify(o.error)+`
|
|
79
|
+
`),1)}function of(n){let e=n;return e?.reminder?e.reminder:(Array.isArray(e?.reminders)?e.reminders:[])[0]}function af(n){return n?.reminder}async function is(n,e,t,r){let s=await ae(e,t,"reminder",{op:"list"});if(!s.ok){r.write(JSON.stringify(s.error)+`
|
|
80
80
|
`);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}`})+`
|
|
81
81
|
`);return}if(typeof a.version!="number"){r.write(JSON.stringify({ok:!1,code:"REMINDER_NO_VERSION",message:`Reminder ${n} has no version field`})+`
|
|
82
|
-
`);return}return a.version}function
|
|
82
|
+
`);return}return a.version}function cf(n,e){let t=n,r=Array.isArray(t?.reminders)?t.reminders:[];if(r.length===0){e.write(`(no reminders)
|
|
83
83
|
`);return}for(let s of r){let i=s.id??"?",o=s.fireAt??"?",a=s.status??"unknown",c=s.title??"",d=s.cadence?` cadence=${s.cadence}`:"";e.write(`${i} ${o} ${a} ${c}${d}
|
|
84
|
-
`)}}function
|
|
84
|
+
`)}}function lf(n,e){let t=n,r=Array.isArray(t?.events)?t.events:[];if(r.length===0){e.write(`(no events)
|
|
85
85
|
`);return}for(let s of r){let i=s.at??"?",o=s.event??"unknown",a=s.id??s.reminderId??"";e.write(`${i} ${o} ${a}
|
|
86
|
-
`)}}async function
|
|
87
|
-
`),1}}async function
|
|
88
|
-
`),1;let o=
|
|
89
|
-
`),1;let a;if(o==="channel:create"){let u=
|
|
90
|
-
`),1;a={name:u};let f=
|
|
91
|
-
`),1;let f=
|
|
92
|
-
`),1;a={channel:u},f!==void 0&&(a.member_handle=f),
|
|
93
|
-
`),1;let c=await
|
|
94
|
-
`),1;let l=
|
|
95
|
-
`),0}async function
|
|
96
|
-
`),1)}function
|
|
86
|
+
`)}}async function df(n,e,t,r,s,i){switch(n){case"prepare":return uf(e,t,r,s,i);case"list":return ff(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown action subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
87
|
+
`),1}}async function uf(n,e,t,r,s){let i=B(n,"--target");if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for action prepare"})+`
|
|
88
|
+
`),1;let o=B(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"})+`
|
|
89
|
+
`),1;let a;if(o==="channel:create"){let u=B(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"})+`
|
|
90
|
+
`),1;a={name:u};let f=B(n,"--visibility");f!==void 0&&(a.visibility=f)}else if(o==="channel:add_member"){let u=B(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"})+`
|
|
91
|
+
`),1;let f=B(n,"--member"),h=B(n,"--member-id");if(f===void 0&&h===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"})+`
|
|
92
|
+
`),1;a={channel:u},f!==void 0&&(a.member_handle=f),h!==void 0&&(a.member_id=h)}else return s.write(JSON.stringify({ok:!1,code:"INVALID_TYPE",message:`Unknown action type: ${o}. Supported: channel:create, channel:add_member`})+`
|
|
93
|
+
`),1;let c=await ae(e,t,"action",{op:"prepare",target:i,type:o,params:a});if(!c.ok)return s.write(JSON.stringify(c.error)+`
|
|
94
|
+
`),1;let l=hf(c.data)?.id??"(new)";return r.write(`Proposed action ${l}: ${o} (target=${i}) \u2014 awaiting human approval
|
|
95
|
+
`),0}async function ff(n,e,t,r,s){let i=B(n,"--status"),o=B(n,"--channel"),a={op:"list"};i!==void 0&&(a.status=i),o!==void 0&&(a.channel=o);let c=await ae(e,t,"action",a);return c.ok?(gf(c.data,r),0):(s.write(JSON.stringify(c.error)+`
|
|
96
|
+
`),1)}function hf(n){let e=n;return e?.action?e.action:(Array.isArray(e?.actions)?e.actions:[])[0]}function gf(n,e){let t=n,r=Array.isArray(t?.actions)?t.actions:[];if(r.length===0){e.write(`(no actions)
|
|
97
97
|
`);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}
|
|
98
|
-
`)}}async function
|
|
99
|
-
`),1}}async function
|
|
100
|
-
`),1;let o=
|
|
101
|
-
`),1;let a=await
|
|
98
|
+
`)}}async function pf(n,e,t,r,s,i){switch(n){case"upload":return mf(e,t,r,s,i);case"view":return yf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown attachment subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
99
|
+
`),1}}async function os(n,e,t,r){let s=Bu(n).toLowerCase(),i=Vi[s];if(!i){let u=Object.keys(Vi).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=zi(n).toString("base64")}catch(u){let f=u instanceof Error?u.message:String(u);return{ok:!1,error:{ok:!1,code:"FILE_READ_ERROR",message:`Cannot read file ${n}: ${f}`}}}let a=Du(n),c=await ae(t,r,"attachment",{op:"upload",filename:a,mime_type:i,data_base64:o,target:e});if(!c.ok)return{ok:!1,error:c.error};let d=c.data;return{ok:!0,id:String(d.attachment_id??d.id??""),filename:a,mimeType:i}}async function mf(n,e,t,r,s){let i=tt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"a local file path is required for attachment upload"})+`
|
|
100
|
+
`),1;let o=B(n,"--target");if(!o)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"--target <#name> is required for attachment upload"})+`
|
|
101
|
+
`),1;let a=await os(i,o,e,t);return a.ok?(r.write(`uploaded: attachment_id=${a.id} filename=${a.filename} mime=${a.mimeType}
|
|
102
102
|
`),0):(s.write(JSON.stringify(a.error)+`
|
|
103
|
-
`),1)}async function
|
|
104
|
-
`),1;let o=
|
|
105
|
-
`),1;let c=a.data,d=String(c.filename??""),l=String(c.mime_type??""),u=c.size_bytes;if(o!==void 0){let
|
|
106
|
-
`),1;let
|
|
107
|
-
`),1}try{
|
|
108
|
-
`),1}return r.write(`saved: ${o} (${
|
|
103
|
+
`),1)}async function yf(n,e,t,r,s){let i=tt(n);if(!i)return s.write(JSON.stringify({ok:!1,code:"MISSING_ARG",message:"an attachment id is required for attachment view"})+`
|
|
104
|
+
`),1;let o=B(n,"--out"),a=await ae(e,t,"attachment",{op:"view",attachment_id:i});if(!a.ok)return s.write(JSON.stringify(a.error)+`
|
|
105
|
+
`),1;let c=a.data,d=String(c.filename??""),l=String(c.mime_type??""),u=c.size_bytes;if(o!==void 0){let h=c.data_base64;if(typeof h!="string")return s.write(JSON.stringify({ok:!1,code:"NO_ATTACHMENT_DATA",message:`attachment ${i} response did not include data_base64 bytes to save`})+`
|
|
106
|
+
`),1;let g=Buffer.from(h,"base64");if(u!==void 0){let m=Number(u);if(!Number.isNaN(m)&&g.length!==m)return s.write(JSON.stringify({ok:!1,code:"SIZE_MISMATCH",message:`attachment ${i} byte length mismatch: server reported size_bytes=${m} but decoded ${g.length} bytes \u2014 not writing ${o}`})+`
|
|
107
|
+
`),1}try{$u(o,g)}catch(m){let y=m instanceof Error?m.message:String(m);return s.write(JSON.stringify({ok:!1,code:"FILE_WRITE_ERROR",message:`Cannot write to ${o}: ${y}`})+`
|
|
108
|
+
`),1}return r.write(`saved: ${o} (${g.length} bytes)
|
|
109
109
|
`),0}let f=u!==void 0?String(u):"?";return r.write(`attachment ${i}: filename=${d} mime_type=${l} size_bytes=${f}
|
|
110
110
|
`),r.write(`(pass --out <path> to save the decoded bytes to a file)
|
|
111
|
-
`),0}async function
|
|
112
|
-
`),1}}async function
|
|
113
|
-
`),1)}async function
|
|
114
|
-
`),1;let a={op:"update"};i!==void 0&&(a.display_name=i),o!==void 0&&(a.description=o);let c=await
|
|
115
|
-
`),1)}function
|
|
111
|
+
`),0}async function _f(n,e,t,r,s,i){switch(n){case"show":return wf(e,t,r,s,i);case"update":return vf(e,t,r,s,i);default:return i.write(JSON.stringify({ok:!1,code:"UNKNOWN_COMMAND",message:`Unknown profile subcommand: ${n??"(none)"}. Try --help.`})+`
|
|
112
|
+
`),1}}async function wf(n,e,t,r,s){let i=tt(n),o={op:"show"};i!==void 0&&(o.handle=i);let a=await ae(e,t,"profile",o);return a.ok?(Qi(a.data,r),0):(s.write(JSON.stringify(a.error)+`
|
|
113
|
+
`),1)}async function vf(n,e,t,r,s){let i=B(n,"--display-name"),o=B(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"})+`
|
|
114
|
+
`),1;let a={op:"update"};i!==void 0&&(a.display_name=i),o!==void 0&&(a.description=o);let c=await ae(e,t,"profile",a);return c.ok?(Qi(c.data,r),0):(s.write(JSON.stringify(c.error)+`
|
|
115
|
+
`),1)}function Qi(n,e){let t=n;if(!t){e.write(`(no profile data)
|
|
116
116
|
`);return}let r=t.handle??"(unknown)",s=t.display_name??"",i=t.role??"",o=t.description??"";if(e.write(`handle: ${r}
|
|
117
117
|
`),s&&e.write(`display_name: ${s}
|
|
118
118
|
`),i&&e.write(`role: ${i}
|
|
119
119
|
`),o&&e.write(`description: ${o}
|
|
120
120
|
`),t.avatar!==void 0){let a=Buffer.byteLength(t.avatar,"utf8");e.write(`avatar: (generated identicon, ${a} bytes)
|
|
121
|
-
`)}}async function
|
|
122
|
-
`);return}for(let s of r)e.write(
|
|
123
|
-
`)}function
|
|
121
|
+
`)}}async function ae(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 bf(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 Zi(n,e){let t=n,r=Array.isArray(t?.messages)?t.messages:[];if(r.length===0){e.write(`(no messages)
|
|
122
|
+
`);return}for(let s of r)e.write(bf(s)+`
|
|
123
|
+
`)}function B(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 Wn(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 eo(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 Vi,kf,to=A(()=>{"use strict";Vi={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".heic":"image/heic",".webp":"image/webp",".gif":"image/gif"};kf=`mio-agent agentcli \u2014 agent-facing message CLI (Slice 1)
|
|
124
124
|
|
|
125
125
|
Usage:
|
|
126
126
|
mio-agent agentcli message check --channel <#name>
|
|
@@ -183,37 +183,37 @@ Error codes (relayed from proxy):
|
|
|
183
183
|
CAPABILITY_DENIED launch lacks the required capability
|
|
184
184
|
UPSTREAM_UNREACHABLE proxy cannot reach the server
|
|
185
185
|
(and others from agentProxy.ts / the server)
|
|
186
|
-
`});var Xi={};Ce(Xi,{runAgentcliCommand:()=>gf});async function gf(){return Ji(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var Qi=R(()=>{"use strict";Ki()});import{execFileSync as ts}from"child_process";function Gn(n){return ts("security",["add-generic-password","-U","-s",qn,"-a",Hn,"-w",n]),`${qn}:${Hn}`}function lt(){return ts("security",["find-generic-password","-s",qn,"-a",Hn,"-w"]).toString().trim()}function Zi(){ts("security",["delete-generic-password","-s",qn,"-a",Hn])}var qn,Hn,Mt=R(()=>{"use strict";qn="io.miomioos.mio-agent",Hn="machine_token"});var ns=Y((b_,eo)=>{eo.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var ro=Y((k_,no)=>{var mf=ns();function to(n){this.mode=mf.MODE_8BIT_BYTE,this.data=n}to.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)}};no.exports=to});var rs=Y((S_,so)=>{var $e={glog:function(n){if(n<1)throw new Error("glog("+n+")");return $e.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return $e.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(ae=0;ae<8;ae++)$e.EXP_TABLE[ae]=1<<ae;var ae;for(ae=8;ae<256;ae++)$e.EXP_TABLE[ae]=$e.EXP_TABLE[ae-4]^$e.EXP_TABLE[ae-5]^$e.EXP_TABLE[ae-6]^$e.EXP_TABLE[ae-8];var ae;for(ae=0;ae<255;ae++)$e.LOG_TABLE[$e.EXP_TABLE[ae]]=ae;var ae;so.exports=$e});var ss=Y((x_,io)=>{var wt=rs();function Wn(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]}Wn.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]^=wt.gexp(wt.glog(this.get(t))+wt.glog(n.get(r)));return new Wn(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=wt.glog(this.get(0))-wt.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]^=wt.gexp(wt.glog(n.get(s))+e);return new Wn(t,0).mod(n)}};io.exports=Wn});var ao=Y((E_,oo)=>{oo.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var uo=Y((T_,lo)=>{var Pe=ns(),co=ss(),yf=rs(),dt=ao(),ge={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;ge.getBCHDigit(e)-ge.getBCHDigit(ge.G15)>=0;)e^=ge.G15<<ge.getBCHDigit(e)-ge.getBCHDigit(ge.G15);return(n<<10|e)^ge.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;ge.getBCHDigit(e)-ge.getBCHDigit(ge.G18)>=0;)e^=ge.G18<<ge.getBCHDigit(e)-ge.getBCHDigit(ge.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return ge.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case dt.PATTERN000:return(e+t)%2===0;case dt.PATTERN001:return e%2===0;case dt.PATTERN010:return t%3===0;case dt.PATTERN011:return(e+t)%3===0;case dt.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case dt.PATTERN101:return e*t%2+e*t%3===0;case dt.PATTERN110:return(e*t%2+e*t%3)%2===0;case dt.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new co([1],0),t=0;t<n;t++)e=e.multiply(new co([1,yf.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case Pe.MODE_NUMBER:return 10;case Pe.MODE_ALPHA_NUM:return 9;case Pe.MODE_8BIT_BYTE:return 8;case Pe.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case Pe.MODE_NUMBER:return 12;case Pe.MODE_ALPHA_NUM:return 11;case Pe.MODE_8BIT_BYTE:return 16;case Pe.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case Pe.MODE_NUMBER:return 14;case Pe.MODE_ALPHA_NUM:return 13;case Pe.MODE_8BIT_BYTE:return 16;case Pe.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}};lo.exports=ge});var is=Y((C_,fo)=>{fo.exports={L:1,M:0,Q:3,H:2}});var po=Y((R_,ho)=>{var jn=is();function je(n,e){this.totalCount=n,this.dataCount=e}je.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]];je.getRSBlocks=function(n,e){var t=je.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 je(a,c));return s};je.getRsBlockTable=function(n,e){switch(e){case jn.L:return je.RS_BLOCK_TABLE[(n-1)*4+0];case jn.M:return je.RS_BLOCK_TABLE[(n-1)*4+1];case jn.Q:return je.RS_BLOCK_TABLE[(n-1)*4+2];case jn.H:return je.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};ho.exports=je});var yo=Y((O_,mo)=>{function go(){this.buffer=[],this.length=0}go.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++}};mo.exports=go});var bo=Y((A_,vo)=>{var _f=ro(),ut=uo(),wf=ss(),_o=po(),wo=yo();function Je(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}Je.prototype={addData:function(n){var e=new _f(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=_o.getRSBlocks(n,this.errorCorrectLevel),t=new wo,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(),ut.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=Je.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=ut.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=ut.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=ut.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=ut.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=ut.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}}}};Je.PAD0=236;Je.PAD1=17;Je.createData=function(n,e,t){for(var r=_o.getRSBlocks(n,e),s=new wo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),ut.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(Je.PAD0,8),s.getLengthInBits()>=a*8));)s.put(Je.PAD1,8);return Je.createBytes(s,r)};Je.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=ut.getErrorCorrectPolynomial(d),f=new wf(i[a],u.getLength()-1),g=f.mod(u);o[a]=new Array(u.getLength()-1);for(var h=0;h<o[a].length;h++){var m=h+g.getLength()-o[a].length;o[a][h]=m>=0?g.get(m):0}}for(var _=0,k=0;k<e.length;k++)_+=e[k].totalCount;for(var E=new Array(_),b=0,S=0;S<r;S++)for(var O=0;O<e.length;O++)S<i[O].length&&(E[b++]=i[O][S]);for(var T=0;T<s;T++)for(var A=0;A<e.length;A++)T<o[A].length&&(E[b++]=o[A][T]);return E};vo.exports=Je});var as=Y((P_,So)=>{var vf=bo(),ko=is(),bf="\x1B[40m \x1B[0m",Jn="\x1B[47m \x1B[0m",kf=function(n){return n?bf:Jn},os=function(n){return{times:function(e){return new Array(e).join(n)}}},Sf=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};So.exports={error:ko.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new vf(-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(Sf(a,o));var l={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=os(l.BLACK_WHITE).times(a+3),f=os(l.WHITE_BLACK).times(a+3);s+=u+`
|
|
187
|
-
`;for(var
|
|
188
|
-
`}d||(s+=f)}else{var m=
|
|
189
|
-
`,r.modules.forEach(function(
|
|
190
|
-
`}),s+=m}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=
|
|
186
|
+
`});var no={};Ce(no,{runAgentcliCommand:()=>Sf});async function Sf(){return Xi(process.argv.slice(3),{stdin:process.stdin,stdout:process.stdout,stderr:process.stderr})}var ro=A(()=>{"use strict";to()});import{execFileSync as as}from"child_process";function Yn(n){return as("security",["add-generic-password","-U","-s",jn,"-a",Jn,"-w",n]),`${jn}:${Jn}`}function ht(){return as("security",["find-generic-password","-s",jn,"-a",Jn,"-w"]).toString().trim()}function so(){as("security",["delete-generic-password","-s",jn,"-a",Jn])}var jn,Jn,Ft=A(()=>{"use strict";jn="io.miomioos.mio-agent",Jn="machine_token"});var cs=z((M_,io)=>{io.exports={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8}});var co=z((L_,ao)=>{var Ef=cs();function oo(n){this.mode=Ef.MODE_8BIT_BYTE,this.data=n}oo.prototype={getLength:function(){return this.data.length},write:function(n){for(var e=0;e<this.data.length;e++)n.put(this.data.charCodeAt(e),8)}};ao.exports=oo});var ls=z(($_,lo)=>{var Fe={glog:function(n){if(n<1)throw new Error("glog("+n+")");return Fe.LOG_TABLE[n]},gexp:function(n){for(;n<0;)n+=255;for(;n>=256;)n-=255;return Fe.EXP_TABLE[n]},EXP_TABLE:new Array(256),LOG_TABLE:new Array(256)};for(ue=0;ue<8;ue++)Fe.EXP_TABLE[ue]=1<<ue;var ue;for(ue=8;ue<256;ue++)Fe.EXP_TABLE[ue]=Fe.EXP_TABLE[ue-4]^Fe.EXP_TABLE[ue-5]^Fe.EXP_TABLE[ue-6]^Fe.EXP_TABLE[ue-8];var ue;for(ue=0;ue<255;ue++)Fe.LOG_TABLE[Fe.EXP_TABLE[ue]]=ue;var ue;lo.exports=Fe});var ds=z((D_,uo)=>{var Et=ls();function Vn(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]}Vn.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]^=Et.gexp(Et.glog(this.get(t))+Et.glog(n.get(r)));return new Vn(e,0)},mod:function(n){if(this.getLength()-n.getLength()<0)return this;for(var e=Et.glog(this.get(0))-Et.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]^=Et.gexp(Et.glog(n.get(s))+e);return new Vn(t,0).mod(n)}};uo.exports=Vn});var ho=z((B_,fo)=>{fo.exports={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7}});var mo=z((F_,po)=>{var Me=cs(),go=ds(),xf=ls(),gt=ho(),ye={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;ye.getBCHDigit(e)-ye.getBCHDigit(ye.G15)>=0;)e^=ye.G15<<ye.getBCHDigit(e)-ye.getBCHDigit(ye.G15);return(n<<10|e)^ye.G15_MASK},getBCHTypeNumber:function(n){for(var e=n<<12;ye.getBCHDigit(e)-ye.getBCHDigit(ye.G18)>=0;)e^=ye.G18<<ye.getBCHDigit(e)-ye.getBCHDigit(ye.G18);return n<<12|e},getBCHDigit:function(n){for(var e=0;n!==0;)e++,n>>>=1;return e},getPatternPosition:function(n){return ye.PATTERN_POSITION_TABLE[n-1]},getMask:function(n,e,t){switch(n){case gt.PATTERN000:return(e+t)%2===0;case gt.PATTERN001:return e%2===0;case gt.PATTERN010:return t%3===0;case gt.PATTERN011:return(e+t)%3===0;case gt.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case gt.PATTERN101:return e*t%2+e*t%3===0;case gt.PATTERN110:return(e*t%2+e*t%3)%2===0;case gt.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}},getErrorCorrectPolynomial:function(n){for(var e=new go([1],0),t=0;t<n;t++)e=e.multiply(new go([1,xf.gexp(t)],0));return e},getLengthInBits:function(n,e){if(1<=e&&e<10)switch(n){case Me.MODE_NUMBER:return 10;case Me.MODE_ALPHA_NUM:return 9;case Me.MODE_8BIT_BYTE:return 8;case Me.MODE_KANJI:return 8;default:throw new Error("mode:"+n)}else if(e<27)switch(n){case Me.MODE_NUMBER:return 12;case Me.MODE_ALPHA_NUM:return 11;case Me.MODE_8BIT_BYTE:return 16;case Me.MODE_KANJI:return 10;default:throw new Error("mode:"+n)}else if(e<41)switch(n){case Me.MODE_NUMBER:return 14;case Me.MODE_ALPHA_NUM:return 13;case Me.MODE_8BIT_BYTE:return 16;case Me.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}};po.exports=ye});var us=z((U_,yo)=>{yo.exports={L:1,M:0,Q:3,H:2}});var wo=z((H_,_o)=>{var zn=us();function Ve(n,e){this.totalCount=n,this.dataCount=e}Ve.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]];Ve.getRSBlocks=function(n,e){var t=Ve.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 Ve(a,c));return s};Ve.getRsBlockTable=function(n,e){switch(e){case zn.L:return Ve.RS_BLOCK_TABLE[(n-1)*4+0];case zn.M:return Ve.RS_BLOCK_TABLE[(n-1)*4+1];case zn.Q:return Ve.RS_BLOCK_TABLE[(n-1)*4+2];case zn.H:return Ve.RS_BLOCK_TABLE[(n-1)*4+3];default:return}};_o.exports=Ve});var ko=z((q_,bo)=>{function vo(){this.buffer=[],this.length=0}vo.prototype={get:function(n){var e=Math.floor(n/8);return(this.buffer[e]>>>7-n%8&1)==1},put:function(n,e){for(var t=0;t<e;t++)this.putBit((n>>>e-t-1&1)==1)},getLengthInBits:function(){return this.length},putBit:function(n){var e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),n&&(this.buffer[e]|=128>>>this.length%8),this.length++}};bo.exports=vo});var To=z((G_,xo)=>{var Tf=co(),pt=mo(),Cf=ds(),So=wo(),Eo=ko();function ze(n,e){this.typeNumber=n,this.errorCorrectLevel=e,this.modules=null,this.moduleCount=0,this.dataCache=null,this.dataList=[]}ze.prototype={addData:function(n){var e=new Tf(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=So.getRSBlocks(n,this.errorCorrectLevel),t=new Eo,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(),pt.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=ze.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=pt.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=pt.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=pt.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=pt.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=pt.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}}}};ze.PAD0=236;ze.PAD1=17;ze.createData=function(n,e,t){for(var r=So.getRSBlocks(n,e),s=new Eo,i=0;i<t.length;i++){var o=t[i];s.put(o.mode,4),s.put(o.getLength(),pt.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(ze.PAD0,8),s.getLengthInBits()>=a*8));)s.put(ze.PAD1,8);return ze.createBytes(s,r)};ze.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=pt.getErrorCorrectPolynomial(d),f=new Cf(i[a],u.getLength()-1),h=f.mod(u);o[a]=new Array(u.getLength()-1);for(var g=0;g<o[a].length;g++){var m=g+h.getLength()-o[a].length;o[a][g]=m>=0?h.get(m):0}}for(var y=0,b=0;b<e.length;b++)y+=e[b].totalCount;for(var x=new Array(y),v=0,S=0;S<r;S++)for(var M=0;M<e.length;M++)S<i[M].length&&(x[v++]=i[M][S]);for(var T=0;T<s;T++)for(var N=0;N<e.length;N++)T<o[N].length&&(x[v++]=o[N][T]);return x};xo.exports=ze});var hs=z((W_,Ro)=>{var Rf=To(),Co=us(),Of="\x1B[40m \x1B[0m",Kn="\x1B[47m \x1B[0m",Af=function(n){return n?Of:Kn},fs=function(n){return{times:function(e){return new Array(e).join(n)}}},Pf=function(n,e){for(var t=new Array(n),r=0;r<n;r++)t[r]=e;return t};Ro.exports={error:Co.L,generate:function(n,e,t){typeof e=="function"&&(t=e,e={});var r=new Rf(-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(Pf(a,o));var l={WHITE_ALL:"\u2588",WHITE_BLACK:"\u2580",BLACK_WHITE:"\u2584",BLACK_ALL:" "},u=fs(l.BLACK_WHITE).times(a+3),f=fs(l.WHITE_BLACK).times(a+3);s+=u+`
|
|
187
|
+
`;for(var h=0;h<a;h+=2){s+=l.WHITE_ALL;for(var g=0;g<a;g++)c[h][g]===o&&c[h+1][g]===o?s+=l.WHITE_ALL:c[h][g]===o&&c[h+1][g]===i?s+=l.WHITE_BLACK:c[h][g]===i&&c[h+1][g]===o?s+=l.BLACK_WHITE:s+=l.BLACK_ALL;s+=l.WHITE_ALL+`
|
|
188
|
+
`}d||(s+=f)}else{var m=fs(Kn).times(r.getModuleCount()+3);s+=m+`
|
|
189
|
+
`,r.modules.forEach(function(y){s+=Kn,s+=y.map(Af).join(""),s+=Kn+`
|
|
190
|
+
`}),s+=m}t?t(s):console.log(s)},setErrorLevel:function(n){this.error=Co[n]||this.error}}});var No={};Ce(No,{runLogin:()=>Bf});import{parseArgs as If}from"node:util";import hn from"node:os";import{mkdirSync as Nf,writeFileSync as Mf,existsSync as Lf}from"node:fs";import{join as Oo}from"node:path";function Df(n){return new Promise(e=>setTimeout(e,n))}function Io(){console.log(`Usage: mio-agent login [--server <url>] [--device-name <name>]
|
|
191
191
|
|
|
192
192
|
Zero-touch machine enrollment via QR + phone approval.
|
|
193
193
|
|
|
194
194
|
Options:
|
|
195
|
-
--server <url> MioServer base URL (default: ${
|
|
195
|
+
--server <url> MioServer base URL (default: ${gs})
|
|
196
196
|
--device-name <name> Friendly name for this machine (default: hostname)
|
|
197
197
|
--help Show this message
|
|
198
|
-
`)}async function
|
|
199
|
-
`);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=
|
|
200
|
-
`);return b.substr(0,b.length-2)},this.getRequestHeader=function(b){return typeof b=="string"&&d[b]?d[b]:""},this.send=function(b){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(f)throw new Error("INVALID_STATE_ERR: send has already been called");var S=!1,O=!1,T=pa.parse(o.url),A;switch(T.protocol){case"https:":S=!0;case"http:":A=T.hostname;break;case"file:":O=!0;break;case void 0:case"":A="localhost";break;default:throw new Error("Protocol not supported.")}if(O){if(o.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(o.async)$t.readFile(unescape(T.pathname),function(j,re){j?e.handleError(j,j.errno||-1):(e.status=200,e.responseText=re.toString("utf8"),e.response=re,E(e.DONE))});else try{this.response=$t.readFileSync(unescape(T.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,E(e.DONE)}catch(j){this.handleError(j,j.errno||-1)}return}var G=T.port||(S?443:80),q=T.pathname+(T.search?T.search:"");if(d.Host=A,S&&G===443||G===80||(d.Host+=":"+T.port),o.user){typeof o.password>"u"&&(o.password="");var F=new Buffer(o.user+":"+o.password);d.Authorization="Basic "+F.toString("base64")}if(o.method==="GET"||o.method==="HEAD")b=null;else if(b){d["Content-Length"]=Buffer.isBuffer(b)?b.length:Buffer.byteLength(b);var W=Object.keys(d);W.some(function(j){return j.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(d["Content-Length"]=0);var K=n.agent||!1,H={host:A,port:G,path:q,method:o.method,headers:d,agent:K};if(S&&(H.pfx=n.pfx,H.key=n.key,H.passphrase=n.passphrase,H.cert=n.cert,H.ca=n.ca,H.ciphers=n.ciphers,H.rejectUnauthorized=n.rejectUnauthorized!==!1),g=!1,o.async){var I=S?r.request:t.request;f=!0,e.dispatchEvent("readystatechange");var y=function(j){if(i=j,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var re=pa.parse(o.url);A=re.hostname;var le={hostname:re.hostname,port:re.port,path:re.path,method:i.statusCode===303?"GET":o.method,headers:d};S&&(le.pfx=n.pfx,le.key=n.key,le.passphrase=n.passphrase,le.cert=n.cert,le.ca=n.ca,le.ciphers=n.ciphers,le.rejectUnauthorized=n.rejectUnauthorized!==!1),s=I(le,y).on("error",w),s.end();return}E(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(de){if(de){var xe=Buffer.from(de);e.response=Buffer.concat([e.response,xe])}f&&E(e.LOADING)}),i.on("end",function(){f&&(f=!1,E(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(de){e.handleError(de)})},w=function(j){if(s.reusedSocket&&j.code==="ECONNRESET")return I(H,y).on("error",w);e.handleError(j)};s=I(H,y).on("error",w),n.autoUnref&&s.on("socket",j=>{j.unref()}),b&&s.write(b),s.end(),e.dispatchEvent("loadstart")}else{var v=".node-xmlhttprequest-content-"+process.pid,C=".node-xmlhttprequest-sync-"+process.pid;$t.writeFileSync(C,"","utf8");for(var $="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(S?"s":"")+".request;var options = "+JSON.stringify(H)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+v+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+C+"');});response.on('error', function(error) {fs.writeFileSync('"+v+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+C+"');});}).on('error', function(error) {fs.writeFileSync('"+v+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+C+"');});"+(b?"req.write('"+JSON.stringify(b).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",M=jf(process.argv[0],["-e",$]),ne;$t.existsSync(C););if(e.responseText=$t.readFileSync(v,"utf8"),M.stdin.end(),$t.unlinkSync(v),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var J=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(J,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var P=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:P.data.headers},e.responseText=P.data.text,e.response=Buffer.from(P.data.data,"base64"),E(e.DONE,!0)}}},this.handleError=function(b,S){this.status=S||0,this.statusText=b,this.responseText=b.stack,g=!0,E(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),g=h=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||f)&&this.readyState!==this.DONE&&(f=!1,E(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(b,S){b in m||(m[b]=[]),m[b].push(S)},this.removeEventListener=function(b,S){b in m&&(m[b]=m[b].filter(function(O){return O!==S}))},this.dispatchEvent=function(b){if(typeof e["on"+b]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+b]()},0):e["on"+b]()),b in m)for(let S=0,O=m[b].length;S<O;S++)this.readyState===this.DONE?setTimeout(function(){m[b][S].call(e)},0):m[b][S].call(e)};var E=function(b){if(!(e.readyState===b||e.readyState===e.UNSENT&&h)&&(e.readyState=b,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let S;h?S="abort":g?S="error":S="load",e.dispatchEvent(S),e.dispatchEvent("loadend")}}}});var Ue,fn,hn,Vn=R(()=>{Ue=Object.create(null);Ue.open="0";Ue.close="1";Ue.ping="2";Ue.pong="3";Ue.message="4";Ue.upgrade="5";Ue.noop="6";fn=Object.create(null);Object.keys(Ue).forEach(n=>{fn[Ue[n]]=n});hn={type:"error",data:"parser error"}});function _a(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(ya(n.data,!1));pn(n,!0,t=>{ps||(ps=new TextEncoder),e(ps.encode(t))})}var pn,ya,ps,wa=R(()=>{Vn();pn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+ya(e,!0).toString("base64")):r(Ue[n]+(e||"")),ya=(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 gn,va,ba=R(()=>{Vn();gn=(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 fn[t]?n.length>1?{type:fn[t],data:n.substring(1)}:{type:fn[t]}:hn},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 Ea(){return new TransformStream({transform(n,e){_a(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 zn(n){return n.reduce((e,t)=>e+t.length,0)}function Kn(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 Ta(n,e){gs||(gs=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(zn(t)<1)break;let c=Kn(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(zn(t)<2)break;let c=Kn(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(zn(t)<8)break;let c=Kn(t,8),d=new DataView(c.buffer,c.byteOffset,c.length),l=d.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(hn);break}s=l*Math.pow(2,32)+d.getUint32(4),r=3}else{if(zn(t)<s)break;let c=Kn(t,s);a.enqueue(gn(i?c:gs.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(hn);break}}}})}var ka,Sa,xa,gs,ms,Dt=R(()=>{wa();ba();Vn();ka="",Sa=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{pn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(ka))})})},xa=(n,e)=>{let t=n.split(ka),r=[];for(let s=0;s<t.length;s++){let i=gn(t[s],e);if(r.push(i),i.type==="error")break}return r};ms=4});var bt=Y(Ca=>{Ca.Emitter=we;function we(n){if(n)return Jf(n)}function Jf(n){for(var e in we.prototype)n[e]=we.prototype[e];return n}we.prototype.on=we.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};we.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};we.prototype.off=we.prototype.removeListener=we.prototype.removeAllListeners=we.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};we.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};we.prototype.emitReserved=we.prototype.emit;we.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};we.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function Oa(){return new ys}function Yf(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 Qe,ve,Ra,ys,kt=R(()=>{Qe=process.nextTick,ve=global,Ra="nodebuffer";ys=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=Yf(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 Xn(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function Ze(n,e){e.useNativeTimers?(n.setTimeoutFn=Vf.bind(ve),n.clearTimeoutFn=zf.bind(ve)):(n.setTimeoutFn=ve.setTimeout.bind(ve),n.clearTimeoutFn=ve.clearTimeout.bind(ve))}function Aa(n){return typeof n=="string"?Xf(n):Math.ceil((n.byteLength||n.size)*Kf)}function Xf(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 Qn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}var Vf,zf,Kf,St=R(()=>{kt();Vf=ve.setTimeout,zf=ve.clearTimeout;Kf=1.33});function Pa(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Ia(n){let e={},t=n.split("&");for(let r=0,s=t.length;r<s;r++){let i=t[r].split("=");e[decodeURIComponent(i[0])]=decodeURIComponent(i[1])}return e}var _s=R(()=>{});var Ma=Y((hw,Na)=>{var Bt=1e3,Ft=Bt*60,Ut=Ft*60,xt=Ut*24,Qf=xt*7,Zf=xt*365.25;Na.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return eh(n);if(t==="number"&&isFinite(n))return e.long?nh(n):th(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function eh(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*Zf;case"weeks":case"week":case"w":return t*Qf;case"days":case"day":case"d":return t*xt;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Ut;case"minutes":case"minute":case"mins":case"min":case"m":return t*Ft;case"seconds":case"second":case"secs":case"sec":case"s":return t*Bt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function th(n){var e=Math.abs(n);return e>=xt?Math.round(n/xt)+"d":e>=Ut?Math.round(n/Ut)+"h":e>=Ft?Math.round(n/Ft)+"m":e>=Bt?Math.round(n/Bt)+"s":n+"ms"}function nh(n){var e=Math.abs(n);return e>=xt?Zn(n,e,xt,"day"):e>=Ut?Zn(n,e,Ut,"hour"):e>=Ft?Zn(n,e,Ft,"minute"):e>=Bt?Zn(n,e,Bt,"second"):n+" ms"}function Zn(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var ws=Y((pw,La)=>{function rh(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=Ma(),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 f=0;f<l.length;f++)u=(u<<5)-u+l.charCodeAt(f),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,f=null,g,h;function m(..._){if(!m.enabled)return;let k=m,E=Number(new Date),b=E-(u||E);k.diff=b,k.prev=u,k.curr=E,u=E,_[0]=t.coerce(_[0]),typeof _[0]!="string"&&_.unshift("%O");let S=0;_[0]=_[0].replace(/%([a-zA-Z%])/g,(T,A)=>{if(T==="%%")return"%";S++;let G=t.formatters[A];if(typeof G=="function"){let q=_[S];T=G.call(k,q),_.splice(S,1),S--}return T}),t.formatArgs.call(k,_),(k.log||t.log).apply(k,_)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),m.extend=r,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(g!==t.namespaces&&(g=t.namespaces,h=t.enabled(l)),h),set:_=>{f=_}}),typeof t.init=="function"&&t.init(m),m}function r(l,u){let f=t(this.namespace+(typeof u>"u"?":":u)+l);return f.log=this.log,f}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 f of u)f[0]==="-"?t.skips.push(f.slice(1)):t.names.push(f)}function i(l,u){let f=0,g=0,h=-1,m=0;for(;f<l.length;)if(g<u.length&&(u[g]===l[f]||u[g]==="*"))u[g]==="*"?(h=g,m=f,g++):(f++,g++);else if(h!==-1)g=h+1,m++,f=m;else return!1;for(;g<u.length&&u[g]==="*";)g++;return g===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}La.exports=rh});var $a=Y((Ee,er)=>{Ee.formatArgs=ih;Ee.save=oh;Ee.load=ah;Ee.useColors=sh;Ee.storage=ch();Ee.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`."))}})();Ee.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 sh(){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 ih(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)}Ee.log=console.debug||console.log||(()=>{});function oh(n){try{n?Ee.storage.setItem("debug",n):Ee.storage.removeItem("debug")}catch{}}function ah(){let n;try{n=Ee.storage.getItem("debug")||Ee.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function ch(){try{return localStorage}catch{}}er.exports=ws()(Ee);var{formatters:lh}=er.exports;lh.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Ba=Y((he,nr)=>{var dh=V("tty"),tr=V("util");he.init=yh;he.log=ph;he.formatArgs=fh;he.save=gh;he.load=mh;he.useColors=uh;he.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`.");he.colors=[6,2,3,4,5,1];try{let n=V("supports-color");n&&(n.stderr||n).level>=2&&(he.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{}he.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 uh(){return"colors"in he.inspectOpts?!!he.inspectOpts.colors:dh.isatty(process.stderr.fd)}function fh(n){let{namespace:e,useColors:t}=this;if(t){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${s};1m${e} \x1B[0m`;n[0]=i+n[0].split(`
|
|
198
|
+
`)}async function Bf(n){let e;try{({values:e}=If({args:n,options:{server:{type:"string",default:gs},"device-name":{type:"string",default:hn.hostname()},help:{type:"boolean",default:!1}},strict:!0}))}catch(v){let S=v instanceof Error?v.message:String(v);return console.error(`Error: ${S}`),Io(),1}if(e.help)return Io(),0;let t=(e.server??gs).replace(/\/+$/,""),r=e["device-name"]??hn.hostname(),s=hn.platform(),i=hn.arch(),o;try{let v=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(!v.ok)return console.error(`Failed to create enrollment intent (HTTP ${v.status}). Check --server (currently ${t}).`),1;o=await v.json()}catch(v){let S=v instanceof Error?v.message:String(v);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 d=await Promise.resolve().then(()=>te(hs(),1)).catch(()=>null),l=d?.default??d,u=typeof l?.generate=="function"?(v,S,M)=>l.generate(v,S,M):null;u?await new Promise(v=>{u(c,{small:!0},S=>{console.log(S),v()})}):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 f=Date.now(),h=Ao,g=null;for(;Date.now()-f<$f;){await Df(h);try{let v=await fetch(`${t}/api/v1/enrollment-intents/${o.intent_id}?code=${encodeURIComponent(o.opaque_code)}`,{method:"GET"});if(v.status===200){g=await v.json();break}if(v.status===202){h=Ao;continue}if(v.status===403)return console.error("Enrollment code became invalid (expired, canceled, or already consumed). Re-run `mio-agent login`."),1;h=Math.min(h*2,Po);continue}catch{h=Math.min(h*2,Po);continue}}if(!g)return console.error("Enrollment timed out (5 min). Re-run `mio-agent login` to retry."),1;let m=Yn(g.machine_token),y=Oo(hn.homedir(),".mio");Lf(y)||Nf(y,{recursive:!0,mode:448});let b=Oo(y,"agent.json"),x={machine_id:g.machine_id,org_id:g.org_id,workroom_id:g.workroom_id,server_url:t,keychain_item_ref:m,runtimes:[],token_buffer:!1};return Mf(b,JSON.stringify(x,null,2),{mode:384}),console.log(""),console.log(`Successfully enrolled as "${r}" in workroom ${g.workroom_id.slice(0,8)}.`),console.log("Config: ~/.mio/agent.json (0600)"),console.log(`Token: macOS Keychain (${m})`),console.log(""),console.log("Run `mio-agent doctor` to verify."),0}var gs,Ao,Po,$f,Mo=A(()=>{"use strict";Ft();gs="https://mio.wdao.chat",Ao=2e3,Po=3e4,$f=300*1e3});var $o={};Ce($o,{runLogs:()=>qf});import{existsSync as ps}from"node:fs";import{homedir as Ff}from"node:os";import{join as Lo}from"node:path";import{spawn as Uf}from"node:child_process";function Hf(){let n=Ff(),e=Lo(n,".mio","logs","mio-agent.log"),t=Lo(n,".mio","logs","mio-agent-error.log"),r="/tmp/mio-agent.log",s=[];return ps(e)&&s.push(e),ps(t)&&s.push(t),s.length===0&&ps(r)&&s.push(r),s}async function qf(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=Hf();if(r.length===0)return console.error("No log file found."),console.error(" Looked for: ~/.mio/logs/mio-agent.log and /tmp/mio-agent.log"),console.error(" Run `mio-agent start` or `mio-agent install --background --version <v>` first."),1;console.error(`# tailing: ${r.join(", ")}
|
|
199
|
+
`);let s=e?["-n",String(t),"-F",...r]:["-n",String(t),...r],i=Uf("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 Do=A(()=>{"use strict"});function p(n,e,t,r){let s={time:new Date().toISOString(),level:n,component:e,message:t,...r};console.log(JSON.stringify(s))}function k(n,e,t){p("error",n,e,{error:t instanceof Error?t.message:String(t)})}var ce=A(()=>{"use strict"});import{readFileSync as Gf,writeFileSync as Wf,mkdirSync as ms,chmodSync as jf,existsSync as Bo}from"fs";import{homedir as Jf}from"os";import{join as gn}from"path";function pn(){ms(he,{recursive:!0,mode:448}),ms(Yf,{recursive:!0,mode:448}),ms(xt,{recursive:!0,mode:448})}function Uo(){return Bo(Ut)}function Ue(){if(!Bo(Ut))throw new Error(`No config at ${Ut}. Run: mio-agent login`);return JSON.parse(Gf(Ut,"utf-8"))}function Xn(n){pn();let e=JSON.stringify(n,null,2);Wf(Ut,e,{encoding:"utf-8",mode:384}),jf(Ut,384)}var he,Ut,Yf,xt,sw,Fo,He=A(()=>{"use strict";he=gn(Jf(),".mio"),Ut=gn(he,"agent.json"),Yf=gn(he,"logs"),xt=gn(he,"tmp"),sw=gn(he,"agent.sock"),Fo=7878});import{readFileSync as Vf,writeFileSync as zf,existsSync as Kf}from"fs";import{join as Xf}from"path";function Ho(){if(!Kf(ys))return{};try{return JSON.parse(Vf(ys,"utf-8"))}catch{return{}}}function Qf(n){pn(),zf(ys,JSON.stringify(n,null,2),{mode:384})}function qo(){let n=Ho();return new Map(Object.entries(n))}function Go(n,e){let t=Ho(),r=t[n];(!r||BigInt(e)>BigInt(r))&&(t[n]=e,Qf(t))}var ys,Wo=A(()=>{"use strict";He();ys=Xf(he,"cursors.json")});async function Z(n,e={}){let t=await fetch(n,{...e,headers:{"Content-Type":"application/json",...e.headers}});if(!t.ok){let r=await t.text().catch(()=>""),s="UNKNOWN";try{s=JSON.parse(r)?.error?.code??s}catch{}throw new mn(t.status,s,`API ${e.method??"GET"} ${n} \u2192 ${t.status} [${s}]`)}if(t.status!==204)return t.json()}function ge(n){return{Authorization:`Bearer ${n}`}}async function jo(n,e){return Z(`${n}/api/v1/auth/machines/refresh`,{method:"POST",headers:ge(e)})}async function Jo(n,e,t){return Z(`${n}/api/v1/workrooms/${e}/sessions`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function Yo(n,e,t){await Z(`${n}/api/v1/sessions/${e}/heartbeat`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function Vo(n,e,t=!1){await Z(`${n}/api/v1/machines/heartbeat`,{method:"POST",headers:ge(e),body:JSON.stringify(t?{going_offline:!0}:{})})}async function zo(n,e,t,r){await Z(`${n}/api/v1/sessions/${e}/status`,{method:"PATCH",headers:ge(r),body:JSON.stringify({status:t})})}async function Ko(n,e,t,r){let s=`${n}/api/v1/workrooms/${e}/events?after_seq=${t}`;return Z(s,{headers:ge(r)})}async function Xo(n,e,t){return Z(`${n}/api/v1/actions/${e}`,{headers:ge(t)})}async function Qo(n,e,t){return Z(`${n}/api/v1/approvals/${e}`,{headers:ge(t)})}async function Zo(n,e,t,r){let s=r?{approval_id:r}:{};return Z(`${n}/api/v1/actions/${e}/fire`,{method:"POST",headers:ge(t),body:JSON.stringify(s)})}async function ea(n,e,t){await Z(`${n}/api/v1/actions/${e}/cancel`,{method:"POST",headers:ge(t),body:JSON.stringify({})})}async function ta(n,e,t,r,s,i){let o=new URLSearchParams;r!==void 0&&o.set("after_seq",r),s!==void 0&&o.set("limit",String(s));let a=o.toString()?`?${o.toString()}`:"",c=`${n}/api/v1/workrooms/${e}/channels/${t}/messages${a}`,d=await Z(c,{headers:ge(i)});return{messages:d.messages,hasMore:d.has_more}}async function Qn(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),Z(`${n}/api/v1/workrooms/${e}/channels/${t}/messages`,{method:"POST",headers:ge(s),body:JSON.stringify(i)})}async function na(n,e,t){return(await Z(`${n}/api/v1/workrooms/${e}/members`,{headers:ge(t)})).members??[]}async function ra(n,e,t){return Z(`${n}/api/v1/workrooms/${e}/roster`,{headers:ge(t)})}async function sa(n,e,t){return(await Z(`${n}/api/v1/workrooms/${e}/channels`,{headers:ge(t)})).channels??[]}async function ia(n,e,t){return(await Z(`${n}/internal/agent-api/channels`,{headers:{...ge(e),"X-Mio-Agent-Id":t}})).channels??[]}async function oa(n,e,t,r){return(await Z(`${n}/internal/agent-api/tasks/list?channel=${encodeURIComponent(r)}`,{headers:{...ge(e),"X-Mio-Agent-Id":t}})).tasks??[]}function Le(n,e){return{...ge(n),"X-Mio-Agent-Id":e}}async function aa(n,e,t,r){return(await Z(`${n}/internal/agent-api/reminders/schedule`,{method:"POST",headers:Le(e,t),body:JSON.stringify(r)})).reminder}async function ca(n,e,t){return(await Z(`${n}/internal/agent-api/reminders/list`,{headers:Le(e,t)})).reminders??[]}async function la(n,e,t,r){return(await Z(`${n}/internal/agent-api/reminders/snooze`,{method:"POST",headers:Le(e,t),body:JSON.stringify(r)})).reminder}async function da(n,e,t,r){return(await Z(`${n}/internal/agent-api/reminders/update`,{method:"POST",headers:Le(e,t),body:JSON.stringify(r)})).reminder}async function ua(n,e,t,r){return(await Z(`${n}/internal/agent-api/reminders/cancel`,{method:"POST",headers:Le(e,t),body:JSON.stringify(r)})).reminder}async function fa(n,e,t){return(await Z(`${n}/internal/agent-api/reminders/log`,{headers:Le(e,t)})).events??[]}async function ha(n,e,t,r){await Z(`${n}/internal/agent-api/typing`,{method:"POST",headers:Le(e,t),body:JSON.stringify({agent_id:t,...r})})}async function ga(n,e,t,r){await Z(`${n}/internal/agent-api/status`,{method:"POST",headers:Le(e,t),body:JSON.stringify({agent_id:t,...r})})}async function pa(n,e,t,r){await Z(`${n}/internal/agent-api/reminders/fire`,{method:"POST",headers:Le(e,t),body:JSON.stringify(r)})}async function ma(n,e,t,r,s){let i=new URLSearchParams;s!==void 0&&i.set("limit",String(s));let o=i.toString()?`?${i.toString()}`:"";return(await Z(`${n}/internal/agent-api/threads/${encodeURIComponent(r)}/replies${o}`,{headers:Le(e,t)})).messages??[]}async function ya(n,e,t,r){return(await Z(`${n}/internal/agent-api/messages/${encodeURIComponent(r)}`,{headers:Le(e,t)})).message}async function _a(n,e,t,r){return Z(`${n}/internal/agent-api/attachments/${r}`,{headers:Le(e,t)})}var mn,Zn=A(()=>{"use strict";mn=class extends Error{constructor(t,r,s){super(s);this.statusCode=t;this.errorCode=r;this.name="ApiError"}statusCode;errorCode;get isDefinitiveRejection(){return this.statusCode>=400&&this.statusCode<500}}});var ba=z((uw,va)=>{var Ht=Q("fs"),wa=Q("url"),Zf=Q("child_process").spawn;va.exports=_s;_s.XMLHttpRequest=_s;function _s(n){"use strict";n=n||{};var e=this,t=Q("http"),r=Q("https"),s,i,o={},a=!1,c={"User-Agent":"node-XMLHttpRequest",Accept:"*/*"},d=Object.assign({},c),l=["accept-charset","accept-encoding","access-control-request-headers","access-control-request-method","connection","content-length","content-transfer-encoding","cookie","cookie2","date","expect","host","keep-alive","origin","referer","te","trailer","transfer-encoding","upgrade","via"],u=["TRACE","TRACK","CONNECT"],f=!1,h=!1,g=!1,m={};this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.readyState=this.UNSENT,this.onreadystatechange=null,this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),this.status=null,this.statusText=null;var y=function(v){return a||v&&l.indexOf(v.toLowerCase())===-1},b=function(v){return v&&u.indexOf(v)===-1};this.open=function(v,S,M,T,N){if(this.abort(),h=!1,g=!1,!b(v))throw new Error("SecurityError: Request method not allowed");o={method:v,url:S.toString(),async:typeof M!="boolean"?!0:M,user:T||null,password:N||null},x(this.OPENED)},this.setDisableHeaderCheck=function(v){a=v},this.setRequestHeader=function(v,S){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: setRequestHeader can only be called when state is OPEN");if(!y(v))return console.warn('Refused to set unsafe header "'+v+'"'),!1;if(f)throw new Error("INVALID_STATE_ERR: send flag is true");return d[v]=S,!0},this.getResponseHeader=function(v){return typeof v=="string"&&this.readyState>this.OPENED&&i.headers[v.toLowerCase()]&&!h?i.headers[v.toLowerCase()]:null},this.getAllResponseHeaders=function(){if(this.readyState<this.HEADERS_RECEIVED||h)return"";var v="";for(var S in i.headers)S!=="set-cookie"&&S!=="set-cookie2"&&(v+=S+": "+i.headers[S]+`\r
|
|
200
|
+
`);return v.substr(0,v.length-2)},this.getRequestHeader=function(v){return typeof v=="string"&&d[v]?d[v]:""},this.send=function(v){if(this.readyState!=this.OPENED)throw new Error("INVALID_STATE_ERR: connection must be opened before send() is called");if(f)throw new Error("INVALID_STATE_ERR: send has already been called");var S=!1,M=!1,T=wa.parse(o.url),N;switch(T.protocol){case"https:":S=!0;case"http:":N=T.hostname;break;case"file:":M=!0;break;case void 0:case"":N="localhost";break;default:throw new Error("Protocol not supported.")}if(M){if(o.method!=="GET")throw new Error("XMLHttpRequest: Only GET method is supported");if(o.async)Ht.readFile(unescape(T.pathname),function(F,le){F?e.handleError(F,F.errno||-1):(e.status=200,e.responseText=le.toString("utf8"),e.response=le,x(e.DONE))});else try{this.response=Ht.readFileSync(unescape(T.pathname)),this.responseText=this.response.toString("utf8"),this.status=200,x(e.DONE)}catch(F){this.handleError(F,F.errno||-1)}return}var j=T.port||(S?443:80),W=T.pathname+(T.search?T.search:"");if(d.Host=N,S&&j===443||j===80||(d.Host+=":"+T.port),o.user){typeof o.password>"u"&&(o.password="");var H=new Buffer(o.user+":"+o.password);d.Authorization="Basic "+H.toString("base64")}if(o.method==="GET"||o.method==="HEAD")v=null;else if(v){d["Content-Length"]=Buffer.isBuffer(v)?v.length:Buffer.byteLength(v);var Y=Object.keys(d);Y.some(function(F){return F.toLowerCase()==="content-type"})||(d["Content-Type"]="text/plain;charset=UTF-8")}else o.method==="POST"&&(d["Content-Length"]=0);var K=n.agent||!1,q={host:N,port:j,path:W,method:o.method,headers:d,agent:K};if(S&&(q.pfx=n.pfx,q.key=n.key,q.passphrase=n.passphrase,q.cert=n.cert,q.ca=n.ca,q.ciphers=n.ciphers,q.rejectUnauthorized=n.rejectUnauthorized!==!1),h=!1,o.async){var ne=S?r.request:t.request;f=!0,e.dispatchEvent("readystatechange");var w=function(F){if(i=F,i.statusCode===302||i.statusCode===303||i.statusCode===307){o.url=i.headers.location;var le=wa.parse(o.url);N=le.hostname;var ie={hostname:le.hostname,port:le.port,path:le.path,method:i.statusCode===303?"GET":o.method,headers:d};S&&(ie.pfx=n.pfx,ie.key=n.key,ie.passphrase=n.passphrase,ie.cert=n.cert,ie.ca=n.ca,ie.ciphers=n.ciphers,ie.rejectUnauthorized=n.rejectUnauthorized!==!1),s=ne(ie,w).on("error",_),s.end();return}x(e.HEADERS_RECEIVED),e.status=i.statusCode,i.on("data",function(I){if(I){var Pe=Buffer.from(I);e.response=Buffer.concat([e.response,Pe])}f&&x(e.LOADING)}),i.on("end",function(){f&&(f=!1,x(e.DONE),e.responseText=e.response.toString("utf8"))}),i.on("error",function(I){e.handleError(I)})},_=function(F){if(s.reusedSocket&&F.code==="ECONNRESET")return ne(q,w).on("error",_);e.handleError(F)};s=ne(q,w).on("error",_),n.autoUnref&&s.on("socket",F=>{F.unref()}),v&&s.write(v),s.end(),e.dispatchEvent("loadstart")}else{var P=".node-xmlhttprequest-content-"+process.pid,R=".node-xmlhttprequest-sync-"+process.pid;Ht.writeFileSync(R,"","utf8");for(var C="var http = require('http'), https = require('https'), fs = require('fs');var doRequest = http"+(S?"s":"")+".request;var options = "+JSON.stringify(q)+";var responseText = '';var responseData = Buffer.alloc(0);var req = doRequest(options, function(response) {response.on('data', function(chunk) { var data = Buffer.from(chunk); responseText += data.toString('utf8'); responseData = Buffer.concat([responseData, data]);});response.on('end', function() {fs.writeFileSync('"+P+"', JSON.stringify({err: null, data: {statusCode: response.statusCode, headers: response.headers, text: responseText, data: responseData.toString('base64')}}), 'utf8');fs.unlinkSync('"+R+"');});response.on('error', function(error) {fs.writeFileSync('"+P+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});}).on('error', function(error) {fs.writeFileSync('"+P+"', 'NODE-XMLHTTPREQUEST-ERROR:' + JSON.stringify(error), 'utf8');fs.unlinkSync('"+R+"');});"+(v?"req.write('"+JSON.stringify(v).slice(1,-1).replace(/'/g,"\\'")+"');":"")+"req.end();",O=Zf(process.argv[0],["-e",C]),E;Ht.existsSync(R););if(e.responseText=Ht.readFileSync(P,"utf8"),O.stdin.end(),Ht.unlinkSync(P),e.responseText.match(/^NODE-XMLHTTPREQUEST-ERROR:/)){var L=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-ERROR:/,""));e.handleError(L,503)}else{e.status=e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:([0-9]*),.*/,"$1");var X=JSON.parse(e.responseText.replace(/^NODE-XMLHTTPREQUEST-STATUS:[0-9]*,(.*)/,"$1"));i={statusCode:e.status,headers:X.data.headers},e.responseText=X.data.text,e.response=Buffer.from(X.data.data,"base64"),x(e.DONE,!0)}}},this.handleError=function(v,S){this.status=S||0,this.statusText=v,this.responseText=v.stack,h=!0,x(this.DONE)},this.abort=function(){s&&(s.abort(),s=null),d=Object.assign({},c),this.responseText="",this.responseXML="",this.response=Buffer.alloc(0),h=g=!0,this.readyState!==this.UNSENT&&(this.readyState!==this.OPENED||f)&&this.readyState!==this.DONE&&(f=!1,x(this.DONE)),this.readyState=this.UNSENT},this.addEventListener=function(v,S){v in m||(m[v]=[]),m[v].push(S)},this.removeEventListener=function(v,S){v in m&&(m[v]=m[v].filter(function(M){return M!==S}))},this.dispatchEvent=function(v){if(typeof e["on"+v]=="function"&&(this.readyState===this.DONE&&o.async?setTimeout(function(){e["on"+v]()},0):e["on"+v]()),v in m)for(let S=0,M=m[v].length;S<M;S++)this.readyState===this.DONE?setTimeout(function(){m[v][S].call(e)},0):m[v][S].call(e)};var x=function(v){if(!(e.readyState===v||e.readyState===e.UNSENT&&g)&&(e.readyState=v,(o.async||e.readyState<e.OPENED||e.readyState===e.DONE)&&e.dispatchEvent("readystatechange"),e.readyState===e.DONE)){let S;g?S="abort":h?S="error":S="load",e.dispatchEvent(S),e.dispatchEvent("loadend")}}}});var qe,yn,_n,er=A(()=>{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";yn=Object.create(null);Object.keys(qe).forEach(n=>{yn[qe[n]]=n});_n={type:"error",data:"parser error"}});function Sa(n,e){if(n.data instanceof ArrayBuffer||ArrayBuffer.isView(n.data))return e(ka(n.data,!1));wn(n,!0,t=>{ws||(ws=new TextEncoder),e(ws.encode(t))})}var wn,ka,ws,Ea=A(()=>{er();wn=({type:n,data:e},t,r)=>e instanceof ArrayBuffer||ArrayBuffer.isView(e)?r(t?e:"b"+ka(e,!0).toString("base64")):r(qe[n]+(e||"")),ka=(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 vn,xa,Ta=A(()=>{er();vn=(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 yn[t]?n.length>1?{type:yn[t],data:n.substring(1)}:{type:yn[t]}:_n},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 Aa(){return new TransformStream({transform(n,e){Sa(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 tr(n){return n.reduce((e,t)=>e+t.length,0)}function nr(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 Pa(n,e){vs||(vs=new TextDecoder);let t=[],r=0,s=-1,i=!1;return new TransformStream({transform(o,a){for(t.push(o);;){if(r===0){if(tr(t)<1)break;let c=nr(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(tr(t)<2)break;let c=nr(t,2);s=new DataView(c.buffer,c.byteOffset,c.length).getUint16(0),r=3}else if(r===2){if(tr(t)<8)break;let c=nr(t,8),d=new DataView(c.buffer,c.byteOffset,c.length),l=d.getUint32(0);if(l>Math.pow(2,21)-1){a.enqueue(_n);break}s=l*Math.pow(2,32)+d.getUint32(4),r=3}else{if(tr(t)<s)break;let c=nr(t,s);a.enqueue(vn(i?c:vs.decode(c),e)),r=0}if(s===0||s>n){a.enqueue(_n);break}}}})}var Ca,Ra,Oa,vs,bs,qt=A(()=>{Ea();Ta();er();Ca="",Ra=(n,e)=>{let t=n.length,r=new Array(t),s=0;n.forEach((i,o)=>{wn(i,!1,a=>{r[o]=a,++s===t&&e(r.join(Ca))})})},Oa=(n,e)=>{let t=n.split(Ca),r=[];for(let s=0;s<t.length;s++){let i=vn(t[s],e);if(r.push(i),i.type==="error")break}return r};bs=4});var Tt=z(Ia=>{Ia.Emitter=be;function be(n){if(n)return eh(n)}function eh(n){for(var e in be.prototype)n[e]=be.prototype[e];return n}be.prototype.on=be.prototype.addEventListener=function(n,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+n]=this._callbacks["$"+n]||[]).push(e),this};be.prototype.once=function(n,e){function t(){this.off(n,t),e.apply(this,arguments)}return t.fn=e,this.on(n,t),this};be.prototype.off=be.prototype.removeListener=be.prototype.removeAllListeners=be.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};be.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};be.prototype.emitReserved=be.prototype.emit;be.prototype.listeners=function(n){return this._callbacks=this._callbacks||{},this._callbacks["$"+n]||[]};be.prototype.hasListeners=function(n){return!!this.listeners(n).length}});function Ma(){return new ks}function th(n){let e=n.split("; "),t=e[0].indexOf("=");if(t===-1)return;let r=e[0].substring(0,t).trim();if(!r.length)return;let s=e[0].substring(t+1).trim();s.charCodeAt(0)===34&&(s=s.slice(1,-1));let i={name:r,value:s};for(let o=1;o<e.length;o++){let a=e[o].split("=");if(a.length!==2)continue;let c=a[0].trim(),d=a[1].trim();switch(c){case"Expires":i.expires=new Date(d);break;case"Max-Age":let l=new Date;l.setUTCSeconds(l.getUTCSeconds()+parseInt(d,10)),i.expires=l;break;default:}}return i}var nt,ke,Na,ks,Ct=A(()=>{nt=process.nextTick,ke=global,Na="nodebuffer";ks=class{constructor(){this._cookies=new Map}parseCookies(e){e&&e.forEach(t=>{let r=th(t);r&&this._cookies.set(r.name,r)})}get cookies(){let e=Date.now();return this._cookies.forEach((t,r)=>{var s;((s=t.expires)===null||s===void 0?void 0:s.getTime())<e&&this._cookies.delete(r)}),this._cookies.entries()}addCookies(e){let t=[];for(let[r,s]of this.cookies)t.push(`${r}=${s.value}`);t.length&&(e.setDisableHeaderCheck(!0),e.setRequestHeader("cookie",t.join("; ")))}appendCookies(e){for(let[t,r]of this.cookies)e.append("cookie",`${t}=${r.value}`)}}});function rr(n,...e){return e.reduce((t,r)=>(n.hasOwnProperty(r)&&(t[r]=n[r]),t),{})}function rt(n,e){e.useNativeTimers?(n.setTimeoutFn=nh.bind(ke),n.clearTimeoutFn=rh.bind(ke)):(n.setTimeoutFn=ke.setTimeout.bind(ke),n.clearTimeoutFn=ke.clearTimeout.bind(ke))}function La(n){return typeof n=="string"?ih(n):Math.ceil((n.byteLength||n.size)*sh)}function ih(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 nh,rh,sh,Rt=A(()=>{Ct();nh=ke.setTimeout,rh=ke.clearTimeout;sh=1.33});function $a(n){let e="";for(let t in n)n.hasOwnProperty(t)&&(e.length&&(e+="&"),e+=encodeURIComponent(t)+"="+encodeURIComponent(n[t]));return e}function Da(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 Ss=A(()=>{});var Fa=z((Tw,Ba)=>{var Gt=1e3,Wt=Gt*60,jt=Wt*60,Ot=jt*24,oh=Ot*7,ah=Ot*365.25;Ba.exports=function(n,e){e=e||{};var t=typeof n;if(t==="string"&&n.length>0)return ch(n);if(t==="number"&&isFinite(n))return e.long?dh(n):lh(n);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(n))};function ch(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*ah;case"weeks":case"week":case"w":return t*oh;case"days":case"day":case"d":return t*Ot;case"hours":case"hour":case"hrs":case"hr":case"h":return t*jt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Wt;case"seconds":case"second":case"secs":case"sec":case"s":return t*Gt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function lh(n){var e=Math.abs(n);return e>=Ot?Math.round(n/Ot)+"d":e>=jt?Math.round(n/jt)+"h":e>=Wt?Math.round(n/Wt)+"m":e>=Gt?Math.round(n/Gt)+"s":n+"ms"}function dh(n){var e=Math.abs(n);return e>=Ot?ir(n,e,Ot,"day"):e>=jt?ir(n,e,jt,"hour"):e>=Wt?ir(n,e,Wt,"minute"):e>=Gt?ir(n,e,Gt,"second"):n+" ms"}function ir(n,e,t,r){var s=e>=t*1.5;return Math.round(n/t)+" "+r+(s?"s":"")}});var Es=z((Cw,Ua)=>{function uh(n){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=Fa(),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 f=0;f<l.length;f++)u=(u<<5)-u+l.charCodeAt(f),u|=0;return t.colors[Math.abs(u)%t.colors.length]}t.selectColor=e;function t(l){let u,f=null,h,g;function m(...y){if(!m.enabled)return;let b=m,x=Number(new Date),v=x-(u||x);b.diff=v,b.prev=u,b.curr=x,u=x,y[0]=t.coerce(y[0]),typeof y[0]!="string"&&y.unshift("%O");let S=0;y[0]=y[0].replace(/%([a-zA-Z%])/g,(T,N)=>{if(T==="%%")return"%";S++;let j=t.formatters[N];if(typeof j=="function"){let W=y[S];T=j.call(b,W),y.splice(S,1),S--}return T}),t.formatArgs.call(b,y),(b.log||t.log).apply(b,y)}return m.namespace=l,m.useColors=t.useColors(),m.color=t.selectColor(l),m.extend=r,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>f!==null?f:(h!==t.namespaces&&(h=t.namespaces,g=t.enabled(l)),g),set:y=>{f=y}}),typeof t.init=="function"&&t.init(m),m}function r(l,u){let f=t(this.namespace+(typeof u>"u"?":":u)+l);return f.log=this.log,f}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 f of u)f[0]==="-"?t.skips.push(f.slice(1)):t.names.push(f)}function i(l,u){let f=0,h=0,g=-1,m=0;for(;f<l.length;)if(h<u.length&&(u[h]===l[f]||u[h]==="*"))u[h]==="*"?(g=h,m=f,h++):(f++,h++);else if(g!==-1)h=g+1,m++,f=m;else return!1;for(;h<u.length&&u[h]==="*";)h++;return h===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}Ua.exports=uh});var Ha=z((xe,or)=>{xe.formatArgs=hh;xe.save=gh;xe.load=ph;xe.useColors=fh;xe.storage=mh();xe.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`."))}})();xe.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 fh(){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 hh(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+or.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}xe.log=console.debug||console.log||(()=>{});function gh(n){try{n?xe.storage.setItem("debug",n):xe.storage.removeItem("debug")}catch{}}function ph(){let n;try{n=xe.storage.getItem("debug")||xe.storage.getItem("DEBUG")}catch{}return!n&&typeof process<"u"&&"env"in process&&(n=process.env.DEBUG),n}function mh(){try{return localStorage}catch{}}or.exports=Es()(xe);var{formatters:yh}=or.exports;yh.j=function(n){try{return JSON.stringify(n)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var Ga=z((pe,cr)=>{var _h=Q("tty"),ar=Q("util");pe.init=xh;pe.log=kh;pe.formatArgs=vh;pe.save=Sh;pe.load=Eh;pe.useColors=wh;pe.destroy=ar.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");pe.colors=[6,2,3,4,5,1];try{let n=Q("supports-color");n&&(n.stderr||n).level>=2&&(pe.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{}pe.inspectOpts=Object.keys(process.env).filter(n=>/^debug_/i.test(n)).reduce((n,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),r=process.env[e];return/^(yes|on|true|enabled)$/i.test(r)?r=!0:/^(no|off|false|disabled)$/i.test(r)?r=!1:r==="null"?r=null:r=Number(r),n[t]=r,n},{});function wh(){return"colors"in pe.inspectOpts?!!pe.inspectOpts.colors:_h.isatty(process.stderr.fd)}function vh(n){let{namespace:e,useColors:t}=this;if(t){let r=this.color,s="\x1B[3"+(r<8?r:"8;5;"+r),i=` ${s};1m${e} \x1B[0m`;n[0]=i+n[0].split(`
|
|
201
201
|
`).join(`
|
|
202
|
-
`+i),n.push(s+"m+"+
|
|
203
|
-
`)}function
|
|
204
|
-
`).map(e=>e.trim()).join(" ")};Da.O=function(n){return this.inspectOpts.colors=this.useColors,tr.inspect(n,this.inspectOpts)}});var Ie=Y((gw,vs)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?vs.exports=$a():vs.exports=Ba()});var Fa,Ua,_h,rr,et,mn=R(()=>{Dt();Fa=X(bt(),1);St();_s();Ua=X(Ie(),1),_h=(0,Ua.default)("engine.io-client:transport"),rr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},et=class extends Fa.Emitter{constructor(e){super(),this.writable=!1,Ze(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):_h("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=gn(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=Pa(e);return t.length?"?"+t:""}}});var qa,qe,yn,bs=R(()=>{mn();St();Dt();qa=X(Ie(),1),qe=(0,qa.default)("engine.io-client:polling"),yn=class extends et{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)};xa(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,Sa(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]=Qn()),!this.supportsBinary&&!t.sid&&(t.b64=1),this.createUri(e,t)}}});var Ha,Ga,Wa=R(()=>{Ha=!1;try{Ha=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Ga=Ha});function wh(){}function ja(){for(let n in tt.requests)tt.requests.hasOwnProperty(n)&&tt.requests[n].abort()}function vh(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Ga))return new XMLHttpRequest}catch{}if(!e)try{return new ve[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Ja,Ya,ks,sr,tt,Ow,Ss=R(()=>{bs();Ja=X(bt(),1);St();kt();Wa();Ya=X(Ie(),1),ks=(0,Ya.default)("engine.io-client:polling");sr=class extends yn{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(){ks("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}},tt=class n extends Ja.Emitter{constructor(e,t,r){super(),this.createRequest=e,Ze(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=Xn(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{ks("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))},ks("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=wh,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()}};tt.requestsCount=0;tt.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",ja);else if(typeof addEventListener=="function"){let n="onpagehide"in ve?"pagehide":"unload";addEventListener(n,ja,!1)}}Ow=(function(){let n=vh({xdomain:!1});return n&&n.responseType!==null})()});var xs,bh,qt,Es=R(()=>{xs=X(ma(),1);Ss();bh=xs.default||xs,qt=class extends sr{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 tt(r=>new bh(r),this.uri(),e)}}});var nt=Y((Nw,Ka)=>{"use strict";var Va=["nodebuffer","arraybuffer","fragments"],za=typeof Blob<"u";za&&Va.push("blob");Ka.exports={BINARY_TYPES:Va,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:za,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var _n=Y((Mw,ir)=>{"use strict";var{EMPTY_BUFFER:kh}=nt(),Ts=Buffer[Symbol.species];function Sh(n,e){if(n.length===0)return kh;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 Ts(t.buffer,t.byteOffset,r):t}function Xa(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function Qa(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function xh(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Cs(n){if(Cs.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Ts(n):ArrayBuffer.isView(n)?e=new Ts(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Cs.readOnly=!1),e}ir.exports={concat:Sh,mask:Xa,toArrayBuffer:xh,toBuffer:Cs,unmask:Qa};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=V("bufferutil");ir.exports.mask=function(e,t,r,s,i){i<48?Xa(e,t,r,s,i):n.mask(e,t,r,s,i)},ir.exports.unmask=function(e,t){e.length<32?Qa(e,t):n.unmask(e,t)}}catch{}});var tc=Y((Lw,ec)=>{"use strict";var Za=Symbol("kDone"),Rs=Symbol("kRun"),Os=class{constructor(e){this[Za]=()=>{this.pending--,this[Rs]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Rs]()}[Rs](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Za])}}};ec.exports=Os});var Wt=Y(($w,ic)=>{"use strict";var wn=V("zlib"),nc=_n(),Eh=tc(),{kStatusCode:rc}=nt(),Th=Buffer[Symbol.species],Ch=Buffer.from([0,0,255,255]),ar=Symbol("permessage-deflate"),rt=Symbol("total-length"),Ht=Symbol("callback"),ft=Symbol("buffers"),Gt=Symbol("error"),or,As=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 Eh(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[Ht];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"?wn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=wn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ar]=this,this._inflate[rt]=0,this._inflate[ft]=[],this._inflate.on("error",Oh),this._inflate.on("data",sc)}this._inflate[Ht]=r,this._inflate.write(e),t&&this._inflate.write(Ch),this._inflate.flush(()=>{let i=this._inflate[Gt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=nc.concat(this._inflate[ft],this._inflate[rt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[rt]=0,this._inflate[ft]=[],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"?wn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=wn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[rt]=0,this._deflate[ft]=[],this._deflate.on("data",Rh)}this._deflate[Ht]=r,this._deflate.write(e),this._deflate.flush(wn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=nc.concat(this._deflate[ft],this._deflate[rt]);t&&(i=new Th(i.buffer,i.byteOffset,i.length-4)),this._deflate[Ht]=null,this._deflate[rt]=0,this._deflate[ft]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};ic.exports=As;function Rh(n){this[ft].push(n),this[rt]+=n.length}function sc(n){if(this[rt]+=n.length,this[ar]._maxPayload<1||this[rt]<=this[ar]._maxPayload){this[ft].push(n);return}this[Gt]=new RangeError("Max payload size exceeded"),this[Gt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Gt][rc]=1009,this.removeListener("data",sc),this.reset()}function Oh(n){if(this[ar]._inflate=null,this[Gt]){this[Ht](this[Gt]);return}n[rc]=1007,this[Ht](n)}});var jt=Y((Dw,cr)=>{"use strict";var{isUtf8:oc}=V("buffer"),{hasBlob:Ah}=nt(),Ph=[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 Ih(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function Ps(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 Nh(n){return Ah&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}cr.exports={isBlob:Nh,isValidStatusCode:Ih,isValidUTF8:Ps,tokenChars:Ph};if(oc)cr.exports.isValidUTF8=function(n){return n.length<24?Ps(n):oc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=V("utf-8-validate");cr.exports.isValidUTF8=function(e){return e.length<32?Ps(e):n(e)}}catch{}});var $s=Y((Bw,hc)=>{"use strict";var{Writable:Mh}=V("stream"),ac=Wt(),{BINARY_TYPES:Lh,EMPTY_BUFFER:cc,kStatusCode:$h,kWebSocket:Dh}=nt(),{concat:Is,toArrayBuffer:Bh,unmask:Fh}=_n(),{isValidStatusCode:Uh,isValidUTF8:lc}=jt(),lr=Buffer[Symbol.species],Ne=0,dc=1,uc=2,fc=3,Ns=4,Ms=5,dr=6,Ls=class extends Mh{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Lh[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Dh]=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=Ne}_write(e,t,r){if(this._opcode===8&&this._state==Ne)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 lr(r.buffer,r.byteOffset+e,r.length-e),new lr(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 lr(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 Ne:this.getInfo(e);break;case dc:this.getPayloadLength16(e);break;case uc:this.getPayloadLength64(e);break;case fc:this.getMask();break;case Ns:this.getData(e);break;case Ms:case dr: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[ac.extensionName]){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(!this._fragmented){let s=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let s=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(s);return}if(r){let s=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(s);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let s=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(s);return}}else{let s=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(s);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let s=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(s);return}}else if(this._masked){let s=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(s);return}this._payloadLength===126?this._state=dc:this._payloadLength===127?this._state=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=Ns}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ns}getData(e){let t=cc;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&&Fh(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Ms,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[ac.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===Ne&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Ne;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=Is(r,t):this._binaryType==="arraybuffer"?s=Bh(Is(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=Ne):(this._state=dr,setImmediate(()=>{this.emit("message",s,!0),this._state=Ne,this.startLoop(e)}))}else{let s=Is(r,t);if(!this._skipUTF8Validation&&!lc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Ms||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=Ne):(this._state=dr,setImmediate(()=>{this.emit("message",s,!1),this._state=Ne,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,cc),this.end();else{let r=e.readUInt16BE(0);if(!Uh(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new lr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!lc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",r,s),this.end()}this._state=Ne;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne):(this._state=dr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Ne,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[$h]=s,o}};hc.exports=Ls});var Fs=Y((Uw,mc)=>{"use strict";var{Duplex:Fw}=V("stream"),{randomFillSync:qh}=V("crypto"),{types:{isUint8Array:Hh}}=V("util"),pc=Wt(),{EMPTY_BUFFER:Gh,kWebSocket:Wh,NOOP:jh}=nt(),{isBlob:Jt,isValidStatusCode:Jh}=jt(),{mask:gc,toBuffer:Et}=_n(),Me=Symbol("kByteLength"),Yh=Buffer.alloc(4),ur=8*1024,Tt,Yt=ur,He=0,Vh=1,zh=2,Ds=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=He,this.onerror=jh,this[Wh]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||Yh,t.generateMask?t.generateMask(r):(Yt===ur&&(Tt===void 0&&(Tt=Buffer.alloc(ur)),qh(Tt,0,ur),Yt=0),r[0]=Tt[Yt++],r[1]=Tt[Yt++],r[2]=Tt[Yt++],r[3]=Tt[Yt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Me]!==void 0?a=t[Me]:(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=Gh;else{if(typeof e!="number"||!Jh(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(Hh(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Me]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==He?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):Jt(e)?(s=e.size,i=!1):(e=Et(e),s=e.length,i=Et.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Jt(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==He?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):Jt(e)?(s=e.size,i=!1):(e=Et(e),s=e.length,i=Et.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Me]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Jt(e)?this._state!==He?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==He?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[pc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Jt(e)?(a=e.size,c=!1):(e=Et(e),a=e.length,c=Et.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={[Me]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Jt(e)?this._state!==He?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==He?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[Me],this._state=zh,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Bs,this,a,s);return}this._bufferedBytes-=r[Me];let o=Et(i);t?this.dispatch(o,t,r,s):(this._state=He,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(Kh,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[pc.extensionName];this._bufferedBytes+=r[Me],this._state=Vh,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Bs(this,c,s);return}this._bufferedBytes-=r[Me],this._state=He,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===He&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Me],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Me],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)}};mc.exports=Ds;function Bs(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 Kh(n,e,t){Bs(n,e,t),n.onerror(e)}});var Ec=Y((qw,xc)=>{"use strict";var{kForOnEventAttribute:vn,kListener:Us}=nt(),yc=Symbol("kCode"),_c=Symbol("kData"),wc=Symbol("kError"),vc=Symbol("kMessage"),bc=Symbol("kReason"),Vt=Symbol("kTarget"),kc=Symbol("kType"),Sc=Symbol("kWasClean"),st=class{constructor(e){this[Vt]=null,this[kc]=e}get target(){return this[Vt]}get type(){return this[kc]}};Object.defineProperty(st.prototype,"target",{enumerable:!0});Object.defineProperty(st.prototype,"type",{enumerable:!0});var Ct=class extends st{constructor(e,t={}){super(e),this[yc]=t.code===void 0?0:t.code,this[bc]=t.reason===void 0?"":t.reason,this[Sc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[yc]}get reason(){return this[bc]}get wasClean(){return this[Sc]}};Object.defineProperty(Ct.prototype,"code",{enumerable:!0});Object.defineProperty(Ct.prototype,"reason",{enumerable:!0});Object.defineProperty(Ct.prototype,"wasClean",{enumerable:!0});var zt=class extends st{constructor(e,t={}){super(e),this[wc]=t.error===void 0?null:t.error,this[vc]=t.message===void 0?"":t.message}get error(){return this[wc]}get message(){return this[vc]}};Object.defineProperty(zt.prototype,"error",{enumerable:!0});Object.defineProperty(zt.prototype,"message",{enumerable:!0});var bn=class extends st{constructor(e,t={}){super(e),this[_c]=t.data===void 0?null:t.data}get data(){return this[_c]}};Object.defineProperty(bn.prototype,"data",{enumerable:!0});var Xh={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[vn]&&s[Us]===e&&!s[vn])return;let r;if(n==="message")r=function(i,o){let a=new bn("message",{data:o?i:i.toString()});a[Vt]=this,fr(e,this,a)};else if(n==="close")r=function(i,o){let a=new Ct("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Vt]=this,fr(e,this,a)};else if(n==="error")r=function(i){let o=new zt("error",{error:i,message:i.message});o[Vt]=this,fr(e,this,o)};else if(n==="open")r=function(){let i=new st("open");i[Vt]=this,fr(e,this,i)};else return;r[vn]=!!t[vn],r[Us]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Us]===e&&!t[vn]){this.removeListener(n,t);break}}};xc.exports={CloseEvent:Ct,ErrorEvent:zt,Event:st,EventTarget:Xh,MessageEvent:bn};function fr(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var hr=Y((Hw,Tc)=>{"use strict";var{tokenChars:kn}=jt();function Ye(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function Qh(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&&kn[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 g=n.slice(c,l);d===44?(Ye(e,g,t),t=Object.create(null)):o=g,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&kn[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),Ye(t,n.slice(c,l),!0),d===44&&(Ye(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(kn[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(kn[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&&kn[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 g=n.slice(c,l);r&&(g=g.replace(/\\/g,""),r=!1),Ye(t,a,g),d===44&&(Ye(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 f=n.slice(c,l);return o===void 0?Ye(e,f,t):(a===void 0?Ye(t,f,!0):r?Ye(t,a,f.replace(/\\/g,"")):Ye(t,a,f),Ye(e,o,t)),e}function Zh(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(", ")}Tc.exports={format:Zh,parse:Qh}});var yr=Y((jw,Bc)=>{"use strict";var ep=V("events"),tp=V("https"),np=V("http"),Oc=V("net"),rp=V("tls"),{randomBytes:sp,createHash:ip}=V("crypto"),{Duplex:Gw,Readable:Ww}=V("stream"),{URL:qs}=V("url"),ht=Wt(),op=$s(),ap=Fs(),{isBlob:cp}=jt(),{BINARY_TYPES:Cc,CLOSE_TIMEOUT:lp,EMPTY_BUFFER:pr,GUID:dp,kForOnEventAttribute:Hs,kListener:up,kStatusCode:fp,kWebSocket:pe,NOOP:Ac}=nt(),{EventTarget:{addEventListener:hp,removeEventListener:pp}}=Ec(),{format:gp,parse:mp}=hr(),{toBuffer:yp}=_n(),Pc=Symbol("kAborted"),Gs=[8,13],it=["CONNECTING","OPEN","CLOSING","CLOSED"],_p=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,se=class n extends ep{constructor(e,t,r){super(),this._binaryType=Cc[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=pr,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(r=t,t=[]):t=[t]),Ic(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Cc.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 op({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new ap(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[pe]=this,i[pe]=this,e[pe]=this,s.on("conclude",bp),s.on("drain",kp),s.on("error",Sp),s.on("message",xp),s.on("ping",Ep),s.on("pong",Tp),i.onerror=Cp,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Lc),e.on("data",mr),e.on("end",$c),e.on("error",Dc),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[ht.extensionName]&&this._extensions[ht.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){Re(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())}),Mc(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){Ws(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||pr,t,r)}pong(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(r=e,e=t=void 0):typeof t=="function"&&(r=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Ws(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||pr,t,r)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,r){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(r=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){Ws(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ht.extensionName]||(s.compress=!1),this._sender.send(e||pr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Re(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(se,"CONNECTING",{enumerable:!0,value:it.indexOf("CONNECTING")});Object.defineProperty(se.prototype,"CONNECTING",{enumerable:!0,value:it.indexOf("CONNECTING")});Object.defineProperty(se,"OPEN",{enumerable:!0,value:it.indexOf("OPEN")});Object.defineProperty(se.prototype,"OPEN",{enumerable:!0,value:it.indexOf("OPEN")});Object.defineProperty(se,"CLOSING",{enumerable:!0,value:it.indexOf("CLOSING")});Object.defineProperty(se.prototype,"CLOSING",{enumerable:!0,value:it.indexOf("CLOSING")});Object.defineProperty(se,"CLOSED",{enumerable:!0,value:it.indexOf("CLOSED")});Object.defineProperty(se.prototype,"CLOSED",{enumerable:!0,value:it.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(se.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(se.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[Hs])return e[up];return null},set(e){for(let t of this.listeners(n))if(t[Hs]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[Hs]:!0})}})});se.prototype.addEventListener=hp;se.prototype.removeEventListener=pp;Bc.exports=se;function Ic(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:lp,protocolVersion:Gs[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,!Gs.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Gs.join(", ")})`);let i;if(e instanceof qs)i=e;else try{i=new qs(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 m=new SyntaxError(c);if(n._redirects===0)throw m;gr(n,m);return}let d=o?443:80,l=sp(16).toString("base64"),u=o?tp.request:np.request,f=new Set,g;if(s.createConnection=s.createConnection||(o?vp:wp),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&&(g=new ht({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=gp({[ht.extensionName]:g.offer()})),t.length){for(let m of t){if(typeof m!="string"||!_p.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}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 m=s.path.split(":");s.socketPath=m[0],s.path=m[1]}let h;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[_,k]of Object.entries(m))r.headers[_.toLowerCase()]=k}else if(n.listenerCount("redirect")===0){let m=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!m||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,m||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),h=n._req=u(s),n._redirects&&n.emit("redirect",n.url,h)}else h=n._req=u(s);s.timeout&&h.on("timeout",()=>{Re(n,h,"Opening handshake has timed out")}),h.on("error",m=>{h===null||h[Pc]||(h=n._req=null,gr(n,m))}),h.on("response",m=>{let _=m.headers.location,k=m.statusCode;if(_&&s.followRedirects&&k>=300&&k<400){if(++n._redirects>s.maxRedirects){Re(n,h,"Maximum redirects exceeded");return}h.abort();let E;try{E=new qs(_,e)}catch{let S=new SyntaxError(`Invalid URL: ${_}`);gr(n,S);return}Ic(n,E,t,r)}else n.emit("unexpected-response",h,m)||Re(n,h,`Unexpected server response: ${m.statusCode}`)}),h.on("upgrade",(m,_,k)=>{if(n.emit("upgrade",m),n.readyState!==se.CONNECTING)return;h=n._req=null;let E=m.headers.upgrade;if(E===void 0||E.toLowerCase()!=="websocket"){Re(n,_,"Invalid Upgrade header");return}let b=ip("sha1").update(l+dp).digest("base64");if(m.headers["sec-websocket-accept"]!==b){Re(n,_,"Invalid Sec-WebSocket-Accept header");return}let S=m.headers["sec-websocket-protocol"],O;if(S!==void 0?f.size?f.has(S)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":f.size&&(O="Server sent no subprotocol"),O){Re(n,_,O);return}S&&(n._protocol=S);let T=m.headers["sec-websocket-extensions"];if(T!==void 0){if(!g){Re(n,_,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let A;try{A=mp(T)}catch{Re(n,_,"Invalid Sec-WebSocket-Extensions header");return}let G=Object.keys(A);if(G.length!==1||G[0]!==ht.extensionName){Re(n,_,"Server indicated an extension that was not requested");return}try{g.accept(A[ht.extensionName])}catch{Re(n,_,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[ht.extensionName]=g}n.setSocket(_,k,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(h,n):h.end()}function gr(n,e){n._readyState=se.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function wp(n){return n.path=n.socketPath,Oc.connect(n)}function vp(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Oc.isIP(n.host)?"":n.host),rp.connect(n)}function Re(n,e,t){n._readyState=se.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Re),e.setHeader?(e[Pc]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(gr,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function Ws(n,e,t){if(e){let r=cp(e)?e.size:yp(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${it[n.readyState]})`);process.nextTick(t,r)}}function bp(n,e){let t=this[pe];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[pe]!==void 0&&(t._socket.removeListener("data",mr),process.nextTick(Nc,t._socket),n===1005?t.close():t.close(n,e))}function kp(){let n=this[pe];n.isPaused||n._socket.resume()}function Sp(n){let e=this[pe];e._socket[pe]!==void 0&&(e._socket.removeListener("data",mr),process.nextTick(Nc,e._socket),e.close(n[fp])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function Rc(){this[pe].emitClose()}function xp(n,e){this[pe].emit("message",n,e)}function Ep(n){let e=this[pe];e._autoPong&&e.pong(n,!this._isServer,Ac),e.emit("ping",n)}function Tp(n){this[pe].emit("pong",n)}function Nc(n){n.resume()}function Cp(n){let e=this[pe];e.readyState!==se.CLOSED&&(e.readyState===se.OPEN&&(e._readyState=se.CLOSING,Mc(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function Mc(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Lc(){let n=this[pe];if(this.removeListener("close",Lc),this.removeListener("data",mr),this.removeListener("end",$c),n._readyState=se.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[pe]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Rc),n._receiver.on("finish",Rc))}function mr(n){this[pe]._receiver.write(n)||this.pause()}function $c(){let n=this[pe];n._readyState=se.CLOSING,n._receiver.end(),this.end()}function Dc(){let n=this[pe];this.removeListener("error",Dc),this.on("error",Ac),n&&(n._readyState=se.CLOSING,this.destroy())}});var Hc=Y((Yw,qc)=>{"use strict";var Jw=yr(),{Duplex:Rp}=V("stream");function Fc(n){n.emit("close")}function Op(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Uc(n){this.removeListener("error",Uc),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function Ap(n,e){let t=!0,r=new Rp({...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(Fc,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(Fc,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",Op),r.on("error",Uc),r}qc.exports=Ap});var js=Y((Vw,Gc)=>{"use strict";var{tokenChars:Pp}=jt();function Ip(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&&Pp[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}Gc.exports={parse:Ip}});var Kc=Y((Kw,zc)=>{"use strict";var Np=V("events"),_r=V("http"),{Duplex:zw}=V("stream"),{createHash:Mp}=V("crypto"),Wc=hr(),Rt=Wt(),Lp=js(),$p=yr(),{CLOSE_TIMEOUT:Dp,GUID:Bp,kWebSocket:Fp}=nt(),Up=/^[+/0-9A-Za-z]{22}==$/,jc=0,Jc=1,Vc=2,Js=class extends Np{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:Dp,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:$p,...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=_r.createServer((r,s)=>{let i=_r.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=qp(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=jc}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===Vc){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Sn,this);return}if(e&&this.once("close",e),this._state!==Jc)if(this._state=Jc,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(Sn,this):process.nextTick(Sn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Sn(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",Yc);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Ot(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Ot(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Up.test(i)){Ot(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Ot(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){xn(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=Lp.parse(c)}catch{Ot(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 f=new Rt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let g=Wc.parse(l);g[Rt.extensionName]&&(f.accept(g[Rt.extensionName]),u[Rt.extensionName]=f)}catch{Ot(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={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(f,(g,h,m,_)=>{if(!g)return xn(t,h||401,m,_);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(f))return xn(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[Fp])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>jc)return xn(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Mp("sha1").update(t+Bp).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[Rt.extensionName]){let u=e[Rt.extensionName].params,f=Wc.format({[Rt.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
202
|
+
`+i),n.push(s+"m+"+cr.exports.humanize(this.diff)+"\x1B[0m")}else n[0]=bh()+e+" "+n[0]}function bh(){return pe.inspectOpts.hideDate?"":new Date().toISOString()+" "}function kh(...n){return process.stderr.write(ar.formatWithOptions(pe.inspectOpts,...n)+`
|
|
203
|
+
`)}function Sh(n){n?process.env.DEBUG=n:delete process.env.DEBUG}function Eh(){return process.env.DEBUG}function xh(n){n.inspectOpts={};let e=Object.keys(pe.inspectOpts);for(let t=0;t<e.length;t++)n.inspectOpts[e[t]]=pe.inspectOpts[e[t]]}cr.exports=Es()(pe);var{formatters:qa}=cr.exports;qa.o=function(n){return this.inspectOpts.colors=this.useColors,ar.inspect(n,this.inspectOpts).split(`
|
|
204
|
+
`).map(e=>e.trim()).join(" ")};qa.O=function(n){return this.inspectOpts.colors=this.useColors,ar.inspect(n,this.inspectOpts)}});var $e=z((Rw,xs)=>{typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?xs.exports=Ha():xs.exports=Ga()});var Wa,ja,Th,lr,st,bn=A(()=>{qt();Wa=te(Tt(),1);Rt();Ss();ja=te($e(),1),Th=(0,ja.default)("engine.io-client:transport"),lr=class extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}},st=class extends Wa.Emitter{constructor(e){super(),this.writable=!1,rt(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 lr(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):Th("transport is not open, discarding packets")}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){let t=vn(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=$a(e);return t.length?"?"+t:""}}});var Ja,Ge,kn,Ts=A(()=>{bn();Rt();qt();Ja=te($e(),1),Ge=(0,Ja.default)("engine.io-client:polling"),kn=class extends st{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";let t=()=>{Ge("paused"),this.readyState="paused",e()};if(this._polling||!this.writable){let r=0;this._polling&&(Ge("we are currently polling - waiting to pause"),r++,this.once("pollComplete",function(){Ge("pre-pause polling complete"),--r||t()})),this.writable||(Ge("we are currently writing - waiting to pause"),r++,this.once("drain",function(){Ge("pre-pause writing complete"),--r||t()}))}else t()}_poll(){Ge("polling"),this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){Ge("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)};Oa(e,this.socket.binaryType).forEach(t),this.readyState!=="closed"&&(this._polling=!1,this.emitReserved("pollComplete"),this.readyState==="open"?this._poll():Ge('ignoring poll - transport state "%s"',this.readyState))}doClose(){let e=()=>{Ge("writing close packet"),this.write([{type:"close"}])};this.readyState==="open"?(Ge("transport open - closing"),e()):(Ge("transport not open - deferring close"),this.once("open",e))}write(e){this.writable=!1,Ra(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 Ya,Va,za=A(()=>{Ya=!1;try{Ya=typeof XMLHttpRequest<"u"&&"withCredentials"in new XMLHttpRequest}catch{}Va=Ya});function Ch(){}function Ka(){for(let n in it.requests)it.requests.hasOwnProperty(n)&&it.requests[n].abort()}function Rh(n){let e=n.xdomain;try{if(typeof XMLHttpRequest<"u"&&(!e||Va))return new XMLHttpRequest}catch{}if(!e)try{return new ke[["Active"].concat("Object").join("X")]("Microsoft.XMLHTTP")}catch{}}var Xa,Qa,Cs,dr,it,qw,Rs=A(()=>{Ts();Xa=te(Tt(),1);Rt();Ct();za();Qa=te($e(),1),Cs=(0,Qa.default)("engine.io-client:polling");dr=class extends kn{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(){Cs("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}},it=class n extends Xa.Emitter{constructor(e,t,r){super(),this.createRequest=e,rt(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=rr(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");t.xdomain=!!this._opts.xd;let r=this._xhr=this.createRequest(t);try{Cs("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))},Cs("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=Ch,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()}};it.requestsCount=0;it.requests={};if(typeof document<"u"){if(typeof attachEvent=="function")attachEvent("onunload",Ka);else if(typeof addEventListener=="function"){let n="onpagehide"in ke?"pagehide":"unload";addEventListener(n,Ka,!1)}}qw=(function(){let n=Rh({xdomain:!1});return n&&n.responseType!==null})()});var Os,Oh,Jt,As=A(()=>{Os=te(ba(),1);Rs();Oh=Os.default||Os,Jt=class extends dr{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 it(r=>new Oh(r),this.uri(),e)}}});var ot=z((Jw,tc)=>{"use strict";var Za=["nodebuffer","arraybuffer","fragments"],ec=typeof Blob<"u";ec&&Za.push("blob");tc.exports={BINARY_TYPES:Za,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:ec,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Sn=z((Yw,ur)=>{"use strict";var{EMPTY_BUFFER:Ah}=ot(),Ps=Buffer[Symbol.species];function Ph(n,e){if(n.length===0)return Ah;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 Ps(t.buffer,t.byteOffset,r):t}function nc(n,e,t,r,s){for(let i=0;i<s;i++)t[r+i]=n[i]^e[i&3]}function rc(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Ih(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Is(n){if(Is.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Ps(n):ArrayBuffer.isView(n)?e=new Ps(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Is.readOnly=!1),e}ur.exports={concat:Ph,mask:nc,toArrayBuffer:Ih,toBuffer:Is,unmask:rc};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=Q("bufferutil");ur.exports.mask=function(e,t,r,s,i){i<48?nc(e,t,r,s,i):n.mask(e,t,r,s,i)},ur.exports.unmask=function(e,t){e.length<32?rc(e,t):n.unmask(e,t)}}catch{}});var oc=z((Vw,ic)=>{"use strict";var sc=Symbol("kDone"),Ns=Symbol("kRun"),Ms=class{constructor(e){this[sc]=()=>{this.pending--,this[Ns]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Ns]()}[Ns](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[sc])}}};ic.exports=Ms});var zt=z((zw,dc)=>{"use strict";var En=Q("zlib"),ac=Sn(),Nh=oc(),{kStatusCode:cc}=ot(),Mh=Buffer[Symbol.species],Lh=Buffer.from([0,0,255,255]),hr=Symbol("permessage-deflate"),at=Symbol("total-length"),Yt=Symbol("callback"),mt=Symbol("buffers"),Vt=Symbol("error"),fr,Ls=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,!fr){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;fr=new Nh(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[Yt];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){fr.add(s=>{this._decompress(e,t,(i,o)=>{s(),r(i,o)})})}compress(e,t,r){fr.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"?En.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=En.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[hr]=this,this._inflate[at]=0,this._inflate[mt]=[],this._inflate.on("error",Dh),this._inflate.on("data",lc)}this._inflate[Yt]=r,this._inflate.write(e),t&&this._inflate.write(Lh),this._inflate.flush(()=>{let i=this._inflate[Vt];if(i){this._inflate.close(),this._inflate=null,r(i);return}let o=ac.concat(this._inflate[mt],this._inflate[at]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[at]=0,this._inflate[mt]=[],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"?En.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=En.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[at]=0,this._deflate[mt]=[],this._deflate.on("data",$h)}this._deflate[Yt]=r,this._deflate.write(e),this._deflate.flush(En.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=ac.concat(this._deflate[mt],this._deflate[at]);t&&(i=new Mh(i.buffer,i.byteOffset,i.length-4)),this._deflate[Yt]=null,this._deflate[at]=0,this._deflate[mt]=[],t&&this.params[`${s}_no_context_takeover`]&&this._deflate.reset(),r(null,i)})}};dc.exports=Ls;function $h(n){this[mt].push(n),this[at]+=n.length}function lc(n){if(this[at]+=n.length,this[hr]._maxPayload<1||this[at]<=this[hr]._maxPayload){this[mt].push(n);return}this[Vt]=new RangeError("Max payload size exceeded"),this[Vt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Vt][cc]=1009,this.removeListener("data",lc),this.reset()}function Dh(n){if(this[hr]._inflate=null,this[Vt]){this[Yt](this[Vt]);return}n[cc]=1007,this[Yt](n)}});var Kt=z((Kw,gr)=>{"use strict";var{isUtf8:uc}=Q("buffer"),{hasBlob:Bh}=ot(),Fh=[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 Uh(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function $s(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 Hh(n){return Bh&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}gr.exports={isBlob:Hh,isValidStatusCode:Uh,isValidUTF8:$s,tokenChars:Fh};if(uc)gr.exports.isValidUTF8=function(n){return n.length<24?$s(n):uc(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=Q("utf-8-validate");gr.exports.isValidUTF8=function(e){return e.length<32?$s(e):n(e)}}catch{}});var Hs=z((Xw,_c)=>{"use strict";var{Writable:qh}=Q("stream"),fc=zt(),{BINARY_TYPES:Gh,EMPTY_BUFFER:hc,kStatusCode:Wh,kWebSocket:jh}=ot(),{concat:Ds,toArrayBuffer:Jh,unmask:Yh}=Sn(),{isValidStatusCode:Vh,isValidUTF8:gc}=Kt(),pr=Buffer[Symbol.species],De=0,pc=1,mc=2,yc=3,Bs=4,Fs=5,mr=6,Us=class extends qh{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Gh[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[jh]=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=De}_write(e,t,r){if(this._opcode===8&&this._state==De)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 pr(r.buffer,r.byteOffset+e,r.length-e),new pr(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 pr(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 De:this.getInfo(e);break;case pc:this.getPayloadLength16(e);break;case mc:this.getPayloadLength64(e);break;case yc:this.getMask();break;case Bs:this.getData(e);break;case Fs: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[fc.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=pc:this._payloadLength===127?this._state=mc: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=yc:this._state=Bs}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Bs}getData(e){let t=hc;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&&Yh(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Fs,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[fc.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===De&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=De;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=Ds(r,t):this._binaryType==="arraybuffer"?s=Jh(Ds(r,t)):this._binaryType==="blob"?s=new Blob(r):s=r,this._allowSynchronousEvents?(this.emit("message",s,!0),this._state=De):(this._state=mr,setImmediate(()=>{this.emit("message",s,!0),this._state=De,this.startLoop(e)}))}else{let s=Ds(r,t);if(!this._skipUTF8Validation&&!gc(s)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===Fs||this._allowSynchronousEvents?(this.emit("message",s,!1),this._state=De):(this._state=mr,setImmediate(()=>{this.emit("message",s,!1),this._state=De,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,hc),this.end();else{let r=e.readUInt16BE(0);if(!Vh(r)){let i=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let s=new pr(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!gc(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=De;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=De):(this._state=mr,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=De,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[Wh]=s,o}};_c.exports=Us});var Ws=z((Zw,bc)=>{"use strict";var{Duplex:Qw}=Q("stream"),{randomFillSync:zh}=Q("crypto"),{types:{isUint8Array:Kh}}=Q("util"),wc=zt(),{EMPTY_BUFFER:Xh,kWebSocket:Qh,NOOP:Zh}=ot(),{isBlob:Xt,isValidStatusCode:eg}=Kt(),{mask:vc,toBuffer:At}=Sn(),Be=Symbol("kByteLength"),tg=Buffer.alloc(4),yr=8*1024,Pt,Qt=yr,We=0,ng=1,rg=2,qs=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=We,this.onerror=Zh,this[Qh]=void 0}static frame(e,t){let r,s=!1,i=2,o=!1;t.mask&&(r=t.maskBuffer||tg,t.generateMask?t.generateMask(r):(Qt===yr&&(Pt===void 0&&(Pt=Buffer.alloc(yr)),zh(Pt,0,yr),Qt=0),r[0]=Pt[Qt++],r[1]=Pt[Qt++],r[2]=Pt[Qt++],r[3]=Pt[Qt++]),o=(r[0]|r[1]|r[2]|r[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[Be]!==void 0?a=t[Be]:(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?(vc(e,r,d,i,a),[d]):(vc(e,r,e,0,a),[d,e])):[d,e]}close(e,t,r,s){let i;if(e===void 0)i=Xh;else{if(typeof e!="number"||!eg(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(Kh(t))i.set(t,2);else throw new TypeError("Second argument must be a string or a Uint8Array")}}let o={[Be]:i.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==We?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):Xt(e)?(s=e.size,i=!1):(e=At(e),s=e.length,i=At.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Be]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};Xt(e)?this._state!==We?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==We?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):Xt(e)?(s=e.size,i=!1):(e=At(e),s=e.length,i=At.readOnly),s>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[Be]:s,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};Xt(e)?this._state!==We?this.enqueue([this.getBlobData,e,!1,o,r]):this.getBlobData(e,!1,o,r):this._state!==We?this.enqueue([this.dispatch,e,!1,o,r]):this.sendFrame(n.frame(e,o),r)}send(e,t,r){let s=this._extensions[wc.extensionName],i=t.binary?2:1,o=t.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):Xt(e)?(a=e.size,c=!1):(e=At(e),a=e.length,c=At.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={[Be]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:c,rsv1:o};Xt(e)?this._state!==We?this.enqueue([this.getBlobData,e,this._compress,d,r]):this.getBlobData(e,this._compress,d,r):this._state!==We?this.enqueue([this.dispatch,e,this._compress,d,r]):this.dispatch(e,this._compress,d,r)}getBlobData(e,t,r,s){this._bufferedBytes+=r[Be],this._state=rg,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Gs,this,a,s);return}this._bufferedBytes-=r[Be];let o=At(i);t?this.dispatch(o,t,r,s):(this._state=We,this.sendFrame(n.frame(o,r),s),this.dequeue())}).catch(i=>{process.nextTick(sg,this,i,s)})}dispatch(e,t,r,s){if(!t){this.sendFrame(n.frame(e,r),s);return}let i=this._extensions[wc.extensionName];this._bufferedBytes+=r[Be],this._state=ng,i.compress(e,r.fin,(o,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");Gs(this,c,s);return}this._bufferedBytes-=r[Be],this._state=We,r.readOnly=!1,this.sendFrame(n.frame(a,r),s),this.dequeue()})}dequeue(){for(;this._state===We&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Be],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Be],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)}};bc.exports=qs;function Gs(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 sg(n,e,t){Gs(n,e,t),n.onerror(e)}});var Ac=z((ev,Oc)=>{"use strict";var{kForOnEventAttribute:xn,kListener:js}=ot(),kc=Symbol("kCode"),Sc=Symbol("kData"),Ec=Symbol("kError"),xc=Symbol("kMessage"),Tc=Symbol("kReason"),Zt=Symbol("kTarget"),Cc=Symbol("kType"),Rc=Symbol("kWasClean"),ct=class{constructor(e){this[Zt]=null,this[Cc]=e}get target(){return this[Zt]}get type(){return this[Cc]}};Object.defineProperty(ct.prototype,"target",{enumerable:!0});Object.defineProperty(ct.prototype,"type",{enumerable:!0});var It=class extends ct{constructor(e,t={}){super(e),this[kc]=t.code===void 0?0:t.code,this[Tc]=t.reason===void 0?"":t.reason,this[Rc]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[kc]}get reason(){return this[Tc]}get wasClean(){return this[Rc]}};Object.defineProperty(It.prototype,"code",{enumerable:!0});Object.defineProperty(It.prototype,"reason",{enumerable:!0});Object.defineProperty(It.prototype,"wasClean",{enumerable:!0});var en=class extends ct{constructor(e,t={}){super(e),this[Ec]=t.error===void 0?null:t.error,this[xc]=t.message===void 0?"":t.message}get error(){return this[Ec]}get message(){return this[xc]}};Object.defineProperty(en.prototype,"error",{enumerable:!0});Object.defineProperty(en.prototype,"message",{enumerable:!0});var Tn=class extends ct{constructor(e,t={}){super(e),this[Sc]=t.data===void 0?null:t.data}get data(){return this[Sc]}};Object.defineProperty(Tn.prototype,"data",{enumerable:!0});var ig={addEventListener(n,e,t={}){for(let s of this.listeners(n))if(!t[xn]&&s[js]===e&&!s[xn])return;let r;if(n==="message")r=function(i,o){let a=new Tn("message",{data:o?i:i.toString()});a[Zt]=this,_r(e,this,a)};else if(n==="close")r=function(i,o){let a=new It("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Zt]=this,_r(e,this,a)};else if(n==="error")r=function(i){let o=new en("error",{error:i,message:i.message});o[Zt]=this,_r(e,this,o)};else if(n==="open")r=function(){let i=new ct("open");i[Zt]=this,_r(e,this,i)};else return;r[xn]=!!t[xn],r[js]=e,t.once?this.once(n,r):this.on(n,r)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[js]===e&&!t[xn]){this.removeListener(n,t);break}}};Oc.exports={CloseEvent:It,ErrorEvent:en,Event:ct,EventTarget:ig,MessageEvent:Tn};function _r(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var wr=z((tv,Pc)=>{"use strict";var{tokenChars:Cn}=Kt();function Ke(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function og(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&&Cn[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 h=n.slice(c,l);d===44?(Ke(e,h,t),t=Object.create(null)):o=h,c=l=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(l===-1&&Cn[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),Ke(t,n.slice(c,l),!0),d===44&&(Ke(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(Cn[d]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);c===-1?c=u:r||(r=!0),s=!1}else if(i)if(Cn[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&&Cn[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 h=n.slice(c,l);r&&(h=h.replace(/\\/g,""),r=!1),Ke(t,a,h),d===44&&(Ke(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 f=n.slice(c,l);return o===void 0?Ke(e,f,t):(a===void 0?Ke(t,f,!0):r?Ke(t,a,f.replace(/\\/g,"")):Ke(t,a,f),Ke(e,o,t)),e}function ag(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(", ")}Pc.exports={format:ag,parse:og}});var Sr=z((sv,Gc)=>{"use strict";var cg=Q("events"),lg=Q("https"),dg=Q("http"),Mc=Q("net"),ug=Q("tls"),{randomBytes:fg,createHash:hg}=Q("crypto"),{Duplex:nv,Readable:rv}=Q("stream"),{URL:Js}=Q("url"),yt=zt(),gg=Hs(),pg=Ws(),{isBlob:mg}=Kt(),{BINARY_TYPES:Ic,CLOSE_TIMEOUT:yg,EMPTY_BUFFER:vr,GUID:_g,kForOnEventAttribute:Ys,kListener:wg,kStatusCode:vg,kWebSocket:me,NOOP:Lc}=ot(),{EventTarget:{addEventListener:bg,removeEventListener:kg}}=Ac(),{format:Sg,parse:Eg}=wr(),{toBuffer:xg}=Sn(),$c=Symbol("kAborted"),Vs=[8,13],lt=["CONNECTING","OPEN","CLOSING","CLOSED"],Tg=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,se=class n extends cg{constructor(e,t,r){super(),this._binaryType=Ic[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=vr,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]),Dc(this,e,t,r)):(this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){Ic.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 gg({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),i=new pg(e,this._extensions,r.generateMask);this._receiver=s,this._sender=i,this._socket=e,s[me]=this,i[me]=this,e[me]=this,s.on("conclude",Og),s.on("drain",Ag),s.on("error",Pg),s.on("message",Ig),s.on("ping",Ng),s.on("pong",Mg),i.onerror=Lg,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Uc),e.on("data",kr),e.on("end",Hc),e.on("error",qc),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[yt.extensionName]&&this._extensions[yt.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){Re(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())}),Fc(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){zs(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||vr,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){zs(this,e,r);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||vr,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){zs(this,e,r);return}let s={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[yt.extensionName]||(s.compress=!1),this._sender.send(e||vr,s,r)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Re(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(se,"CONNECTING",{enumerable:!0,value:lt.indexOf("CONNECTING")});Object.defineProperty(se.prototype,"CONNECTING",{enumerable:!0,value:lt.indexOf("CONNECTING")});Object.defineProperty(se,"OPEN",{enumerable:!0,value:lt.indexOf("OPEN")});Object.defineProperty(se.prototype,"OPEN",{enumerable:!0,value:lt.indexOf("OPEN")});Object.defineProperty(se,"CLOSING",{enumerable:!0,value:lt.indexOf("CLOSING")});Object.defineProperty(se.prototype,"CLOSING",{enumerable:!0,value:lt.indexOf("CLOSING")});Object.defineProperty(se,"CLOSED",{enumerable:!0,value:lt.indexOf("CLOSED")});Object.defineProperty(se.prototype,"CLOSED",{enumerable:!0,value:lt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(se.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(se.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[Ys])return e[wg];return null},set(e){for(let t of this.listeners(n))if(t[Ys]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[Ys]:!0})}})});se.prototype.addEventListener=bg;se.prototype.removeEventListener=kg;Gc.exports=se;function Dc(n,e,t,r){let s={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:yg,protocolVersion:Vs[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,!Vs.includes(s.protocolVersion))throw new RangeError(`Unsupported protocol version: ${s.protocolVersion} (supported versions: ${Vs.join(", ")})`);let i;if(e instanceof Js)i=e;else try{i=new Js(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 m=new SyntaxError(c);if(n._redirects===0)throw m;br(n,m);return}let d=o?443:80,l=fg(16).toString("base64"),u=o?lg.request:dg.request,f=new Set,h;if(s.createConnection=s.createConnection||(o?Rg:Cg),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&&(h=new yt({...s.perMessageDeflate,isServer:!1,maxPayload:s.maxPayload}),s.headers["Sec-WebSocket-Extensions"]=Sg({[yt.extensionName]:h.offer()})),t.length){for(let m of t){if(typeof m!="string"||!Tg.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}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 m=s.path.split(":");s.socketPath=m[0],s.path=m[1]}let g;if(s.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?s.socketPath:i.host;let m=r&&r.headers;if(r={...r,headers:{}},m)for(let[y,b]of Object.entries(m))r.headers[y.toLowerCase()]=b}else if(n.listenerCount("redirect")===0){let m=a?n._originalIpc?s.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!m||n._originalSecure&&!o)&&(delete s.headers.authorization,delete s.headers.cookie,m||delete s.headers.host,s.auth=void 0)}s.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(s.auth).toString("base64")),g=n._req=u(s),n._redirects&&n.emit("redirect",n.url,g)}else g=n._req=u(s);s.timeout&&g.on("timeout",()=>{Re(n,g,"Opening handshake has timed out")}),g.on("error",m=>{g===null||g[$c]||(g=n._req=null,br(n,m))}),g.on("response",m=>{let y=m.headers.location,b=m.statusCode;if(y&&s.followRedirects&&b>=300&&b<400){if(++n._redirects>s.maxRedirects){Re(n,g,"Maximum redirects exceeded");return}g.abort();let x;try{x=new Js(y,e)}catch{let S=new SyntaxError(`Invalid URL: ${y}`);br(n,S);return}Dc(n,x,t,r)}else n.emit("unexpected-response",g,m)||Re(n,g,`Unexpected server response: ${m.statusCode}`)}),g.on("upgrade",(m,y,b)=>{if(n.emit("upgrade",m),n.readyState!==se.CONNECTING)return;g=n._req=null;let x=m.headers.upgrade;if(x===void 0||x.toLowerCase()!=="websocket"){Re(n,y,"Invalid Upgrade header");return}let v=hg("sha1").update(l+_g).digest("base64");if(m.headers["sec-websocket-accept"]!==v){Re(n,y,"Invalid Sec-WebSocket-Accept header");return}let S=m.headers["sec-websocket-protocol"],M;if(S!==void 0?f.size?f.has(S)||(M="Server sent an invalid subprotocol"):M="Server sent a subprotocol but none was requested":f.size&&(M="Server sent no subprotocol"),M){Re(n,y,M);return}S&&(n._protocol=S);let T=m.headers["sec-websocket-extensions"];if(T!==void 0){if(!h){Re(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let N;try{N=Eg(T)}catch{Re(n,y,"Invalid Sec-WebSocket-Extensions header");return}let j=Object.keys(N);if(j.length!==1||j[0]!==yt.extensionName){Re(n,y,"Server indicated an extension that was not requested");return}try{h.accept(N[yt.extensionName])}catch{Re(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[yt.extensionName]=h}n.setSocket(y,b,{allowSynchronousEvents:s.allowSynchronousEvents,generateMask:s.generateMask,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation})}),s.finishRequest?s.finishRequest(g,n):g.end()}function br(n,e){n._readyState=se.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function Cg(n){return n.path=n.socketPath,Mc.connect(n)}function Rg(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=Mc.isIP(n.host)?"":n.host),ug.connect(n)}function Re(n,e,t){n._readyState=se.CLOSING;let r=new Error(t);Error.captureStackTrace(r,Re),e.setHeader?(e[$c]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(br,n,r)):(e.destroy(r),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function zs(n,e,t){if(e){let r=mg(e)?e.size:xg(e).length;n._socket?n._sender._bufferedBytes+=r:n._bufferedAmount+=r}if(t){let r=new Error(`WebSocket is not open: readyState ${n.readyState} (${lt[n.readyState]})`);process.nextTick(t,r)}}function Og(n,e){let t=this[me];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[me]!==void 0&&(t._socket.removeListener("data",kr),process.nextTick(Bc,t._socket),n===1005?t.close():t.close(n,e))}function Ag(){let n=this[me];n.isPaused||n._socket.resume()}function Pg(n){let e=this[me];e._socket[me]!==void 0&&(e._socket.removeListener("data",kr),process.nextTick(Bc,e._socket),e.close(n[vg])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function Nc(){this[me].emitClose()}function Ig(n,e){this[me].emit("message",n,e)}function Ng(n){let e=this[me];e._autoPong&&e.pong(n,!this._isServer,Lc),e.emit("ping",n)}function Mg(n){this[me].emit("pong",n)}function Bc(n){n.resume()}function Lg(n){let e=this[me];e.readyState!==se.CLOSED&&(e.readyState===se.OPEN&&(e._readyState=se.CLOSING,Fc(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function Fc(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Uc(){let n=this[me];if(this.removeListener("close",Uc),this.removeListener("data",kr),this.removeListener("end",Hc),n._readyState=se.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[me]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",Nc),n._receiver.on("finish",Nc))}function kr(n){this[me]._receiver.write(n)||this.pause()}function Hc(){let n=this[me];n._readyState=se.CLOSING,n._receiver.end(),this.end()}function qc(){let n=this[me];this.removeListener("error",qc),this.on("error",Lc),n&&(n._readyState=se.CLOSING,this.destroy())}});var Yc=z((ov,Jc)=>{"use strict";var iv=Sr(),{Duplex:$g}=Q("stream");function Wc(n){n.emit("close")}function Dg(){!this.destroyed&&this._writableState.finished&&this.destroy()}function jc(n){this.removeListener("error",jc),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function Bg(n,e){let t=!0,r=new $g({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&r._readableState.objectMode?i.toString():i;r.push(a)||n.pause()}),n.once("error",function(i){r.destroyed||(t=!1,r.destroy(i))}),n.once("close",function(){r.destroyed||r.push(null)}),r._destroy=function(s,i){if(n.readyState===n.CLOSED){i(s),process.nextTick(Wc,r);return}let o=!1;n.once("error",function(c){o=!0,i(c)}),n.once("close",function(){o||i(s),process.nextTick(Wc,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",Dg),r.on("error",jc),r}Jc.exports=Bg});var Ks=z((av,Vc)=>{"use strict";var{tokenChars:Fg}=Kt();function Ug(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&&Fg[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}Vc.exports={parse:Ug}});var tl=z((lv,el)=>{"use strict";var Hg=Q("events"),Er=Q("http"),{Duplex:cv}=Q("stream"),{createHash:qg}=Q("crypto"),zc=wr(),Nt=zt(),Gg=Ks(),Wg=Sr(),{CLOSE_TIMEOUT:jg,GUID:Jg,kWebSocket:Yg}=ot(),Vg=/^[+/0-9A-Za-z]{22}==$/,Kc=0,Xc=1,Zc=2,Xs=class extends Hg{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:jg,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Wg,...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=Er.createServer((r,s)=>{let i=Er.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=zg(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=Kc}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===Zc){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Rn,this);return}if(e&&this.once("close",e),this._state!==Xc)if(this._state=Xc,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(Rn,this):process.nextTick(Rn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Rn(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",Qc);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Mt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Mt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Vg.test(i)){Mt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Mt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){On(t,400);return}let c=e.headers["sec-websocket-protocol"],d=new Set;if(c!==void 0)try{d=Gg.parse(c)}catch{Mt(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 f=new Nt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let h=zc.parse(l);h[Nt.extensionName]&&(f.accept(h[Nt.extensionName]),u[Nt.extensionName]=f)}catch{Mt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={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(f,(h,g,m,y)=>{if(!h)return On(t,g||401,m,y);this.completeUpgrade(u,i,d,e,t,r,s)});return}if(!this.options.verifyClient(f))return On(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[Yg])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Kc)return On(i,503);let d=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${qg("sha1").update(t+Jg).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[Nt.extensionName]){let u=e[Nt.extensionName].params,f=zc.format({[Nt.extensionName]:[u]});d.push(`Sec-WebSocket-Extensions: ${f}`),l._extensions=e}this.emit("headers",d,s),i.write(d.concat(`\r
|
|
205
205
|
`).join(`\r
|
|
206
|
-
`)),i.removeListener("error",
|
|
206
|
+
`)),i.removeListener("error",Qc),l.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(l),l.on("close",()=>{this.clients.delete(l),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Rn,this)})),a(l,s)}};el.exports=Xs;function zg(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 Rn(n){n._state=Zc,n.emit("close")}function Qc(){this.destroy()}function On(n,e,t,r){t=t||Er.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} ${Er.STATUS_CODES[e]}\r
|
|
207
207
|
`+Object.keys(r).map(s=>`${s}: ${r[s]}`).join(`\r
|
|
208
208
|
`)+`\r
|
|
209
209
|
\r
|
|
210
|
-
`+t)}function Ot(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Ot),n.emit("wsClientError",o,t,e)}else xn(t,r,s,i)}});var Hp,Gp,Wp,jp,Jp,Yp,Ys,Vp,Xc=R(()=>{Hp=X(Hc(),1),Gp=X(hr(),1),Wp=X(Wt(),1),jp=X($s(),1),Jp=X(Fs(),1),Yp=X(js(),1),Ys=X(yr(),1),Vp=X(Kc(),1)});var Qc,Kp,Xp,wr,tv,Vs=R(()=>{mn();St();Dt();kt();Qc=X(Ie(),1),Kp=(0,Qc.default)("engine.io-client:websocket"),Xp=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",wr=class extends et{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=Xp?{}:Xn(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;pn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{Kp("websocket closed before onclose event")}s&&Qe(()=>{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]=Qn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}},tv=ve.WebSocket||ve.MozWebSocket});var Kt,zs=R(()=>{Xc();Vs();Kt=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 Ys.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 Zc,En,Xt,Ks=R(()=>{mn();kt();Dt();Zc=X(Ie(),1),En=(0,Zc.default)("engine.io-client:webtransport"),Xt=class extends et{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(()=>{En("transport closed gracefully"),this.onClose()}).catch(e=>{En("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Ta(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=Ea();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){En("session is closed");return}En("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{En("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&&Qe(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var Xs,Qs=R(()=>{Es();zs();Ks();Xs={websocket:Kt,webtransport:Xt,polling:qt}});function Qt(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=Qp.exec(n||""),i={},o=14;for(;o--;)i[Zp[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=eg(i,i.path),i.queryKey=tg(i,i.query),i}function eg(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 tg(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var Qp,Zp,Zs=R(()=>{Qp=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Zp=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var el,tl,te,ei,Tn,At,vr,Zt,ti=R(()=>{Qs();St();_s();Zs();el=X(bt(),1);Dt();kt();tl=X(Ie(),1),te=(0,tl.default)("engine.io-client:socket"),ei=typeof addEventListener=="function"&&typeof removeEventListener=="function",Tn=[];ei&&addEventListener("offline",()=>{te("closing %d connection(s) because the network was lost",Tn.length),Tn.forEach(n=>n())},!1);At=class n extends el.Emitter{constructor(e,t){if(super(),this.binaryType=Ra,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=Qt(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=Qt(t.host).host);Ze(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=Ia(this.opts.query)),ei&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(te("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Tn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=Oa()),this._open()}createTransport(e){te('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=ms,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return te("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){te("setting transport %s",e.name),this.transport&&(te("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(){te("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(te('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 te('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();te("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+=Aa(s)),r>0&&t>this._maxPayload)return te("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return te("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&&(te("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,Qe(()=>{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"),te("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(te("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return te("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(te('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ei&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Tn.indexOf(this._offlineEventListener);r!==-1&&(te("removing listener for the 'offline' event"),Tn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};At.protocol=ms;vr=class extends At{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){te("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){te('probing transport "%s"',e);let t=this.createTransport(e),r=!1;At.priorWebsocketSuccess=!1;let s=()=>{r||(te('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(te('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;At.priorWebsocketSuccess=t.name==="websocket",te('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(te("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{te('probe transport "%s" failed',e);let f=new Error("probe error");f.transport=t.name,this.emitReserved("upgradeError",f)}}))};function i(){r||(r=!0,l(),t.close(),t=null)}let o=u=>{let f=new Error("probe error: "+u);f.transport=t.name,i(),te('probe transport "%s" failed because of error: %s',e,u),this.emitReserved("upgradeError",f)};function a(){o("transport closed")}function c(){o("socket closed")}function d(u){t&&u.name!==t.name&&(te('"%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}},Zt=class extends vr{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=>Xs[s]).filter(s=>!!s)),super(e,r)}}});var nl=R(()=>{bs()});var xv,br=R(()=>{ti();ti();mn();Qs();St();Zs();kt();nl();Es();Ss();zs();Vs();Ks();xv=Zt.protocol});function il(n,e="",t){let r=n;t=t||typeof location<"u"&&location,n==null&&(n=t.protocol+"//"+t.host),typeof n=="string"&&(n.charAt(0)==="/"&&(n.charAt(1)==="/"?n=t.protocol+n:n=t.host+n),/^(https?|wss?):\/\//.test(n)||(rl("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),rl("parse %s",n),r=Qt(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 sl,rl,ol=R(()=>{br();sl=X(Ie(),1),rl=(0,sl.default)("socket.io-client:url")});function Rn(n){return ig&&(n instanceof ArrayBuffer||og(n))||ag&&n instanceof Blob||cg&&n instanceof File}function Cn(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Cn(n[t]))return!0;return!1}if(Rn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return Cn(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&Cn(n[t]))return!0;return!1}var ig,og,al,ag,cg,ni=R(()=>{ig=typeof ArrayBuffer=="function",og=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,al=Object.prototype.toString,ag=typeof Blob=="function"||typeof Blob<"u"&&al.call(Blob)==="[object BlobConstructor]",cg=typeof File=="function"||typeof File<"u"&&al.call(File)==="[object FileConstructor]"});function cl(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(Rn(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 ll(n,e){return n.data=si(n.data,e),delete n.attachments,n}function si(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]=si(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=si(n[t],e));return n}var dl=R(()=>{ni()});var li={};Ce(li,{Decoder:()=>ai,Encoder:()=>oi,PacketType:()=>U,isPacketValid:()=>fg,protocol:()=>pl});function lg(n){return typeof n=="string"}function dg(n){return n===void 0||gl(n)}function kr(n){return Object.prototype.toString.call(n)==="[object Object]"}function ug(n,e){switch(n){case U.CONNECT:return e===void 0||kr(e);case U.DISCONNECT:return e===void 0;case U.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&hl.indexOf(e[0])===-1);case U.ACK:return Array.isArray(e);case U.CONNECT_ERROR:return typeof e=="string"||kr(e);default:return!1}}function fg(n){return lg(n.nsp)&&dg(n.id)&&ug(n.type,n.data)}var ul,fl,ii,hl,pl,U,oi,ai,ci,gl,Sr=R(()=>{ul=X(bt(),1);dl();ni();fl=X(Ie(),1),ii=(0,fl.default)("socket.io-parser"),hl=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],pl=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"})(U||(U={}));oi=class{constructor(e){this.replacer=e}encode(e){return ii("encoding packet %j",e),(e.type===U.EVENT||e.type===U.ACK)&&Cn(e)?this.encodeAsBinary({type:e.type===U.EVENT?U.BINARY_EVENT:U.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id}):[this.encodeAsString(e)]}encodeAsString(e){let t=""+e.type;return(e.type===U.BINARY_EVENT||e.type===U.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=cl(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},ai=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===U.BINARY_EVENT;r||t.type===U.BINARY_ACK?(t.type=r?U.EVENT:U.ACK,this.reconstructor=new ci(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Rn(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(U[r.type]===void 0)throw new Error("unknown packet type "+r.type);if(r.type===U.BINARY_EVENT||r.type===U.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 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 U.CONNECT:return kr(t);case U.DISCONNECT:return t===void 0;case U.CONNECT_ERROR:return typeof t=="string"||kr(t);case U.EVENT:case U.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&hl.indexOf(t[0])===-1);case U.ACK:case U.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},ci=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=ll(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 Oe(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var di=R(()=>{});var ml,yl,ce,hg,en,ui=R(()=>{Sr();di();ml=X(bt(),1),yl=X(Ie(),1),ce=(0,yl.default)("socket.io-client:socket"),hg=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),en=class extends ml.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=[Oe(e,"open",this.onopen.bind(this)),Oe(e,"packet",this.onpacket.bind(this)),Oe(e,"error",this.onerror.bind(this)),Oe(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(hg.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:U.EVENT,data:t};if(o.options={},o.options.compress=this.flags.compress!==!1,typeof t[t.length-1]=="function"){let l=this.ids++;ce("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?ce("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&&(ce("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));ce("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]?ce("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(ce("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(ce("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(ce("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){ce("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,ce("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(){ce("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:U.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){ce("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 U.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 U.EVENT:case U.BINARY_EVENT:this.onevent(e);break;case U.ACK:case U.BINARY_ACK:this.onack(e);break;case U.DISCONNECT:this.ondisconnect();break;case U.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||[];ce("emitting event %j",t),e.id!=null&&(ce("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,ce("sending ack %j",s),t.packet({type:U.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){ce("bad ack %s",e.id);return}delete this.acks[e.id],ce("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){ce("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(){ce("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&&(ce("performing disconnect (%s)",this.nsp),this.packet({type:U.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 Pt(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 _l=R(()=>{Pt.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};Pt.prototype.reset=function(){this.attempts=0};Pt.prototype.setMin=function(n){this.ms=n};Pt.prototype.setMax=function(n){this.max=n};Pt.prototype.setJitter=function(n){this.jitter=n}});var wl,vl,me,tn,bl=R(()=>{br();ui();Sr();di();_l();wl=X(bt(),1),vl=X(Ie(),1),me=(0,vl.default)("socket.io-client:manager"),tn=class extends wl.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,Ze(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 Pt({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||li;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(me("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;me("opening %s",this.uri),this.engine=new Zt(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Oe(t,"open",function(){r.onopen(),e&&e()}),i=a=>{me("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Oe(t,"error",i);if(this._timeout!==!1){let a=this._timeout;me("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{me("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(){me("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Oe(e,"ping",this.onping.bind(this)),Oe(e,"data",this.ondata.bind(this)),Oe(e,"error",this.onerror.bind(this)),Oe(e,"close",this.onclose.bind(this)),Oe(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){Qe(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){me("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new en(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){me("socket %s is still active, skipping close",r);return}this._close()}_packet(e){me("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(){me("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){me("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;me("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)me("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();me("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(me("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(me("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(me("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 An(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=il(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=On[s]&&i in On[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 tn(r,e)):(On[s]||(kl("new io instance for %s",r),On[s]=new tn(r,e)),c=On[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var Sl,kl,On,xl=R(()=>{ol();bl();ui();Sl=X(Ie(),1);Sr();br();kl=(0,Sl.default)("socket.io-client"),On={};Object.assign(An,{Manager:tn,Socket:en,io:An,connect:An})});var Ve,pg,xr,El=R(()=>{"use strict";xl();oe();Ve="wsClient",pg=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),xr=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,p("info",Ve,"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(Ve,"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=An(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{p("info",Ve,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{x(Ve,"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(Ve,"event handler threw",i)})});for(let t of pg)e.on(t,r=>{p("error",Ve,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,p("error",Ve,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{p("warn",Ve,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{x(Ve,"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,p("info",Ve,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var Ge,Er,Tl=R(()=>{"use strict";Mt();Fo();fs();El();oe();Ge="serverGateway",Er=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=lt(),p("info",Ge,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new xr({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>Bo(t,r)});let e=Do();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),p("info",Ge,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),p("info",Ge,`Gateway started \u2192 ${this.config.server_url}`)}async stop(){this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null),this.wsClient?.destroy(),this.wsClient=null,p("info",Ge,"Gateway stopped")}subscribe(e,t){if(!this.wsClient)throw new Error("Gateway not started \u2014 call start() first");this.wsClient.subscribe(e,t),p("info",Ge,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return qo(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await Ho(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1){await Go(this.config.server_url,this._getToken(),e)}async updateSessionStatus(e,t){await Wo(this.config.server_url,e,t,this._getToken())}async getAction(e){return Jo(this.config.server_url,e,this._getToken())}async getApproval(e){return Yo(this.config.server_url,e,this._getToken())}async fireAction(e,t){return Vo(this.config.server_url,e,this._getToken(),t)}async cancelAction(e){await zo(this.config.server_url,e,this._getToken())}async getChannelMessages(e,t,r,s){return Ko(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return Xo(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return Qo(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return ea(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return ta(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return Zo(this.config.server_url,e,this._getToken())}async getTasks(e,t){return na(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return ra(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return sa(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 oa(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return aa(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return ca(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await ua(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await la(this.config.server_url,this._getToken(),e,{channel_id:t,state:r})}async notifyAgentStatus(e,t,r){let s={state:r};t!==void 0&&(s.channel_id=t),await da(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r){return fa(this.config.server_url,this._getToken(),e,t,r)}async getMessageById(e,t){return ha(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){p("info",Ge,"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 jo(this.config.server_url,e,t,this._getToken());if(r.seq_expired){p("warn",Ge,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}p("info",Ge,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){x(Ge,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=lt(),t=await Uo(this.config.server_url,e);Gn(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),p("info",Ge,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){x(Ge,"token refresh failed",e)}}_getToken(){return this.token||(this.token=lt()),this.token}}});var pt,Cl,Tr,Rl=R(()=>{"use strict";oe();pt="sessionManager",Cl=3e4,Tr=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},Cl),p("info",pt,`Heartbeat timer started (every ${Cl/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(pt,`Failed to mark session ${t.sessionId} disconnected`,r)}))),p("info",pt,`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),p("info",pt,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){p("warn",pt,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,p("info",pt,"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(pt,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&p("debug",pt,`Sent ${e.length} heartbeat(s)`)}}});var ot,Cr,Ol=R(()=>{"use strict";oe();ot="workroomCoordinator",Cr=class{constructor(e,t){this.sessionManager=e;this.actionGate=t}sessionManager;actionGate;workroomRegistry=new Map;shuttingDown=!1;async openWorkroom(e){if(this.shuttingDown)return p("warn",ot,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return p("info",ot,"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(ot,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return x(ot,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{x(ot,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),p("info",ot,"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),p("info",ot,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){x(ot,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),p("info",ot,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as hi,unlink as gg,readdir as mg,stat as yg}from"fs/promises";import{join as Rr}from"path";import{randomBytes as pi}from"crypto";async function Pl(n,e){let t=pi(8).toString("hex"),r=Rr(vt,`action-${n}-${t}${Al}`),s;try{s=await hi(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return p("info",at,"secret file written",{actionId:n,filePath:r}),r}async function Pn(n){try{await gg(n),p("info",at,"secret file deleted",{filePath:n})}catch(e){if(fi(e))return;x(at,"failed to delete secret file (best-effort)",e)}}async function Il(){let n;try{n=await mg(vt)}catch(s){if(fi(s))return;x(at,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(Al)),r=0;for(let s of t){let i=Rr(vt,s);try{let o=await yg(i),a=e-o.mtimeMs;a>=_g&&(await Pn(i),r++,p("info",at,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(fi(o))continue;x(at,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&p("info",at,"TTL scan complete",{scanned:t.length,purged:r})}async function Nl(n){let e=Date.now(),t=pi(4).toString("hex"),r=Rr(vt,`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 p("info",at,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function Ml(n){let e=Date.now(),t=pi(4).toString("hex"),r=Rr(vt,`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 p("info",at,"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 at,_g,Al,Or=R(()=>{"use strict";Be();oe();at="secretManager",_g=600*1e3,Al=".secret"});import{spawn as wg}from"child_process";import{stat as vg}from"fs/promises";async function Ll(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return p("warn",It,"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 vg(e.path)}catch{return p("warn",It,"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 Pl(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return x(It,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=wg(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return x(It,"spawn failed",i),r&&Pn(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{p("info",It,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&Pn(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{x(It,"subprocess error after spawn",i),r&&Pn(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),p("info",It,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var It,$l=R(()=>{"use strict";oe();Or();It="runtimeAdapter"});var B,Dl,In,Bl,Nn,Fl,bg,Ar,gi=R(()=>{"use strict";fs();oe();$l();Or();B="actionGate",Dl=new Set(["proposed","approved"]),In=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),Bl="irreversible_no_abort",Nn=new Set(["transmission_complete","succeeded","canceled","failed"]),Fl=15,bg=8e3,Ar=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),p("info",B,"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);p("info",B,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,p("info",B,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=bg){if(this.inFlightIrreversible.size===0){p("info",B,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return p("warn",B,"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(B,"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 Nl({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.'});p("info",B,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){x(B,"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)&&Nn.has(r)&&this.gateway.getAction(t).then(s=>{Nn.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):p("warn",B,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{x(B,"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}),p("info",B,"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),p("info",B,"deregistered in-flight irreversible action",{actionId:e,source:t,remainingCount:this.inFlightIrreversible.size}),this._checkDrainComplete())}_checkDrainComplete(){if(this.inFlightIrreversible.size===0&&this.drainResolve!==null){p("info",B,"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=>{Nn.has(s.status)?(p("info",B,"subprocess exit: action confirmed drain-complete \u2014 deregistering",{actionId:e,exitCode:t,exitSignal:r,serverStatus:s.status}),this._deregisterInFlight(e,`subprocess_exit:${s.status}`)):p("warn",B,"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(B,"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(B,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){p("info",B,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){p("warn",B,"action.created: missing action_id in payload \u2014 ignoring");return}p("info",B,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(In.has(r.status)){p("info",B,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!Dl.has(r.status)){p("info",B,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===Bl?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){p("info",B,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&p("info",B,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),p("info",B,"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){p("warn",B,"approval.decided: missing required fields \u2014 ignoring");return}if(p("info",B,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),p("info",B,"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),In.has(i.status)){p("info",B,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!Dl.has(i.status)){p("warn",B,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){p("warn",B,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){p("warn",B,"approval already consumed \u2014 abort fire (anti-replay)",{approvalId:t});return}if(o.expires_at!==null&&new Date(o.expires_at)<=new Date){p("warn",B,"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&&In.has(r),a=i&&Nn.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&In.has(c.status)&&(this.pendingApproval.delete(t),p("info",B,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&Nn.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;p("info",B,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let l=await this.gateway.fireAction(r,t);p("info",B,"action fired",{actionId:r,fired_at:l.fired_at}),a=l.action_token,o=!0}catch(l){if(l instanceof un&&l.isDefinitiveRejection){x(B,`fire definitively rejected (${l.statusCode} ${l.errorCode}) \u2014 re-querying before cancel`,l);let f=await this.gateway.getAction(r).catch(()=>null);if(!f||In.has(f.status)){p("info",B,"action already in non-cancelable state after rejected fire \u2014 skipping cancel (concurrent winner?)",{actionId:r,currentStatus:f?.status});return}await this.gateway.cancelAction(r).catch(g=>{x(B,"cancel after rejected fire also failed",g)});return}x(B,"fire failed with uncertain error \u2014 reconciling action state",l);let u=await this.gateway.getAction(r).catch(()=>null);if(u?.status==="fired"){p("warn",B,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let f=u.fired_at??new Date().toISOString();await Ml({schema_version:1,reason:"fire_response_lost_token_unrecoverable",action_id:r,workroom_id:i,session_id:s,fired_at:f,operator_note:"The fire HTTP response was lost before the action_token was received. The raw token is unrecoverable (server stores only hash). The subprocess was NOT spawned. Verify action status on the server manually.",server_todo:'Server reconcile endpoint implemented (Phase 5C). POST /api/v1/actions/:id/reconcile with { reason: "fire_response_lost_token_unrecoverable", evidence_id: "<this-file-uuid>" }. Auth: machine_token bearer. Remove this file after reconcile confirms needs_human status.'}).catch(g=>{x(B,"failed to write response-lost evidence (CRITICAL)",g)});return}else{p("warn",B,"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===Bl;c&&this._registerInFlight(e);let d=await Ll({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||(p("warn",B,"spawn returned not-ok",{actionId:r,reason_code:d.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as kg}from"net";import{chmod as Sg}from"fs/promises";var ze,Pr,Ul=R(()=>{"use strict";oe();ze="ipcServer",Pr=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=kg(s=>{this._handleConnection(s)}),this.server.once("error",s=>{x(ze,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Sg(e,384)}catch(s){x(ze,"Failed to chmod IPC socket",s)}p("info",ze,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{p("info",ze,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){p("debug",ze,"subprocess connected");let t="";e.on("data",r=>{t+=r.toString("utf8");let s=t.split(`
|
|
211
|
-
`);t=s.pop()??"";for(let i of s){let o=i.trim();o&&this._processLine(o)}}),e.on("error",r=>{
|
|
212
|
-
`}catch(i){process.stderr.write(`[agentTrace] serialize error agent=${
|
|
213
|
-
`);return}let s=
|
|
214
|
-
`)});return}process.stderr.write(`[agentTrace] append failed agent=${
|
|
215
|
-
`)})}var jl,Nr,gt=R(()=>{"use strict";jl=Wl(Cg(),".mio","logs"),Nr=null});import{readFileSync as Pg,writeFileSync as Ig,existsSync as Ng}from"fs";import{join as Mg}from"path";function Jl(){return Mg(ue,"agent-inbox-cursor.json")}function Yl(){let n=Jl();if(!Ng(n))return{};try{return JSON.parse(Pg(n,"utf-8"))}catch{return{}}}function Lg(n){dn(),Ig(Jl(),JSON.stringify(n,null,2),{mode:384})}function Vl(n,e){return Yl()[`${n}:${e}`]??"0"}function Nt(n,e,t){let r=Yl(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,Lg(r))}var yi=R(()=>{"use strict";Be()});import{createServer as $g}from"http";import{randomBytes as Dg,timingSafeEqual as Bg}from"crypto";function Te(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Gg(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 Lr);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function Wg(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Bg(t,r)}async function be(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 zl(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??qg,c=i instanceof Set?i:new Set(i),d=Dg(32).toString("hex");async function l(m,_){if(m.method!=="POST"||m.url!=="/act"){_.writeHead(404),_.end();return}let k=m.headers.authorization??"",E=`Bearer ${d}`;if(!Wg(k,E)){Te(_,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let b;try{b=await Gg(m,Ug)}catch(F){if(F instanceof Lr){Te(_,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Te(_,400,{ok:!1,code:"INVALID_JSON"});return}let S;try{S=JSON.parse(b)}catch{Te(_,400,{ok:!1,code:"INVALID_JSON"});return}let O=S.action,T=S.payload!=null&&typeof S.payload=="object"?S.payload:{};if(O!=="attachment"&&Buffer.byteLength(b)>Fg){Te(_,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(O)){Te(_,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let A=Hg[O];if(!c.has(A)){Te(_,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let G={Authorization:`Bearer ${s}`,"X-Perf-Caller-Context":"agent_originated","X-Mio-Agent-Id":e,"Content-Type":"application/json"},q=Date.now();try{if(O==="send"){let F=T,W=null;if(o)try{let y=o.get(e);y&&typeof T.context_message_id!="string"&&(F={...T,context_message_id:y},W=y)}catch(y){x(mt,"contextTracker.get threw (non-fatal)",y)}let K=typeof T.target=="string"?T.target:null,H=typeof T.parent_message_id=="string"?T.parent_message_id:null,I=typeof T.content=="string"?T.content.slice(0,120):null;p("info",mt,"forward send",{agentId:e,target:K,parent_message_id:H,stamped_context:W!==null,context_message_id:W}),Z(e,"outbound",{action:"send",target:K,parent_message_id:H,context_message_id:W,context_message_id_short:W?W.replace(/-/g,"").slice(0,8):null,content_preview:I,content_bytes:typeof T.content=="string"?T.content.length:0}),await jg(_,r,G,F,a),Z(e,"outbound_done",{action:"send",status:_.statusCode,duration_ms:Date.now()-q})}else if(O==="reply"){let F=typeof T.target=="string"?T.target:null,W=typeof T.parent_message_id=="string"?T.parent_message_id:null,K=typeof T.content=="string"?T.content.slice(0,120):null;Z(e,"outbound",{action:"reply",target:F,parent_message_id:W,parent_message_id_short:W?W.replace(/-/g,"").slice(0,8):null,content_preview:K}),await Jg(_,r,G,T,a),Z(e,"outbound_done",{action:"reply",status:_.statusCode,duration_ms:Date.now()-q})}else if(O==="history")await Yg(_,r,G,T,a);else if(O==="task"){let F=typeof T.op=="string"?T.op:null;Z(e,"task",{action:F,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 zg(_,r,G,T,a),Z(e,"task_done",{action:F,status:_.statusCode,duration_ms:Date.now()-q})}else O==="reminder"?await Xg(_,r,G,T,a):O==="action"?await Zg(_,r,G,T,a):O==="react"?await em(_,r,G,T,a):O==="attachment"?await tm(_,r,G,T,a):O==="profile"?await nm(_,r,G,T,a):await rm(_,r,G,e,T,a)}catch(F){x(mt,"upstream forwarding error",F);let W=F instanceof Error&&F.name==="AbortError";Te(_,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:W?`upstream timed out after ${a}ms`:String(F)})}}let u=$g((m,_)=>{l(m,_).catch(k=>{x(mt,"unhandled request error",k),_.writeHead(500),_.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((m,_)=>{u.once("error",k=>{x(mt,"agent proxy startup error",k),_(k)}),u.listen(0,"127.0.0.1",()=>{let k=u.address(),E=typeof k=="object"&&k?k.port:0;p("info",mt,"agent proxy listening",{agentId:e,launchId:t,port:E}),m(E)})})}`,proxyToken:d,close:()=>new Promise(m=>{u.close(()=>{p("info",mt,"agent proxy stopped",{agentId:e,launchId:t}),m()})})}}async function jg(n,e,t,r,s){let i=await be(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await ke(n,i)}async function Jg(n,e,t,r,s){let i=await be(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await ke(n,i)}async function Yg(n,e,t,r,s){let i=sm(r),o=await be(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await ke(n,o)}async function zg(n,e,t,r,s){let i=String(r.op??""),o=Vg[i];if(!o){Te(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,f]of Object.entries(r))u!=="op"&&f!==void 0&&c.set(u,String(f));let d=c.toString(),l=await be(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await ke(n,l)}else{let{op:c,...d}=r,l=await be(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await ke(n,l)}}async function Xg(n,e,t,r,s){let i=String(r.op??""),o=Kg[i];if(!o){Te(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,f]of Object.entries(r))u!=="op"&&f!==void 0&&c.set(u,String(f));let d=c.toString(),l=await be(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await ke(n,l)}else{let{op:c,...d}=r,l=await be(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await ke(n,l)}}async function Zg(n,e,t,r,s){let i=String(r.op??""),o=Qg[i];if(!o){Te(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,f]of Object.entries(r))u!=="op"&&f!==void 0&&c.set(u,String(f));let d=c.toString(),l=await be(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await ke(n,l)}else{let{op:c,...d}=r,l=await be(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await ke(n,l)}}async function em(n,e,t,r,s){let i=await be(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await ke(n,i)}async function tm(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await be(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await ke(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await be(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await ke(n,a);return}Te(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function nm(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 be(c,{method:"GET",headers:t},s);await ke(n,d);return}if(i==="update"){let{op:o,...a}=r,c=await be(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await ke(n,c);return}Te(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function rm(n,e,t,r,s,i){let o=String(s.channel??""),a=Vl(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),d=await be(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!d.ok){await ke(n,d);return}let l=await d.json(),u=l.messages??[];if(u.length>0){let g=u.reduce((h,m)=>{let _=0n;try{_=BigInt(String(m.seq??"0"))}catch{x(mt,"bad seq from upstream",{seq:m.seq}),_=0n}return _>h?_:h},0n);g>0n&&Nt(r,o,g.toString())}let f=JSON.stringify(l);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(f)}),n.end(f)}async function ke(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{}Te(n,e.status,{ok:!1,code:r,message:s})}function sm(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 mt,Fg,Ug,qg,Hg,Lr,Vg,Kg,Qg,Kl=R(()=>{"use strict";oe();gt();yi();mt="agentProxy",Fg=1024*1024,Ug=12*1024*1024,qg=15e3,Hg={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};Lr=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};Vg={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"}};Kg={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"}};Qg={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as Xl,writeFile as _i,chmod as Ql}from"fs/promises";import{existsSync as Zl}from"fs";import{join as Mn,resolve as im,dirname as om}from"path";import{spawnSync as am}from"child_process";import{fileURLToPath as cm}from"url";function Ln(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function yt(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function lm(n){let e=om(cm(import.meta.url))+"/../..",t=n?.localTsxPath??im(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>Zl(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??dm)();return i||"tsx"}function dm(){let e=am("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&Zl(e)?e:null}function wi(n){let e=n!==void 0?n.execPath:process.execPath,t=n!==void 0?n.argv1:process.argv[1];return t===void 0||t===e?{mode:"sea",seaBinaryPath:e}:t.endsWith(".ts")?{mode:"tsx-source",tsxPath:lm(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function ed(n){let{agentId:e,launchId:t,workingDirectory:r,serverUrl:s,machineToken:i,capabilities:o=["send","read","tasks","reminders","actions","reactions","attachments","profile"]}=n,a=n.execContext??wi(),c=Mn(r,".mio");await Xl(c,{recursive:!0,mode:493});let d=await zl({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:l,proxyToken:u}=d;try{let f=Ln(e),g=Ln(t),h=Mn(ue,"agent-proxy-tokens",f),m=Mn(h,`${g}.token`);await Xl(h,{recursive:!0,mode:448}),await _i(m,u,{encoding:"utf8",mode:384}),await Ql(m,384);let _=o.join(","),k=um({execContext:a,proxyUrl:l,tokenFile:m,capabilityStr:_}),E=Mn(c,"mio");await _i(E,k,{encoding:"utf8",mode:493}),await Ql(E,493),await _i(Mn(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let b={...process.env},S=b.PATH??"";return b.PATH=S?`${c}:${S}`:c,delete b.CLAUDECODE,{mioDir:c,spawnEnv:b,proxyHandle:d}}catch(f){throw await d.close().catch(()=>{}),f}}function um(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${yt(t)} MIO_AGENT_PROXY_TOKEN_FILE=${yt(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${yt(s)}`,o;return e.mode==="npm"?o=`exec ${yt(e.nodePath)} ${yt(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${yt(e.tsxPath)} ${yt(e.cliEntryPath)} agentcli "$@"`:o=`exec ${yt(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
|
|
216
|
-
`)}var
|
|
210
|
+
`+t)}function Mt(n,e,t,r,s,i){if(n.listenerCount("wsClientError")){let o=new Error(s);Error.captureStackTrace(o,Mt),n.emit("wsClientError",o,t,e)}else On(t,r,s,i)}});var Kg,Xg,Qg,Zg,ep,tp,Qs,np,nl=A(()=>{Kg=te(Yc(),1),Xg=te(wr(),1),Qg=te(zt(),1),Zg=te(Hs(),1),ep=te(Ws(),1),tp=te(Ks(),1),Qs=te(Sr(),1),np=te(tl(),1)});var rl,sp,ip,xr,gv,Zs=A(()=>{bn();Rt();qt();Ct();rl=te($e(),1),sp=(0,rl.default)("engine.io-client:websocket"),ip=typeof navigator<"u"&&typeof navigator.product=="string"&&navigator.product.toLowerCase()==="reactnative",xr=class extends st{get name(){return"websocket"}doOpen(){let e=this.uri(),t=this.opts.protocols,r=ip?{}:rr(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;wn(r,this.supportsBinary,i=>{try{this.doWrite(r,i)}catch{sp("websocket closed before onclose event")}s&&nt(()=>{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)}},gv=ke.WebSocket||ke.MozWebSocket});var tn,ei=A(()=>{nl();Zs();tn=class extends xr{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 Qs.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 sl,An,nn,ti=A(()=>{bn();Ct();qt();sl=te($e(),1),An=(0,sl.default)("engine.io-client:webtransport"),nn=class extends st{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(()=>{An("transport closed gracefully"),this.onClose()}).catch(e=>{An("transport closed due to %s",e),this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{let t=Pa(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),s=Aa();s.readable.pipeTo(e.writable),this._writer=s.writable.getWriter();let i=()=>{r.read().then(({done:a,value:c})=>{if(a){An("session is closed");return}An("received chunk: %o",c),this.onPacket(c),i()}).catch(a=>{An("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&&nt(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;(e=this._transport)===null||e===void 0||e.close()}}});var ni,ri=A(()=>{As();ei();ti();ni={websocket:tn,webtransport:nn,polling:Jt}});function rn(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=op.exec(n||""),i={},o=14;for(;o--;)i[ap[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=cp(i,i.path),i.queryKey=lp(i,i.query),i}function cp(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 lp(n,e){let t={};return e.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(r,s,i){s&&(t[s]=i)}),t}var op,ap,si=A(()=>{op=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,ap=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"]});var il,ol,re,ii,Pn,Lt,Tr,sn,oi=A(()=>{ri();Rt();Ss();si();il=te(Tt(),1);qt();Ct();ol=te($e(),1),re=(0,ol.default)("engine.io-client:socket"),ii=typeof addEventListener=="function"&&typeof removeEventListener=="function",Pn=[];ii&&addEventListener("offline",()=>{re("closing %d connection(s) because the network was lost",Pn.length),Pn.forEach(n=>n())},!1);Lt=class n extends il.Emitter{constructor(e,t){if(super(),this.binaryType=Na,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=rn(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=rn(t.host).host);rt(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=Da(this.opts.query)),ii&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),this.hostname!=="localhost"&&(re("adding listener for the 'offline' event"),this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},Pn.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=Ma()),this._open()}createTransport(e){re('creating transport "%s"',e);let t=Object.assign({},this.opts.query);t.EIO=bs,t.transport=e,this.id&&(t.sid=this.id);let r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return re("options: %j",r),new this._transportsByName[e](r)}_open(){if(this.transports.length===0){this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);return}let e=this.opts.rememberUpgrade&&n.priorWebsocketSuccess&&this.transports.indexOf("websocket")!==-1?"websocket":this.transports[0];this.readyState="opening";let t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){re("setting transport %s",e.name),this.transport&&(re("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",t=>this._onClose("transport close",t))}onOpen(){re("socket open"),this.readyState="open",n.priorWebsocketSuccess=this.transport.name==="websocket",this.emitReserved("open"),this.flush()}_onPacket(e){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing")switch(re('socket receive: type "%s", data "%s"',e.type,e.data),this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":let t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data);break}else re('packet received with socket readyState "%s"',this.readyState)}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),this.readyState!=="closed"&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);let e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,this.writeBuffer.length===0?this.emitReserved("drain"):this.flush()}flush(){if(this.readyState!=="closed"&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){let e=this._getWritablePackets();re("flushing %d packets in socket",e.length),this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&this.transport.name==="polling"&&this.writeBuffer.length>1))return this.writeBuffer;let t=1;for(let r=0;r<this.writeBuffer.length;r++){let s=this.writeBuffer[r].data;if(s&&(t+=La(s)),r>0&&t>this._maxPayload)return re("only send %d out of %d packets",r,this.writeBuffer.length),this.writeBuffer.slice(0,r);t+=2}return re("payload size is %d (max: %d)",t,this._maxPayload),this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;let e=Date.now()>this._pingTimeoutTime;return e&&(re("throttled timer detected, scheduling connection close"),this._pingTimeoutTime=0,nt(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,s){if(typeof t=="function"&&(s=t,t=void 0),typeof r=="function"&&(s=r,r=null),this.readyState==="closing"||this.readyState==="closed")return;r=r||{},r.compress=r.compress!==!1;let i={type:e,data:t,options:r};this.emitReserved("packetCreate",i),this.writeBuffer.push(i),s&&this.once("flush",s),this.flush()}close(){let e=()=>{this._onClose("forced close"),re("socket closing - telling transport to close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return(this.readyState==="opening"||this.readyState==="open")&&(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(re("socket error %j",e),n.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&this.readyState==="opening")return re("trying next transport"),this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if(this.readyState==="opening"||this.readyState==="open"||this.readyState==="closing"){if(re('socket close with reason: "%s"',e),this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),ii&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){let r=Pn.indexOf(this._offlineEventListener);r!==-1&&(re("removing listener for the 'offline' event"),Pn.splice(r,1))}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}};Lt.protocol=bs;Tr=class extends Lt{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),this.readyState==="open"&&this.opts.upgrade){re("starting upgrade probes");for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}}_probe(e){re('probing transport "%s"',e);let t=this.createTransport(e),r=!1;Lt.priorWebsocketSuccess=!1;let s=()=>{r||(re('probe transport "%s" opened',e),t.send([{type:"ping",data:"probe"}]),t.once("packet",u=>{if(!r)if(u.type==="pong"&&u.data==="probe"){if(re('probe transport "%s" pong',e),this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Lt.priorWebsocketSuccess=t.name==="websocket",re('pausing current transport "%s"',this.transport.name),this.transport.pause(()=>{r||this.readyState!=="closed"&&(re("changing transport and sending upgrade packet"),l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{re('probe transport "%s" failed',e);let f=new Error("probe error");f.transport=t.name,this.emitReserved("upgradeError",f)}}))};function i(){r||(r=!0,l(),t.close(),t=null)}let o=u=>{let f=new Error("probe error: "+u);f.transport=t.name,i(),re('probe transport "%s" failed because of error: %s',e,u),this.emitReserved("upgradeError",f)};function a(){o("transport closed")}function c(){o("socket closed")}function d(u){t&&u.name!==t.name&&(re('"%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}},sn=class extends Tr{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=>ni[s]).filter(s=>!!s)),super(e,r)}}});var al=A(()=>{Ts()});var Dv,Cr=A(()=>{oi();oi();bn();ri();Rt();si();Ct();al();As();Rs();ei();Zs();ti();Dv=sn.protocol});function dl(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)||(cl("protocol-less url %s",n),typeof t<"u"?n=t.protocol+"//"+n:n="https://"+n),cl("parse %s",n),r=rn(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 ll,cl,ul=A(()=>{Cr();ll=te($e(),1),cl=(0,ll.default)("socket.io-client:url")});function Nn(n){return hp&&(n instanceof ArrayBuffer||gp(n))||pp&&n instanceof Blob||mp&&n instanceof File}function In(n,e){if(!n||typeof n!="object")return!1;if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(In(n[t]))return!0;return!1}if(Nn(n))return!0;if(n.toJSON&&typeof n.toJSON=="function"&&arguments.length===1)return In(n.toJSON(),!0);for(let t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&In(n[t]))return!0;return!1}var hp,gp,fl,pp,mp,ai=A(()=>{hp=typeof ArrayBuffer=="function",gp=n=>typeof ArrayBuffer.isView=="function"?ArrayBuffer.isView(n):n.buffer instanceof ArrayBuffer,fl=Object.prototype.toString,pp=typeof Blob=="function"||typeof Blob<"u"&&fl.call(Blob)==="[object BlobConstructor]",mp=typeof File=="function"||typeof File<"u"&&fl.call(File)==="[object FileConstructor]"});function hl(n){let e=[],t=n.data,r=n;return r.data=ci(t,e),r.attachments=e.length,{packet:r,buffers:e}}function ci(n,e){if(!n)return n;if(Nn(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]=ci(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]=ci(n[r],e));return t}return n}function gl(n,e){return n.data=li(n.data,e),delete n.attachments,n}function li(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]=li(n[t],e);else if(typeof n=="object")for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&(n[t]=li(n[t],e));return n}var pl=A(()=>{ai()});var gi={};Ce(gi,{Decoder:()=>fi,Encoder:()=>ui,PacketType:()=>G,isPacketValid:()=>vp,protocol:()=>wl});function yp(n){return typeof n=="string"}function _p(n){return n===void 0||vl(n)}function Rr(n){return Object.prototype.toString.call(n)==="[object Object]"}function wp(n,e){switch(n){case G.CONNECT:return e===void 0||Rr(e);case G.DISCONNECT:return e===void 0;case G.EVENT:return Array.isArray(e)&&(typeof e[0]=="number"||typeof e[0]=="string"&&_l.indexOf(e[0])===-1);case G.ACK:return Array.isArray(e);case G.CONNECT_ERROR:return typeof e=="string"||Rr(e);default:return!1}}function vp(n){return yp(n.nsp)&&_p(n.id)&&wp(n.type,n.data)}var ml,yl,di,_l,wl,G,ui,fi,hi,vl,Or=A(()=>{ml=te(Tt(),1);pl();ai();yl=te($e(),1),di=(0,yl.default)("socket.io-parser"),_l=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"],wl=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={}));ui=class{constructor(e){this.replacer=e}encode(e){return di("encoding packet %j",e),(e.type===G.EVENT||e.type===G.ACK)&&In(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)),di("encoded %j as %s",e,t),t}encodeAsBinary(e){let t=hl(e),r=this.encodeAsString(t.packet),s=t.buffers;return s.unshift(r),s}},fi=class n extends ml.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 hi(t),t.attachments===0&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else if(Nn(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(!vl(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 di("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 Rr(t);case G.DISCONNECT:return t===void 0;case G.CONNECT_ERROR:return typeof t=="string"||Rr(t);case G.EVENT:case G.BINARY_EVENT:return Array.isArray(t)&&(typeof t[0]=="number"||typeof t[0]=="string"&&_l.indexOf(t[0])===-1);case G.ACK:case G.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}},hi=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=gl(this.reconPack,this.buffers);return this.finishedReconstruction(),t}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}};vl=Number.isInteger||function(n){return typeof n=="number"&&isFinite(n)&&Math.floor(n)===n}});function Oe(n,e,t){return n.on(e,t),function(){n.off(e,t)}}var pi=A(()=>{});var bl,kl,fe,bp,on,mi=A(()=>{Or();pi();bl=te(Tt(),1),kl=te($e(),1),fe=(0,kl.default)("socket.io-client:socket"),bp=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1}),on=class extends bl.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=[Oe(e,"open",this.onopen.bind(this)),Oe(e,"packet",this.onpacket.bind(this)),Oe(e,"error",this.onerror.bind(this)),Oe(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(bp.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++;fe("emitting packet with ack id %d",l);let u=t.pop();this._registerAckCallback(l,u),o.id=l}let a=(s=(r=this.io.engine)===null||r===void 0?void 0:r.transport)===null||s===void 0?void 0:s.writable,c=this.connected&&!(!((i=this.io.engine)===null||i===void 0)&&i._hasPingExpired());return this.flags.volatile&&!a?fe("discard packet as the transport is not currently writable"):c?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o),this.flags={},this}_registerAckCallback(e,t){var r;let s=(r=this.flags.timeout)!==null&&r!==void 0?r:this._opts.ackTimeout;if(s===void 0){this.acks[e]=t;return}let i=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let a=0;a<this.sendBuffer.length;a++)this.sendBuffer[a].id===e&&(fe("removing packet with ack id %d from the buffer",e),this.sendBuffer.splice(a,1));fe("event with ack id %d has timed out after %d ms",e,s),t.call(this,new Error("operation has timed out"))},s),o=(...a)=>{this.io.clearTimeoutFn(i),t.apply(this,a)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,s)=>{let i=(o,a)=>o?s(o):r(a);i.withError=!0,t.push(i),this.emit(e,...t)})}_addToQueue(e){let t;typeof e[e.length-1]=="function"&&(t=e.pop());let r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((s,...i)=>r!==this._queue[0]?fe("packet [%d] already acknowledged",r.id):(s!==null?r.tryCount>this._opts.retries&&(fe("packet [%d] is discarded after %d tries",r.id,r.tryCount),this._queue.shift(),t&&t(s)):(fe("packet [%d] was successfully sent",r.id),this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue())),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(fe("draining queue"),!this.connected||this._queue.length===0)return;let t=this._queue[0];if(t.pending&&!e){fe("packet [%d] has already been sent and is waiting for an ack",t.id);return}t.pending=!0,t.tryCount++,fe("sending packet [%d] (try n\xB0%d)",t.id,t.tryCount),this.flags=t.flags,this.emit.apply(this,t.args)}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){fe("transport is open - connecting"),typeof this.auth=="function"?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type: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){fe("close (%s)",e),this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(r=>String(r.id)===e)){let r=this.acks[e];delete this.acks[e],r.withError&&r.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case 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||[];fe("emitting event %j",t),e.id!=null&&(fe("attaching ack callback to event"),t.push(this.ack(e.id))),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){let t=this._anyListeners.slice();for(let r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&typeof e[e.length-1]=="string"&&(this._lastOffset=e[e.length-1])}ack(e){let t=this,r=!1;return function(...s){r||(r=!0,fe("sending ack %j",s),t.packet({type:G.ACK,id:e,data:s}))}}onack(e){let t=this.acks[e.id];if(typeof t!="function"){fe("bad ack %s",e.id);return}delete this.acks[e.id],fe("calling ack %s with %j",e.id,e.data),t.withError&&e.data.unshift(null),t.apply(this,e.data)}onconnect(e,t){fe("socket connected with id %s",e),this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this._drainQueue(!0),this.emitReserved("connect")}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){fe("server disconnect (%s)",this.nsp),this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&(fe("performing disconnect (%s)",this.nsp),this.packet({type: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 $t(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 Sl=A(()=>{$t.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};$t.prototype.reset=function(){this.attempts=0};$t.prototype.setMin=function(n){this.ms=n};$t.prototype.setMax=function(n){this.max=n};$t.prototype.setJitter=function(n){this.jitter=n}});var El,xl,_e,an,Tl=A(()=>{Cr();mi();Or();pi();Sl();El=te(Tt(),1),xl=te($e(),1),_e=(0,xl.default)("socket.io-client:manager"),an=class extends El.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,rt(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 $t({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(t.timeout==null?2e4:t.timeout),this._readyState="closed",this.uri=e;let s=t.parser||gi;this.encoder=new s.Encoder,this.decoder=new s.Decoder,this._autoConnect=t.autoConnect!==!1,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return e===void 0?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return e===void 0?this._reconnectionDelay:(this._reconnectionDelay=e,(t=this.backoff)===null||t===void 0||t.setMin(e),this)}randomizationFactor(e){var t;return e===void 0?this._randomizationFactor:(this._randomizationFactor=e,(t=this.backoff)===null||t===void 0||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return e===void 0?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,(t=this.backoff)===null||t===void 0||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&this.backoff.attempts===0&&this.reconnect()}open(e){if(_e("readyState %s",this._readyState),~this._readyState.indexOf("open"))return this;_e("opening %s",this.uri),this.engine=new sn(this.uri,this.opts);let t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;let s=Oe(t,"open",function(){r.onopen(),e&&e()}),i=a=>{_e("error"),this.cleanup(),this._readyState="closed",this.emitReserved("error",a),e?e(a):this.maybeReconnectOnOpen()},o=Oe(t,"error",i);if(this._timeout!==!1){let a=this._timeout;_e("connect attempt will timeout after %d",a);let c=this.setTimeoutFn(()=>{_e("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(){_e("open"),this.cleanup(),this._readyState="open",this.emitReserved("open");let e=this.engine;this.subs.push(Oe(e,"ping",this.onping.bind(this)),Oe(e,"data",this.ondata.bind(this)),Oe(e,"error",this.onerror.bind(this)),Oe(e,"close",this.onclose.bind(this)),Oe(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){nt(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){_e("error",e),this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new on(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){_e("socket %s is still active, skipping close",r);return}this._close()}_packet(e){_e("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(){_e("cleanup"),this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){_e("disconnect"),this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;_e("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)_e("reconnect failed"),this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{let t=this.backoff.duration();_e("will wait %dms before reconnect attempt",t),this._reconnecting=!0;let r=this.setTimeoutFn(()=>{e.skipReconnect||(_e("attempting reconnect"),this.emitReserved("reconnect_attempt",e.backoff.attempts),!e.skipReconnect&&e.open(s=>{s?(_e("reconnect attempt error"),e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",s)):(_e("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 Ln(n,e){typeof n=="object"&&(e=n,n=void 0),e=e||{};let t=dl(n,e.path||"/socket.io"),r=t.source,s=t.id,i=t.path,o=Mn[s]&&i in Mn[s].nsps,a=e.forceNew||e["force new connection"]||e.multiplex===!1||o,c;return a?(Cl("ignoring socket cache for %s",r),c=new an(r,e)):(Mn[s]||(Cl("new io instance for %s",r),Mn[s]=new an(r,e)),c=Mn[s]),t.query&&!e.query&&(e.query=t.queryKey),c.socket(t.path,e)}var Rl,Cl,Mn,Ol=A(()=>{ul();Tl();mi();Rl=te($e(),1);Or();Cr();Cl=(0,Rl.default)("socket.io-client"),Mn={};Object.assign(Ln,{Manager:an,Socket:on,io:Ln,connect:Ln})});var Xe,kp,Ar,Al=A(()=>{"use strict";Ol();ce();Xe="wsClient",kp=new Set(["FORBIDDEN","MISSING_FIELDS","INVALID_TOKEN"]),Ar=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,p("info",Xe,"Token updated (will take effect on next subscribe)")}async dispatchCatchUpEvents(e,t){let r=this.handlers.get(e);if(r)for(let s of t){this._advanceSeq(s.workroom_id,s.seq);for(let i of r)await Promise.resolve(i(s)).catch(o=>{k(Xe,"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=Ln(this.opts.serverUrl,{path:"/api/v1/ws/control",reconnection:!1,transports:["websocket"]});this.socket=e,e.on("connect",()=>{p("info",Xe,"WS connected",{attempt:this.reconnectAttempt}),this.reconnectAttempt=0,this.opts.onReconnect?Promise.resolve(this.opts.onReconnect()).then(()=>this._resubscribeAll()).catch(t=>{k(Xe,"onReconnect hook failed",t),this._resubscribeAll()}):this._resubscribeAll()}),e.on("workroom:event",t=>{this._advanceSeq(t.workroom_id,t.seq);let r=this.handlers.get(t.workroom_id);if(r)for(let s of r)Promise.resolve(s(t)).catch(i=>{k(Xe,"event handler threw",i)})});for(let t of kp)e.on(t,r=>{p("error",Xe,`Auth error from server: ${t}`,{payload:typeof r=="object"?r:{raw:r}}),this.authFailed=!0,p("error",Xe,"Reconnect suppressed \u2014 fix machine_token and restart daemon")});e.on("disconnect",t=>{p("warn",Xe,"WS disconnected",{reason:t,authFailed:this.authFailed}),this.socket=null,this.authFailed||this._scheduleReconnect()}),e.on("connect_error",t=>{k(Xe,"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,p("info",Xe,`Reconnecting in ${r}ms`,{attempt:this.reconnectAttempt}),this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=null,!this.destroyed&&!this.authFailed&&this._connect()},r)}}});var je,Pr,Pl=A(()=>{"use strict";Ft();Wo();Zn();Al();ce();je="serverGateway",Pr=class{constructor(e){this.config=e}config;wsClient=null;tokenRefreshTimer=null;token="";async start(){this.token=ht(),p("info",je,"machine_token loaded from Keychain (not logged, not stored in config)"),this.wsClient=new Ar({serverUrl:this.config.server_url,token:this.token,onReconnect:()=>this._onWsReconnect(),onSeqUpdate:(t,r)=>Go(t,r)});let e=qo();for(let[t,r]of e)this.wsClient.lastSeenSeq.set(t,r),p("info",je,"Restored cursor from disk",{workroomId:t,seq:r});this.wsClient.connect(),p("info",je,`Gateway started \u2192 ${this.config.server_url}`)}async stop(){this.tokenRefreshTimer&&(clearTimeout(this.tokenRefreshTimer),this.tokenRefreshTimer=null),this.wsClient?.destroy(),this.wsClient=null,p("info",je,"Gateway stopped")}subscribe(e,t){if(!this.wsClient)throw new Error("Gateway not started \u2014 call start() first");this.wsClient.subscribe(e,t),p("info",je,"Subscribed to workroom",{workroomId:e})}unsubscribe(e,t){this.wsClient?.unsubscribe(e,t)}async createSession(e){return Jo(this.config.server_url,e,this._getToken())}async sessionHeartbeat(e){await Yo(this.config.server_url,e,this._getToken())}async machineHeartbeat(e=!1){await Vo(this.config.server_url,this._getToken(),e)}async updateSessionStatus(e,t){await zo(this.config.server_url,e,t,this._getToken())}async getAction(e){return Xo(this.config.server_url,e,this._getToken())}async getApproval(e){return Qo(this.config.server_url,e,this._getToken())}async fireAction(e,t){return Zo(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 ta(this.config.server_url,e,t,r,s,this._getToken())}async postChannelMessage(e,t,r){return Qn(this.config.server_url,e,t,r,this._getToken())}async getWorkroomMembers(e){return na(this.config.server_url,e,this._getToken())}async getWorkroomChannels(e){return sa(this.config.server_url,e,this._getToken())}async getAgentChannels(e){return ia(this.config.server_url,this._getToken(),e)}async getWorkroomRoster(e){return ra(this.config.server_url,e,this._getToken())}async getTasks(e,t){return oa(this.config.server_url,this._getToken(),e,t)}async scheduleReminder(e,t){return aa(this.config.server_url,this._getToken(),e,t)}async listReminders(e){return ca(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 da(this.config.server_url,this._getToken(),e,t)}async cancelReminder(e,t){return ua(this.config.server_url,this._getToken(),e,t)}async reminderLog(e){return fa(this.config.server_url,this._getToken(),e)}async reminderFire(e,t,r){await pa(this.config.server_url,this._getToken(),e,{id:t,version:r})}async notifyTyping(e,t,r){await ha(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 ga(this.config.server_url,this._getToken(),e,s)}async getThreadReplies(e,t,r){return ma(this.config.server_url,this._getToken(),e,t,r)}async getMessageById(e,t){return ya(this.config.server_url,this._getToken(),e,t)}async _onWsReconnect(){if(this.wsClient){p("info",je,"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 Ko(this.config.server_url,e,t,this._getToken());if(r.seq_expired){p("warn",je,"catch-up seq_expired \u2014 snapshot reload needed (not yet implemented)",{workroomId:e,afterSeq:t,events_behind:r.events_behind});return}p("info",je,`Replaying ${r.events.length} missed events`,{workroomId:e,afterSeq:t}),await this.wsClient.dispatchCatchUpEvents(e,r.events)}catch(r){k(je,"catch-up request failed \u2014 will retry on next reconnect",r)}}async _refreshToken(){try{let e=ht(),t=await jo(this.config.server_url,e);Yn(t.machine_token),this.token=t.machine_token,this.wsClient?.updateToken(t.machine_token),p("info",je,"machine_token refreshed \u2014 Keychain updated, old token gone")}catch(e){k(je,"token refresh failed",e)}}_getToken(){return this.token||(this.token=ht()),this.token}}});var _t,Il,Ir,Nl=A(()=>{"use strict";ce();_t="sessionManager",Il=3e4,Ir=class{constructor(e){this.gateway=e}gateway;sessions=new Map;heartbeatTimer=null;startHeartbeats(){this.heartbeatTimer||(this.heartbeatTimer=setInterval(()=>{this._sendHeartbeats()},Il),p("info",_t,`Heartbeat timer started (every ${Il/1e3}s)`))}async stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null);let e=[...this.sessions.values()].filter(t=>t.status!=="completed"&&t.status!=="failed");await Promise.all(e.map(t=>this.updateStatus(t.sessionId,"disconnected").catch(r=>{k(_t,`Failed to mark session ${t.sessionId} disconnected`,r)}))),p("info",_t,`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),p("info",_t,"Session created",{sessionId:r.sessionId,workroomId:e}),r}async updateStatus(e,t){let r=this.sessions.get(e);if(!r){p("warn",_t,`updateStatus: unknown sessionId ${e}`);return}await this.gateway.updateSessionStatus(e,t),r.status=t,p("info",_t,"Session status updated",{sessionId:e,status:t})}getSession(e){return this.sessions.get(e)}getAllSessions(){return[...this.sessions.values()]}async _sendHeartbeats(){let e=[...this.sessions.values()].filter(t=>t.status!=="completed"&&t.status!=="failed"&&t.status!=="disconnected");await Promise.all(e.map(t=>this.gateway.sessionHeartbeat(t.sessionId).catch(r=>{k(_t,`Heartbeat failed for session ${t.sessionId}`,r)}))),e.length>0&&p("debug",_t,`Sent ${e.length} heartbeat(s)`)}}});var dt,Nr,Ml=A(()=>{"use strict";ce();dt="workroomCoordinator",Nr=class{constructor(e,t){this.sessionManager=e;this.actionGate=t}sessionManager;actionGate;workroomRegistry=new Map;shuttingDown=!1;async openWorkroom(e){if(this.shuttingDown)return p("warn",dt,"openWorkroom called during shutdown \u2014 ignoring",{workroomId:e}),null;let t=this.workroomRegistry.get(e);if(t)return p("info",dt,"openWorkroom: workroom already open \u2014 reusing session",{workroomId:e,sessionId:t.sessionId}),t;let r;try{r=await this.sessionManager.createSession(e)}catch(s){return k(dt,"openWorkroom: createSession failed \u2014 not subscribing to workroom events",s),null}try{this.actionGate.registerWorkroom(e)}catch(s){return k(dt,"openWorkroom: registerWorkroom/subscribe failed after createSession \u2014 compensating session",s),await this.sessionManager.updateStatus(r.sessionId,"disconnected").catch(i=>{k(dt,"openWorkroom: compensation updateStatus also failed",i)}),null}return this.workroomRegistry.set(e,r),p("info",dt,"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),p("info",dt,"shutdownAll: deregistered workroom",{workroomId:e})}catch(t){k(dt,"shutdownAll: deregisterWorkroom error (non-fatal)",t)}this.workroomRegistry.clear(),p("info",dt,"shutdownAll: all workrooms deregistered")}getSession(e){return this.workroomRegistry.get(e)}getOpenWorkrooms(){return[...this.workroomRegistry.keys()]}}});import{open as _i,unlink as Sp,readdir as Ep,stat as xp}from"fs/promises";import{join as Mr}from"path";import{randomBytes as wi}from"crypto";async function $l(n,e){let t=wi(8).toString("hex"),r=Mr(xt,`action-${n}-${t}${Ll}`),s;try{s=await _i(r,"wx",384),await s.writeFile(e,"utf-8")}finally{await s?.close()}return p("info",ut,"secret file written",{actionId:n,filePath:r}),r}async function $n(n){try{await Sp(n),p("info",ut,"secret file deleted",{filePath:n})}catch(e){if(yi(e))return;k(ut,"failed to delete secret file (best-effort)",e)}}async function Dl(){let n;try{n=await Ep(xt)}catch(s){if(yi(s))return;k(ut,"scanAndPurgeStaleTtl: failed to read TMP_DIR",s);return}let e=Date.now(),t=n.filter(s=>s.endsWith(Ll)),r=0;for(let s of t){let i=Mr(xt,s);try{let o=await xp(i),a=e-o.mtimeMs;a>=Tp&&(await $n(i),r++,p("info",ut,"purged stale secret file (TTL expired)",{name:s,ageSeconds:Math.round(a/1e3)}))}catch(o){if(yi(o))continue;k(ut,"scanAndPurgeStaleTtl: error processing file",o)}}(r>0||t.length>0)&&p("info",ut,"TTL scan complete",{scanned:t.length,purged:r})}async function Bl(n){let e=Date.now(),t=wi(4).toString("hex"),r=Mr(xt,`drain-evidence-${e}-${t}.json`),s;try{s=await _i(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return p("info",ut,"drain evidence file written",{filePath:r,actionCount:n.action_ids.length}),r}async function Fl(n){let e=Date.now(),t=wi(4).toString("hex"),r=Mr(xt,`response-lost-${e}-${t}.json`),s;try{s=await _i(r,"wx",384),await s.writeFile(JSON.stringify(n,null,2),"utf-8")}finally{await s?.close()}return p("info",ut,"response-lost evidence file written",{filePath:r,actionId:n.action_id,reason:n.reason}),r}function yi(n){return typeof n=="object"&&n!==null&&"code"in n&&n.code==="ENOENT"}var ut,Tp,Ll,Lr=A(()=>{"use strict";He();ce();ut="secretManager",Tp=600*1e3,Ll=".secret"});import{spawn as Cp}from"child_process";import{stat as Rp}from"fs/promises";async function Ul(n){let e=n.runtimes.find(i=>i.kind===n.kind&&i.enabled);if(!e)return p("warn",Dt,"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 Rp(e.path)}catch{return p("warn",Dt,"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 $l(n.actionId,n.secretContent),t.MIO_SECRET_PATH=r}catch(i){return k(Dt,"failed to write secret file \u2014 aborting spawn",i),{ok:!1,reason_code:"SPAWN_FAILED"}}let s;try{s=Cp(e.path,e.args??[],{detached:!1,stdio:"pipe",env:t})}catch(i){return k(Dt,"spawn failed",i),r&&$n(r),{ok:!1,reason_code:"SPAWN_FAILED"}}return s.on("exit",(i,o)=>{p("info",Dt,"subprocess exited",{actionId:n.actionId,pid:s.pid,code:i,signal:o}),r&&$n(r),n.onSubprocessExit?.(i,o)}),s.on("error",i=>{k(Dt,"subprocess error after spawn",i),r&&$n(r)}),s.stdout?.on("data",()=>{}),s.stderr?.on("data",()=>{}),p("info",Dt,"subprocess spawned",{actionId:n.actionId,kind:n.kind,pid:s.pid,hasSecret:!!r}),{ok:!0}}var Dt,Hl=A(()=>{"use strict";ce();Lr();Dt="runtimeAdapter"});var U,ql,Dn,Gl,Bn,Wl,Op,$r,vi=A(()=>{"use strict";Zn();ce();Hl();Lr();U="actionGate",ql=new Set(["proposed","approved"]),Dn=new Set(["fired","canceled","failed","succeeded","transmission_complete","needs_human"]),Gl="irreversible_no_abort",Bn=new Set(["transmission_complete","succeeded","canceled","failed"]),Wl=15,Op=8e3,$r=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),p("info",U,"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);p("info",U,"deregistered from workroom",{workroomId:e})}beginShutdown(){this._shuttingDown=!0,p("info",U,"beginShutdown: ignoring new action.created events")}async drainIrreversible(e=Op){if(this.inFlightIrreversible.size===0){p("info",U,"drainIrreversible: no in-flight irreversible actions \u2014 exiting immediately");return}let t=[...this.inFlightIrreversible.keys()];return p("warn",U,"SIGTERM with irreversible_no_abort actions in flight \u2014 bounded drain started",{count:this.inFlightIrreversible.size,actionIds:t,deadlineMs:e}),new Promise(r=>{this.drainResolve=r,this.drainTimeoutId=setTimeout(async()=>{this.drainResolve=null,this.drainTimeoutId=null;let s=new Map(this.inFlightIrreversible);k(U,"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 Bl({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.'});p("info",U,"drain evidence written \u2014 operator must verify before restart",{evidencePath:i})}catch(i){k(U,"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)&&Bn.has(r)&&this.gateway.getAction(t).then(s=>{Bn.has(s.status)?this._deregisterInFlight(t,`ipc_status_changed:${s.status}`):p("warn",U,"IPC status_changed claims drain-complete but server disagrees \u2014 keeping in drain",{actionId:t,ipcStatus:r,serverStatus:s.status})}).catch(s=>{k(U,"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}),p("info",U,"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),p("info",U,"deregistered in-flight irreversible action",{actionId:e,source:t,remainingCount:this.inFlightIrreversible.size}),this._checkDrainComplete())}_checkDrainComplete(){if(this.inFlightIrreversible.size===0&&this.drainResolve!==null){p("info",U,"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=>{Bn.has(s.status)?(p("info",U,"subprocess exit: action confirmed drain-complete \u2014 deregistering",{actionId:e,exitCode:t,exitSignal:r,serverStatus:s.status}),this._deregisterInFlight(e,`subprocess_exit:${s.status}`)):p("warn",U,"subprocess exit: action not yet drain-complete \u2014 awaiting WS/IPC signal or drain deadline",{actionId:e,exitCode:t,exitSignal:r,serverStatus:s.status,note:"subprocess may have sent output; server may still be processing"})}).catch(s=>{k(U,"subprocess exit: failed to re-query action \u2014 keeping in drain (conservative)",s)})}async _handleEvent(e){let{topic:t,payload:r}=e;try{t==="action.created"?await this._onActionCreated(r):t==="approval.decided"?await this._onApprovalDecided(r):t==="action.status_changed"&&await this._onActionStatusChanged(r)}catch(s){k(U,`Unhandled error in event handler (topic=${t})`,s)}}async _onActionCreated(e){if(this._shuttingDown){p("info",U,"action.created: shutdown in progress \u2014 ignoring new action",{action_id:e.action_id});return}let t=e.action_id;if(!t){p("warn",U,"action.created: missing action_id in payload \u2014 ignoring");return}p("info",U,"action.created \u2014 fetching authoritative state",{actionId:t});let r=await this.gateway.getAction(t);if(Dn.has(r.status)){p("info",U,"action already terminal \u2014 skip (catch-up replay?)",{actionId:t,status:r.status});return}if(!ql.has(r.status)){p("info",U,"action not in fireable status \u2014 skip",{actionId:t,status:r.status});return}r.reversibility===Gl?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){p("info",U,"irreversible_no_abort has pre-existing approved approval \u2014 firing",{actionId:t,approvalId:s}),await this._fireAndSpawn(e,s);return}o&&p("info",U,"pre-existing approval expired \u2014 awaiting new approval decision",{actionId:t,approvalId:s})}this.pendingApproval.set(t,r),p("info",U,"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){p("warn",U,"approval.decided: missing required fields \u2014 ignoring");return}if(p("info",U,"approval.decided received",{approvalId:t,actionId:r,decision:s}),s!=="approved"){this.pendingApproval.delete(r),p("info",U,"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),Dn.has(i.status)){p("info",U,"action already terminal after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(!ql.has(i.status)){p("warn",U,"action not fireable after approval.decided \u2014 skip",{actionId:r,status:i.status});return}if(o.status!=="approved"){p("warn",U,"authoritative approval not in approved state \u2014 abort fire",{approvalId:t,approvalStatus:o.status});return}if(o.consumed){p("warn",U,"approval already consumed \u2014 abort fire (anti-replay)",{approvalId:t});return}if(o.expires_at!==null&&new Date(o.expires_at)<=new Date){p("warn",U,"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&&Dn.has(r),a=i&&Bn.has(r);if(!o&&!a)return;let c=await this.gateway.getAction(t).catch(()=>null);c&&(s&&Dn.has(c.status)&&(this.pendingApproval.delete(t),p("info",U,"action became terminal \u2014 cleared from pendingApproval (approval.decided will not arrive)",{actionId:t,status:c.status})),i&&Bn.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;p("info",U,"firing action",{actionId:r,reversibility:e.reversibility,hasApproval:!!t});let o=!1,a;try{let l=await this.gateway.fireAction(r,t);p("info",U,"action fired",{actionId:r,fired_at:l.fired_at}),a=l.action_token,o=!0}catch(l){if(l instanceof mn&&l.isDefinitiveRejection){k(U,`fire definitively rejected (${l.statusCode} ${l.errorCode}) \u2014 re-querying before cancel`,l);let f=await this.gateway.getAction(r).catch(()=>null);if(!f||Dn.has(f.status)){p("info",U,"action already in non-cancelable state after rejected fire \u2014 skipping cancel (concurrent winner?)",{actionId:r,currentStatus:f?.status});return}await this.gateway.cancelAction(r).catch(h=>{k(U,"cancel after rejected fire also failed",h)});return}k(U,"fire failed with uncertain error \u2014 reconciling action state",l);let u=await this.gateway.getAction(r).catch(()=>null);if(u?.status==="fired"){p("warn",U,"reconcile: fire response lost \u2014 action_token unrecoverable; halting spawn",{actionId:r});let f=u.fired_at??new Date().toISOString();await Fl({schema_version:1,reason:"fire_response_lost_token_unrecoverable",action_id:r,workroom_id:i,session_id:s,fired_at:f,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(h=>{k(U,"failed to write response-lost evidence (CRITICAL)",h)});return}else{p("warn",U,"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===Gl;c&&this._registerInFlight(e);let d=await Ul({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||(p("warn",U,"spawn returned not-ok",{actionId:r,reason_code:d.reason_code}),c&&this._deregisterInFlight(r,"spawn_failed"))}}});import{createServer as Ap}from"net";import{chmod as Pp}from"fs/promises";var Qe,Dr,jl=A(()=>{"use strict";ce();Qe="ipcServer",Dr=class{server=null;handler=null;onMessage(e){this.handler=e}async listen(e){return new Promise((t,r)=>{this.server=Ap(s=>{this._handleConnection(s)}),this.server.once("error",s=>{k(Qe,"IPC server startup error",s),r(s)}),this.server.listen(e,async()=>{try{await Pp(e,384)}catch(s){k(Qe,"Failed to chmod IPC socket",s)}p("info",Qe,"IPC server listening",{socketPath:e}),t()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{p("info",Qe,"IPC server stopped"),e()}),this.server=null})}_handleConnection(e){p("debug",Qe,"subprocess connected");let t="";e.on("data",r=>{t+=r.toString("utf8");let s=t.split(`
|
|
211
|
+
`);t=s.pop()??"";for(let i of s){let o=i.trim();o&&this._processLine(o)}}),e.on("error",r=>{k(Qe,"IPC socket connection error",r)}),e.on("close",()=>{p("debug",Qe,"subprocess disconnected")})}_processLine(e){let t;try{t=JSON.parse(e)}catch{p("warn",Qe,"malformed IPC message (not JSON) \u2014 ignored");return}if(typeof t.type!="string"){p("warn",Qe,"IPC message missing required `type` field \u2014 ignored");return}p("debug",Qe,"IPC message received",{type:t.type}),this.handler?.(t)}}});import{createServer as Ip}from"http";var bi,Np,Mp,Br,Jl=A(()=>{"use strict";ce();bi="healthServer",Np="127.0.0.1",Mp=7878,Br=class{constructor(e){this.version=e}version;server=null;startTime=Date.now();async listen(e=Np,t=Mp){return new Promise((r,s)=>{this.server=Ip((i,o)=>this._handleRequest(i,o)),this.server.once("error",i=>{k(bi,"Health server startup error",i),s(i)}),this.server.listen(t,e,()=>{p("info",bi,`Health server listening on ${e}:${t}`),r()})})}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{p("info",bi,"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 Yl,mkdir as Vl}from"node:fs/promises";import{homedir as Lp}from"node:os";import{dirname as $p,join as zl}from"node:path";function Dp(){return Fr||(Fr=Vl(Kl,{recursive:!0}).then(()=>{},n=>{throw Fr=null,n})),Fr}function Ur(n){return n&&n.replace(/-/g,"").slice(0,8)||"unknown"}function Bp(n){return zl(Kl,`agent-${Ur(n)}.jsonl`)}function ee(n,e,t){let r;try{let i={ts:new Date().toISOString(),agent_id:n,kind:e,...t};r=JSON.stringify(i)+`
|
|
212
|
+
`}catch(i){process.stderr.write(`[agentTrace] serialize error agent=${Ur(n)} kind=${e}: ${i.message}
|
|
213
|
+
`);return}let s=Bp(n);Dp().then(()=>Yl(s,r,{encoding:"utf8"})).catch(i=>{if(i.code==="ENOENT"){let o=$p(s);Vl(o,{recursive:!0}).then(()=>Yl(s,r,{encoding:"utf8"})).catch(a=>{process.stderr.write(`[agentTrace] append failed agent=${Ur(n)} kind=${e}: ${a.message}
|
|
214
|
+
`)});return}process.stderr.write(`[agentTrace] append failed agent=${Ur(n)} kind=${e}: ${i.message}
|
|
215
|
+
`)})}var Kl,Fr,wt=A(()=>{"use strict";Kl=zl(Lp(),".mio","logs"),Fr=null});import{readFileSync as Fp,writeFileSync as Up,existsSync as Hp}from"fs";import{join as qp}from"path";function Xl(){return qp(he,"agent-inbox-cursor.json")}function Ql(){let n=Xl();if(!Hp(n))return{};try{return JSON.parse(Fp(n,"utf-8"))}catch{return{}}}function Gp(n){pn(),Up(Xl(),JSON.stringify(n,null,2),{mode:384})}function Zl(n,e){return Ql()[`${n}:${e}`]??"0"}function vt(n,e,t){let r=Ql(),s=`${n}:${e}`,i=r[s];(!i||BigInt(t)>BigInt(i))&&(r[s]=t,Gp(r))}var ki=A(()=>{"use strict";He()});import{createServer as Wp}from"http";import{randomBytes as jp,timingSafeEqual as Jp}from"crypto";function Te(n,e,t){let r=JSON.stringify(t);n.writeHead(e,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(r)}),n.end(r)}function Xp(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 Hr);return}s.push(o)}),n.on("end",()=>t(Buffer.concat(s).toString("utf8"))),n.on("error",r)})}function Qp(n,e){let t=Buffer.from(n,"utf8"),r=Buffer.from(e,"utf8");return t.length!==r.length?!1:Jp(t,r)}async function Se(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 ed(n){let{agentId:e,launchId:t,serverUrl:r,machineToken:s,capabilities:i,contextTracker:o}=n,a=n.upstreamTimeoutMs??zp,c=i instanceof Set?i:new Set(i),d=jp(32).toString("hex");async function l(m,y){if(m.method!=="POST"||m.url!=="/act"){y.writeHead(404),y.end();return}let b=m.headers.authorization??"",x=`Bearer ${d}`;if(!Qp(b,x)){Te(y,401,{ok:!1,code:"PROXY_TOKEN_INVALID"});return}let v;try{v=await Xp(m,Vp)}catch(H){if(H instanceof Hr){Te(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}Te(y,400,{ok:!1,code:"INVALID_JSON"});return}let S;try{S=JSON.parse(v)}catch{Te(y,400,{ok:!1,code:"INVALID_JSON"});return}let M=S.action,T=S.payload!=null&&typeof S.payload=="object"?S.payload:{};if(M!=="attachment"&&Buffer.byteLength(v)>Yp){Te(y,413,{ok:!1,code:"BODY_TOO_LARGE"});return}if(!["send","reply","history","check","task","reminder","action","react","attachment","profile"].includes(M)){Te(y,400,{ok:!1,code:"UNKNOWN_ACTION"});return}let N=Kp[M];if(!c.has(N)){Te(y,403,{ok:!1,code:"CAPABILITY_DENIED"});return}let j={Authorization:`Bearer ${s}`,"X-Perf-Caller-Context":"agent_originated","X-Mio-Agent-Id":e,"Content-Type":"application/json"},W=Date.now();try{if(M==="send"){let H=T,Y=null;if(o)try{let w=o.get(e);w&&typeof T.context_message_id!="string"&&(H={...T,context_message_id:w},Y=w)}catch(w){k(bt,"contextTracker.get threw (non-fatal)",w)}let K=typeof T.target=="string"?T.target:null,q=typeof T.parent_message_id=="string"?T.parent_message_id:null,ne=typeof T.content=="string"?T.content.slice(0,120):null;p("info",bt,"forward send",{agentId:e,target:K,parent_message_id:q,stamped_context:Y!==null,context_message_id:Y}),ee(e,"outbound",{action:"send",target:K,parent_message_id:q,context_message_id:Y,context_message_id_short:Y?Y.replace(/-/g,"").slice(0,8):null,content_preview:ne,content_bytes:typeof T.content=="string"?T.content.length:0}),await Zp(y,r,j,H,a),ee(e,"outbound_done",{action:"send",status:y.statusCode,duration_ms:Date.now()-W})}else if(M==="reply"){let H=typeof T.target=="string"?T.target:null,Y=typeof T.parent_message_id=="string"?T.parent_message_id:null,K=typeof T.content=="string"?T.content.slice(0,120):null;ee(e,"outbound",{action:"reply",target:H,parent_message_id:Y,parent_message_id_short:Y?Y.replace(/-/g,"").slice(0,8):null,content_preview:K}),await em(y,r,j,T,a),ee(e,"outbound_done",{action:"reply",status:y.statusCode,duration_ms:Date.now()-W})}else if(M==="history")await tm(y,r,j,T,a);else if(M==="task"){let H=typeof T.op=="string"?T.op:null;ee(e,"task",{action:H,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 rm(y,r,j,T,a),ee(e,"task_done",{action:H,status:y.statusCode,duration_ms:Date.now()-W})}else M==="reminder"?await im(y,r,j,T,a):M==="action"?await am(y,r,j,T,a):M==="react"?await cm(y,r,j,T,a):M==="attachment"?await lm(y,r,j,T,a):M==="profile"?await dm(y,r,j,T,a):await um(y,r,j,e,T,a)}catch(H){k(bt,"upstream forwarding error",H);let Y=H instanceof Error&&H.name==="AbortError";Te(y,502,{ok:!1,code:"UPSTREAM_UNREACHABLE",message:Y?`upstream timed out after ${a}ms`:String(H)})}}let u=Wp((m,y)=>{l(m,y).catch(b=>{k(bt,"unhandled request error",b),y.writeHead(500),y.end()})});return{proxyUrl:`http://127.0.0.1:${await new Promise((m,y)=>{u.once("error",b=>{k(bt,"agent proxy startup error",b),y(b)}),u.listen(0,"127.0.0.1",()=>{let b=u.address(),x=typeof b=="object"&&b?b.port:0;p("info",bt,"agent proxy listening",{agentId:e,launchId:t,port:x}),m(x)})})}`,proxyToken:d,close:()=>new Promise(m=>{u.close(()=>{p("info",bt,"agent proxy stopped",{agentId:e,launchId:t}),m()})})}}async function Zp(n,e,t,r,s){let i=await Se(`${e}/internal/agent-api/send`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ee(n,i)}async function em(n,e,t,r,s){let i=await Se(`${e}/internal/agent-api/threads/reply`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ee(n,i)}async function tm(n,e,t,r,s){let i=fm(r),o=await Se(`${e}/internal/agent-api/history${i}`,{method:"GET",headers:t},s);await Ee(n,o)}async function rm(n,e,t,r,s){let i=String(r.op??""),o=nm[i];if(!o){Te(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,f]of Object.entries(r))u!=="op"&&f!==void 0&&c.set(u,String(f));let d=c.toString(),l=await Se(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Ee(n,l)}else{let{op:c,...d}=r,l=await Se(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Ee(n,l)}}async function im(n,e,t,r,s){let i=String(r.op??""),o=sm[i];if(!o){Te(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,f]of Object.entries(r))u!=="op"&&f!==void 0&&c.set(u,String(f));let d=c.toString(),l=await Se(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Ee(n,l)}else{let{op:c,...d}=r,l=await Se(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Ee(n,l)}}async function am(n,e,t,r,s){let i=String(r.op??""),o=om[i];if(!o){Te(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,f]of Object.entries(r))u!=="op"&&f!==void 0&&c.set(u,String(f));let d=c.toString(),l=await Se(d?`${a}?${d}`:a,{method:"GET",headers:t},s);await Ee(n,l)}else{let{op:c,...d}=r,l=await Se(a,{method:"POST",headers:t,body:JSON.stringify(d)},s);await Ee(n,l)}}async function cm(n,e,t,r,s){let i=await Se(`${e}/internal/agent-api/messages/react`,{method:"POST",headers:t,body:JSON.stringify(r)},s);await Ee(n,i)}async function lm(n,e,t,r,s){let i=String(r.op??"");if(i==="upload"){let{op:o,...a}=r,c=await Se(`${e}/internal/agent-api/attachments`,{method:"POST",headers:t,body:JSON.stringify(a)},s);await Ee(n,c);return}if(i==="view"){let o=encodeURIComponent(String(r.attachment_id??"")),a=await Se(`${e}/internal/agent-api/attachments/${o}`,{method:"GET",headers:t},s);await Ee(n,a);return}Te(n,400,{ok:!1,code:"UNKNOWN_ATTACHMENT_OP",message:`Unknown attachment op: ${i}`})}async function dm(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 Se(c,{method:"GET",headers:t},s);await Ee(n,d);return}if(i==="update"){let{op:o,...a}=r,c=await Se(`${e}/internal/agent-api/profile`,{method:"PATCH",headers:t,body:JSON.stringify(a)},s);await Ee(n,c);return}Te(n,400,{ok:!1,code:"UNKNOWN_PROFILE_OP",message:`Unknown profile op: ${i}`})}async function um(n,e,t,r,s,i){let o=String(s.channel??""),a=Zl(r,o),c=new URLSearchParams({channel:o,after_seq:a}).toString(),d=await Se(`${e}/internal/agent-api/history?${c}`,{method:"GET",headers:t},i);if(!d.ok){await Ee(n,d);return}let l=await d.json(),u=l.messages??[];if(u.length>0){let h=u.reduce((g,m)=>{let y=0n;try{y=BigInt(String(m.seq??"0"))}catch{k(bt,"bad seq from upstream",{seq:m.seq}),y=0n}return y>g?y:g},0n);h>0n&&vt(r,o,h.toString())}let f=JSON.stringify(l);n.writeHead(200,{"Content-Type":"application/json","Content-Length":Buffer.byteLength(f)}),n.end(f)}async function Ee(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{}Te(n,e.status,{ok:!1,code:r,message:s})}function fm(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 bt,Yp,Vp,zp,Kp,Hr,nm,sm,om,td=A(()=>{"use strict";ce();wt();ki();bt="agentProxy",Yp=1024*1024,Vp=12*1024*1024,zp=15e3,Kp={send:"send",reply:"send",history:"read",check:"read",task:"tasks",reminder:"reminders",action:"actions",react:"reactions",attachment:"attachments",profile:"profile"};Hr=class extends Error{constructor(){super("request body exceeds limit"),this.name="BodyTooLargeError"}};nm={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"}};sm={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"}};om={prepare:{method:"POST",path:"prepare"},list:{method:"GET",path:"list"}}});import{mkdir as nd,writeFile as Si,chmod as rd}from"fs/promises";import{existsSync as sd}from"fs";import{join as Fn,resolve as hm,dirname as gm}from"path";import{spawnSync as pm}from"child_process";import{fileURLToPath as mm}from"url";function Un(n){return n.replace(/[^a-zA-Z0-9-]/g,"-").replace(/-{2,}/g,"-").replace(/^-+|-+$/g,"")||"unknown"}function kt(n){return`'${n.replace(/'/g,`'"'"'`)}'`}function ym(n){let e=gm(mm(import.meta.url))+"/../..",t=n?.localTsxPath??hm(e,"node_modules/.bin/tsx"),r=n?.localTsxExists??(o=>sd(o));if(n?.resolveTsx)return n.resolveTsx(t);if(r(t))return t;let i=(n?.pathTsxLookup??_m)();return i||"tsx"}function _m(){let e=pm("which",["tsx"],{encoding:"utf8",env:process.env}).stdout?.trim();return e&&sd(e)?e:null}function Ei(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:ym(n),cliEntryPath:t}:t.endsWith(".js")?{mode:"npm",nodePath:e,cliEntryPath:t}:{mode:"sea",seaBinaryPath:e}}async function id(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??Ei(),c=Fn(r,".mio");await nd(c,{recursive:!0,mode:493});let d=await ed({agentId:e,launchId:t,serverUrl:s,machineToken:i,capabilities:o,...n.contextTracker?{contextTracker:n.contextTracker}:{}}),{proxyUrl:l,proxyToken:u}=d;try{let f=Un(e),h=Un(t),g=Fn(he,"agent-proxy-tokens",f),m=Fn(g,`${h}.token`);await nd(g,{recursive:!0,mode:448}),await Si(m,u,{encoding:"utf8",mode:384}),await rd(m,384);let y=o.join(","),b=wm({execContext:a,proxyUrl:l,tokenFile:m,capabilityStr:y}),x=Fn(c,"mio");await Si(x,b,{encoding:"utf8",mode:493}),await rd(x,493),await Si(Fn(c,"mcp-config.json"),JSON.stringify({mcpServers:{}}),{encoding:"utf8",mode:384});let v={...process.env},S=v.PATH??"";return v.PATH=S?`${c}:${S}`:c,delete v.CLAUDECODE,{mioDir:c,spawnEnv:v,proxyHandle:d}}catch(f){throw await d.close().catch(()=>{}),f}}function wm(n){let{execContext:e,proxyUrl:t,tokenFile:r,capabilityStr:s}=n,i=`MIO_AGENT_PROXY_URL=${kt(t)} MIO_AGENT_PROXY_TOKEN_FILE=${kt(r)} MIO_AGENT_ACTIVE_CAPABILITIES=${kt(s)}`,o;return e.mode==="npm"?o=`exec ${kt(e.nodePath)} ${kt(e.cliEntryPath)} agentcli "$@"`:e.mode==="tsx-source"?o=`exec ${kt(e.tsxPath)} ${kt(e.cliEntryPath)} agentcli "$@"`:o=`exec ${kt(e.seaBinaryPath)} agentcli "$@"`,["#!/usr/bin/env bash",`${i} ${o}`,""].join(`
|
|
216
|
+
`)}var od=A(()=>{"use strict";He();td()});function ad(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 vm,bm,km,Sm,Em,xm,cd,ld=A(()=>{"use strict";vm=`## Role: Product Manager
|
|
217
217
|
|
|
218
218
|
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.
|
|
219
219
|
|
|
@@ -248,7 +248,7 @@ Deliberative on scope, decisive on next step. Default to "let's get one concrete
|
|
|
248
248
|
- Bundle everything into one giant announcement. One concrete deliverable per message = one task.
|
|
249
249
|
|
|
250
250
|
### Posting cadence
|
|
251
|
-
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.`,
|
|
251
|
+
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.`,bm=`## Role: Engineer
|
|
252
252
|
|
|
253
253
|
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.
|
|
254
254
|
|
|
@@ -282,7 +282,7 @@ Pragmatic. Prefer the boring correct solution. When two approaches are roughly e
|
|
|
282
282
|
- Apologise for limitations. Just state what's done and what's left.
|
|
283
283
|
|
|
284
284
|
### Posting cadence
|
|
285
|
-
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.`,
|
|
285
|
+
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.`,km=`## Role: Designer
|
|
286
286
|
|
|
287
287
|
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.
|
|
288
288
|
|
|
@@ -315,7 +315,7 @@ Reference-driven. When in doubt, point to a precedent \u2014 either in this prod
|
|
|
315
315
|
- Design the happy path only.
|
|
316
316
|
|
|
317
317
|
### Posting cadence
|
|
318
|
-
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.`,
|
|
318
|
+
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.`,Sm=`## Role: Researcher
|
|
319
319
|
|
|
320
320
|
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.
|
|
321
321
|
|
|
@@ -348,7 +348,7 @@ Evidence-led. Form an opinion only after you've seen the data; revise the opinio
|
|
|
348
348
|
- Recommend an action without separating it from the evidence ("the data shows X; my read is therefore Y").
|
|
349
349
|
|
|
350
350
|
### Posting cadence
|
|
351
|
-
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.`,
|
|
351
|
+
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.`,Em=`## Role: Ops / SRE
|
|
352
352
|
|
|
353
353
|
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.
|
|
354
354
|
|
|
@@ -381,7 +381,7 @@ Cautious by default \u2014 production systems are real. Move faster on reversibl
|
|
|
381
381
|
- Treat a fix as done until you've watched it stay healthy for at least one cycle.
|
|
382
382
|
|
|
383
383
|
### Posting cadence
|
|
384
|
-
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.`,
|
|
384
|
+
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.`,xm=`## Role: Generalist
|
|
385
385
|
|
|
386
386
|
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.
|
|
387
387
|
|
|
@@ -412,14 +412,14 @@ Take initiative on small, reversible things. Escalate to a human or specialist f
|
|
|
412
412
|
- Stretch one request into a sprawling project. Stay scoped.
|
|
413
413
|
|
|
414
414
|
### Posting cadence
|
|
415
|
-
Match the cadence of whoever you're talking to. When in doubt: send each logical step as its own short message.`,
|
|
415
|
+
Match the cadence of whoever you're talking to. When in doubt: send each logical step as its own short message.`,cd={product_manager:vm,engineer:bm,designer:km,researcher:Sm,ops:Em,general:xm}});function Mm(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 Lm(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 ${Mm(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(`
|
|
416
416
|
`);return`${e.channelName?`## In #${e.channelName} right now`:"## In this channel right now"}
|
|
417
417
|
|
|
418
418
|
${r}
|
|
419
419
|
|
|
420
|
-
For teammates in other channels, load the \`mio-team\` skill.`}function
|
|
420
|
+
For teammates in other channels, load the \`mio-team\` skill.`}function dd(n){let{agentId:e,handle:t,displayName:r,description:s,role:i,serverId:o,computer:a,hostname:c,os:d,workspace:l}=n,u=n.presetRole??ad(r,`${i??""} ${s}`),f=cd[u],h=s&&s.trim()?`## Additional context from your operator
|
|
421
421
|
|
|
422
|
-
${s.trim()}`:"",
|
|
422
|
+
${s.trim()}`:"",g=`## Runtime context
|
|
423
423
|
|
|
424
424
|
This is authoritative \u2014 do NOT infer your identity, host, or workspace from anything else when this section is present.
|
|
425
425
|
|
|
@@ -432,70 +432,77 @@ This is authoritative \u2014 do NOT infer your identity, host, or workspace from
|
|
|
432
432
|
- OS: ${d}
|
|
433
433
|
- Workspace: ${l}
|
|
434
434
|
|
|
435
|
-
When someone writes ${t} they are addressing YOU.`,m=`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\`.`,
|
|
435
|
+
When someone writes ${t} they are addressing YOU.`,m=`You are **${r}**, an AI teammate on a Mio team. Your stable @mention handle is \`${t}\`. You collaborate with humans and other AI agents over a shared messaging platform; you persist across sessions through your workspace and \`MEMORY.md\`.`,y=Lm(n),b=500,x=n.persona?n.persona.trim():"",v=x.length>b?x.slice(0,b).replace(/\s+\S*$/,"")+"\u2026":x,S=v.length>0?`## What I've learned (from past interactions)
|
|
436
436
|
|
|
437
|
-
${
|
|
437
|
+
${v}`:"";return[m,Tm,Rm,Om,Am,f,h,g,y,S,Nm,Pm,n.runtime==="codex"?Im:"",Cm].filter(T=>T&&T.length>0).join(`
|
|
438
438
|
|
|
439
439
|
`)+`
|
|
440
|
-
`}var
|
|
440
|
+
`}var Tm,Cm,Rm,Om,Am,Pm,Im,Nm,ud=A(()=>{"use strict";ld();Tm='## 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.',Cm='## Reminder \u2014 hard constraints (reinforced)\n\nBefore you send anything to a human, check:\n\n- Are you about to paste a `mio` command, an endpoint, a UUID, a raw message ID, or any internal plumbing? STOP. Translate it.\n- Are you about to say "CLI", "command", "API", "tool", "endpoint", "proxy", "agent-api", or any other internal-mechanism word \u2014 even as a bare concept ("CLI \u6CA1\u6709\u8FD9\u4E2A\u547D\u4EE4", "\u5DE5\u5177\u4E0D\u652F\u6301")? STOP. Rephrase as a human teammate would: describe what you CAN do, or say "\u6211\u6CA1\u6CD5\u76F4\u63A5\u505A\u8FD9\u4E2A" without naming the mechanism.\n- Are you about to echo the `@handle` or the `[target=... msg=...]` header? STOP. Drop it.\n- Is this message inside a thread (`[thread context \u2026]`)? Then normal task discussion goes to `mio message reply --parent \u2026`, not `mio message send`. Exception: if you are coordinating and splitting separate independent work for other teammates, send fresh main-channel one-line @handoffs with `mio message send`, one handoff per task.\n- The server-side classifier auto-creates tasks from actionable main-channel messages \u2014 you do NOT call `mio task create` for delegation. To delegate work, send separate short main-channel messages tagging one assignee each (e.g. `@Backend \u5B9E\u73B0 X`); the classifier converts each one to a task and wakes them. A task assigned TO you is born already owned + already `in_progress` \u2014 do NOT list, claim, or set `in_progress`; just start it. `mio task claim #N` is ONLY for picking up an UNASSIGNED `todo` task that has no owner.\n- **Wrong-person handoff.** If someone addresses YOU with work that clearly belongs to another teammate\'s role (check the roster\'s roles/descriptions above), do NOT attempt it yourself and do NOT just refuse. Hand it off: send one short main-channel message `@<the right teammate> <one-line of what\'s needed>`, and tell the human in natural language that you\'ve passed it to that teammate (name them by name, never by @handle-echo). Pick the teammate whose described role best fits the request. Only take it on yourself if it genuinely fits YOUR role. If no teammate fits, say so plainly and suggest the closest option.\n- Are you hedging, apologising, disclaiming, or restating the question? STOP. Just answer.\n\nThe user sees natural language only. The mechanism is YOURS to manage, never theirs to hear about.\n\n\u274C "CLI \u6CA1\u6709\u76F4\u63A5\u6307\u6D3E\u7ED9\u4ED6\u4EBA\u7684\u547D\u4EE4" / "\u6211\u7684\u5DE5\u5177\u4E0D\u652F\u6301\u8FD9\u4E2A" / "API \u6CA1\u6709\u8FD9\u4E2A\u7AEF\u70B9"\n\u2713 "\u6211\u6CA1\u6CD5\u76F4\u63A5\u5E2E\u4ED6\u8BA4\u9886\uFF0C\u5F97\u4ED6\u81EA\u5DF1\u63A5\u624B" / "\u8FD9\u4EF6\u4E8B\u6211\u505A\u4E0D\u4E86\uFF0C\u5F97\u8BF7\u64CD\u4F5C\u5458" / "\u6211\u624B\u5934\u67E5\u4E0D\u5230"',Rm="## 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`.",Om=`## System-event wakes
|
|
441
441
|
|
|
442
442
|
A \`[system event: ...]\` wake = task status changed / assigned / new in channel.
|
|
443
443
|
Post a brief status only if something meaningful actually changed worth telling
|
|
444
444
|
the team. Otherwise stay silent. Never re-ack the same event twice; never fake
|
|
445
|
-
activity.`,
|
|
445
|
+
activity.`,Am=`## Posting cadence
|
|
446
446
|
|
|
447
|
-
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.`,
|
|
447
|
+
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.`,Pm="## 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",Im='## 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]`.',Nm=`## Startup and memory
|
|
448
448
|
|
|
449
449
|
1. On every startup, read \`MEMORY.md\` in your cwd first. It is your recovery point after context compression or sleep.
|
|
450
450
|
2. If this turn includes an incoming message, decide whether it needs a reply and handle it.
|
|
451
451
|
3. If there is no incoming message, stop and wait. New messages may be delivered automatically.
|
|
452
452
|
4. Complete ALL your work before stopping \u2014 don't leave a half-finished thought.
|
|
453
453
|
|
|
454
|
-
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
|
|
455
|
-
`),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var
|
|
456
|
-
`)}var
|
|
457
|
-
`)}}function f(
|
|
458
|
-
`}function
|
|
459
|
-
`);return}
|
|
460
|
-
`)}if(
|
|
461
|
-
`);f("coalesce_flush",{coalesced_count:
|
|
462
|
-
`)});let C=
|
|
463
|
-
`)}},
|
|
464
|
-
`)}}
|
|
465
|
-
`))
|
|
466
|
-
`)
|
|
467
|
-
`)
|
|
468
|
-
`)}
|
|
469
|
-
`),
|
|
470
|
-
`)
|
|
471
|
-
`)}
|
|
472
|
-
`)}
|
|
473
|
-
`)
|
|
474
|
-
`)
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
`)}function bd(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:d,onInjected:l,reminderCache:u,onInboundMessage:f,contextTracker:g,contextPolicy:h=Dn}=n,m=a??e.getChannelMessages.bind(e),_=new Map;async function k(y){let w=await e.getWorkroomChannels(o);for(let v of w)v.id&&v.name&&_.set(v.id,v.name);return _.get(y)}let E=c??k;async function b(y){let w=_.get(y);if(w!==void 0)return w;let v=await E(y);return v!==void 0&&_.set(y,v),v}let S=d??(async()=>new Set((await e.getAgentChannels(r)).map(y=>y.id))),O=null,T=new Set,A=250,G=5e3,q=A,F=y=>new Promise(w=>{let v=setTimeout(w,y);typeof v.unref=="function"&&v.unref()});function W(){let y=S().then(w=>(q=A,w)).catch(w=>{x(z,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",w);let v=q;return q=Math.min(q*2,G),O===y&&(O=F(v).then(()=>(W(),O??new Set))),new Set});O=y}let K;t.onInjected(y=>{K?.(y)}),l&&(K=l);async function H(y){if(y.topic==="reminder.upserted"||y.topic==="reminder.canceled"){if(u){let N=y.payload;if(y.topic==="reminder.upserted")if(N.reminder){if(N.reminder.agentId!==r)return;u.upsert(N.reminder)}else p("warn",z,"reminder.upserted event missing reminder payload",{payload:y.payload});else if(N.reminderId){if(N.agentId!==r)return;u.cancel(N.reminderId,N.version)}else p("warn",z,"reminder.canceled event missing reminderId",{payload:y.payload})}return}if(y.topic==="channel.member_added"||y.topic==="channel.member_removed"||y.topic==="roster.member_added"||y.topic==="roster.member_removed"){let N=y.payload;N.member_id===r&&(p("info",z,"membership changed for self \u2014 invalidating membership cache",{topic:y.topic,channelId:N.channel_id}),T.clear(),W());return}if(y.topic!=="message.created"&&y.topic!=="thread.reply")return;let w=y.payload,v=w.channel_id,C=w.seq,$=w.message_id,M=w.parent_message_id;if(!v||!C){p("warn",z,"message.created event missing channel_id or seq",{payload:w});return}Z(r,"event_received",{topic:y.topic,channel_id:v,seq:C,message_id:$??null,parent_message_id:M??null});let J=(await(O??Promise.resolve(new Set))).has(v);if(!J&&!T.has(v)){p("info",z,"re-verifying membership for unknown channel before skip",{channelId:v,seq:C});try{let N=await S();O=Promise.resolve(N),q=A,J=N.has(v),J?p("info",z,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:v,seq:C}):T.add(v)}catch(N){x(z,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",N)}}if(!J){p("debug",z,"skip not-a-member channel",{channelId:v,seq:C,topic:y.topic}),Z(r,"skip",{reason:"not_a_member",channel_id:v,seq:C,topic:y.topic});return}if(w.sender_id&&w.sender_id===r){p("debug",z,"skip self-authored message (pre-fetch)",{seq:C,sender_id:w.sender_id}),Z(r,"skip",{reason:"self_authored_prefetch",channel_id:v,seq:C,message_id:$??null});return}let P,j;if(y.topic==="thread.reply"){if(!M){p("warn",z,"thread.reply event missing parent_message_id",{payload:w});return}if(!e.getThreadReplies){p("warn",z,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:v,messageSeq:C});return}try{let N=await e.getThreadReplies(r,M,50);j=N,P=$&&N.find(ee=>ee.id===$)||N.find(ee=>ee.seq===C),P&&!P.parent_message_id&&(P={...P,parent_message_id:M})}catch(N){x(z,"failed to fetch thread replies after thread.reply event",N);return}}else{let N=(BigInt(C)-1n).toString();try{P=(await m(o,v,N,1)).messages.find(Le=>Le.seq===C)}catch(ee){x(z,"failed to fetch message after message.created event",ee);return}}if(!P){p("warn",z,"message not found in GET response",{channelId:v,messageSeq:C,topic:y.topic});return}if(P.sender_id===r){p("debug",z,"skip self-authored message",{seq:C,sender_id:P.sender_id}),Z(r,"skip",{reason:"self_authored",channel_id:v,seq:C,message_id:P.id});return}let re=vd(P.content,s,i),le=!!P.parent_message_id;if(P.sender_kind==="system"&&!h.deliverSystemMessages){p("debug",z,"skip system message by context policy",{seq:C,message_id:P.id}),Z(r,"skip",{reason:"context_policy_system_message",channel_id:v,seq:C,message_id:P.id}),Nt(r,v,P.seq);return}if(!le&&P.sender_kind!=="system"&&!h.deliverBroadcastMessages&&!re){p("debug",z,"skip broadcast message by context policy",{seq:C,message_id:P.id}),Z(r,"skip",{reason:"context_policy_broadcast_message",channel_id:v,seq:C,message_id:P.id}),Nt(r,v,P.seq);return}if(le&&P.sender_kind!=="system"&&!h.deliverThreadBroadcastMessages&&!re){p("debug",z,"skip thread broadcast message by context policy",{seq:C,message_id:P.id}),Z(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:v,seq:C,message_id:P.id}),Nt(r,v,P.seq);return}let de;try{de=await b(v)}catch(N){x(z,"failed to resolve channel name \u2014 dropping message",N);return}if(!de){p("warn",z,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:v,messageSeq:C});return}let xe;if(P.parent_message_id){let N,ee=[],Le=!1;if(e.getMessageById)try{N=await e.getMessageById(r,P.parent_message_id)}catch(ye){Le=!0,p("warn",z,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:P.parent_message_id,err:ye instanceof Error?ye.message:String(ye)})}else Le=!0;if(j&&P.parent_message_id===M)ee=j.slice(0,h.threadReplyLimit);else if(e.getThreadReplies)try{ee=await e.getThreadReplies(r,P.parent_message_id,h.threadReplyLimit)}catch(ye){Le=!0,p("warn",z,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:P.parent_message_id,err:ye instanceof Error?ye.message:String(ye)})}else Le=!0;xe=Wm(P,N,ee,de),Le&&p("info",z,"thread context degraded (parent or replies missing)",{channelId:v,parent_message_id:P.parent_message_id})}else xe=qr(P,de);let _t=P.parent_message_id?[{name:"thread_context",bytes:xe.length,reply_limit:h.threadReplyLimit},{name:"incoming",bytes:P.content.length}]:[{name:"inbound_message",bytes:xe.length}];if(Z(r,"context_injection",{topic:y.topic,channel_id:v,channel_name:de,message_id:P.id,parent_message_id:P.parent_message_id??null,sender_kind:P.sender_kind,mode:P.parent_message_id?"thread":"main",explicitly_mentioned:re,policy:{deliver_broadcast_messages:h.deliverBroadcastMessages,deliver_system_messages:h.deliverSystemMessages,deliver_thread_broadcast_messages:h.deliverThreadBroadcastMessages,thread_reply_limit:h.threadReplyLimit},sections:_t,rendered_bytes:xe.length}),t.enqueueUserTurn(xe),g&&P.sender_kind!=="system")try{g.set(r,P.id)}catch(N){x(z,"contextTracker.set threw (non-fatal)",N)}if(f)try{f(v)}catch(N){x(z,"onInboundMessage callback threw (non-fatal)",N)}Nt(r,v,P.seq),p("info",z,"enqueued inbound message",{channelId:v,channelName:de,seq:P.seq,sender_id:P.sender_id}),Z(r,"inbound",{topic:y.topic,channel_id:v,channel_name:de,seq:P.seq,message_id:P.id,message_id_short:P.id.replace(/-/g,"").slice(0,8),parent_message_id:P.parent_message_id??null,sender_id:P.sender_id,sender_kind:P.sender_kind,sender_display_name:P.sender_display_name??null,content_preview:P.content.slice(0,120),rendered_bytes:xe.length})}let I=y=>H(y).catch(w=>{x(z,"unhandled error in handleEvent",w)});return{start(){W(),e.subscribe(o,I),p("info",z,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,I),p("info",z,"InboxCoordinator stopped",{workroomId:o})},onInjected(y){K=y}}}var z,kd=R(()=>{"use strict";yi();oe();gt();Ur();z="inboxDelivery"});var Sd,Hr,xd=R(()=>{"use strict";oe();Sd="typingNotifier",Hr=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=>{p("warn",Sd,"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=>{p("warn",Sd,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var ki,Gr,Ed=R(()=>{"use strict";oe();gt();ki="agentPresence",Gr=class{constructor(e){this.gateway=e}gateway;current=new Map;set(e,t,r){let s=this.current.get(e);if(s===t){p("debug",ki,"presence transition deduped",{agentId:e,state:t,channelId:r});return}this.current.set(e,t),p("info",ki,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),Z(e,"presence",{state:t,prev:s??null,channel_id:r??null}),this.gateway.notifyAgentStatus&&this.gateway.notifyAgentStatus(e,r,t).catch(i=>{p("warn",ki,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function Td(n){let{agentId:e,onFire:t,clock:r=()=>Date.now()}=n,s=new Map,i=new Map;function o(l){let u=s.get(l);u?.timer&&clearTimeout(u.timer),s.delete(l)}function a(){for(let l of s.values())l.timer&&clearTimeout(l.timer);s.clear()}function c(l){let u=s.get(l);if(!u)return;let f=u.reminder.version,g=i.get(l);g!==void 0&&g>=f||(i.set(l,f),Promise.resolve().then(()=>t(u.reminder)).catch(h=>{x(jm,`onFire callback failed for reminder ${l} (agent ${e})`,h)}))}function d(l){let u=s.get(l.id);if(u&&u.reminder.version>=l.version)return;u?.timer&&clearTimeout(u.timer);let f=Date.parse(l.fireAt),g=r(),h=Math.max(0,f-g);if(f<=g){s.set(l.id,{reminder:l,timer:null}),c(l.id);return}let m=setTimeout(()=>c(l.id),h);typeof m.unref=="function"&&m.unref(),s.set(l.id,{reminder:l,timer:m})}return{upsert:d,cancel(l,u){o(l)},snapshot(l){a();for(let u of l)d(u)},clear(){a()},stop(){a(),i.clear()}}}var jm,Cd=R(()=>{"use strict";oe();jm="reminderCache"});function Rd(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}),p("debug",Si,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),Z(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){p("debug",Si,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),p("debug",Si,"context get expired",{agentId:r,messageId:s.id}),Z(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var Si,Od=R(()=>{"use strict";oe();gt();Si="contextTracker"});import{readFileSync as Jm,writeFileSync as Ym,existsSync as Vm,mkdirSync as zm}from"fs";import{dirname as Km}from"path";function Pd(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function Id(){return{version:1,entities:{},relations:{},observations:[],obs_seq:0}}function xi(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 Ad,Wr,Nd=R(()=>{"use strict";Ad=500;Wr=class{constructor(e){this.path=e;if(Vm(e))try{let t=Jm(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=Id()}else this.file=Id(),zm(Km(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[Pd(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[Pd(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>Ad&&this.file.observations.splice(0,this.file.observations.length-Ad),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&&(Ym(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 We(n){return n.replace(/-/g,"").slice(0,8)}function on(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+We(e)}function Bn(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+We(e)}function Md(n){let{subscribe:e,unsubscribe:t,host:r,selfAgentId:s,workroomId:i,companion:o,quietSeconds:a,maxRepliesPerWindow:c,windowSeconds:d,contextPolicy:l=Dn,now:u=()=>Date.now()}=n,f=[],g=new Map,h=3e4,m=new Set;function _(y=u()){f.push(y);let w=y-d*1e3;for(;f.length>0&&f[0]<w;)f.shift()}function k(y){return f.length===0?Number.POSITIVE_INFINITY:y-f[f.length-1]}function E(y){let w=y-d*1e3;for(;f.length>0&&f[0]<w;)f.shift();return f.length}function b(y){return y?o.listChannelMembers(y).some(v=>v.id===s):!1}function S(y){let w=u();for(let[v,C]of g)w-C>h&&g.delete(v);return g.has(y)?!1:(g.set(y,w),!0)}function O(y){return`assigned:${y}:${s}`}function T(y,w){let v=u(),C=k(v);if(C<a*1e3)return p("debug",Ke,"wake skipped: quiet_seconds gate",{reason:y,taskId:w,sinceMs:C,quietSeconds:a}),!1;let $=E(v);return $>=c?(p("debug",Ke,"wake skipped: max_replies_per_window gate",{reason:y,taskId:w,count:$,max:c,windowSeconds:d}),!1):!0}function A(y,w,v){p("info",Ke,"poking agent with system event",{reason:w,taskId:v}),Z(s,"wake",{reason:w,task_id:v,task_id_short:We(v),bytes:y.length}),r.enqueueUserTurn(y)}function G(y){let w=y.task_id,v=y.channel_id,C=y.title,$=y.created_by,M=y.owner_id??y.assignee_id;if(!w||$===s||M===s)return;if(!(l.wakeOnChannelTaskCreated&&b(v))){p("debug",Ke,"task.created not relevant \u2014 skip",{taskId:w});return}if(!S(`created:${w}`)||!T("task-created",w))return;let J=on(o,$),P=Bn(o,v),j=`[system event: task #${We(w)} was just created in your channel ${P}]
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
454
|
+
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 fd(n){let e="",t=new Set;function r(i,o,...a){if(i)try{i(...a)}catch(c){n.onError?.(c instanceof Error?c:new Error(String(c)),o)}}function s(i){let o=i.replace(/\r$/,"");if(o.trim()==="")return;let a;try{a=JSON.parse(o)}catch(l){n.onError&&n.onError(l instanceof Error?l:new Error(String(l)),o);return}if(typeof a!="object"||a===null)return;let c=a,d=c.type;if(typeof d=="string"){if(d==="system"&&c.subtype==="init"){let l=c.session_id;typeof l=="string"&&l.length>0&&(t.has(l)||(t.add(l),r(n.onSessionId,"<onSessionId>",l)));return}if(d==="result"){let l=c.usage;if(n.onUsage&&l&&typeof l=="object"){let u=l,f={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>",f)}if(n.onResultError&&c.is_error===!0){let u=c.result,f=c.error,h=typeof u=="string"&&u.trim()?u:typeof f=="string"&&f.trim()?f:typeof c.subtype=="string"?String(c.subtype):"turn failed";r(n.onResultError,"<onResultError>",h)}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(`
|
|
455
|
+
`),a=o.slice(0,-1);e=o[o.length-1];for(let c of a)s(c)}catch{}}}}var hd=A(()=>{"use strict"});import{existsSync as cn}from"node:fs";import{execFileSync as qr}from"node:child_process";import{homedir as $m}from"node:os";function ln(){let n=process.env.MIO_CLAUDE_PATH;if(n&&cn(n))return n;for(let e of Dm)if(cn(e))return e;try{let e=qr("/usr/bin/which",["claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&cn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=qr(e,["-lc","command -v claude"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&cn(t))return t}catch{}try{let e=qr("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/claude`;if(cn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=qr("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/claude`;if(cn(s))return s}}catch{}return null}function gd(){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(`
|
|
456
|
+
`)}var xi,Dm,Gr=A(()=>{"use strict";xi=$m(),Dm=["/Applications/cmux.app/Contents/Resources/bin/claude",`${xi}/.local/bin/claude`,`${xi}/.claude/local/claude`,`${xi}/.npm-global/bin/claude`,"/opt/homebrew/bin/claude","/usr/local/bin/claude"]});import{spawn as Bm}from"child_process";function pd(n){let{workingDirectory:e,model:t="sonnet",systemPromptPath:r,mcpConfigPath:s,spawnEnv:i,firstTurnText:o,spawnFn:a=Bm,maxRestarts:c=5,presenceTracker:d,agentId:l}=n;function u(_){if(!(!d||!l))try{d.set(l,_)}catch(P){process.stderr.write(`[claudeStreamHost] presence(${_}) error: ${P.message}
|
|
457
|
+
`)}}function f(_,P){l&&ee(l,_,P)}let h=0,g=n.claudeCommand??ln()??"claude",m=null,y=n.sessionId,b=!1,x=[],v=!1,S=0,M,T,N,j,W;function H(_){let P=["--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--verbose","--permission-mode","bypassPermissions","--output-format","stream-json","--input-format","stream-json","--model",t,"--disallowed-tools",Fm,"--append-system-prompt-file",r,"--mcp-config",s,"--setting-sources","user,project,local","--chrome"];return _&&P.push("--resume",_),P}function Y(_,P){let R={type:"user",message:{role:"user",content:[{type:"text",text:_}]}};return P!==void 0&&(R.session_id=P),JSON.stringify(R)+`
|
|
458
|
+
`}function K(_,P){if(!m||!m.stdin)return;let R=Y(_,P);p("debug","claudeStreamHost","injected user turn",{bytes:R.length}),f("inject",{bytes:R.length,content_bytes:_.length,resume:P!==void 0}),u("thinking");try{m.stdin.write(R)}catch(C){process.stderr.write(`[claudeStreamHost] stdin write error (will restart): ${C.message}
|
|
459
|
+
`);return}W?.(_)}function q(){S=0,f("boundary",{pending_queue_len:x.length});try{M?.()}catch(_){process.stderr.write(`[claudeStreamHost] onBoundary callback error: ${_.message}
|
|
460
|
+
`)}if(x.length>0){let _=x.length,P=x.splice(0,x.length).join(`
|
|
461
|
+
`);f("coalesce_flush",{coalesced_count:_,bytes:P.length}),K(P,y)}else b=!1,u("idle")}function ne(_){let P=H(_);p("info","claudeStreamHost","spawning claude",{command:g,argsCount:P.length,cwd:e,resume:!!_}),h=Date.now(),f("spawn",{command:g,args_count:P.length,resume:!!_,resume_session_id:_??null,restart_count:S}),u("starting"),m&&(m.stdout?.removeAllListeners(),m.stderr?.removeAllListeners());let R=a(g,P,{cwd:e,env:i,stdio:["pipe","pipe","pipe"]});m=R,R.stdin?.on("error",E=>{R===m&&process.stderr.write(`[claudeStreamHost] stdin error (will restart): ${E.message}
|
|
462
|
+
`)});let C=fd({onSessionId:E=>{if(R!==m)return;y=E;let L=h?Date.now()-h:null;p("info","claudeStreamHost","session id captured",{sessionId:E,duration_ms:L}),f("session_ready",{session_id:E,spawn_duration_ms:L}),u("idle");try{N?.(E)}catch(X){process.stderr.write(`[claudeStreamHost] onSessionId callback error: ${X.message}
|
|
463
|
+
`)}},onResultError:E=>{if(R===m){p("warn","claudeStreamHost","turn ended with error",{message:E.slice(0,120)});try{T?.(E)}catch(L){process.stderr.write(`[claudeStreamHost] onTurnError callback error: ${L.message}
|
|
464
|
+
`)}}},onUsage:E=>{R===m&&f("usage",{runtime:"claude",model:t,input_tokens:E.inputTokens??null,output_tokens:E.outputTokens??null,cache_read_tokens:E.cacheReadTokens??null,cache_creation_tokens:E.cacheCreationTokens??null,duration_ms:E.durationMs??null,total_cost_usd:E.totalCostUsd??null})},onBoundary:()=>{R===m&&(p("debug","claudeStreamHost","turn boundary",{}),q())},onError:(E,L)=>{process.stderr.write(`[claudeStreamHost] parser error on "${L}": ${E.message}
|
|
465
|
+
`)}});R.stdout?.on("data",E=>{R===m&&C.feed(typeof E=="string"?E:E.toString("utf8"))});let O="";R.stderr?.on("data",E=>{if(R!==m)return;O+=typeof E=="string"?E:E.toString("utf8");let L;for(;(L=O.indexOf(`
|
|
466
|
+
`))!==-1;){let X=O.slice(0,L).trimEnd();O=O.slice(L+1),X.length>0&&p("warn","claudeStreamHost","claude stderr",{line:X})}}),R.on("exit",E=>{R===m&&w(E)}),R.on("error",E=>{process.stderr.write(`[claudeStreamHost] spawn error: ${E.message}
|
|
467
|
+
`)})}function w(_){if(!v){if(S++,S>c){k("claudeStreamHost","giving up after max restarts",{restartCount:S}),process.stderr.write(`[claudeStreamHost] gave up after ${c} restarts (code=${_})
|
|
468
|
+
`);try{j?.(_)}catch(P){process.stderr.write(`[claudeStreamHost] onExit callback error: ${P.message}
|
|
469
|
+
`)}return}if(p("warn","claudeStreamHost","claude exited",{code:_,willRestart:!0,restartCount:S}),f("exit",{code:_,will_restart:!0,restart_count:S}),process.stderr.write(`[claudeStreamHost] unexpected exit (code=${_}), restarting (attempt ${S}/${c})...
|
|
470
|
+
`),b=!1,ne(y),x.length>0){let P=x.splice(0,x.length).join(`
|
|
471
|
+
`);b=!0,K(P,y)}}}return{start(){ne(y),b=!0,K(o,y)},enqueueUserTurn(_){b?x.push(_):(b=!0,K(_,y))},stop(){if(v=!0,m){try{m.stdin?.end()}catch{}let _=setTimeout(()=>{try{m?.kill()}catch{}},2e3);_.unref&&_.unref()}},onTurnError(_){T=_},onBoundary(_){M=_},onSessionId(_){N=_},onExit(_){j=_},onInjected(_){W=_}}}var Fm,md=A(()=>{"use strict";hd();ce();wt();Gr();Fm=["EnterPlanMode","ExitPlanMode","ScheduleWakeup","CronCreate","CronList","CronDelete"].join(",")});import{existsSync as dn}from"node:fs";import{execFileSync as Wr}from"node:child_process";import{homedir as Um}from"node:os";function jr(){let n=process.env.MIO_CODEX_PATH;if(n&&dn(n))return n;for(let e of Hm)if(dn(e))return e;try{let e=Wr("/usr/bin/which",["codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e&&dn(e))return e}catch{}for(let e of["/bin/zsh","/bin/bash"])try{let t=Wr(e,["-lc","command -v codex"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(t&&dn(t))return t}catch{}try{let e=Wr("/usr/bin/env",["npm","config","get","prefix"],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(e){let t=`${e}/bin/codex`;if(dn(t))return t}}catch{}for(let[e,t]of[["pnpm",["bin","-g"]],["yarn",["global","bin"]],["bun",["pm","bin","-g"]]])try{let r=Wr("/usr/bin/env",[e,...t],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim();if(r){let s=`${r}/codex`;if(dn(s))return s}}catch{}return null}function _d(){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(`
|
|
472
|
+
`)}var yd,Hm,Ti=A(()=>{"use strict";yd=Um(),Hm=["/opt/homebrew/bin/codex","/usr/local/bin/codex",`${yd}/.npm-global/bin/codex`,`${yd}/.codex/bin/codex`]});import{spawn as qm}from"node:child_process";function wd(n){let e=n.spawnFn??Wm,t=n.log??(()=>{}),r=n.requestTimeoutMs??6e4,s=e(n.command,n.args,{cwd:n.cwd,env:n.env}),i=!0,o=1,a="",c=new Map;function d(h){if(!(!i||!s.stdin))try{s.stdin.write(JSON.stringify(h)+`
|
|
473
|
+
`)}catch(g){t("warn","appServerClient stdin write failed",{err:g.message})}}function l(h){for(let[,g]of c)clearTimeout(g.timer),g.reject(new Error(h));c.clear()}function u(h){let g=h.id!==void 0&&h.id!==null,m=typeof h.method=="string";if(g&&!m){let y=h.id,b=c.get(y);if(!b){t("debug","appServerClient response for unknown id",{id:y});return}c.delete(y),clearTimeout(b.timer),h.error!==void 0?b.reject(new Error(`app-server error: ${JSON.stringify(h.error)}`)):b.resolve(h.result);return}if(m&&g){let y=h.id,b=h.method;Promise.resolve().then(()=>n.onServerRequest?n.onServerRequest(b,h.params):void 0).then(x=>d({id:y,result:x??{}})).catch(x=>{t("warn","onServerRequest handler threw",{method:b,err:x.message}),d({id:y,error:{code:-32e3,message:String(x.message)}})});return}if(m){try{n.onNotification(h.method,h.params)}catch(y){t("warn","onNotification handler threw",{method:h.method,err:y.message})}return}t("debug","appServerClient unrecognized message",{keys:Object.keys(h)})}function f(h){if(a+=typeof h=="string"?h:h.toString("utf8"),a.length>Gm){t("warn","appServerClient buffer overflow \u2014 clearing",{bytes:a.length}),a="";return}let g;for(;(g=a.indexOf(`
|
|
474
|
+
`))>=0;){let m=a.slice(0,g).replace(/\r$/,"");if(a=a.slice(g+1),!m.trim())continue;let y;try{y=JSON.parse(m)}catch{t("debug","appServerClient non-JSON line",{preview:m.slice(0,120)});continue}y&&typeof y=="object"&&u(y)}}return s.stdout?.on("data",f),s.stderr?.on("data",h=>{let g=typeof h=="string"?h:h.toString("utf8");n.onStderr&&n.onStderr(g)}),s.on("error",h=>{t("warn","appServerClient spawn error",{err:h.message}),i=!1,l(`app-server spawn error: ${h.message}`),n.onExit?.(null)}),s.on("exit",h=>{t("info","appServerClient exited",{code:h}),i=!1,l(`app-server exited (code=${h})`),n.onExit?.(h)}),{request(h,g){if(!i)return Promise.reject(new Error("app-server not alive"));let m=o++;return new Promise((y,b)=>{let x=setTimeout(()=>{c.delete(m),b(new Error(`app-server request '${h}' timed out after ${r}ms`))},r);x.unref?.(),c.set(m,{resolve:y,reject:b,timer:x}),d({method:h,id:m,params:g})})},notify(h,g){d({method:h,params:g})},isAlive(){return i},close(){if(i){i=!1,l("app-server client closed");try{s.stdin?.end()}catch{}try{s.kill("SIGTERM")}catch{}}}}}var Gm,Wm,vd=A(()=>{"use strict";Gm=4*1048576,Wm=(n,e,t)=>qm(n,e,{cwd:t.cwd,env:t.env,stdio:["pipe","pipe","pipe"]})});import{readFileSync as jm}from"node:fs";function Jm(n){let e=n?.trim();return e==="read-only"||e==="workspace-write"||e==="danger-full-access"?e:"danger-full-access"}function Ym(n){let e=n?.trim();if(e&&e!=="gpt-5-codex")return e}function bd(n){let e=n.codexCommand??jr()??"codex",t=(process.env.MIO_CODEX_MODEL_REASONING||n.reasoningEffort||"medium").trim(),r=Ym((process.env.MIO_CODEX_MODEL||n.spawnEnv.MIO_CODEX_MODEL||"").trim()||n.model),s=Jm(process.env.MIO_CODEX_SANDBOX||n.spawnEnv.MIO_CODEX_SANDBOX),i=n.maxRestarts??5,o=n.agentId,a=null,c=n.sessionId,d=!1,l=!1,u=!1,f=0,h=[],g,m="",y,b,x,v,S;function M(w,_){o&&ee(o,w,{runtime:"codex-app-server",..._})}function T(w){if(!(!n.presenceTracker||!o))try{n.presenceTracker.set(o,w)}catch(_){process.stderr.write(`[${we}] presence(${w}) error: ${_.message}
|
|
475
|
+
`)}}function N(){try{return jm(n.systemPromptPath,"utf8")}catch(w){return k(we,`failed to read system prompt at ${n.systemPromptPath}`,w),""}}function j(w,_){return p("debug",we,"auto-approving server request",{method:w}),{decision:"approved"}}function W(w){let _=w.content;return Array.isArray(_)?_.map(P=>P&&typeof P=="object"&&typeof P.text=="string"?P.text:"").join(""):typeof w.text=="string"?w.text:""}function H(w,_){let P=_??{};switch(w){case"thread/started":{let C=P.thread?.id;if(C&&C!==c){c=C;try{b?.(C)}catch(O){k(we,"onSessionId cb error",O)}M("spawn",{thread_id:C})}break}case"turn/started":d=!0,T("thinking");break;case"item/agentMessage/delta":{let R=P.delta??P.text;typeof R=="string"&&(m+=R);break}case"item/started":M("runtime_command",{phase:"started"});break;case"item/completed":{let R=P.item;if(!R)break;let C=R.type;if(C==="agentMessage"||C==="assistantMessage"){let O=W(R).trim();O&&M("runtime_message",{chars:O.length,preview:O.slice(0,240)})}else(C==="commandExecution"||C==="localShellCall")&&M("runtime_command",{phase:"completed"});break}case"thread/tokenUsage/updated":{let R=P.tokenUsage?.last;if(R){let C=Number(R.inputTokens??0),O=Number(R.cachedInputTokens??0);M("usage",{input_tokens:C,output_tokens:Number(R.outputTokens??0),cache_read_tokens:O,total_tokens:Number(R.totalTokens??0)})}break}case"turn/completed":{let R=P.turn,C=R?.status;if(C&&C!=="completed"){p("warn",we,"turn ended non-completed",{status:C,error:R?.error});let O=R?.error,E=typeof O=="string"?O:O&&typeof O.message=="string"?O.message:`codex turn ${C}`;try{S?.(E)}catch(L){k(we,"onTurnError cb error",L)}}m="",d=!1,T("idle");try{y?.()}catch(O){k(we,"onBoundary cb error",O)}K();break}default:break}}function Y(w){if(!a||!a.isAlive()||!c){h.push(w);return}d=!0,T("thinking"),m="",M("inbound",{chars:w.length});try{v?.(w)}catch(_){k(we,"onInjected cb error",_)}a.request("turn/start",{threadId:c,input:[{type:"text",text:w,text_elements:[]}]}).catch(_=>{p("warn",we,"turn/start failed",{err:_.message}),d=!1,T("idle");try{y?.()}catch{}K()})}function K(){if(d||h.length===0)return;let w=h.splice(0).join(`
|
|
476
|
+
|
|
477
|
+
`);Y(w)}async function q(w){let _={...n.spawnEnv},P=["app-server","-c",`model_reasoning_effort="${t}"`,...s==="workspace-write"?["-c","sandbox_workspace_write.network_access=true"]:[]];a=wd({command:e,args:P,cwd:n.workingDirectory,env:_,onNotification:H,onServerRequest:j,onStderr:R=>{R.trim()&&p("debug",we,"app-server stderr",{snippet:R.slice(0,200)})},onExit:ne,log:(R,C,O)=>p(R,we,C,O),...n.appServerSpawnFn?{spawnFn:n.appServerSpawnFn}:{}});try{if(await a.request("initialize",{clientInfo:{name:"mio-agent",title:null,version:"1"},capabilities:null}),c&&w)await a.request("thread/resume",{threadId:c}),p("info",we,"resumed thread",{threadId:c});else{let R=N()||void 0,O=(await a.request("thread/start",{cwd:n.workingDirectory,sandbox:s,sandbox_mode:s,approvalPolicy:"never",...r?{model:r}:{},...R?{baseInstructions:R}:{}}))?.thread?.id;if(O){c=O;try{b?.(O)}catch(E){k(we,"onSessionId cb error",E)}}}}catch(R){k(we,"handshake failed",R);return}if(!w&&g!==void 0){let R=g;g=void 0,Y(R)}else d=!1,K()}function ne(w){if(l){try{x?.(w)}catch{}return}if(f>=i){p("warn",we,"max restarts reached \u2014 giving up",{restartCount:f});try{x?.(w)}catch{}return}f++,d=!1,p("info",we,"app-server exited \u2014 respawning",{code:w,restartCount:f,threadId:c}),M("boundary",{reason:"respawn",code:w}),q(!0)}return{start(){u||(u=!0,T("starting"),g=n.firstTurnText,q(!1))},enqueueUserTurn(w){if(d||!a||!a.isAlive()||!c){h.push(w);return}Y(w)},stop(){l=!0;try{a?.close()}catch{}},onBoundary(w){y=w},onSessionId(w){b=w},onExit(w){x=w},onInjected(w){v=w},onTurnError(w){S=w}}}var we,kd=A(()=>{"use strict";ce();wt();Ti();vd();we="codexAppServerHost"});function Sd(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:void 0}function Hn(n){return typeof n=="boolean"?n:void 0}function ey(n){if(typeof n!="number"||!Number.isFinite(n))return;let e=Math.floor(n);return e>0?e:void 0}function ty(n){return Math.max(1,Math.min(6,Math.floor(n)))}function xd(n){let e=n.role??"",t=`${n.displayName??""} ${n.description??""} ${e}`,r={...qn};Qm(t)&&!Zm(t)&&(r.deliverBroadcastMessages=!1,r.deliverThreadBroadcastMessages=!1,r.wakeOnChannelTaskCreated=!1,r.wakeOnChannelTaskStatus=!1,r.threadReplyLimit=3);let s=Sd(n.capabilities),i=Sd(s?.context_policy);return i&&(r.deliverBroadcastMessages=Hn(i.deliver_broadcast_messages)??r.deliverBroadcastMessages,r.deliverSystemMessages=Hn(i.deliver_system_messages)??r.deliverSystemMessages,r.deliverThreadBroadcastMessages=Hn(i.deliver_thread_broadcast_messages)??r.deliverThreadBroadcastMessages,r.wakeOnChannelTaskCreated=Hn(i.wake_on_channel_task_created)??r.wakeOnChannelTaskCreated,r.wakeOnChannelTaskStatus=Hn(i.wake_on_channel_task_status)??r.wakeOnChannelTaskStatus,r.threadReplyLimit=ty(ey(i.thread_reply_limit)??r.threadReplyLimit)),r}function Td(n,e,t){let r=[e,t].map(s=>typeof s=="string"?s.trim():"").filter(s=>s.length>0);return r.length===0?!1:r.some(s=>n.includes(s))}var qn,Vm,zm,Km,Xm,Ed,Qm,Zm,Jr=A(()=>{"use strict";qn={deliverBroadcastMessages:!0,deliverSystemMessages:!1,deliverThreadBroadcastMessages:!0,wakeOnChannelTaskCreated:!0,wakeOnChannelTaskStatus:!1,threadReplyLimit:6},Vm=/\b(engineer|backend|frontend|ui|designer|design|executor|implement|coder|tester|qa|reviewer|operator|ops)\b/i,zm=/\b(pm|product|planner|coordinator|researcher|research|market|analyst|analysis)\b/i,Km=["\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"],Xm=["\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"],Ed=(n,e)=>e.some(t=>n.includes(t)),Qm=n=>Vm.test(n)||Ed(n,Km),Zm=n=>zm.test(n)||Ed(n,Xm)});import{writeFileSync as ny,mkdirSync as ry}from"node:fs";import{join as Cd}from"node:path";function Yr(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 sy(n,e,t,r){let s=n.parent_message_id??"",i=s.replace(/-/g,"").slice(0,8),o=e?.attached_task??null,a=[];o&&a.push(`task #${o.task_number} "${o.title}" status=${o.status}`),a.push(`channel=#${r}`),i&&a.push(`parent=${i}`);let d=[`[thread context, ${a.join(", ")}]`];e?d.push(`parent: ${Yr(e,r)}`):n.parent_message_id&&d.push(`parent: (unavailable \u2014 parent message id ${i||s})`);let l=t.filter(u=>u.id!==n.id);if(l.length>0){d.push("recent replies:");for(let u of l)d.push(` ${Yr(u,r)}`)}return d.push("incoming:"),d.push(Yr(n,r)),s&&d.push(`(reply with: mio message reply --parent ${s} --target "#${r}")`),d.join(`
|
|
478
|
+
`)}function Rd(n){let{gateway:e,host:t,selfAgentId:r,selfHandle:s,selfDisplayName:i,workroomId:o,fetchMessage:a,resolveChannelName:c,resolveAgentChannels:d,onInjected:l,reminderCache:u,onInboundMessage:f,contextTracker:h,contextPolicy:g=qn,mioDir:m,downloadAttachment:y}=n,b=/^image\//;async function x(C){let O=C.attachment_ids??[];if(O.length===0||!m||!y)return"";let E=Cd(m,"inbound"),L=[];for(let X of O.slice(0,10))try{let F=await y(X);if(!b.test(F.mime_type))continue;try{ry(E,{recursive:!0})}catch{}let le=(F.filename||`${X}.png`).replace(/[^\w.\-]/g,"_").slice(-60),ie=Cd(E,`${C.id.slice(0,8)}-${le}`);ny(ie,Buffer.from(F.data_base64,"base64")),L.push(ie)}catch(F){k(V,"inbound attachment download failed (skipping)",F)}return L.length===0?"":`
|
|
479
|
+
|
|
480
|
+
[\u9644\u4EF6] \u7528\u6237\u5728\u8FD9\u6761\u6D88\u606F\u91CC\u53D1\u4E86 ${L.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
|
|
481
|
+
`+L.map(X=>` - ${X}`).join(`
|
|
482
|
+
`)}let v=a??e.getChannelMessages.bind(e),S=new Map;async function M(C){let O=await e.getWorkroomChannels(o);for(let E of O)E.id&&E.name&&S.set(E.id,E.name);return S.get(C)}let T=c??M;async function N(C){let O=S.get(C);if(O!==void 0)return O;let E=await T(C);return E!==void 0&&S.set(C,E),E}let j=d??(async()=>new Set((await e.getAgentChannels(r)).map(C=>C.id))),W=null,H=new Set,Y=250,K=5e3,q=Y,ne=C=>new Promise(O=>{let E=setTimeout(O,C);typeof E.unref=="function"&&E.unref()});function w(){let C=j().then(O=>(q=Y,O)).catch(O=>{k(V,"failed to resolve agent channel membership \u2014 failing safe (deliver nothing), will retry",O);let E=q;return q=Math.min(q*2,K),W===C&&(W=ne(E).then(()=>(w(),W??new Set))),new Set});W=C}let _;t.onInjected(C=>{_?.(C)}),l&&(_=l);async function P(C){if(C.topic==="reminder.upserted"||C.topic==="reminder.canceled"){if(u){let J=C.payload;if(C.topic==="reminder.upserted")if(J.reminder){if(J.reminder.agentId!==r)return;u.upsert(J.reminder)}else p("warn",V,"reminder.upserted event missing reminder payload",{payload:C.payload});else if(J.reminderId){if(J.agentId!==r)return;u.cancel(J.reminderId,J.version)}else p("warn",V,"reminder.canceled event missing reminderId",{payload:C.payload})}return}if(C.topic==="channel.member_added"||C.topic==="channel.member_removed"||C.topic==="roster.member_added"||C.topic==="roster.member_removed"){let J=C.payload;J.member_id===r&&(p("info",V,"membership changed for self \u2014 invalidating membership cache",{topic:C.topic,channelId:J.channel_id}),H.clear(),w());return}if(C.topic!=="message.created"&&C.topic!=="thread.reply")return;let O=C.payload,E=O.channel_id,L=O.seq,X=O.message_id,F=O.parent_message_id;if(!E||!L){p("warn",V,"message.created event missing channel_id or seq",{payload:O});return}ee(r,"event_received",{topic:C.topic,channel_id:E,seq:L,message_id:X??null,parent_message_id:F??null});let ie=(await(W??Promise.resolve(new Set))).has(E);if(!ie&&!H.has(E)){p("info",V,"re-verifying membership for unknown channel before skip",{channelId:E,seq:L});try{let J=await j();W=Promise.resolve(J),q=Y,ie=J.has(E),ie?p("info",V,"self-healed stale membership \u2014 channel IS a member, delivering",{channelId:E,seq:L}):H.add(E)}catch(J){k(V,"self-heal membership re-resolve failed \u2014 skipping this message (will retry next)",J)}}if(!ie){p("debug",V,"skip not-a-member channel",{channelId:E,seq:L,topic:C.topic}),ee(r,"skip",{reason:"not_a_member",channel_id:E,seq:L,topic:C.topic});return}if(O.sender_id&&O.sender_id===r){p("debug",V,"skip self-authored message (pre-fetch)",{seq:L,sender_id:O.sender_id}),ee(r,"skip",{reason:"self_authored_prefetch",channel_id:E,seq:L,message_id:X??null});return}let I,Pe;if(C.topic==="thread.reply"){if(!F){p("warn",V,"thread.reply event missing parent_message_id",{payload:O});return}if(!e.getThreadReplies){p("warn",V,"thread.reply received but gateway has no getThreadReplies \u2014 dropping",{channelId:E,messageSeq:L});return}try{let J=await e.getThreadReplies(r,F,50);Pe=J,I=X&&J.find(de=>de.id===X)||J.find(de=>de.seq===L),I&&!I.parent_message_id&&(I={...I,parent_message_id:F})}catch(J){k(V,"failed to fetch thread replies after thread.reply event",J);return}}else{let J=(BigInt(L)-1n).toString();try{I=(await v(o,E,J,1)).messages.find(Ne=>Ne.seq===L)}catch(de){k(V,"failed to fetch message after message.created event",de);return}}if(!I){p("warn",V,"message not found in GET response",{channelId:E,messageSeq:L,topic:C.topic});return}if(I.sender_id===r){p("debug",V,"skip self-authored message",{seq:L,sender_id:I.sender_id}),ee(r,"skip",{reason:"self_authored",channel_id:E,seq:L,message_id:I.id});return}let Ie=Td(I.content,s,i),Bt=!!I.parent_message_id;if(I.sender_kind==="system"&&!g.deliverSystemMessages){p("debug",V,"skip system message by context policy",{seq:L,message_id:I.id}),ee(r,"skip",{reason:"context_policy_system_message",channel_id:E,seq:L,message_id:I.id}),vt(r,E,I.seq);return}let St=O.wake_agent_ids;if(!Bt&&I.sender_kind!=="system"){if(Array.isArray(St)){if(!(St.includes(r)||Ie)){p("debug",V,"skip: not in server wake set",{seq:L,message_id:I.id}),ee(r,"skip",{reason:"not_in_wake_set",channel_id:E,seq:L,message_id:I.id}),vt(r,E,I.seq);return}}else if(!g.deliverBroadcastMessages&&!Ie){p("debug",V,"skip broadcast message by context policy",{seq:L,message_id:I.id}),ee(r,"skip",{reason:"context_policy_broadcast_message",channel_id:E,seq:L,message_id:I.id}),vt(r,E,I.seq);return}}if(Bt&&I.sender_kind!=="system"&&!g.deliverThreadBroadcastMessages&&!Ie){p("debug",V,"skip thread broadcast message by context policy",{seq:L,message_id:I.id}),ee(r,"skip",{reason:"context_policy_thread_broadcast_message",channel_id:E,seq:L,message_id:I.id}),vt(r,E,I.seq);return}let Ye;try{Ye=await N(E)}catch(J){k(V,"failed to resolve channel name \u2014 dropping message",J);return}if(!Ye){p("warn",V,"channel name unresolvable \u2014 dropping message (unreplyable target)",{channelId:E,messageSeq:L});return}let D;if(I.parent_message_id){let J,de=[],Ne=!1;if(e.getMessageById)try{J=await e.getMessageById(r,I.parent_message_id)}catch(et){Ne=!0,p("warn",V,"thread parent fetch failed \u2014 degrading thread context",{parent_message_id:I.parent_message_id,err:et instanceof Error?et.message:String(et)})}else Ne=!0;if(Pe&&I.parent_message_id===F)de=Pe.slice(0,g.threadReplyLimit);else if(e.getThreadReplies)try{de=await e.getThreadReplies(r,I.parent_message_id,g.threadReplyLimit)}catch(et){Ne=!0,p("warn",V,"thread replies fetch failed \u2014 degrading thread context",{parent_message_id:I.parent_message_id,err:et instanceof Error?et.message:String(et)})}else Ne=!0;D=sy(I,J,de,Ye),Ne&&p("info",V,"thread context degraded (parent or replies missing)",{channelId:E,parent_message_id:I.parent_message_id})}else D=Yr(I,Ye);let oe=I.parent_message_id?[{name:"thread_context",bytes:D.length,reply_limit:g.threadReplyLimit},{name:"incoming",bytes:I.content.length}]:[{name:"inbound_message",bytes:D.length}];if(ee(r,"context_injection",{topic:C.topic,channel_id:E,channel_name:Ye,message_id:I.id,parent_message_id:I.parent_message_id??null,sender_kind:I.sender_kind,mode:I.parent_message_id?"thread":"main",explicitly_mentioned:Ie,policy:{deliver_broadcast_messages:g.deliverBroadcastMessages,deliver_system_messages:g.deliverSystemMessages,deliver_thread_broadcast_messages:g.deliverThreadBroadcastMessages,thread_reply_limit:g.threadReplyLimit},sections:oe,rendered_bytes:D.length}),!I.parent_message_id&&I.sender_kind!=="system"&&Array.isArray(O.wake_agent_ids)&&O.wake_agent_ids.includes(r)&&!Ie&&(D+=`
|
|
483
|
+
|
|
484
|
+
[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.`),D+=await x(I),t.enqueueUserTurn(D),h&&I.sender_kind!=="system")try{h.set(r,I.id)}catch(J){k(V,"contextTracker.set threw (non-fatal)",J)}if(f)try{f(E)}catch(J){k(V,"onInboundMessage callback threw (non-fatal)",J)}vt(r,E,I.seq),p("info",V,"enqueued inbound message",{channelId:E,channelName:Ye,seq:I.seq,sender_id:I.sender_id}),ee(r,"inbound",{topic:C.topic,channel_id:E,channel_name:Ye,seq:I.seq,message_id:I.id,message_id_short:I.id.replace(/-/g,"").slice(0,8),parent_message_id:I.parent_message_id??null,sender_id:I.sender_id,sender_kind:I.sender_kind,sender_display_name:I.sender_display_name??null,content_preview:I.content.slice(0,120),rendered_bytes:D.length})}let R=C=>P(C).catch(O=>{k(V,"unhandled error in handleEvent",O)});return{start(){w(),e.subscribe(o,R),p("info",V,"InboxCoordinator started",{workroomId:o})},stop(){e.unsubscribe(o,R),p("info",V,"InboxCoordinator stopped",{workroomId:o})},onInjected(C){_=C}}}var V,Od=A(()=>{"use strict";ki();ce();wt();Jr();V="inboxDelivery"});var Ad,Vr,Pd=A(()=>{"use strict";ce();Ad="typingNotifier",Vr=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=>{p("warn",Ad,"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=>{p("warn",Ad,"notifyTyping(stopped) failed (non-fatal)",{agentId:e,channelId:t,error:r.message})}))}}});var Ci,zr,Id=A(()=>{"use strict";ce();wt();Ci="agentPresence",zr=class{constructor(e){this.gateway=e}gateway;current=new Map;set(e,t,r){let s=this.current.get(e);if(s===t){p("debug",Ci,"presence transition deduped",{agentId:e,state:t,channelId:r});return}this.current.set(e,t),p("info",Ci,"presence transition",{agentId:e,prev:s??null,state:t,channelId:r??null}),ee(e,"presence",{state:t,prev:s??null,channel_id:r??null}),this.gateway.notifyAgentStatus&&this.gateway.notifyAgentStatus(e,r,t).catch(i=>{p("warn",Ci,"notifyAgentStatus failed (non-fatal)",{agentId:e,channelId:r,state:t,error:i.message})})}get(e){return this.current.get(e)}}});function Nd(n){let{agentId:e,onFire:t,clock:r=()=>Date.now()}=n,s=new Map,i=new Map;function o(l){let u=s.get(l);u?.timer&&clearTimeout(u.timer),s.delete(l)}function a(){for(let l of s.values())l.timer&&clearTimeout(l.timer);s.clear()}function c(l){let u=s.get(l);if(!u)return;let f=u.reminder.version,h=i.get(l);h!==void 0&&h>=f||(i.set(l,f),Promise.resolve().then(()=>t(u.reminder)).catch(g=>{k(iy,`onFire callback failed for reminder ${l} (agent ${e})`,g)}))}function d(l){let u=s.get(l.id);if(u&&u.reminder.version>=l.version)return;u?.timer&&clearTimeout(u.timer);let f=Date.parse(l.fireAt),h=r(),g=Math.max(0,f-h);if(f<=h){s.set(l.id,{reminder:l,timer:null}),c(l.id);return}let m=setTimeout(()=>c(l.id),g);typeof m.unref=="function"&&m.unref(),s.set(l.id,{reminder:l,timer:m})}return{upsert:d,cancel(l,u){o(l)},snapshot(l){a();for(let u of l)d(u)},clear(){a()},stop(){a(),i.clear()}}}var iy,Md=A(()=>{"use strict";ce();iy="reminderCache"});function Ld(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}),p("debug",Ri,"context set",{agentId:r,messageId:s,prev_id:i?.id??null,ttl_ms:e}),ee(r,"context",{action:"set",message_id:s,message_id_short:s.replace(/-/g,"").slice(0,8),prev_message_id:i?.id??null,ttl_ms:e})},get(r){let s=t.get(r);if(!s){p("debug",Ri,"context get miss",{agentId:r});return}if(s.expiresAt<Date.now()){t.delete(r),p("debug",Ri,"context get expired",{agentId:r,messageId:s.id}),ee(r,"context",{action:"expire",message_id:s.id,message_id_short:s.id.replace(/-/g,"").slice(0,8)});return}return s.id}}}var Ri,$d=A(()=>{"use strict";ce();wt();Ri="contextTracker"});import{readFileSync as oy,writeFileSync as ay,existsSync as cy,mkdirSync as ly}from"fs";import{dirname as dy}from"path";function Bd(n){return`${n.from_id}\0${n.to_id}\0${n.kind}`}function Fd(){return{version:1,entities:{},relations:{},observations:[],obs_seq:0}}function Oi(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 Dd,Kr,Ud=A(()=>{"use strict";Dd=500;Kr=class{constructor(e){this.path=e;if(cy(e))try{let t=oy(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=Fd()}else this.file=Fd(),ly(dy(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[Bd(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[Bd(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>Dd&&this.file.observations.splice(0,this.file.observations.length-Dd),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&&(ay(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 Je(n){return n.replace(/-/g,"").slice(0,8)}function un(n,e){if(!e)return"@someone";let t=n.getEntity(e);return t?.display_name?"@"+t.display_name:"@"+Je(e)}function Gn(n,e){if(!e)return"#unknown";let t=n.getEntity(e);return t?.display_name?"#"+t.display_name:"#"+Je(e)}function Hd(n){let{subscribe:e,unsubscribe:t,host:r,selfAgentId:s,workroomId:i,companion:o,quietSeconds:a,maxRepliesPerWindow:c,windowSeconds:d,contextPolicy:l=qn,now:u=()=>Date.now()}=n,f=[],h=new Map,g=3e4,m=new Set;function y(w=u()){f.push(w);let _=w-d*1e3;for(;f.length>0&&f[0]<_;)f.shift()}function b(w){return f.length===0?Number.POSITIVE_INFINITY:w-f[f.length-1]}function x(w){let _=w-d*1e3;for(;f.length>0&&f[0]<_;)f.shift();return f.length}function v(w){return w?o.listChannelMembers(w).some(P=>P.id===s):!1}function S(w){let _=u();for(let[P,R]of h)_-R>g&&h.delete(P);return h.has(w)?!1:(h.set(w,_),!0)}function M(w){return`assigned:${w}:${s}`}function T(w,_){let P=u(),R=b(P);if(R<a*1e3)return p("debug",Ze,"wake skipped: quiet_seconds gate",{reason:w,taskId:_,sinceMs:R,quietSeconds:a}),!1;let C=x(P);return C>=c?(p("debug",Ze,"wake skipped: max_replies_per_window gate",{reason:w,taskId:_,count:C,max:c,windowSeconds:d}),!1):!0}function N(w,_,P){p("info",Ze,"poking agent with system event",{reason:_,taskId:P}),ee(s,"wake",{reason:_,task_id:P,task_id_short:Je(P),bytes:w.length}),r.enqueueUserTurn(w)}function j(w){let _=w.task_id,P=w.channel_id,R=w.title,C=w.created_by,O=w.owner_id??w.assignee_id;if(!_||C===s||O===s)return;if(!(l.wakeOnChannelTaskCreated&&v(P))){p("debug",Ze,"task.created not relevant \u2014 skip",{taskId:_});return}if(!S(`created:${_}`)||!T("task-created",_))return;let L=un(o,C),X=Gn(o,P),F=`[system event: task #${Je(_)} was just created in your channel ${X}]
|
|
485
|
+
Title: ${R?`"${R}"`:"(no title)"}
|
|
486
|
+
Created by ${L}.${O?` Assigned to ${un(o,O)}.`:" No assignee yet."}
|
|
487
|
+
You may want to volunteer for it, acknowledge, or skip.`;N(F,"task-created",_)}function W(w){let{taskId:_,channelId:P,parentMessageId:R,assignerId:C,reason:O,dedupeAlreadyReserved:E}=w;if(!E){if(m.has(M(_)))return p("debug",Ze,"assigned wake suppressed: boot-scoped self-heal reservation",{taskId:_,reason:O}),!1;if(!S(M(_)))return!1}if(!T(O,_))return!1;let L=Gn(o,P),X=C?` by ${un(o,C)}`:"",F=R?`
|
|
481
488
|
|
|
482
489
|
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:
|
|
483
|
-
mio message reply --parent ${
|
|
490
|
+
mio message reply --parent ${R} --target ${L} <<'EOF'
|
|
484
491
|
\u2026
|
|
485
492
|
EOF
|
|
486
|
-
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.`:"",
|
|
487
|
-
Channel: ${
|
|
488
|
-
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 #${
|
|
489
|
-
Channel: ${
|
|
490
|
-
Reviewer feedback: ${
|
|
491
|
-
Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${
|
|
492
|
-
Channel: ${
|
|
493
|
-
Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;
|
|
493
|
+
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.`:"",le=`[system event: task #${Je(_)} was assigned to you${X}]
|
|
494
|
+
Channel: ${L}
|
|
495
|
+
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 #${Je(_)} --status done\`. Briefly acknowledge then begin.`+F;return N(le,O,_),!0}function H(w){let _=w.task_id,P=w.channel_id,R=w.assignee_id,C=w.assigner_id,O=w.parent_message_id;if(_&&C!==s){if(R!==s){p("debug",Ze,"task.assigned not to self \u2014 skip",{taskId:_,assigneeId:R});return}W({taskId:_,channelId:P,parentMessageId:O,assignerId:C,reason:"task-assigned"})}}function Y(w){let _=w.task_id,P=w.channel_id,R=w.from,C=w.to,O=w.actor_id,E=w.assignee_id;if(!_||O===s)return;if(!(E===s||l.wakeOnChannelTaskStatus&&v(P))){p("debug",Ze,"task.status_changed not relevant \u2014 skip",{taskId:_});return}let X=w.review_verdict,F=w.review_feedback;if(X==="bounce"&&E===s){if(!S(`bounce:${_}`))return;let Pe=un(o,O),Ie=Gn(o,P),Bt=F&&F.trim()?F.trim():"(see the task thread)",St=`[system event: your task #${Je(_)} was BOUNCED back for rework by ${Pe} after independent review]
|
|
496
|
+
Channel: ${Ie}.
|
|
497
|
+
Reviewer feedback: ${Bt}
|
|
498
|
+
Fix exactly what was flagged (usually a missing test or an unhandled edge case), then run \`mio task update #${Je(_)} --channel ${Ie} --status done\` again \u2014 it auto-closes after this one rework, no second review. This is NOT optional; do not stay silent.`;N(St,"task-bounce",_);return}if(!S(`status:${_}:${C}`)||!T("task-status",_))return;let le=un(o,O),ie=Gn(o,P),I=`[system event: task #${Je(_)} status changed from ${R??"?"} to ${C??"?"} by ${le}]
|
|
499
|
+
Channel: ${ie}.
|
|
500
|
+
Consider whether to push a brief update. Stay silent if nothing meaningful changed for you.`;N(I,"task-status",_)}function K(w){let _=w.task_id,P=w.channel_id,R=w.reviewer_id,C=w.owner_id,O=w.parent_message_id,E=w.title,L=w.number;if(!_)return;if(R!==s){p("debug",Ze,"review_requested not for self \u2014 skip",{taskId:_,reviewerId:R});return}if(!S(`review:${_}`))return;let X=un(o,C),F=Gn(o,P),le=L!==void 0?`#${L}`:`#${Je(_)}`,ie=O?`
|
|
494
501
|
Get the surrounding context, then inspect the ACTUAL deliverable (its files \u2014 build it, run its tests), not just the chat:
|
|
495
|
-
mio message read --channel ${
|
|
502
|
+
mio message read --channel ${F} --around ${Je(O)}
|
|
496
503
|
Post your review findings in the task thread:
|
|
497
|
-
mio message reply --parent ${
|
|
498
|
-
Channel: ${
|
|
504
|
+
mio message reply --parent ${O} --target ${F}`:"",I=`[system event: task ${le} "${E??""}" by ${X} is awaiting YOUR independent review]
|
|
505
|
+
Channel: ${F}.${ie}
|
|
499
506
|
|
|
500
507
|
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:
|
|
501
508
|
1. Build it and run its tests yourself. If build or tests fail \u2192 bounce.
|
|
@@ -504,12 +511,12 @@ You are the INDEPENDENT reviewer. Do an adversarial / mutation audit of the ACTU
|
|
|
504
511
|
|
|
505
512
|
Then submit your verdict:
|
|
506
513
|
\u2022 Everything works AND every claimed feature has a test that fails when broken \u2192
|
|
507
|
-
mio task review ${
|
|
514
|
+
mio task review ${le} --channel ${F} --pass
|
|
508
515
|
\u2022 A feature is unprotected (mutation stayed green), or you found a real bug \u2192
|
|
509
|
-
mio task review ${
|
|
510
|
-
A bounce sends it back to ${
|
|
516
|
+
mio task review ${le} --channel ${F} --bounce --feedback "<exactly what is untested/broken>"
|
|
517
|
+
A bounce sends it back to ${X} to add the missing test/fix; after their rework it closes without a second review.`;N(I,"task-review",_)}function q(w){w.sender_id===s&&y()}let ne=w=>{try{let _=w.payload??{};switch(w.topic){case"task.created":j(_);break;case"task.assigned":H(_);break;case"task.status_changed":Y(_);break;case"task.review_requested":K(_);break;case"message.created":q(_);break;default:break}}catch(_){p("warn",Ze,"task wake handler error (non-fatal)",{err:String(_)})}};return{start(){e(i,ne),p("info",Ze,"task wake router started",{workroomId:i,selfAgentId:s,quietSeconds:a,maxRepliesPerWindow:c,windowSeconds:d})},stop(){try{t(i,ne)}catch{}},noteSelfPost:y,synthesizeAssignedWake(w){return w.task_id?W({taskId:w.task_id,channelId:w.channel_id,parentMessageId:w.parent_message_id,reason:"task-assigned-selfheal",dedupeAlreadyReserved:!0}):!1},reserveAssignedDedupeKeys(w){for(let _ of w)_&&(S(M(_)),m.add(M(_)))}}}var Ze,qd=A(()=>{"use strict";ce();wt();Jr();Ze="taskWakeRouter"});import{spawn as uy}from"node:child_process";import{readFileSync as Xr,writeFileSync as Gd,existsSync as Qr,renameSync as fy,statSync as hy,unlinkSync as gy}from"node:fs";import{join as Zr}from"node:path";function Vd(n){let e=Zr(n.mioDir,"persona-counter.json"),t=Zr(n.mioDir,"persona.md"),r=t+".tmp",s=n.claudeCommand??ln()??"claude",i=!1,o=0,a=!1,c=d();function d(){if(Qr(e))try{let g=Xr(e,"utf8"),m=JSON.parse(g);if(m&&typeof m.messages_since_last_extract=="number")return{version:1,messages_since_last_extract:m.messages_since_last_extract,last_extract_at:m.last_extract_at??null}}catch{}return{version:1,messages_since_last_extract:0,last_extract_at:null}}function l(){try{Gd(e,JSON.stringify(c,null,2),{encoding:"utf8",mode:384})}catch(g){k(ve,"persona-counter write failed (non-fatal)",g)}}function u(){let g=Date.now();if(i)return{go:!1,reason:"already running"};if(g-o<n.quietSeconds*1e3)return{go:!1,reason:"within quietSeconds"};if(c.messages_since_last_extract>=Wd)return{go:!0,reason:`message threshold (${c.messages_since_last_extract})`};if(c.last_extract_at){let m=Date.parse(c.last_extract_at);if(!Number.isNaN(m)&&g-m>=py)return{go:!0,reason:"elapsed 24h"}}return{go:!1,reason:"no trigger"}}async function f(g){if(!i&&!a){i=!0,o=Date.now();try{p("info",ve,"persona extraction starting",{agentId:n.agentId,reason:g});let m=[];if(n.channelId)try{m=(await n.gateway.getChannelMessages(n.workroomId,n.channelId,void 0,Jd)).messages.slice(-Jd).map(W=>({sender:W.sender_display_name||`${W.sender_kind}:${W.sender_id.slice(0,8)}`,content:W.content,at:W.created_at}))}catch(N){k(ve,"getChannelMessages failed (continuing with empty messages)",N)}let y=[];try{let N=Zr(n.mioDir,"companion.json");if(Qr(N)){let j=Xr(N,"utf8"),W=JSON.parse(j);y=(Array.isArray(W.observations)?W.observations:[]).slice(-my)}}catch(N){k(ve,"companion.json read failed (continuing without observations)",N)}let b=[];try{n.channelId&&(b=n.companion.listChannelMembers(n.channelId).map(N=>({id:N.id,name:N.display_name??N.id,role:N.role??"",description:N.description??""}))),b.length===0&&(b=n.companion.listWorkroomEntities(n.workroomId).map(N=>({id:N.id,name:N.display_name??N.id,role:N.role??"",description:N.description??""})))}catch(N){k(ve,"roster derivation failed",N)}let x="";if(Qr(t))try{x=Xr(t,"utf8")}catch{}let v=yy(n.displayName,n.handle,n.role),S=_y({existingPersona:x,messages:m,observations:y,roster:b}),M=await wy(s,v,S,n.workspace,n.spawnEnv);if(!M||M.trim().length===0){p("warn",ve,"persona extraction produced empty output (keeping prior persona)",{agentId:n.agentId});return}let T=M.trim();T.startsWith("<!-- mio:persona v1 -->")||(T=`<!-- mio:persona v1 -->
|
|
511
518
|
|
|
512
|
-
${T}`),T=
|
|
519
|
+
${T}`),T=vy(T);try{Gd(r,T,{encoding:"utf8",mode:384}),fy(r,t)}catch(N){k(ve,"persona.md atomic write failed",N);try{gy(r)}catch{}return}c.messages_since_last_extract=0,c.last_extract_at=new Date().toISOString(),l(),p("info",ve,"persona extraction completed",{agentId:n.agentId,bytes:T.length,reason:g})}catch(m){k(ve,"persona extraction failed (keeping prior persona)",m)}finally{i=!1}}}function h(g){let{go:m,reason:y}=u();if(!m){p("debug",ve,"extraction skipped",{agentId:n.agentId,reason:g,gate:y});return}f(g)}return{noteMessage(){a||(c.messages_since_last_extract+=1,l(),c.messages_since_last_extract>=Wd&&h("threshold"))},kick(g="kick"){if(a)return;let m=Date.now();if(i){p("debug",ve,"kick ignored: already running",{agentId:n.agentId});return}if(m-o<n.quietSeconds*1e3){p("debug",ve,"kick ignored: within quietSeconds",{agentId:n.agentId});return}f(g)},stop(){a=!0}}}function yy(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}).
|
|
513
520
|
|
|
514
521
|
Below you'll see:
|
|
515
522
|
- The agent's existing persona.md (their cumulative knowledge so far)
|
|
@@ -535,22 +542,22 @@ Constraints:
|
|
|
535
542
|
- NEVER include UUIDs, internal IDs, mio CLI commands, or implementation details
|
|
536
543
|
- NEVER include speculation; only facts you can point to evidence for
|
|
537
544
|
|
|
538
|
-
Output the persona.md now.`}function
|
|
539
|
-
`)}function
|
|
540
|
-
`),t=[],r=[],s=null;for(let l of e)l.startsWith("## ")?(s&&t.push(s),s={header:l,body:[]}):s?s.body.push(l):r.push(l);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((l,u)=>{let f=i.findIndex(
|
|
545
|
+
Output the persona.md now.`}function _y(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(`
|
|
546
|
+
`)}function wy(n,e,t,r,s){return new Promise(i=>{let o=["-p","--output-format","text","--append-system-prompt",e,"--allow-dangerously-skip-permissions","--dangerously-skip-permissions","--permission-mode","bypassPermissions","--setting-sources","project,local"],a={...s??process.env};delete a.CLAUDECODE;let c="",d="",l=!1,u=uy(n,o,{cwd:r,env:a,stdio:["pipe","pipe","pipe"]}),f=setTimeout(()=>{if(!l){l=!0;try{u.kill("SIGTERM")}catch{}k(ve,"one-shot claude timed out",{timeoutMs:jd,stderrSnippet:d.slice(0,200)}),i("")}},jd);f.unref?.(),u.stdout?.on("data",h=>{c+=typeof h=="string"?h:h.toString("utf8")}),u.stderr?.on("data",h=>{d+=typeof h=="string"?h:h.toString("utf8")}),u.on("error",h=>{l||(l=!0,clearTimeout(f),k(ve,"one-shot claude spawn error",h),i(""))}),u.on("exit",h=>{if(!l){if(l=!0,clearTimeout(f),h!==0){p("warn",ve,"one-shot claude exited non-zero",{code:h,stderrSnippet:d.slice(0,400),stdoutSnippet:c.slice(0,400)}),i("");return}i(c)}});try{u.stdin?.write(t),u.stdin?.end()}catch(h){k(ve,"one-shot claude stdin write failed",h)}})}function vy(n){if(n.length<=Yd)return n;let e=n.split(`
|
|
547
|
+
`),t=[],r=[],s=null;for(let l of e)l.startsWith("## ")?(s&&t.push(s),s={header:l,body:[]}):s?s.body.push(l):r.push(l);s&&t.push(s);let i=["About the user","About my work patterns","About this workroom","About the team"],o=[...t].sort((l,u)=>{let f=i.findIndex(g=>l.header.includes(g)),h=i.findIndex(g=>u.header.includes(g));return(f===-1?99:f)-(h===-1?99:h)}),a=[...r],c=Yd-a.join(`
|
|
541
548
|
`).length,d=new Set;for(let l of o){let u=l.header.length+1+l.body.join(`
|
|
542
549
|
`).length+1;u<=c&&(d.add(l),c-=u)}for(let l of t)d.has(l)&&(a.push(l.header),a.push(...l.body));return a.join(`
|
|
543
550
|
`).trim()+`
|
|
544
|
-
`}function Hd(n){let e=Yr(n,"persona.md");if(!Jr(e))return null;try{let t=Zm(e);if(!t.isFile()||t.size===0)return null;let s=jr(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var _e,Dd,ty,Bd,Fd,ny,Ud,Gd=R(()=>{"use strict";Dr();oe();_e="personaCrystallizer",Dd=50,ty=1440*60*1e3,Bd=6e4,Fd=50,ny=50;Ud=4e3});var Qd={};Ce(Qd,{bootAgentSpine:()=>Xd,deriveAgentWorkspace:()=>zd,normalizeRuntime:()=>Kd,runDaemon:()=>Ci,startAgentSpine:()=>Yd});import{join as Ae,dirname as ay}from"path";import{fileURLToPath as cy}from"url";import{homedir as ly,hostname as Wd,arch as dy}from"os";import{unlink as uy,writeFile as jd,mkdir as Ti,readdir as fy,copyFile as hy,readFile as py}from"fs/promises";import{existsSync as gy}from"fs";import{spawnSync as my}from"child_process";import{randomUUID as yy}from"crypto";async function Yd(n){let{config:e,machineToken:t,workingDirectory:r,gateway:s,agentId:i,launchId:o,agentHandle:a,displayName:c,description:d,role:l,spawnFn:u,claudeCommand:f,codexCommand:g,model:h,runtime:m="claude",reasoningEffort:_,contextTracker:k,presenceTracker:E,contextPolicy:b}=n,S=n.execContext??wi(),O=b??wd({role:l,displayName:c,description:d,capabilities:n.serverCapabilities}),T=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:A,spawnEnv:G,proxyHandle:q}=await ed({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:T,execContext:S,...k?{contextTracker:k}:{}}),F=null,W=Ae(A,"companion.json"),K=new Wr(W),H=null,I=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{H=await s.getWorkroomRoster(I),xi(K,H),p("info",L,"CompanionGraph hydrated from roster",{agentId:i,channels:H.channels.length,members:H.members.length})}catch(w){x(L,"CompanionGraph hydrate failed (continuing with empty graph)",w)}let y;if(H){let v=H.channels.filter(C=>C.member_ids.includes(i))[0]??H.channels[0];if(v){let C=new Map(H.members.map(J=>[J.id,J])),$=v.member_ids.map(J=>C.get(J)).filter(J=>!!J),M=new Set(v.member_ids),ne=H.members.filter(J=>!M.has(J.id));y={channelId:v.id,channelName:v.name,inChannel:$,otherInWorkroom:ne}}}try{let w={agentId:i,handle:a,displayName:c,description:d,role:l,serverId:e.org_id,computer:`${Wd()} (${e.machine_id})`,hostname:Wd(),os:`${process.platform} ${dy()}`,workspace:r,runtime:m,capabilities:T,roster:y,persona:Hd(A)??void 0},v=id(w),C=Ae(A,"system-prompt.md");if(await jd(C,v,{encoding:"utf8",mode:384}),m==="claude")try{let N=Ae(r,".claude","skills");await Ti(N,{recursive:!0});let ee=ay(cy(import.meta.url)),Le=Ae(ee,"..","..","runtimes","skills"),ye=(await fy(Le)).filter(Fn=>Fn.endsWith(".md"));for(let Fn of ye){let vu=Fn.replace(/\.md$/,""),Bi=Ae(N,vu);await Ti(Bi,{recursive:!0}),await hy(Ae(Le,Fn),Ae(Bi,"SKILL.md"))}p("info",L,"Materialised Claude skills",{count:ye.length,destRoot:N})}catch(N){x(L,"Failed to materialise Claude skills (continuing without)",N)}let $=Ae(A,"mcp-config.json"),M="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.";if(m==="codex"){let N={workingDirectory:r,model:h??"gpt-5-codex",..._?{reasoningEffort:_}:{},systemPromptPath:C,mcpConfigPath:$,spawnEnv:G,firstTurnText:M,...u?{spawnFn:u}:{},...g?{codexCommand:g}:{},...E?{presenceTracker:E,agentId:i}:{}};F=md(N),p("info",L,"codex host: app-server",{agentId:i})}else F=dd({workingDirectory:r,model:h??"sonnet",systemPromptPath:C,mcpConfigPath:$,spawnEnv:G,firstTurnText:M,...u?{spawnFn:u}:{},...f?{claudeCommand:f}:{},...E?{presenceTracker:E,agentId:i}:{}});F.start();let ne=Td({agentId:i,onFire:async N=>{F.enqueueUserTurn(`[reminder fired] ${N.title}`);try{await s.reminderFire(i,N.id,N.version)}catch(ee){x(L,`reminder report-fire failed (agent ${i}, reminder ${N.id}) \u2014 local wake already happened; will retry on next sync`,ee)}}}),J=e.autonomous_agent.workroom_id,P=new Hr(s),j=bd({gateway:s,host:F,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:J,reminderCache:ne,onInboundMessage:N=>{P.start(i,N)},...k?{contextTracker:k}:{},contextPolicy:O});j.start(),F.onBoundary(()=>{P.stop(i)});let re=e.autonomous_agent,le=Md({subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:F,selfAgentId:i,workroomId:J,companion:K,quietSeconds:re.quiet_seconds,maxRepliesPerWindow:re.max_replies_per_window,windowSeconds:re.window_seconds,contextPolicy:O});le.start();let de=y?.channelId??H?.channels.find(N=>N.member_ids.includes(i))?.id,xe=qd({workspace:r,mioDir:A,agentId:i,displayName:c,handle:a,role:l,workroomId:I,channelId:de,gateway:s,companion:K,quietSeconds:re.quiet_seconds,...f?{claudeCommand:f}:{}}),_t=N=>{try{let ee=N.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(N.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(I).then(ye=>xi(K,ye)).catch(ye=>x(L,`roster refetch failed for ${N.topic}`,ye)),ee.channel_id&&ee.member_id&&K.logObservation({channel_id:ee.channel_id,entity_id:ee.member_id,kind:N.topic})),N.topic==="message.created"&&ee.sender_id&&ee.channel_id){K.logObservation({entity_id:ee.sender_id,channel_id:ee.channel_id,kind:"sent_message"});try{xe.noteMessage()}catch(ye){x(L,"personaCrystallizer.noteMessage error (non-fatal)",ye)}}}catch(ee){x(L,"companionWsHandler error (non-fatal)",ee)}};return s.subscribe(I,_t),s.listReminders(i).then(N=>ne.snapshot(N)).catch(N=>x(L,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,N)),xy({gateway:s,agentId:i,taskWakeRouter:le,bootRoster:H,mioDir:A}).catch(N=>x(L,`cold-start task self-heal failed for agent ${i} (non-fatal)`,N)),p("info",L,"Agentic spine started",{agentId:i,workroomId:J,mioDir:A}),vy(j,F,q,i,ne,{companion:K,gateway:s,workroomId:I,companionWsHandler:_t,taskWakeRouter:le,personaCrystallizer:xe})}catch(w){try{F?.stop()}catch{}try{K.close()}catch{}throw await q.close().catch(()=>{}),w}}function vy(n,e,t,r,s,i){e.onExit(c=>{p("warn",L,"agent claude host exited",{agentId:r,code:c})}),e.onSessionId(c=>{p("info",L,"agent session id",{agentId:r,sessionId:c})}),n.onInjected(c=>{p("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)}}p("info",L,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function ky(n){try{let e=await py(Ae(n,Vd),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function Sy(n,e){try{await jd(Ae(n,Vd),JSON.stringify([...e]),"utf8")}catch(t){x(L,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function xy(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){p("debug",L,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(h=>h.member_ids.includes(t)).map(h=>h.name).filter(h=>!!h)),o.length===0)try{o=(await e.getAgentChannels(t)).map(m=>m.name).filter(m=>!!m)}catch(h){x(L,`self-heal: getAgentChannels failed for agent ${t}`,h);return}if(o.length===0){p("debug",L,"self-heal: agent has no channels \u2014 nothing to scan",{agentId:t});return}let a=e.getTasks,c=[],d=await Promise.allSettled(o.map(h=>a(t,h.startsWith("#")?h:`#${h}`)));for(let h of d)if(h.status==="fulfilled")for(let m of h.value)m.assignee_id===t&&m.status==="in_progress"&&c.push(m);else x(L,`self-heal: getTasks failed for a channel (agent ${t})`,h.reason);if(c.length===0){p("debug",L,"self-heal: no owned in_progress tasks",{agentId:t});return}let l=h=>{let m=h.updated_at??h.created_at,_=m?Date.parse(m):NaN;return Number.isFinite(_)?_:0};c.sort((h,m)=>l(m)-l(h));let u=await ky(i),f=c.filter(h=>!u.has(h.id)).slice(0,by);if(f.length===0){p("debug",L,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(f.map(h=>h.id));let g=0;try{for(let h of f){let m=!1;if(h.parent_message_id&&e.getThreadReplies)try{m=(await e.getThreadReplies(t,h.parent_message_id,50)).some(k=>k.sender_id===t)}catch(_){x(L,`self-heal: getThreadReplies failed for task ${h.id} (agent ${t}) \u2014 treating as no activity`,_)}if(u.add(h.id),m){p("debug",L,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:h.id});continue}try{r.synthesizeAssignedWake({task_id:h.id,...h.channel_id?{channel_id:h.channel_id}:{},...h.parent_message_id?{parent_message_id:h.parent_message_id}:{}})&&(g+=1)}catch(_){x(L,`self-heal: synthesizeAssignedWake threw for task ${h.id} (agent ${t}) \u2014 task already marked seen, continuing`,_)}}}finally{await Sy(i,u)}p("info",L,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:f.length,healed:g})}function zd(n,e,t){let r=Ln(n.replace(/^@/,"").toLowerCase()),s=Ln(e),i=`${r}-${s}`,o=Ae(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function Kd(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 Ey(n){try{let t=my("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&gy(t)}catch{return!1}}async function Xd(n){let{config:e,gateway:t,retrieveTokenFn:r=lt,mkdirFn:s=k=>Ti(k,{recursive:!0,mode:448}),startSpineFn:i=Yd,mioDir:o=Jd,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=Ey}=n,d=e.autonomous_agent;if(!d?.enabled)return;let l,u;try{l=r(),u=await a(d.workroom_id)}catch(k){x(L,"Failed to start agentic spine \u2014 daemon continues without spine",k);return}let f=u.filter(k=>k.kind==="agent"&&k.machine_id===e.machine_id);if(f.length===0){p("error",L,`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 g=Rd(),h=new Gr(t),m=[];for(let k of f){let E=k.handle??"@"+k.display_name,{selected:b,raw:S}=Kd(k.runtime);if(b==="codex"){if(!c("codex")){p("error",L,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:k.id,handle:E});continue}}else if(b==="unsupported"){p("warn",L,`runtime '${S}' not supported; spine not started for this agent ${k.id}`,{agentId:k.id,handle:E,runtime:S});continue}if(b==="claude"&&!c("claude")){p("error",L,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:k.id,handle:E});continue}try{let O=k.id,{workingDirectory:T}=zd(E,e.machine_id,o);await s(T);let A=k.display_name||E.replace(/^@/,""),G=k.description||"An AI agent running on this machine.",q=b==="codex"?"gpt-5-codex":"sonnet",F=k.model||q,W;if(b==="codex"){let H=k.capabilities;if(H&&typeof H=="object"){let I=H.reasoning_effort;typeof I=="string"&&(I==="low"||I==="medium"||I==="high")&&(W=I)}W=W??"medium"}let K=await i({config:e,machineToken:l,workingDirectory:T,gateway:t,agentId:O,launchId:yy(),agentHandle:E,displayName:A,description:G,role:k.role,serverCapabilities:k.capabilities,model:F,runtime:b,...W?{reasoningEffort:W}:{},contextTracker:g,presenceTracker:h});m.push(K),p("info",L,"Agentic spine started",{agentId:O,workroomId:d.workroom_id})}catch(O){x(L,`Failed to start spine for agent ${k.id} \u2014 continuing`,O);continue}}if(m.length===0)return;let _=!1;return{handles:m,async stop(){_||(_=!0,await Promise.allSettled(m.map(k=>k.stop())))}}}async function Ci(){p("info",L,"Starting mio-agent daemon");let n=De();p("info",L,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await Il();let e=new Pr;await uy(Ei).catch(()=>{}),await e.listen(Ei);let t=new Ir("0.1.0");await t.listen(_y,wy);let r=new Er(n);await r.start();let s=new Tr(r);s.startHeartbeats();let i=45e3;r.machineHeartbeat().catch(f=>x(L,"Initial machine heartbeat failed (non-fatal)",f));let o=setInterval(()=>{r.machineHeartbeat().catch(f=>x(L,"Machine heartbeat failed (non-fatal)",f))},i),a=new Ar(r,{runtimes:n.runtimes,ipcSocketPath:Ei}),c=new Cr(s,a),d=await Xd({config:n,gateway:r,getWorkroomMembersFn:f=>r.getWorkroomMembers(f)});e.onMessage(f=>{if(p("info",L,"IPC message from subprocess",{type:f.type}),a.onIpcMessage(f),f.type==="kick_persona"){let g=f.agent_id,h=f.reason??"ipc_kick";if(!d){p("warn",L,"IPC kick_persona: no spine running \u2014 ignoring");return}let m=0;for(let _ of d.handles)if(!(g&&_.agentId!==g))try{_.personaCrystallizer?.kick(h),m+=1}catch(k){x(L,"IPC kick_persona: kick failed",k)}p("info",L,"IPC kick_persona dispatched",{kicked:m,targetAgent:g,reason:h});return}if(f.type==="join_workroom"){let g=f.workroom_id;if(!g){p("warn",L,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}c.openWorkroom(g).then(h=>{h?p("info",L,"IPC join_workroom: workroom opened",{workroomId:g,sessionId:h.sessionId}):p("warn",L,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:g})}).catch(h=>{x(L,"IPC join_workroom: unexpected error (should not happen)",h)})}}),p("info",L,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let l=!1;async function u(f){if(!l){l=!0,p("info",L,`${f} received \u2014 initiating graceful shutdown`);try{clearInterval(o),await r.machineHeartbeat(!0).catch(g=>x(L,"Going-offline heartbeat failed (non-fatal)",g)),a.beginShutdown(),await a.drainIrreversible(),c.shutdownAll(),await s.stop(),d&&await d.stop(),await r.stop(),await e.stop(),await t.stop(),p("info",L,"Graceful shutdown complete")}catch(g){x(L,"Error during shutdown",g)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{u("SIGTERM")}),process.on("SIGINT",()=>{u("SIGINT")}),await new Promise(()=>{})}var L,Jd,Ei,_y,wy,by,Vd,Ri=R(()=>{"use strict";Be();Mt();oe();Tl();Rl();Ol();gi();Ul();ql();Or();td();od();ud();yd();kd();xd();Ed();Cd();Od();Nd();Ld();Gd();Ur();L="daemon",Jd=Ae(ly(),".mio"),Ei=Ae(Jd,"agent.sock"),_y="127.0.0.1",wy=7878;by=5,Vd="self-heal-seen.json"});var Oi={};Ce(Oi,{runStart:()=>Ty});async function Ty(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}p("info","start","Starting mio-agent in foreground (dev mode, latest OK)"),await Ci()}var Ai=R(()=>{"use strict";oe();Ri()});import{createHash as Cy}from"crypto";import{mkdtempSync as Ry,rmSync as Zd,readFileSync as Oy,copyFileSync as Ay,chmodSync as Py,renameSync as Iy,existsSync as eu}from"fs";import{execFileSync as an}from"child_process";import{tmpdir as Ny,platform as My}from"os";import{join as Vr}from"path";function By(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function Fy(n){return`https://github.com/${Ly}/${$y}/releases/download/v${n}/`}function tu(n,e){try{return an("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function Uy(n,e){for(let t of n.split(`
|
|
545
|
-
`)){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
|
|
551
|
+
`}function zd(n){let e=Zr(n,"persona.md");if(!Qr(e))return null;try{let t=hy(e);if(!t.isFile()||t.size===0)return null;let s=Xr(e,"utf8").replace(/^<!--\s*mio:persona v1\s*-->\s*/,"").trim();return s.length>0?s:null}catch{return null}}var ve,Wd,py,jd,Jd,my,Yd,Kd=A(()=>{"use strict";Gr();ce();ve="personaCrystallizer",Wd=50,py=1440*60*1e3,jd=6e4,Jd=50,my=50;Yd=4e3});var ou={};Ce(ou,{bootAgentSpine:()=>iu,deriveAgentWorkspace:()=>ru,normalizeRuntime:()=>su,runDaemon:()=>Ii,startAgentSpine:()=>tu});import{join as Ae,dirname as by}from"path";import{fileURLToPath as ky}from"url";import{homedir as Sy,hostname as Xd,arch as Ey}from"os";import{unlink as xy,writeFile as Qd,mkdir as Pi,readdir as Ty,copyFile as Cy,readFile as Ry}from"fs/promises";import{existsSync as Oy}from"fs";import{spawnSync as Ay}from"child_process";import{randomUUID as Zd}from"crypto";async function tu(n){let{config:e,machineToken:t,workingDirectory:r,gateway:s,agentId:i,launchId:o,agentHandle:a,displayName:c,description:d,role:l,spawnFn:u,claudeCommand:f,codexCommand:h,model:g,runtime:m="claude",reasoningEffort:y,contextTracker:b,presenceTracker:x,contextPolicy:v}=n,S=n.execContext??Ei(),M=v??xd({role:l,displayName:c,description:d,capabilities:n.serverCapabilities}),T=["send","read","tasks","reminders","actions","reactions","attachments","profile"],{mioDir:N,spawnEnv:j,proxyHandle:W}=await id({agentId:i,launchId:o,workingDirectory:r,serverUrl:e.server_url,machineToken:t,capabilities:T,execContext:S,...b?{contextTracker:b}:{}}),H=null,Y=Ae(N,"companion.json"),K=new Kr(Y),q=null,ne=e.autonomous_agent.workroom_id;if(s.getWorkroomRoster)try{q=await s.getWorkroomRoster(ne),Oi(K,q),p("info",$,"CompanionGraph hydrated from roster",{agentId:i,channels:q.channels.length,members:q.members.length})}catch(_){k($,"CompanionGraph hydrate failed (continuing with empty graph)",_)}let w;if(q){let P=q.channels.filter(R=>R.member_ids.includes(i))[0]??q.channels[0];if(P){let R=new Map(q.members.map(L=>[L.id,L])),C=P.member_ids.map(L=>R.get(L)).filter(L=>!!L),O=new Set(P.member_ids),E=q.members.filter(L=>!O.has(L.id));w={channelId:P.id,channelName:P.name,inChannel:C,otherInWorkroom:E}}}try{let _={agentId:i,handle:a,displayName:c,description:d,role:l,serverId:e.org_id,computer:`${Xd()} (${e.machine_id})`,hostname:Xd(),os:`${process.platform} ${Ey()}`,workspace:r,runtime:m,capabilities:T,roster:w,persona:zd(N)??void 0},P=dd(_),R=Ae(N,"system-prompt.md");if(await Qd(R,P,{encoding:"utf8",mode:384}),m==="claude")try{let D=Ae(r,".claude","skills");await Pi(D,{recursive:!0});let oe=by(ky(import.meta.url)),J=Ae(oe,"..","..","runtimes","skills"),de=(await Ty(J)).filter(Ne=>Ne.endsWith(".md"));for(let Ne of de){let et=Ne.replace(/\.md$/,""),Gi=Ae(D,et);await Pi(Gi,{recursive:!0}),await Cy(Ae(J,Ne),Ae(Gi,"SKILL.md"))}p("info",$,"Materialised Claude skills",{count:de.length,destRoot:D})}catch(D){k($,"Failed to materialise Claude skills (continuing without)",D)}let C=Ae(N,"mcp-config.json"),O="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.";if(m==="codex"){let D={workingDirectory:r,model:g??"gpt-5-codex",...y?{reasoningEffort:y}:{},systemPromptPath:R,mcpConfigPath:C,spawnEnv:j,firstTurnText:O,...u?{spawnFn:u}:{},...h?{codexCommand:h}:{},...x?{presenceTracker:x,agentId:i}:{}};H=bd(D),p("info",$,"codex host: app-server",{agentId:i})}else H=pd({workingDirectory:r,model:g??"sonnet",systemPromptPath:R,mcpConfigPath:C,spawnEnv:j,firstTurnText:O,...u?{spawnFn:u}:{},...f?{claudeCommand:f}:{},...x?{presenceTracker:x,agentId:i}:{}});H.start();let E=Nd({agentId:i,onFire:async D=>{H.enqueueUserTurn(`[reminder fired] ${D.title}`);try{await s.reminderFire(i,D.id,D.version)}catch(oe){k($,`reminder report-fire failed (agent ${i}, reminder ${D.id}) \u2014 local wake already happened; will retry on next sync`,oe)}}}),L=e.autonomous_agent.workroom_id,X=new Vr(s),F,le=Rd({gateway:s,host:H,selfAgentId:i,selfHandle:a,selfDisplayName:c,workroomId:L,reminderCache:E,onInboundMessage:D=>{F=D,X.start(i,D)},...b?{contextTracker:b}:{},contextPolicy:M,mioDir:N,downloadAttachment:D=>_a(e.server_url,t,i,D).then(oe=>({filename:oe.filename,mime_type:oe.mime_type,data_base64:oe.data_base64}))});le.start(),H.onBoundary(()=>{X.stop(i)});let ie=0,I="";H.onTurnError?.(D=>{let oe=Date.now();if(D===I&&oe-ie<6e4||!F)return;I=D,ie=oe;let J=/usage limit/i.test(D)?"\u7528\u91CF\u5DF2\u8FBE\u4E0A\u9650,\u8BF7\u5145\u503C\u6216\u7A0D\u540E\u518D\u8BD5":/unauthor|auth|401|403/i.test(D)?"\u8BA4\u8BC1\u5931\u8D25,\u8BF7\u68C0\u67E5\u767B\u5F55/\u5BC6\u94A5":D.slice(0,160);Qn(e.server_url,L,F,{content:`\u26A0\uFE0F \u6211\u6682\u65F6\u65E0\u6CD5\u56DE\u590D(${c} \u8FD0\u884C\u51FA\u9519:${J})`,clientIdempotencyKey:Zd(),agentId:i},t).catch(de=>k("run","post turn-error notice failed",de))});let Pe=e.autonomous_agent,Ie=Hd({subscribe:s.subscribe.bind(s),unsubscribe:s.unsubscribe.bind(s),host:H,selfAgentId:i,workroomId:L,companion:K,quietSeconds:Pe.quiet_seconds,maxRepliesPerWindow:Pe.max_replies_per_window,windowSeconds:Pe.window_seconds,contextPolicy:M});Ie.start();let Bt=w?.channelId??q?.channels.find(D=>D.member_ids.includes(i))?.id,St=Vd({workspace:r,mioDir:N,agentId:i,displayName:c,handle:a,role:l,workroomId:ne,channelId:Bt,gateway:s,companion:K,quietSeconds:Pe.quiet_seconds,spawnEnv:j,...f?{claudeCommand:f}:{}}),Ye=D=>{try{let oe=D.payload??{};if(new Set(["roster.member_added","roster.member_removed","roster.profile_updated","channel.created","channel.updated"]).has(D.topic)&&s.getWorkroomRoster&&(s.getWorkroomRoster(ne).then(de=>Oi(K,de)).catch(de=>k($,`roster refetch failed for ${D.topic}`,de)),oe.channel_id&&oe.member_id&&K.logObservation({channel_id:oe.channel_id,entity_id:oe.member_id,kind:D.topic})),D.topic==="message.created"&&oe.sender_id&&oe.channel_id){K.logObservation({entity_id:oe.sender_id,channel_id:oe.channel_id,kind:"sent_message"});try{St.noteMessage()}catch(de){k($,"personaCrystallizer.noteMessage error (non-fatal)",de)}}}catch(oe){k($,"companionWsHandler error (non-fatal)",oe)}};return s.subscribe(ne,Ye),s.listReminders(i).then(D=>E.snapshot(D)).catch(D=>k($,`reminder boot snapshot failed for agent ${i} \u2014 cache starts empty, will fill via WS`,D)),Dy({gateway:s,agentId:i,taskWakeRouter:Ie,bootRoster:q,mioDir:N}).catch(D=>k($,`cold-start task self-heal failed for agent ${i} (non-fatal)`,D)),p("info",$,"Agentic spine started",{agentId:i,workroomId:L,mioDir:N}),Ny(le,H,W,i,E,{companion:K,gateway:s,workroomId:ne,companionWsHandler:Ye,taskWakeRouter:Ie,personaCrystallizer:St})}catch(_){try{H?.stop()}catch{}try{K.close()}catch{}throw await W.close().catch(()=>{}),_}}function Ny(n,e,t,r,s,i){e.onExit(c=>{p("warn",$,"agent claude host exited",{agentId:r,code:c})}),e.onSessionId(c=>{p("info",$,"agent session id",{agentId:r,sessionId:c})}),n.onInjected(c=>{p("info",$,"injected message to agent",{agentId:r})});let o=!1;async function a(){if(!o){o=!0;try{n.stop()}catch(c){k($,"coord.stop() error",c)}try{s.stop()}catch(c){k($,"reminderCache.stop() error",c)}try{e.stop()}catch(c){k($,"host.stop() error",c)}try{await t.close()}catch(c){k($,"proxyHandle.close() error",c)}if(i){try{i.personaCrystallizer?.stop()}catch(c){k($,"personaCrystallizer.stop() error",c)}try{i.taskWakeRouter?.stop()}catch(c){k($,"taskWakeRouter.stop() error",c)}try{i.gateway.unsubscribe(i.workroomId,i.companionWsHandler)}catch(c){k($,"companion gateway.unsubscribe() error",c)}try{i.companion.close()}catch(c){k($,"companion.close() error",c)}}p("info",$,"Agentic spine stopped",{agentId:r})}}return{coord:n,host:e,agentId:r,personaCrystallizer:i?.personaCrystallizer,stop:a}}async function Ly(n){try{let e=await Ry(Ae(n,nu),"utf8"),t=JSON.parse(e);if(Array.isArray(t))return new Set(t.filter(r=>typeof r=="string"))}catch{}return new Set}async function $y(n,e){try{await Qd(Ae(n,nu),JSON.stringify([...e]),"utf8")}catch(t){k($,"self-heal: failed to persist self-heal-seen.json (non-fatal)",t)}}async function Dy(n){let{gateway:e,agentId:t,taskWakeRouter:r,bootRoster:s,mioDir:i}=n;if(!e.getTasks){p("debug",$,"self-heal skipped: gateway has no getTasks",{agentId:t});return}let o=[];if(s&&(o=s.channels.filter(g=>g.member_ids.includes(t)).map(g=>g.name).filter(g=>!!g)),o.length===0)try{o=(await e.getAgentChannels(t)).map(m=>m.name).filter(m=>!!m)}catch(g){k($,`self-heal: getAgentChannels failed for agent ${t}`,g);return}if(o.length===0){p("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(g=>a(t,g.startsWith("#")?g:`#${g}`)));for(let g of d)if(g.status==="fulfilled")for(let m of g.value)m.assignee_id===t&&m.status==="in_progress"&&c.push(m);else k($,`self-heal: getTasks failed for a channel (agent ${t})`,g.reason);if(c.length===0){p("debug",$,"self-heal: no owned in_progress tasks",{agentId:t});return}let l=g=>{let m=g.updated_at??g.created_at,y=m?Date.parse(m):NaN;return Number.isFinite(y)?y:0};c.sort((g,m)=>l(m)-l(g));let u=await Ly(i),f=c.filter(g=>!u.has(g.id)).slice(0,My);if(f.length===0){p("debug",$,"self-heal: all owned in_progress tasks already self-healed in a prior boot",{agentId:t,ownedInProgress:c.length});return}r.reserveAssignedDedupeKeys(f.map(g=>g.id));let h=0;try{for(let g of f){let m=!1;if(g.parent_message_id&&e.getThreadReplies)try{m=(await e.getThreadReplies(t,g.parent_message_id,50)).some(b=>b.sender_id===t)}catch(y){k($,`self-heal: getThreadReplies failed for task ${g.id} (agent ${t}) \u2014 treating as no activity`,y)}if(u.add(g.id),m){p("debug",$,"self-heal: task already has agent activity \u2014 skip",{agentId:t,taskId:g.id});continue}try{r.synthesizeAssignedWake({task_id:g.id,...g.channel_id?{channel_id:g.channel_id}:{},...g.parent_message_id?{parent_message_id:g.parent_message_id}:{}})&&(h+=1)}catch(y){k($,`self-heal: synthesizeAssignedWake threw for task ${g.id} (agent ${t}) \u2014 task already marked seen, continuing`,y)}}}finally{await $y(i,u)}p("info",$,"cold-start task self-heal complete",{agentId:t,ownedInProgress:c.length,scanned:f.length,healed:h})}function ru(n,e,t){let r=Un(n.replace(/^@/,"").toLowerCase()),s=Un(e),i=`${r}-${s}`,o=Ae(t,"workspaces",i);return{agentId:i,workingDirectory:o}}function su(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 By(n){try{let t=Ay("which",[n],{encoding:"utf8",env:process.env}).stdout?.trim();return!!t&&Oy(t)}catch{return!1}}async function iu(n){let{config:e,gateway:t,retrieveTokenFn:r=ht,mkdirFn:s=b=>Pi(b,{recursive:!0,mode:448}),startSpineFn:i=tu,mioDir:o=eu,getWorkroomMembersFn:a,isRuntimeAvailableFn:c=By}=n,d=e.autonomous_agent;if(!d?.enabled)return;let l,u;try{l=r(),u=await a(d.workroom_id)}catch(b){k($,"Failed to start agentic spine \u2014 daemon continues without spine",b);return}let f=u.filter(b=>b.kind==="agent"&&b.machine_id===e.machine_id);if(f.length===0){p("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 h=Ld(),g=new zr(t),m=[];for(let b of f){let x=b.handle??"@"+b.display_name,{selected:v,raw:S}=su(b.runtime);if(v==="codex"){if(!c("codex")){p("error",$,"codex runtime selected but the 'codex' command was not found on PATH; spine not started",{agentId:b.id,handle:x});continue}}else if(v==="unsupported"){p("warn",$,`runtime '${S}' not supported; spine not started for this agent ${b.id}`,{agentId:b.id,handle:x,runtime:S});continue}if(v==="claude"&&!c("claude")){p("error",$,"claude runtime selected but the 'claude' command was not found on PATH; spine not started",{agentId:b.id,handle:x});continue}try{let M=b.id,{workingDirectory:T}=ru(x,e.machine_id,o);await s(T);let N=b.display_name||x.replace(/^@/,""),j=b.description||"An AI agent running on this machine.",W=v==="codex"?"gpt-5-codex":"sonnet",H=b.model||W,Y;if(v==="codex"){let q=b.capabilities;if(q&&typeof q=="object"){let ne=q.reasoning_effort;typeof ne=="string"&&(ne==="low"||ne==="medium"||ne==="high")&&(Y=ne)}Y=Y??"medium"}let K=await i({config:e,machineToken:l,workingDirectory:T,gateway:t,agentId:M,launchId:Zd(),agentHandle:x,displayName:N,description:j,role:b.role,serverCapabilities:b.capabilities,model:H,runtime:v,...Y?{reasoningEffort:Y}:{},contextTracker:h,presenceTracker:g});m.push(K),p("info",$,"Agentic spine started",{agentId:M,workroomId:d.workroom_id})}catch(M){k($,`Failed to start spine for agent ${b.id} \u2014 continuing`,M);continue}}if(m.length===0)return;let y=!1;return{handles:m,async stop(){y||(y=!0,await Promise.allSettled(m.map(b=>b.stop())))}}}async function Ii(){p("info",$,"Starting mio-agent daemon");let n=Ue();p("info",$,`Machine: ${n.machine_id}, Server: ${n.server_url}`),await Dl();let e=new Dr;await xy(Ai).catch(()=>{}),await e.listen(Ai);let t=new Br("0.1.0");await t.listen(Py,Iy);let r=new Pr(n);await r.start();let s=new Ir(r);s.startHeartbeats();let i=45e3;r.machineHeartbeat().catch(f=>k($,"Initial machine heartbeat failed (non-fatal)",f));let o=setInterval(()=>{r.machineHeartbeat().catch(f=>k($,"Machine heartbeat failed (non-fatal)",f))},i),a=new $r(r,{runtimes:n.runtimes,ipcSocketPath:Ai}),c=new Nr(s,a),d=await iu({config:n,gateway:r,getWorkroomMembersFn:f=>r.getWorkroomMembers(f)});e.onMessage(f=>{if(p("info",$,"IPC message from subprocess",{type:f.type}),a.onIpcMessage(f),f.type==="kick_persona"){let h=f.agent_id,g=f.reason??"ipc_kick";if(!d){p("warn",$,"IPC kick_persona: no spine running \u2014 ignoring");return}let m=0;for(let y of d.handles)if(!(h&&y.agentId!==h))try{y.personaCrystallizer?.kick(g),m+=1}catch(b){k($,"IPC kick_persona: kick failed",b)}p("info",$,"IPC kick_persona dispatched",{kicked:m,targetAgent:h,reason:g});return}if(f.type==="join_workroom"){let h=f.workroom_id;if(!h){p("warn",$,"IPC join_workroom: missing workroom_id \u2014 ignoring");return}c.openWorkroom(h).then(g=>{g?p("info",$,"IPC join_workroom: workroom opened",{workroomId:h,sessionId:g.sessionId}):p("warn",$,"IPC join_workroom: openWorkroom returned null (see earlier log)",{workroomId:h})}).catch(g=>{k($,"IPC join_workroom: unexpected error (should not happen)",g)})}}),p("info",$,"Daemon ready \u2014 IPC + health + gateway + coordinator connected, awaiting events");let l=!1;async function u(f){if(!l){l=!0,p("info",$,`${f} received \u2014 initiating graceful shutdown`);try{clearInterval(o),await r.machineHeartbeat(!0).catch(h=>k($,"Going-offline heartbeat failed (non-fatal)",h)),a.beginShutdown(),await a.drainIrreversible(),c.shutdownAll(),await s.stop(),d&&await d.stop(),await r.stop(),await e.stop(),await t.stop(),p("info",$,"Graceful shutdown complete")}catch(h){k($,"Error during shutdown",h)}finally{process.exit(0)}}}process.on("SIGTERM",()=>{u("SIGTERM")}),process.on("SIGINT",()=>{u("SIGINT")}),await new Promise(()=>{})}var $,eu,Ai,Py,Iy,My,nu,Ni=A(()=>{"use strict";He();Ft();ce();Pl();Nl();Ml();vi();jl();Jl();Lr();od();ud();md();kd();Od();Pd();Id();Md();$d();Ud();qd();Kd();Jr();Zn();$="daemon",eu=Ae(Sy(),".mio"),Ai=Ae(eu,"agent.sock"),Py="127.0.0.1",Iy=7878;My=5,nu="self-heal-seen.json"});var Mi={};Ce(Mi,{runStart:()=>Fy});async function Fy(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}p("info","start","Starting mio-agent in foreground (dev mode, latest OK)"),await Ii()}var Li=A(()=>{"use strict";ce();Ni()});import{createHash as Uy}from"crypto";import{mkdtempSync as Hy,rmSync as au,readFileSync as qy,copyFileSync as Gy,chmodSync as Wy,renameSync as jy,existsSync as cu}from"fs";import{execFileSync as fn}from"child_process";import{tmpdir as Jy,platform as Yy}from"os";import{join as es}from"path";function Xy(){return process.arch==="arm64"?"darwin-arm64":"darwin-x64"}function Qy(n){return`https://github.com/${Vy}/${zy}/releases/download/v${n}/`}function lu(n,e){try{return fn("curl",["-fSL",n],{encoding:"utf-8",maxBuffer:16*1024*1024})}catch(t){throw new Error(`Failed to fetch ${e} from ${n}: ${t.message}`)}}function Zy(n,e){for(let t of n.split(`
|
|
552
|
+
`)){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 du(n){let{version:e,destPath:t}=n,r=n.onProgress??(()=>{}),s=Xy(),i=n._baseUrl??Qy(e),o=`mio-agent-${e}-${s}.tar.gz`,a=`mio-agent-${e}-${s}`,c=`mio-agent-${e}-manifest.json`;r("Verifying release manifest...");let d;try{d=JSON.parse(lu(i+c,"release manifest"))}catch(g){throw new Error(`Release manifest fetch/parse failed: ${g.message}`)}let l=new Set(d.required_fixes??[]),u=Ky.filter(g=>!l.has(g));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 f=Zy(lu(i+"SHASUMS256.txt","SHASUMS256.txt"),o);if(!f)throw new Error(`SHA-256 entry for '${o}' not found in SHASUMS256.txt`);let h=Hy(es(Jy(),"mio-agent-install-"));try{r(`Downloading mio-agent ${e}...`);let g=es(h,o);try{fn("curl",["-fSL",i+o,"-o",g])}catch(v){throw new Error(`Binary download failed: ${v.message}`)}r("Verifying checksum...");let m=Uy("sha256").update(qy(g)).digest("hex");if(m!==f)throw new Error(`Checksum mismatch \u2014 expected ${f.slice(0,12)}\u2026, got ${m.slice(0,12)}\u2026`);r("Extracting binary...");let y=es(h,"extract");fn("mkdir",["-p",y]),fn("tar",["-xzf",g,"-C",y]);let b=es(y,a);if(!cu(b))throw new Error(`mio-agent binary '${a}' not found inside the downloaded tarball`);r("Installing mio-agent...");let x=`${t}.staging`;cu(x)&&au(x,{force:!0}),Gy(b,x),Wy(x,493),Yy()==="darwin"&&!n._skipSign&&(fn("codesign",["--force","--sign","-",x]),fn("xattr",["-dr","com.apple.quarantine",x])),jy(x,t)}finally{au(h,{recursive:!0,force:!0})}}var Vy,zy,Ky,uu=A(()=>{"use strict";Vy="MioMioOS",zy="mio-agent",Ky=["machine-api-v1-prefix","socketio-control-path"]});var pu={};Ce(pu,{runInstall:()=>Fi});import{mkdirSync as fu,writeFileSync as e_}from"fs";import{execFileSync as t_}from"child_process";import{homedir as hu}from"os";import{join as ts}from"path";async function Fi(n){if(!n.background){console.log("Starting daemon in foreground (use --background --version <semver> for LaunchAgent)");let{runStart:i}=await Promise.resolve().then(()=>(Li(),Mi));await i({background:!1});return}n.version||(console.error("Error: --background requires --version <semver>"),process.exit(1));let e=Ue(),t=n.version;console.log(`Installing mio-agent ${t} as LaunchAgent...`),fu(ts(he,"bin"),{recursive:!0,mode:448}),du({version:t,destPath:Di,onProgress:i=>console.log(i)}),e.pinned_version=t,Xn(e),fu(gu,{recursive:!0});let r=hu(),s=`<?xml version="1.0" encoding="UTF-8"?>
|
|
546
553
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
547
554
|
<plist version="1.0">
|
|
548
555
|
<dict>
|
|
549
556
|
<key>Label</key>
|
|
550
|
-
<string>${
|
|
557
|
+
<string>${Bi}</string>
|
|
551
558
|
<key>ProgramArguments</key>
|
|
552
559
|
<array>
|
|
553
|
-
<string>${
|
|
560
|
+
<string>${Di}</string>
|
|
554
561
|
<string>run</string>
|
|
555
562
|
</array>
|
|
556
563
|
<key>RunAtLoad</key>
|
|
@@ -558,20 +565,20 @@ Output the persona.md now.`}function sy(n){let e=[];if(e.push("=== EXISTING pers
|
|
|
558
565
|
<key>KeepAlive</key>
|
|
559
566
|
<true/>
|
|
560
567
|
<key>ExitTimeOut</key>
|
|
561
|
-
<integer>${
|
|
568
|
+
<integer>${Wl}</integer>
|
|
562
569
|
<key>StandardOutPath</key>
|
|
563
570
|
<string>${r}/.mio/logs/mio-agent.log</string>
|
|
564
571
|
<key>StandardErrorPath</key>
|
|
565
572
|
<string>${r}/.mio/logs/mio-agent-error.log</string>
|
|
566
573
|
</dict>
|
|
567
|
-
</plist>`;
|
|
568
|
-
mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${
|
|
569
|
-
Run: mio-agent doctor \u2014 to verify health`)}var
|
|
570
|
-
To upgrade: mio-agent upgrade --version ${t}`)}async function
|
|
571
|
-
mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var
|
|
572
|
-
`);let n=
|
|
573
|
-
`))console.log(` ${c}`)}let o=
|
|
574
|
-
`))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>
|
|
574
|
+
</plist>`;e_($i,s,{encoding:"utf-8",mode:420}),t_("launchctl",["bootstrap",`gui/${process.getuid()}`,$i]),console.log(`
|
|
575
|
+
mio-agent ${t} installed as LaunchAgent.`),console.log(` Binary: ${Di}`),console.log(` Plist: ${$i}`),console.log(` Label: ${Bi}`),console.log(`
|
|
576
|
+
Run: mio-agent doctor \u2014 to verify health`)}var Bi,gu,$i,Di,Ui=A(()=>{"use strict";He();vi();uu();Bi="io.miomioos.mio-agent",gu=ts(hu(),"Library","LaunchAgents"),$i=ts(gu,`${Bi}.plist`),Di=ts(he,"bin","mio-agent")});var Hi={};Ce(Hi,{runUpgrade:()=>s_,runUpgradeCheck:()=>r_});import{execFileSync as n_}from"child_process";async function r_(){let e=Ue().pinned_version??"unknown (foreground/dev mode)",t=n_("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.":`
|
|
577
|
+
To upgrade: mio-agent upgrade --version ${t}`)}async function s_(n){let e=Ue();e.pinned_version=n.version,Xn(e),console.log(`Pinned version updated to ${n.version} in config.`),await Fi({background:!0,version:n.version})}var qi=A(()=>{"use strict";He();Ui()});var mu={};Ce(mu,{runStop:()=>a_});import{execFileSync as i_}from"child_process";async function a_(){try{i_("launchctl",["stop",o_]),console.log("Daemon stopped.")}catch{console.log("Daemon was not running or stop signal sent.")}}var o_,yu=A(()=>{"use strict";o_="io.miomioos.mio-agent"});var vu={};Ce(vu,{runUninstall:()=>f_});import{execFileSync as c_}from"child_process";import{rmSync as _u,existsSync as wu}from"fs";import{join as l_}from"path";import{homedir as d_}from"os";async function f_(){console.log("Uninstalling mio-agent...");try{c_("launchctl",["bootout",`gui/${process.getuid()}`,ns]),console.log(" LaunchAgent unregistered.")}catch{console.log(" LaunchAgent was not registered (skipped).")}wu(ns)&&(_u(ns),console.log(` Deleted: ${ns}`));try{so(),console.log(" Keychain entry deleted.")}catch{console.log(" No Keychain entry found (skipped).")}wu(he)&&(_u(he,{recursive:!0,force:!0}),console.log(` Deleted: ${he}`)),console.log(`
|
|
578
|
+
mio-agent uninstalled. To also remove the npm package:`),console.log(" npm uninstall -g @miomioos/mio-agent")}var u_,ns,bu=A(()=>{"use strict";Ft();He();u_="io.miomioos.mio-agent",ns=l_(d_(),"Library","LaunchAgents",`${u_}.plist`)});var Su={};Ce(Su,{runDoctor:()=>p_});import{execFileSync as h_,spawnSync as ku}from"child_process";import{existsSync as g_}from"fs";function ft(n,e,t){let r=e?"\u2705":"\u274C",s=t?`${r} ${n}: ${t}`:`${r} ${n}`;console.log(s)}async function p_(){console.log(`mio-agent doctor
|
|
579
|
+
`);let n=Uo();if(ft("Config (~/.mio/agent.json)",n,n?"found":"missing \u2014 run: mio-agent login"),!n)return;let e=Ue(),t=!1;try{h_("security",["find-generic-password","-s","io.miomioos.mio-agent","-a","machine_token"],{stdio:"ignore"}),t=!0}catch{}ft("Keychain (machine_token)",t,t?"found":"missing \u2014 run: mio-agent login");let r=!1;try{r=ku("curl",["-fsS","--max-time","3",`${e.server_url}/health`]).status===0}catch{}ft("Server connectivity",r,r?e.server_url:`unreachable: ${e.server_url}`);let s=!1;try{s=ku("curl",["-fsS","--max-time","1",`http://127.0.0.1:${Fo}/health`]).status===0}catch{}ft("Daemon (127.0.0.1:7878)",s,s?"running":"not running"),console.log(""),console.log("Runtimes:");let i=ln();if(i)ft(" claude",!0,i);else{ft(" claude",!1,"not found");for(let c of gd().split(`
|
|
580
|
+
`))console.log(` ${c}`)}let o=jr();if(o){let c=(process.env.MIO_CODEX_MODEL||"").trim();ft(" codex",!0,c?`${o} (model override: ${c})`:`${o} (model: local default)`)}else{ft(" codex",!1,"not found");for(let c of _d().split(`
|
|
581
|
+
`))console.log(` ${c}`)}let a=["/usr/local/bin/opencode","/opt/homebrew/bin/opencode"].find(c=>g_(c));ft(" opencode",!!a,a??"not found in PATH"),console.log("")}var Eu=A(()=>{"use strict";He();Gr();Ti()});var Tu={};Ce(Tu,{buildPairingDeeplink:()=>xu,runPairPhone:()=>__});function xu(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 m_(n){let e=new Date(n).getTime()-Date.now();return`${Math.max(0,Math.round(e/6e4))} min`}function y_(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 __(n){n||(console.error("Usage: mio-agent pair-phone <workroom_id>"),process.exit(1));let e=Ue(),t;try{t=ht()}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 ${y_(s.status)}`),process.exit(1);return}let i=await s.json(),o=xu(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 ${m_(i.expires_at)} (${i.expires_at})`),console.log(` Pairing: ${i.pairing_id}`),console.log("");let a=!1;try{let c=await Promise.resolve().then(()=>te(hs(),1)).catch(()=>null),d=c?.default??c;typeof d?.generate=="function"&&(d.generate(o,{small:!0},l=>console.log(l)),a=!0)}catch{}a||console.log(" Render this payload as a QR (MioIsland shows it on screen; or paste into any QR tool):"),console.log(` ${o}`),console.log(""),console.log(" The raw operator token is NOT in this code \u2014 the phone mints it securely on redeem."),console.log(" To cancel/regenerate, re-run pair-phone (old code stays valid until it expires unless canceled in MioIsland)."),console.log("")}var Cu=A(()=>{"use strict";He();Ft()});import{parseArgs as w_}from"util";import{fileURLToPath as v_}from"url";import{realpathSync as Ru}from"fs";function b_(n){return n[0]==="agentcli"}function k_(n){return n[0]==="login"}async function S_(){let n=process.argv.slice(2);if(n.length===1&&(n[0]==="--version"||n[0]==="-v")){let{getPackageVersion:i}=await Promise.resolve().then(()=>(Ji(),ji));console.log(i()),process.exit(0)}if(b_(n)){let{runAgentcliCommand:i}=await Promise.resolve().then(()=>(ro(),no));process.exit(await i())}if(k_(n)){let{runLogin:i}=await Promise.resolve().then(()=>(Mo(),No));process.exit(await i(process.argv.slice(3)))}if(n[0]==="logs"){let{runLogs:i}=await Promise.resolve().then(()=>(Do(),$o));process.exit(await i(process.argv.slice(3)))}let{values:e,positionals:t}=w_({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(()=>(Li(),Mi));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(()=>(Ui(),pu));await i({background:e.background??!1,version:e.version});break}case"upgrade":{if(e.check){let{runUpgradeCheck:i}=await Promise.resolve().then(()=>(qi(),Hi));await i()}else if(e.version){let{runUpgrade:i}=await Promise.resolve().then(()=>(qi(),Hi));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(()=>(Ni(),ou));await i();break}case"stop":{let{runStop:i}=await Promise.resolve().then(()=>(yu(),mu));await i();break}case"uninstall":{let{runUninstall:i}=await Promise.resolve().then(()=>(bu(),vu));await i();break}case"doctor":{let{runDoctor:i}=await Promise.resolve().then(()=>(Eu(),Su));await i();break}case"pair-phone":{let{runPairPhone:i}=await Promise.resolve().then(()=>(Cu(),Tu));await i(s[0]);break}default:console.log(`Mio Agent \u2014 background AI worker daemon
|
|
575
582
|
|
|
576
583
|
Global flags:
|
|
577
584
|
--version, -v Print version and exit
|
|
@@ -590,7 +597,7 @@ Commands:
|
|
|
590
597
|
logs [-n N] [-f] Tail daemon logs (~/.mio/logs/, or /tmp/mio-agent.log in dev mode)
|
|
591
598
|
agentcli <subcommand> Agent-facing CLI (message check/send/read); use --help for details
|
|
592
599
|
run Internal: launched by launchd (do not call directly)
|
|
593
|
-
`),process.exit(r?1:0)}}function
|
|
600
|
+
`),process.exit(r?1:0)}}function E_(){try{let n=Q("node:sea");return typeof n.isSea=="function"&&n.isSea()}catch{return!1}}function x_(){if(E_())return!0;let n=process.argv[1];if(!n)return!1;try{return Ru(v_(import.meta.url))===Ru(n)}catch{return!1}}x_()&&S_().catch(n=>{console.error("Fatal:",n.message),process.exit(1)});export{b_ as isAgentcliInvocation,k_ as isLoginInvocation};
|
|
594
601
|
/*! Bundled license information:
|
|
595
602
|
|
|
596
603
|
xmlhttprequest-ssl/lib/XMLHttpRequest.js:
|