agentschat-mcp 0.36.22 → 0.36.24

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,
@@ -123,17 +123,33 @@ import {
123
123
  } from "./identity-guard.ts";
124
124
  // Read-cursor persistence: a state change that merely *lives* in the teardown path.
125
125
  import { flushCursor, loadCursor, persistCursor } from "./read-cursor.ts";
126
+ import { CURSOR_INIT_KEY, joinChannelRest, parseMaxIdleMs, sendRestMessage, wakeOnce } from "./rest-cli.ts";
126
127
  import { randomUUID } from "crypto";
127
128
 
128
129
  function parseArgs() {
129
130
  const args = process.argv.slice(2);
130
131
  const parsed: Record<string, string> = {};
131
- const values = new Set(["name", "id", "url", "token", "caps", "profile"]);
132
+ const values = new Set([
133
+ "name",
134
+ "id",
135
+ "url",
136
+ "token",
137
+ "caps",
138
+ "profile",
139
+ "join",
140
+ "send",
141
+ "text",
142
+ "reply-to",
143
+ "channel",
144
+ "timeout",
145
+ "max-idle",
146
+ ]);
132
147
  for (let i = 0; i < args.length; i++) {
133
148
  const arg = args[i];
134
149
  if (arg === "--help" || arg === "-h") continue;
135
150
  if (arg === "--register") { parsed.register = "1"; continue; }
136
151
  if (arg === "--register-only") { parsed.registerOnly = "1"; continue; }
152
+ if (arg === "--wake-once") { parsed.wakeOnce = "1"; continue; }
137
153
  if (arg === "--accept-terms") continue; // Legacy compatibility; no consent is recorded.
138
154
  const equal = arg.indexOf("=");
139
155
  const key = (equal < 0 ? arg : arg.slice(0, equal)).slice(2);
@@ -142,7 +158,7 @@ function parseArgs() {
142
158
  process.exit(1);
143
159
  }
144
160
  const value = equal < 0 ? args[++i] : arg.slice(equal + 1);
145
- if (!value?.trim() || value.startsWith("-")) {
161
+ if (!value?.trim() || (key !== "text" && value.startsWith("-"))) {
146
162
  process.stderr.write(`[agentchat] ERROR: missing value for --${key}. See --help.\n`);
147
163
  process.exit(1);
148
164
  }
@@ -152,6 +168,7 @@ function parseArgs() {
152
168
  }
153
169
 
154
170
  const cliArgs = parseArgs();
171
+ const isOneShotCli = Boolean(cliArgs.registerOnly || cliArgs.join || cliArgs.send || cliArgs.wakeOnce);
155
172
 
156
173
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
157
174
  const localOnboardingPath = join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
@@ -176,6 +193,14 @@ Options:
176
193
  --profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
177
194
  --register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
178
195
  --register Explicitly opt in to registering a new agent (implied by --name)
196
+ --join <channel> Join a public channel via REST (e.g. --join welcome) and exit (or combine with --send / --wake-once).
197
+ --send <channel> Send a message to <channel> via REST (--text <msg> [--reply-to <msg_id>]), advance read cursor, and exit.
198
+ --text <msg> Message content for --send.
199
+ --reply-to <id> Optional target message ID for --send.
200
+ --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.
201
+ --channel <ids> Comma-separated channels to join/watch with --wake-once (default: welcome + all joined channels).
202
+ --timeout <sec> Max wait time in seconds per --wake-once window (default: 240).
203
+ --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: 3600 = 1 hour).
179
204
  --accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
180
205
  No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
181
206
  --id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
@@ -222,6 +247,25 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
222
247
 
223
248
  // Explicit CLI selection > project binding > runtime binding > environment > default.
224
249
  // Onboarding resolves ambiguous unbound candidates with the user; never scan-and-pick.
250
+ // A dedicated Codex bridge is the identity authority for all inherited MCP entries.
251
+ // No credentials in this envelope; read the existing private profile.
252
+ const codexIdentity = process.env.AGENTSCHAT_CODEX_IDENTITY
253
+ ? JSON.parse(process.env.AGENTSCHAT_CODEX_IDENTITY) as { profileFile: string; agentId: string; apiUrl: string; wsUrl: string }
254
+ : undefined;
255
+ if (codexIdentity) {
256
+ if (process.env.AGENTSCHAT_TOOL_ONLY !== "1" ||
257
+ [codexIdentity.profileFile, codexIdentity.agentId, codexIdentity.apiUrl, codexIdentity.wsUrl].some(v => typeof v !== "string" || !v.trim())) {
258
+ throw new Error("Invalid Codex tool identity");
259
+ }
260
+ // Override inherited CLI/project/env selectors; they may belong to another bot.
261
+ cliArgs.profile = codexIdentity.profileFile;
262
+ cliArgs.id = codexIdentity.agentId;
263
+ cliArgs.url = codexIdentity.apiUrl;
264
+ delete cliArgs.token;
265
+ delete cliArgs.name;
266
+ delete process.env.AGENTCHAT_TOKEN;
267
+ process.env.AGENTSCHAT_EXPECT_AGENT_ID = codexIdentity.agentId;
268
+ }
225
269
  const homeDir = process.env.HOME || process.env.USERPROFILE || ".";
226
270
  const configDir = join(homeDir, ".agentschat");
227
271
  const legacyConfigDir = join(homeDir, ".agentchat");
@@ -229,7 +273,15 @@ const profileDirs = [configDir, legacyConfigDir];
229
273
  const lockDir = resolveLockDir(homeDir, process.env);
230
274
  const lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
231
275
  const toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
232
- let runtimeSession: DetectedSession | null = detectRuntimeSession(process.env);
276
+ let runtimeSessionComputed = false;
277
+ let runtimeSession: DetectedSession | null = null;
278
+ function ensureRuntimeSession(): DetectedSession | null {
279
+ if (!runtimeSessionComputed) {
280
+ runtimeSessionComputed = true;
281
+ runtimeSession = detectRuntimeSession(process.env);
282
+ }
283
+ return runtimeSession;
284
+ }
233
285
  /** One-shot notice when DSH is detected but no session can be resolved (see the DSH branch). */
234
286
  let dshRouteWarned = false;
235
287
 
@@ -331,13 +383,14 @@ function resolveProfile(): { path: string; source: ProfileSource; declaredName?:
331
383
 
332
384
  // Unified session-bind (`~/.agentschat/session-binds.json` / `agy-binds.json`):
333
385
  // maps CLAUDE_CODE_SESSION_ID / ANTIGRAVITY_CONVERSATION_ID / ZCODE_SESSION_ID to a profile.
334
- if (!grokToken && runtimeSession?.sessionId) {
386
+ const bootSession = !grokToken ? ensureRuntimeSession() : null;
387
+ if (!grokToken && bootSession?.sessionId) {
335
388
  const sessionBinds = loadSessionBinds(configDir);
336
- const boundProfile = sessionBinds[runtimeSession.sessionId];
389
+ const boundProfile = sessionBinds[bootSession.sessionId];
337
390
  if (boundProfile) {
338
391
  const boundPath = nameToPath(boundProfile);
339
392
  if (existsSync(boundPath)) {
340
- process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} → profile "${boundProfile}"\n`);
393
+ process.stderr.write(`[agentchat] session-bind (${bootSession.runtime}): ${bootSession.sessionId} → profile "${boundProfile}"\n`);
341
394
  return { path: boundPath, source: "session-bind", declaredName: boundProfile };
342
395
  }
343
396
  }
@@ -433,43 +486,67 @@ function readIdentityProfile(file: string): any {
433
486
  }
434
487
 
435
488
  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) {
489
+ const isDefaultProfileFile =
490
+ profileSource === "default" || profileNameFromPath(profileFile)?.toLowerCase() === "profile";
491
+ const defaultCollision = isDefaultProfileFile ? findDefaultProfileCollision(configDir, profileFile) : null;
492
+ if (defaultCollision) {
493
+ if (profileSource !== "default") {
494
+ process.stderr.write(
495
+ `[agentchat] ERROR: Refusing to load duplicate profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).\n` +
496
+ ` Delete ${profileFile} and use --profile ${defaultCollision.collidingName} instead.\n`,
497
+ );
498
+ process.exit(1);
499
+ }
461
500
  anonymousMode = true;
462
501
  activeProfileFile = null;
463
502
  profile = {};
464
503
  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`,
504
+ `[agentchat] Ignoring duplicate default profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).\n` +
505
+ ` Starting in ANONYMOUS mode instead of shadowing "${defaultCollision.collidingName}". Delete ${profileFile} or bind this session via connect_profile(profile_name="${defaultCollision.collidingName}").\n`,
470
506
  );
471
507
  } else {
472
- process.stderr.write(`[agentchat] Profile loaded: ${profileFile}\n`);
508
+ try {
509
+ profile = readIdentityProfile(profileFile);
510
+ if (codexIdentity && profile.agent_id !== codexIdentity.agentId) {
511
+ throw new Error("Codex tool profile identity mismatch");
512
+ }
513
+ if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
514
+ throw new Error("Project agent_id does not match selected profile");
515
+ }
516
+ validateIdentityProfile(profile && !Array.isArray(profile) ? {
517
+ ...profile,
518
+ agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
519
+ token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
520
+ capabilities: cliArgs.caps?.split(",") ?? profile.capabilities,
521
+ } : profile, profileFile, !hasToken);
522
+ } catch (e) {
523
+ process.stderr.write(`[agentchat] ERROR: ${(e as Error).message}\n`);
524
+ process.exit(1);
525
+ }
526
+ const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
527
+ if (!isOneShotCli && !toolOnlyMode) ensureRuntimeSession();
528
+ const lockCheck = (!isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token")
529
+ ? checkAgentLock({
530
+ lockDir,
531
+ agentId: candidateAgentId,
532
+ currentSessionId: runtimeSession?.sessionId ?? null,
533
+ lockOwnerPid,
534
+ })
535
+ : { locked: false };
536
+ if (lockCheck.locked) {
537
+ anonymousMode = true;
538
+ activeProfileFile = null;
539
+ profile = {};
540
+ process.stderr.write(
541
+ `[agentchat] Profile "${declaredName ?? profileNameFromPath(profileFile) ?? "profile"}" (${lockCheck.holder?.agentId}) is already in use by active process pid=${lockCheck.holder?.pid}` +
542
+ `${lockCheck.holder?.runtime ? ` (${lockCheck.holder.runtime})` : ""}` +
543
+ `${lockCheck.holder?.sessionId ? ` session=${lockCheck.holder.sessionId}` : ""}.\n` +
544
+ ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.\n` +
545
+ ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.\n`,
546
+ );
547
+ } else {
548
+ process.stderr.write(`[agentchat] Profile loaded: ${profileFile}\n`);
549
+ }
473
550
  }
474
551
  } else if (identity.mode === "env-creds") {
475
552
  // Token handed to us directly — authenticate with it, register nothing, write nothing.
@@ -637,20 +714,29 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
637
714
  }
638
715
  }
639
716
 
640
- 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" };
717
+ if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
718
+ let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
719
+ 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);
720
+ const isImplicitAgyBoot =
721
+ (runtimeSession?.runtime === "antigravity" || (!runtimeSession && Boolean(discoverAntigravityHost()))) &&
722
+ !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
723
+ if (activeName && isImplicitAgyBoot) {
724
+ const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
725
+ const existingAgentRoute = resolveSessionForAgent(AGENT_ID, { configDir, filter: isAgyUuid });
726
+ const resolvedSid = existingBoundSid || existingAgentRoute?.sessionId || "";
727
+ if (resolvedSid) {
728
+ runtimeSession = { sessionId: resolvedSid, runtime: "antigravity" };
729
+ if (
730
+ profileSource === "default" &&
731
+ existingAgentRoute?.profileName &&
732
+ existingAgentRoute.profileName !== activeName
733
+ ) {
734
+ const aliasPath = nameToPath(existingAgentRoute.profileName);
735
+ if (existsSync(aliasPath)) {
736
+ activeProfileFile = aliasPath;
737
+ activeName = existingAgentRoute.profileName;
738
+ }
739
+ }
654
740
  }
655
741
  }
656
742
  acquireAgentLock({
@@ -661,7 +747,14 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
661
747
  runtime: runtimeSession?.runtime ?? "mcp",
662
748
  });
663
749
  if (runtimeSession?.sessionId && activeName) {
664
- saveSessionBind(configDir, runtimeSession.sessionId, activeName);
750
+ // Only auto-persist session-binds at boot when the session ID was explicitly
751
+ // supplied (e.g. CLAUDE_CODE_SESSION_ID / ZCODE_SESSION_ID / ANTIGRAVITY_CONVERSATION_ID)
752
+ // or already matches an existing bind — never passively bind a random open
753
+ // Antigravity window before that conversation invokes any AgentsChat tool.
754
+ const existingBinds = loadSessionBinds(configDir);
755
+ if (!isImplicitAgyBoot || existingBinds[runtimeSession.sessionId] === activeName) {
756
+ saveSessionBind(configDir, runtimeSession.sessionId, activeName);
757
+ }
665
758
  }
666
759
  }
667
760
 
@@ -728,14 +821,83 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
728
821
  }
729
822
 
730
823
  // Authoritative, secret-free status; absent fields never mean unclaimed.
731
- if (cliArgs.registerOnly && !TOKEN) {
824
+ if (isOneShotCli && (!TOKEN || TOKEN === "dev-token")) {
732
825
  process.stderr.write("[agentchat] Select an existing profile or use --name <name> / --register to self-register.\n");
733
826
  process.exit(1);
734
827
  }
828
+ if (cliArgs.join || cliArgs.send || cliArgs.wakeOnce) {
829
+ if (cliArgs.send && !cliArgs.text) {
830
+ process.stderr.write("[agentchat] ERROR: --send <channel> requires --text <message>. See --help.\n");
831
+ process.exit(1);
832
+ }
833
+ if (cliArgs.join && !cliArgs.send && !cliArgs.wakeOnce) {
834
+ const res = await joinChannelRest({
835
+ restUrl: REST_URL,
836
+ agentId: AGENT_ID,
837
+ token: TOKEN,
838
+ channelId: cliArgs.join,
839
+ });
840
+ console.log(JSON.stringify(res));
841
+ process.exit(res.ok ? 0 : 1);
842
+ }
843
+ const explicitMaxIdleMs = parseMaxIdleMs(cliArgs["max-idle"]);
844
+ if (cliArgs.send) {
845
+ if (cliArgs.join) {
846
+ await joinChannelRest({
847
+ restUrl: REST_URL,
848
+ agentId: AGENT_ID,
849
+ token: TOKEN,
850
+ channelId: cliArgs.join,
851
+ });
852
+ }
853
+ const res = await sendRestMessage({
854
+ restUrl: REST_URL,
855
+ configDir,
856
+ agentId: AGENT_ID,
857
+ token: TOKEN,
858
+ channelId: cliArgs.send,
859
+ text: cliArgs.text!,
860
+ replyTo: cliArgs["reply-to"],
861
+ maxIdleMs: explicitMaxIdleMs,
862
+ });
863
+ console.log(JSON.stringify(res));
864
+ process.exit(res.ok ? 0 : 1);
865
+ }
866
+ if (cliArgs.wakeOnce) {
867
+ const rawChans = [
868
+ ...(cliArgs.join ? [cliArgs.join] : []),
869
+ ...(cliArgs.channel ? cliArgs.channel.split(",").map((c) => c.trim()).filter(Boolean) : []),
870
+ ];
871
+ const channels = rawChans.length > 0 ? [...new Set(rawChans)] : ["welcome"];
872
+ const timeoutSec = cliArgs.timeout !== undefined ? Number(cliArgs.timeout) : 240;
873
+ const timeoutMs = Number.isFinite(timeoutSec) && timeoutSec >= 0 ? timeoutSec * 1000 : 240_000;
874
+ const ev = await wakeOnce({
875
+ restUrl: REST_URL,
876
+ configDir,
877
+ agentId: AGENT_ID,
878
+ displayName: profile.display_name || AGENT_ID,
879
+ token: TOKEN,
880
+ channels,
881
+ timeoutMs,
882
+ maxIdleMs: explicitMaxIdleMs,
883
+ });
884
+ console.log(JSON.stringify(ev));
885
+ process.exit(0);
886
+ }
887
+ }
735
888
  if (TOKEN && TOKEN !== "dev-token") {
736
889
  const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
737
890
  process.stderr.write(`[agentchat] ${claimSummary(status)}\n`);
738
891
  if (cliArgs.registerOnly) {
892
+ try {
893
+ mkdirSync(configDir, { recursive: true });
894
+ const lastSeenFile = join(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
895
+ const cursor = loadCursor(lastSeenFile, (m) => process.stderr.write(m));
896
+ if (!cursor.get(CURSOR_INIT_KEY)) {
897
+ cursor.set(CURSOR_INIT_KEY, new Date().toISOString());
898
+ persistCursor(lastSeenFile, cursor, (m) => process.stderr.write(m));
899
+ }
900
+ } catch {}
739
901
  console.log(JSON.stringify({...status, terms_notice: TERMS_NOTICE, claim_url: status.claimed === true ? null : `${status.chat_url}?key=${encodeURIComponent(TOKEN)}`, profile_file: activeProfileFile, reply_verified: false}));
740
902
  process.exit(0);
741
903
  }
@@ -1651,7 +1813,7 @@ const ALL_TOOL_DEFS = [
1651
1813
  },
1652
1814
  {
1653
1815
  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.",
1816
+ 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
1817
  inputSchema: {
1656
1818
  type: "object" as const,
1657
1819
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -1660,7 +1822,7 @@ const ALL_TOOL_DEFS = [
1660
1822
  },
1661
1823
  {
1662
1824
  name: "list_members",
1663
- description: "List members in a channel.",
1825
+ description: "List members in a channel with full @agent_id handles, online status, and peer capability tags (human login emails/phones masked).",
1664
1826
  inputSchema: {
1665
1827
  type: "object" as const,
1666
1828
  properties: {
@@ -2489,6 +2651,34 @@ function setAnonymousCallerState(callerSession?: DetectedSession | null): void {
2489
2651
  }
2490
2652
  }
2491
2653
 
2654
+ function findSlotByAgentId(agentId: string | null | undefined): ProfileSlot | undefined {
2655
+ if (!agentId) return undefined;
2656
+ for (const s of profileSlots.values()) {
2657
+ if (s.agentId === agentId) return s;
2658
+ }
2659
+ return undefined;
2660
+ }
2661
+
2662
+ function upgradeAliasSlotInPlace(
2663
+ slot: ProfileSlot,
2664
+ newProfileName: string,
2665
+ newProfileFile: string,
2666
+ newProfile: any,
2667
+ sess: DetectedSession,
2668
+ ): void {
2669
+ if (slot.profileName !== newProfileName) {
2670
+ profileSlots.delete(slot.profileName);
2671
+ slot.profileName = newProfileName;
2672
+ profileSlots.set(newProfileName, slot);
2673
+ }
2674
+ slot.profileFile = newProfileFile;
2675
+ slot.profile = newProfile;
2676
+ slot.runtimeSession = sess;
2677
+ if (activeSlot === slot) {
2678
+ activateSlot(slot, sess);
2679
+ }
2680
+ }
2681
+
2492
2682
  function teardownSlot(slot: ProfileSlot, opts?: { releaseLock?: boolean }): void {
2493
2683
  try { flushSlotLastSeenMessageTs(slot); } catch {}
2494
2684
  try { slot.heartbeat.stop(); } catch {}
@@ -2683,11 +2873,15 @@ function formatProfileList(): string {
2683
2873
  : { locked: false };
2684
2874
  const slot = profileSlots.get(entry.name);
2685
2875
  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
- : "";
2876
+ const dupCollision =
2877
+ entry.name.toLowerCase() === "profile" ? findDefaultProfileCollision(configDir, entry.path) : null;
2878
+ const statusSuffix = dupCollision
2879
+ ? ` [duplicate of ${dupCollision.collidingName} — disallowed; delete profile.json]`
2880
+ : lock.locked
2881
+ ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]`
2882
+ : slot && slot.ws?.readyState === WebSocket.OPEN
2883
+ ? ` [online${boundSid ? ` session=${boundSid}` : ""}]`
2884
+ : "";
2691
2885
  return `${isCurrent ? "→ " : " "}${entry.name}${statusSuffix}`;
2692
2886
  });
2693
2887
  return `Current: ${current || "(anonymous / disconnected)"}\nAvailable profiles:\n${lines.join("\n")}`;
@@ -2701,6 +2895,42 @@ async function registerAndConnectProfile(
2701
2895
  if (!cleanName) {
2702
2896
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
2703
2897
  }
2898
+ const safeBase = cleanName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
2899
+ if (safeBase.toLowerCase() === "profile") {
2900
+ return {
2901
+ content: [{
2902
+ type: "text",
2903
+ 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").',
2904
+ }],
2905
+ isError: true,
2906
+ };
2907
+ }
2908
+ const existingTargetFile = nameToPath(cleanName);
2909
+ if (existsSync(existingTargetFile)) {
2910
+ return {
2911
+ content: [{
2912
+ type: "text",
2913
+ text: `Error: Profile "${cleanName}" already exists at ${existingTargetFile}. Pass profile_name="${cleanName}" to connect to it, or choose a different register_name.`,
2914
+ }],
2915
+ isError: true,
2916
+ };
2917
+ }
2918
+ const existingDefaultPath = nameToPath("profile");
2919
+ if (existsSync(existingDefaultPath)) {
2920
+ try {
2921
+ const defParsed = JSON.parse(readFileSync(existingDefaultPath, "utf-8"));
2922
+ const defDisplay = typeof defParsed?.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
2923
+ if (defDisplay && defDisplay === cleanName.toLowerCase()) {
2924
+ return {
2925
+ content: [{
2926
+ type: "text",
2927
+ 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.`,
2928
+ }],
2929
+ isError: true,
2930
+ };
2931
+ }
2932
+ } catch {}
2933
+ }
2704
2934
  const caps = ["claude-code", "coding", "chat"];
2705
2935
  try {
2706
2936
  const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
@@ -2732,10 +2962,6 @@ async function registerAndConnectProfile(
2732
2962
  validateIdentityProfile(newProfile, targetFile);
2733
2963
  mkdirSync(dirname(targetFile), { recursive: true });
2734
2964
  safeWriteProfile(targetFile, newProfile);
2735
- const defaultProfileFile = nameToPath("profile");
2736
- if (!existsSync(defaultProfileFile)) {
2737
- safeWriteProfile(defaultProfileFile, newProfile);
2738
- }
2739
2965
  applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
2740
2966
  const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
2741
2967
  return {
@@ -2825,6 +3051,21 @@ async function handleProfileSwitchOrConnect(args: any): Promise<{ content: any[]
2825
3051
  };
2826
3052
  }
2827
3053
 
3054
+ if (profileNameFromPath(targetFile)?.toLowerCase() === "profile") {
3055
+ const dupCollision = findDefaultProfileCollision(configDir, targetFile);
3056
+ if (dupCollision) {
3057
+ return {
3058
+ content: [{
3059
+ type: "text",
3060
+ text:
3061
+ `Refusing to connect "profile" (${targetFile}): profile.json collides (${dupCollision.reason}) with named profile "${dupCollision.collidingName}" (${dupCollision.collidingPath}). ` +
3062
+ `Delete ${targetFile} and connect via profile_name="${dupCollision.collidingName}" instead.`,
3063
+ }],
3064
+ isError: true,
3065
+ };
3066
+ }
3067
+ }
3068
+
2828
3069
  const newProfile = readIdentityProfile(targetFile);
2829
3070
  validateIdentityProfile(newProfile, targetFile);
2830
3071
 
@@ -3064,6 +3305,10 @@ const handleToolCall = async (request: any): Promise<any> => {
3064
3305
  // SDK error, so the calling agent always learns the call failed. Explicit
3065
3306
  // error returns below carry isError:true individually.
3066
3307
  try {
3308
+ if (codexIdentity && (AGENT_ID !== codexIdentity.agentId ||
3309
+ ["connect_profile", "switch_profile", "disconnect_profile"].includes(name))) {
3310
+ return { content: [{ type: "text", text: "Codex bridge owns this tool identity; change the bot configuration and restart to change identity." }], isError: true };
3311
+ }
3067
3312
  // Resolve the calling session/conversation and automatically route to its
3068
3313
  // bound ProfileSlot in profileSlots (`session_id -> profile -> agent_id`).
3069
3314
  const rawMeta = (request.params as any)?._meta;
@@ -3072,7 +3317,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3072
3317
  args as Record<string, any> | undefined,
3073
3318
  rawMeta,
3074
3319
  );
3075
- if (callerSession) {
3320
+ if (callerSession && !codexIdentity) {
3076
3321
  runtimeSession = callerSession;
3077
3322
  const binds = loadSessionBinds(configDir);
3078
3323
  const boundProfileName = binds[callerSession.sessionId];
@@ -3097,16 +3342,37 @@ const handleToolCall = async (request: any): Promise<any> => {
3097
3342
  if (existsSync(boundPath)) {
3098
3343
  try {
3099
3344
  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);
3345
+ const aliasSlot = candidate?.agent_id ? findSlotByAgentId(candidate.agent_id) : undefined;
3346
+ const aliasSid = aliasSlot
3347
+ ? aliasSlot.runtimeSession?.sessionId ||
3348
+ findBoundSessionForProfile(configDir, aliasSlot.profileName) ||
3349
+ resolveSessionForAgent(aliasSlot.agentId, { configDir })?.sessionId ||
3350
+ null
3351
+ : null;
3352
+ if (aliasSlot && (!aliasSid || aliasSid === callerSession.sessionId)) {
3353
+ upgradeAliasSlotInPlace(aliasSlot, boundProfileName, boundPath, candidate, callerSession);
3354
+ activateSlot(aliasSlot, callerSession);
3355
+ if (!toolOnlyMode) {
3356
+ acquireAgentLock({
3357
+ lockDir,
3358
+ agentId: aliasSlot.agentId,
3359
+ profileName: boundProfileName,
3360
+ sessionId: callerSession.sessionId,
3361
+ runtime: callerSession.runtime,
3362
+ });
3363
+ }
3364
+ } else {
3365
+ const lock = checkAgentLock({
3366
+ lockDir,
3367
+ agentId: candidate?.agent_id,
3368
+ currentSessionId: callerSession.sessionId,
3369
+ lockOwnerPid,
3370
+ });
3371
+ if (!lock.locked) {
3372
+ applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
3373
+ } else if (isPerCallSession) {
3374
+ setAnonymousCallerState(callerSession);
3375
+ }
3110
3376
  }
3111
3377
  } catch {}
3112
3378
  } else if (isPerCallSession) {
@@ -3119,7 +3385,9 @@ const handleToolCall = async (request: any): Promise<any> => {
3119
3385
  let unboundSlot: ProfileSlot | null = null;
3120
3386
  for (const slot of profileSlots.values()) {
3121
3387
  const slotBoundSid =
3122
- slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
3388
+ slot.runtimeSession?.sessionId ||
3389
+ findBoundSessionForProfile(configDir, slot.profileName) ||
3390
+ resolveSessionForAgent(slot.agentId, { configDir })?.sessionId;
3123
3391
  if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
3124
3392
  unboundSlot = slot;
3125
3393
  break;
@@ -3157,7 +3425,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3157
3425
 
3158
3426
  // Shared Cursor MCP: heal back to grok-bind identity if another agent
3159
3427
  // stole the live profile via switch_profile. No-op when unbound.
3160
- ensureGrokBoundIdentity();
3428
+ if (!codexIdentity) ensureGrokBoundIdentity();
3161
3429
 
3162
3430
  // Identity guard (task_muk0154j_pstaosfn): after a suspect fallback (explicit
3163
3431
  // identity lost on respawn → default profile), WRITE tools refuse until the
@@ -3738,7 +4006,7 @@ const handleToolCall = async (request: any): Promise<any> => {
3738
4006
  const data = await r.json() as any;
3739
4007
  if (data.messages?.length > 0) {
3740
4008
  const results = data.messages.map((m: any) =>
3741
- `[${m.sender_id?.slice(0, 8)}] ${m.content?.slice(0, 80)}`
4009
+ `[${redactParticipantPii(m.sender_id || "?")}] ${m.content?.slice(0, 80)}`
3742
4010
  ).join("\n");
3743
4011
  return { content: [{ type: "text", text: `Found ${data.messages.length} results:\n${results}` }] };
3744
4012
  }
@@ -3779,9 +4047,51 @@ const handleToolCall = async (request: any): Promise<any> => {
3779
4047
  return { content: [{ type: "text", text: "Not connected" }] };
3780
4048
  }
3781
4049
 
4050
+ async function fetchMcpChannelContext(chatId: string): Promise<{
4051
+ channel?: { id?: string; name?: string; type?: string; topic?: string; member_count?: number };
4052
+ agents?: Array<{ id: string; name?: string; capabilities?: string[]; online?: boolean; is_self?: boolean }>;
4053
+ } | null> {
4054
+ if (!chatId || !TOKEN) return null;
4055
+ try {
4056
+ const r = await apiFetch(
4057
+ `${REST_URL}/mcp`,
4058
+ {
4059
+ method: "POST",
4060
+ headers: {
4061
+ "Authorization": `Bearer ${TOKEN}`,
4062
+ "Content-Type": "application/json",
4063
+ ...(AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}),
4064
+ },
4065
+ body: JSON.stringify({
4066
+ jsonrpc: "2.0",
4067
+ id: 1,
4068
+ method: "tools/call",
4069
+ params: {
4070
+ name: "agentschat_get_channel_context",
4071
+ arguments: { channel_id: chatId },
4072
+ },
4073
+ }),
4074
+ },
4075
+ 2500,
4076
+ );
4077
+ if (!r.ok) return null;
4078
+ const rpc = await r.json() as any;
4079
+ if (rpc?.error || rpc?.result?.isError) return null;
4080
+ const structured = rpc?.result?.structuredContent;
4081
+ if (structured && typeof structured === "object") return structured;
4082
+ const textPayload = rpc?.result?.content?.[0]?.text;
4083
+ if (typeof textPayload === "string" && textPayload.trim().startsWith("{")) {
4084
+ return JSON.parse(textPayload);
4085
+ }
4086
+ return null;
4087
+ } catch {
4088
+ return null;
4089
+ }
4090
+ }
4091
+
3782
4092
  // 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.
4093
+ // channel, composed from existing REST reads + /mcp agentschat_get_channel_context.
4094
+ // Sections fail soft (null) so a single flaky fetch never blanks the brief.
3785
4095
  async function channelBrief(chatId: string): Promise<string> {
3786
4096
  const get = async (path: string) => {
3787
4097
  try {
@@ -3789,10 +4099,11 @@ const handleToolCall = async (request: any): Promise<any> => {
3789
4099
  return r.ok ? await r.json() as any : null;
3790
4100
  } catch { return null; }
3791
4101
  };
3792
- const [membersData, docsData, okrData] = await Promise.all([
4102
+ const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
3793
4103
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
3794
4104
  get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
3795
4105
  get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
4106
+ fetchMcpChannelContext(chatId),
3796
4107
  ]);
3797
4108
  // membersData === null means the /members read FAILED (most often a 403 because
3798
4109
  // you are not a member of this channel, or the channel does not exist) — NOT an
@@ -3800,20 +4111,52 @@ const handleToolCall = async (request: any): Promise<any> => {
3800
4111
  // truth was "you cannot see this channel's roster", corrupting their self-model.
3801
4112
  const membersReadable = membersData !== null;
3802
4113
  const memberIds: string[] = (membersData?.members || []).map((m: any) => m?.agent_id).filter(Boolean);
4114
+ const memberIdSet = new Set<string>(memberIds);
4115
+ const rawOnlineSet = new Set<string>();
3803
4116
  let online: string[] = [];
3804
4117
  if (memberIds.length > 0) {
3805
4118
  // Batch the presence query in chunks of 50 so channels with >50 members
3806
4119
  // report accurately (was: memberIds.slice(0,50) — silently wrong past 50).
3807
- const onlineSet = new Set<string>();
3808
4120
  for (let i = 0; i < memberIds.length; i += 50) {
3809
4121
  const batch = memberIds.slice(i, i + 50);
3810
4122
  const pres = await get(`/api/presence?ids=${encodeURIComponent(batch.join(","))}`);
3811
4123
  for (const [k, v] of Object.entries(pres?.presence || {})) {
3812
- if (v === "online") onlineSet.add(k);
4124
+ if (v === "online" && memberIdSet.has(k)) rawOnlineSet.add(k);
3813
4125
  }
3814
4126
  }
3815
- online = [...onlineSet];
4127
+ const maskedOnlineSet = new Set<string>();
4128
+ for (const id of rawOnlineSet) {
4129
+ maskedOnlineSet.add(redactParticipantPii(id));
4130
+ }
4131
+ online = [...maskedOnlineSet];
3816
4132
  }
4133
+ const agentPeers = Array.isArray(mcpCtx?.agents)
4134
+ ? mcpCtx.agents
4135
+ .filter((a: any) => a?.id && !isHumanPiiHandle(a.id))
4136
+ .map((a: any) => ({
4137
+ id: String(a.id),
4138
+ ...(a.name && !isHumanPiiHandle(a.name) ? { name: String(a.name) } : {}),
4139
+ capabilities: Array.isArray(a.capabilities) ? a.capabilities.map(String) : [],
4140
+ ...(typeof a.online === "boolean"
4141
+ ? { online: a.online }
4142
+ : memberIds.length > 0
4143
+ ? { online: rawOnlineSet.has(String(a.id)) }
4144
+ : {}),
4145
+ is_self: typeof a.is_self === "boolean" ? a.is_self : String(a.id) === AGENT_ID,
4146
+ }))
4147
+ : (membersData?.members || [])
4148
+ .filter((m: any) => m?.agent_id && !isHumanPiiHandle(m.agent_id) && m.type !== "user")
4149
+ .map((m: any) => ({
4150
+ id: String(m.agent_id),
4151
+ ...(m.display_name && !isHumanPiiHandle(m.display_name) ? { name: String(m.display_name) } : {}),
4152
+ capabilities: Array.isArray(m.capabilities) ? m.capabilities.map(String) : [],
4153
+ ...(typeof m.online === "boolean"
4154
+ ? { online: m.online }
4155
+ : memberIds.length > 0
4156
+ ? { online: rawOnlineSet.has(String(m.agent_id)) }
4157
+ : {}),
4158
+ is_self: String(m.agent_id) === AGENT_ID,
4159
+ }));
3817
4160
  const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
3818
4161
  const skills = allDocs.filter(isSkillDoc).map((d: any) => ({ doc_id: d.id, title: d.title }));
3819
4162
  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 +4177,12 @@ const handleToolCall = async (request: any): Promise<any> => {
3834
4177
  }));
3835
4178
  return JSON.stringify({
3836
4179
  channel: chatId,
4180
+ ...(mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {}),
4181
+ ...(mcpCtx?.channel?.topic ? { topic: String(mcpCtx.channel.topic) } : {}),
3837
4182
  members: membersReadable
3838
4183
  ? { total: memberIds.length, online }
3839
4184
  : { total: null, note: "roster unreadable — you are likely not a member of this channel (or it does not exist)" },
4185
+ ...(membersReadable ? { agent_peers: agentPeers } : {}),
3840
4186
  okr_objectives: objectives,
3841
4187
  skills,
3842
4188
  docs,
@@ -3852,19 +4198,28 @@ const handleToolCall = async (request: any): Promise<any> => {
3852
4198
 
3853
4199
  if (name === "join_channel") {
3854
4200
  const { chat_id } = args as any;
3855
- // Try WebSocket join first, then verify membership via REST
4201
+ // Try WebSocket join + authoritative REST /join (for non-WS / proxied clients)
3856
4202
  if (ws && ws.readyState === WebSocket.OPEN) {
3857
4203
  try { ws.send(JSON.stringify({ type: "join_channel", channel_id: chat_id, agent_id: AGENT_ID })); } catch {}
3858
4204
  }
3859
- // Verify by checking membership
3860
4205
  try {
3861
- await new Promise(r => setTimeout(r, 500)); // wait for server to process
4206
+ const joinRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/join`, {
4207
+ method: "POST",
4208
+ headers: { "Authorization": `Bearer ${TOKEN}`, "Content-Type": "application/json" },
4209
+ body: JSON.stringify({ sender_id: AGENT_ID }),
4210
+ });
4211
+ if (joinRes.ok) {
4212
+ if (activeSlot) activeSlot.knownChannels.add(chat_id);
4213
+ const brief = await channelBrief(chat_id).catch(() => "");
4214
+ return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}\n${brief}` }] };
4215
+ }
4216
+ await new Promise(r => setTimeout(r, 300));
3862
4217
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
3863
4218
  if (r.ok) {
3864
4219
  const data = await r.json() as any;
3865
4220
  const isMember = (data.members || []).some((m: any) => m.agent_id === AGENT_ID);
3866
4221
  if (isMember) {
3867
- // P3: joining hands you the room's capability synopsis immediately.
4222
+ if (activeSlot) activeSlot.knownChannels.add(chat_id);
3868
4223
  const brief = await channelBrief(chat_id).catch(() => "");
3869
4224
  return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}\n${brief}` }] };
3870
4225
  }
@@ -4212,13 +4567,43 @@ const handleToolCall = async (request: any): Promise<any> => {
4212
4567
  if (name === "list_members") {
4213
4568
  const { chat_id } = args as any;
4214
4569
  try {
4215
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { "Authorization": `Bearer ${TOKEN}` } });
4570
+ const [r, mcpCtx] = await Promise.all([
4571
+ apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { "Authorization": `Bearer ${TOKEN}` } }),
4572
+ fetchMcpChannelContext(chat_id),
4573
+ ]);
4216
4574
  if (r.ok) {
4217
4575
  const data = await r.json() as any;
4218
4576
  const members = data.members || [];
4219
4577
  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}` }] };
4578
+ const peerById = new Map<string, { name?: string; capabilities?: string[]; online?: boolean }>();
4579
+ for (const a of Array.isArray(mcpCtx?.agents) ? mcpCtx!.agents! : []) {
4580
+ if (a?.id && !isHumanPiiHandle(a.id)) {
4581
+ peerById.set(String(a.id), a);
4582
+ }
4583
+ }
4584
+ const list = members
4585
+ .map((m: any) => {
4586
+ const rawId = String(m?.agent_id ?? "");
4587
+ const isHuman = isHumanPiiHandle(rawId) || m?.type === "user";
4588
+ const safeId = redactParticipantPii(rawId);
4589
+ const peer = !isHuman ? peerById.get(rawId) : undefined;
4590
+ const rawDisplay = m?.display_name ? String(m.display_name).trim() : (peer?.name ? String(peer.name).trim() : "");
4591
+ const safeDisplay = rawDisplay && !isHumanPiiHandle(rawDisplay) ? rawDisplay : safeId;
4592
+ const handleBadge = isHuman ? `(${safeId})` : `(@${safeId})`;
4593
+ const roleBadge = m?.role ? ` [${m.role}]` : "";
4594
+ const onlineVal = typeof m?.online === "boolean" ? m.online : peer?.online;
4595
+ const onlineBadge = typeof onlineVal === "boolean" ? ` (${onlineVal ? "online" : "offline"})` : "";
4596
+ const caps =
4597
+ Array.isArray(peer?.capabilities) && peer!.capabilities!.length > 0
4598
+ ? peer!.capabilities!
4599
+ : Array.isArray(m?.capabilities)
4600
+ ? m.capabilities
4601
+ : [];
4602
+ const capsBadge = caps.length > 0 ? ` {capabilities: ${caps.join(", ")}}` : "";
4603
+ return `• ${safeDisplay} ${handleBadge}${roleBadge}${onlineBadge}${capsBadge}`;
4604
+ })
4605
+ .join("\n");
4606
+ return { content: [{ type: "text", text: `${members.length} members in ${chat_id}:\n${list}` }] };
4222
4607
  }
4223
4608
  return { content: [{ type: "text", text: `Failed to list members (${r.status})` }] };
4224
4609
  } catch (e) {
@@ -4237,7 +4622,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4237
4622
  full || rawContent.length <= MAX_HISTORY_MESSAGE_CHARS
4238
4623
  ? rawContent
4239
4624
  : `${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}`;
4625
+ let line = `[${time}] ${redactParticipantPii(m.sender_id || "?")}: ${body}`;
4241
4626
  // Surface media attachments so an agent can perceive voice/image messages,
4242
4627
  // not just their text caption. Audio: show any server transcript inline
4243
4628
  // (agent reads it directly); otherwise point at transcribe(url).
@@ -4313,7 +4698,7 @@ const handleToolCall = async (request: any): Promise<any> => {
4313
4698
  const list = msgs.map((m: any) => formatHistoryMessage(m, false)).join("\n");
4314
4699
  return { content: [{ type: "text", text: `${msgs.length} messages:\n${list}` }] };
4315
4700
  }
4316
- return { content: [{ type: "text", text: `Failed to get history (${r.status})` }] };
4701
+ return { content: [{ type: "text", text: `Failed to get history (${r.status})` }], isError: true };
4317
4702
  } catch (e) {
4318
4703
  return { content: [{ type: "text", text: `Error: ${e}` }] };
4319
4704
  }
@@ -4869,13 +5254,16 @@ function clearFinishedHiddenIdentityGamesFromMessage(data: any) {
4869
5254
  // duplicate or drop older out-of-order messages that were never processed.
4870
5255
  // Dedup core (key derivation + bounded set) lives in ./dedup.ts; this file
4871
5256
  // keeps the thin logging wrapper so call sites and stderr output are unchanged.
5257
+ const processAgentMessageDedup = new MessageDedup();
4872
5258
  function deliverySource(data: any): string {
4873
5259
  return typeof data?.__source === "string" ? data.__source : "live";
4874
5260
  }
4875
5261
  function recordOrSkipDeliveredMessage(data: any, slot: ProfileSlot | null = activeSlot): boolean {
4876
5262
  const key = messageDedupKey(data);
4877
5263
  if (!key || !slot) return false;
4878
- const skip = slot.messageDedup.recordOrSkip(key);
5264
+ const slotSkip = slot.messageDedup.recordOrSkip(key);
5265
+ const agentSkip = slot.agentId ? processAgentMessageDedup.recordOrSkip(`${slot.agentId}:${key}`) : false;
5266
+ const skip = slotSkip || agentSkip;
4879
5267
  if (skip) {
4880
5268
  process.stderr.write(
4881
5269
  `[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 +5356,26 @@ function syncOpenBoundSessions(): void {
4968
5356
  try {
4969
5357
  const candidate = readIdentityProfile(boundPath);
4970
5358
  validateIdentityProfile(candidate, boundPath);
5359
+ const sess: DetectedSession = { sessionId: cid, runtime: "antigravity" };
5360
+ // Prevent duplicate WebSocket slots when `profile.json` and `<Name>.json`
5361
+ // share the same `agent_id`: upgrade the unbound alias slot in-place.
5362
+ const existingByAgent = findSlotByAgentId(candidate.agent_id);
5363
+ if (existingByAgent) {
5364
+ const existingSid =
5365
+ existingByAgent.runtimeSession?.sessionId ||
5366
+ findBoundSessionForProfile(configDir, existingByAgent.profileName);
5367
+ if (!existingSid || existingSid === cid) {
5368
+ upgradeAliasSlotInPlace(existingByAgent, boundProf, boundPath, candidate, sess);
5369
+ acquireAgentLock({
5370
+ lockDir,
5371
+ agentId: existingByAgent.agentId,
5372
+ profileName: boundProf,
5373
+ sessionId: cid,
5374
+ runtime: "antigravity",
5375
+ });
5376
+ }
5377
+ continue;
5378
+ }
4971
5379
  const lock = checkAgentLock({
4972
5380
  lockDir,
4973
5381
  agentId: candidate.agent_id,
@@ -4975,7 +5383,6 @@ function syncOpenBoundSessions(): void {
4975
5383
  lockOwnerPid,
4976
5384
  });
4977
5385
  if (lock.locked) continue;
4978
- const sess: DetectedSession = { sessionId: cid, runtime: "antigravity" };
4979
5386
  acquireAgentLock({
4980
5387
  lockDir,
4981
5388
  agentId: candidate.agent_id,
@@ -5135,7 +5542,7 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5135
5542
  const truncatedMsgs = trimmed.length < msgs.length;
5136
5543
  if (trimmed.length > 0) {
5137
5544
  const context = trimmed
5138
- .map((m: any) => `${m.sender_id}: ${m.content}${formatWakeAttachments(m.attachments)}`)
5545
+ .map((m: any) => `${redactParticipantPii(m.sender_id || "?")}: ${m.content}${formatWakeAttachments(m.attachments)}`)
5139
5546
  .join("\n");
5140
5547
  const note = truncatedMsgs
5141
5548
  ? `[频道上下文 - 最近 ${trimmed.length} 条消息(更早的已截断保护上下文窗口)]`
@@ -5224,8 +5631,10 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5224
5631
  process.env.AGENTCHAT_WAKE_MODE === "zcode" ||
5225
5632
  Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")))
5226
5633
  ) {
5634
+ const isZcodeSid = (sid: string) => sid.startsWith("sess_");
5227
5635
  const zcodeSid =
5228
- findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")) ||
5636
+ findBoundSessionForProfile(configDir, slotProfName, isZcodeSid) ||
5637
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isZcodeSid })?.sessionId ||
5229
5638
  (slotRuntime === "zcode" ? slot!.runtimeSession?.sessionId : "") ||
5230
5639
  "";
5231
5640
  if (zcodeSid) {
@@ -5243,9 +5652,10 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5243
5652
  isDshHostProcess() ||
5244
5653
  Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")))
5245
5654
  ) {
5655
+ const isDshSid = (sid: string) => sid.startsWith("session-");
5246
5656
  const dshSid =
5247
- findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")) ||
5248
- resolveSessionForAgent(slot!.agentId, { configDir })?.sessionId ||
5657
+ findBoundSessionForProfile(configDir, slotProfName, isDshSid) ||
5658
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isDshSid })?.sessionId ||
5249
5659
  (slotRuntime === "dsh" ? slot!.runtimeSession?.sessionId : "") ||
5250
5660
  undefined;
5251
5661
  const dshWakeUrl =
@@ -5265,19 +5675,42 @@ function connectWS(slot: ProfileSlot | null = activeSlot) {
5265
5675
  const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
5266
5676
  const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
5267
5677
  if (!agyHost && !lsAddress) return;
5678
+ const isAgyUuid = (sid: string) =>
5679
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
5268
5680
  const allBinds = loadSessionBinds(configDir);
5269
5681
  let targetCid =
5270
- findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) ||
5271
- (slotRuntime === "antigravity" ? slot!.runtimeSession?.sessionId : "") ||
5682
+ findBoundSessionForProfile(configDir, slotProfName, isAgyUuid) ||
5683
+ resolveSessionForAgent(slot!.agentId, { configDir, filter: isAgyUuid })?.sessionId ||
5684
+ (slotRuntime === "antigravity" &&
5685
+ slot!.runtimeSession?.sessionId &&
5686
+ isAgyUuid(slot!.runtimeSession.sessionId)
5687
+ ? slot!.runtimeSession.sessionId
5688
+ : "") ||
5272
5689
  "";
5273
5690
  if (!targetCid && agyHost) {
5274
5691
  if (agyHost.openConversations.length === 1) {
5275
- targetCid = agyHost.openConversations[0]!;
5692
+ const soleCid = agyHost.openConversations[0]!;
5693
+ const soleBoundProf = allBinds[soleCid];
5694
+ let soleMatchesAgent = false;
5695
+ if (soleBoundProf) {
5696
+ const p = nameToPath(soleBoundProf);
5697
+ if (existsSync(p)) {
5698
+ try {
5699
+ soleMatchesAgent = readIdentityProfile(p)?.agent_id === slot!.agentId;
5700
+ } catch {}
5701
+ }
5702
+ }
5703
+ if (!soleBoundProf || soleBoundProf === slotProfName || soleMatchesAgent) {
5704
+ targetCid = soleCid;
5705
+ }
5276
5706
  } else if (agyHost.openConversations.length > 1) {
5277
- const unboundOrSame = agyHost.openConversations.find(
5278
- (cid) => !allBinds[cid] || allBinds[cid] === slotProfName,
5707
+ // Never guess an unbound conversation (`!allBinds[cid]`) or `openConversations[0]`
5708
+ // when multiple Antigravity windows are open — guessing leaks wakes into
5709
+ // unrelated project windows!
5710
+ rateLimitedLog(
5711
+ `agy-wake-unbound:${slot!.agentId}`,
5712
+ `[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
5713
  );
5280
- targetCid = unboundOrSame || agyHost.openConversations[0]!;
5281
5714
  }
5282
5715
  }
5283
5716
  if (targetCid && csrfToken) {
@@ -5436,9 +5869,24 @@ async function checkVersionStaleness(): Promise<void> {
5436
5869
 
5437
5870
  // --- Start ---
5438
5871
  async function main() {
5872
+ if (codexIdentity) {
5873
+ const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
5874
+ if (status.authentication !== "ok") throw new Error("Codex tool authentication failed; bridge transport alone is not tool readiness");
5875
+ }
5439
5876
  installStdioLifecycleGuards();
5440
5877
  if (!toolOnlyMode) {
5441
5878
  syncOpenBoundSessions();
5879
+ if (
5880
+ process.env.__CFBundleIdentifier === "com.google.antigravity" ||
5881
+ Boolean(process.env.AGY_BROWSER_WS_URL) ||
5882
+ Boolean(process.env.ANTIGRAVITY_LS_ADDRESS) ||
5883
+ Boolean(discoverAntigravityHost())
5884
+ ) {
5885
+ const agySyncTimer = setInterval(() => {
5886
+ if (!shuttingDown) syncOpenBoundSessions();
5887
+ }, 15_000);
5888
+ (agySyncTimer as any).unref?.();
5889
+ }
5442
5890
  }
5443
5891
  // Anonymous = no credentials to present. Connecting would just fail auth in a
5444
5892
  // reconnect loop; stdio (initialize/tools/list) is served either way.