agentschat-mcp 0.36.25 → 0.36.27

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 (86) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +10 -10
  3. package/codex/README.md +4 -4
  4. package/codex/app-server.ts +101 -22
  5. package/codex/bots-config.ts +32 -11
  6. package/codex/bridge.ts +127 -28
  7. package/codex/config.ts +137 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +77 -12
  10. package/codex/loop-grants.ts +49 -11
  11. package/codex/manager.ts +108 -27
  12. package/codex/owner.ts +106 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +51 -11
  16. package/codex/thread-history.ts +87 -30
  17. package/codex/transport.ts +135 -22
  18. package/connector/README.md +1 -1
  19. package/connector/auth.ts +57 -5
  20. package/connector/backfill.ts +92 -10
  21. package/connector/descriptor.ts +27 -1
  22. package/connector/identities.ts +82 -14
  23. package/connector/ingest.ts +11 -2
  24. package/connector/normalize.ts +32 -12
  25. package/connector/run.ts +314 -67
  26. package/connector/server.ts +95 -26
  27. package/cordis.patch.yml +4 -2
  28. package/dist/codex-bots.js +437 -75
  29. package/dist/codex-bridge.js +2111 -582
  30. package/dist/connector.js +1300 -493
  31. package/dist/dsh.js +1789 -299
  32. package/dist/muse.js +967 -221
  33. package/dist/server.js +4410 -919
  34. package/dsh/README.md +1 -1
  35. package/dsh/client.js +7 -5
  36. package/dsh/identity-ui/client.js +7 -5
  37. package/dsh/identity-ui/index.js +43 -8
  38. package/dsh/inbound-bridge/index.js +677 -154
  39. package/dsh/src/cli.ts +430 -91
  40. package/dsh/src/patch.ts +295 -15
  41. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  42. package/dsh/tests/dsh.test.ts +1174 -3
  43. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  44. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  45. package/muse/src/bridge.ts +54 -13
  46. package/muse/src/cli.ts +226 -41
  47. package/muse/src/client.ts +249 -34
  48. package/muse/src/config.ts +128 -12
  49. package/muse/src/policy.ts +28 -8
  50. package/muse/src/types.ts +1 -0
  51. package/muse/src/typing.ts +18 -1
  52. package/muse/src/wake.ts +237 -35
  53. package/muse/tests/bridge.test.mjs +131 -0
  54. package/muse/tests/client.test.mjs +327 -0
  55. package/muse/tests/config.test.mjs +78 -1
  56. package/muse/tests/hardening.test.mjs +199 -0
  57. package/muse/tests/hardening126.test.mjs +292 -0
  58. package/muse/tests/policy.test.mjs +83 -1
  59. package/muse/tests/wake.test.mjs +134 -6
  60. package/package.json +3 -3
  61. package/scripts/ensure-grok-wakes.mjs +93 -8
  62. package/scripts/example-url-wake-receiver.mjs +254 -61
  63. package/scripts/grok-bind-register.sh +38 -8
  64. package/skills/onboarding.md +15 -15
  65. package/src/argcheck.ts +113 -33
  66. package/src/cli.mjs +100 -16
  67. package/src/dedup.ts +57 -8
  68. package/src/grok-bind.ts +182 -33
  69. package/src/heartbeat.ts +39 -11
  70. package/src/identity-guard.ts +93 -20
  71. package/src/identity.ts +67 -11
  72. package/src/mentions.ts +26 -5
  73. package/src/onboarding-status.ts +134 -11
  74. package/src/profile-selection.ts +299 -18
  75. package/src/profile-store.ts +248 -30
  76. package/src/read-cursor.ts +280 -9
  77. package/src/reconnect.ts +98 -2
  78. package/src/redact.ts +34 -15
  79. package/src/rest-cli.ts +713 -159
  80. package/src/server.ts +286 -94
  81. package/src/session-bind.ts +777 -134
  82. package/src/session-route.ts +183 -12
  83. package/src/team-lead-skill.ts +3 -0
  84. package/src/timestamps.ts +56 -23
  85. package/src/tool-annotations.ts +10 -1
  86. package/src/wake.ts +510 -91
package/src/server.ts CHANGED
@@ -44,7 +44,12 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
44
44
  import { isHumanPiiHandle, redactParticipantPii, redactSecrets } from "./redact.ts";
45
45
  import { matchesMention } from "./mentions.ts";
46
46
  import { messageDedupKey, MessageDedup } from "./dedup.ts";
47
- import { computeReconnectDelay } from "./reconnect.ts";
47
+ import {
48
+ computePleaseReconnectDelay,
49
+ computeReconnectDelay,
50
+ resolveDrainReconnectDelay,
51
+ withTimeoutController,
52
+ } from "./reconnect.ts";
48
53
  import { normalizeTimestampForCursor } from "./timestamps.ts";
49
54
  import {
50
55
  CREATE_LOOP_MODES,
@@ -92,6 +97,7 @@ import {
92
97
  resolveGrokBindsPath,
93
98
  DEFAULT_GROK_BINDS_FILENAME,
94
99
  boundProfileForConversation,
100
+ gateGrokProfileMutation,
95
101
  gateSwitchProfile,
96
102
  grokBindApplies,
97
103
  nonGrokWakeReason,
@@ -142,6 +148,7 @@ import {
142
148
 
143
149
  // --- Config: CLI args > env vars > profile file > defaults ---
144
150
  import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from "fs";
151
+ import { homedir } from "os";
145
152
  import { join, dirname } from "path";
146
153
  import { fileURLToPath } from "url";
147
154
  // Atomic + 0600-by-construction profile writer. Lives in its own module so the
@@ -160,7 +167,7 @@ import {
160
167
  type IdentityGuardRecord,
161
168
  } from "./identity-guard.ts";
162
169
  // Read-cursor persistence: a state change that merely *lives* in the teardown path.
163
- import { flushCursor, loadCursor, persistCursor } from "./read-cursor.ts";
170
+ import { cursorFileForAgent, flushCursor, loadCursor, persistCursor } from "./read-cursor.ts";
164
171
  import { CURSOR_INIT_KEY, joinChannelRest, parseMaxIdleMs, sendRestMessage, wakeOnce } from "./rest-cli.ts";
165
172
  import { randomUUID } from "crypto";
166
173
 
@@ -184,7 +191,7 @@ function parseArgs() {
184
191
  ]);
185
192
  for (let i = 0; i < args.length; i++) {
186
193
  const arg = args[i];
187
- if (arg === "--help" || arg === "-h") continue;
194
+ if (arg === "--help" || arg === "-h" || arg === "--version" || arg === "-v") continue;
188
195
  if (arg === "--register") { parsed.register = "1"; continue; }
189
196
  if (arg === "--register-only") { parsed.registerOnly = "1"; continue; }
190
197
  if (arg === "--wake-once") { parsed.wakeOnce = "1"; continue; }
@@ -208,6 +215,11 @@ function parseArgs() {
208
215
  const cliArgs = parseArgs();
209
216
  const isOneShotCli = Boolean(cliArgs.registerOnly || cliArgs.join || cliArgs.send || cliArgs.wakeOnce);
210
217
 
218
+ if (process.argv.includes("--version") || process.argv.includes("-v")) {
219
+ console.log(`agentschat-mcp v${pkg.version}`);
220
+ process.exit(0);
221
+ }
222
+
211
223
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
212
224
  const localOnboardingPath = join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
213
225
  console.log(`agentschat-mcp v${pkg.version} — AgentsChat MCP and host bridges
@@ -237,8 +249,8 @@ Options:
237
249
  --reply-to <id> Optional target message ID for --send.
238
250
  --wake-once Wait via HTTPS SSE + REST cursor for the next @mention or DM, print wake JSON + prompt, advance per-channel cursor, and exit 0.
239
251
  --channel <ids> Comma-separated channels to join/watch with --wake-once (default: welcome + all joined channels).
240
- --timeout <sec> Max wait time in seconds per --wake-once window (default: 240).
241
- --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: 3600 = 1 hour).
252
+ --timeout <sec> Max wait time in seconds per --wake-once window (default: 240; pass 0 to listen continuously).
253
+ --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: never / 0; e.g. 1h, 3h, never).
242
254
  --accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
243
255
  No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
244
256
  --id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
@@ -247,6 +259,7 @@ Options:
247
259
  explicitly selected profile. Skips registration entirely.
248
260
  --caps <a,b,c> Capabilities (comma-separated)
249
261
  --supervise Respawn on crash (or AGENTCHAT_WAKE_SUPERVISE=1); for wake daemons
262
+ -v, --version Print package version and exit
250
263
  -h, --help Show this help
251
264
 
252
265
  Wake a host that has no channel-notification surface (Grok Bot, generic MCP clients):
@@ -279,7 +292,7 @@ project/runtime binding or default profile is loaded; only when none exists and
279
292
  credentials are supplied does the server run ANONYMOUS (lists tools, no account).
280
293
 
281
294
  Profiles stored in: ~/.agentschat/ (legacy fallback: ~/.agentchat/)
282
- Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
295
+ Docs: https://github.com/swswordholy-tech/AgentsChat`);
283
296
  process.exit(0);
284
297
  }
285
298
 
@@ -304,7 +317,7 @@ if (codexIdentity) {
304
317
  delete process.env.AGENTCHAT_TOKEN;
305
318
  process.env.AGENTSCHAT_EXPECT_AGENT_ID = codexIdentity.agentId;
306
319
  }
307
- const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
320
+ const homeDir = process.env.HOME || process.env.USERPROFILE || homedir() || ".";
308
321
  const configDir = join(homeDir, ".agentschat");
309
322
  const legacyConfigDir = join(homeDir, ".agentchat");
310
323
  const profileDirs = [configDir, legacyConfigDir];
@@ -326,15 +339,16 @@ let dshRouteWarned = false;
326
339
  function profileNameToPaths(name: string): string[] {
327
340
  if (name.startsWith("~/")) return [join(homeDir, name.slice(2))];
328
341
  if (name.includes("/") || name.includes("\\")) return [name]; // explicit path
329
- name = name.replace(/\.json$/, "");
342
+ name = name.replace(/\.json$/i, "");
330
343
  const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
331
344
  return profileDirs.map((dir) => join(dir, `${safeName}.json`));
332
345
  }
333
346
 
334
347
  function nameToPath(name: string): string {
335
348
  const candidates = profileNameToPaths(name);
336
- const nested = join(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
337
- if (!name.includes("/") && !name.includes("\\") && existsSync(nested)) return nested;
349
+ const safeBase = name.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
350
+ const nested = join(configDir, "profiles", safeBase + ".json");
351
+ if (!name.includes("/") && !name.includes("\\") && safeBase && existsSync(nested)) return nested;
338
352
  return candidates.find((path) => existsSync(path)) || candidates[0];
339
353
  }
340
354
 
@@ -343,15 +357,16 @@ function listProfileFiles(): Array<{ name: string; path: string }> {
343
357
  const profiles: Array<{ name: string; path: string }> = [];
344
358
  for (const dir of [join(configDir, "profiles"), ...profileDirs]) {
345
359
  let files: string[] = [];
346
- try { files = readdirSync(dir).filter((f: string) => f.endsWith(".json")); } catch {}
360
+ try { files = readdirSync(dir).filter((f: string) => /\.json$/i.test(f)); } catch {}
347
361
  for (const file of files) {
362
+ const lowerFile = file.toLowerCase();
348
363
  if (
349
- file === DEFAULT_GROK_BINDS_FILENAME ||
350
- file === GROK_BINDS_META_FILENAME ||
351
- file === DEFAULT_SESSION_BINDS_FILENAME ||
352
- file === LEGACY_AGY_BINDS_FILENAME
364
+ lowerFile === DEFAULT_GROK_BINDS_FILENAME.toLowerCase() ||
365
+ lowerFile === GROK_BINDS_META_FILENAME.toLowerCase() ||
366
+ lowerFile === DEFAULT_SESSION_BINDS_FILENAME.toLowerCase() ||
367
+ lowerFile === LEGACY_AGY_BINDS_FILENAME.toLowerCase()
353
368
  ) continue; // bind map, not a profile
354
- const name = file.replace(/\.json$/, "");
369
+ const name = file.replace(/\.json$/i, "");
355
370
  if (seen.has(name)) continue;
356
371
  seen.add(name);
357
372
  profiles.push({ name, path: join(dir, file) });
@@ -494,17 +509,16 @@ async function apiFetch(
494
509
  const wakeId = resolveEnvWakeId();
495
510
  if (wakeId) headers[WAKE_ID_HEADER] = wakeId;
496
511
  }
497
- const controller = new AbortController();
498
- const timer = setTimeout(() => controller.abort(), timeoutMs);
512
+ const { signal, cleanup } = withTimeoutController(init.signal, timeoutMs);
499
513
  try {
500
- const response = await nativeFetch(input as any, { ...init, headers, signal: init.signal ?? controller.signal });
514
+ const response = await nativeFetch(input as any, { ...init, headers, signal });
501
515
  if (!bufferBody) return response;
502
516
  // Keep the abort deadline active until the body is consumed. Headers alone
503
517
  // must not mark a stalled JSON response as complete.
504
518
  const body = await response.text();
505
519
  return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });
506
520
  } finally {
507
- clearTimeout(timer);
521
+ cleanup();
508
522
  }
509
523
  }
510
524
 
@@ -942,7 +956,7 @@ if (TOKEN && TOKEN !== "dev-token") {
942
956
  if (cliArgs.registerOnly) {
943
957
  try {
944
958
  mkdirSync(configDir, { recursive: true });
945
- const lastSeenFile = join(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
959
+ const lastSeenFile = cursorFileForAgent(configDir, AGENT_ID);
946
960
  const cursor = loadCursor(lastSeenFile, (m) => process.stderr.write(m));
947
961
  if (!cursor.get(CURSOR_INIT_KEY)) {
948
962
  cursor.set(CURSOR_INIT_KEY, new Date().toISOString());
@@ -995,6 +1009,8 @@ function startTypingHeartbeat(channelId: string, slot: ProfileSlot | null = acti
995
1009
  sendTypingFrame(channelId, slot); // immediate first pulse
996
1010
  const interval = setInterval(() => sendTypingFrame(channelId, slot), TYPING_HEARTBEAT_MS);
997
1011
  const cap = setTimeout(() => stopTypingHeartbeat(channelId, slot), TYPING_HEARTBEAT_MAX_MS);
1012
+ (interval as any).unref?.();
1013
+ (cap as any).unref?.();
998
1014
  typingHeartbeats.set(typingHeartbeatKey(channelId, agentId), { interval, cap });
999
1015
  }
1000
1016
  function stopTypingHeartbeat(channelId: string, slot: ProfileSlot | null = activeSlot) {
@@ -2536,26 +2552,97 @@ const TOOL_INPUT_SCHEMAS: Map<string, any> = new Map(
2536
2552
  * a newly-joined member's display_name would be resolvable.
2537
2553
  */
2538
2554
  const MEMBER_CACHE_TTL_MS = 5 * 60_000;
2555
+ const MEMBER_CACHE_MAX_ENTRIES = 512;
2556
+ const RESERVED_MCP_ROUTE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
2539
2557
  const memberCache = new Map<string, { at: number; members: { agent_id: string; display_name?: string }[]; sameOwnerDirect?: boolean }>();
2540
2558
 
2559
+ function isSafeChannelRouteId(raw: unknown): raw is string {
2560
+ if (typeof raw !== "string") return false;
2561
+ const trimmed = raw.trim();
2562
+ if (!trimmed || trimmed.length > 256) return false;
2563
+ if (/[\x00-\x1f\x7f-\x9f\\?#]/.test(trimmed)) return false;
2564
+ if (/%2f|%5c|%00|%2e%2e/i.test(trimmed)) return false;
2565
+ if (/^(?:ac_|sk-|mcp_(?:at|rt|code)_|agent_key_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-)/i.test(trimmed)) {
2566
+ return false;
2567
+ }
2568
+ const segments = trimmed.split("/");
2569
+ for (const seg of segments) {
2570
+ if (!seg || seg === "." || seg === ".." || RESERVED_MCP_ROUTE_KEYS.has(seg.toLowerCase())) {
2571
+ return false;
2572
+ }
2573
+ }
2574
+ return true;
2575
+ }
2576
+
2577
+ function isSafeProposalRouteId(raw: unknown): raw is string {
2578
+ if (typeof raw !== "string") return false;
2579
+ const trimmed = raw.trim();
2580
+ if (!trimmed || trimmed.length > 128) return false;
2581
+ if (trimmed === "." || trimmed.includes("..") || RESERVED_MCP_ROUTE_KEYS.has(trimmed.toLowerCase())) {
2582
+ return false;
2583
+ }
2584
+ if (/[\x00-\x1f\x7f-\x9f/\\?#%]/.test(trimmed)) return false;
2585
+ return true;
2586
+ }
2587
+
2588
+ function scrubMcpHandlerError(raw: unknown, maxLen = 180): string {
2589
+ const base = redactSecrets(String((raw as { message?: unknown })?.message || raw || "error").slice(0, 4096));
2590
+ return base
2591
+ .replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer [REDACTED]")
2592
+ .replace(/\bBasic\s+[A-Za-z0-9+/=_-]{8,}/gi, "Basic [REDACTED]")
2593
+ .replace(/([a-z][a-z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/gi, "$1[REDACTED]@")
2594
+ .replace(/[\x00-\x1f\x7f-\x9f]+/g, " ")
2595
+ .trim()
2596
+ .slice(0, Math.max(1, maxLen));
2597
+ }
2598
+
2599
+ function parseSafeJsonObject(raw: string): any {
2600
+ const parsed = JSON.parse(raw);
2601
+ if (parsed && typeof parsed === "object" && Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
2602
+ throw new Error("Invalid JSON response object");
2603
+ }
2604
+ return parsed;
2605
+ }
2606
+
2607
+ function setBoundedMemberCache(
2608
+ key: string,
2609
+ entry: { at: number; members: { agent_id: string; display_name?: string }[]; sameOwnerDirect?: boolean },
2610
+ ): void {
2611
+ if (!memberCache.has(key) && memberCache.size >= MEMBER_CACHE_MAX_ENTRIES) {
2612
+ for (const [k, v] of memberCache.entries()) {
2613
+ if (entry.at - v.at >= MEMBER_CACHE_TTL_MS) memberCache.delete(k);
2614
+ }
2615
+ if (memberCache.size >= MEMBER_CACHE_MAX_ENTRIES) {
2616
+ const oldest = memberCache.keys().next().value;
2617
+ if (oldest !== undefined) memberCache.delete(oldest);
2618
+ }
2619
+ }
2620
+ memberCache.set(key, entry);
2621
+ }
2622
+
2541
2623
  function memberCacheKey(chatId: string): string {
2542
2624
  return `${AGENT_ID || "anon"}:${chatId}`;
2543
2625
  }
2544
2626
 
2545
2627
  async function fetchChannelMembers(chatId: string): Promise<{ agent_id: string; display_name?: string }[]> {
2628
+ const normalizedChatId = typeof chatId === "string" ? chatId.trim() : "";
2629
+ if (!isSafeChannelRouteId(normalizedChatId)) return [];
2546
2630
  const now = Date.now();
2547
- const key = memberCacheKey(chatId);
2631
+ const key = memberCacheKey(normalizedChatId);
2548
2632
  const hit = memberCache.get(key);
2549
2633
  if (hit && now - hit.at < MEMBER_CACHE_TTL_MS) return hit.members;
2550
2634
  try {
2551
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/members`, {
2635
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(normalizedChatId)}/members`, {
2552
2636
  headers: { "Authorization": `Bearer ${TOKEN}` },
2553
2637
  });
2554
2638
  if (!r.ok) return hit?.members || [];
2555
2639
  const body = await r.json() as any;
2640
+ if (body && typeof body === "object" && Object.prototype.hasOwnProperty.call(body, "__proto__")) {
2641
+ return hit?.members || [];
2642
+ }
2556
2643
  const members = Array.isArray(body?.members) ? body.members : [];
2557
2644
  const sameOwnerDirect = body?.same_owner_direct === true;
2558
- memberCache.set(key, { at: now, members, sameOwnerDirect });
2645
+ setBoundedMemberCache(key, { at: now, members, sameOwnerDirect });
2559
2646
  return members;
2560
2647
  } catch {
2561
2648
  return hit?.members || [];
@@ -2654,16 +2741,19 @@ HANDLERS.set("okr_reparent_objective", async (args) => {
2654
2741
  });
2655
2742
  const text = await r.text();
2656
2743
  if (!r.ok) {
2657
- return { content: [{ type: "text", text: `okr_reparent_objective failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2744
+ return { content: [{ type: "text", text: `okr_reparent_objective failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2658
2745
  }
2659
2746
  return { content: [{ type: "text", text: `Reparented: ${text}` }] };
2660
2747
  } catch (e: any) {
2661
- return { content: [{ type: "text", text: `okr_reparent_objective network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2748
+ return { content: [{ type: "text", text: `okr_reparent_objective network error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2662
2749
  }
2663
2750
  });
2664
2751
 
2665
2752
  async function setLoopPaused(args: any, action: "pause" | "resume") {
2666
- const loopId = String(args?.loop_id || "");
2753
+ const loopId = String(args?.loop_id || "").trim();
2754
+ if (!isSafeLoopIdentifier(loopId)) {
2755
+ return { content: [{ type: "text", text: `${action}_loop needs a valid loop_id.` }], isError: true };
2756
+ }
2667
2757
  try {
2668
2758
  const r = await apiFetch(`${REST_URL}/api/loops/${encodeURIComponent(loopId)}/${action}`, {
2669
2759
  method: "POST",
@@ -2671,9 +2761,9 @@ async function setLoopPaused(args: any, action: "pause" | "resume") {
2671
2761
  });
2672
2762
  const text = await r.text();
2673
2763
  if (!r.ok) {
2674
- return { content: [{ type: "text", text: `${action}_loop failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2764
+ return { content: [{ type: "text", text: `${action}_loop failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2675
2765
  }
2676
- JSON.parse(text);
2766
+ parseSafeJsonObject(text);
2677
2767
  const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2678
2768
  headers: { "Authorization": `Bearer ${TOKEN}` },
2679
2769
  });
@@ -2701,7 +2791,7 @@ async function setLoopPaused(args: any, action: "pause" | "resume") {
2701
2791
  }],
2702
2792
  };
2703
2793
  } catch (e: any) {
2704
- return { content: [{ type: "text", text: `${action}_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2794
+ return { content: [{ type: "text", text: `${action}_loop error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2705
2795
  }
2706
2796
  }
2707
2797
 
@@ -2718,9 +2808,9 @@ HANDLERS.set("create_loop", async (args) => {
2718
2808
  });
2719
2809
  const text = await r.text();
2720
2810
  if (!r.ok) {
2721
- return { content: [{ type: "text", text: `create_loop failed (${r.status}): ${text.slice(0, 220)}` }], isError: true };
2811
+ return { content: [{ type: "text", text: `create_loop failed (${r.status}): ${scrubMcpHandlerError(text, 220)}` }], isError: true };
2722
2812
  }
2723
- const createdPayload = JSON.parse(text) as any;
2813
+ const createdPayload = parseSafeJsonObject(text) as any;
2724
2814
  const createdLoopId = String(createdPayload?.loop?.loop_id || "").trim();
2725
2815
  if (!isSafeLoopIdentifier(createdLoopId)) {
2726
2816
  return {
@@ -2777,7 +2867,7 @@ HANDLERS.set("create_loop", async (args) => {
2777
2867
  }],
2778
2868
  };
2779
2869
  } catch (e: any) {
2780
- return { content: [{ type: "text", text: `create_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2870
+ return { content: [{ type: "text", text: `create_loop error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2781
2871
  }
2782
2872
  });
2783
2873
 
@@ -2788,7 +2878,9 @@ const LOOP_INTERVAL_MIN_MS = 60_000;
2788
2878
  const LOOP_INTERVAL_MAX_MS = 86_400_000;
2789
2879
 
2790
2880
  function isSafeLoopIdentifier(loopId: string): boolean {
2791
- return /^[A-Za-z0-9_.:-]{1,128}$/.test(loopId) && !loopId.includes("..");
2881
+ if (!/^[A-Za-z0-9_.:-]{1,128}$/.test(loopId)) return false;
2882
+ if (loopId === "." || loopId.includes("..")) return false;
2883
+ return !RESERVED_MCP_ROUTE_KEYS.has(loopId.toLowerCase());
2792
2884
  }
2793
2885
 
2794
2886
  HANDLERS.set("set_loop_interval", async (args) => {
@@ -2811,9 +2903,9 @@ HANDLERS.set("set_loop_interval", async (args) => {
2811
2903
  });
2812
2904
  const text = await r.text();
2813
2905
  if (!r.ok) {
2814
- return { content: [{ type: "text", text: `set_loop_interval failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2906
+ return { content: [{ type: "text", text: `set_loop_interval failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2815
2907
  }
2816
- JSON.parse(text);
2908
+ parseSafeJsonObject(text);
2817
2909
  const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2818
2910
  headers: { "Authorization": `Bearer ${TOKEN}` },
2819
2911
  });
@@ -2845,7 +2937,7 @@ HANDLERS.set("set_loop_interval", async (args) => {
2845
2937
  }],
2846
2938
  };
2847
2939
  } catch (e: any) {
2848
- return { content: [{ type: "text", text: `set_loop_interval error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2940
+ return { content: [{ type: "text", text: `set_loop_interval error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2849
2941
  }
2850
2942
  });
2851
2943
 
@@ -2861,9 +2953,9 @@ HANDLERS.set("stop_loop", async (args) => {
2861
2953
  });
2862
2954
  const text = await r.text();
2863
2955
  if (!r.ok) {
2864
- return { content: [{ type: "text", text: `stop_loop failed (${r.status}): ${text.slice(0, 200)}` }], isError: true };
2956
+ return { content: [{ type: "text", text: `stop_loop failed (${r.status}): ${scrubMcpHandlerError(text, 200)}` }], isError: true };
2865
2957
  }
2866
- JSON.parse(text);
2958
+ parseSafeJsonObject(text);
2867
2959
  const verified = await apiFetch(`${REST_URL}/api/loops/mine`, {
2868
2960
  headers: { "Authorization": `Bearer ${TOKEN}` },
2869
2961
  });
@@ -2888,7 +2980,7 @@ HANDLERS.set("stop_loop", async (args) => {
2888
2980
  }],
2889
2981
  };
2890
2982
  } catch (e: any) {
2891
- return { content: [{ type: "text", text: `stop_loop error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
2983
+ return { content: [{ type: "text", text: `stop_loop error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2892
2984
  }
2893
2985
  });
2894
2986
 
@@ -2908,11 +3000,11 @@ HANDLERS.set("delete_memory", async (args) => {
2908
3000
  const text = await r.text();
2909
3001
  if (!r.ok) {
2910
3002
  return {
2911
- content: [{ type: "text", text: `delete_memory failed (${r.status}): ${text.slice(0, 240)}` }],
3003
+ content: [{ type: "text", text: `delete_memory failed (${r.status}): ${scrubMcpHandlerError(text, 240)}` }],
2912
3004
  isError: true,
2913
3005
  };
2914
3006
  }
2915
- const resp = JSON.parse(text) as any;
3007
+ const resp = parseSafeJsonObject(text) as any;
2916
3008
  const deleted = Boolean(resp?.deleted);
2917
3009
  if (!deleted && !checked.value.allow_missing) {
2918
3010
  return {
@@ -2934,7 +3026,7 @@ HANDLERS.set("delete_memory", async (args) => {
2934
3026
  }],
2935
3027
  };
2936
3028
  } catch (e: any) {
2937
- return { content: [{ type: "text", text: `delete_memory network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3029
+ return { content: [{ type: "text", text: `delete_memory network error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2938
3030
  }
2939
3031
  });
2940
3032
 
@@ -2952,19 +3044,20 @@ HANDLERS.set("okr_update_kr", async (args) => {
2952
3044
  });
2953
3045
  const text = await r.text();
2954
3046
  if (!r.ok) {
2955
- return { content: [{ type: "text", text: `okr_update_kr failed (${r.status}): ${text.slice(0, 160)}` }], isError: true };
3047
+ return { content: [{ type: "text", text: `okr_update_kr failed (${r.status}): ${scrubMcpHandlerError(text, 160)}` }], isError: true };
2956
3048
  }
2957
3049
  return { content: [{ type: "text", text: `Updated: ${text}` }] };
2958
3050
  } catch (e: any) {
2959
- return { content: [{ type: "text", text: `okr_update_kr network error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3051
+ return { content: [{ type: "text", text: `okr_update_kr network error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
2960
3052
  }
2961
3053
  });
2962
3054
 
2963
3055
  function redactCloudAgentDisplayName(name: string): string {
2964
- const safe = redactSecrets(name)
3056
+ const preScrubbed = name
2965
3057
  .replace(/\bsk-(?:ant|proj|live|test)-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]")
2966
3058
  .replace(/\bgh[pousr]_[A-Za-z0-9]{20,}\b/g, "[REDACTED]")
2967
3059
  .replace(/\bAIza[0-9A-Za-z_-]{30,}\b/g, "[REDACTED]");
3060
+ const safe = redactSecrets(preScrubbed);
2968
3061
  return redactParticipantPii(safe).slice(0, 128);
2969
3062
  }
2970
3063
 
@@ -2999,7 +3092,7 @@ function projectWakeHealthPayload(channelId: string, data: any): { channel_id: s
2999
3092
 
3000
3093
  HANDLERS.set("cloud_agent_wake_health", async (args) => {
3001
3094
  const channelId = String(args?.channel_id || "").trim();
3002
- if (!channelId || /[\x00-\x1f\x7f]/.test(channelId)) {
3095
+ if (!isSafeChannelRouteId(channelId)) {
3003
3096
  return { content: [{ type: "text", text: "cloud_agent_wake_health needs channel_id." }], isError: true };
3004
3097
  }
3005
3098
  const reqHeaders = {
@@ -3021,7 +3114,7 @@ HANDLERS.set("cloud_agent_wake_health", async (args) => {
3021
3114
  const rpc = await r.json() as any;
3022
3115
  if (!rpc?.error && !rpc?.result?.isError) {
3023
3116
  let data = rpc?.result?.structuredContent;
3024
- if (!data && typeof rpc?.result?.content?.[0]?.text === "string") data = JSON.parse(rpc.result.content[0].text);
3117
+ if (!data && typeof rpc?.result?.content?.[0]?.text === "string") data = parseSafeJsonObject(rpc.result.content[0].text);
3025
3118
  const projected = projectWakeHealthPayload(channelId, data);
3026
3119
  if (!projected) return { content: [{ type: "text", text: "cloud_agent_wake_health returned an invalid response" }], isError: true };
3027
3120
  return { content: [{ type: "text", text: JSON.stringify(projected) }] };
@@ -3029,23 +3122,29 @@ HANDLERS.set("cloud_agent_wake_health", async (args) => {
3029
3122
  rpcErrorCode = rpc?.error?.code ?? "remote_error";
3030
3123
  rpcErrorMsg = typeof rpc?.error?.message === "string" ? rpc.error.message : "";
3031
3124
  }
3032
- // Fallback to REST /api/channels/:id/cloud-wake-health when /mcp predates the tool (-32601/-32602 Unknown tool or 404/405).
3125
+ // Fallback to REST /api/channels/:id/wake-health (with legacy /cloud-wake-health fallback)
3126
+ // when /mcp predates the tool (-32601/-32602 Unknown tool or 404/405).
3033
3127
  const canFallback = (!r.ok && (r.status === 404 || r.status === 405)) ||
3034
3128
  ((rpcErrorCode === -32601 || rpcErrorCode === -32602) && !/denied|forbidden|invalid cloud wake health/i.test(rpcErrorMsg));
3035
3129
  if (canFallback) {
3036
- const restRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(channelId)}/cloud-wake-health`, {
3130
+ let restRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(channelId)}/wake-health`, {
3037
3131
  headers: reqHeaders,
3038
3132
  }, 5000, true);
3133
+ if (restRes.status === 404 || restRes.status === 405) {
3134
+ restRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(channelId)}/cloud-wake-health`, {
3135
+ headers: reqHeaders,
3136
+ }, 5000, true);
3137
+ }
3039
3138
  if (restRes.ok) {
3040
3139
  const projected = projectWakeHealthPayload(channelId, await restRes.json());
3041
3140
  if (projected) return { content: [{ type: "text", text: JSON.stringify(projected) }] };
3042
3141
  }
3043
3142
  }
3044
3143
  if (!r.ok) return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${r.status})` }], isError: true };
3045
- const safeDetail = rpcErrorMsg ? `: ${redactSecrets(redactParticipantPii(rpcErrorMsg)).slice(0, 80)}` : "";
3144
+ const safeDetail = rpcErrorMsg ? `: ${scrubMcpHandlerError(redactParticipantPii(rpcErrorMsg), 80)}` : "";
3046
3145
  return { content: [{ type: "text", text: `cloud_agent_wake_health failed (${rpcErrorCode}${safeDetail})` }], isError: true };
3047
3146
  } catch (e: any) {
3048
- return { content: [{ type: "text", text: `cloud_agent_wake_health error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3147
+ return { content: [{ type: "text", text: `cloud_agent_wake_health error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3049
3148
  }
3050
3149
  });
3051
3150
 
@@ -3056,7 +3155,9 @@ function sanitizeProposalItem(p: any): any {
3056
3155
  voter_id: typeof v?.voter_id === "string" ? redactParticipantPii(v.voter_id) : "unknown",
3057
3156
  voter_type: v?.voter_type === "human" ? "human" : "agent",
3058
3157
  decision: v?.decision,
3059
- ...(typeof v?.reason === "string" && v.reason ? { reason: redactSecrets(redactParticipantPii(v.reason)).slice(0, 500) } : {}),
3158
+ ...(typeof v?.reason === "string" && v.reason
3159
+ ? { reason: redactSecrets(v.reason.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ").trim()).slice(0, 500) }
3160
+ : {}),
3060
3161
  }))
3061
3162
  : [];
3062
3163
  return {
@@ -3078,7 +3179,7 @@ function sanitizeProposalItem(p: any): any {
3078
3179
 
3079
3180
  HANDLERS.set("list_pins", async (args) => {
3080
3181
  const chatId = String(args?.chat_id || "").trim();
3081
- if (!chatId || /[\x00-\x1f\x7f]/.test(chatId) || /^(?:ac_|sk-)/i.test(chatId)) {
3182
+ if (!isSafeChannelRouteId(chatId)) {
3082
3183
  return { content: [{ type: "text", text: "list_pins needs a valid chat_id." }], isError: true };
3083
3184
  }
3084
3185
  try {
@@ -3091,9 +3192,9 @@ HANDLERS.set("list_pins", async (args) => {
3091
3192
  });
3092
3193
  const text = await r.text();
3093
3194
  if (!r.ok) {
3094
- return { content: [{ type: "text", text: `list_pins failed (${r.status}): ${redactSecrets(text).slice(0, 180)}` }], isError: true };
3195
+ return { content: [{ type: "text", text: `list_pins failed (${r.status}): ${scrubMcpHandlerError(text, 180)}` }], isError: true };
3095
3196
  }
3096
- const body = JSON.parse(text) as any;
3197
+ const body = parseSafeJsonObject(text) as any;
3097
3198
  const seen = new Set<string>();
3098
3199
  const pinnedMessages: string[] = [];
3099
3200
  if (Array.isArray(body?.pinned_messages)) {
@@ -3116,14 +3217,14 @@ HANDLERS.set("list_pins", async (args) => {
3116
3217
  }],
3117
3218
  };
3118
3219
  } catch (e: any) {
3119
- return { content: [{ type: "text", text: `list_pins error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3220
+ return { content: [{ type: "text", text: `list_pins error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3120
3221
  }
3121
3222
  });
3122
3223
 
3123
3224
  HANDLERS.set("list_proposals", async (args) => {
3124
3225
  const chatId = String(args?.chat_id || "").trim();
3125
3226
  const statusFilter = String(args?.status || "all").trim().toLowerCase();
3126
- if (!chatId || /[\x00-\x1f\x7f]/.test(chatId)) {
3227
+ if (!isSafeChannelRouteId(chatId)) {
3127
3228
  return { content: [{ type: "text", text: "list_proposals needs chat_id." }], isError: true };
3128
3229
  }
3129
3230
  if (!["all", "pending", "passed", "rejected"].includes(statusFilter)) {
@@ -3138,23 +3239,23 @@ HANDLERS.set("list_proposals", async (args) => {
3138
3239
  });
3139
3240
  const text = await r.text();
3140
3241
  if (!r.ok) {
3141
- return { content: [{ type: "text", text: `list_proposals failed (${r.status}): ${redactSecrets(text).slice(0, 180)}` }], isError: true };
3242
+ return { content: [{ type: "text", text: `list_proposals failed (${r.status}): ${scrubMcpHandlerError(text, 180)}` }], isError: true };
3142
3243
  }
3143
- const body = JSON.parse(text) as any;
3244
+ const body = parseSafeJsonObject(text) as any;
3144
3245
  let proposals = (Array.isArray(body?.proposals) ? body.proposals : []).map(sanitizeProposalItem).filter(Boolean);
3145
3246
  if (statusFilter !== "all") {
3146
3247
  proposals = proposals.filter((p: any) => p.status === statusFilter);
3147
3248
  }
3148
3249
  return { content: [{ type: "text", text: JSON.stringify({ channel_id: chatId, count: proposals.length, proposals, untrusted: true }) }] };
3149
3250
  } catch (e: any) {
3150
- return { content: [{ type: "text", text: `list_proposals error: ${String(e?.message || e).slice(0, 120)}` }], isError: true };
3251
+ return { content: [{ type: "text", text: `list_proposals error: ${scrubMcpHandlerError(e, 120)}` }], isError: true };
3151
3252
  }
3152
3253
  });
3153
3254
 
3154
3255
  HANDLERS.set("propose", async (args) => {
3155
3256
  const { chat_id, title, content, code_diff, consensus_rule, expires_at } = (args || {}) as any;
3156
3257
  const chatId = typeof chat_id === "string" ? chat_id.trim() : "";
3157
- if (!chatId || /[\x00-\x1f\x7f]/.test(chatId) || typeof title !== "string" || !title.trim() || typeof content !== "string") {
3258
+ if (!isSafeChannelRouteId(chatId) || typeof title !== "string" || !title.trim() || typeof content !== "string") {
3158
3259
  return { content: [{ type: "text", text: "Error: chat_id, non-empty title, and content (strings) required" }], isError: true };
3159
3260
  }
3160
3261
  const rule = consensus_rule || "majority";
@@ -3191,7 +3292,7 @@ HANDLERS.set("propose", async (args) => {
3191
3292
  }
3192
3293
  if (r.status !== 404 && r.status !== 405 && r.status !== 501) {
3193
3294
  const errText = await r.text();
3194
- return { content: [{ type: "text", text: `propose failed (${r.status}): ${redactSecrets(errText).slice(0, 180)}` }], isError: true };
3295
+ return { content: [{ type: "text", text: `propose failed (${r.status}): ${scrubMcpHandlerError(errText, 180)}` }], isError: true };
3195
3296
  }
3196
3297
  } catch {
3197
3298
  // Network/pre-deploy fallback to WebSocket below when open.
@@ -3212,18 +3313,22 @@ HANDLERS.set("propose", async (args) => {
3212
3313
 
3213
3314
  HANDLERS.set("vote", async (args) => {
3214
3315
  const { chat_id, channel_id, proposal_id, decision, reason } = (args || {}) as any;
3215
- if (typeof proposal_id !== "string" || !proposal_id.trim() || typeof decision !== "string") {
3316
+ if (!isSafeProposalRouteId(proposal_id) || typeof decision !== "string") {
3216
3317
  return { content: [{ type: "text", text: "Error: proposal_id and decision (strings) required" }], isError: true };
3217
3318
  }
3218
3319
  if (!["approve", "reject", "abstain"].includes(decision)) {
3219
3320
  return { content: [{ type: "text", text: "Error: decision must be approve, reject, or abstain" }], isError: true };
3220
3321
  }
3322
+ const propId = proposal_id.trim();
3221
3323
  const chatId = typeof chat_id === "string" && chat_id.trim()
3222
3324
  ? chat_id.trim()
3223
3325
  : (typeof channel_id === "string" && channel_id.trim() ? channel_id.trim() : "");
3224
- if (chatId && !/[\x00-\x1f\x7f]/.test(chatId) && TOKEN) {
3326
+ if (chatId && !isSafeChannelRouteId(chatId)) {
3327
+ return { content: [{ type: "text", text: "Error: invalid chat_id" }], isError: true };
3328
+ }
3329
+ if (chatId && TOKEN) {
3225
3330
  try {
3226
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals/${encodeURIComponent(proposal_id.trim())}/votes`, {
3331
+ const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/proposals/${encodeURIComponent(propId)}/votes`, {
3227
3332
  method: "POST",
3228
3333
  headers: {
3229
3334
  "Authorization": `Bearer ${TOKEN}`,
@@ -3238,13 +3343,13 @@ HANDLERS.set("vote", async (args) => {
3238
3343
  });
3239
3344
  if (r.ok) {
3240
3345
  const data = await r.json() as any;
3241
- return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal_id: data?.proposal_id ?? proposal_id.trim(), vote_result: data?.vote_result }) }] };
3346
+ return { content: [{ type: "text", text: JSON.stringify({ ok: true, transport: "rest", proposal_id: data?.proposal_id ?? propId, vote_result: data?.vote_result }) }] };
3242
3347
  }
3243
3348
  const errText = await r.text();
3244
3349
  // Only fall back to WS when the server build predates the REST route (404 with HTML/route missing, not Proposal not found JSON).
3245
3350
  const isProposal404 = r.status === 404 && /proposal not found|channel not found/i.test(errText);
3246
3351
  if ((r.status !== 404 && r.status !== 405 && r.status !== 501) || isProposal404) {
3247
- return { content: [{ type: "text", text: `vote failed (${r.status}): ${redactSecrets(errText).slice(0, 180)}` }], isError: true };
3352
+ return { content: [{ type: "text", text: `vote failed (${r.status}): ${scrubMcpHandlerError(errText, 180)}` }], isError: true };
3248
3353
  }
3249
3354
  } catch {
3250
3355
  // Fall back to WS below if open.
@@ -3252,10 +3357,10 @@ HANDLERS.set("vote", async (args) => {
3252
3357
  }
3253
3358
  if (ws && ws.readyState === WebSocket.OPEN) {
3254
3359
  ws.send(JSON.stringify({
3255
- type: "vote", proposal_id: proposal_id.trim(), voter_id: AGENT_ID,
3360
+ type: "vote", proposal_id: propId, voter_id: AGENT_ID,
3256
3361
  voter_type: "agent", decision, reason,
3257
3362
  }));
3258
- return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${proposal_id.trim().slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
3363
+ return { content: [{ type: "text", text: `Vote '${decision}' dispatched for proposal ${propId.slice(0, 8)}; server may reject (invalid proposal_id or expired)` }] };
3259
3364
  }
3260
3365
  return { content: [{ type: "text", text: "Not connected" }], isError: true };
3261
3366
  });
@@ -3274,7 +3379,9 @@ HANDLERS.set("list_channels", async (args) => {
3274
3379
  const list = channels.map((ch: any) => {
3275
3380
  const onlineBadge = typeof ch.online_agent_count === "number" && ch.online_agent_count > 0 ? `, 🟢 ${ch.online_agent_count} online` : "";
3276
3381
  const caps = Array.isArray(ch.capabilities) && ch.capabilities.length > 0 ? ` [${ch.capabilities.slice(0, 6).join(", ")}]` : "";
3277
- const topic = ch.topic ? ` — ${redactSecrets(redactParticipantPii(String(ch.topic))).slice(0, 60)}` : "";
3382
+ const topic = ch.topic
3383
+ ? ` — ${redactSecrets(String(ch.topic).replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, " ").trim()).slice(0, 60)}`
3384
+ : "";
3278
3385
  return `• ${ch.name || ch.id} (${ch.id}) — ${ch.member_count || "?"} members${onlineBadge}${caps}${topic}`;
3279
3386
  }).join("\n");
3280
3387
  return { content: [{ type: "text", text: `${channels.length} channels:\n${list}` }] };
@@ -3564,7 +3671,7 @@ function createProfileSlot(opts: {
3564
3671
  capabilities: string[];
3565
3672
  runtimeSession: DetectedSession | null;
3566
3673
  }): ProfileSlot {
3567
- const lastSeenFile = join(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
3674
+ const lastSeenFile = cursorFileForAgent(configDir, opts.agentId);
3568
3675
  const slot: ProfileSlot = {
3569
3676
  profileName: opts.profileName,
3570
3677
  profileFile: opts.profileFile,
@@ -3600,8 +3707,9 @@ function createProfileSlot(opts: {
3600
3707
  ws = null;
3601
3708
  sessionId = null;
3602
3709
  }
3603
- slot.wsReconnectAttempt = 0;
3604
- scheduleReconnect(500, slot);
3710
+ slot.wsReconnectAttempt++;
3711
+ const delay = slot.wsReconnectAttempt === 1 ? 500 : computeReconnectDelay(slot.wsReconnectAttempt);
3712
+ scheduleReconnect(delay, slot);
3605
3713
  },
3606
3714
  getReadyState: () => slot.ws?.readyState ?? WS_CLOSED,
3607
3715
  }, 15_000, 45_000, 30_000);
@@ -3887,12 +3995,22 @@ async function registerAndConnectProfile(
3887
3995
  if (!cleanName) {
3888
3996
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
3889
3997
  }
3890
- const safeBase = cleanName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
3891
- if (safeBase.toLowerCase() === "profile") {
3998
+ const safeBase = cleanName.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
3999
+ const reservedRegisterBases = new Set([
4000
+ "profile",
4001
+ "grok-binds",
4002
+ "grok-binds_meta",
4003
+ "session-binds",
4004
+ "agy-session-binds",
4005
+ "__proto__",
4006
+ "constructor",
4007
+ "prototype",
4008
+ ]);
4009
+ if (!safeBase || reservedRegisterBases.has(safeBase.toLowerCase())) {
3892
4010
  return {
3893
4011
  content: [{
3894
4012
  type: "text",
3895
- text: 'Error: "profile" (profile.json) is reserved and cannot be registered as a named agent profile. Choose a distinct profile name (e.g. "Antigravity", "Claude_Work", "Codex_Dev").',
4013
+ text: `Error: "${safeBase || cleanName}" is reserved and cannot be registered as a named agent profile. Choose a distinct profile name (e.g. "Antigravity", "Claude_Work", "Codex_Dev").`,
3896
4014
  }],
3897
4015
  isError: true,
3898
4016
  };
@@ -3989,7 +4107,28 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
3989
4107
  conversation_id?: string;
3990
4108
  };
3991
4109
 
4110
+ // Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
4111
+ // when set, or via current profile when Cursor stdio started with --profile
4112
+ // and no CURSOR_CONVERSATION_ID. Refuse switches, disconnects, and fresh
4113
+ // registrations that leave the locked identity. No-op allowed.
4114
+ // Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
4115
+ // profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
4116
+ const switchBinds = loadGrokBinds();
4117
+ const bindApplies = currentGrokBindApplicability(switchBinds);
4118
+ const currentBoundProfile = profileNameFromPath(activeProfileFile);
4119
+
3992
4120
  if (disconnect) {
4121
+ if (bindApplies.applies) {
4122
+ const discGate = gateGrokProfileMutation({
4123
+ conversationId: process.env.CURSOR_CONVERSATION_ID,
4124
+ binds: switchBinds,
4125
+ currentProfileName: currentBoundProfile,
4126
+ action: "disconnect",
4127
+ });
4128
+ if (discGate.kind === "locked") {
4129
+ return { content: [{ type: "text", text: discGate.message }], isError: true };
4130
+ }
4131
+ }
3993
4132
  const { prevAgentId, prevProfileName } = disconnectCurrentProfile();
3994
4133
  return {
3995
4134
  content: [{
@@ -4003,6 +4142,18 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
4003
4142
 
4004
4143
  const explicitSessionId = typeof conversation_id === "string" && conversation_id.trim() ? conversation_id.trim() : null;
4005
4144
  if (typeof register_name === "string" && register_name.trim()) {
4145
+ if (bindApplies.applies) {
4146
+ const regGate = gateGrokProfileMutation({
4147
+ conversationId: process.env.CURSOR_CONVERSATION_ID,
4148
+ binds: switchBinds,
4149
+ currentProfileName: currentBoundProfile,
4150
+ action: "register",
4151
+ requestedName: register_name.trim(),
4152
+ });
4153
+ if (regGate.kind === "locked") {
4154
+ return { content: [{ type: "text", text: regGate.message }], isError: true };
4155
+ }
4156
+ }
4006
4157
  return await registerAndConnectProfile(register_name.trim(), explicitSessionId);
4007
4158
  }
4008
4159
 
@@ -4010,19 +4161,11 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
4010
4161
  return { content: [{ type: "text", text: formatProfileList() }] };
4011
4162
  }
4012
4163
 
4013
- // Shared Cursor MCP: grok-binds lock outbound identity — via conversation id
4014
- // when set, or via current profile when Cursor stdio started with --profile
4015
- // and no CURSOR_CONVERSATION_ID. Refuse switches that leave the locked
4016
- // identity (including other Grok bots or Hermes/Spiral). No-op allowed.
4017
- // Non-Grok wakes (Antigravity / ZCode) and explicit --profile ≠ bound
4018
- // profile are exempt: an inherited CURSOR_CONVERSATION_ID must not lock them.
4019
- const switchBinds = loadGrokBinds();
4020
- const bindApplies = currentGrokBindApplicability(switchBinds);
4021
4164
  const switchGate = !bindApplies.applies ? ({ kind: "allow" } as const) : gateSwitchProfile({
4022
4165
  conversationId: process.env.CURSOR_CONVERSATION_ID,
4023
4166
  binds: switchBinds,
4024
4167
  requestedProfileName: profile_name,
4025
- currentProfileName: profileNameFromPath(activeProfileFile),
4168
+ currentProfileName: currentBoundProfile,
4026
4169
  });
4027
4170
  if (switchGate.kind === "locked") {
4028
4171
  return { content: [{ type: "text", text: switchGate.message }], isError: true };
@@ -4100,6 +4243,19 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
4100
4243
 
4101
4244
  HANDLERS.set("connect_profile", async (args) => handleProfileSwitchOrConnect(args));
4102
4245
  HANDLERS.set("disconnect_profile", async (args) => {
4246
+ const switchBinds = loadGrokBinds();
4247
+ const bindApplies = currentGrokBindApplicability(switchBinds);
4248
+ if (bindApplies.applies) {
4249
+ const discGate = gateGrokProfileMutation({
4250
+ conversationId: process.env.CURSOR_CONVERSATION_ID,
4251
+ binds: switchBinds,
4252
+ currentProfileName: profileNameFromPath(activeProfileFile),
4253
+ action: "disconnect",
4254
+ });
4255
+ if (discGate.kind === "locked") {
4256
+ return { content: [{ type: "text", text: discGate.message }], isError: true };
4257
+ }
4258
+ }
4103
4259
  const { keep_binding } = (args || {}) as { keep_binding?: boolean };
4104
4260
  const { prevAgentId, prevProfileName } = disconnectCurrentProfile({ keepBinding: keep_binding });
4105
4261
  return {
@@ -4798,8 +4954,8 @@ const handleToolCall = async (request: any): Promise<any> => {
4798
4954
 
4799
4955
  if (name === "sync_skill") {
4800
4956
  const a = (args || {}) as { chat_id?: string; doc_id?: string; name?: string; dir?: string };
4801
- const home = process.env.HOME || process.env.USERPROFILE || ".";
4802
- const cacheDir = (a.dir && String(a.dir).trim()) || `${home}/.agentchat/skills`;
4957
+ const home = process.env.HOME || process.env.USERPROFILE || homedir() || ".";
4958
+ const cacheDir = (a.dir && String(a.dir).trim()) || join(home, ".agentchat", "skills");
4803
4959
  const safe = (s: string) => String(s).replace(/[^A-Za-z0-9_.-]/g, "_");
4804
4960
  // PERSONAL skill: sync_skill({name}) — version from GET /api/skills (cheap,
4805
4961
  // no body), body from GET /api/skills/:name only when missing/stale.
@@ -4809,7 +4965,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4809
4965
  return { content: [{ type: "text", text: slugCheck.error }], isError: true };
4810
4966
  }
4811
4967
  const pSlug = slugCheck.value;
4812
- const pBase = `${cacheDir}/personal__${safe(pSlug)}`;
4968
+ const pBase = join(cacheDir, `personal__${safe(pSlug)}`);
4813
4969
  const pMd = `${pBase}.md`; const pMeta = `${pBase}.json`;
4814
4970
  try {
4815
4971
  const listR = await apiFetch(`${REST_URL}/api/skills`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
@@ -6176,7 +6332,11 @@ const handleToolCall = async (request: any): Promise<any> => {
6176
6332
  const safeId = redactParticipantPii(rawId);
6177
6333
  const peer = !isHuman ? peerById.get(rawId) : undefined;
6178
6334
  const rawDisplay = m?.display_name ? String(m.display_name).trim() : (peer?.name ? String(peer.name).trim() : "");
6179
- const safeDisplay = rawDisplay && !isHumanPiiHandle(rawDisplay) ? rawDisplay : safeId;
6335
+ const cleanDisplay =
6336
+ rawDisplay && !/^user:[a-z0-9]{1,4}\*\*\*$/i.test(rawDisplay)
6337
+ ? redactParticipantPii(rawDisplay)
6338
+ : "";
6339
+ const safeDisplay = cleanDisplay || safeId;
6180
6340
  const handleBadge = isHuman ? `(${safeId})` : `(@${safeId})`;
6181
6341
  const roleBadge = m?.role ? ` [${m.role}]` : "";
6182
6342
  const onlineVal = typeof m?.online === "boolean" ? m.online : peer?.online;
@@ -7227,11 +7387,13 @@ function recordOrSkipDeliveredMessage(data: any, slot: ProfileSlot | null = acti
7227
7387
 
7228
7388
  function scheduleReconnect(delayMs: number, slot: ProfileSlot | null = activeSlot) {
7229
7389
  if (shuttingDown || !slot) return; // don't resurrect the socket after shutdown
7390
+ slot.heartbeat.stop();
7230
7391
  if (slot.reconnectTimer) clearTimeout(slot.reconnectTimer);
7231
7392
  slot.reconnectTimer = setTimeout(() => {
7232
7393
  slot.reconnectTimer = null;
7233
7394
  connectWS(slot);
7234
7395
  }, delayMs);
7396
+ (slot.reconnectTimer as any).unref?.();
7235
7397
  }
7236
7398
 
7237
7399
  /**
@@ -7368,6 +7530,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
7368
7530
  socket = new WebSocket(WS_URL);
7369
7531
  slot.ws = socket;
7370
7532
  if (activeSlot === slot) ws = socket;
7533
+ slot.heartbeat.start();
7371
7534
  } catch (e) {
7372
7535
  process.stderr.write(`[agentchat] WebSocket constructor failed: ${e}, retrying in 5s\n`);
7373
7536
  scheduleReconnect(5000, slot);
@@ -7420,6 +7583,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
7420
7583
  slot!.backfillTimer = null;
7421
7584
  if (!shuttingDown) void backfillAllChannels(slot!);
7422
7585
  }, 2000);
7586
+ (slot!.backfillTimer as any).unref?.();
7423
7587
  } else if ((data.type === "message" || data.type === "thread_reply") &&
7424
7588
  data.sender_id === slot!.agentId && typeof data.content === "string" && data.content !== "__typing__" &&
7425
7589
  !["loop_tick", "slash_input", "loop_status", "slash_response"].includes(data.meta?.kind)) {
@@ -7553,6 +7717,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
7553
7717
  const port = grokPortFromGatewayConfig(gwcfg);
7554
7718
  const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
7555
7719
  headers: token ? { Authorization: `Bearer ${token}` } : {},
7720
+ signal: AbortSignal.timeout(5000),
7556
7721
  });
7557
7722
  if (!res.ok) throw new Error(`listAgents HTTP ${res.status}`);
7558
7723
  const d = (await res.json()) as any;
@@ -7699,7 +7864,8 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
7699
7864
  process.stderr.write(`[agentchat] Joined channel: ${data.name}\n`);
7700
7865
  if (typeof data.channel_id === "string") slot!.knownChannels.add(data.channel_id);
7701
7866
  } else if (data.type === "shard_moved") {
7702
- process.stderr.write(`[agentchat] Shard moved, reconnecting...\n`);
7867
+ const delay = resolveDrainReconnectDelay(data);
7868
+ process.stderr.write(`[agentchat] Shard moved, reconnecting in ${delay}ms...\n`);
7703
7869
  if (data.redirect_url) {
7704
7870
  const newUrl = data.redirect_url.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws";
7705
7871
  process.stderr.write(`[agentchat] Redirecting to: ${newUrl}\n`);
@@ -7709,7 +7875,28 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
7709
7875
  slot!.sessionId = null;
7710
7876
  if (activeSlot === slot) { ws = null; sessionId = null; }
7711
7877
  slot!.wsReconnectAttempt = 0;
7712
- scheduleReconnect(500, slot!);
7878
+ scheduleReconnect(delay, slot!);
7879
+ } else if (data.type === "please_reconnect") {
7880
+ const delay = resolveDrainReconnectDelay(data);
7881
+ process.stderr.write(`[agentchat] Server draining (please_reconnect), reconnecting in ${delay}ms...\n`);
7882
+ if (slot!.ws) { slot!.ws.onclose = null; try { slot!.ws.close(); } catch {} }
7883
+ slot!.ws = null;
7884
+ slot!.sessionId = null;
7885
+ if (activeSlot === slot) { ws = null; sessionId = null; }
7886
+ slot!.wsReconnectAttempt = 0;
7887
+ scheduleReconnect(delay, slot!);
7888
+ } else if (data.type === "auth_error") {
7889
+ const reason = data.error || data.message || "authentication failed";
7890
+ process.stderr.write(`[agentchat] Auth error for ${slot!.agentId}: ${reason} — halting reconnect loop\n`);
7891
+ slot!.heartbeat.stop();
7892
+ if (slot!.reconnectTimer) {
7893
+ clearTimeout(slot!.reconnectTimer);
7894
+ slot!.reconnectTimer = null;
7895
+ }
7896
+ if (slot!.ws) { slot!.ws.onclose = null; try { slot!.ws.close(); } catch {} }
7897
+ slot!.ws = null;
7898
+ slot!.sessionId = null;
7899
+ if (activeSlot === slot) { ws = null; sessionId = null; }
7713
7900
  } else if (data.type === "error") {
7714
7901
  process.stderr.write(`[agentchat] Error: ${data.message}\n`);
7715
7902
  }
@@ -7717,8 +7904,12 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
7717
7904
 
7718
7905
  socket.onclose = (event) => {
7719
7906
  if (slot.ws !== socket) return;
7907
+ slot.ws = null;
7720
7908
  slot.sessionId = null;
7721
- if (activeSlot === slot) sessionId = null;
7909
+ if (activeSlot === slot) {
7910
+ ws = null;
7911
+ sessionId = null;
7912
+ }
7722
7913
  slot.heartbeat.resetReconnecting();
7723
7914
  slot.wsReconnectAttempt++;
7724
7915
  const delay = computeReconnectDelay(slot.wsReconnectAttempt);
@@ -7802,6 +7993,7 @@ function installStdioLifecycleGuards() {
7802
7993
  async function checkVersionStaleness(): Promise<void> {
7803
7994
  const controller = new AbortController();
7804
7995
  const timer = setTimeout(() => controller.abort(), 5000);
7996
+ (timer as any).unref?.();
7805
7997
  try {
7806
7998
  const r = await nativeFetch("https://registry.npmjs.org/agentschat-mcp/latest", { signal: controller.signal });
7807
7999
  if (!r.ok) return;
@@ -7810,7 +8002,7 @@ async function checkVersionStaleness(): Promise<void> {
7810
8002
  process.stderr.write(
7811
8003
  `[agentchat] Update available: running agentschat-mcp ${pkg.version}, latest published is ${latest}. ` +
7812
8004
  `New tools/capabilities load only on a SESSION RESTART (hot-reload isn't possible); ` +
7813
- `update deliberately (bump the pinned agentschat-mcp@<version> in each MCP entry / reinstall) then restart this session to pick them up.\n`,
8005
+ `use npx -y agentschat-mcp@latest in each MCP entry (or reinstall npm i -g agentschat-mcp@latest) then restart this session to pick them up.\n`,
7814
8006
  );
7815
8007
  }
7816
8008
  } catch {