agentschat-mcp 0.36.21 → 0.36.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/server.ts CHANGED
@@ -41,7 +41,7 @@ if (process.env.AGENTCHAT_NO_PROXY === "1" && process.env.NODE_USE_ENV_PROXY !==
41
41
 
42
42
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
43
43
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
44
- import { redactSecrets } from "./redact.ts";
44
+ import { isHumanPiiHandle, redactParticipantPii, redactSecrets } from "./redact.ts";
45
45
  import { matchesMention } from "./mentions.ts";
46
46
  import { messageDedupKey, MessageDedup } from "./dedup.ts";
47
47
  import { computeReconnectDelay } from "./reconnect.ts";
@@ -105,9 +105,10 @@ import {
105
105
  // --- Config: CLI args > env vars > profile file > defaults ---
106
106
  import { readFileSync, existsSync, writeFileSync, mkdirSync, readdirSync } from "fs";
107
107
  import { join, dirname } from "path";
108
+ import { fileURLToPath } from "url";
108
109
  // Atomic + 0600-by-construction profile writer. Lives in its own module so the
109
110
  // "the key is never world-readable, even mid-write" property is directly testable.
110
- import { safeWriteProfile } from "./profile-store.ts";
111
+ import { safeWriteProfile, findDefaultProfileCollision } from "./profile-store.ts";
111
112
  import {
112
113
  decideIdentityGuard,
113
114
  advanceGuardRecord,
@@ -153,18 +154,20 @@ function parseArgs() {
153
154
  const cliArgs = parseArgs();
154
155
 
155
156
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
157
+ const localOnboardingPath = join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
156
158
  console.log(`agentschat-mcp v${pkg.version} — AgentsChat MCP and host bridges
157
159
 
158
160
  Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
159
161
  claude --dangerously-load-development-channels server:agentschat
160
- One MCP server entry per bot, each pinning --profile.
162
+ One MCP server entry per bot, each pinning --profile (or omit --profile on session-aware hosts).
161
163
 
162
- Setup guide for every supported host:
163
- Read skills/onboarding.md relative to this installed package root.
164
- Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
164
+ Setup guide for every supported host (Single Source of Truth):
165
+ Local file: ${localOnboardingPath}
166
+ Relative: skills/onboarding.md (relative to this installed package root)
167
+ Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
165
168
  Newest release (first install): npx -y agentschat-mcp@latest --help
166
- The guide selects Claude Code, Codex, OpenClaw, Hermes, Grok Bot, URL wake,
167
- or the separately deployed dot remote MCP + Events integration.
169
+ Covers Claude Code, Codex, DeepSeek Harness (dsh), OpenClaw, Hermes, Grok Bot,
170
+ Antigravity, ZCode, Muse, dot / Work Cloud (remote MCP + Events), and URL wake.
168
171
  Help only prints instructions; follow the guide and verify a real reply.
169
172
 
170
173
  Options:
@@ -430,43 +433,63 @@ function readIdentityProfile(file: string): any {
430
433
  }
431
434
 
432
435
  if (identity.mode === "profile") {
433
- try {
434
- profile = readIdentityProfile(profileFile);
435
- if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
436
- throw new Error("Project agent_id does not match selected profile");
437
- }
438
- validateIdentityProfile(profile && !Array.isArray(profile) ? {
439
- ...profile,
440
- agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
441
- token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
442
- capabilities: cliArgs.caps?.split(",") ?? profile.capabilities,
443
- } : profile, profileFile, !hasToken);
444
- } catch (e) {
445
- process.stderr.write(`[agentchat] ERROR: ${(e as Error).message}\n`);
446
- process.exit(1);
447
- }
448
- const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
449
- const lockCheck = (!cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
450
- ? checkAgentLock({
451
- lockDir,
452
- agentId: candidateAgentId,
453
- currentSessionId: runtimeSession?.sessionId ?? null,
454
- lockOwnerPid,
455
- })
456
- : { locked: false };
457
- if (lockCheck.locked) {
436
+ const isDefaultProfileFile =
437
+ profileSource === "default" || profileNameFromPath(profileFile)?.toLowerCase() === "profile";
438
+ const defaultCollision = isDefaultProfileFile ? findDefaultProfileCollision(configDir, profileFile) : null;
439
+ if (defaultCollision) {
440
+ if (profileSource !== "default") {
441
+ process.stderr.write(
442
+ `[agentchat] ERROR: Refusing to load duplicate profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).\n` +
443
+ ` Delete ${profileFile} and use --profile ${defaultCollision.collidingName} instead.\n`,
444
+ );
445
+ process.exit(1);
446
+ }
458
447
  anonymousMode = true;
459
448
  activeProfileFile = null;
460
449
  profile = {};
461
450
  process.stderr.write(
462
- `[agentchat] Profile "${declaredName ?? profileNameFromPath(profileFile) ?? "profile"}" (${lockCheck.holder?.agentId}) is already in use by active process pid=${lockCheck.holder?.pid}` +
463
- `${lockCheck.holder?.runtime ? ` (${lockCheck.holder.runtime})` : ""}` +
464
- `${lockCheck.holder?.sessionId ? ` session=${lockCheck.holder.sessionId}` : ""}.\n` +
465
- ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.\n` +
466
- ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.\n`,
451
+ `[agentchat] Ignoring duplicate default profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).\n` +
452
+ ` Starting in ANONYMOUS mode instead of shadowing "${defaultCollision.collidingName}". Delete ${profileFile} or bind this session via connect_profile(profile_name="${defaultCollision.collidingName}").\n`,
467
453
  );
468
454
  } else {
469
- process.stderr.write(`[agentchat] Profile loaded: ${profileFile}\n`);
455
+ try {
456
+ profile = readIdentityProfile(profileFile);
457
+ if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
458
+ throw new Error("Project agent_id does not match selected profile");
459
+ }
460
+ validateIdentityProfile(profile && !Array.isArray(profile) ? {
461
+ ...profile,
462
+ agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
463
+ token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
464
+ capabilities: cliArgs.caps?.split(",") ?? profile.capabilities,
465
+ } : profile, profileFile, !hasToken);
466
+ } catch (e) {
467
+ process.stderr.write(`[agentchat] ERROR: ${(e as Error).message}\n`);
468
+ process.exit(1);
469
+ }
470
+ const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
471
+ const lockCheck = (!cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
472
+ ? checkAgentLock({
473
+ lockDir,
474
+ agentId: candidateAgentId,
475
+ currentSessionId: runtimeSession?.sessionId ?? null,
476
+ lockOwnerPid,
477
+ })
478
+ : { locked: false };
479
+ if (lockCheck.locked) {
480
+ anonymousMode = true;
481
+ activeProfileFile = null;
482
+ profile = {};
483
+ process.stderr.write(
484
+ `[agentchat] Profile "${declaredName ?? profileNameFromPath(profileFile) ?? "profile"}" (${lockCheck.holder?.agentId}) is already in use by active process pid=${lockCheck.holder?.pid}` +
485
+ `${lockCheck.holder?.runtime ? ` (${lockCheck.holder.runtime})` : ""}` +
486
+ `${lockCheck.holder?.sessionId ? ` session=${lockCheck.holder.sessionId}` : ""}.\n` +
487
+ ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.\n` +
488
+ ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.\n`,
489
+ );
490
+ } else {
491
+ process.stderr.write(`[agentchat] Profile loaded: ${profileFile}\n`);
492
+ }
470
493
  }
471
494
  } else if (identity.mode === "env-creds") {
472
495
  // Token handed to us directly — authenticate with it, register nothing, write nothing.
@@ -635,19 +658,28 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
635
658
  }
636
659
 
637
660
  if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
638
- const activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
639
- if (
640
- activeName &&
641
- runtimeSession?.runtime === "antigravity" &&
642
- !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim()
643
- ) {
644
- const existingBoundSid = findBoundSessionForProfile(
645
- configDir,
646
- activeName,
647
- (sid) => /^[0-9a-f-]{36}$/i.test(sid),
648
- );
649
- if (existingBoundSid) {
650
- runtimeSession = { sessionId: existingBoundSid, runtime: "antigravity" };
661
+ let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
662
+ const isAgyUuid = (sid: string) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
663
+ const isImplicitAgyBoot =
664
+ (runtimeSession?.runtime === "antigravity" || (!runtimeSession && Boolean(discoverAntigravityHost()))) &&
665
+ !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
666
+ if (activeName && isImplicitAgyBoot) {
667
+ const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
668
+ const existingAgentRoute = resolveSessionForAgent(AGENT_ID, { configDir, filter: isAgyUuid });
669
+ const resolvedSid = existingBoundSid || existingAgentRoute?.sessionId || "";
670
+ if (resolvedSid) {
671
+ runtimeSession = { sessionId: resolvedSid, runtime: "antigravity" };
672
+ if (
673
+ profileSource === "default" &&
674
+ existingAgentRoute?.profileName &&
675
+ existingAgentRoute.profileName !== activeName
676
+ ) {
677
+ const aliasPath = nameToPath(existingAgentRoute.profileName);
678
+ if (existsSync(aliasPath)) {
679
+ activeProfileFile = aliasPath;
680
+ activeName = existingAgentRoute.profileName;
681
+ }
682
+ }
651
683
  }
652
684
  }
653
685
  acquireAgentLock({
@@ -658,7 +690,14 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
658
690
  runtime: runtimeSession?.runtime ?? "mcp",
659
691
  });
660
692
  if (runtimeSession?.sessionId && activeName) {
661
- saveSessionBind(configDir, runtimeSession.sessionId, activeName);
693
+ // Only auto-persist session-binds at boot when the session ID was explicitly
694
+ // supplied (e.g. CLAUDE_CODE_SESSION_ID / ZCODE_SESSION_ID / ANTIGRAVITY_CONVERSATION_ID)
695
+ // or already matches an existing bind — never passively bind a random open
696
+ // Antigravity window before that conversation invokes any AgentsChat tool.
697
+ const existingBinds = loadSessionBinds(configDir);
698
+ if (!isImplicitAgyBoot || existingBinds[runtimeSession.sessionId] === activeName) {
699
+ saveSessionBind(configDir, runtimeSession.sessionId, activeName);
700
+ }
662
701
  }
663
702
  }
664
703
 
@@ -1648,7 +1687,7 @@ const ALL_TOOL_DEFS = [
1648
1687
  },
1649
1688
  {
1650
1689
  name: "channel_brief",
1651
- description: "Capability synopsis of a channel: who's here (and ONLINE right now), linked OKR objectives with open-task counts, available channel skills, loadable extended tool groups (with load state), recent docs, and what you can do. Call after joining or when entering an unfamiliar room.",
1690
+ description: "Capability synopsis of a channel: who's here (and ONLINE right now, with human emails/phones masked), active agent_peers with their specialty capabilities, linked OKR objectives with open-task counts, available channel skills, loadable extended tool groups (with load state), recent docs, and what you can do. Call after joining or when entering an unfamiliar room.",
1652
1691
  inputSchema: {
1653
1692
  type: "object" as const,
1654
1693
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -1657,7 +1696,7 @@ const ALL_TOOL_DEFS = [
1657
1696
  },
1658
1697
  {
1659
1698
  name: "list_members",
1660
- description: "List members in a channel.",
1699
+ description: "List members in a channel with full @agent_id handles, online status, and peer capability tags (human login emails/phones masked).",
1661
1700
  inputSchema: {
1662
1701
  type: "object" as const,
1663
1702
  properties: {
@@ -2486,6 +2525,34 @@ function setAnonymousCallerState(callerSession?: DetectedSession | null): void {
2486
2525
  }
2487
2526
  }
2488
2527
 
2528
+ function findSlotByAgentId(agentId: string | null | undefined): ProfileSlot | undefined {
2529
+ if (!agentId) return undefined;
2530
+ for (const s of profileSlots.values()) {
2531
+ if (s.agentId === agentId) return s;
2532
+ }
2533
+ return undefined;
2534
+ }
2535
+
2536
+ function upgradeAliasSlotInPlace(
2537
+ slot: ProfileSlot,
2538
+ newProfileName: string,
2539
+ newProfileFile: string,
2540
+ newProfile: any,
2541
+ sess: DetectedSession,
2542
+ ): void {
2543
+ if (slot.profileName !== newProfileName) {
2544
+ profileSlots.delete(slot.profileName);
2545
+ slot.profileName = newProfileName;
2546
+ profileSlots.set(newProfileName, slot);
2547
+ }
2548
+ slot.profileFile = newProfileFile;
2549
+ slot.profile = newProfile;
2550
+ slot.runtimeSession = sess;
2551
+ if (activeSlot === slot) {
2552
+ activateSlot(slot, sess);
2553
+ }
2554
+ }
2555
+
2489
2556
  function teardownSlot(slot: ProfileSlot, opts?: { releaseLock?: boolean }): void {
2490
2557
  try { flushSlotLastSeenMessageTs(slot); } catch {}
2491
2558
  try { slot.heartbeat.stop(); } catch {}
@@ -2680,11 +2747,15 @@ function formatProfileList(): string {
2680
2747
  : { locked: false };
2681
2748
  const slot = profileSlots.get(entry.name);
2682
2749
  const boundSid = findBoundSessionForProfile(configDir, entry.name);
2683
- const statusSuffix = lock.locked
2684
- ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]`
2685
- : slot && slot.ws?.readyState === WebSocket.OPEN
2686
- ? ` [online${boundSid ? ` session=${boundSid}` : ""}]`
2687
- : "";
2750
+ const dupCollision =
2751
+ entry.name.toLowerCase() === "profile" ? findDefaultProfileCollision(configDir, entry.path) : null;
2752
+ const statusSuffix = dupCollision
2753
+ ? ` [duplicate of ${dupCollision.collidingName} — disallowed; delete profile.json]`
2754
+ : lock.locked
2755
+ ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]`
2756
+ : slot && slot.ws?.readyState === WebSocket.OPEN
2757
+ ? ` [online${boundSid ? ` session=${boundSid}` : ""}]`
2758
+ : "";
2688
2759
  return `${isCurrent ? "→ " : " "}${entry.name}${statusSuffix}`;
2689
2760
  });
2690
2761
  return `Current: ${current || "(anonymous / disconnected)"}\nAvailable profiles:\n${lines.join("\n")}`;
@@ -2698,6 +2769,42 @@ async function registerAndConnectProfile(
2698
2769
  if (!cleanName) {
2699
2770
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
2700
2771
  }
2772
+ const safeBase = cleanName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
2773
+ if (safeBase.toLowerCase() === "profile") {
2774
+ return {
2775
+ content: [{
2776
+ type: "text",
2777
+ 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").',
2778
+ }],
2779
+ isError: true,
2780
+ };
2781
+ }
2782
+ const existingTargetFile = nameToPath(cleanName);
2783
+ if (existsSync(existingTargetFile)) {
2784
+ return {
2785
+ content: [{
2786
+ type: "text",
2787
+ text: `Error: Profile "${cleanName}" already exists at ${existingTargetFile}. Pass profile_name="${cleanName}" to connect to it, or choose a different register_name.`,
2788
+ }],
2789
+ isError: true,
2790
+ };
2791
+ }
2792
+ const existingDefaultPath = nameToPath("profile");
2793
+ if (existsSync(existingDefaultPath)) {
2794
+ try {
2795
+ const defParsed = JSON.parse(readFileSync(existingDefaultPath, "utf-8"));
2796
+ const defDisplay = typeof defParsed?.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
2797
+ if (defDisplay && defDisplay === cleanName.toLowerCase()) {
2798
+ return {
2799
+ content: [{
2800
+ type: "text",
2801
+ text: `Error: Default profile.json already uses display_name "${defParsed.display_name}". Delete ${existingDefaultPath} or choose a distinct name so profile.json never collides with a named profile.`,
2802
+ }],
2803
+ isError: true,
2804
+ };
2805
+ }
2806
+ } catch {}
2807
+ }
2701
2808
  const caps = ["claude-code", "coding", "chat"];
2702
2809
  try {
2703
2810
  const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
@@ -2729,10 +2836,6 @@ async function registerAndConnectProfile(
2729
2836
  validateIdentityProfile(newProfile, targetFile);
2730
2837
  mkdirSync(dirname(targetFile), { recursive: true });
2731
2838
  safeWriteProfile(targetFile, newProfile);
2732
- const defaultProfileFile = nameToPath("profile");
2733
- if (!existsSync(defaultProfileFile)) {
2734
- safeWriteProfile(defaultProfileFile, newProfile);
2735
- }
2736
2839
  applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
2737
2840
  const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
2738
2841
  return {
@@ -2822,6 +2925,21 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
2822
2925
  };
2823
2926
  }
2824
2927
 
2928
+ if (profileNameFromPath(targetFile)?.toLowerCase() === "profile") {
2929
+ const dupCollision = findDefaultProfileCollision(configDir, targetFile);
2930
+ if (dupCollision) {
2931
+ return {
2932
+ content: [{
2933
+ type: "text",
2934
+ text:
2935
+ `Refusing to connect "profile" (${targetFile}): profile.json collides (${dupCollision.reason}) with named profile "${dupCollision.collidingName}" (${dupCollision.collidingPath}). ` +
2936
+ `Delete ${targetFile} and connect via profile_name="${dupCollision.collidingName}" instead.`,
2937
+ }],
2938
+ isError: true,
2939
+ };
2940
+ }
2941
+ }
2942
+
2825
2943
  const newProfile = readIdentityProfile(targetFile);
2826
2944
  validateIdentityProfile(newProfile, targetFile);
2827
2945
 
@@ -3094,16 +3212,37 @@ const handleToolCall = async (request: any): Promise<any> => {
3094
3212
  if (existsSync(boundPath)) {
3095
3213
  try {
3096
3214
  const candidate = readIdentityProfile(boundPath);
3097
- const lock = checkAgentLock({
3098
- lockDir,
3099
- agentId: candidate?.agent_id,
3100
- currentSessionId: callerSession.sessionId,
3101
- lockOwnerPid,
3102
- });
3103
- if (!lock.locked) {
3104
- applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
3105
- } else if (isPerCallSession) {
3106
- setAnonymousCallerState(callerSession);
3215
+ const aliasSlot = candidate?.agent_id ? findSlotByAgentId(candidate.agent_id) : undefined;
3216
+ const aliasSid = aliasSlot
3217
+ ? aliasSlot.runtimeSession?.sessionId ||
3218
+ findBoundSessionForProfile(configDir, aliasSlot.profileName) ||
3219
+ resolveSessionForAgent(aliasSlot.agentId, { configDir })?.sessionId ||
3220
+ null
3221
+ : null;
3222
+ if (aliasSlot && (!aliasSid || aliasSid === callerSession.sessionId)) {
3223
+ upgradeAliasSlotInPlace(aliasSlot, boundProfileName, boundPath, candidate, callerSession);
3224
+ activateSlot(aliasSlot, callerSession);
3225
+ if (!toolOnlyMode) {
3226
+ acquireAgentLock({
3227
+ lockDir,
3228
+ agentId: aliasSlot.agentId,
3229
+ profileName: boundProfileName,
3230
+ sessionId: callerSession.sessionId,
3231
+ runtime: callerSession.runtime,
3232
+ });
3233
+ }
3234
+ } else {
3235
+ const lock = checkAgentLock({
3236
+ lockDir,
3237
+ agentId: candidate?.agent_id,
3238
+ currentSessionId: callerSession.sessionId,
3239
+ lockOwnerPid,
3240
+ });
3241
+ if (!lock.locked) {
3242
+ applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
3243
+ } else if (isPerCallSession) {
3244
+ setAnonymousCallerState(callerSession);
3245
+ }
3107
3246
  }
3108
3247
  } catch {}
3109
3248
  } else if (isPerCallSession) {
@@ -3116,7 +3255,9 @@ const handleToolCall = async (request: any): Promise<any> => {
3116
3255
  let unboundSlot: ProfileSlot | null = null;
3117
3256
  for (const slot of profileSlots.values()) {
3118
3257
  const slotBoundSid =
3119
- slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
3258
+ slot.runtimeSession?.sessionId ||
3259
+ findBoundSessionForProfile(configDir, slot.profileName) ||
3260
+ resolveSessionForAgent(slot.agentId, { configDir })?.sessionId;
3120
3261
  if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
3121
3262
  unboundSlot = slot;
3122
3263
  break;
@@ -3735,7 +3876,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3735
3876
  const data = await r.json() as any;
3736
3877
  if (data.messages?.length > 0) {
3737
3878
  const results = data.messages.map((m: any) =>
3738
- `[${m.sender_id?.slice(0, 8)}] ${m.content?.slice(0, 80)}`
3879
+ `[${redactParticipantPii(m.sender_id || "?")}] ${m.content?.slice(0, 80)}`
3739
3880
  ).join("\n");
3740
3881
  return { content: [{ type: "text", text: `Found ${data.messages.length} results:\n${results}` }] };
3741
3882
  }
@@ -3776,9 +3917,51 @@ const handleToolCall = async (request: any): Promise<any> => {
3776
3917
  return { content: [{ type: "text", text: "Not connected" }] };
3777
3918
  }
3778
3919
 
3920
+ async function fetchMcpChannelContext(chatId: string): Promise<{
3921
+ channel?: { id?: string; name?: string; type?: string; topic?: string; member_count?: number };
3922
+ agents?: Array<{ id: string; name?: string; capabilities?: string[]; online?: boolean; is_self?: boolean }>;
3923
+ } | null> {
3924
+ if (!chatId || !TOKEN) return null;
3925
+ try {
3926
+ const r = await apiFetch(
3927
+ `${REST_URL}/mcp`,
3928
+ {
3929
+ method: "POST",
3930
+ headers: {
3931
+ "Authorization": `Bearer ${TOKEN}`,
3932
+ "Content-Type": "application/json",
3933
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
3934
+ },
3935
+ body: JSON.stringify({
3936
+ jsonrpc: "2.0",
3937
+ id: 1,
3938
+ method: "tools/call",
3939
+ params: {
3940
+ name: "agentschat_get_channel_context",
3941
+ arguments: { channel_id: chatId },
3942
+ },
3943
+ }),
3944
+ },
3945
+ 2500,
3946
+ );
3947
+ if (!r.ok) return null;
3948
+ const rpc = await r.json() as any;
3949
+ if (rpc?.error || rpc?.result?.isError) return null;
3950
+ const structured = rpc?.result?.structuredContent;
3951
+ if (structured && typeof structured === "object") return structured;
3952
+ const textPayload = rpc?.result?.content?.[0]?.text;
3953
+ if (typeof textPayload === "string" && textPayload.trim().startsWith("{")) {
3954
+ return JSON.parse(textPayload);
3955
+ }
3956
+ return null;
3957
+ } catch {
3958
+ return null;
3959
+ }
3960
+ }
3961
+
3779
3962
  // P3 capability synopsis (kr_mq66wu4u): everything an agent can DO in a
3780
- // channel, composed from existing REST reads. Sections fail soft (null)
3781
- // so a single flaky fetch never blanks the brief.
3963
+ // channel, composed from existing REST reads + /mcp agentschat_get_channel_context.
3964
+ // Sections fail soft (null) so a single flaky fetch never blanks the brief.
3782
3965
  async function channelBrief(chatId: string): Promise<string> {
3783
3966
  const get = async (path: string) => {
3784
3967
  try {
@@ -3786,10 +3969,11 @@ const handleToolCall = async (request: any): Promise<any> => {
3786
3969
  return r.ok ? await r.json() as any : null;
3787
3970
  } catch { return null; }
3788
3971
  };
3789
- const [membersData, docsData, okrData] = await Promise.all([
3972
+ const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
3790
3973
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
3791
3974
  get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
3792
3975
  get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
3976
+ fetchMcpChannelContext(chatId),
3793
3977
  ]);
3794
3978
  // membersData === null means the /members read FAILED (most often a 403 because
3795
3979
  // you are not a member of this channel, or the channel does not exist) — NOT an
@@ -3797,20 +3981,52 @@ const handleToolCall = async (request: any): Promise<any> => {
3797
3981
  // truth was "you cannot see this channel's roster", corrupting their self-model.
3798
3982
  const membersReadable = membersData !== null;
3799
3983
  const memberIds: string[] = (membersData?.members || []).map((m: any) => m?.agent_id).filter(Boolean);
3984
+ const memberIdSet = new Set<string>(memberIds);
3985
+ const rawOnlineSet = new Set<string>();
3800
3986
  let online: string[] = [];
3801
3987
  if (memberIds.length > 0) {
3802
3988
  // Batch the presence query in chunks of 50 so channels with >50 members
3803
3989
  // report accurately (was: memberIds.slice(0,50) — silently wrong past 50).
3804
- const onlineSet = new Set<string>();
3805
3990
  for (let i = 0; i < memberIds.length; i += 50) {
3806
3991
  const batch = memberIds.slice(i, i + 50);
3807
3992
  const pres = await get(`/api/presence?ids=${encodeURIComponent(batch.join(","))}`);
3808
3993
  for (const [k, v] of Object.entries(pres?.presence || {})) {
3809
- if (v === "online") onlineSet.add(k);
3994
+ if (v === "online" && memberIdSet.has(k)) rawOnlineSet.add(k);
3810
3995
  }
3811
3996
  }
3812
- online = [...onlineSet];
3997
+ const maskedOnlineSet = new Set<string>();
3998
+ for (const id of rawOnlineSet) {
3999
+ maskedOnlineSet.add(redactParticipantPii(id));
4000
+ }
4001
+ online = [...maskedOnlineSet];
3813
4002
  }
4003
+ const agentPeers = Array.isArray(mcpCtx?.agents)
4004
+ ? mcpCtx.agents
4005
+ .filter((a: any) => a?.id && !isHumanPiiHandle(a.id))
4006
+ .map((a: any) => ({
4007
+ id: String(a.id),
4008
+ ...(a.name && !isHumanPiiHandle(a.name) ? { name: String(a.name) } : {}),
4009
+ capabilities: Array.isArray(a.capabilities) ? a.capabilities.map(String) : [],
4010
+ ...(typeof a.online === "boolean"
4011
+ ? { online: a.online }
4012
+ : memberIds.length > 0
4013
+ ? { online: rawOnlineSet.has(String(a.id)) }
4014
+ : {}),
4015
+ is_self: typeof a.is_self === "boolean" ? a.is_self : String(a.id) === AGENT_ID,
4016
+ }))
4017
+ : (membersData?.members || [])
4018
+ .filter((m: any) => m?.agent_id && !isHumanPiiHandle(m.agent_id) && m.type !== "user")
4019
+ .map((m: any) => ({
4020
+ id: String(m.agent_id),
4021
+ ...(m.display_name && !isHumanPiiHandle(m.display_name) ? { name: String(m.display_name) } : {}),
4022
+ capabilities: Array.isArray(m.capabilities) ? m.capabilities.map(String) : [],
4023
+ ...(typeof m.online === "boolean"
4024
+ ? { online: m.online }
4025
+ : memberIds.length > 0
4026
+ ? { online: rawOnlineSet.has(String(m.agent_id)) }
4027
+ : {}),
4028
+ is_self: String(m.agent_id) === AGENT_ID,
4029
+ }));
3814
4030
  const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
3815
4031
  const skills = allDocs.filter(isSkillDoc).map((d: any) => ({ doc_id: d.id, title: d.title }));
3816
4032
  const docs = allDocs.filter((d: any) => !isSkillDoc(d)).slice(0, 10).map((d: any) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
@@ -3831,9 +4047,12 @@ const handleToolCall = async (request: any): Promise<any> => {
3831
4047
  }));
3832
4048
  return JSON.stringify({
3833
4049
  channel: chatId,
4050
+ ...(mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {}),
4051
+ ...(mcpCtx?.channel?.topic ? { topic: String(mcpCtx.channel.topic) } : {}),
3834
4052
  members: membersReadable
3835
4053
  ? { total: memberIds.length, online }
3836
4054
  : { total: null, note: "roster unreadable — you are likely not a member of this channel (or it does not exist)" },
4055
+ ...(membersReadable ? { agent_peers: agentPeers } : {}),
3837
4056
  okr_objectives: objectives,
3838
4057
  skills,
3839
4058
  docs,
@@ -4209,13 +4428,43 @@ const handleToolCall = async (request: any): Promise<any> => {
4209
4428
  if (name === "list_members") {
4210
4429
  const { chat_id } = args as any;
4211
4430
  try {
4212
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4431
+ const [r, mcpCtx] = await Promise.all([
4432
+ apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { "Authorization": `Bearer ${TOKEN}` } }),
4433
+ fetchMcpChannelContext(chat_id),
4434
+ ]);
4213
4435
  if (r.ok) {
4214
4436
  const data = await r.json() as any;
4215
4437
  const members = data.members || [];
4216
4438
  if (members.length === 0) return { content: [{ type: "text", text: "No members found." }] };
4217
- const list = members.map((m: any) => `• ${m.display_name || m.agent_id} (${m.agent_id.slice(0, 12)})${m.role ? ` [${m.role}]` : ""}`).join("\n");
4218
- return { content: [{ type: "text", text: `${members.length} members in ${chat_id.slice(0, 8)}:\n${list}` }] };
4439
+ const peerById = new Map<string, { name?: string; capabilities?: string[]; online?: boolean }>();
4440
+ for (const a of Array.isArray(mcpCtx?.agents) ? mcpCtx!.agents! : []) {
4441
+ if (a?.id && !isHumanPiiHandle(a.id)) {
4442
+ peerById.set(String(a.id), a);
4443
+ }
4444
+ }
4445
+ const list = members
4446
+ .map((m: any) => {
4447
+ const rawId = String(m?.agent_id ?? "");
4448
+ const isHuman = isHumanPiiHandle(rawId) || m?.type === "user";
4449
+ const safeId = redactParticipantPii(rawId);
4450
+ const peer = !isHuman ? peerById.get(rawId) : undefined;
4451
+ const rawDisplay = m?.display_name ? String(m.display_name).trim() : (peer?.name ? String(peer.name).trim() : "");
4452
+ const safeDisplay = rawDisplay && !isHumanPiiHandle(rawDisplay) ? rawDisplay : safeId;
4453
+ const handleBadge = isHuman ? `(${safeId})` : `(@${safeId})`;
4454
+ const roleBadge = m?.role ? ` [${m.role}]` : "";
4455
+ const onlineVal = typeof m?.online === "boolean" ? m.online : peer?.online;
4456
+ const onlineBadge = typeof onlineVal === "boolean" ? ` (${onlineVal ? "online" : "offline"})` : "";
4457
+ const caps =
4458
+ Array.isArray(peer?.capabilities) && peer!.capabilities!.length > 0
4459
+ ? peer!.capabilities!
4460
+ : Array.isArray(m?.capabilities)
4461
+ ? m.capabilities
4462
+ : [];
4463
+ const capsBadge = caps.length > 0 ? ` {capabilities: ${caps.join(", ")}}` : "";
4464
+ return `• ${safeDisplay} ${handleBadge}${roleBadge}${onlineBadge}${capsBadge}`;
4465
+ })
4466
+ .join("\n");
4467
+ return { content: [{ type: "text", text: `${members.length} members in ${chat_id}:\n${list}` }] };
4219
4468
  }
4220
4469
  return { content: [{ type: "text", text: `Failed to list members (${r.status})` }] };
4221
4470
  } catch (e) {
@@ -4234,7 +4483,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4234
4483
  full || rawContent.length <= MAX_HISTORY_MESSAGE_CHARS
4235
4484
  ? rawContent
4236
4485
  : `${rawContent.slice(0, MAX_HISTORY_MESSAGE_CHARS)}… [truncated ${rawContent.length - MAX_HISTORY_MESSAGE_CHARS} chars; pass message_id="${m.id || ""}" to get_history for full text]`;
4237
- let line = `[${time}] ${m.sender_id?.slice(0, 12)}: ${body}`;
4486
+ let line = `[${time}] ${redactParticipantPii(m.sender_id || "?")}: ${body}`;
4238
4487
  // Surface media attachments so an agent can perceive voice/image messages,
4239
4488
  // not just their text caption. Audio: show any server transcript inline
4240
4489
  // (agent reads it directly); otherwise point at transcribe(url).
@@ -4866,13 +5115,16 @@ function clearFinishedHiddenIdentityGamesFromMessage(data: any) {
4866
5115
  // duplicate or drop older out-of-order messages that were never processed.
4867
5116
  // Dedup core (key derivation + bounded set) lives in ./dedup.ts; this file
4868
5117
  // keeps the thin logging wrapper so call sites and stderr output are unchanged.
5118
+ const processAgentMessageDedup = new MessageDedup();
4869
5119
  function deliverySource(data: any): string {
4870
5120
  return typeof data?.__source === "string" ? data.__source : "live";
4871
5121
  }
4872
5122
  function recordOrSkipDeliveredMessage(data: any, slot: ProfileSlot | null = activeSlot): boolean {
4873
5123
  const key = messageDedupKey(data);
4874
5124
  if (!key || !slot) return false;
4875
- const skip = slot.messageDedup.recordOrSkip(key);
5125
+ const slotSkip = slot.messageDedup.recordOrSkip(key);
5126
+ const agentSkip = slot.agentId ? processAgentMessageDedup.recordOrSkip(`${slot.agentId}:${key}`) : false;
5127
+ const skip = slotSkip || agentSkip;
4876
5128
  if (skip) {
4877
5129
  process.stderr.write(
4878
5130
  `[agentchat] Duplicate message skipped source=${deliverySource(data)} chat=${String(data.channel_id).slice(0, 12)} id=${String(data.id).slice(0, 12)}\n`,
@@ -4965,6 +5217,26 @@ function syncOpenBoundSessions(): void {
4965
5217
  try {
4966
5218
  const candidate = readIdentityProfile(boundPath);
4967
5219
  validateIdentityProfile(candidate, boundPath);
5220
+ const sess: DetectedSession = { sessionId: cid, runtime: "antigravity" };
5221
+ // Prevent duplicate WebSocket slots when `profile.json` and `<Name>.json`
5222
+ // share the same `agent_id`: upgrade the unbound alias slot in-place.
5223
+ const existingByAgent = findSlotByAgentId(candidate.agent_id);
5224
+ if (existingByAgent) {
5225
+ const existingSid =
5226
+ existingByAgent.runtimeSession?.sessionId ||
5227
+ findBoundSessionForProfile(configDir, existingByAgent.profileName);
5228
+ if (!existingSid || existingSid === cid) {
5229
+ upgradeAliasSlotInPlace(existingByAgent, boundProf, boundPath, candidate, sess);
5230
+ acquireAgentLock({
5231
+ lockDir,
5232
+ agentId: existingByAgent.agentId,
5233
+ profileName: boundProf,
5234
+ sessionId: cid,
5235
+ runtime: "antigravity",
5236
+ });
5237
+ }
5238
+ continue;
5239
+ }
4968
5240
  const lock = checkAgentLock({
4969
5241
  lockDir,
4970
5242
  agentId: candidate.agent_id,
@@ -4972,7 +5244,6 @@ function syncOpenBoundSessions(): void {
4972
5244
  lockOwnerPid,
4973
5245
  });
4974
5246
  if (lock.locked) continue;
4975
- const sess: DetectedSession = { sessionId: cid, runtime: "antigravity" };
4976
5247
  acquireAgentLock({
4977
5248
  lockDir,
4978
5249
  agentId: candidate.agent_id,
@@ -5132,7 +5403,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5132
5403
  const truncatedMsgs = trimmed.length < msgs.length;
5133
5404
  if (trimmed.length > 0) {
5134
5405
  const context = trimmed
5135
- .map((m: any) => `${m.sender_id}: ${m.content}${formatWakeAttachments(m.attachments)}`)
5406
+ .map((m: any) => `${redactParticipantPii(m.sender_id || "?")}: ${m.content}${formatWakeAttachments(m.attachments)}`)
5136
5407
  .join("\n");
5137
5408
  const note = truncatedMsgs
5138
5409
  ? `[频道上下文 - 最近 ${trimmed.length} 条消息(更早的已截断保护上下文窗口)]`
@@ -5221,8 +5492,10 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5221
5492
  process.env.AGENTCHAT_WAKE_MODE === "zcode" ||
5222
5493
  Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")))
5223
5494
  ) {
5495
+ const isZcodeSid = (sid: string) => sid.startsWith("sess_");
5224
5496
  const zcodeSid =
5225
- findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")) ||
5497
+ findBoundSessionForProfile(configDir, slotProfName, isZcodeSid) ||
5498
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isZcodeSid })?.sessionId ||
5226
5499
  (slotRuntime === "zcode" ? slot!.runtimeSession?.sessionId : "") ||
5227
5500
  "";
5228
5501
  if (zcodeSid) {
@@ -5240,9 +5513,10 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5240
5513
  isDshHostProcess() ||
5241
5514
  Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")))
5242
5515
  ) {
5516
+ const isDshSid = (sid: string) => sid.startsWith("session-");
5243
5517
  const dshSid =
5244
- findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")) ||
5245
- resolveSessionForAgent(slot!.agentId, { configDir })?.sessionId ||
5518
+ findBoundSessionForProfile(configDir, slotProfName, isDshSid) ||
5519
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isDshSid })?.sessionId ||
5246
5520
  (slotRuntime === "dsh" ? slot!.runtimeSession?.sessionId : "") ||
5247
5521
  undefined;
5248
5522
  const dshWakeUrl =
@@ -5262,19 +5536,42 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5262
5536
  const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
5263
5537
  const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
5264
5538
  if (!agyHost && !lsAddress) return;
5539
+ const isAgyUuid = (sid: string) =>
5540
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
5265
5541
  const allBinds = loadSessionBinds(configDir);
5266
5542
  let targetCid =
5267
- findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) ||
5268
- (slotRuntime === "antigravity" ? slot!.runtimeSession?.sessionId : "") ||
5543
+ findBoundSessionForProfile(configDir, slotProfName, isAgyUuid) ||
5544
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isAgyUuid })?.sessionId ||
5545
+ (slotRuntime === "antigravity" &&
5546
+ slot!.runtimeSession?.sessionId &&
5547
+ isAgyUuid(slot!.runtimeSession.sessionId)
5548
+ ? slot!.runtimeSession.sessionId
5549
+ : "") ||
5269
5550
  "";
5270
5551
  if (!targetCid && agyHost) {
5271
5552
  if (agyHost.openConversations.length === 1) {
5272
- targetCid = agyHost.openConversations[0]!;
5553
+ const soleCid = agyHost.openConversations[0]!;
5554
+ const soleBoundProf = allBinds[soleCid];
5555
+ let soleMatchesAgent = false;
5556
+ if (soleBoundProf) {
5557
+ const p = nameToPath(soleBoundProf);
5558
+ if (existsSync(p)) {
5559
+ try {
5560
+ soleMatchesAgent = readIdentityProfile(p)?.agent_id === slot!.agentId;
5561
+ } catch {}
5562
+ }
5563
+ }
5564
+ if (!soleBoundProf || soleBoundProf === slotProfName || soleMatchesAgent) {
5565
+ targetCid = soleCid;
5566
+ }
5273
5567
  } else if (agyHost.openConversations.length > 1) {
5274
- const unboundOrSame = agyHost.openConversations.find(
5275
- (cid) => !allBinds[cid] || allBinds[cid] === slotProfName,
5568
+ // Never guess an unbound conversation (`!allBinds[cid]`) or `openConversations[0]`
5569
+ // when multiple Antigravity windows are open — guessing leaks wakes into
5570
+ // unrelated project windows!
5571
+ rateLimitedLog(
5572
+ `agy-wake-unbound:${slot!.agentId}`,
5573
+ `[agentchat] Skipping ambiguous Antigravity wake for ${slot!.agentId}: ${agyHost.openConversations.length} conversations are open and none is bound to this agent (call whoami or connect_profile in the target conversation to bind it).\n`,
5276
5574
  );
5277
- targetCid = unboundOrSame || agyHost.openConversations[0]!;
5278
5575
  }
5279
5576
  }
5280
5577
  if (targetCid && csrfToken) {
@@ -5436,6 +5733,17 @@ async function main() {
5436
5733
  installStdioLifecycleGuards();
5437
5734
  if (!toolOnlyMode) {
5438
5735
  syncOpenBoundSessions();
5736
+ if (
5737
+ process.env.__CFBundleIdentifier === "com.google.antigravity" ||
5738
+ Boolean(process.env.AGY_BROWSER_WS_URL) ||
5739
+ Boolean(process.env.ANTIGRAVITY_LS_ADDRESS) ||
5740
+ Boolean(discoverAntigravityHost())
5741
+ ) {
5742
+ const agySyncTimer = setInterval(() => {
5743
+ if (!shuttingDown) syncOpenBoundSessions();
5744
+ }, 15_000);
5745
+ (agySyncTimer as any).unref?.();
5746
+ }
5439
5747
  }
5440
5748
  // Anonymous = no credentials to present. Connecting would just fail auth in a
5441
5749
  // reconnect loop; stdio (initialize/tools/list) is served either way.