agentschat-mcp 0.36.25 → 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 (82) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/codex/README.md +1 -1
  3. package/codex/app-server.ts +79 -22
  4. package/codex/bots-config.ts +31 -11
  5. package/codex/bridge.ts +123 -25
  6. package/codex/config.ts +128 -21
  7. package/codex/gui-channel.ts +66 -9
  8. package/codex/inbox-sync.ts +65 -12
  9. package/codex/loop-grants.ts +41 -11
  10. package/codex/manager.ts +101 -25
  11. package/codex/owner.ts +81 -9
  12. package/codex/processes.ts +51 -7
  13. package/codex/run.ts +70 -17
  14. package/codex/runtime-home.ts +41 -11
  15. package/codex/thread-history.ts +77 -30
  16. package/codex/transport.ts +122 -19
  17. package/connector/auth.ts +57 -5
  18. package/connector/backfill.ts +92 -10
  19. package/connector/descriptor.ts +27 -1
  20. package/connector/identities.ts +82 -14
  21. package/connector/ingest.ts +11 -2
  22. package/connector/normalize.ts +32 -12
  23. package/connector/run.ts +314 -67
  24. package/connector/server.ts +95 -26
  25. package/dist/codex-bots.js +410 -73
  26. package/dist/codex-bridge.js +1996 -576
  27. package/dist/connector.js +1286 -493
  28. package/dist/dsh.js +1776 -299
  29. package/dist/muse.js +967 -221
  30. package/dist/server.js +4277 -929
  31. package/dsh/client.js +7 -5
  32. package/dsh/identity-ui/client.js +7 -5
  33. package/dsh/identity-ui/index.js +43 -8
  34. package/dsh/inbound-bridge/index.js +595 -146
  35. package/dsh/src/cli.ts +430 -91
  36. package/dsh/src/patch.ts +295 -15
  37. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  38. package/dsh/tests/dsh.test.ts +990 -3
  39. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  40. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  41. package/muse/src/bridge.ts +54 -13
  42. package/muse/src/cli.ts +226 -41
  43. package/muse/src/client.ts +249 -34
  44. package/muse/src/config.ts +128 -12
  45. package/muse/src/policy.ts +28 -8
  46. package/muse/src/types.ts +1 -0
  47. package/muse/src/typing.ts +18 -1
  48. package/muse/src/wake.ts +237 -35
  49. package/muse/tests/bridge.test.mjs +131 -0
  50. package/muse/tests/client.test.mjs +327 -0
  51. package/muse/tests/config.test.mjs +78 -1
  52. package/muse/tests/hardening.test.mjs +199 -0
  53. package/muse/tests/hardening126.test.mjs +292 -0
  54. package/muse/tests/policy.test.mjs +83 -1
  55. package/muse/tests/wake.test.mjs +134 -6
  56. package/package.json +1 -1
  57. package/scripts/ensure-grok-wakes.mjs +93 -8
  58. package/scripts/example-url-wake-receiver.mjs +254 -61
  59. package/scripts/grok-bind-register.sh +38 -8
  60. package/skills/onboarding.md +9 -9
  61. package/src/argcheck.ts +113 -33
  62. package/src/cli.mjs +98 -14
  63. package/src/dedup.ts +57 -8
  64. package/src/grok-bind.ts +160 -33
  65. package/src/heartbeat.ts +39 -11
  66. package/src/identity-guard.ts +93 -20
  67. package/src/identity.ts +67 -11
  68. package/src/mentions.ts +26 -5
  69. package/src/onboarding-status.ts +134 -11
  70. package/src/profile-selection.ts +269 -18
  71. package/src/profile-store.ts +222 -28
  72. package/src/read-cursor.ts +256 -9
  73. package/src/reconnect.ts +98 -2
  74. package/src/redact.ts +34 -15
  75. package/src/rest-cli.ts +713 -159
  76. package/src/server.ts +285 -93
  77. package/src/session-bind.ts +731 -132
  78. package/src/session-route.ts +183 -12
  79. package/src/team-lead-skill.ts +3 -0
  80. package/src/timestamps.ts +56 -23
  81. package/src/tool-annotations.ts +10 -1
  82. package/src/wake.ts +510 -91
@@ -26,14 +26,16 @@
26
26
  */
27
27
  import { spawn } from "node:child_process";
28
28
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, writeFileSync, appendFileSync } from "node:fs";
29
- import { homedir } from "node:os";
29
+ import { homedir, tmpdir } from "node:os";
30
30
  import { dirname, join } from "node:path";
31
31
  import { fileURLToPath } from "node:url";
32
32
 
33
- const HOME = homedir();
33
+ const HOME = process.env.HOME || process.env.USERPROFILE || homedir();
34
34
  const LOCK = process.env.MUSE_WAKE_ENSURE_LOCK ?? join(HOME, ".agentschat", "muse-wake-ensure.lock");
35
35
  const PIDFILE = process.env.MUSE_WAKE_PIDFILE ?? join(HOME, ".agentschat", "muse-wake.pid");
36
- const LOG = process.env.MUSE_WAKE_LOG ?? "/tmp/agentschat-muse-wake.log";
36
+ const LOG =
37
+ process.env.MUSE_WAKE_LOG ??
38
+ (process.platform === "win32" ? join(tmpdir(), "agentschat-muse-wake.log") : "/tmp/agentschat-muse-wake.log");
37
39
  const PLUGIN_DIR = join(dirname(fileURLToPath(import.meta.url)), "..");
38
40
 
39
41
  function pidAlive(pid) {
@@ -11,11 +11,14 @@
11
11
  * node scripts/muse-wake-receiver.mjs # listens on 127.0.0.1:18766
12
12
  */
13
13
  import { createServer } from "node:http";
14
+ import { homedir } from "node:os";
15
+ import { join } from "node:path";
14
16
  import { appendWakeQueue, verifyWakeSignature, WAKE_SIG_HEADER } from "../src/wake.ts";
15
17
 
16
18
  const PORT = Number(process.env.MUSE_WAKE_PORT ?? 18766);
17
19
  const SECRET = process.env.MUSE_WAKE_SECRET ?? "";
18
- const QUEUE = process.env.MUSE_WAKE_QUEUE ?? `${process.env.HOME}/.agentschat/muse-wake-queue.jsonl`;
20
+ const HOME = process.env.HOME || process.env.USERPROFILE || homedir();
21
+ const QUEUE = process.env.MUSE_WAKE_QUEUE ?? join(HOME, ".agentschat", "muse-wake-queue.jsonl");
19
22
 
20
23
  const server = createServer((req, res) => {
21
24
  if (req.method !== "POST" || req.url !== "/wake") {
@@ -29,8 +29,12 @@ export interface MuseBridgeOptions {
29
29
  * separation is deliberate — this plugin must not invent a Muse model API;
30
30
  * the embedding Muse host passes in whatever responder it already has.
31
31
  */
32
+ const FORBIDDEN_BRIDGE_CHANNELS = new Set(["__proto__", "constructor", "prototype"]);
33
+ const BRIDGE_CHANNEL_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
34
+
32
35
  export class MuseBridge {
33
36
  private readonly client: MuseAgentChatClient;
37
+ private readonly activeReplies = new Map<string, number>();
34
38
  private readonly history = new Map<string, ChatMessage[]>();
35
39
  private readonly opts: MuseBridgeOptions;
36
40
  private readonly typing = new TypingHeartbeat((channelId) => this.client.sendTyping(channelId));
@@ -38,7 +42,7 @@ export class MuseBridge {
38
42
  constructor(client: MuseAgentChatClient, opts: MuseBridgeOptions) {
39
43
  this.client = client;
40
44
  this.opts = opts;
41
- this.client.onMessage((m) => void this.handleMessage(m));
45
+ this.client.onMessage((m) => this.handleMessage(m));
42
46
  }
43
47
 
44
48
  async start(): Promise<void> {
@@ -52,6 +56,8 @@ export class MuseBridge {
52
56
  }
53
57
 
54
58
  stop(): void {
59
+ this.typing.stopAll();
60
+ this.activeReplies.clear();
55
61
  this.client.disconnect();
56
62
  }
57
63
 
@@ -61,23 +67,58 @@ export class MuseBridge {
61
67
 
62
68
  /** Test seam: feed an inbound message without a socket. */
63
69
  async handleMessage(message: ChatMessage): Promise<void> {
70
+ if (
71
+ !message ||
72
+ typeof message.channel_id !== "string" ||
73
+ !message.channel_id ||
74
+ message.channel_id.length > 256 ||
75
+ FORBIDDEN_BRIDGE_CHANNELS.has(message.channel_id.toLowerCase()) ||
76
+ Object.getOwnPropertyNames(Object.prototype).some((k) => k.toLowerCase() === message.channel_id.toLowerCase()) ||
77
+ message.content === "__typing__"
78
+ ) {
79
+ return;
80
+ }
81
+ if (!this.history.has(message.channel_id) && this.history.size >= 200) {
82
+ const oldest = this.history.keys().next().value;
83
+ if (oldest !== undefined) this.history.delete(oldest);
84
+ }
64
85
  const list = this.history.get(message.channel_id) ?? [];
65
86
  list.push(message);
66
87
  this.history.set(message.channel_id, list.slice(-50));
67
- const kind = this.opts.channelKinds?.[message.channel_id];
88
+ const kinds = this.opts.channelKinds;
89
+ const kind = kinds && Object.prototype.hasOwnProperty.call(kinds, message.channel_id)
90
+ ? kinds[message.channel_id]
91
+ : undefined;
68
92
  if (!shouldDispatch(message, { agentId: this.opts.agentId, displayName: this.opts.displayName, channelKind: kind })) {
69
93
  return;
70
94
  }
71
- // Show "thinking" from the moment we decide to answer until the reply lands.
72
- this.typing.start(message.channel_id);
73
- const ctx: MuseResponderContext = {
74
- message,
75
- channelKind: kind,
76
- history: [...(this.history.get(message.channel_id) ?? [])],
77
- context: buildContext(this.history.get(message.channel_id) ?? [], this.opts.agentId),
78
- };
79
- const reply = await this.opts.responder(ctx);
80
- if (reply) this.client.sendMessage(message.channel_id, reply);
81
- this.typing.stop(message.channel_id);
95
+ // Show "thinking" from the moment we decide to answer until the reply lands (even if responder throws).
96
+ const active = this.activeReplies.get(message.channel_id) ?? 0;
97
+ this.activeReplies.set(message.channel_id, active + 1);
98
+ if (active === 0) this.typing.start(message.channel_id);
99
+ try {
100
+ const ctx: MuseResponderContext = {
101
+ message,
102
+ channelKind: kind,
103
+ history: [...(this.history.get(message.channel_id) ?? [])],
104
+ context: buildContext(this.history.get(message.channel_id) ?? [], this.opts.agentId),
105
+ };
106
+ const reply = await this.opts.responder(ctx);
107
+ if (reply && !BRIDGE_CHANNEL_CTRL_RE.test(message.channel_id)) {
108
+ if (message.thread_id && !BRIDGE_CHANNEL_CTRL_RE.test(message.thread_id)) {
109
+ this.client.sendMessage(message.channel_id, reply, "text", message.thread_id);
110
+ } else {
111
+ this.client.sendMessage(message.channel_id, reply);
112
+ }
113
+ }
114
+ } finally {
115
+ const remaining = (this.activeReplies.get(message.channel_id) ?? 1) - 1;
116
+ if (remaining <= 0) {
117
+ this.activeReplies.delete(message.channel_id);
118
+ this.typing.stop(message.channel_id);
119
+ } else {
120
+ this.activeReplies.set(message.channel_id, remaining);
121
+ }
122
+ }
82
123
  }
83
124
  }
package/muse/src/cli.ts CHANGED
@@ -15,44 +15,191 @@
15
15
  * Tokens are never printed. Registration uses the public REST endpoint and
16
16
  * shows the nonblocking Terms notice at https://agents-chat.com/terms.
17
17
  */
18
- import { writeFileSync, mkdirSync } from "node:fs";
18
+ import { randomBytes } from "node:crypto";
19
+ import { chmodSync, copyFileSync, writeFileSync, mkdirSync, renameSync, unlinkSync, lstatSync } from "node:fs";
19
20
  import { dirname } from "node:path";
20
21
  import { homedir } from "node:os";
21
22
  import { join } from "node:path";
22
23
  import { MuseBridge } from "./bridge.ts";
23
24
  import { MuseAgentChatClient } from "./client.ts";
24
- import { loadConfig, PROFILE_PATH, safeConfig } from "./config.ts";
25
+ import { assertSafeParentDirectories, isSafeAgentId, loadConfig, PROFILE_PATH, safeConfig, validateEndpointUrl } from "./config.ts";
25
26
  import { shouldDispatch } from "./policy.ts";
26
27
  import { TypingHeartbeat } from "./typing.ts";
27
- import { appendWakeQueue, buildWakePayload, fireWake } from "./wake.ts";
28
+ import { appendWakeQueue, buildWakePayload, fireWake, redactSecrets, sanitizeMuseText } from "./wake.ts";
28
29
 
29
- function arg(name: string, argv: string[]): string | undefined {
30
+ function safeLogText(text: string): string {
31
+ return sanitizeMuseText(text);
32
+ }
33
+
34
+ const MAX_REGISTRATION_BYTES = 1024 * 1024;
35
+ const MUSE_CLI_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
36
+ const MUSE_CLI_PRETRIM_CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/;
37
+ const FORBIDDEN_CHANNEL_KEYS = new Set(["__proto__", "constructor", "prototype"]);
38
+
39
+ export interface MuseProfileFsOps {
40
+ renameSync?: typeof renameSync;
41
+ copyFileSync?: typeof copyFileSync;
42
+ }
43
+
44
+ export function validateMuseChannelId(value: string | undefined): string {
45
+ if (
46
+ typeof value !== "string" ||
47
+ !value ||
48
+ value.startsWith("--") ||
49
+ value.length > 128 ||
50
+ value === "." ||
51
+ value === ".." ||
52
+ value.includes("..") ||
53
+ /[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(value) ||
54
+ FORBIDDEN_CHANNEL_KEYS.has(value.toLowerCase()) ||
55
+ Object.getOwnPropertyNames(Object.prototype).some((k) => k.toLowerCase() === value.toLowerCase())
56
+ ) {
57
+ throw new Error("Invalid channel id");
58
+ }
59
+ return value;
60
+ }
61
+
62
+ async function readRegistrationBody(res: Response): Promise<string> {
63
+ if (!res.body) throw new Error("Registration response body is missing");
64
+ const reader = res.body.getReader();
65
+ const decoder = new TextDecoder("utf-8", { fatal: true });
66
+ let bytes = 0;
67
+ let body = "";
68
+ let complete = false;
69
+ try {
70
+ while (true) {
71
+ const { done, value } = await reader.read();
72
+ if (done) break;
73
+ bytes += value.byteLength;
74
+ if (bytes > MAX_REGISTRATION_BYTES) throw new Error("Registration response exceeds 1MiB limit");
75
+ body += decoder.decode(value, { stream: true });
76
+ }
77
+ body += decoder.decode();
78
+ complete = true;
79
+ return body;
80
+ } finally {
81
+ if (!complete) void reader.cancel().catch(() => {});
82
+ reader.releaseLock();
83
+ }
84
+ }
85
+
86
+ export function arg(name: string, argv: string[]): string | undefined {
30
87
  const i = argv.indexOf(name);
31
- return i >= 0 ? argv[i + 1] : undefined;
88
+ if (i < 0) return undefined;
89
+ const val = argv[i + 1];
90
+ return val !== undefined && !val.startsWith("--") ? val : undefined;
32
91
  }
33
92
  function has(name: string, argv: string[]): boolean {
34
93
  return argv.includes(name);
35
94
  }
36
95
 
37
- async function registerOnly(name: string, restUrl: string): Promise<void> {
96
+ export async function registerOnly(
97
+ name: string,
98
+ restUrl: string,
99
+ profilePath: string = PROFILE_PATH,
100
+ fetchImpl: typeof fetch = fetch,
101
+ fsOps: MuseProfileFsOps = {},
102
+ ): Promise<void> {
103
+ if (typeof name !== "string" || MUSE_CLI_PRETRIM_CTRL_RE.test(name)) {
104
+ throw new Error("Invalid --name value");
105
+ }
106
+ const cleanName = name.trim();
107
+ if (!cleanName || cleanName.length > 64 || MUSE_CLI_CTRL_RE.test(cleanName)) {
108
+ throw new Error("Invalid --name value");
109
+ }
110
+ const endpoint = validateEndpointUrl(restUrl, "rest");
111
+ const profileDir = dirname(profilePath);
112
+ assertSafeParentDirectories(profilePath);
113
+ mkdirSync(profileDir, { recursive: true, mode: 0o700 });
114
+ assertSafeParentDirectories(profilePath);
115
+ try {
116
+ const st = lstatSync(profilePath);
117
+ if (st.isSymbolicLink() || !st.isFile()) {
118
+ throw new Error("Refusing to overwrite symlink or non-regular Muse profile");
119
+ }
120
+ } catch (err) {
121
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
122
+ }
38
123
  console.log("Terms notice: https://agents-chat.com/terms (notice only, no acceptance prompt)");
39
- const res = await fetch(`${restUrl.replace(/\/$/, "")}/api/account/register`, {
124
+ const res = await fetchImpl(`${endpoint.replace(/\/$/, "")}/api/account/register`, {
40
125
  method: "POST",
41
126
  headers: { "content-type": "application/json" },
42
- body: JSON.stringify({ name, type: "agent", capabilities: ["chat"] }),
127
+ body: JSON.stringify({ name: cleanName, type: "agent", capabilities: ["chat"] }),
128
+ redirect: "error",
129
+ signal: AbortSignal.timeout(15_000),
43
130
  });
44
- if (!res.ok) throw new Error(`Registration failed: ${res.status} ${await res.text()}`);
45
- const data = (await res.json()) as Record<string, unknown>;
46
- const agentId = (data.agentId ?? data.agent_id ?? data.id) as string | undefined;
47
- const token = (data.agentKey ?? data.token ?? data.key) as string | undefined;
131
+ const responseBody = await readRegistrationBody(res);
132
+ if (!res.ok) {
133
+ const errBody = redactSecrets(responseBody).slice(0, 512);
134
+ throw new Error(`Registration failed: ${res.status} ${errBody}`);
135
+ }
136
+ const data = JSON.parse(responseBody) as Record<string, unknown>;
137
+ if (
138
+ !data ||
139
+ typeof data !== "object" ||
140
+ Array.isArray(data) ||
141
+ Object.getPrototypeOf(data) !== Object.prototype ||
142
+ Object.hasOwn(data, "__proto__")
143
+ ) {
144
+ throw new Error("Invalid registration response");
145
+ }
146
+ const rawAgentId = data.agentId ?? data.agent_id ?? data.id;
147
+ const rawToken = data.agentKey ?? data.token ?? data.key;
148
+ if (typeof rawAgentId !== "string" || typeof rawToken !== "string" || !rawAgentId || !rawToken) {
149
+ throw new Error("Registration response did not include an agent id/token");
150
+ }
151
+ if (MUSE_CLI_PRETRIM_CTRL_RE.test(rawAgentId) || MUSE_CLI_PRETRIM_CTRL_RE.test(rawToken)) {
152
+ throw new Error("Registration response contained unsafe agent id or token");
153
+ }
154
+ const agentId = rawAgentId.trim();
155
+ const token = rawToken.trim();
48
156
  if (!agentId || !token) throw new Error("Registration response did not include an agent id/token");
49
- mkdirSync(dirname(PROFILE_PATH), { recursive: true });
50
- writeFileSync(PROFILE_PATH, JSON.stringify({ agentId, token }, null, 2), { mode: 0o600 });
51
- console.log(`Registered agent '${name}' as ${agentId}. Identity saved to ${PROFILE_PATH} (token not printed).`);
157
+ if (!isSafeAgentId(agentId) || MUSE_CLI_CTRL_RE.test(token)) {
158
+ throw new Error("Registration response contained unsafe agent id or token");
159
+ }
160
+ const doRename = fsOps.renameSync ?? renameSync;
161
+ const doCopy = fsOps.copyFileSync ?? copyFileSync;
162
+ const tmp = `${profilePath}.${process.pid}.${Date.now()}.${randomBytes(6).toString("hex")}.tmp`;
163
+ try {
164
+ assertSafeParentDirectories(profilePath);
165
+ writeFileSync(tmp, JSON.stringify({ agentId, token }, null, 2), { mode: 0o600, flag: "wx" });
166
+ assertSafeParentDirectories(profilePath);
167
+ try {
168
+ const st = lstatSync(profilePath);
169
+ if (st.isSymbolicLink() || !st.isFile()) {
170
+ throw new Error("Refusing to overwrite symlink or non-regular Muse profile");
171
+ }
172
+ } catch (err) {
173
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
174
+ }
175
+ try {
176
+ doRename(tmp, profilePath);
177
+ } catch (renameErr) {
178
+ const code = (renameErr as NodeJS.ErrnoException)?.code;
179
+ if (code !== "EPERM" && code !== "EACCES") throw renameErr;
180
+ assertSafeParentDirectories(profilePath);
181
+ try {
182
+ const st = lstatSync(profilePath);
183
+ if (st.isSymbolicLink() || !st.isFile()) {
184
+ throw new Error("Refusing to overwrite symlink or non-regular Muse profile");
185
+ }
186
+ } catch (err) {
187
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
188
+ }
189
+ doCopy(tmp, profilePath);
190
+ try { unlinkSync(tmp); } catch {}
191
+ }
192
+ if (process.platform !== "win32") {
193
+ try { chmodSync(profilePath, 0o600); } catch {}
194
+ }
195
+ } catch (err) {
196
+ try { unlinkSync(tmp); } catch {}
197
+ throw err;
198
+ }
199
+ console.log(`Registered agent '${cleanName}' as ${agentId}. Identity saved to ${profilePath} (token not printed).`);
52
200
  }
53
201
 
54
- async function main(): Promise<void> {
55
- const argv = process.argv.slice(2);
202
+ export async function main(argv: string[] = process.argv.slice(2)): Promise<void> {
56
203
  if (has("--help", argv) || has("-h", argv)) {
57
204
  console.log("Usage: agentschat-mcp --muse --register-only --name <name> | --wake [--channel <id>...] | --listen [--channel <id>...] [--auto-reply <text>] | --send <channel-id> --text <text>");
58
205
  return;
@@ -64,8 +211,13 @@ async function main(): Promise<void> {
64
211
  await registerOnly(name, restUrl);
65
212
  return;
66
213
  }
214
+ for (let i = 0; i < argv.length; i++) {
215
+ if (argv[i] === "--channel" || argv[i] === "--send") {
216
+ validateMuseChannelId(argv[i + 1]);
217
+ }
218
+ }
67
219
  const config = loadConfig();
68
- console.log("Muse AgentsChat:", JSON.stringify(safeConfig(config)));
220
+ console.log("Muse AgentsChat:", safeLogText(JSON.stringify(safeConfig(config))));
69
221
  const client = new MuseAgentChatClient({
70
222
  url: config.wsUrl,
71
223
  agentId: config.agentId,
@@ -79,9 +231,10 @@ async function main(): Promise<void> {
79
231
  // Muse turn to pick up. Replying is the host turn's job.
80
232
  const wakeChannels: string[] = [];
81
233
  for (let i = 0; i < argv.length; i++) {
82
- if (argv[i] === "--channel" && argv[i + 1]) wakeChannels.push(argv[i + 1]);
234
+ if (argv[i] === "--channel" && argv[i + 1] && !argv[i + 1].startsWith("--")) wakeChannels.push(validateMuseChannelId(argv[i + 1]));
83
235
  }
84
- if (config.defaultChannelId) wakeChannels.push(config.defaultChannelId);
236
+ if (config.defaultChannelId) wakeChannels.push(validateMuseChannelId(config.defaultChannelId));
237
+ const uniqueWakeChannels = [...new Set(wakeChannels)];
85
238
  const queueFile =
86
239
  process.env.MUSE_WAKE_QUEUE ?? join(homedir(), ".agentschat", "muse-wake-queue.jsonl");
87
240
  const wakeUrl = process.env.MUSE_WAKE_URL ?? process.env.AGENTCHAT_WAKE_URL;
@@ -90,36 +243,49 @@ async function main(): Promise<void> {
90
243
  // so the UI shows "typing…" through the whole hook-poll + model-turn
91
244
  // wait; stop when our own reply appears on the socket (or at the cap).
92
245
  const typing = new TypingHeartbeat((channelId) => client.sendTyping(channelId));
93
- process.on("SIGINT", () => typing.stopAll());
246
+ const shutdownWake = () => {
247
+ typing.stopAll();
248
+ client.disconnect();
249
+ };
250
+ process.once("SIGINT", shutdownWake);
251
+ process.once("SIGTERM", shutdownWake);
252
+ if (process.platform !== "win32") process.once("SIGHUP", shutdownWake);
94
253
  client.onMessage((m) => {
95
254
  if (m.sender_id === config.agentId) {
96
255
  typing.stop(m.channel_id);
97
256
  return;
98
257
  }
99
- const kind = m.channel_id.startsWith("dm-") ? "direct" : "group";
258
+ const kind = /^dm[-:]/i.test(m.channel_id) ? "direct" : "group";
100
259
  if (!shouldDispatch(m, { agentId: config.agentId, displayName: config.displayName, channelKind: kind })) return;
101
260
  typing.start(m.channel_id);
102
261
  const payload = buildWakePayload({ ...m, type: "message" });
103
262
  const queued = appendWakeQueue(queueFile, payload);
104
- void fireWake({ ...m, type: "message" }, { url: wakeUrl, secret: wakeSecret, logger: console.error });
105
- console.log(`[wake] ${m.channel_id} ${m.sender_id} ${m.id} queued=${queued}`);
263
+ void fireWake({ ...m, type: "message" }, { url: wakeUrl, secret: wakeSecret, logger: (text) => console.error(safeLogText(text)) });
264
+ console.log(`[wake] ${safeLogText(m.channel_id)} ${safeLogText(m.sender_id)} ${safeLogText(m.id)} queued=${queued}`);
106
265
  });
107
266
  client.onReconnect = () => {
108
- for (const c of wakeChannels) client.joinChannel(c);
267
+ for (const c of uniqueWakeChannels) client.joinChannel(c);
109
268
  };
110
- await client.connect();
111
- for (const c of wakeChannels) client.joinChannel(c);
112
- console.log(`Wake daemon listening on ${wakeChannels.join(", ") || "(no channels — pass --channel <id>)"}, queue=${queueFile}. Press Ctrl+C to stop.`);
113
- await client.waitUntilClosed();
269
+ try {
270
+ await client.connect();
271
+ for (const c of uniqueWakeChannels) client.joinChannel(c);
272
+ console.log(`Wake daemon listening on ${safeLogText(uniqueWakeChannels.join(", ")) || "(no channels — pass --channel <id>)"}, queue=${safeLogText(queueFile)}. Press Ctrl+C to stop.`);
273
+ await client.waitUntilClosed();
274
+ } finally {
275
+ process.removeListener("SIGINT", shutdownWake);
276
+ process.removeListener("SIGTERM", shutdownWake);
277
+ if (process.platform !== "win32") process.removeListener("SIGHUP", shutdownWake);
278
+ }
114
279
  return;
115
280
  }
116
281
  if (has("--send", argv)) {
117
- const channelId = arg("--send", argv);
282
+ const channelId = validateMuseChannelId(arg("--send", argv));
118
283
  const text = arg("--text", argv);
119
284
  if (!channelId || !text) throw new Error("--send requires a channel id and --text <text>");
120
285
  await client.connect();
121
286
  client.joinChannel(channelId);
122
287
  client.sendMessage(channelId, text);
288
+ await new Promise((r) => setTimeout(r, 500));
123
289
  console.log(`Sent to ${channelId}`);
124
290
  client.disconnect();
125
291
  return;
@@ -127,29 +293,48 @@ async function main(): Promise<void> {
127
293
  // Default: --listen
128
294
  const channels: string[] = [];
129
295
  for (let i = 0; i < argv.length; i++) {
130
- if (argv[i] === "--channel" && argv[i + 1]) channels.push(argv[i + 1]);
296
+ if (argv[i] === "--channel" && argv[i + 1] && !argv[i + 1].startsWith("--")) channels.push(validateMuseChannelId(argv[i + 1]));
131
297
  }
132
- if (config.defaultChannelId) channels.push(config.defaultChannelId);
298
+ if (config.defaultChannelId) channels.push(validateMuseChannelId(config.defaultChannelId));
299
+ const uniqueChannels = [...new Set(channels)];
133
300
  const autoReply = arg("--auto-reply", argv);
134
301
  const bridge = new MuseBridge(client, {
135
302
  agentId: config.agentId,
136
303
  displayName: config.displayName,
137
- channels,
304
+ channels: uniqueChannels,
138
305
  responder: async (ctx) => {
139
- console.log(`[${ctx.message.channel_id}] ${ctx.message.sender_id}: ${ctx.message.content}`);
306
+ console.log(`[${safeLogText(ctx.message.channel_id)}] ${safeLogText(ctx.message.sender_id)}: ${safeLogText(ctx.message.content)}`);
140
307
  // Without a host responder, --auto-reply is the only reply path.
141
308
  // A real Muse host should inject its own responder via the API.
142
309
  return autoReply ?? null;
143
310
  },
144
311
  });
312
+ const shutdownListen = () => bridge.stop();
313
+ process.once("SIGINT", shutdownListen);
314
+ process.once("SIGTERM", shutdownListen);
315
+ if (process.platform !== "win32") process.once("SIGHUP", shutdownListen);
145
316
  // Re-join after reconnects.
146
317
  client.onReconnect = () => bridge.rejoin();
147
- await bridge.start();
148
- console.log(`Listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"}. Press Ctrl+C to stop.`);
149
- await client.waitUntilClosed();
318
+ try {
319
+ await bridge.start();
320
+ console.log(`Listening on ${safeLogText(uniqueChannels.join(", ")) || "(no channels — pass --channel <id>)"}. Press Ctrl+C to stop.`);
321
+ await client.waitUntilClosed();
322
+ } finally {
323
+ process.removeListener("SIGINT", shutdownListen);
324
+ process.removeListener("SIGTERM", shutdownListen);
325
+ if (process.platform !== "win32") process.removeListener("SIGHUP", shutdownListen);
326
+ }
150
327
  }
151
328
 
152
- main().catch((err: unknown) => {
153
- console.error(err instanceof Error ? err.message : String(err));
154
- process.exit(1);
155
- });
329
+ const entryPath = (process.argv[1] ?? "").replace(/\\/g, "/");
330
+ const invokedDirectly =
331
+ entryPath.endsWith("muse/src/cli.ts") ||
332
+ entryPath.endsWith("dist/muse.js") ||
333
+ process.argv.includes("--muse");
334
+
335
+ if (invokedDirectly) {
336
+ main().catch((err: unknown) => {
337
+ console.error(safeLogText(err instanceof Error ? err.message : String(err)));
338
+ process.exit(1);
339
+ });
340
+ }