agentschat-mcp 0.36.22 → 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";
@@ -108,7 +108,7 @@ import { join, dirname } from "path";
108
108
  import { fileURLToPath } from "url";
109
109
  // Atomic + 0600-by-construction profile writer. Lives in its own module so the
110
110
  // "the key is never world-readable, even mid-write" property is directly testable.
111
- import { safeWriteProfile } from "./profile-store.ts";
111
+ import { safeWriteProfile, findDefaultProfileCollision } from "./profile-store.ts";
112
112
  import {
113
113
  decideIdentityGuard,
114
114
  advanceGuardRecord,
@@ -433,43 +433,63 @@ function readIdentityProfile(file: string): any {
433
433
  }
434
434
 
435
435
  if (identity.mode === "profile") {
436
- try {
437
- profile = readIdentityProfile(profileFile);
438
- if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
439
- throw new Error("Project agent_id does not match selected profile");
440
- }
441
- validateIdentityProfile(profile && !Array.isArray(profile) ? {
442
- ...profile,
443
- agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
444
- token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
445
- capabilities: cliArgs.caps?.split(",") ?? profile.capabilities,
446
- } : profile, profileFile, !hasToken);
447
- } catch (e) {
448
- process.stderr.write(`[agentchat] ERROR: ${(e as Error).message}\n`);
449
- process.exit(1);
450
- }
451
- const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
452
- const lockCheck = (!cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
453
- ? checkAgentLock({
454
- lockDir,
455
- agentId: candidateAgentId,
456
- currentSessionId: runtimeSession?.sessionId ?? null,
457
- lockOwnerPid,
458
- })
459
- : { locked: false };
460
- 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
+ }
461
447
  anonymousMode = true;
462
448
  activeProfileFile = null;
463
449
  profile = {};
464
450
  process.stderr.write(
465
- `[agentchat] Profile "${declaredName ?? profileNameFromPath(profileFile) ?? "profile"}" (${lockCheck.holder?.agentId}) is already in use by active process pid=${lockCheck.holder?.pid}` +
466
- `${lockCheck.holder?.runtime ? ` (${lockCheck.holder.runtime})` : ""}` +
467
- `${lockCheck.holder?.sessionId ? ` session=${lockCheck.holder.sessionId}` : ""}.\n` +
468
- ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.\n` +
469
- ` 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`,
470
453
  );
471
454
  } else {
472
- 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
+ }
473
493
  }
474
494
  } else if (identity.mode === "env-creds") {
475
495
  // Token handed to us directly — authenticate with it, register nothing, write nothing.
@@ -638,19 +658,28 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
638
658
  }
639
659
 
640
660
  if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
641
- const activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
642
- if (
643
- activeName &&
644
- runtimeSession?.runtime === "antigravity" &&
645
- !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim()
646
- ) {
647
- const existingBoundSid = findBoundSessionForProfile(
648
- configDir,
649
- activeName,
650
- (sid) => /^[0-9a-f-]{36}$/i.test(sid),
651
- );
652
- if (existingBoundSid) {
653
- 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
+ }
654
683
  }
655
684
  }
656
685
  acquireAgentLock({
@@ -661,7 +690,14 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
661
690
  runtime: runtimeSession?.runtime ?? "mcp",
662
691
  });
663
692
  if (runtimeSession?.sessionId && activeName) {
664
- 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
+ }
665
701
  }
666
702
  }
667
703
 
@@ -1651,7 +1687,7 @@ const ALL_TOOL_DEFS = [
1651
1687
  },
1652
1688
  {
1653
1689
  name: "channel_brief",
1654
- 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.",
1655
1691
  inputSchema: {
1656
1692
  type: "object" as const,
1657
1693
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -1660,7 +1696,7 @@ const ALL_TOOL_DEFS = [
1660
1696
  },
1661
1697
  {
1662
1698
  name: "list_members",
1663
- 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).",
1664
1700
  inputSchema: {
1665
1701
  type: "object" as const,
1666
1702
  properties: {
@@ -2489,6 +2525,34 @@ function setAnonymousCallerState(callerSession?: DetectedSession | null): void {
2489
2525
  }
2490
2526
  }
2491
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
+
2492
2556
  function teardownSlot(slot: ProfileSlot, opts?: { releaseLock?: boolean }): void {
2493
2557
  try { flushSlotLastSeenMessageTs(slot); } catch {}
2494
2558
  try { slot.heartbeat.stop(); } catch {}
@@ -2683,11 +2747,15 @@ function formatProfileList(): string {
2683
2747
  : { locked: false };
2684
2748
  const slot = profileSlots.get(entry.name);
2685
2749
  const boundSid = findBoundSessionForProfile(configDir, entry.name);
2686
- const statusSuffix = lock.locked
2687
- ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]`
2688
- : slot && slot.ws?.readyState === WebSocket.OPEN
2689
- ? ` [online${boundSid ? ` session=${boundSid}` : ""}]`
2690
- : "";
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
+ : "";
2691
2759
  return `${isCurrent ? "→ " : " "}${entry.name}${statusSuffix}`;
2692
2760
  });
2693
2761
  return `Current: ${current || "(anonymous / disconnected)"}\nAvailable profiles:\n${lines.join("\n")}`;
@@ -2701,6 +2769,42 @@ async function registerAndConnectProfile(
2701
2769
  if (!cleanName) {
2702
2770
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
2703
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
+ }
2704
2808
  const caps = ["claude-code", "coding", "chat"];
2705
2809
  try {
2706
2810
  const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
@@ -2732,10 +2836,6 @@ async function registerAndConnectProfile(
2732
2836
  validateIdentityProfile(newProfile, targetFile);
2733
2837
  mkdirSync(dirname(targetFile), { recursive: true });
2734
2838
  safeWriteProfile(targetFile, newProfile);
2735
- const defaultProfileFile = nameToPath("profile");
2736
- if (!existsSync(defaultProfileFile)) {
2737
- safeWriteProfile(defaultProfileFile, newProfile);
2738
- }
2739
2839
  applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
2740
2840
  const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
2741
2841
  return {
@@ -2825,6 +2925,21 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
2825
2925
  };
2826
2926
  }
2827
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
+
2828
2943
  const newProfile = readIdentityProfile(targetFile);
2829
2944
  validateIdentityProfile(newProfile, targetFile);
2830
2945
 
@@ -3097,16 +3212,37 @@ const handleToolCall = async (request: any): Promise<any> => {
3097
3212
  if (existsSync(boundPath)) {
3098
3213
  try {
3099
3214
  const candidate = readIdentityProfile(boundPath);
3100
- const lock = checkAgentLock({
3101
- lockDir,
3102
- agentId: candidate?.agent_id,
3103
- currentSessionId: callerSession.sessionId,
3104
- lockOwnerPid,
3105
- });
3106
- if (!lock.locked) {
3107
- applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
3108
- } else if (isPerCallSession) {
3109
- 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
+ }
3110
3246
  }
3111
3247
  } catch {}
3112
3248
  } else if (isPerCallSession) {
@@ -3119,7 +3255,9 @@ const handleToolCall = async (request: any): Promise<any> => {
3119
3255
  let unboundSlot: ProfileSlot | null = null;
3120
3256
  for (const slot of profileSlots.values()) {
3121
3257
  const slotBoundSid =
3122
- slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
3258
+ slot.runtimeSession?.sessionId ||
3259
+ findBoundSessionForProfile(configDir, slot.profileName) ||
3260
+ resolveSessionForAgent(slot.agentId, { configDir })?.sessionId;
3123
3261
  if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
3124
3262
  unboundSlot = slot;
3125
3263
  break;
@@ -3738,7 +3876,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3738
3876
  const data = await r.json() as any;
3739
3877
  if (data.messages?.length > 0) {
3740
3878
  const results = data.messages.map((m: any) =>
3741
- `[${m.sender_id?.slice(0, 8)}] ${m.content?.slice(0, 80)}`
3879
+ `[${redactParticipantPii(m.sender_id || "?")}] ${m.content?.slice(0, 80)}`
3742
3880
  ).join("\n");
3743
3881
  return { content: [{ type: "text", text: `Found ${data.messages.length} results:\n${results}` }] };
3744
3882
  }
@@ -3779,9 +3917,51 @@ const handleToolCall = async (request: any): Promise<any> => {
3779
3917
  return { content: [{ type: "text", text: "Not connected" }] };
3780
3918
  }
3781
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
+
3782
3962
  // P3 capability synopsis (kr_mq66wu4u): everything an agent can DO in a
3783
- // channel, composed from existing REST reads. Sections fail soft (null)
3784
- // 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.
3785
3965
  async function channelBrief(chatId: string): Promise<string> {
3786
3966
  const get = async (path: string) => {
3787
3967
  try {
@@ -3789,10 +3969,11 @@ const handleToolCall = async (request: any): Promise<any> => {
3789
3969
  return r.ok ? await r.json() as any : null;
3790
3970
  } catch { return null; }
3791
3971
  };
3792
- const [membersData, docsData, okrData] = await Promise.all([
3972
+ const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
3793
3973
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
3794
3974
  get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
3795
3975
  get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
3976
+ fetchMcpChannelContext(chatId),
3796
3977
  ]);
3797
3978
  // membersData === null means the /members read FAILED (most often a 403 because
3798
3979
  // you are not a member of this channel, or the channel does not exist) — NOT an
@@ -3800,20 +3981,52 @@ const handleToolCall = async (request: any): Promise<any> => {
3800
3981
  // truth was "you cannot see this channel's roster", corrupting their self-model.
3801
3982
  const membersReadable = membersData !== null;
3802
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>();
3803
3986
  let online: string[] = [];
3804
3987
  if (memberIds.length > 0) {
3805
3988
  // Batch the presence query in chunks of 50 so channels with >50 members
3806
3989
  // report accurately (was: memberIds.slice(0,50) — silently wrong past 50).
3807
- const onlineSet = new Set<string>();
3808
3990
  for (let i = 0; i < memberIds.length; i += 50) {
3809
3991
  const batch = memberIds.slice(i, i + 50);
3810
3992
  const pres = await get(`/api/presence?ids=${encodeURIComponent(batch.join(","))}`);
3811
3993
  for (const [k, v] of Object.entries(pres?.presence || {})) {
3812
- if (v === "online") onlineSet.add(k);
3994
+ if (v === "online" && memberIdSet.has(k)) rawOnlineSet.add(k);
3813
3995
  }
3814
3996
  }
3815
- online = [...onlineSet];
3997
+ const maskedOnlineSet = new Set<string>();
3998
+ for (const id of rawOnlineSet) {
3999
+ maskedOnlineSet.add(redactParticipantPii(id));
4000
+ }
4001
+ online = [...maskedOnlineSet];
3816
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
+ }));
3817
4030
  const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
3818
4031
  const skills = allDocs.filter(isSkillDoc).map((d: any) => ({ doc_id: d.id, title: d.title }));
3819
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 }));
@@ -3834,9 +4047,12 @@ const handleToolCall = async (request: any): Promise<any> => {
3834
4047
  }));
3835
4048
  return JSON.stringify({
3836
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) } : {}),
3837
4052
  members: membersReadable
3838
4053
  ? { total: memberIds.length, online }
3839
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 } : {}),
3840
4056
  okr_objectives: objectives,
3841
4057
  skills,
3842
4058
  docs,
@@ -4212,13 +4428,43 @@ const handleToolCall = async (request: any): Promise<any> => {
4212
4428
  if (name === "list_members") {
4213
4429
  const { chat_id } = args as any;
4214
4430
  try {
4215
- 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
+ ]);
4216
4435
  if (r.ok) {
4217
4436
  const data = await r.json() as any;
4218
4437
  const members = data.members || [];
4219
4438
  if (members.length === 0) return { content: [{ type: "text", text: "No members found." }] };
4220
- const list = members.map((m: any) => `• ${m.display_name || m.agent_id} (${m.agent_id.slice(0, 12)})${m.role ? ` [${m.role}]` : ""}`).join("\n");
4221
- 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}` }] };
4222
4468
  }
4223
4469
  return { content: [{ type: "text", text: `Failed to list members (${r.status})` }] };
4224
4470
  } catch (e) {
@@ -4237,7 +4483,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4237
4483
  full || rawContent.length <= MAX_HISTORY_MESSAGE_CHARS
4238
4484
  ? rawContent
4239
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]`;
4240
- let line = `[${time}] ${m.sender_id?.slice(0, 12)}: ${body}`;
4486
+ let line = `[${time}] ${redactParticipantPii(m.sender_id || "?")}: ${body}`;
4241
4487
  // Surface media attachments so an agent can perceive voice/image messages,
4242
4488
  // not just their text caption. Audio: show any server transcript inline
4243
4489
  // (agent reads it directly); otherwise point at transcribe(url).
@@ -4869,13 +5115,16 @@ function clearFinishedHiddenIdentityGamesFromMessage(data: any) {
4869
5115
  // duplicate or drop older out-of-order messages that were never processed.
4870
5116
  // Dedup core (key derivation + bounded set) lives in ./dedup.ts; this file
4871
5117
  // keeps the thin logging wrapper so call sites and stderr output are unchanged.
5118
+ const processAgentMessageDedup = new MessageDedup();
4872
5119
  function deliverySource(data: any): string {
4873
5120
  return typeof data?.__source === "string" ? data.__source : "live";
4874
5121
  }
4875
5122
  function recordOrSkipDeliveredMessage(data: any, slot: ProfileSlot | null = activeSlot): boolean {
4876
5123
  const key = messageDedupKey(data);
4877
5124
  if (!key || !slot) return false;
4878
- 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;
4879
5128
  if (skip) {
4880
5129
  process.stderr.write(
4881
5130
  `[agentchat] Duplicate message skipped source=${deliverySource(data)} chat=${String(data.channel_id).slice(0, 12)} id=${String(data.id).slice(0, 12)}\n`,
@@ -4968,6 +5217,26 @@ function syncOpenBoundSessions(): void {
4968
5217
  try {
4969
5218
  const candidate = readIdentityProfile(boundPath);
4970
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
+ }
4971
5240
  const lock = checkAgentLock({
4972
5241
  lockDir,
4973
5242
  agentId: candidate.agent_id,
@@ -4975,7 +5244,6 @@ function syncOpenBoundSessions(): void {
4975
5244
  lockOwnerPid,
4976
5245
  });
4977
5246
  if (lock.locked) continue;
4978
- const sess: DetectedSession = { sessionId: cid, runtime: "antigravity" };
4979
5247
  acquireAgentLock({
4980
5248
  lockDir,
4981
5249
  agentId: candidate.agent_id,
@@ -5135,7 +5403,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5135
5403
  const truncatedMsgs = trimmed.length < msgs.length;
5136
5404
  if (trimmed.length > 0) {
5137
5405
  const context = trimmed
5138
- .map((m: any) => `${m.sender_id}: ${m.content}${formatWakeAttachments(m.attachments)}`)
5406
+ .map((m: any) => `${redactParticipantPii(m.sender_id || "?")}: ${m.content}${formatWakeAttachments(m.attachments)}`)
5139
5407
  .join("\n");
5140
5408
  const note = truncatedMsgs
5141
5409
  ? `[频道上下文 - 最近 ${trimmed.length} 条消息(更早的已截断保护上下文窗口)]`
@@ -5224,8 +5492,10 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5224
5492
  process.env.AGENTCHAT_WAKE_MODE === "zcode" ||
5225
5493
  Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")))
5226
5494
  ) {
5495
+ const isZcodeSid = (sid: string) => sid.startsWith("sess_");
5227
5496
  const zcodeSid =
5228
- findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")) ||
5497
+ findBoundSessionForProfile(configDir, slotProfName, isZcodeSid) ||
5498
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isZcodeSid })?.sessionId ||
5229
5499
  (slotRuntime === "zcode" ? slot!.runtimeSession?.sessionId : "") ||
5230
5500
  "";
5231
5501
  if (zcodeSid) {
@@ -5243,9 +5513,10 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5243
5513
  isDshHostProcess() ||
5244
5514
  Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")))
5245
5515
  ) {
5516
+ const isDshSid = (sid: string) => sid.startsWith("session-");
5246
5517
  const dshSid =
5247
- findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")) ||
5248
- resolveSessionForAgent(slot!.agentId, { configDir })?.sessionId ||
5518
+ findBoundSessionForProfile(configDir, slotProfName, isDshSid) ||
5519
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isDshSid })?.sessionId ||
5249
5520
  (slotRuntime === "dsh" ? slot!.runtimeSession?.sessionId : "") ||
5250
5521
  undefined;
5251
5522
  const dshWakeUrl =
@@ -5265,19 +5536,42 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5265
5536
  const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
5266
5537
  const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
5267
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);
5268
5541
  const allBinds = loadSessionBinds(configDir);
5269
5542
  let targetCid =
5270
- findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) ||
5271
- (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
+ : "") ||
5272
5550
  "";
5273
5551
  if (!targetCid && agyHost) {
5274
5552
  if (agyHost.openConversations.length === 1) {
5275
- 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
+ }
5276
5567
  } else if (agyHost.openConversations.length > 1) {
5277
- const unboundOrSame = agyHost.openConversations.find(
5278
- (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`,
5279
5574
  );
5280
- targetCid = unboundOrSame || agyHost.openConversations[0]!;
5281
5575
  }
5282
5576
  }
5283
5577
  if (targetCid && csrfToken) {
@@ -5439,6 +5733,17 @@ async function main() {
5439
5733
  installStdioLifecycleGuards();
5440
5734
  if (!toolOnlyMode) {
5441
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
+ }
5442
5747
  }
5443
5748
  // Anonymous = no credentials to present. Connecting would just fail auth in a
5444
5749
  // reconnect loop; stdio (initialize/tools/list) is served either way.