agentschat-mcp 0.36.24 → 0.36.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +8 -0
  3. package/codex/README.md +1 -1
  4. package/codex/app-server.ts +79 -22
  5. package/codex/bots-config.ts +31 -11
  6. package/codex/bridge.ts +123 -25
  7. package/codex/config.ts +128 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +65 -12
  10. package/codex/loop-grants.ts +41 -11
  11. package/codex/manager.ts +101 -25
  12. package/codex/owner.ts +81 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +41 -11
  16. package/codex/thread-history.ts +77 -30
  17. package/codex/transport.ts +122 -19
  18. package/connector/auth.ts +57 -5
  19. package/connector/backfill.ts +92 -10
  20. package/connector/descriptor.ts +27 -1
  21. package/connector/identities.ts +82 -14
  22. package/connector/ingest.ts +11 -2
  23. package/connector/normalize.ts +32 -12
  24. package/connector/run.ts +314 -67
  25. package/connector/server.ts +95 -26
  26. package/dist/codex-bots.js +410 -73
  27. package/dist/codex-bridge.js +1996 -576
  28. package/dist/connector.js +1286 -493
  29. package/dist/dsh.js +1776 -299
  30. package/dist/muse.js +967 -221
  31. package/dist/server.js +7645 -1172
  32. package/dsh/client.js +7 -5
  33. package/dsh/identity-ui/client.js +7 -5
  34. package/dsh/identity-ui/index.js +43 -8
  35. package/dsh/inbound-bridge/index.js +595 -146
  36. package/dsh/src/cli.ts +430 -91
  37. package/dsh/src/patch.ts +295 -15
  38. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  39. package/dsh/tests/dsh.test.ts +990 -3
  40. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  41. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  42. package/muse/src/bridge.ts +54 -13
  43. package/muse/src/cli.ts +226 -41
  44. package/muse/src/client.ts +249 -34
  45. package/muse/src/config.ts +128 -12
  46. package/muse/src/policy.ts +28 -8
  47. package/muse/src/types.ts +1 -0
  48. package/muse/src/typing.ts +18 -1
  49. package/muse/src/wake.ts +237 -35
  50. package/muse/tests/bridge.test.mjs +131 -0
  51. package/muse/tests/client.test.mjs +327 -0
  52. package/muse/tests/config.test.mjs +78 -1
  53. package/muse/tests/hardening.test.mjs +199 -0
  54. package/muse/tests/hardening126.test.mjs +292 -0
  55. package/muse/tests/policy.test.mjs +83 -1
  56. package/muse/tests/wake.test.mjs +134 -6
  57. package/package.json +3 -3
  58. package/scripts/ensure-grok-wakes.mjs +93 -8
  59. package/scripts/example-url-wake-receiver.mjs +254 -61
  60. package/scripts/grok-bind-register.sh +38 -8
  61. package/skills/agentschat-team-lead/SKILL.md +1 -1
  62. package/skills/onboarding.md +14 -10
  63. package/src/argcheck.ts +1890 -1
  64. package/src/cli.mjs +98 -14
  65. package/src/dedup.ts +57 -8
  66. package/src/grok-bind.ts +160 -33
  67. package/src/heartbeat.ts +39 -11
  68. package/src/identity-guard.ts +93 -20
  69. package/src/identity.ts +67 -11
  70. package/src/mentions.ts +26 -5
  71. package/src/onboarding-status.ts +134 -11
  72. package/src/profile-selection.ts +269 -18
  73. package/src/profile-store.ts +222 -28
  74. package/src/read-cursor.ts +256 -9
  75. package/src/reconnect.ts +98 -2
  76. package/src/redact.ts +34 -15
  77. package/src/rest-cli.ts +713 -159
  78. package/src/server.ts +2487 -342
  79. package/src/session-bind.ts +731 -132
  80. package/src/session-route.ts +183 -12
  81. package/src/team-lead-skill.ts +3 -0
  82. package/src/timestamps.ts +56 -23
  83. package/src/tool-annotations.ts +22 -1
  84. package/src/wake.ts +524 -90
package/dist/muse.js CHANGED
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // muse/src/cli.ts
4
- import { writeFileSync, mkdirSync } from "node:fs";
5
- import { dirname } from "node:path";
4
+ import { randomBytes as randomBytes2 } from "node:crypto";
5
+ import { chmodSync as chmodSync2, copyFileSync as copyFileSync2, writeFileSync as writeFileSync2, mkdirSync as mkdirSync2, renameSync as renameSync2, unlinkSync as unlinkSync2, lstatSync as lstatSync3 } from "node:fs";
6
+ import { dirname as dirname3 } from "node:path";
6
7
  import { homedir as homedir2 } from "node:os";
7
8
  import { join as join2 } from "node:path";
8
9
 
@@ -11,23 +12,37 @@ var MAX_HISTORY_MESSAGES = 50;
11
12
  var MAX_CONTEXT_BYTES = 15000;
12
13
  var MAX_MESSAGE_BYTES = 2000;
13
14
  function isMentioned(content, agentId, displayName) {
15
+ if (typeof content !== "string")
16
+ return false;
14
17
  const haystack = content.toLowerCase();
15
- const names = [`@${agentId.toLowerCase()}`];
16
- if (displayName)
17
- names.push(`@${displayName.toLowerCase()}`);
18
- names.push("@muse");
19
- return names.some((name) => haystack.includes(name));
18
+ const names = [agentId, displayName, "muse"].filter((name) => typeof name === "string" && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(name) && name.trim().length > 0).map((name) => `@${name.trim().toLowerCase()}`);
19
+ return names.some((name) => {
20
+ let index = haystack.indexOf(name);
21
+ while (index !== -1) {
22
+ const before = haystack[index - 1];
23
+ const afterCodePoint = haystack.codePointAt(index + name.length);
24
+ const after = afterCodePoint === undefined ? "" : String.fromCodePoint(afterCodePoint);
25
+ if ((!before || !/[a-z0-9@]/i.test(before)) && (!after || !/[\p{L}\p{N}\p{M}_-]/u.test(after)))
26
+ return true;
27
+ index = haystack.indexOf(name, index + 1);
28
+ }
29
+ return false;
30
+ });
20
31
  }
21
32
  function shouldDispatch(message, opts) {
33
+ if (!message || typeof message !== "object" || typeof message.content !== "string")
34
+ return false;
22
35
  if (message.sender_id === opts.agentId)
23
36
  return false;
24
37
  if (opts.channelKind === "direct")
25
38
  return true;
26
- if (!opts.channelKind)
27
- return isMentioned(message.content, opts.agentId, opts.displayName);
39
+ if (!opts.channelKind && typeof message.channel_id === "string" && /^dm[-:]/i.test(message.channel_id))
40
+ return true;
28
41
  return isMentioned(message.content, opts.agentId, opts.displayName);
29
42
  }
30
43
  function truncateToBytes(text, maxBytes) {
44
+ if (typeof text !== "string" || maxBytes <= 0)
45
+ return "";
31
46
  const encoder = new TextEncoder;
32
47
  if (encoder.encode(text).length <= maxBytes)
33
48
  return text;
@@ -40,6 +55,8 @@ function truncateToBytes(text, maxBytes) {
40
55
  else
41
56
  high = mid - 1;
42
57
  }
58
+ if (low > 0 && low < text.length && text.charCodeAt(low - 1) >= 55296 && text.charCodeAt(low - 1) <= 56319 && text.charCodeAt(low) >= 56320 && text.charCodeAt(low) <= 57343)
59
+ low -= 1;
43
60
  return text.slice(0, low);
44
61
  }
45
62
  function buildContext(messages, agentId) {
@@ -47,20 +64,23 @@ function buildContext(messages, agentId) {
47
64
  const lines = [];
48
65
  let bytes = 0;
49
66
  for (const m of [...recent].reverse()) {
50
- const line = `${m.sender_id}: ${truncateToBytes(m.content, MAX_MESSAGE_BYTES)}
67
+ const sender = typeof m.sender_id === "string" ? m.sender_id.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ").slice(0, 128) : "unknown";
68
+ const line = `${sender}: ${truncateToBytes(m.content, MAX_MESSAGE_BYTES)}
51
69
  `;
52
70
  const lineBytes = new TextEncoder().encode(line).length;
53
71
  if (bytes + lineBytes > MAX_CONTEXT_BYTES)
54
72
  break;
55
73
  bytes += lineBytes;
56
- lines.unshift(line);
74
+ lines.push(line);
57
75
  }
58
- return lines.join("");
76
+ return lines.reverse().join("");
59
77
  }
60
78
 
61
79
  // muse/src/typing.ts
62
80
  var TYPING_HEARTBEAT_MS = 2000;
63
81
  var TYPING_HEARTBEAT_MAX_MS = 120000;
82
+ var MAX_TYPING_CHANNELS = 256;
83
+ var FORBIDDEN_TYPING_KEYS = new Set(["__proto__", "constructor", "prototype"]);
64
84
 
65
85
  class TypingHeartbeat {
66
86
  timers = new Map;
@@ -74,12 +94,20 @@ class TypingHeartbeat {
74
94
  } catch {}
75
95
  }
76
96
  start(channelId) {
77
- if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0")
97
+ if (typeof channelId !== "string" || !channelId || channelId.length > 128 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channelId) || FORBIDDEN_TYPING_KEYS.has(channelId.toLowerCase()) || process.env.AGENTSCHAT_AUTO_TYPING === "0") {
78
98
  return;
99
+ }
79
100
  this.stop(channelId);
101
+ if (this.timers.size >= MAX_TYPING_CHANNELS) {
102
+ const oldest = this.timers.keys().next().value;
103
+ if (oldest !== undefined)
104
+ this.stop(oldest);
105
+ }
80
106
  this.pulse(channelId);
81
107
  const interval = setInterval(() => this.pulse(channelId), TYPING_HEARTBEAT_MS);
108
+ interval.unref?.();
82
109
  const cap = setTimeout(() => this.stop(channelId), TYPING_HEARTBEAT_MAX_MS);
110
+ cap.unref?.();
83
111
  this.timers.set(channelId, { interval, cap });
84
112
  }
85
113
  stop(channelId) {
@@ -97,15 +125,19 @@ class TypingHeartbeat {
97
125
  }
98
126
 
99
127
  // muse/src/bridge.ts
128
+ var FORBIDDEN_BRIDGE_CHANNELS = new Set(["__proto__", "constructor", "prototype"]);
129
+ var BRIDGE_CHANNEL_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
130
+
100
131
  class MuseBridge {
101
132
  client;
133
+ activeReplies = new Map;
102
134
  history = new Map;
103
135
  opts;
104
136
  typing = new TypingHeartbeat((channelId) => this.client.sendTyping(channelId));
105
137
  constructor(client, opts) {
106
138
  this.client = client;
107
139
  this.opts = opts;
108
- this.client.onMessage((m) => void this.handleMessage(m));
140
+ this.client.onMessage((m) => this.handleMessage(m));
109
141
  }
110
142
  async start() {
111
143
  await this.client.connect();
@@ -117,41 +149,529 @@ class MuseBridge {
117
149
  this.client.joinChannel(channelId);
118
150
  }
119
151
  stop() {
152
+ this.typing.stopAll();
153
+ this.activeReplies.clear();
120
154
  this.client.disconnect();
121
155
  }
122
156
  get isConnected() {
123
157
  return this.client.isConnected;
124
158
  }
125
159
  async handleMessage(message) {
160
+ if (!message || typeof message.channel_id !== "string" || !message.channel_id || message.channel_id.length > 256 || FORBIDDEN_BRIDGE_CHANNELS.has(message.channel_id.toLowerCase()) || Object.getOwnPropertyNames(Object.prototype).some((k) => k.toLowerCase() === message.channel_id.toLowerCase()) || message.content === "__typing__") {
161
+ return;
162
+ }
163
+ if (!this.history.has(message.channel_id) && this.history.size >= 200) {
164
+ const oldest = this.history.keys().next().value;
165
+ if (oldest !== undefined)
166
+ this.history.delete(oldest);
167
+ }
126
168
  const list = this.history.get(message.channel_id) ?? [];
127
169
  list.push(message);
128
170
  this.history.set(message.channel_id, list.slice(-50));
129
- const kind = this.opts.channelKinds?.[message.channel_id];
171
+ const kinds = this.opts.channelKinds;
172
+ const kind = kinds && Object.prototype.hasOwnProperty.call(kinds, message.channel_id) ? kinds[message.channel_id] : undefined;
130
173
  if (!shouldDispatch(message, { agentId: this.opts.agentId, displayName: this.opts.displayName, channelKind: kind })) {
131
174
  return;
132
175
  }
133
- this.typing.start(message.channel_id);
134
- const ctx = {
135
- message,
136
- channelKind: kind,
137
- history: [...this.history.get(message.channel_id) ?? []],
138
- context: buildContext(this.history.get(message.channel_id) ?? [], this.opts.agentId)
139
- };
140
- const reply = await this.opts.responder(ctx);
141
- if (reply)
142
- this.client.sendMessage(message.channel_id, reply);
143
- this.typing.stop(message.channel_id);
176
+ const active = this.activeReplies.get(message.channel_id) ?? 0;
177
+ this.activeReplies.set(message.channel_id, active + 1);
178
+ if (active === 0)
179
+ this.typing.start(message.channel_id);
180
+ try {
181
+ const ctx = {
182
+ message,
183
+ channelKind: kind,
184
+ history: [...this.history.get(message.channel_id) ?? []],
185
+ context: buildContext(this.history.get(message.channel_id) ?? [], this.opts.agentId)
186
+ };
187
+ const reply = await this.opts.responder(ctx);
188
+ if (reply && !BRIDGE_CHANNEL_CTRL_RE.test(message.channel_id)) {
189
+ if (message.thread_id && !BRIDGE_CHANNEL_CTRL_RE.test(message.thread_id)) {
190
+ this.client.sendMessage(message.channel_id, reply, "text", message.thread_id);
191
+ } else {
192
+ this.client.sendMessage(message.channel_id, reply);
193
+ }
194
+ }
195
+ } finally {
196
+ const remaining = (this.activeReplies.get(message.channel_id) ?? 1) - 1;
197
+ if (remaining <= 0) {
198
+ this.activeReplies.delete(message.channel_id);
199
+ this.typing.stop(message.channel_id);
200
+ } else {
201
+ this.activeReplies.set(message.channel_id, remaining);
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ // muse/src/config.ts
208
+ import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs";
209
+ import { homedir } from "node:os";
210
+ import { dirname, isAbsolute, join, sep } from "node:path";
211
+ var DEFAULT_WS_URL = "wss://agents-chat.com/ws";
212
+ var DEFAULT_REST_URL = "https://agents-chat.com";
213
+ var PROFILE_PATH = join(homedir(), ".agentschat", "muse.json");
214
+ var MAX_PROFILE_BYTES = 64 * 1024;
215
+ function isLoopbackHost(hostname) {
216
+ const h = hostname.toLowerCase();
217
+ return h === "localhost" || h === "127.0.0.1" || h === "[::1]" || h === "::1";
218
+ }
219
+ function isUnsafeEndpointHost(hostname) {
220
+ let host = hostname.toLowerCase().replace(/\.+$/, "");
221
+ if (["metadata.google.internal", "metadata.goog", "metadata", "instance-data"].includes(host) || host.endsWith(".metadata.google.internal") || host.endsWith(".metadata.goog"))
222
+ return true;
223
+ const unsafeV4 = (ip) => ip.startsWith("0.") || ip === "100.100.100.200" || ip.startsWith("169.254.");
224
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host))
225
+ return unsafeV4(host);
226
+ if (!host.startsWith("["))
227
+ return false;
228
+ try {
229
+ host = new URL(`http://${host}`).hostname.toLowerCase();
230
+ } catch {
231
+ return true;
232
+ }
233
+ const address = host.slice(1, -1);
234
+ const [left, right = ""] = address.split("::");
235
+ const head = left ? left.split(":") : [];
236
+ const tail = right ? right.split(":") : [];
237
+ const words = (address.includes("::") ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail] : head).map((x) => parseInt(x, 16));
238
+ if (words.length !== 8)
239
+ return true;
240
+ const mapped = words.slice(0, 5).every((x) => x === 0) && words[5] === 65535 || words.slice(0, 4).every((x) => x === 0) && words[4] === 65535 && words[5] === 0;
241
+ if (mapped)
242
+ return unsafeV4(`${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`);
243
+ return words.every((x) => x === 0) || (words[0] & 65472) === 65152 || words[0] === 64768 && words[1] === 3778 && words.slice(2, 7).every((x) => x === 0) && words[7] === 596;
244
+ }
245
+ function isSafeAgentId(value) {
246
+ return typeof value === "string" && value.length > 0 && value.length <= 128 && ![".", "..", "__proto__", "constructor", "prototype"].includes(value.toLowerCase()) && !/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value);
247
+ }
248
+ function assertSafeParentDirectories(file) {
249
+ if (!file || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(file)) {
250
+ throw new Error("Refusing to write Muse file inside symlinked or non-directory parent");
251
+ }
252
+ const parent = dirname(isAbsolute(file) ? file : `${process.cwd()}${sep}${file}`);
253
+ const parts = parent.split(sep);
254
+ for (let i = 1;i <= parts.length; i++) {
255
+ const dir = parts.slice(0, i).join(sep) || sep;
256
+ try {
257
+ const st = lstatSync(dir);
258
+ const systemLink = process.platform === "darwin" && ["/var", "/tmp", "/etc"].includes(dir) && st.isSymbolicLink() && realpathSync(dir) === `/private${dir}` && !lstatSync("/private").isSymbolicLink() && lstatSync("/private").isDirectory() && !lstatSync(`/private${dir}`).isSymbolicLink() && lstatSync(`/private${dir}`).isDirectory();
259
+ if (!systemLink && st.isSymbolicLink() || !st.isDirectory() && !systemLink) {
260
+ throw new Error("Refusing to write Muse file inside symlinked or non-directory parent");
261
+ }
262
+ } catch (err) {
263
+ if (err?.code !== "ENOENT")
264
+ throw err;
265
+ }
266
+ }
267
+ }
268
+ function validateEndpointUrl(raw, kind) {
269
+ if (raw !== raw.trim() || /["<>\\\x00-\x20\x7f-\x9f\u2028\u2029]/.test(raw)) {
270
+ throw new Error(`Invalid Muse ${kind} URL`);
271
+ }
272
+ const trimmed = raw;
273
+ let parsed;
274
+ try {
275
+ parsed = new URL(trimmed);
276
+ } catch {
277
+ throw new Error(`Invalid Muse ${kind} URL`);
278
+ }
279
+ if (isUnsafeEndpointHost(parsed.hostname)) {
280
+ throw new Error(`Unsafe Muse ${kind} URL host`);
281
+ }
282
+ if (parsed.port === "0" || parsed.search || parsed.hash || raw.includes("?") || raw.includes("#")) {
283
+ throw new Error(`Invalid Muse ${kind} URL port/query/hash`);
284
+ }
285
+ if (parsed.username || parsed.password) {
286
+ throw new Error(`Embedded credentials are not allowed in Muse ${kind} URL`);
287
+ }
288
+ if (kind === "ws") {
289
+ if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") {
290
+ throw new Error(`Invalid Muse ws URL protocol: ${parsed.protocol}`);
291
+ }
292
+ if (parsed.protocol === "ws:" && !isLoopbackHost(parsed.hostname)) {
293
+ throw new Error("Remote Muse ws URL must use wss://");
294
+ }
295
+ } else {
296
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
297
+ throw new Error(`Invalid Muse rest URL protocol: ${parsed.protocol}`);
298
+ }
299
+ if (parsed.protocol === "http:" && !isLoopbackHost(parsed.hostname)) {
300
+ throw new Error("Remote Muse rest URL must use https://");
301
+ }
302
+ }
303
+ return trimmed;
304
+ }
305
+ function redact(value) {
306
+ if (!value)
307
+ return "(missing)";
308
+ if (value.length <= 4)
309
+ return "****";
310
+ return `${value.slice(0, 2)}****${value.slice(-2)}`;
311
+ }
312
+ function safeConfig(config) {
313
+ return {
314
+ agentId: config.agentId,
315
+ wsUrl: config.wsUrl,
316
+ restUrl: config.restUrl,
317
+ displayName: config.displayName,
318
+ defaultChannelId: config.defaultChannelId,
319
+ token: redact(config.token)
320
+ };
321
+ }
322
+ function readProfile(path = PROFILE_PATH) {
323
+ try {
324
+ assertSafeParentDirectories(path);
325
+ if (!existsSync(path))
326
+ return {};
327
+ const st = lstatSync(path);
328
+ if (!st.isFile() || st.isSymbolicLink() || st.size > MAX_PROFILE_BYTES)
329
+ return {};
330
+ const parsed = JSON.parse(readFileSync(path, "utf8"));
331
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) && !Object.hasOwn(parsed, "__proto__") ? parsed : {};
332
+ } catch {
333
+ return {};
334
+ }
335
+ }
336
+ function loadConfig(env = process.env, profilePath) {
337
+ const profile = readProfile(profilePath);
338
+ const rawAgentId = (env.AGENTCHAT_AGENT_ID ?? profile.agentId ?? "").trim();
339
+ const rawToken = (env.AGENTCHAT_TOKEN ?? profile.token ?? "").trim();
340
+ if (!isSafeAgentId(rawAgentId) || !rawToken || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(rawAgentId) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(rawToken)) {
341
+ throw new Error("Missing AgentsChat identity: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " + `or create ${profilePath ?? PROFILE_PATH} via 'muse-agentchat --register-only --name <name>'. ` + "Tokens are never printed; see README for registration.");
342
+ }
343
+ const wsUrl = validateEndpointUrl(env.AGENTCHAT_WS_URL ?? profile.wsUrl ?? DEFAULT_WS_URL, "ws");
344
+ const restUrl = validateEndpointUrl(env.AGENTCHAT_REST_URL ?? profile.restUrl ?? DEFAULT_REST_URL, "rest");
345
+ const rawDisplay = (env.AGENTCHAT_DISPLAY_NAME ?? profile.displayName)?.trim();
346
+ const rawChannel = (env.AGENTCHAT_CHANNEL_ID ?? profile.defaultChannelId)?.trim();
347
+ return {
348
+ agentId: rawAgentId,
349
+ token: rawToken,
350
+ wsUrl,
351
+ restUrl,
352
+ displayName: rawDisplay || undefined,
353
+ defaultChannelId: rawChannel || undefined
354
+ };
355
+ }
356
+
357
+ // muse/src/wake.ts
358
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
359
+ import { appendFileSync, chmodSync, copyFileSync, lstatSync as lstatSync2, mkdirSync, readFileSync as readFileSync2, renameSync, unlinkSync, writeFileSync } from "node:fs";
360
+ import { dirname as dirname2 } from "node:path";
361
+ var WAKE_SIG_HEADER = "x-agentschat-signature";
362
+ var WAKE_CONTENT_MAX = 500;
363
+ function redactSecrets(text) {
364
+ return text.replace(/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|$)/g, "[redacted]").replace(/\b(https?:\/\/)([^/\s@]*@)/gi, "$1[redacted]@").replace(/\b(?:Bearer|Basic)\s+[^\s"'<>\\]+/gi, "[redacted]").replace(/(?:ac_|agent_key_|mcp_(?:at|rt|code)_|sk-|sk_|rk_(?:live|test)_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|mr_|whsec_|AIza)[A-Za-z0-9_-]+/g, "[redacted]").replace(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, "[redacted]").replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted]");
365
+ }
366
+ function sanitizeMuseText(text) {
367
+ return redactSecrets(redactSecrets(text).replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, ""));
368
+ }
369
+ function buildWakePayload(msg, opts = {}) {
370
+ const clean = (value, cap = 128) => typeof value === "string" ? sanitizeMuseText(value).slice(0, cap) : undefined;
371
+ const targetSessionId = clean(opts.targetSessionId);
372
+ return {
373
+ type: clean(msg.type, 64) ?? "message",
374
+ channel_id: clean(msg.channel_id),
375
+ message_id: clean(msg.id, 256),
376
+ sender_id: clean(msg.sender_id),
377
+ content: clean(msg.content, WAKE_CONTENT_MAX),
378
+ mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string").slice(0, 256).map((x) => clean(x)) : undefined,
379
+ timestamp: clean(msg.timestamp, 64),
380
+ ...targetSessionId ? { target_session_id: targetSessionId } : {}
381
+ };
382
+ }
383
+ function sanitizeWakeLogUrl(rawUrl) {
384
+ try {
385
+ const parsed = new URL(rawUrl);
386
+ parsed.username = "";
387
+ parsed.password = "";
388
+ parsed.search = "";
389
+ parsed.hash = "";
390
+ return parsed.toString();
391
+ } catch {
392
+ return redactSecrets(rawUrl.split(/[?#]/)[0] ?? "[invalid-url]");
393
+ }
394
+ }
395
+ function signWakeBody(body, secret) {
396
+ return createHmac("sha256", secret).update(body, "utf8").digest("hex");
397
+ }
398
+ function isUnsafeWakeHost(hostname) {
399
+ if (isUnsafeEndpointHost(hostname))
400
+ return true;
401
+ const host = hostname.toLowerCase().replace(/\.$/, "");
402
+ if (["metadata.google.internal", "metadata.goog"].includes(host))
403
+ return true;
404
+ const unsafeV4 = (ip) => {
405
+ const [a, b] = ip.split(".").map(Number);
406
+ return a === 0 || a === 10 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
407
+ };
408
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host))
409
+ return unsafeV4(host);
410
+ if (host.startsWith("[")) {
411
+ const address = host.slice(1, -1);
412
+ const [left, right = ""] = address.split("::");
413
+ const head = left ? left.split(":") : [];
414
+ const tail = right ? right.split(":") : [];
415
+ const words = address.includes("::") ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail].map((x) => parseInt(x, 16)) : head.map((x) => parseInt(x, 16));
416
+ if (words.length !== 8)
417
+ return true;
418
+ const mapped = words.slice(0, 5).every((x) => x === 0) && words[5] === 65535 || words.slice(0, 4).every((x) => x === 0) && words[4] === 65535 && words[5] === 0;
419
+ if (mapped)
420
+ return unsafeV4(`${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`);
421
+ return words.every((x) => x === 0) || (words[0] & 65472) === 65152 || (words[0] & 65024) === 64512 || (words[0] & 65280) === 65280;
422
+ }
423
+ return false;
424
+ }
425
+ async function fireWake(msg, cfg) {
426
+ const log = (text) => cfg.logger?.(sanitizeMuseText(text));
427
+ const url = (cfg.url ?? "").trim();
428
+ if (!url)
429
+ return;
430
+ const safeLogUrl = sanitizeWakeLogUrl(url);
431
+ let parsedUrl;
432
+ try {
433
+ parsedUrl = new URL(url);
434
+ } catch {
435
+ log(`[muse-agentchat] wake POST rejected invalid URL: ${safeLogUrl}`);
436
+ return;
437
+ }
438
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
439
+ log(`[muse-agentchat] wake POST rejected unsupported protocol: ${parsedUrl.protocol}`);
440
+ return;
441
+ }
442
+ if (parsedUrl.port === "0" || parsedUrl.username || parsedUrl.password || isUnsafeWakeHost(parsedUrl.hostname)) {
443
+ log(`[muse-agentchat] wake POST rejected unsafe URL: ${safeLogUrl}`);
444
+ return;
445
+ }
446
+ const timeoutMs = typeof cfg.timeoutMs === "number" && Number.isFinite(cfg.timeoutMs) && cfg.timeoutMs >= 1 ? Math.min(cfg.timeoutMs, 60000) : 5000;
447
+ const payload = buildWakePayload(msg, { targetSessionId: cfg.targetSessionId });
448
+ if (!payload.timestamp)
449
+ payload.timestamp = new Date().toISOString();
450
+ const body = JSON.stringify(payload);
451
+ const headers = { "Content-Type": "application/json" };
452
+ if (cfg.secret)
453
+ headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
454
+ const doPost = async () => {
455
+ const f = cfg.fetchImpl ?? fetch;
456
+ const ctrl = new AbortController;
457
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
458
+ t.unref?.();
459
+ try {
460
+ const res = await f(url, { method: "POST", headers, body, redirect: "error", signal: ctrl.signal });
461
+ try {
462
+ await res?.body?.cancel?.();
463
+ } catch {}
464
+ if (!res.ok)
465
+ log(`[muse-agentchat] wake POST ${safeLogUrl} → HTTP ${res.status}`);
466
+ } finally {
467
+ clearTimeout(t);
468
+ }
469
+ };
470
+ try {
471
+ await doPost();
472
+ } catch (e) {
473
+ try {
474
+ await doPost();
475
+ } catch (e2) {
476
+ log(`[muse-agentchat] wake POST ${safeLogUrl} failed: ${redactSecrets(String(e2))}`);
477
+ }
478
+ }
479
+ }
480
+ var MAX_WAKE_QUEUE_LINES = 500;
481
+ var MAX_WAKE_QUEUE_BYTES = 16 * 1024 * 1024;
482
+ var wakeTmpSeq = 0;
483
+ function atomicReplaceWakeFile(tmp, queueFile, fsOps) {
484
+ const renameFn = fsOps?.renameSync ?? renameSync;
485
+ const copyFn = fsOps?.copyFileSync ?? copyFileSync;
486
+ const unlinkFn = fsOps?.unlinkSync ?? unlinkSync;
487
+ assertSafeParentDirectories(queueFile);
488
+ try {
489
+ const st = lstatSync2(queueFile);
490
+ if (st.isSymbolicLink() || !st.isFile()) {
491
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
492
+ }
493
+ } catch (err) {
494
+ if (err?.code !== "ENOENT")
495
+ throw err;
496
+ }
497
+ try {
498
+ renameFn(tmp, queueFile);
499
+ } catch (renameErr) {
500
+ const code = renameErr?.code;
501
+ if (code === "EPERM" || code === "EACCES") {
502
+ assertSafeParentDirectories(queueFile);
503
+ try {
504
+ const st = lstatSync2(queueFile);
505
+ if (st.isSymbolicLink() || !st.isFile()) {
506
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
507
+ }
508
+ } catch (err) {
509
+ if (err?.code !== "ENOENT")
510
+ throw err;
511
+ }
512
+ copyFn(tmp, queueFile);
513
+ if (process.platform !== "win32") {
514
+ try {
515
+ chmodSync(queueFile, 384);
516
+ } catch {}
517
+ }
518
+ try {
519
+ unlinkFn(tmp);
520
+ } catch {}
521
+ return;
522
+ }
523
+ throw renameErr;
524
+ }
525
+ }
526
+ function appendWakeQueue(queueFile, payload, maxLines = MAX_WAKE_QUEUE_LINES, fsOps) {
527
+ const dir = dirname2(queueFile);
528
+ assertSafeParentDirectories(queueFile);
529
+ mkdirSync(dir, { recursive: true, mode: 448 });
530
+ assertSafeParentDirectories(queueFile);
531
+ const line = JSON.stringify(payload);
532
+ let existingLines = [];
533
+ let existedBefore = false;
534
+ try {
535
+ const st = lstatSync2(queueFile);
536
+ if (st.isSymbolicLink() || !st.isFile()) {
537
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
538
+ }
539
+ if (st.size > MAX_WAKE_QUEUE_BYTES) {
540
+ throw new Error("Muse wake queue exceeds maximum size limit");
541
+ }
542
+ existedBefore = true;
543
+ } catch (err) {
544
+ if (err?.code !== "ENOENT")
545
+ throw err;
546
+ }
547
+ if (existedBefore) {
548
+ const existing = readFileSync2(queueFile, "utf8");
549
+ existingLines = existing.split(`
550
+ `).filter((l) => l.length > 0);
551
+ if (payload.message_id && existingLines.some((l) => {
552
+ try {
553
+ return JSON.parse(l).message_id === payload.message_id;
554
+ } catch {
555
+ return false;
556
+ }
557
+ })) {
558
+ return false;
559
+ }
560
+ }
561
+ const cap = Number.isFinite(maxLines) ? Math.max(1, Math.floor(maxLines)) : MAX_WAKE_QUEUE_LINES;
562
+ if (existingLines.length >= cap) {
563
+ const kept = [...cap === 1 ? [] : existingLines.slice(-(cap - 1)), line];
564
+ const tmp = `${queueFile}.${process.pid}.${Date.now()}.${++wakeTmpSeq}.${randomBytes(6).toString("hex")}.tmp`;
565
+ try {
566
+ assertSafeParentDirectories(queueFile);
567
+ writeFileSync(tmp, `${kept.join(`
568
+ `)}
569
+ `, { mode: 384, flag: "wx" });
570
+ atomicReplaceWakeFile(tmp, queueFile, fsOps);
571
+ } catch (err) {
572
+ try {
573
+ unlinkSync(tmp);
574
+ } catch {}
575
+ throw err;
576
+ }
577
+ return true;
578
+ }
579
+ if (!existedBefore) {
580
+ try {
581
+ writeFileSync(queueFile, `${line}
582
+ `, { mode: 384, flag: "wx" });
583
+ if (process.platform !== "win32") {
584
+ try {
585
+ chmodSync(queueFile, 384);
586
+ } catch {}
587
+ }
588
+ return true;
589
+ } catch (err) {
590
+ if (err?.code !== "EEXIST")
591
+ throw err;
592
+ const st = lstatSync2(queueFile);
593
+ if (st.isSymbolicLink() || !st.isFile()) {
594
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
595
+ }
596
+ if (st.size > MAX_WAKE_QUEUE_BYTES) {
597
+ throw new Error("Muse wake queue exceeds maximum size limit");
598
+ }
599
+ }
600
+ }
601
+ assertSafeParentDirectories(queueFile);
602
+ const finalTarget = lstatSync2(queueFile);
603
+ if (finalTarget.isSymbolicLink() || !finalTarget.isFile()) {
604
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
144
605
  }
606
+ appendFileSync(queueFile, `${line}
607
+ `, { mode: 384 });
608
+ return true;
609
+ }
610
+
611
+ // src/reconnect.ts
612
+ function safeUnitRand(rand) {
613
+ let r;
614
+ try {
615
+ r = rand();
616
+ } catch {
617
+ return 0;
618
+ }
619
+ if (!Number.isFinite(r) || r <= 0)
620
+ return 0;
621
+ return r >= 1 ? 0.999999 : r;
622
+ }
623
+ function computePleaseReconnectDelay(jitterMs, rand = Math.random) {
624
+ const maxJitter = typeof jitterMs === "number" && Number.isFinite(jitterMs) && jitterMs > 0 ? Math.min(Math.floor(jitterMs), 1e4) : 2000;
625
+ return 200 + Math.floor(safeUnitRand(rand) * maxJitter);
626
+ }
627
+ function resolveDrainReconnectDelay(frame, rand = Math.random) {
628
+ const safeFrame = frame && typeof frame === "object" && !Array.isArray(frame) && !Object.prototype.hasOwnProperty.call(frame, "__proto__") ? frame : null;
629
+ return computePleaseReconnectDelay(safeFrame?.jitter_ms ?? safeFrame?.within_ms, rand);
145
630
  }
146
631
 
147
632
  // muse/src/client.ts
633
+ var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
634
+ var MAX_JOINED_CHANNELS = 256;
635
+ var MAX_WS_FRAME_BYTES = 1048576;
636
+ function rawFrameByteLength(data) {
637
+ if (typeof data === "string") {
638
+ if (data.length > MAX_WS_FRAME_BYTES)
639
+ return data.length;
640
+ if (data.length * 3 <= MAX_WS_FRAME_BYTES)
641
+ return data.length;
642
+ return Buffer.byteLength(data, "utf8");
643
+ }
644
+ if (data instanceof ArrayBuffer)
645
+ return data.byteLength;
646
+ if (ArrayBuffer.isView(data))
647
+ return data.byteLength;
648
+ return 0;
649
+ }
650
+ function safeDelayMs(value, fallback, min = 0) {
651
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min)
652
+ return fallback;
653
+ return Math.min(value, MAX_TIMER_DELAY_MS);
654
+ }
655
+ function normalizeChannelId(raw) {
656
+ if (typeof raw !== "string")
657
+ return null;
658
+ const trimmed = raw.trim();
659
+ if (!trimmed || trimmed.length > 128 || /[\/\\\x00-\x20\x7f-\x9f\u2028\u2029]/.test(trimmed) || [".", "..", "__proto__", "constructor", "prototype"].includes(trimmed.toLowerCase()))
660
+ return null;
661
+ return trimmed;
662
+ }
663
+
148
664
  class MuseAgentChatClient {
149
665
  ws = null;
150
666
  sessionId = null;
151
667
  heartbeatTimer = null;
152
668
  reconnectTimer = null;
669
+ connectTimer = null;
670
+ nextReconnectDelayOverrideMs = null;
153
671
  messageHandlers = [];
154
672
  errorHandlers = [];
673
+ joinedChannels = new Set;
674
+ sessionJoined = new Set;
155
675
  connectResolve = null;
156
676
  connectReject = null;
157
677
  lifecycleResolve = null;
@@ -164,25 +684,58 @@ class MuseAgentChatClient {
164
684
  token;
165
685
  capabilities;
166
686
  heartbeatIntervalMs;
687
+ connectTimeoutMs;
167
688
  reconnect;
168
689
  initialReconnectDelayMs;
169
690
  maxReconnectDelayMs;
170
691
  onDebug;
171
692
  onReconnect;
172
693
  constructor(options) {
173
- this.url = options.url;
694
+ this.url = validateEndpointUrl(options.url, "ws");
174
695
  this.agentId = options.agentId;
175
696
  this.token = options.token;
176
697
  this.capabilities = options.capabilities ?? ["chat"];
177
- this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 30000;
698
+ this.heartbeatIntervalMs = safeDelayMs(options.heartbeatIntervalMs, 30000, 100);
699
+ this.connectTimeoutMs = safeDelayMs(options.connectTimeoutMs, 15000, 0);
178
700
  this.reconnect = options.reconnect ?? true;
179
- this.initialReconnectDelayMs = options.initialReconnectDelayMs ?? 1000;
180
- this.maxReconnectDelayMs = options.maxReconnectDelayMs ?? 60000;
701
+ this.initialReconnectDelayMs = safeDelayMs(options.initialReconnectDelayMs, 1000, 0);
702
+ this.maxReconnectDelayMs = safeDelayMs(options.maxReconnectDelayMs, 60000, 0);
181
703
  this.onDebug = options.onDebug;
182
704
  this.onReconnect = options.onReconnect;
183
705
  }
706
+ clearConnectTimer() {
707
+ if (this.connectTimer) {
708
+ clearTimeout(this.connectTimer);
709
+ this.connectTimer = null;
710
+ }
711
+ }
712
+ emitError(err) {
713
+ for (const h of this.errorHandlers) {
714
+ try {
715
+ h(err);
716
+ } catch {}
717
+ }
718
+ }
184
719
  connect() {
185
720
  return new Promise((resolve, reject) => {
721
+ this.clearConnectTimer();
722
+ if (this.reconnectTimer) {
723
+ clearTimeout(this.reconnectTimer);
724
+ this.reconnectTimer = null;
725
+ }
726
+ if (this.heartbeatTimer) {
727
+ clearInterval(this.heartbeatTimer);
728
+ this.heartbeatTimer = null;
729
+ }
730
+ const prevWs = this.ws;
731
+ this.ws = null;
732
+ this.sessionId = null;
733
+ this.sessionJoined.clear();
734
+ if (prevWs) {
735
+ try {
736
+ prevWs.close();
737
+ } catch {}
738
+ }
186
739
  this.connectSettled = false;
187
740
  this.explicitlyDisconnected = false;
188
741
  this.reconnectAttempt = 0;
@@ -208,16 +761,28 @@ class MuseAgentChatClient {
208
761
  }
209
762
  disconnect() {
210
763
  this.explicitlyDisconnected = true;
764
+ this.clearConnectTimer();
211
765
  if (this.reconnectTimer)
212
766
  clearTimeout(this.reconnectTimer);
213
767
  if (this.heartbeatTimer)
214
768
  clearInterval(this.heartbeatTimer);
215
769
  this.reconnectTimer = null;
216
770
  this.heartbeatTimer = null;
217
- this.ws?.close();
771
+ if (!this.connectSettled) {
772
+ this.connectSettled = true;
773
+ this.connectReject?.(new Error("Disconnected before authentication completed"));
774
+ }
775
+ this.connectResolve = null;
776
+ this.connectReject = null;
777
+ this.lifecycleResolve?.();
778
+ this.lifecycleResolve = null;
779
+ const prev = this.ws;
218
780
  this.ws = null;
219
781
  this.sessionId = null;
220
- this.lifecycleResolve?.();
782
+ this.sessionJoined.clear();
783
+ try {
784
+ prev?.close();
785
+ } catch {}
221
786
  }
222
787
  get isConnected() {
223
788
  return this.ws?.readyState === WebSocket.OPEN && this.sessionId !== null;
@@ -232,60 +797,149 @@ class MuseAgentChatClient {
232
797
  this.errorHandlers.push(handler);
233
798
  }
234
799
  joinChannel(channelId) {
235
- this.send({ type: "join_channel", channel_id: channelId, agent_id: this.agentId });
800
+ const clean = normalizeChannelId(channelId);
801
+ if (!clean)
802
+ return;
803
+ if (!this.joinedChannels.has(clean) && this.joinedChannels.size >= MAX_JOINED_CHANNELS)
804
+ return;
805
+ this.joinedChannels.add(clean);
806
+ this.sessionJoined.add(clean);
807
+ this.send({ type: "join_channel", channel_id: clean, agent_id: this.agentId });
236
808
  }
237
809
  leaveChannel(channelId) {
238
- this.send({ type: "leave_channel", channel_id: channelId, agent_id: this.agentId });
810
+ const clean = normalizeChannelId(channelId);
811
+ if (!clean)
812
+ return;
813
+ this.joinedChannels.delete(clean);
814
+ this.sessionJoined.delete(clean);
815
+ this.send({ type: "leave_channel", channel_id: clean, agent_id: this.agentId });
239
816
  }
240
- sendMessage(channelId, content, contentType = "text") {
817
+ sendMessage(channelId, content, contentType = "text", replyTo) {
818
+ const clean = normalizeChannelId(channelId);
819
+ if (!clean || replyTo !== undefined && (typeof replyTo !== "string" || replyTo.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(replyTo)))
820
+ return;
241
821
  this.send({
242
822
  type: "message",
243
823
  id: crypto.randomUUID(),
244
- channel_id: channelId,
824
+ channel_id: clean,
245
825
  sender_id: this.agentId,
246
826
  sender_type: "agent",
247
827
  content,
248
828
  content_type: contentType,
249
- timestamp: new Date().toISOString()
829
+ timestamp: new Date().toISOString(),
830
+ ...replyTo ? { reply_to: replyTo } : {}
250
831
  });
251
832
  }
252
833
  sendTyping(channelId) {
253
- this.send({ type: "typing", channel_id: channelId, sender_id: this.agentId, cross_pod: true });
834
+ const clean = normalizeChannelId(channelId);
835
+ if (!clean)
836
+ return;
837
+ this.send({ type: "typing", channel_id: clean, sender_id: this.agentId, cross_pod: true });
254
838
  }
255
839
  debug(event, meta) {
256
840
  this.onDebug?.(event, meta);
257
841
  }
258
842
  openSocket() {
259
843
  this.debug("connect:start", { url: this.url, agentId: this.agentId });
844
+ this.clearConnectTimer();
845
+ this.sessionJoined.clear();
260
846
  const ws = new WebSocket(this.url);
261
847
  this.ws = ws;
848
+ if (this.connectTimeoutMs > 0) {
849
+ this.connectTimer = setTimeout(() => {
850
+ this.connectTimer = null;
851
+ if (this.ws !== ws)
852
+ return;
853
+ const err = new Error(`AgentsChat connect timed out after ${this.connectTimeoutMs}ms`);
854
+ if (!this.connectSettled) {
855
+ this.connectSettled = true;
856
+ this.explicitlyDisconnected = true;
857
+ try {
858
+ ws.close();
859
+ } catch {}
860
+ this.connectReject?.(err);
861
+ this.emitError(err);
862
+ } else if (this.sessionId === null) {
863
+ this.emitError(err);
864
+ try {
865
+ ws.close();
866
+ } catch {}
867
+ }
868
+ }, this.connectTimeoutMs);
869
+ this.connectTimer.unref?.();
870
+ }
262
871
  ws.onopen = () => {
263
- this.send({
264
- type: "auth",
265
- agent_id: this.agentId,
266
- token: this.token,
267
- capabilities: this.capabilities
268
- });
872
+ if (this.ws !== ws)
873
+ return;
874
+ try {
875
+ this.send({
876
+ type: "auth",
877
+ agent_id: this.agentId,
878
+ token: this.token,
879
+ capabilities: this.capabilities
880
+ });
881
+ } catch (err) {
882
+ this.clearConnectTimer();
883
+ if (!this.connectSettled) {
884
+ this.connectSettled = true;
885
+ this.connectReject?.(err instanceof Error ? err : new Error(String(err)));
886
+ }
887
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
888
+ try {
889
+ ws.close();
890
+ } catch {}
891
+ return;
892
+ }
269
893
  if (this.heartbeatTimer)
270
894
  clearInterval(this.heartbeatTimer);
271
895
  this.heartbeatTimer = setInterval(() => {
272
- this.send({ type: "ping", timestamp: new Date().toISOString() });
896
+ if (this.ws !== ws)
897
+ return;
898
+ if (ws.readyState === WebSocket.OPEN) {
899
+ try {
900
+ this.send({ type: "ping", timestamp: new Date().toISOString() });
901
+ } catch (err) {
902
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
903
+ try {
904
+ ws.close();
905
+ } catch {}
906
+ }
907
+ }
273
908
  }, this.heartbeatIntervalMs);
909
+ this.heartbeatTimer.unref?.();
910
+ };
911
+ ws.onmessage = (event) => {
912
+ if (this.ws !== ws)
913
+ return;
914
+ if (rawFrameByteLength(event.data) > MAX_WS_FRAME_BYTES)
915
+ return;
916
+ this.handleMessage(String(event.data));
274
917
  };
275
- ws.onmessage = (event) => this.handleMessage(String(event.data));
276
918
  ws.onerror = () => {
919
+ if (this.ws !== ws)
920
+ return;
277
921
  const err = new Error("WebSocket error");
278
922
  if (!this.connectSettled) {
923
+ this.clearConnectTimer();
279
924
  this.connectSettled = true;
280
925
  this.connectReject?.(err);
281
926
  }
282
- this.errorHandlers.forEach((h) => h(err));
927
+ this.emitError(err);
283
928
  };
284
929
  ws.onclose = () => {
930
+ if (this.ws !== ws)
931
+ return;
932
+ this.clearConnectTimer();
285
933
  if (this.heartbeatTimer)
286
934
  clearInterval(this.heartbeatTimer);
287
935
  this.heartbeatTimer = null;
288
936
  this.sessionId = null;
937
+ this.sessionJoined.clear();
938
+ if (!this.connectSettled && !this.reconnect) {
939
+ this.clearConnectTimer();
940
+ this.connectSettled = true;
941
+ this.connectReject?.(new Error("WebSocket closed before authentication"));
942
+ }
289
943
  if (this.explicitlyDisconnected) {
290
944
  this.lifecycleResolve?.();
291
945
  return;
@@ -294,11 +948,19 @@ class MuseAgentChatClient {
294
948
  this.lifecycleResolve?.();
295
949
  return;
296
950
  }
297
- const delay = Math.min(this.initialReconnectDelayMs * 2 ** this.reconnectAttempt, this.maxReconnectDelayMs);
298
- this.reconnectAttempt += 1;
951
+ let delay;
952
+ if (this.nextReconnectDelayOverrideMs !== null) {
953
+ delay = this.nextReconnectDelayOverrideMs;
954
+ this.nextReconnectDelayOverrideMs = null;
955
+ } else {
956
+ const exp = Math.min(Math.max(0, this.reconnectAttempt), 30);
957
+ delay = Math.min(this.initialReconnectDelayMs * 2 ** exp, this.maxReconnectDelayMs);
958
+ this.reconnectAttempt += 1;
959
+ }
299
960
  this.isReconnecting = true;
300
961
  this.debug("reconnect:scheduled", { delayMs: delay, attempt: this.reconnectAttempt });
301
962
  this.reconnectTimer = setTimeout(() => this.openSocket(), delay);
963
+ this.reconnectTimer.unref?.();
302
964
  };
303
965
  }
304
966
  send(payload) {
@@ -308,13 +970,20 @@ class MuseAgentChatClient {
308
970
  this.ws.send(JSON.stringify(payload));
309
971
  }
310
972
  handleMessage(raw) {
311
- let msg;
973
+ if (Buffer.byteLength(raw, "utf8") > 1048576)
974
+ return;
975
+ let parsed;
312
976
  try {
313
- msg = JSON.parse(raw);
977
+ parsed = JSON.parse(raw);
314
978
  } catch {
315
979
  return;
316
980
  }
981
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.hasOwn(parsed, "__proto__")) {
982
+ return;
983
+ }
984
+ const msg = parsed;
317
985
  if (msg.type === "auth_ok") {
986
+ this.clearConnectTimer();
318
987
  this.sessionId = typeof msg.session_id === "string" ? msg.session_id : null;
319
988
  this.reconnectAttempt = 0;
320
989
  const wasReconnect = this.isReconnecting;
@@ -324,25 +993,49 @@ class MuseAgentChatClient {
324
993
  this.connectResolve?.();
325
994
  } else if (wasReconnect) {
326
995
  this.onReconnect?.();
996
+ for (const ch of this.joinedChannels) {
997
+ if (!this.sessionJoined.has(ch) && this.ws?.readyState === WebSocket.OPEN) {
998
+ this.joinChannel(ch);
999
+ }
1000
+ }
327
1001
  }
328
1002
  return;
329
1003
  }
330
- if (msg.type === "error") {
331
- const err = new Error(typeof msg.message === "string" ? msg.message : "AgentsChat error");
1004
+ if (msg.type === "auth_error" || msg.type === "error") {
1005
+ const text = typeof msg.error === "string" ? msg.error : typeof msg.message === "string" ? msg.message : msg.type === "auth_error" ? "AgentsChat authentication error" : "AgentsChat error";
1006
+ const err = new Error(sanitizeMuseText(text).slice(0, 1024));
1007
+ if (msg.type === "auth_error") {
1008
+ this.explicitlyDisconnected = true;
1009
+ try {
1010
+ this.ws?.close();
1011
+ } catch {}
1012
+ }
332
1013
  if (!this.connectSettled) {
1014
+ this.clearConnectTimer();
333
1015
  this.connectSettled = true;
334
1016
  this.connectReject?.(err);
335
1017
  }
336
- this.errorHandlers.forEach((h) => h(err));
1018
+ this.emitError(err);
1019
+ return;
1020
+ }
1021
+ if (msg.type === "please_reconnect" || msg.type === "shard_moved") {
1022
+ this.nextReconnectDelayOverrideMs = resolveDrainReconnectDelay(msg);
1023
+ this.reconnectAttempt = 0;
1024
+ try {
1025
+ this.ws?.close();
1026
+ } catch {}
337
1027
  return;
338
1028
  }
339
1029
  if (msg.type === "pong")
340
1030
  return;
341
1031
  if (msg.type === "channel_created" && typeof msg.channel_id === "string" && msg.channel_id) {
342
- this.joinChannel(msg.channel_id);
1032
+ if (this.ws?.readyState === WebSocket.OPEN)
1033
+ this.joinChannel(msg.channel_id);
343
1034
  return;
344
1035
  }
345
- if (msg.type === "message") {
1036
+ if (msg.type === "message" || msg.type === "thread_reply") {
1037
+ if (msg.content === "__typing__")
1038
+ return;
346
1039
  const chat = {
347
1040
  id: String(msg.id ?? ""),
348
1041
  channel_id: String(msg.channel_id ?? ""),
@@ -352,168 +1045,177 @@ class MuseAgentChatClient {
352
1045
  content_type: msg.content_type ?? "text",
353
1046
  timestamp: String(msg.timestamp ?? new Date().toISOString()),
354
1047
  channel_type: msg.channel_type,
355
- thread_id: typeof msg.thread_id === "string" ? msg.thread_id : undefined
1048
+ thread_id: typeof msg.thread_id === "string" ? msg.thread_id : typeof msg.parent_id === "string" ? msg.parent_id : undefined
356
1049
  };
357
- for (const h of this.messageHandlers)
358
- h(chat);
1050
+ for (const h of this.messageHandlers) {
1051
+ try {
1052
+ Promise.resolve(h(chat)).catch((err) => {
1053
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
1054
+ });
1055
+ } catch (err) {
1056
+ this.emitError(err instanceof Error ? err : new Error(String(err)));
1057
+ }
1058
+ }
359
1059
  }
360
1060
  }
361
1061
  }
362
1062
 
363
- // muse/src/config.ts
364
- import { existsSync, readFileSync } from "node:fs";
365
- import { homedir } from "node:os";
366
- import { join } from "node:path";
367
- var DEFAULT_WS_URL = "wss://agents-chat.com/ws";
368
- var DEFAULT_REST_URL = "https://agents-chat.com";
369
- var PROFILE_PATH = join(homedir(), ".agentschat", "muse.json");
370
- function redact(value) {
371
- if (!value)
372
- return "(missing)";
373
- if (value.length <= 4)
374
- return "****";
375
- return `${value.slice(0, 2)}****${value.slice(-2)}`;
376
- }
377
- function safeConfig(config) {
378
- return {
379
- agentId: config.agentId,
380
- wsUrl: config.wsUrl,
381
- restUrl: config.restUrl,
382
- displayName: config.displayName,
383
- defaultChannelId: config.defaultChannelId,
384
- token: redact(config.token)
385
- };
386
- }
387
- function readProfile(path = PROFILE_PATH) {
388
- try {
389
- if (!existsSync(path))
390
- return {};
391
- return JSON.parse(readFileSync(path, "utf8"));
392
- } catch {
393
- return {};
394
- }
1063
+ // muse/src/cli.ts
1064
+ function safeLogText(text) {
1065
+ return sanitizeMuseText(text);
395
1066
  }
396
- function loadConfig(env = process.env, profilePath) {
397
- const profile = readProfile(profilePath);
398
- const agentId = env.AGENTCHAT_AGENT_ID ?? profile.agentId;
399
- const token = env.AGENTCHAT_TOKEN ?? profile.token;
400
- if (!agentId || !token) {
401
- throw new Error("Missing AgentsChat identity: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " + `or create ${profilePath ?? PROFILE_PATH} via 'muse-agentchat --register-only --name <name>'. ` + "Tokens are never printed; see README for registration.");
1067
+ var MAX_REGISTRATION_BYTES = 1024 * 1024;
1068
+ var MUSE_CLI_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
1069
+ var MUSE_CLI_PRETRIM_CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/;
1070
+ var FORBIDDEN_CHANNEL_KEYS = new Set(["__proto__", "constructor", "prototype"]);
1071
+ function validateMuseChannelId(value) {
1072
+ if (typeof value !== "string" || !value || value.startsWith("--") || value.length > 128 || value === "." || value === ".." || value.includes("..") || /[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(value) || FORBIDDEN_CHANNEL_KEYS.has(value.toLowerCase()) || Object.getOwnPropertyNames(Object.prototype).some((k) => k.toLowerCase() === value.toLowerCase())) {
1073
+ throw new Error("Invalid channel id");
402
1074
  }
403
- return {
404
- agentId,
405
- token,
406
- wsUrl: env.AGENTCHAT_WS_URL ?? profile.wsUrl ?? DEFAULT_WS_URL,
407
- restUrl: env.AGENTCHAT_REST_URL ?? profile.restUrl ?? DEFAULT_REST_URL,
408
- displayName: env.AGENTCHAT_DISPLAY_NAME ?? profile.displayName,
409
- defaultChannelId: env.AGENTCHAT_CHANNEL_ID ?? profile.defaultChannelId
410
- };
1075
+ return value;
411
1076
  }
412
-
413
- // muse/src/wake.ts
414
- import { createHmac, timingSafeEqual } from "node:crypto";
415
- import { appendFileSync, existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
416
- var WAKE_SIG_HEADER = "x-agentschat-signature";
417
- var WAKE_CONTENT_MAX = 500;
418
- function redactSecrets(text) {
419
- return text.replace(/ac_[A-Za-z0-9_-]+/g, "[redacted]").replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted]");
420
- }
421
- function buildWakePayload(msg, opts = {}) {
422
- const content = typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX)) : undefined;
423
- const targetSessionId = typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
424
- return {
425
- type: typeof msg.type === "string" ? msg.type : "message",
426
- channel_id: msg.channel_id,
427
- message_id: msg.id,
428
- sender_id: msg.sender_id,
429
- content,
430
- mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string") : undefined,
431
- timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined,
432
- ...targetSessionId ? { target_session_id: targetSessionId } : {}
433
- };
434
- }
435
- function signWakeBody(body, secret) {
436
- return createHmac("sha256", secret).update(body, "utf8").digest("hex");
437
- }
438
- async function fireWake(msg, cfg) {
439
- const log = cfg.logger ?? (() => {});
440
- const url = (cfg.url ?? "").trim();
441
- if (!url)
442
- return;
443
- const body = JSON.stringify(buildWakePayload(msg, { targetSessionId: cfg.targetSessionId }));
444
- const headers = { "Content-Type": "application/json" };
445
- if (cfg.secret)
446
- headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
447
- const doPost = async () => {
448
- const f = cfg.fetchImpl ?? fetch;
449
- const ctrl = new AbortController;
450
- const t = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 5000);
451
- try {
452
- const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
453
- if (!res.ok)
454
- log(`[muse-agentchat] wake POST ${url} → HTTP ${res.status}`);
455
- } finally {
456
- clearTimeout(t);
457
- }
458
- };
1077
+ async function readRegistrationBody(res) {
1078
+ if (!res.body)
1079
+ throw new Error("Registration response body is missing");
1080
+ const reader = res.body.getReader();
1081
+ const decoder = new TextDecoder("utf-8", { fatal: true });
1082
+ let bytes = 0;
1083
+ let body = "";
1084
+ let complete = false;
459
1085
  try {
460
- await doPost();
461
- } catch (e) {
462
- try {
463
- await doPost();
464
- } catch (e2) {
465
- log(`[muse-agentchat] wake POST ${url} failed: ${e2}`);
466
- }
467
- }
468
- }
469
- function appendWakeQueue(queueFile, payload) {
470
- const line = JSON.stringify(payload);
471
- if (payload.message_id && existsSync2(queueFile)) {
472
- const existing = readFileSync2(queueFile, "utf8");
473
- if (existing.split(`
474
- `).some((l) => {
475
- try {
476
- return JSON.parse(l).message_id === payload.message_id;
477
- } catch {
478
- return false;
479
- }
480
- })) {
481
- return false;
1086
+ while (true) {
1087
+ const { done, value } = await reader.read();
1088
+ if (done)
1089
+ break;
1090
+ bytes += value.byteLength;
1091
+ if (bytes > MAX_REGISTRATION_BYTES)
1092
+ throw new Error("Registration response exceeds 1MiB limit");
1093
+ body += decoder.decode(value, { stream: true });
482
1094
  }
1095
+ body += decoder.decode();
1096
+ complete = true;
1097
+ return body;
1098
+ } finally {
1099
+ if (!complete)
1100
+ reader.cancel().catch(() => {});
1101
+ reader.releaseLock();
483
1102
  }
484
- appendFileSync(queueFile, line + `
485
- `);
486
- return true;
487
1103
  }
488
-
489
- // muse/src/cli.ts
490
1104
  function arg(name, argv) {
491
1105
  const i = argv.indexOf(name);
492
- return i >= 0 ? argv[i + 1] : undefined;
1106
+ if (i < 0)
1107
+ return;
1108
+ const val = argv[i + 1];
1109
+ return val !== undefined && !val.startsWith("--") ? val : undefined;
493
1110
  }
494
1111
  function has(name, argv) {
495
1112
  return argv.includes(name);
496
1113
  }
497
- async function registerOnly(name, restUrl) {
1114
+ async function registerOnly(name, restUrl, profilePath = PROFILE_PATH, fetchImpl = fetch, fsOps = {}) {
1115
+ if (typeof name !== "string" || MUSE_CLI_PRETRIM_CTRL_RE.test(name)) {
1116
+ throw new Error("Invalid --name value");
1117
+ }
1118
+ const cleanName = name.trim();
1119
+ if (!cleanName || cleanName.length > 64 || MUSE_CLI_CTRL_RE.test(cleanName)) {
1120
+ throw new Error("Invalid --name value");
1121
+ }
1122
+ const endpoint = validateEndpointUrl(restUrl, "rest");
1123
+ const profileDir = dirname3(profilePath);
1124
+ assertSafeParentDirectories(profilePath);
1125
+ mkdirSync2(profileDir, { recursive: true, mode: 448 });
1126
+ assertSafeParentDirectories(profilePath);
1127
+ try {
1128
+ const st = lstatSync3(profilePath);
1129
+ if (st.isSymbolicLink() || !st.isFile()) {
1130
+ throw new Error("Refusing to overwrite symlink or non-regular Muse profile");
1131
+ }
1132
+ } catch (err) {
1133
+ if (err?.code !== "ENOENT")
1134
+ throw err;
1135
+ }
498
1136
  console.log("Terms notice: https://agents-chat.com/terms (notice only, no acceptance prompt)");
499
- const res = await fetch(`${restUrl.replace(/\/$/, "")}/api/account/register`, {
1137
+ const res = await fetchImpl(`${endpoint.replace(/\/$/, "")}/api/account/register`, {
500
1138
  method: "POST",
501
1139
  headers: { "content-type": "application/json" },
502
- body: JSON.stringify({ name, type: "agent", capabilities: ["chat"] })
1140
+ body: JSON.stringify({ name: cleanName, type: "agent", capabilities: ["chat"] }),
1141
+ redirect: "error",
1142
+ signal: AbortSignal.timeout(15000)
503
1143
  });
504
- if (!res.ok)
505
- throw new Error(`Registration failed: ${res.status} ${await res.text()}`);
506
- const data = await res.json();
507
- const agentId = data.agentId ?? data.agent_id ?? data.id;
508
- const token = data.agentKey ?? data.token ?? data.key;
1144
+ const responseBody = await readRegistrationBody(res);
1145
+ if (!res.ok) {
1146
+ const errBody = redactSecrets(responseBody).slice(0, 512);
1147
+ throw new Error(`Registration failed: ${res.status} ${errBody}`);
1148
+ }
1149
+ const data = JSON.parse(responseBody);
1150
+ if (!data || typeof data !== "object" || Array.isArray(data) || Object.getPrototypeOf(data) !== Object.prototype || Object.hasOwn(data, "__proto__")) {
1151
+ throw new Error("Invalid registration response");
1152
+ }
1153
+ const rawAgentId = data.agentId ?? data.agent_id ?? data.id;
1154
+ const rawToken = data.agentKey ?? data.token ?? data.key;
1155
+ if (typeof rawAgentId !== "string" || typeof rawToken !== "string" || !rawAgentId || !rawToken) {
1156
+ throw new Error("Registration response did not include an agent id/token");
1157
+ }
1158
+ if (MUSE_CLI_PRETRIM_CTRL_RE.test(rawAgentId) || MUSE_CLI_PRETRIM_CTRL_RE.test(rawToken)) {
1159
+ throw new Error("Registration response contained unsafe agent id or token");
1160
+ }
1161
+ const agentId = rawAgentId.trim();
1162
+ const token = rawToken.trim();
509
1163
  if (!agentId || !token)
510
1164
  throw new Error("Registration response did not include an agent id/token");
511
- mkdirSync(dirname(PROFILE_PATH), { recursive: true });
512
- writeFileSync(PROFILE_PATH, JSON.stringify({ agentId, token }, null, 2), { mode: 384 });
513
- console.log(`Registered agent '${name}' as ${agentId}. Identity saved to ${PROFILE_PATH} (token not printed).`);
1165
+ if (!isSafeAgentId(agentId) || MUSE_CLI_CTRL_RE.test(token)) {
1166
+ throw new Error("Registration response contained unsafe agent id or token");
1167
+ }
1168
+ const doRename = fsOps.renameSync ?? renameSync2;
1169
+ const doCopy = fsOps.copyFileSync ?? copyFileSync2;
1170
+ const tmp = `${profilePath}.${process.pid}.${Date.now()}.${randomBytes2(6).toString("hex")}.tmp`;
1171
+ try {
1172
+ assertSafeParentDirectories(profilePath);
1173
+ writeFileSync2(tmp, JSON.stringify({ agentId, token }, null, 2), { mode: 384, flag: "wx" });
1174
+ assertSafeParentDirectories(profilePath);
1175
+ try {
1176
+ const st = lstatSync3(profilePath);
1177
+ if (st.isSymbolicLink() || !st.isFile()) {
1178
+ throw new Error("Refusing to overwrite symlink or non-regular Muse profile");
1179
+ }
1180
+ } catch (err) {
1181
+ if (err?.code !== "ENOENT")
1182
+ throw err;
1183
+ }
1184
+ try {
1185
+ doRename(tmp, profilePath);
1186
+ } catch (renameErr) {
1187
+ const code = renameErr?.code;
1188
+ if (code !== "EPERM" && code !== "EACCES")
1189
+ throw renameErr;
1190
+ assertSafeParentDirectories(profilePath);
1191
+ try {
1192
+ const st = lstatSync3(profilePath);
1193
+ if (st.isSymbolicLink() || !st.isFile()) {
1194
+ throw new Error("Refusing to overwrite symlink or non-regular Muse profile");
1195
+ }
1196
+ } catch (err) {
1197
+ if (err?.code !== "ENOENT")
1198
+ throw err;
1199
+ }
1200
+ doCopy(tmp, profilePath);
1201
+ try {
1202
+ unlinkSync2(tmp);
1203
+ } catch {}
1204
+ }
1205
+ if (process.platform !== "win32") {
1206
+ try {
1207
+ chmodSync2(profilePath, 384);
1208
+ } catch {}
1209
+ }
1210
+ } catch (err) {
1211
+ try {
1212
+ unlinkSync2(tmp);
1213
+ } catch {}
1214
+ throw err;
1215
+ }
1216
+ console.log(`Registered agent '${cleanName}' as ${agentId}. Identity saved to ${profilePath} (token not printed).`);
514
1217
  }
515
- async function main() {
516
- const argv = process.argv.slice(2);
1218
+ async function main(argv = process.argv.slice(2)) {
517
1219
  if (has("--help", argv) || has("-h", argv)) {
518
1220
  console.log("Usage: agentschat-mcp --muse --register-only --name <name> | --wake [--channel <id>...] | --listen [--channel <id>...] [--auto-reply <text>] | --send <channel-id> --text <text>");
519
1221
  return;
@@ -526,8 +1228,13 @@ async function main() {
526
1228
  await registerOnly(name, restUrl);
527
1229
  return;
528
1230
  }
1231
+ for (let i = 0;i < argv.length; i++) {
1232
+ if (argv[i] === "--channel" || argv[i] === "--send") {
1233
+ validateMuseChannelId(argv[i + 1]);
1234
+ }
1235
+ }
529
1236
  const config = loadConfig();
530
- console.log("Muse AgentsChat:", JSON.stringify(safeConfig(config)));
1237
+ console.log("Muse AgentsChat:", safeLogText(JSON.stringify(safeConfig(config))));
531
1238
  const client = new MuseAgentChatClient({
532
1239
  url: config.wsUrl,
533
1240
  agentId: config.agentId,
@@ -537,76 +1244,115 @@ async function main() {
537
1244
  if (has("--wake", argv)) {
538
1245
  const wakeChannels = [];
539
1246
  for (let i = 0;i < argv.length; i++) {
540
- if (argv[i] === "--channel" && argv[i + 1])
541
- wakeChannels.push(argv[i + 1]);
1247
+ if (argv[i] === "--channel" && argv[i + 1] && !argv[i + 1].startsWith("--"))
1248
+ wakeChannels.push(validateMuseChannelId(argv[i + 1]));
542
1249
  }
543
1250
  if (config.defaultChannelId)
544
- wakeChannels.push(config.defaultChannelId);
1251
+ wakeChannels.push(validateMuseChannelId(config.defaultChannelId));
1252
+ const uniqueWakeChannels = [...new Set(wakeChannels)];
545
1253
  const queueFile = process.env.MUSE_WAKE_QUEUE ?? join2(homedir2(), ".agentschat", "muse-wake-queue.jsonl");
546
1254
  const wakeUrl = process.env.MUSE_WAKE_URL ?? process.env.AGENTCHAT_WAKE_URL;
547
1255
  const wakeSecret = process.env.MUSE_WAKE_SECRET ?? process.env.AGENTCHAT_WAKE_SECRET;
548
1256
  const typing = new TypingHeartbeat((channelId) => client.sendTyping(channelId));
549
- process.on("SIGINT", () => typing.stopAll());
1257
+ const shutdownWake = () => {
1258
+ typing.stopAll();
1259
+ client.disconnect();
1260
+ };
1261
+ process.once("SIGINT", shutdownWake);
1262
+ process.once("SIGTERM", shutdownWake);
1263
+ if (process.platform !== "win32")
1264
+ process.once("SIGHUP", shutdownWake);
550
1265
  client.onMessage((m) => {
551
1266
  if (m.sender_id === config.agentId) {
552
1267
  typing.stop(m.channel_id);
553
1268
  return;
554
1269
  }
555
- const kind = m.channel_id.startsWith("dm-") ? "direct" : "group";
1270
+ const kind = /^dm[-:]/i.test(m.channel_id) ? "direct" : "group";
556
1271
  if (!shouldDispatch(m, { agentId: config.agentId, displayName: config.displayName, channelKind: kind }))
557
1272
  return;
558
1273
  typing.start(m.channel_id);
559
1274
  const payload = buildWakePayload({ ...m, type: "message" });
560
1275
  const queued = appendWakeQueue(queueFile, payload);
561
- fireWake({ ...m, type: "message" }, { url: wakeUrl, secret: wakeSecret, logger: console.error });
562
- console.log(`[wake] ${m.channel_id} ${m.sender_id} ${m.id} queued=${queued}`);
1276
+ fireWake({ ...m, type: "message" }, { url: wakeUrl, secret: wakeSecret, logger: (text) => console.error(safeLogText(text)) });
1277
+ console.log(`[wake] ${safeLogText(m.channel_id)} ${safeLogText(m.sender_id)} ${safeLogText(m.id)} queued=${queued}`);
563
1278
  });
564
1279
  client.onReconnect = () => {
565
- for (const c of wakeChannels)
1280
+ for (const c of uniqueWakeChannels)
566
1281
  client.joinChannel(c);
567
1282
  };
568
- await client.connect();
569
- for (const c of wakeChannels)
570
- client.joinChannel(c);
571
- console.log(`Wake daemon listening on ${wakeChannels.join(", ") || "(no channels — pass --channel <id>)"}, queue=${queueFile}. Press Ctrl+C to stop.`);
572
- await client.waitUntilClosed();
1283
+ try {
1284
+ await client.connect();
1285
+ for (const c of uniqueWakeChannels)
1286
+ client.joinChannel(c);
1287
+ console.log(`Wake daemon listening on ${safeLogText(uniqueWakeChannels.join(", ")) || "(no channels — pass --channel <id>)"}, queue=${safeLogText(queueFile)}. Press Ctrl+C to stop.`);
1288
+ await client.waitUntilClosed();
1289
+ } finally {
1290
+ process.removeListener("SIGINT", shutdownWake);
1291
+ process.removeListener("SIGTERM", shutdownWake);
1292
+ if (process.platform !== "win32")
1293
+ process.removeListener("SIGHUP", shutdownWake);
1294
+ }
573
1295
  return;
574
1296
  }
575
1297
  if (has("--send", argv)) {
576
- const channelId = arg("--send", argv);
1298
+ const channelId = validateMuseChannelId(arg("--send", argv));
577
1299
  const text = arg("--text", argv);
578
1300
  if (!channelId || !text)
579
1301
  throw new Error("--send requires a channel id and --text <text>");
580
1302
  await client.connect();
581
1303
  client.joinChannel(channelId);
582
1304
  client.sendMessage(channelId, text);
1305
+ await new Promise((r) => setTimeout(r, 500));
583
1306
  console.log(`Sent to ${channelId}`);
584
1307
  client.disconnect();
585
1308
  return;
586
1309
  }
587
1310
  const channels = [];
588
1311
  for (let i = 0;i < argv.length; i++) {
589
- if (argv[i] === "--channel" && argv[i + 1])
590
- channels.push(argv[i + 1]);
1312
+ if (argv[i] === "--channel" && argv[i + 1] && !argv[i + 1].startsWith("--"))
1313
+ channels.push(validateMuseChannelId(argv[i + 1]));
591
1314
  }
592
1315
  if (config.defaultChannelId)
593
- channels.push(config.defaultChannelId);
1316
+ channels.push(validateMuseChannelId(config.defaultChannelId));
1317
+ const uniqueChannels = [...new Set(channels)];
594
1318
  const autoReply = arg("--auto-reply", argv);
595
1319
  const bridge = new MuseBridge(client, {
596
1320
  agentId: config.agentId,
597
1321
  displayName: config.displayName,
598
- channels,
1322
+ channels: uniqueChannels,
599
1323
  responder: async (ctx) => {
600
- console.log(`[${ctx.message.channel_id}] ${ctx.message.sender_id}: ${ctx.message.content}`);
1324
+ console.log(`[${safeLogText(ctx.message.channel_id)}] ${safeLogText(ctx.message.sender_id)}: ${safeLogText(ctx.message.content)}`);
601
1325
  return autoReply ?? null;
602
1326
  }
603
1327
  });
1328
+ const shutdownListen = () => bridge.stop();
1329
+ process.once("SIGINT", shutdownListen);
1330
+ process.once("SIGTERM", shutdownListen);
1331
+ if (process.platform !== "win32")
1332
+ process.once("SIGHUP", shutdownListen);
604
1333
  client.onReconnect = () => bridge.rejoin();
605
- await bridge.start();
606
- console.log(`Listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"}. Press Ctrl+C to stop.`);
607
- await client.waitUntilClosed();
608
- }
609
- main().catch((err) => {
610
- console.error(err instanceof Error ? err.message : String(err));
611
- process.exit(1);
612
- });
1334
+ try {
1335
+ await bridge.start();
1336
+ console.log(`Listening on ${safeLogText(uniqueChannels.join(", ")) || "(no channels — pass --channel <id>)"}. Press Ctrl+C to stop.`);
1337
+ await client.waitUntilClosed();
1338
+ } finally {
1339
+ process.removeListener("SIGINT", shutdownListen);
1340
+ process.removeListener("SIGTERM", shutdownListen);
1341
+ if (process.platform !== "win32")
1342
+ process.removeListener("SIGHUP", shutdownListen);
1343
+ }
1344
+ }
1345
+ var entryPath = (process.argv[1] ?? "").replace(/\\/g, "/");
1346
+ var invokedDirectly = entryPath.endsWith("muse/src/cli.ts") || entryPath.endsWith("dist/muse.js") || process.argv.includes("--muse");
1347
+ if (invokedDirectly) {
1348
+ main().catch((err) => {
1349
+ console.error(safeLogText(err instanceof Error ? err.message : String(err)));
1350
+ process.exit(1);
1351
+ });
1352
+ }
1353
+ export {
1354
+ validateMuseChannelId,
1355
+ registerOnly,
1356
+ main,
1357
+ arg
1358
+ };