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/muse/src/types.ts CHANGED
@@ -23,6 +23,7 @@ export interface MuseAgentChatOptions {
23
23
  token: string;
24
24
  capabilities?: string[];
25
25
  heartbeatIntervalMs?: number;
26
+ connectTimeoutMs?: number;
26
27
  reconnect?: boolean;
27
28
  initialReconnectDelayMs?: number;
28
29
  maxReconnectDelayMs?: number;
@@ -11,6 +11,8 @@
11
11
  */
12
12
  export const TYPING_HEARTBEAT_MS = 2_000;
13
13
  export const TYPING_HEARTBEAT_MAX_MS = 120_000;
14
+ export const MAX_TYPING_CHANNELS = 256;
15
+ const FORBIDDEN_TYPING_KEYS = new Set(["__proto__", "constructor", "prototype"]);
14
16
 
15
17
  export class TypingHeartbeat {
16
18
  private readonly timers = new Map<string, { interval: ReturnType<typeof setInterval>; cap: ReturnType<typeof setTimeout> }>();
@@ -29,11 +31,26 @@ export class TypingHeartbeat {
29
31
  }
30
32
 
31
33
  start(channelId: string): void {
32
- if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0") return;
34
+ if (
35
+ typeof channelId !== "string" ||
36
+ !channelId ||
37
+ channelId.length > 128 ||
38
+ /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(channelId) ||
39
+ FORBIDDEN_TYPING_KEYS.has(channelId.toLowerCase()) ||
40
+ process.env.AGENTSCHAT_AUTO_TYPING === "0"
41
+ ) {
42
+ return;
43
+ }
33
44
  this.stop(channelId); // reset if one is already running for this channel
45
+ if (this.timers.size >= MAX_TYPING_CHANNELS) {
46
+ const oldest = this.timers.keys().next().value;
47
+ if (oldest !== undefined) this.stop(oldest);
48
+ }
34
49
  this.pulse(channelId); // immediate first pulse
35
50
  const interval = setInterval(() => this.pulse(channelId), TYPING_HEARTBEAT_MS);
51
+ interval.unref?.();
36
52
  const cap = setTimeout(() => this.stop(channelId), TYPING_HEARTBEAT_MAX_MS);
53
+ cap.unref?.();
37
54
  this.timers.set(channelId, { interval, cap });
38
55
  }
39
56
 
package/muse/src/wake.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { createHmac, timingSafeEqual } from "node:crypto";
2
- import { appendFileSync, existsSync, readFileSync } from "node:fs";
1
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { appendFileSync, chmodSync, copyFileSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { assertSafeParentDirectories, isUnsafeEndpointHost } from "./config.ts";
3
5
 
4
6
  /**
5
7
  * Muse wake — the Grok Bot pattern, adapted for Muse.
@@ -58,42 +60,69 @@ export interface WakePayload {
58
60
 
59
61
  export function redactSecrets(text: string): string {
60
62
  return text
61
- .replace(/ac_[A-Za-z0-9_-]+/g, "[redacted]")
63
+ .replace(/-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\s\S]*?(?:-----END (?:[A-Z0-9]+ )*PRIVATE KEY-----|$)/g, "[redacted]")
64
+ .replace(/\b(https?:\/\/)([^/\s@]*@)/gi, "$1[redacted]@")
65
+ .replace(/\b(?:Bearer|Basic)\s+[^\s"'<>\\]+/gi, "[redacted]")
66
+ .replace(
67
+ /(?: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,
68
+ "[redacted]",
69
+ )
70
+ .replace(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, "[redacted]")
62
71
  .replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted]");
63
72
  }
64
73
 
74
+ /** Redact before stripping controls (PEM/header syntax), then catch joined fragments. */
75
+ export function sanitizeMuseText(text: string): string {
76
+ return redactSecrets(redactSecrets(text).replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, ""));
77
+ }
78
+
65
79
  export function buildWakePayload(
66
80
  msg: WakeMessage,
67
81
  opts: { targetSessionId?: string } = {},
68
82
  ): WakePayload {
69
- const content =
70
- typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX)) : undefined;
71
- const targetSessionId =
72
- typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
83
+ const clean = (value: unknown, cap = 128): string | undefined =>
84
+ typeof value === "string" ? sanitizeMuseText(value).slice(0, cap) : undefined;
85
+ const targetSessionId = clean(opts.targetSessionId);
73
86
  return {
74
- type: typeof msg.type === "string" ? msg.type : "message",
75
- channel_id: msg.channel_id,
76
- message_id: msg.id,
77
- sender_id: msg.sender_id,
78
- content,
79
- mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string") : undefined,
80
- timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined,
87
+ type: clean(msg.type, 64) ?? "message",
88
+ channel_id: clean(msg.channel_id),
89
+ message_id: clean(msg.id, 256),
90
+ sender_id: clean(msg.sender_id),
91
+ content: clean(msg.content, WAKE_CONTENT_MAX),
92
+ mentioned_ids: Array.isArray(msg.mentioned_ids)
93
+ ? msg.mentioned_ids.filter((x): x is string => typeof x === "string").slice(0, 256).map(x => clean(x)!)
94
+ : undefined,
95
+ timestamp: clean(msg.timestamp, 64),
81
96
  ...(targetSessionId ? { target_session_id: targetSessionId } : {}),
82
97
  };
83
98
  }
84
99
 
100
+ function sanitizeWakeLogUrl(rawUrl: string): string {
101
+ try {
102
+ const parsed = new URL(rawUrl);
103
+ parsed.username = "";
104
+ parsed.password = "";
105
+ parsed.search = "";
106
+ parsed.hash = "";
107
+ return parsed.toString();
108
+ } catch {
109
+ return redactSecrets(rawUrl.split(/[?#]/)[0] ?? "[invalid-url]");
110
+ }
111
+ }
112
+
85
113
  export function signWakeBody(body: string, secret: string): string {
86
114
  return createHmac("sha256", secret).update(body, "utf8").digest("hex");
87
115
  }
88
116
 
89
117
  export function verifyWakeSignature(body: string, sigHex: string, secrets: readonly string[]): boolean {
118
+ if (typeof sigHex !== "string" || !/^[0-9a-f]{64}$/i.test(sigHex)) return false;
90
119
  let sigBuf: Buffer;
91
120
  try {
92
121
  sigBuf = Buffer.from(sigHex, "hex");
93
122
  } catch {
94
123
  return false;
95
124
  }
96
- if (sigBuf.length === 0) return false;
125
+ if (sigBuf.length !== 32) return false;
97
126
  for (const secret of secrets) {
98
127
  if (!secret) continue;
99
128
  const expected = Buffer.from(signWakeBody(body, secret), "hex");
@@ -105,11 +134,15 @@ export function verifyWakeSignature(body: string, sigHex: string, secrets: reado
105
134
 
106
135
  /** Prompt text a Muse host can inject into a turn, mirroring buildGrokPrompt. */
107
136
  export function buildMuseWakePrompt(payload: WakePayload): string {
108
- const where = payload.channel_id?.startsWith("dm-") ? "私聊 (DM)" : `频道 ${payload.channel_id ?? "?"}`;
137
+ const clean = (value: string) => value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ").slice(0, 128);
138
+ const sender = clean(payload.sender_id ?? "someone");
139
+ const channel = clean(payload.channel_id ?? "?");
140
+ const message = clean(payload.message_id ?? "");
141
+ const where = /^dm[-:]/i.test(channel) ? "私聊 (DM)" : `频道 ${channel}`;
109
142
  const content = payload.content ? `:“${payload.content}”` : "。";
110
143
  return (
111
- `[AgentsChat] ${payload.sender_id ?? "someone"} 在${where}提到了你${content}` +
112
- (payload.message_id ? ` (channel_id=${payload.channel_id}, message_id=${payload.message_id},请用 bridge 回复;仅需更早历史时调 history)` : "")
144
+ `[AgentsChat] ${sender} 在${where}提到了你${content}` +
145
+ (payload.message_id ? ` (channel_id=${channel}, message_id=${message},请用 bridge 回复;仅需更早历史时调 history)` : "")
113
146
  );
114
147
  }
115
148
 
@@ -123,21 +156,76 @@ export interface WakeConfig {
123
156
  targetSessionId?: string;
124
157
  }
125
158
 
159
+ // Loopback receivers are intentional; remote non-public address literals are not.
160
+ function isUnsafeWakeHost(hostname: string): boolean {
161
+ if (isUnsafeEndpointHost(hostname)) return true;
162
+ const host = hostname.toLowerCase().replace(/\.$/, "");
163
+ if (["metadata.google.internal", "metadata.goog"].includes(host)) return true;
164
+ const unsafeV4 = (ip: string) => {
165
+ const [a, b] = ip.split(".").map(Number);
166
+ return a === 0 || a === 10 || a === 169 && b === 254 ||
167
+ a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a >= 224;
168
+ };
169
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return unsafeV4(host);
170
+ if (host.startsWith("[")) {
171
+ const address = host.slice(1, -1);
172
+ const [left, right = ""] = address.split("::");
173
+ const head = left ? left.split(":") : [];
174
+ const tail = right ? right.split(":") : [];
175
+ const words = address.includes("::")
176
+ ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail].map(x => parseInt(x, 16))
177
+ : head.map(x => parseInt(x, 16));
178
+ if (words.length !== 8) return true;
179
+ const mapped = (words.slice(0, 5).every(x => x === 0) && words[5] === 0xffff) ||
180
+ (words.slice(0, 4).every(x => x === 0) && words[4] === 0xffff && words[5] === 0);
181
+ if (mapped) return unsafeV4(`${words[6]! >> 8}.${words[6]! & 255}.${words[7]! >> 8}.${words[7]! & 255}`);
182
+ return words.every(x => x === 0) || (words[0]! & 0xffc0) === 0xfe80 ||
183
+ (words[0]! & 0xfe00) === 0xfc00 || (words[0]! & 0xff00) === 0xff00;
184
+ }
185
+ return false;
186
+ }
187
+
126
188
  /** POST a wake event. Best-effort: resolves void whether it succeeded or not. */
127
189
  export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void> {
128
- const log = cfg.logger ?? (() => {});
190
+ const log = (text: string) => cfg.logger?.(sanitizeMuseText(text));
129
191
  const url = (cfg.url ?? "").trim();
130
192
  if (!url) return;
131
- const body = JSON.stringify(buildWakePayload(msg, { targetSessionId: cfg.targetSessionId }));
193
+ const safeLogUrl = sanitizeWakeLogUrl(url);
194
+ let parsedUrl: URL;
195
+ try {
196
+ parsedUrl = new URL(url);
197
+ } catch {
198
+ log(`[muse-agentchat] wake POST rejected invalid URL: ${safeLogUrl}`);
199
+ return;
200
+ }
201
+ if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") {
202
+ log(`[muse-agentchat] wake POST rejected unsupported protocol: ${parsedUrl.protocol}`);
203
+ return;
204
+ }
205
+ if (parsedUrl.port === "0" || parsedUrl.username || parsedUrl.password || isUnsafeWakeHost(parsedUrl.hostname)) {
206
+ log(`[muse-agentchat] wake POST rejected unsafe URL: ${safeLogUrl}`);
207
+ return;
208
+ }
209
+ const timeoutMs =
210
+ typeof cfg.timeoutMs === "number" && Number.isFinite(cfg.timeoutMs) && cfg.timeoutMs >= 1
211
+ ? Math.min(cfg.timeoutMs, 60_000)
212
+ : 5_000;
213
+ const payload = buildWakePayload(msg, { targetSessionId: cfg.targetSessionId });
214
+ if (!payload.timestamp) payload.timestamp = new Date().toISOString();
215
+ const body = JSON.stringify(payload);
132
216
  const headers: Record<string, string> = { "Content-Type": "application/json" };
133
217
  if (cfg.secret) headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
134
218
  const doPost = async (): Promise<void> => {
135
219
  const f = cfg.fetchImpl ?? fetch;
136
220
  const ctrl = new AbortController();
137
- const t = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 5000);
221
+ const t = setTimeout(() => ctrl.abort(), timeoutMs);
222
+ t.unref?.();
138
223
  try {
139
- const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
140
- if (!res.ok) log(`[muse-agentchat] wake POST ${url} → HTTP ${res.status}`);
224
+ const res = await f(url, { method: "POST", headers, body, redirect: "error", signal: ctrl.signal });
225
+ try {
226
+ await (res as Response)?.body?.cancel?.();
227
+ } catch {}
228
+ if (!res.ok) log(`[muse-agentchat] wake POST ${safeLogUrl} → HTTP ${res.status}`);
141
229
  } finally {
142
230
  clearTimeout(t);
143
231
  }
@@ -148,29 +236,143 @@ export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void>
148
236
  try {
149
237
  await doPost();
150
238
  } catch (e2) {
151
- log(`[muse-agentchat] wake POST ${url} failed: ${e2}`);
239
+ log(`[muse-agentchat] wake POST ${safeLogUrl} failed: ${redactSecrets(String(e2))}`);
240
+ }
241
+ }
242
+ }
243
+
244
+ export const MAX_WAKE_QUEUE_LINES = 500;
245
+ export const MAX_WAKE_QUEUE_BYTES = 16 * 1024 * 1024;
246
+ let wakeTmpSeq = 0;
247
+
248
+ export interface AtomicWakeFsOps {
249
+ renameSync?: (oldPath: string, newPath: string) => void;
250
+ copyFileSync?: (src: string, dest: string) => void;
251
+ unlinkSync?: (path: string) => void;
252
+ }
253
+
254
+ export function atomicReplaceWakeFile(tmp: string, queueFile: string, fsOps?: AtomicWakeFsOps): void {
255
+ const renameFn = fsOps?.renameSync ?? renameSync;
256
+ const copyFn = fsOps?.copyFileSync ?? copyFileSync;
257
+ const unlinkFn = fsOps?.unlinkSync ?? unlinkSync;
258
+ assertSafeParentDirectories(queueFile);
259
+ try {
260
+ const st = lstatSync(queueFile);
261
+ if (st.isSymbolicLink() || !st.isFile()) {
262
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
263
+ }
264
+ } catch (err) {
265
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
266
+ }
267
+ try {
268
+ renameFn(tmp, queueFile);
269
+ } catch (renameErr) {
270
+ const code = (renameErr as NodeJS.ErrnoException)?.code;
271
+ if (code === "EPERM" || code === "EACCES") {
272
+ assertSafeParentDirectories(queueFile);
273
+ try {
274
+ const st = lstatSync(queueFile);
275
+ if (st.isSymbolicLink() || !st.isFile()) {
276
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
277
+ }
278
+ } catch (err) {
279
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
280
+ }
281
+ copyFn(tmp, queueFile);
282
+ if (process.platform !== "win32") {
283
+ try { chmodSync(queueFile, 0o600); } catch {}
284
+ }
285
+ try { unlinkFn(tmp); } catch {}
286
+ return;
152
287
  }
288
+ throw renameErr;
153
289
  }
154
290
  }
155
291
 
156
292
  /**
157
- * Append a wake payload to the queue file, deduplicated by message_id.
293
+ * Append a wake payload to the queue file, deduplicated by message_id,
294
+ * auto-creating missing parent directories (0700), enforcing private 0600
295
+ * file permissions, and bounding retained lines to MAX_WAKE_QUEUE_LINES.
158
296
  * Returns true if appended, false if it was already queued.
159
297
  */
160
- export function appendWakeQueue(queueFile: string, payload: WakePayload): boolean {
298
+ export function appendWakeQueue(
299
+ queueFile: string,
300
+ payload: WakePayload,
301
+ maxLines = MAX_WAKE_QUEUE_LINES,
302
+ fsOps?: AtomicWakeFsOps,
303
+ ): boolean {
304
+ const dir = dirname(queueFile);
305
+ assertSafeParentDirectories(queueFile);
306
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
307
+ assertSafeParentDirectories(queueFile);
161
308
  const line = JSON.stringify(payload);
162
- if (payload.message_id && existsSync(queueFile)) {
309
+ let existingLines: string[] = [];
310
+ let existedBefore = false;
311
+ try {
312
+ const st = lstatSync(queueFile);
313
+ if (st.isSymbolicLink() || !st.isFile()) {
314
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
315
+ }
316
+ if (st.size > MAX_WAKE_QUEUE_BYTES) {
317
+ throw new Error("Muse wake queue exceeds maximum size limit");
318
+ }
319
+ existedBefore = true;
320
+ } catch (err) {
321
+ if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
322
+ }
323
+ if (existedBefore) {
163
324
  const existing = readFileSync(queueFile, "utf8");
164
- if (existing.split("\n").some((l) => {
165
- try {
166
- return (JSON.parse(l) as WakePayload).message_id === payload.message_id;
167
- } catch {
168
- return false;
169
- }
170
- })) {
325
+ existingLines = existing.split("\n").filter((l) => l.length > 0);
326
+ if (
327
+ payload.message_id &&
328
+ existingLines.some((l) => {
329
+ try {
330
+ return (JSON.parse(l) as WakePayload).message_id === payload.message_id;
331
+ } catch {
332
+ return false;
333
+ }
334
+ })
335
+ ) {
171
336
  return false;
172
337
  }
173
338
  }
174
- appendFileSync(queueFile, line + "\n");
339
+ const cap = Number.isFinite(maxLines) ? Math.max(1, Math.floor(maxLines)) : MAX_WAKE_QUEUE_LINES;
340
+ if (existingLines.length >= cap) {
341
+ const kept = [...(cap === 1 ? [] : existingLines.slice(-(cap - 1))), line];
342
+ const tmp = `${queueFile}.${process.pid}.${Date.now()}.${++wakeTmpSeq}.${randomBytes(6).toString("hex")}.tmp`;
343
+ try {
344
+ assertSafeParentDirectories(queueFile);
345
+ writeFileSync(tmp, `${kept.join("\n")}\n`, { mode: 0o600, flag: "wx" });
346
+ atomicReplaceWakeFile(tmp, queueFile, fsOps);
347
+ } catch (err) {
348
+ try { unlinkSync(tmp); } catch {}
349
+ throw err;
350
+ }
351
+ return true;
352
+ }
353
+ if (!existedBefore) {
354
+ try {
355
+ writeFileSync(queueFile, `${line}\n`, { mode: 0o600, flag: "wx" });
356
+ if (process.platform !== "win32") {
357
+ try { chmodSync(queueFile, 0o600); } catch {}
358
+ }
359
+ return true;
360
+ } catch (err) {
361
+ if ((err as NodeJS.ErrnoException)?.code !== "EEXIST") throw err;
362
+ const st = lstatSync(queueFile);
363
+ if (st.isSymbolicLink() || !st.isFile()) {
364
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
365
+ }
366
+ if (st.size > MAX_WAKE_QUEUE_BYTES) {
367
+ throw new Error("Muse wake queue exceeds maximum size limit");
368
+ }
369
+ }
370
+ }
371
+ assertSafeParentDirectories(queueFile);
372
+ const finalTarget = lstatSync(queueFile);
373
+ if (finalTarget.isSymbolicLink() || !finalTarget.isFile()) {
374
+ throw new Error("Refusing to use symlink or non-regular file for Muse wake queue");
375
+ }
376
+ appendFileSync(queueFile, `${line}\n`, { mode: 0o600 });
175
377
  return true;
176
378
  }
@@ -49,3 +49,134 @@ test("own messages and null replies stay silent", async () => {
49
49
  await bridge.handleMessage(msg({ channel_id: "dm1" }));
50
50
  assert.deepEqual(sent, []);
51
51
  });
52
+
53
+ test("responder failure still stops typing indicator in finally", async () => {
54
+ const client = new MuseAgentChatClient({ url: "ws://127.0.0.1:1", agentId: "muse-bot", token: "x" });
55
+ let typingFrames = 0;
56
+ client.sendTyping = () => {
57
+ typingFrames += 1;
58
+ };
59
+ const bridge = new MuseBridge(client, {
60
+ agentId: "muse-bot",
61
+ channels: ["dm1"],
62
+ channelKinds: { dm1: "direct" },
63
+ responder: async () => {
64
+ throw new Error("llm_down");
65
+ },
66
+ });
67
+ await assert.rejects(() => bridge.handleMessage(msg({ channel_id: "dm1", content: "ping" })), /llm_down/);
68
+ assert.equal(typingFrames, 1);
69
+ // Wait longer than typing interval safeguard or verify stopAll leaves 0 active timers
70
+ bridge.stop();
71
+ });
72
+
73
+ test("Campaign #93: MuseAgentChatClient ignores __typing__ frames and MuseBridge forwards thread_id as reply_to", async () => {
74
+ const client = new MuseAgentChatClient({ url: "ws://127.0.0.1:1", agentId: "muse-bot", token: "x" });
75
+ const sent = [];
76
+ client.sendMessage = (channelId, content, contentType, replyTo) =>
77
+ sent.push({ channelId, content, contentType, replyTo });
78
+ let capturedHistory = [];
79
+ const bridge = new MuseBridge(client, {
80
+ agentId: "muse-bot",
81
+ channels: ["general"],
82
+ channelKinds: { general: "group" },
83
+ responder: async (ctx) => {
84
+ capturedHistory = ctx.history;
85
+ return "threaded-reply";
86
+ },
87
+ });
88
+
89
+ // Feed 60 ephemeral __typing__ frames over the client wire parser; none should enter bridge history!
90
+ for (let i = 0; i < 60; i++) {
91
+ client.handleMessage(
92
+ JSON.stringify({
93
+ type: "message",
94
+ id: `t-${i}`,
95
+ channel_id: "general",
96
+ sender_id: "alice",
97
+ content: "__typing__",
98
+ }),
99
+ );
100
+ }
101
+ await bridge.handleMessage(msg({ id: "real-1", content: "context line" }));
102
+ await bridge.handleMessage(msg({ id: "tr-2", content: "hey @muse-bot", thread_id: "root-msg-1" }));
103
+ assert.equal(capturedHistory.length, 2);
104
+ assert.equal(sent.length, 1);
105
+ assert.equal(sent[0].replyTo, "root-msg-1");
106
+ });
107
+
108
+ for (const firstFails of [false, true]) {
109
+ test(`concurrent replies keep channel typing until the last settles (failure=${firstFails})`, async () => {
110
+ const client = new MuseAgentChatClient({ url: "ws://localhost:1", agentId: "muse-bot", token: "x" });
111
+ const sent = [];
112
+ client.sendTyping = () => {};
113
+ client.sendMessage = (channelId, content) => sent.push({ channelId, content });
114
+ const pending = new Map();
115
+ const bridge = new MuseBridge(client, {
116
+ agentId: "muse-bot", channels: [], channelKinds: { dm1: "direct", general: "group" },
117
+ responder: ({ message }) => new Promise((resolve, reject) => pending.set(message.id, { resolve, reject })),
118
+ });
119
+ const starts = [];
120
+ const stops = [];
121
+ const start = bridge.typing.start.bind(bridge.typing);
122
+ const stop = bridge.typing.stop.bind(bridge.typing);
123
+ bridge.typing.start = (ch) => { starts.push(ch); start(ch); };
124
+ bridge.typing.stop = (ch) => { stops.push(ch); stop(ch); };
125
+ try {
126
+ const one = bridge.handleMessage(msg({ id: "one", channel_id: "dm1" }));
127
+ const two = bridge.handleMessage(msg({ id: "two", channel_id: "dm1" }));
128
+ const other = bridge.handleMessage(msg({ id: "other", content: "@muse-bot" }));
129
+ assert.deepEqual(starts, ["dm1", "general"]);
130
+ // start() itself calls stop() to reset a prior heartbeat.
131
+ stops.length = 0;
132
+ assert.equal(bridge.typing.timers.size, 2);
133
+ if (firstFails) {
134
+ const rejected = assert.rejects(one, /responder failed/);
135
+ pending.get("one").reject(new Error("responder failed"));
136
+ await rejected;
137
+ } else {
138
+ pending.get("one").resolve("first");
139
+ await one;
140
+ }
141
+ assert.deepEqual(stops, []);
142
+ assert.equal(bridge.typing.timers.has("dm1"), true);
143
+ pending.get("other").resolve(null);
144
+ await other;
145
+ assert.deepEqual(stops, ["general"]);
146
+ assert.equal(bridge.typing.timers.has("dm1"), true);
147
+ pending.get("two").resolve("second");
148
+ await two;
149
+ assert.deepEqual(stops, ["general", "dm1"]);
150
+ assert.equal(bridge.typing.timers.size, 0);
151
+ assert.equal(bridge.activeReplies.size, 0);
152
+ assert.equal(sent.at(-1).content, "second");
153
+ } finally {
154
+ bridge.stop();
155
+ }
156
+ });
157
+ }
158
+
159
+ test("direct bridge typing frames never enter history or dispatch; stop clears active reply counts", async () => {
160
+ const client = new MuseAgentChatClient({ url: "ws://localhost:1", agentId: "muse-bot", token: "x" });
161
+ client.sendTyping = () => {};
162
+ let finish;
163
+ let history;
164
+ const bridge = new MuseBridge(client, {
165
+ agentId: "muse-bot", channels: [], channelKinds: { dm1: "direct" },
166
+ responder: (ctx) => { history = ctx.history; return new Promise((resolve) => { finish = resolve; }); },
167
+ });
168
+ for (let i = 0; i < 60; i++) {
169
+ await bridge.handleMessage(msg({ id: `typing-${i}`, channel_id: "dm1", content: "__typing__" }));
170
+ }
171
+ assert.equal(bridge.history.size, 0);
172
+ assert.equal(history, undefined);
173
+ const reply = bridge.handleMessage(msg({ id: "real", channel_id: "dm1" }));
174
+ assert.deepEqual(history.map((m) => m.id), ["real"]);
175
+ assert.equal(bridge.activeReplies.get("dm1"), 1);
176
+ bridge.stop();
177
+ assert.equal(bridge.activeReplies.size, 0);
178
+ assert.equal(bridge.typing.timers.size, 0);
179
+ finish(null);
180
+ await reply;
181
+ assert.equal(bridge.activeReplies.size, 0);
182
+ });