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/dist/server.js CHANGED
@@ -60,6 +60,32 @@ function redactSecrets(text, opts) {
60
60
  const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
61
61
  return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
62
62
  }
63
+ var PHONE_PII_RE = /^\+?\d[\d\s()-]{5,}$/;
64
+ function isHumanPiiHandle(rawId) {
65
+ const s = String(rawId ?? "").trim();
66
+ if (!s)
67
+ return false;
68
+ if (s.includes("@"))
69
+ return true;
70
+ if (PHONE_PII_RE.test(s))
71
+ return true;
72
+ return false;
73
+ }
74
+ function redactParticipantPii(rawId) {
75
+ const s = String(rawId ?? "").trim();
76
+ if (!s)
77
+ return "unknown";
78
+ const atIdx = s.indexOf("@");
79
+ if (atIdx >= 0) {
80
+ const local = s.slice(0, atIdx).replace(/[^a-zA-Z0-9]/g, "");
81
+ return `user:${(local.slice(0, 2) || "u").toLowerCase()}***`;
82
+ }
83
+ if (PHONE_PII_RE.test(s)) {
84
+ const digits = s.replace(/\D/g, "");
85
+ return `user:phone_***${digits.slice(-2) || "00"}`;
86
+ }
87
+ return s;
88
+ }
63
89
 
64
90
  // src/mentions.ts
65
91
  function matchesMention(content, agentId) {
@@ -886,13 +912,13 @@ function fireZcodeWake(msg, cfg) {
886
912
 
887
913
  // src/session-bind.ts
888
914
  import { createHash } from "node:crypto";
889
- import { closeSync, existsSync as existsSync3, mkdirSync, openSync, readFileSync as readFileSync3, readSync, readdirSync, statSync as statSync2, unlinkSync as unlinkSync2 } from "node:fs";
915
+ import { closeSync, existsSync as existsSync3, mkdirSync, openSync, readFileSync as readFileSync4, readSync, readdirSync as readdirSync2, statSync as statSync2, unlinkSync as unlinkSync2 } from "node:fs";
890
916
  import { homedir, tmpdir } from "node:os";
891
917
  import { join as join3 } from "node:path";
892
918
  import { spawnSync } from "node:child_process";
893
919
 
894
920
  // src/profile-store.ts
895
- import { existsSync as existsSync2, writeFileSync, renameSync, chmodSync, unlinkSync, statSync } from "fs";
921
+ import { existsSync as existsSync2, writeFileSync, renameSync, chmodSync, unlinkSync, statSync, readdirSync, readFileSync as readFileSync3 } from "fs";
896
922
  var defaultWarn = (m) => process.stderr.write(m);
897
923
  function safeWriteProfile(path, data, warn = defaultWarn) {
898
924
  const tmp = path + ".tmp";
@@ -922,6 +948,16 @@ function safeWriteProfile(path, data, warn = defaultWarn) {
922
948
  `);
923
949
  }
924
950
  }
951
+ var NON_PROFILE_JSON_FILES = new Set([
952
+ "session-binds.json",
953
+ "agy-binds.json",
954
+ "grok-binds.json",
955
+ "grok-binds-meta.json",
956
+ "grok-binds.meta.json",
957
+ "identity-guard.json",
958
+ "dsh.json",
959
+ "config.json"
960
+ ]);
925
961
 
926
962
  // src/session-bind.ts
927
963
  var DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
@@ -957,7 +993,7 @@ function readAgentLock(lockDir, agentId) {
957
993
  if (!existsSync3(file))
958
994
  return null;
959
995
  try {
960
- const raw = JSON.parse(readFileSync3(file, "utf8"));
996
+ const raw = JSON.parse(readFileSync4(file, "utf8"));
961
997
  if (!raw || typeof raw !== "object" || typeof raw.pid !== "number" || typeof raw.agentId !== "string") {
962
998
  return null;
963
999
  }
@@ -1054,25 +1090,49 @@ function loadSessionBinds(configDir) {
1054
1090
  if (!existsSync3(path))
1055
1091
  continue;
1056
1092
  try {
1057
- Object.assign(merged, parseSessionBinds(JSON.parse(readFileSync3(path, "utf8"))));
1093
+ Object.assign(merged, parseSessionBinds(JSON.parse(readFileSync4(path, "utf8"))));
1058
1094
  } catch {}
1059
1095
  }
1060
1096
  return merged;
1061
1097
  }
1098
+ function resolveAgentIdForProfileName(configDir, name) {
1099
+ if (!name || name.includes("/") || name.includes("\\"))
1100
+ return null;
1101
+ const base = name.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
1102
+ for (const candidate of [join3(configDir, "profiles", `${base}.json`), join3(configDir, `${base}.json`)]) {
1103
+ if (!existsSync3(candidate))
1104
+ continue;
1105
+ try {
1106
+ const parsed = JSON.parse(readFileSync4(candidate, "utf8"));
1107
+ if (typeof parsed?.agent_id === "string" && parsed.agent_id.trim()) {
1108
+ return parsed.agent_id.trim();
1109
+ }
1110
+ } catch {}
1111
+ }
1112
+ return null;
1113
+ }
1062
1114
  function saveSessionBind(configDir, sessionId, profileName) {
1063
1115
  const sid = sessionId.trim();
1064
1116
  const prof = profileName.trim();
1065
1117
  if (!sid || !prof)
1066
1118
  return;
1119
+ const targetAgentId = resolveAgentIdForProfileName(configDir, prof);
1120
+ const isSameProfileOrAgent = (existingProf) => {
1121
+ if (existingProf === prof)
1122
+ return true;
1123
+ if (!targetAgentId)
1124
+ return false;
1125
+ return resolveAgentIdForProfileName(configDir, existingProf) === targetAgentId;
1126
+ };
1067
1127
  const path = join3(configDir, DEFAULT_SESSION_BINDS_FILENAME);
1068
1128
  let current = {};
1069
1129
  if (existsSync3(path)) {
1070
1130
  try {
1071
- current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
1131
+ current = parseSessionBinds(JSON.parse(readFileSync4(path, "utf8")));
1072
1132
  } catch {}
1073
1133
  }
1074
1134
  for (const [existingSid, existingProf] of Object.entries(current)) {
1075
- if (existingProf === prof && existingSid !== sid) {
1135
+ if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
1076
1136
  delete current[existingSid];
1077
1137
  }
1078
1138
  }
@@ -1083,10 +1143,10 @@ function saveSessionBind(configDir, sessionId, profileName) {
1083
1143
  const legacyPath = join3(configDir, LEGACY_AGY_BINDS_FILENAME);
1084
1144
  if (existsSync3(legacyPath)) {
1085
1145
  try {
1086
- const legacy = parseSessionBinds(JSON.parse(readFileSync3(legacyPath, "utf8")));
1146
+ const legacy = parseSessionBinds(JSON.parse(readFileSync4(legacyPath, "utf8")));
1087
1147
  let changed = false;
1088
1148
  for (const [existingSid, existingProf] of Object.entries(legacy)) {
1089
- if (existingProf === prof && existingSid !== sid) {
1149
+ if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
1090
1150
  delete legacy[existingSid];
1091
1151
  changed = true;
1092
1152
  }
@@ -1106,7 +1166,7 @@ function removeSessionBind(configDir, sessionId) {
1106
1166
  if (!existsSync3(path))
1107
1167
  continue;
1108
1168
  try {
1109
- const current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
1169
+ const current = parseSessionBinds(JSON.parse(readFileSync4(path, "utf8")));
1110
1170
  if (sid in current) {
1111
1171
  delete current[sid];
1112
1172
  safeWriteProfile(path, current);
@@ -1164,7 +1224,53 @@ function detectRuntimeSession(env = process.env, meta) {
1164
1224
  return null;
1165
1225
  }
1166
1226
  var cachedAgyHost = null;
1227
+ function parseAntigravityLsofOutput(stdout, appDataDir = "antigravity") {
1228
+ const ports = [];
1229
+ const presenceConversations = [];
1230
+ const dbConversations = [];
1231
+ const cleanAppDir = (appDataDir || "antigravity").trim().replace(/^\/+|\/+$/g, "");
1232
+ const isCliTarget = cleanAppDir === "antigravity-cli";
1233
+ for (const line of (stdout || "").split(/\r?\n/)) {
1234
+ const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
1235
+ if (portMatch) {
1236
+ const p = Number(portMatch[1]);
1237
+ if (p > 0 && !ports.includes(p))
1238
+ ports.push(p);
1239
+ }
1240
+ if (!isCliTarget && line.includes("/antigravity-cli/"))
1241
+ continue;
1242
+ const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/);
1243
+ if (presMatch) {
1244
+ const cid = presMatch[1];
1245
+ if (!presenceConversations.includes(cid))
1246
+ presenceConversations.push(cid);
1247
+ continue;
1248
+ }
1249
+ const dbMatch = line.match(/\/conversations\/([0-9a-fA-F-]{36})\.db$/);
1250
+ if (dbMatch) {
1251
+ if (cleanAppDir && line.includes("/.gemini/") && !line.includes(`/${cleanAppDir}/conversations/`)) {
1252
+ continue;
1253
+ }
1254
+ const cid = dbMatch[1];
1255
+ if (!dbConversations.includes(cid))
1256
+ dbConversations.push(cid);
1257
+ }
1258
+ }
1259
+ ports.sort((a, b) => b - a);
1260
+ const openConversations = presenceConversations.length > 0 ? presenceConversations : dbConversations;
1261
+ return { ports, openConversations };
1262
+ }
1167
1263
  function discoverAntigravityHost(opts) {
1264
+ if (!opts?.currentPid) {
1265
+ const envAddr = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
1266
+ const envCsrf = process.env.ANTIGRAVITY_CSRF_TOKEN?.trim() || "";
1267
+ if (envAddr && envCsrf) {
1268
+ const portMatch = envAddr.match(/:(\d+)$/);
1269
+ const ports = portMatch ? [Number(portMatch[1])] : [];
1270
+ const openConversations = (process.env.ANTIGRAVITY_OPEN_CONVERSATIONS || "").split(",").map((s) => s.trim()).filter((s) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s));
1271
+ return { lsPid: process.ppid, csrfToken: envCsrf, ports, openConversations };
1272
+ }
1273
+ }
1168
1274
  const now = Date.now();
1169
1275
  const cacheMs = opts?.cacheMs ?? 5000;
1170
1276
  if (cachedAgyHost && now - cachedAgyHost.at < cacheMs)
@@ -1202,26 +1308,10 @@ function discoverAntigravityHost(opts) {
1202
1308
  cachedAgyHost = { at: now, info: null };
1203
1309
  return null;
1204
1310
  }
1311
+ const appDirMatch = lsCmd.match(/--app_data_dir[=\s]+([^\s]+)/);
1312
+ const appDataDir = appDirMatch?.[1]?.trim() || "antigravity";
1205
1313
  const lsof = spawnSync("lsof", ["-Pan", "-p", String(lsPid)], { encoding: "utf8", timeout: 1500 });
1206
- const ports = [];
1207
- const openConversations = [];
1208
- if (lsof.status === 0 && lsof.stdout) {
1209
- for (const line of lsof.stdout.split(/\r?\n/)) {
1210
- const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
1211
- if (portMatch) {
1212
- const p = Number(portMatch[1]);
1213
- if (p > 0 && !ports.includes(p))
1214
- ports.push(p);
1215
- }
1216
- const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/) || line.match(/\/conversations\/([0-9a-fA-F-]{36})\.db$/);
1217
- if (presMatch) {
1218
- const cid = presMatch[1];
1219
- if (!openConversations.includes(cid))
1220
- openConversations.push(cid);
1221
- }
1222
- }
1223
- }
1224
- ports.sort((a, b) => b - a);
1314
+ const { ports, openConversations } = lsof.status === 0 && lsof.stdout ? parseAntigravityLsofOutput(lsof.stdout, appDataDir) : { ports: [], openConversations: [] };
1225
1315
  const info = { lsPid, csrfToken, ports, openConversations };
1226
1316
  cachedAgyHost = { at: now, info };
1227
1317
  return info;
@@ -1243,7 +1333,7 @@ function detectAntigravityCallerSession(opts) {
1243
1333
  candidateSet.add(cid);
1244
1334
  }
1245
1335
  try {
1246
- for (const entry of readdirSync(brainDir)) {
1336
+ for (const entry of readdirSync2(brainDir)) {
1247
1337
  if (uuidRe.test(entry))
1248
1338
  candidateSet.add(entry);
1249
1339
  }
@@ -1380,7 +1470,7 @@ function sessionDirMtime(dir) {
1380
1470
  function sessionLogMtime(dshHome, sid) {
1381
1471
  let projects;
1382
1472
  try {
1383
- projects = readdirSync(join3(dshHome, "sessions"));
1473
+ projects = readdirSync2(join3(dshHome, "sessions"));
1384
1474
  } catch {
1385
1475
  return 0;
1386
1476
  }
@@ -1396,7 +1486,7 @@ function newestSessionLog(dshHome, nowMs, maxAgeMs) {
1396
1486
  const root = join3(dshHome, "sessions");
1397
1487
  let projects;
1398
1488
  try {
1399
- projects = readdirSync(root);
1489
+ projects = readdirSync2(root);
1400
1490
  } catch {
1401
1491
  return null;
1402
1492
  }
@@ -1404,7 +1494,7 @@ function newestSessionLog(dshHome, nowMs, maxAgeMs) {
1404
1494
  for (const project of projects) {
1405
1495
  let entries;
1406
1496
  try {
1407
- entries = readdirSync(join3(root, project));
1497
+ entries = readdirSync2(join3(root, project));
1408
1498
  } catch {
1409
1499
  continue;
1410
1500
  }
@@ -1461,12 +1551,12 @@ async function detectDshCallerSession(opts) {
1461
1551
  }
1462
1552
 
1463
1553
  // src/session-route.ts
1464
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
1554
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
1465
1555
  import { homedir as homedir2 } from "node:os";
1466
1556
  import { join as join5 } from "node:path";
1467
1557
 
1468
1558
  // src/session-bind.ts
1469
- import { closeSync as closeSync2, existsSync as existsSync4, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync4, readSync as readSync2, readdirSync as readdirSync2, statSync as statSync3, unlinkSync as unlinkSync3 } from "node:fs";
1559
+ import { closeSync as closeSync2, existsSync as existsSync4, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync5, readSync as readSync2, readdirSync as readdirSync3, statSync as statSync3, unlinkSync as unlinkSync3 } from "node:fs";
1470
1560
  import { join as join4 } from "node:path";
1471
1561
  var DEFAULT_SESSION_BINDS_FILENAME2 = "session-binds.json";
1472
1562
  var LEGACY_AGY_BINDS_FILENAME2 = "agy-binds.json";
@@ -1493,7 +1583,7 @@ function loadSessionBinds2(configDir) {
1493
1583
  if (!existsSync4(path))
1494
1584
  continue;
1495
1585
  try {
1496
- Object.assign(merged, parseSessionBinds2(JSON.parse(readFileSync4(path, "utf8"))));
1586
+ Object.assign(merged, parseSessionBinds2(JSON.parse(readFileSync5(path, "utf8"))));
1497
1587
  } catch {}
1498
1588
  }
1499
1589
  return merged;
@@ -1515,7 +1605,7 @@ function profilePathForName(configDir, name) {
1515
1605
  }
1516
1606
  function readAgentId(path) {
1517
1607
  try {
1518
- const parsed = JSON.parse(readFileSync5(path, "utf8"));
1608
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
1519
1609
  return typeof parsed.agent_id === "string" && parsed.agent_id ? parsed.agent_id : undefined;
1520
1610
  } catch {
1521
1611
  return;
@@ -1532,6 +1622,8 @@ function resolveSessionForAgent(agentId, opts = {}) {
1532
1622
  return;
1533
1623
  }
1534
1624
  for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
1625
+ if (opts.filter && !opts.filter(sessionId))
1626
+ continue;
1535
1627
  const path = profilePathForName(configDir, profileName);
1536
1628
  if (path === undefined)
1537
1629
  continue;
@@ -1619,7 +1711,7 @@ class HeartbeatMonitor {
1619
1711
  var package_default = {
1620
1712
  name: "agentschat-mcp",
1621
1713
  mcpName: "io.github.swswordholy-tech/agentschat-mcp",
1622
- version: "0.36.22",
1714
+ version: "0.36.23",
1623
1715
  description: "Connect Claude Code to AgentsChat — AI Agent social network. Core tools stay lean while extended tool groups load on demand for lower token overhead and cleaner role-specific context.",
1624
1716
  type: "module",
1625
1717
  bin: {
@@ -1635,14 +1727,14 @@ var package_default = {
1635
1727
  scripts: {
1636
1728
  start: "bun src/server.ts",
1637
1729
  dev: "bun --watch src/server.ts",
1638
- test: "bun test",
1730
+ test: "bun test ./tests ./dsh/tests && node --experimental-strip-types --test muse/tests/*.test.mjs",
1639
1731
  typecheck: "tsc --noEmit",
1640
1732
  build: "bun scripts/build.mjs",
1641
1733
  "check:version": "bun scripts/check-version-sync.mjs",
1642
1734
  "check:docs": "bun scripts/sync-doc-versions.mjs --check",
1643
1735
  "sync:docs": "bun scripts/sync-doc-versions.mjs --write",
1644
1736
  version: "bun run build && bun scripts/sync-doc-versions.mjs --write --git-add",
1645
- verify: "bun run build && bun scripts/check-version-sync.mjs && bun scripts/sync-doc-versions.mjs --check && tsc --noEmit && bun test",
1737
+ verify: "bun run build && bun scripts/check-version-sync.mjs && bun scripts/sync-doc-versions.mjs --check && tsc --noEmit && bun run test",
1646
1738
  prepublishOnly: "bun run check:version && bun run check:docs && bun test tests/doc-versions.test.ts tests/packaging.test.ts"
1647
1739
  },
1648
1740
  keywords: [
@@ -1765,12 +1857,13 @@ import {
1765
1857
  CallToolRequestSchema,
1766
1858
  ListToolsRequestSchema
1767
1859
  } from "@modelcontextprotocol/sdk/types.js";
1768
- import { readFileSync as readFileSync7, existsSync as existsSync7, writeFileSync as writeFileSync4, mkdirSync as mkdirSync3, readdirSync as readdirSync3 } from "fs";
1769
- import { join as join6, dirname } from "path";
1860
+ import { readFileSync as readFileSync9, existsSync as existsSync7, writeFileSync as writeFileSync4, mkdirSync as mkdirSync3, readdirSync as readdirSync5 } from "fs";
1861
+ import { join as join7, dirname } from "path";
1770
1862
  import { fileURLToPath } from "url";
1771
1863
 
1772
1864
  // src/profile-store.ts
1773
- import { existsSync as existsSync6, writeFileSync as writeFileSync2, renameSync as renameSync2, chmodSync as chmodSync2, unlinkSync as unlinkSync4, statSync as statSync4 } from "fs";
1865
+ import { existsSync as existsSync6, writeFileSync as writeFileSync2, renameSync as renameSync2, chmodSync as chmodSync2, unlinkSync as unlinkSync4, statSync as statSync4, readdirSync as readdirSync4, readFileSync as readFileSync7 } from "fs";
1866
+ import { join as join6, resolve as resolve2 } from "path";
1774
1867
  var defaultWarn2 = (m) => process.stderr.write(m);
1775
1868
  function safeWriteProfile2(path, data, warn = defaultWarn2) {
1776
1869
  const tmp = path + ".tmp";
@@ -1800,6 +1893,73 @@ function safeWriteProfile2(path, data, warn = defaultWarn2) {
1800
1893
  `);
1801
1894
  }
1802
1895
  }
1896
+ var NON_PROFILE_JSON_FILES2 = new Set([
1897
+ "session-binds.json",
1898
+ "agy-binds.json",
1899
+ "grok-binds.json",
1900
+ "grok-binds-meta.json",
1901
+ "grok-binds.meta.json",
1902
+ "identity-guard.json",
1903
+ "dsh.json",
1904
+ "config.json"
1905
+ ]);
1906
+ function findDefaultProfileCollision(configDir, defaultProfilePath) {
1907
+ if (!defaultProfilePath || !existsSync6(defaultProfilePath))
1908
+ return null;
1909
+ let defParsed;
1910
+ try {
1911
+ defParsed = JSON.parse(readFileSync7(defaultProfilePath, "utf8"));
1912
+ } catch {
1913
+ return null;
1914
+ }
1915
+ if (!defParsed || typeof defParsed !== "object" || Array.isArray(defParsed))
1916
+ return null;
1917
+ const defAgentId = typeof defParsed.agent_id === "string" ? defParsed.agent_id.trim() : "";
1918
+ const defDisplayName = typeof defParsed.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
1919
+ if (!defAgentId && !defDisplayName)
1920
+ return null;
1921
+ const resolvedDefault = resolve2(defaultProfilePath);
1922
+ for (const dir of [join6(configDir, "profiles"), configDir]) {
1923
+ if (!existsSync6(dir))
1924
+ continue;
1925
+ let files = [];
1926
+ try {
1927
+ files = readdirSync4(dir).filter((f) => f.endsWith(".json"));
1928
+ } catch {
1929
+ continue;
1930
+ }
1931
+ for (const file of files) {
1932
+ if (NON_PROFILE_JSON_FILES2.has(file))
1933
+ continue;
1934
+ const candidatePath = join6(dir, file);
1935
+ if (resolve2(candidatePath) === resolvedDefault)
1936
+ continue;
1937
+ const baseName = file.replace(/\.json$/, "");
1938
+ if (baseName.toLowerCase() === "profile")
1939
+ continue;
1940
+ let candidate;
1941
+ try {
1942
+ candidate = JSON.parse(readFileSync7(candidatePath, "utf8"));
1943
+ } catch {
1944
+ continue;
1945
+ }
1946
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate))
1947
+ continue;
1948
+ const candAgentId = typeof candidate.agent_id === "string" ? candidate.agent_id.trim() : "";
1949
+ const candToken = typeof candidate.token === "string" ? candidate.token.trim() : "";
1950
+ if (!candAgentId || !candToken)
1951
+ continue;
1952
+ if (defAgentId && candAgentId === defAgentId) {
1953
+ return { collidingName: baseName, collidingPath: candidatePath, reason: "agent_id" };
1954
+ }
1955
+ const candDisplayName = typeof candidate.display_name === "string" ? candidate.display_name.trim().toLowerCase() : "";
1956
+ if (defDisplayName && (candDisplayName === defDisplayName || baseName.toLowerCase() === defDisplayName)) {
1957
+ return { collidingName: baseName, collidingPath: candidatePath, reason: "display_name" };
1958
+ }
1959
+ }
1960
+ }
1961
+ return null;
1962
+ }
1803
1963
 
1804
1964
  // src/identity-guard.ts
1805
1965
  var IDENTITY_GUARD_FILENAME = "identity-guard.json";
@@ -1883,10 +2043,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
1883
2043
  }
1884
2044
 
1885
2045
  // src/read-cursor.ts
1886
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
2046
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
1887
2047
  function loadCursor(file, warn) {
1888
2048
  try {
1889
- return new Map(Object.entries(JSON.parse(readFileSync6(file, "utf-8"))));
2049
+ return new Map(Object.entries(JSON.parse(readFileSync8(file, "utf-8"))));
1890
2050
  } catch (e) {
1891
2051
  if (e?.code !== "ENOENT") {
1892
2052
  warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
@@ -1968,7 +2128,7 @@ function parseArgs() {
1968
2128
  }
1969
2129
  var cliArgs = parseArgs();
1970
2130
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
1971
- const localOnboardingPath = join6(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
2131
+ const localOnboardingPath = join7(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
1972
2132
  console.log(`agentschat-mcp v${package_default.version} \u2014 AgentsChat MCP and host bridges
1973
2133
 
1974
2134
  Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
@@ -2034,8 +2194,8 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
2034
2194
  process.exit(0);
2035
2195
  }
2036
2196
  var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
2037
- var configDir = join6(homeDir, ".agentschat");
2038
- var legacyConfigDir = join6(homeDir, ".agentchat");
2197
+ var configDir = join7(homeDir, ".agentschat");
2198
+ var legacyConfigDir = join7(homeDir, ".agentchat");
2039
2199
  var profileDirs = [configDir, legacyConfigDir];
2040
2200
  var lockDir = resolveLockDir(homeDir, process.env);
2041
2201
  var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
@@ -2044,16 +2204,16 @@ var runtimeSession = detectRuntimeSession(process.env);
2044
2204
  var dshRouteWarned = false;
2045
2205
  function profileNameToPaths(name) {
2046
2206
  if (name.startsWith("~/"))
2047
- return [join6(homeDir, name.slice(2))];
2207
+ return [join7(homeDir, name.slice(2))];
2048
2208
  if (name.includes("/") || name.includes("\\"))
2049
2209
  return [name];
2050
2210
  name = name.replace(/\.json$/, "");
2051
2211
  const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
2052
- return profileDirs.map((dir) => join6(dir, `${safeName}.json`));
2212
+ return profileDirs.map((dir) => join7(dir, `${safeName}.json`));
2053
2213
  }
2054
2214
  function nameToPath(name) {
2055
2215
  const candidates = profileNameToPaths(name);
2056
- const nested = join6(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
2216
+ const nested = join7(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
2057
2217
  if (!name.includes("/") && !name.includes("\\") && existsSync7(nested))
2058
2218
  return nested;
2059
2219
  return candidates.find((path) => existsSync7(path)) || candidates[0];
@@ -2061,10 +2221,10 @@ function nameToPath(name) {
2061
2221
  function listProfileFiles() {
2062
2222
  const seen = new Set;
2063
2223
  const profiles = [];
2064
- for (const dir of [join6(configDir, "profiles"), ...profileDirs]) {
2224
+ for (const dir of [join7(configDir, "profiles"), ...profileDirs]) {
2065
2225
  let files = [];
2066
2226
  try {
2067
- files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
2227
+ files = readdirSync5(dir).filter((f) => f.endsWith(".json"));
2068
2228
  } catch {}
2069
2229
  for (const file of files) {
2070
2230
  if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME || file === DEFAULT_SESSION_BINDS_FILENAME || file === LEGACY_AGY_BINDS_FILENAME)
@@ -2073,7 +2233,7 @@ function listProfileFiles() {
2073
2233
  if (seen.has(name))
2074
2234
  continue;
2075
2235
  seen.add(name);
2076
- profiles.push({ name, path: join6(dir, file) });
2236
+ profiles.push({ name, path: join7(dir, file) });
2077
2237
  }
2078
2238
  }
2079
2239
  return profiles;
@@ -2100,7 +2260,7 @@ function resolveProfile() {
2100
2260
  const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
2101
2261
  if (existsSync7(bindPath)) {
2102
2262
  try {
2103
- const parsed = parseGrokBindsText(readFileSync7(bindPath, "utf-8"));
2263
+ const parsed = parseGrokBindsText(readFileSync9(bindPath, "utf-8"));
2104
2264
  binds = parsed.binds;
2105
2265
  if (parsed.malformed) {
2106
2266
  process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
@@ -2191,46 +2351,63 @@ var identity = decideIdentity({
2191
2351
  });
2192
2352
  function readIdentityProfile(file) {
2193
2353
  try {
2194
- return JSON.parse(readFileSync7(file, "utf-8"));
2354
+ return JSON.parse(readFileSync9(file, "utf-8"));
2195
2355
  } catch {
2196
2356
  throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
2197
2357
  }
2198
2358
  }
2199
2359
  if (identity.mode === "profile") {
2200
- try {
2201
- profile = readIdentityProfile(profileFile);
2202
- if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
2203
- throw new Error("Project agent_id does not match selected profile");
2204
- }
2205
- validateIdentityProfile(profile && !Array.isArray(profile) ? {
2206
- ...profile,
2207
- agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
2208
- token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
2209
- capabilities: cliArgs.caps?.split(",") ?? profile.capabilities
2210
- } : profile, profileFile, !hasToken);
2211
- } catch (e) {
2212
- process.stderr.write(`[agentchat] ERROR: ${e.message}
2360
+ const isDefaultProfileFile = profileSource === "default" || profileNameFromPath(profileFile)?.toLowerCase() === "profile";
2361
+ const defaultCollision = isDefaultProfileFile ? findDefaultProfileCollision(configDir, profileFile) : null;
2362
+ if (defaultCollision) {
2363
+ if (profileSource !== "default") {
2364
+ process.stderr.write(`[agentchat] ERROR: Refusing to load duplicate profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).
2365
+ ` + ` Delete ${profileFile} and use --profile ${defaultCollision.collidingName} instead.
2213
2366
  `);
2214
- process.exit(1);
2215
- }
2216
- const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
2217
- const lockCheck = !cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
2218
- lockDir,
2219
- agentId: candidateAgentId,
2220
- currentSessionId: runtimeSession?.sessionId ?? null,
2221
- lockOwnerPid
2222
- }) : { locked: false };
2223
- if (lockCheck.locked) {
2367
+ process.exit(1);
2368
+ }
2224
2369
  anonymousMode = true;
2225
2370
  activeProfileFile = null;
2226
2371
  profile = {};
2227
- process.stderr.write(`[agentchat] Profile "${declaredName ?? profileNameFromPath(profileFile) ?? "profile"}" (${lockCheck.holder?.agentId}) is already in use by active process pid=${lockCheck.holder?.pid}` + `${lockCheck.holder?.runtime ? ` (${lockCheck.holder.runtime})` : ""}` + `${lockCheck.holder?.sessionId ? ` session=${lockCheck.holder.sessionId}` : ""}.
2372
+ process.stderr.write(`[agentchat] Ignoring duplicate default profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).
2373
+ ` + ` Starting in ANONYMOUS mode instead of shadowing "${defaultCollision.collidingName}". Delete ${profileFile} or bind this session via connect_profile(profile_name="${defaultCollision.collidingName}").
2374
+ `);
2375
+ } else {
2376
+ try {
2377
+ profile = readIdentityProfile(profileFile);
2378
+ if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
2379
+ throw new Error("Project agent_id does not match selected profile");
2380
+ }
2381
+ validateIdentityProfile(profile && !Array.isArray(profile) ? {
2382
+ ...profile,
2383
+ agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
2384
+ token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
2385
+ capabilities: cliArgs.caps?.split(",") ?? profile.capabilities
2386
+ } : profile, profileFile, !hasToken);
2387
+ } catch (e) {
2388
+ process.stderr.write(`[agentchat] ERROR: ${e.message}
2389
+ `);
2390
+ process.exit(1);
2391
+ }
2392
+ const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
2393
+ const lockCheck = !cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
2394
+ lockDir,
2395
+ agentId: candidateAgentId,
2396
+ currentSessionId: runtimeSession?.sessionId ?? null,
2397
+ lockOwnerPid
2398
+ }) : { locked: false };
2399
+ if (lockCheck.locked) {
2400
+ anonymousMode = true;
2401
+ activeProfileFile = null;
2402
+ profile = {};
2403
+ process.stderr.write(`[agentchat] Profile "${declaredName ?? profileNameFromPath(profileFile) ?? "profile"}" (${lockCheck.holder?.agentId}) is already in use by active process pid=${lockCheck.holder?.pid}` + `${lockCheck.holder?.runtime ? ` (${lockCheck.holder.runtime})` : ""}` + `${lockCheck.holder?.sessionId ? ` session=${lockCheck.holder.sessionId}` : ""}.
2228
2404
  ` + ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.
2229
2405
  ` + ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.
2230
2406
  `);
2231
- } else {
2232
- process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
2407
+ } else {
2408
+ process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
2233
2409
  `);
2410
+ }
2234
2411
  }
2235
2412
  } else if (identity.mode === "env-creds") {
2236
2413
  activeProfileFile = null;
@@ -2373,11 +2550,22 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
2373
2550
  }
2374
2551
  }
2375
2552
  if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
2376
- const activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
2377
- if (activeName && runtimeSession?.runtime === "antigravity" && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim()) {
2378
- const existingBoundSid = findBoundSessionForProfile(configDir, activeName, (sid) => /^[0-9a-f-]{36}$/i.test(sid));
2379
- if (existingBoundSid) {
2380
- runtimeSession = { sessionId: existingBoundSid, runtime: "antigravity" };
2553
+ let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
2554
+ const isAgyUuid = (sid) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
2555
+ const isImplicitAgyBoot = (runtimeSession?.runtime === "antigravity" || !runtimeSession && Boolean(discoverAntigravityHost())) && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
2556
+ if (activeName && isImplicitAgyBoot) {
2557
+ const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
2558
+ const existingAgentRoute = resolveSessionForAgent(AGENT_ID, { configDir, filter: isAgyUuid });
2559
+ const resolvedSid = existingBoundSid || existingAgentRoute?.sessionId || "";
2560
+ if (resolvedSid) {
2561
+ runtimeSession = { sessionId: resolvedSid, runtime: "antigravity" };
2562
+ if (profileSource === "default" && existingAgentRoute?.profileName && existingAgentRoute.profileName !== activeName) {
2563
+ const aliasPath = nameToPath(existingAgentRoute.profileName);
2564
+ if (existsSync7(aliasPath)) {
2565
+ activeProfileFile = aliasPath;
2566
+ activeName = existingAgentRoute.profileName;
2567
+ }
2568
+ }
2381
2569
  }
2382
2570
  }
2383
2571
  acquireAgentLock({
@@ -2388,11 +2576,14 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
2388
2576
  runtime: runtimeSession?.runtime ?? "mcp"
2389
2577
  });
2390
2578
  if (runtimeSession?.sessionId && activeName) {
2391
- saveSessionBind(configDir, runtimeSession.sessionId, activeName);
2579
+ const existingBinds = loadSessionBinds(configDir);
2580
+ if (!isImplicitAgyBoot || existingBinds[runtimeSession.sessionId] === activeName) {
2581
+ saveSessionBind(configDir, runtimeSession.sessionId, activeName);
2582
+ }
2392
2583
  }
2393
2584
  }
2394
2585
  var identityGateMessage = "";
2395
- var identityGuardFile = join6(configDir, IDENTITY_GUARD_FILENAME);
2586
+ var identityGuardFile = join7(configDir, IDENTITY_GUARD_FILENAME);
2396
2587
  function persistGuardRecord(rec) {
2397
2588
  try {
2398
2589
  mkdirSync3(configDir, { recursive: true });
@@ -2411,7 +2602,7 @@ function confirmLiveIdentityTrusted() {
2411
2602
  }
2412
2603
  var guardRecord = (() => {
2413
2604
  try {
2414
- return parseGuardRecord(readFileSync7(identityGuardFile, "utf-8"));
2605
+ return parseGuardRecord(readFileSync9(identityGuardFile, "utf-8"));
2415
2606
  } catch {
2416
2607
  return emptyGuardRecord();
2417
2608
  }
@@ -3309,7 +3500,7 @@ var ALL_TOOL_DEFS = [
3309
3500
  },
3310
3501
  {
3311
3502
  name: "channel_brief",
3312
- 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.",
3503
+ 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.",
3313
3504
  inputSchema: {
3314
3505
  type: "object",
3315
3506
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -3318,7 +3509,7 @@ var ALL_TOOL_DEFS = [
3318
3509
  },
3319
3510
  {
3320
3511
  name: "list_members",
3321
- description: "List members in a channel.",
3512
+ description: "List members in a channel with full @agent_id handles, online status, and peer capability tags (human login emails/phones masked).",
3322
3513
  inputSchema: {
3323
3514
  type: "object",
3324
3515
  properties: {
@@ -3799,7 +3990,7 @@ async function uploadLocalFile(path, kindHint) {
3799
3990
  if (!existsSync7(path))
3800
3991
  throw new Error(`file not found: ${path}`);
3801
3992
  const mime = mimeFromPath(path, kindHint);
3802
- const buf = readFileSync7(path);
3993
+ const buf = readFileSync9(path);
3803
3994
  const name = path.split("/").pop() || "upload";
3804
3995
  const form = new FormData;
3805
3996
  form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
@@ -3999,7 +4190,7 @@ function loadGrokBinds() {
3999
4190
  if (!existsSync7(bindPath))
4000
4191
  return {};
4001
4192
  try {
4002
- return parseGrokBindsText(readFileSync7(bindPath, "utf-8")).binds;
4193
+ return parseGrokBindsText(readFileSync9(bindPath, "utf-8")).binds;
4003
4194
  } catch {
4004
4195
  return {};
4005
4196
  }
@@ -4034,7 +4225,7 @@ function scheduleSlotLastSeenMessageTsSave(slot) {
4034
4225
  slot.lastSeenMessageTsTimer.unref?.();
4035
4226
  }
4036
4227
  function createProfileSlot(opts) {
4037
- const lastSeenFile = join6(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
4228
+ const lastSeenFile = join7(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
4038
4229
  const slot = {
4039
4230
  profileName: opts.profileName,
4040
4231
  profileFile: opts.profileFile,
@@ -4116,6 +4307,28 @@ function setAnonymousCallerState(callerSession) {
4116
4307
  runtimeSession = callerSession;
4117
4308
  }
4118
4309
  }
4310
+ function findSlotByAgentId(agentId) {
4311
+ if (!agentId)
4312
+ return;
4313
+ for (const s of profileSlots.values()) {
4314
+ if (s.agentId === agentId)
4315
+ return s;
4316
+ }
4317
+ return;
4318
+ }
4319
+ function upgradeAliasSlotInPlace(slot, newProfileName, newProfileFile, newProfile, sess) {
4320
+ if (slot.profileName !== newProfileName) {
4321
+ profileSlots.delete(slot.profileName);
4322
+ slot.profileName = newProfileName;
4323
+ profileSlots.set(newProfileName, slot);
4324
+ }
4325
+ slot.profileFile = newProfileFile;
4326
+ slot.profile = newProfile;
4327
+ slot.runtimeSession = sess;
4328
+ if (activeSlot === slot) {
4329
+ activateSlot(slot, sess);
4330
+ }
4331
+ }
4119
4332
  function teardownSlot(slot, opts) {
4120
4333
  try {
4121
4334
  flushSlotLastSeenMessageTs(slot);
@@ -4262,7 +4475,7 @@ function formatProfileList() {
4262
4475
  const lines = profileEntries.map((entry) => {
4263
4476
  let entryAgentId = "";
4264
4477
  try {
4265
- const parsed = JSON.parse(readFileSync7(entry.path, "utf-8"));
4478
+ const parsed = JSON.parse(readFileSync9(entry.path, "utf-8"));
4266
4479
  if (typeof parsed?.agent_id === "string")
4267
4480
  entryAgentId = parsed.agent_id;
4268
4481
  } catch {}
@@ -4270,7 +4483,8 @@ function formatProfileList() {
4270
4483
  const lock = entryAgentId ? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid }) : { locked: false };
4271
4484
  const slot = profileSlots.get(entry.name);
4272
4485
  const boundSid = findBoundSessionForProfile(configDir, entry.name);
4273
- const statusSuffix = lock.locked ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]` : slot && slot.ws?.readyState === WebSocket.OPEN ? ` [online${boundSid ? ` session=${boundSid}` : ""}]` : "";
4486
+ const dupCollision = entry.name.toLowerCase() === "profile" ? findDefaultProfileCollision(configDir, entry.path) : null;
4487
+ const statusSuffix = dupCollision ? ` [duplicate of ${dupCollision.collidingName} \u2014 disallowed; delete profile.json]` : lock.locked ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]` : slot && slot.ws?.readyState === WebSocket.OPEN ? ` [online${boundSid ? ` session=${boundSid}` : ""}]` : "";
4274
4488
  return `${isCurrent ? "\u2192 " : " "}${entry.name}${statusSuffix}`;
4275
4489
  });
4276
4490
  return `Current: ${current || "(anonymous / disconnected)"}
@@ -4283,6 +4497,42 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
4283
4497
  if (!cleanName) {
4284
4498
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
4285
4499
  }
4500
+ const safeBase = cleanName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
4501
+ if (safeBase.toLowerCase() === "profile") {
4502
+ return {
4503
+ content: [{
4504
+ type: "text",
4505
+ 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").'
4506
+ }],
4507
+ isError: true
4508
+ };
4509
+ }
4510
+ const existingTargetFile = nameToPath(cleanName);
4511
+ if (existsSync7(existingTargetFile)) {
4512
+ return {
4513
+ content: [{
4514
+ type: "text",
4515
+ text: `Error: Profile "${cleanName}" already exists at ${existingTargetFile}. Pass profile_name="${cleanName}" to connect to it, or choose a different register_name.`
4516
+ }],
4517
+ isError: true
4518
+ };
4519
+ }
4520
+ const existingDefaultPath = nameToPath("profile");
4521
+ if (existsSync7(existingDefaultPath)) {
4522
+ try {
4523
+ const defParsed = JSON.parse(readFileSync9(existingDefaultPath, "utf-8"));
4524
+ const defDisplay = typeof defParsed?.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
4525
+ if (defDisplay && defDisplay === cleanName.toLowerCase()) {
4526
+ return {
4527
+ content: [{
4528
+ type: "text",
4529
+ 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.`
4530
+ }],
4531
+ isError: true
4532
+ };
4533
+ }
4534
+ } catch {}
4535
+ }
4286
4536
  const caps = ["claude-code", "coding", "chat"];
4287
4537
  try {
4288
4538
  const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
@@ -4314,10 +4564,6 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
4314
4564
  validateIdentityProfile(newProfile, targetFile);
4315
4565
  mkdirSync3(dirname(targetFile), { recursive: true });
4316
4566
  safeWriteProfile2(targetFile, newProfile);
4317
- const defaultProfileFile = nameToPath("profile");
4318
- if (!existsSync7(defaultProfileFile)) {
4319
- safeWriteProfile2(defaultProfileFile, newProfile);
4320
- }
4321
4567
  applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
4322
4568
  const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
4323
4569
  return {
@@ -4385,6 +4631,18 @@ async function handleProfileSwitchOrConnect(args) {
4385
4631
  isError: true
4386
4632
  };
4387
4633
  }
4634
+ if (profileNameFromPath(targetFile)?.toLowerCase() === "profile") {
4635
+ const dupCollision = findDefaultProfileCollision(configDir, targetFile);
4636
+ if (dupCollision) {
4637
+ return {
4638
+ content: [{
4639
+ type: "text",
4640
+ text: `Refusing to connect "profile" (${targetFile}): profile.json collides (${dupCollision.reason}) with named profile "${dupCollision.collidingName}" (${dupCollision.collidingPath}). ` + `Delete ${targetFile} and connect via profile_name="${dupCollision.collidingName}" instead.`
4641
+ }],
4642
+ isError: true
4643
+ };
4644
+ }
4645
+ }
4388
4646
  const newProfile = readIdentityProfile(targetFile);
4389
4647
  validateIdentityProfile(newProfile, targetFile);
4390
4648
  const effectiveSessionId = explicitSessionId ?? runtimeSession?.sessionId ?? null;
@@ -4559,16 +4817,32 @@ var handleToolCall = async (request) => {
4559
4817
  if (existsSync7(boundPath)) {
4560
4818
  try {
4561
4819
  const candidate = readIdentityProfile(boundPath);
4562
- const lock = checkAgentLock({
4563
- lockDir,
4564
- agentId: candidate?.agent_id,
4565
- currentSessionId: callerSession.sessionId,
4566
- lockOwnerPid
4567
- });
4568
- if (!lock.locked) {
4569
- applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
4570
- } else if (isPerCallSession) {
4571
- setAnonymousCallerState(callerSession);
4820
+ const aliasSlot = candidate?.agent_id ? findSlotByAgentId(candidate.agent_id) : undefined;
4821
+ const aliasSid = aliasSlot ? aliasSlot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, aliasSlot.profileName) || resolveSessionForAgent(aliasSlot.agentId, { configDir })?.sessionId || null : null;
4822
+ if (aliasSlot && (!aliasSid || aliasSid === callerSession.sessionId)) {
4823
+ upgradeAliasSlotInPlace(aliasSlot, boundProfileName, boundPath, candidate, callerSession);
4824
+ activateSlot(aliasSlot, callerSession);
4825
+ if (!toolOnlyMode) {
4826
+ acquireAgentLock({
4827
+ lockDir,
4828
+ agentId: aliasSlot.agentId,
4829
+ profileName: boundProfileName,
4830
+ sessionId: callerSession.sessionId,
4831
+ runtime: callerSession.runtime
4832
+ });
4833
+ }
4834
+ } else {
4835
+ const lock = checkAgentLock({
4836
+ lockDir,
4837
+ agentId: candidate?.agent_id,
4838
+ currentSessionId: callerSession.sessionId,
4839
+ lockOwnerPid
4840
+ });
4841
+ if (!lock.locked) {
4842
+ applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
4843
+ } else if (isPerCallSession) {
4844
+ setAnonymousCallerState(callerSession);
4845
+ }
4572
4846
  }
4573
4847
  } catch {}
4574
4848
  } else if (isPerCallSession) {
@@ -4580,7 +4854,7 @@ var handleToolCall = async (request) => {
4580
4854
  } else {
4581
4855
  let unboundSlot = null;
4582
4856
  for (const slot of profileSlots.values()) {
4583
- const slotBoundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
4857
+ const slotBoundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName) || resolveSessionForAgent(slot.agentId, { configDir })?.sessionId;
4584
4858
  if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
4585
4859
  unboundSlot = slot;
4586
4860
  break;
@@ -4833,7 +5107,7 @@ ${a.body || ""}`;
4833
5107
  const currentVersion = Number(meta.version ?? 0);
4834
5108
  let cachedVersion = null;
4835
5109
  try {
4836
- cachedVersion = Number(JSON.parse(readFileSync7(pMeta, "utf8")).version);
5110
+ cachedVersion = Number(JSON.parse(readFileSync9(pMeta, "utf8")).version);
4837
5111
  } catch {}
4838
5112
  if (cachedVersion !== null && cachedVersion === currentVersion) {
4839
5113
  return { content: [{ type: "text", text: `up-to-date: personal skill "${a.name}" v${currentVersion} already at ${pMd} \u2014 no download. Read that file to run it.` }] };
@@ -4867,7 +5141,7 @@ ${a.body || ""}`;
4867
5141
  const currentVersion = Number(meta.version ?? 0);
4868
5142
  let cachedVersion = null;
4869
5143
  try {
4870
- cachedVersion = Number(JSON.parse(readFileSync7(metaPath, "utf8")).version);
5144
+ cachedVersion = Number(JSON.parse(readFileSync9(metaPath, "utf8")).version);
4871
5145
  } catch {}
4872
5146
  if (cachedVersion !== null && cachedVersion === currentVersion) {
4873
5147
  return { content: [{ type: "text", text: `up-to-date: "${a.doc_id}" v${currentVersion} already at ${mdPath} \u2014 no download. Read that file to run it.` }] };
@@ -5196,7 +5470,7 @@ ${a.body || ""}`;
5196
5470
  }
5197
5471
  const data = await r.json();
5198
5472
  if (data.messages?.length > 0) {
5199
- const results = data.messages.map((m) => `[${m.sender_id?.slice(0, 8)}] ${m.content?.slice(0, 80)}`).join(`
5473
+ const results = data.messages.map((m) => `[${redactParticipantPii(m.sender_id || "?")}] ${m.content?.slice(0, 80)}`).join(`
5200
5474
  `);
5201
5475
  return { content: [{ type: "text", text: `Found ${data.messages.length} results:
5202
5476
  ${results}` }] };
@@ -5244,6 +5518,44 @@ ${results}` }] };
5244
5518
  }
5245
5519
  return { content: [{ type: "text", text: "Not connected" }] };
5246
5520
  }
5521
+ async function fetchMcpChannelContext(chatId) {
5522
+ if (!chatId || !TOKEN)
5523
+ return null;
5524
+ try {
5525
+ const r = await apiFetch(`${REST_URL}/mcp`, {
5526
+ method: "POST",
5527
+ headers: {
5528
+ Authorization: `Bearer ${TOKEN}`,
5529
+ "Content-Type": "application/json",
5530
+ ...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
5531
+ },
5532
+ body: JSON.stringify({
5533
+ jsonrpc: "2.0",
5534
+ id: 1,
5535
+ method: "tools/call",
5536
+ params: {
5537
+ name: "agentschat_get_channel_context",
5538
+ arguments: { channel_id: chatId }
5539
+ }
5540
+ })
5541
+ }, 2500);
5542
+ if (!r.ok)
5543
+ return null;
5544
+ const rpc = await r.json();
5545
+ if (rpc?.error || rpc?.result?.isError)
5546
+ return null;
5547
+ const structured = rpc?.result?.structuredContent;
5548
+ if (structured && typeof structured === "object")
5549
+ return structured;
5550
+ const textPayload = rpc?.result?.content?.[0]?.text;
5551
+ if (typeof textPayload === "string" && textPayload.trim().startsWith("{")) {
5552
+ return JSON.parse(textPayload);
5553
+ }
5554
+ return null;
5555
+ } catch {
5556
+ return null;
5557
+ }
5558
+ }
5247
5559
  async function channelBrief(chatId) {
5248
5560
  const get = async (path) => {
5249
5561
  try {
@@ -5253,26 +5565,45 @@ ${results}` }] };
5253
5565
  return null;
5254
5566
  }
5255
5567
  };
5256
- const [membersData, docsData, okrData] = await Promise.all([
5568
+ const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
5257
5569
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
5258
5570
  get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
5259
- get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`)
5571
+ get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
5572
+ fetchMcpChannelContext(chatId)
5260
5573
  ]);
5261
5574
  const membersReadable = membersData !== null;
5262
5575
  const memberIds = (membersData?.members || []).map((m) => m?.agent_id).filter(Boolean);
5576
+ const memberIdSet = new Set(memberIds);
5577
+ const rawOnlineSet = new Set;
5263
5578
  let online = [];
5264
5579
  if (memberIds.length > 0) {
5265
- const onlineSet = new Set;
5266
5580
  for (let i = 0;i < memberIds.length; i += 50) {
5267
5581
  const batch = memberIds.slice(i, i + 50);
5268
5582
  const pres = await get(`/api/presence?ids=${encodeURIComponent(batch.join(","))}`);
5269
5583
  for (const [k, v] of Object.entries(pres?.presence || {})) {
5270
- if (v === "online")
5271
- onlineSet.add(k);
5584
+ if (v === "online" && memberIdSet.has(k))
5585
+ rawOnlineSet.add(k);
5272
5586
  }
5273
5587
  }
5274
- online = [...onlineSet];
5275
- }
5588
+ const maskedOnlineSet = new Set;
5589
+ for (const id of rawOnlineSet) {
5590
+ maskedOnlineSet.add(redactParticipantPii(id));
5591
+ }
5592
+ online = [...maskedOnlineSet];
5593
+ }
5594
+ const agentPeers = Array.isArray(mcpCtx?.agents) ? mcpCtx.agents.filter((a) => a?.id && !isHumanPiiHandle(a.id)).map((a) => ({
5595
+ id: String(a.id),
5596
+ ...a.name && !isHumanPiiHandle(a.name) ? { name: String(a.name) } : {},
5597
+ capabilities: Array.isArray(a.capabilities) ? a.capabilities.map(String) : [],
5598
+ ...typeof a.online === "boolean" ? { online: a.online } : memberIds.length > 0 ? { online: rawOnlineSet.has(String(a.id)) } : {},
5599
+ is_self: typeof a.is_self === "boolean" ? a.is_self : String(a.id) === AGENT_ID
5600
+ })) : (membersData?.members || []).filter((m) => m?.agent_id && !isHumanPiiHandle(m.agent_id) && m.type !== "user").map((m) => ({
5601
+ id: String(m.agent_id),
5602
+ ...m.display_name && !isHumanPiiHandle(m.display_name) ? { name: String(m.display_name) } : {},
5603
+ capabilities: Array.isArray(m.capabilities) ? m.capabilities.map(String) : [],
5604
+ ...typeof m.online === "boolean" ? { online: m.online } : memberIds.length > 0 ? { online: rawOnlineSet.has(String(m.agent_id)) } : {},
5605
+ is_self: String(m.agent_id) === AGENT_ID
5606
+ }));
5276
5607
  const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
5277
5608
  const skills = allDocs.filter(isSkillDoc).map((d) => ({ doc_id: d.id, title: d.title }));
5278
5609
  const docs = allDocs.filter((d) => !isSkillDoc(d)).slice(0, 10).map((d) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
@@ -5288,7 +5619,10 @@ ${results}` }] };
5288
5619
  }));
5289
5620
  return JSON.stringify({
5290
5621
  channel: chatId,
5622
+ ...mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {},
5623
+ ...mcpCtx?.channel?.topic ? { topic: String(mcpCtx.channel.topic) } : {},
5291
5624
  members: membersReadable ? { total: memberIds.length, online } : { total: null, note: "roster unreadable \u2014 you are likely not a member of this channel (or it does not exist)" },
5625
+ ...membersReadable ? { agent_peers: agentPeers } : {},
5292
5626
  okr_objectives: objectives,
5293
5627
  skills,
5294
5628
  docs,
@@ -5658,15 +5992,38 @@ ${lines}` }] };
5658
5992
  if (name === "list_members") {
5659
5993
  const { chat_id } = args;
5660
5994
  try {
5661
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { Authorization: `Bearer ${TOKEN}` } });
5995
+ const [r, mcpCtx] = await Promise.all([
5996
+ apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { Authorization: `Bearer ${TOKEN}` } }),
5997
+ fetchMcpChannelContext(chat_id)
5998
+ ]);
5662
5999
  if (r.ok) {
5663
6000
  const data = await r.json();
5664
6001
  const members = data.members || [];
5665
6002
  if (members.length === 0)
5666
6003
  return { content: [{ type: "text", text: "No members found." }] };
5667
- const list = members.map((m) => `\u2022 ${m.display_name || m.agent_id} (${m.agent_id.slice(0, 12)})${m.role ? ` [${m.role}]` : ""}`).join(`
6004
+ const peerById = new Map;
6005
+ for (const a of Array.isArray(mcpCtx?.agents) ? mcpCtx.agents : []) {
6006
+ if (a?.id && !isHumanPiiHandle(a.id)) {
6007
+ peerById.set(String(a.id), a);
6008
+ }
6009
+ }
6010
+ const list = members.map((m) => {
6011
+ const rawId = String(m?.agent_id ?? "");
6012
+ const isHuman = isHumanPiiHandle(rawId) || m?.type === "user";
6013
+ const safeId = redactParticipantPii(rawId);
6014
+ const peer = !isHuman ? peerById.get(rawId) : undefined;
6015
+ const rawDisplay = m?.display_name ? String(m.display_name).trim() : peer?.name ? String(peer.name).trim() : "";
6016
+ const safeDisplay = rawDisplay && !isHumanPiiHandle(rawDisplay) ? rawDisplay : safeId;
6017
+ const handleBadge = isHuman ? `(${safeId})` : `(@${safeId})`;
6018
+ const roleBadge = m?.role ? ` [${m.role}]` : "";
6019
+ const onlineVal = typeof m?.online === "boolean" ? m.online : peer?.online;
6020
+ const onlineBadge = typeof onlineVal === "boolean" ? ` (${onlineVal ? "online" : "offline"})` : "";
6021
+ const caps = Array.isArray(peer?.capabilities) && peer.capabilities.length > 0 ? peer.capabilities : Array.isArray(m?.capabilities) ? m.capabilities : [];
6022
+ const capsBadge = caps.length > 0 ? ` {capabilities: ${caps.join(", ")}}` : "";
6023
+ return `\u2022 ${safeDisplay} ${handleBadge}${roleBadge}${onlineBadge}${capsBadge}`;
6024
+ }).join(`
5668
6025
  `);
5669
- return { content: [{ type: "text", text: `${members.length} members in ${chat_id.slice(0, 8)}:
6026
+ return { content: [{ type: "text", text: `${members.length} members in ${chat_id}:
5670
6027
  ${list}` }] };
5671
6028
  }
5672
6029
  return { content: [{ type: "text", text: `Failed to list members (${r.status})` }] };
@@ -5682,7 +6039,7 @@ ${list}` }] };
5682
6039
  const time = m.timestamp ? new Date(m.timestamp).toLocaleString() : "?";
5683
6040
  const rawContent = String(m.content ?? "");
5684
6041
  const body = full || rawContent.length <= MAX_HISTORY_MESSAGE_CHARS ? rawContent : `${rawContent.slice(0, MAX_HISTORY_MESSAGE_CHARS)}\u2026 [truncated ${rawContent.length - MAX_HISTORY_MESSAGE_CHARS} chars; pass message_id="${m.id || ""}" to get_history for full text]`;
5685
- let line = `[${time}] ${m.sender_id?.slice(0, 12)}: ${body}`;
6042
+ let line = `[${time}] ${redactParticipantPii(m.sender_id || "?")}: ${body}`;
5686
6043
  const atts = Array.isArray(m.attachments) ? m.attachments : [];
5687
6044
  for (const a of atts) {
5688
6045
  if (!a?.url)
@@ -6121,7 +6478,7 @@ ${list}` }] };
6121
6478
  }
6122
6479
  };
6123
6480
  server.setRequestHandler(CallToolRequestSchema, (request) => serializeCall(() => handleToolCall(request)));
6124
- var mentionTsFile = join6(configDir, `mention-ts-${AGENT_ID}.json`);
6481
+ var mentionTsFile = join7(configDir, `mention-ts-${AGENT_ID}.json`);
6125
6482
  function loadMentionTimestamps() {
6126
6483
  return loadCursor(mentionTsFile, safeStderrWrite);
6127
6484
  }
@@ -6268,6 +6625,7 @@ function clearFinishedHiddenIdentityGamesFromMessage(data) {
6268
6625
  }
6269
6626
  }
6270
6627
  }
6628
+ var processAgentMessageDedup = new MessageDedup;
6271
6629
  function deliverySource(data) {
6272
6630
  return typeof data?.__source === "string" ? data.__source : "live";
6273
6631
  }
@@ -6275,7 +6633,9 @@ function recordOrSkipDeliveredMessage(data, slot = activeSlot) {
6275
6633
  const key = messageDedupKey(data);
6276
6634
  if (!key || !slot)
6277
6635
  return false;
6278
- const skip = slot.messageDedup.recordOrSkip(key);
6636
+ const slotSkip = slot.messageDedup.recordOrSkip(key);
6637
+ const agentSkip = slot.agentId ? processAgentMessageDedup.recordOrSkip(`${slot.agentId}:${key}`) : false;
6638
+ const skip = slotSkip || agentSkip;
6279
6639
  if (skip) {
6280
6640
  process.stderr.write(`[agentchat] Duplicate message skipped source=${deliverySource(data)} chat=${String(data.channel_id).slice(0, 12)} id=${String(data.id).slice(0, 12)}
6281
6641
  `);
@@ -6364,6 +6724,22 @@ function syncOpenBoundSessions() {
6364
6724
  try {
6365
6725
  const candidate = readIdentityProfile(boundPath);
6366
6726
  validateIdentityProfile(candidate, boundPath);
6727
+ const sess = { sessionId: cid, runtime: "antigravity" };
6728
+ const existingByAgent = findSlotByAgentId(candidate.agent_id);
6729
+ if (existingByAgent) {
6730
+ const existingSid = existingByAgent.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, existingByAgent.profileName);
6731
+ if (!existingSid || existingSid === cid) {
6732
+ upgradeAliasSlotInPlace(existingByAgent, boundProf, boundPath, candidate, sess);
6733
+ acquireAgentLock({
6734
+ lockDir,
6735
+ agentId: existingByAgent.agentId,
6736
+ profileName: boundProf,
6737
+ sessionId: cid,
6738
+ runtime: "antigravity"
6739
+ });
6740
+ }
6741
+ continue;
6742
+ }
6367
6743
  const lock = checkAgentLock({
6368
6744
  lockDir,
6369
6745
  agentId: candidate.agent_id,
@@ -6372,7 +6748,6 @@ function syncOpenBoundSessions() {
6372
6748
  });
6373
6749
  if (lock.locked)
6374
6750
  continue;
6375
- const sess = { sessionId: cid, runtime: "antigravity" };
6376
6751
  acquireAgentLock({
6377
6752
  lockDir,
6378
6753
  agentId: candidate.agent_id,
@@ -6527,7 +6902,7 @@ function connectWS(slot = activeSlot) {
6527
6902
  }
6528
6903
  const truncatedMsgs = trimmed.length < msgs.length;
6529
6904
  if (trimmed.length > 0) {
6530
- const context = trimmed.map((m) => `${m.sender_id}: ${m.content}${formatWakeAttachments(m.attachments)}`).join(`
6905
+ const context = trimmed.map((m) => `${redactParticipantPii(m.sender_id || "?")}: ${m.content}${formatWakeAttachments(m.attachments)}`).join(`
6531
6906
  `);
6532
6907
  const note = truncatedMsgs ? `[\u9891\u9053\u4E0A\u4E0B\u6587 - \u6700\u8FD1 ${trimmed.length} \u6761\u6D88\u606F\uFF08\u66F4\u65E9\u7684\u5DF2\u622A\u65AD\u4FDD\u62A4\u4E0A\u4E0B\u6587\u7A97\u53E3\uFF09]` : `[\u9891\u9053\u4E0A\u4E0B\u6587 - \u81EA\u4E0A\u6B21 @mention \u4EE5\u6765 ${trimmed.length} \u6761\u6D88\u606F]`;
6533
6908
  contextPrefix = `${note}
@@ -6575,7 +6950,7 @@ ${context}
6575
6950
  if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
6576
6951
  (async () => {
6577
6952
  try {
6578
- const { readFileSync: readFileSync8, existsSync: existsSync8 } = await import("fs");
6953
+ const { readFileSync: readFileSync10, existsSync: existsSync8 } = await import("fs");
6579
6954
  const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync8);
6580
6955
  let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
6581
6956
  if (!agentId) {
@@ -6583,7 +6958,7 @@ ${context}
6583
6958
  explicitId: "",
6584
6959
  agentschatName: slot.profile.display_name || slot.agentId,
6585
6960
  listAgents: async () => {
6586
- const gwcfg = JSON.parse(readFileSync8(gwPath, "utf8"));
6961
+ const gwcfg = JSON.parse(readFileSync10(gwPath, "utf8"));
6587
6962
  const token = grokBearerFromGatewayConfig(gwcfg);
6588
6963
  const port = grokPortFromGatewayConfig(gwcfg);
6589
6964
  const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
@@ -6613,7 +6988,8 @@ ${context}
6613
6988
  targetSessionId
6614
6989
  });
6615
6990
  } else if (slotRuntime === "zcode" || process.env.AGENTCHAT_WAKE_MODE === "zcode" || Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")))) {
6616
- const zcodeSid = findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")) || (slotRuntime === "zcode" ? slot.runtimeSession?.sessionId : "") || "";
6991
+ const isZcodeSid = (sid) => sid.startsWith("sess_");
6992
+ const zcodeSid = findBoundSessionForProfile(configDir, slotProfName, isZcodeSid) || resolveSessionForAgent(slot.agentId, { configDir, filter: isZcodeSid })?.sessionId || (slotRuntime === "zcode" ? slot.runtimeSession?.sessionId : "") || "";
6617
6993
  if (zcodeSid) {
6618
6994
  fireZcodeWake(data, {
6619
6995
  sessionId: zcodeSid,
@@ -6626,7 +7002,8 @@ ${context}
6626
7002
  });
6627
7003
  }
6628
7004
  } else if (slotRuntime === "dsh" || isDshHostProcess() || Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")))) {
6629
- const dshSid = findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")) || resolveSessionForAgent(slot.agentId, { configDir })?.sessionId || (slotRuntime === "dsh" ? slot.runtimeSession?.sessionId : "") || undefined;
7005
+ const isDshSid = (sid) => sid.startsWith("session-");
7006
+ const dshSid = findBoundSessionForProfile(configDir, slotProfName, isDshSid) || resolveSessionForAgent(slot.agentId, { configDir, filter: isDshSid })?.sessionId || (slotRuntime === "dsh" ? slot.runtimeSession?.sessionId : "") || undefined;
6630
7007
  const dshWakeUrl = process.env.DSH_WAKE_URL || process.env.AGENTSCHAT_DSH_WAKE_URL || "http://127.0.0.1:8799/wake";
6631
7008
  fireWake(data, {
6632
7009
  url: dshWakeUrl,
@@ -6641,14 +7018,28 @@ ${context}
6641
7018
  const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
6642
7019
  if (!agyHost && !lsAddress)
6643
7020
  return;
7021
+ const isAgyUuid = (sid) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(sid);
6644
7022
  const allBinds = loadSessionBinds(configDir);
6645
- let targetCid = findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) || (slotRuntime === "antigravity" ? slot.runtimeSession?.sessionId : "") || "";
7023
+ let targetCid = findBoundSessionForProfile(configDir, slotProfName, isAgyUuid) || resolveSessionForAgent(slot.agentId, { configDir, filter: isAgyUuid })?.sessionId || (slotRuntime === "antigravity" && slot.runtimeSession?.sessionId && isAgyUuid(slot.runtimeSession.sessionId) ? slot.runtimeSession.sessionId : "") || "";
6646
7024
  if (!targetCid && agyHost) {
6647
7025
  if (agyHost.openConversations.length === 1) {
6648
- targetCid = agyHost.openConversations[0];
7026
+ const soleCid = agyHost.openConversations[0];
7027
+ const soleBoundProf = allBinds[soleCid];
7028
+ let soleMatchesAgent = false;
7029
+ if (soleBoundProf) {
7030
+ const p = nameToPath(soleBoundProf);
7031
+ if (existsSync7(p)) {
7032
+ try {
7033
+ soleMatchesAgent = readIdentityProfile(p)?.agent_id === slot.agentId;
7034
+ } catch {}
7035
+ }
7036
+ }
7037
+ if (!soleBoundProf || soleBoundProf === slotProfName || soleMatchesAgent) {
7038
+ targetCid = soleCid;
7039
+ }
6649
7040
  } else if (agyHost.openConversations.length > 1) {
6650
- const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] === slotProfName);
6651
- targetCid = unboundOrSame || agyHost.openConversations[0];
7041
+ rateLimitedLog(`agy-wake-unbound:${slot.agentId}`, `[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).
7042
+ `);
6652
7043
  }
6653
7044
  }
6654
7045
  if (targetCid && csrfToken) {
@@ -6828,6 +7219,13 @@ async function main() {
6828
7219
  installStdioLifecycleGuards();
6829
7220
  if (!toolOnlyMode) {
6830
7221
  syncOpenBoundSessions();
7222
+ if (process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL) || Boolean(process.env.ANTIGRAVITY_LS_ADDRESS) || Boolean(discoverAntigravityHost())) {
7223
+ const agySyncTimer = setInterval(() => {
7224
+ if (!shuttingDown)
7225
+ syncOpenBoundSessions();
7226
+ }, 15000);
7227
+ agySyncTimer.unref?.();
7228
+ }
6831
7229
  }
6832
7230
  if (anonymousMode && profileSlots.size === 0) {
6833
7231
  process.stderr.write(`[agentchat] Anonymous \u2014 not connecting to the hub.