agentschat-mcp 0.36.21 → 0.36.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.21",
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,11 +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";
1862
+ import { fileURLToPath } from "url";
1770
1863
 
1771
1864
  // src/profile-store.ts
1772
- 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";
1773
1867
  var defaultWarn2 = (m) => process.stderr.write(m);
1774
1868
  function safeWriteProfile2(path, data, warn = defaultWarn2) {
1775
1869
  const tmp = path + ".tmp";
@@ -1799,6 +1893,73 @@ function safeWriteProfile2(path, data, warn = defaultWarn2) {
1799
1893
  `);
1800
1894
  }
1801
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
+ }
1802
1963
 
1803
1964
  // src/identity-guard.ts
1804
1965
  var IDENTITY_GUARD_FILENAME = "identity-guard.json";
@@ -1882,10 +2043,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
1882
2043
  }
1883
2044
 
1884
2045
  // src/read-cursor.ts
1885
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
2046
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
1886
2047
  function loadCursor(file, warn) {
1887
2048
  try {
1888
- return new Map(Object.entries(JSON.parse(readFileSync6(file, "utf-8"))));
2049
+ return new Map(Object.entries(JSON.parse(readFileSync8(file, "utf-8"))));
1889
2050
  } catch (e) {
1890
2051
  if (e?.code !== "ENOENT") {
1891
2052
  warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
@@ -1967,18 +2128,20 @@ function parseArgs() {
1967
2128
  }
1968
2129
  var cliArgs = parseArgs();
1969
2130
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
2131
+ const localOnboardingPath = join7(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
1970
2132
  console.log(`agentschat-mcp v${package_default.version} \u2014 AgentsChat MCP and host bridges
1971
2133
 
1972
2134
  Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
1973
2135
  claude --dangerously-load-development-channels server:agentschat
1974
- One MCP server entry per bot, each pinning --profile.
2136
+ One MCP server entry per bot, each pinning --profile (or omit --profile on session-aware hosts).
1975
2137
 
1976
- Setup guide for every supported host:
1977
- Read skills/onboarding.md relative to this installed package root.
1978
- Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
2138
+ Setup guide for every supported host (Single Source of Truth):
2139
+ Local file: ${localOnboardingPath}
2140
+ Relative: skills/onboarding.md (relative to this installed package root)
2141
+ Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
1979
2142
  Newest release (first install): npx -y agentschat-mcp@latest --help
1980
- The guide selects Claude Code, Codex, OpenClaw, Hermes, Grok Bot, URL wake,
1981
- or the separately deployed dot remote MCP + Events integration.
2143
+ Covers Claude Code, Codex, DeepSeek Harness (dsh), OpenClaw, Hermes, Grok Bot,
2144
+ Antigravity, ZCode, Muse, dot / Work Cloud (remote MCP + Events), and URL wake.
1982
2145
  Help only prints instructions; follow the guide and verify a real reply.
1983
2146
 
1984
2147
  Options:
@@ -2031,8 +2194,8 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
2031
2194
  process.exit(0);
2032
2195
  }
2033
2196
  var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
2034
- var configDir = join6(homeDir, ".agentschat");
2035
- var legacyConfigDir = join6(homeDir, ".agentchat");
2197
+ var configDir = join7(homeDir, ".agentschat");
2198
+ var legacyConfigDir = join7(homeDir, ".agentchat");
2036
2199
  var profileDirs = [configDir, legacyConfigDir];
2037
2200
  var lockDir = resolveLockDir(homeDir, process.env);
2038
2201
  var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
@@ -2041,16 +2204,16 @@ var runtimeSession = detectRuntimeSession(process.env);
2041
2204
  var dshRouteWarned = false;
2042
2205
  function profileNameToPaths(name) {
2043
2206
  if (name.startsWith("~/"))
2044
- return [join6(homeDir, name.slice(2))];
2207
+ return [join7(homeDir, name.slice(2))];
2045
2208
  if (name.includes("/") || name.includes("\\"))
2046
2209
  return [name];
2047
2210
  name = name.replace(/\.json$/, "");
2048
2211
  const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
2049
- return profileDirs.map((dir) => join6(dir, `${safeName}.json`));
2212
+ return profileDirs.map((dir) => join7(dir, `${safeName}.json`));
2050
2213
  }
2051
2214
  function nameToPath(name) {
2052
2215
  const candidates = profileNameToPaths(name);
2053
- const nested = join6(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
2216
+ const nested = join7(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
2054
2217
  if (!name.includes("/") && !name.includes("\\") && existsSync7(nested))
2055
2218
  return nested;
2056
2219
  return candidates.find((path) => existsSync7(path)) || candidates[0];
@@ -2058,10 +2221,10 @@ function nameToPath(name) {
2058
2221
  function listProfileFiles() {
2059
2222
  const seen = new Set;
2060
2223
  const profiles = [];
2061
- for (const dir of [join6(configDir, "profiles"), ...profileDirs]) {
2224
+ for (const dir of [join7(configDir, "profiles"), ...profileDirs]) {
2062
2225
  let files = [];
2063
2226
  try {
2064
- files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
2227
+ files = readdirSync5(dir).filter((f) => f.endsWith(".json"));
2065
2228
  } catch {}
2066
2229
  for (const file of files) {
2067
2230
  if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME || file === DEFAULT_SESSION_BINDS_FILENAME || file === LEGACY_AGY_BINDS_FILENAME)
@@ -2070,7 +2233,7 @@ function listProfileFiles() {
2070
2233
  if (seen.has(name))
2071
2234
  continue;
2072
2235
  seen.add(name);
2073
- profiles.push({ name, path: join6(dir, file) });
2236
+ profiles.push({ name, path: join7(dir, file) });
2074
2237
  }
2075
2238
  }
2076
2239
  return profiles;
@@ -2097,7 +2260,7 @@ function resolveProfile() {
2097
2260
  const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
2098
2261
  if (existsSync7(bindPath)) {
2099
2262
  try {
2100
- const parsed = parseGrokBindsText(readFileSync7(bindPath, "utf-8"));
2263
+ const parsed = parseGrokBindsText(readFileSync9(bindPath, "utf-8"));
2101
2264
  binds = parsed.binds;
2102
2265
  if (parsed.malformed) {
2103
2266
  process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
@@ -2188,46 +2351,63 @@ var identity = decideIdentity({
2188
2351
  });
2189
2352
  function readIdentityProfile(file) {
2190
2353
  try {
2191
- return JSON.parse(readFileSync7(file, "utf-8"));
2354
+ return JSON.parse(readFileSync9(file, "utf-8"));
2192
2355
  } catch {
2193
2356
  throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
2194
2357
  }
2195
2358
  }
2196
2359
  if (identity.mode === "profile") {
2197
- try {
2198
- profile = readIdentityProfile(profileFile);
2199
- if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
2200
- throw new Error("Project agent_id does not match selected profile");
2201
- }
2202
- validateIdentityProfile(profile && !Array.isArray(profile) ? {
2203
- ...profile,
2204
- agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
2205
- token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
2206
- capabilities: cliArgs.caps?.split(",") ?? profile.capabilities
2207
- } : profile, profileFile, !hasToken);
2208
- } catch (e) {
2209
- 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.
2210
2366
  `);
2211
- process.exit(1);
2212
- }
2213
- const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
2214
- const lockCheck = !cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
2215
- lockDir,
2216
- agentId: candidateAgentId,
2217
- currentSessionId: runtimeSession?.sessionId ?? null,
2218
- lockOwnerPid
2219
- }) : { locked: false };
2220
- if (lockCheck.locked) {
2367
+ process.exit(1);
2368
+ }
2221
2369
  anonymousMode = true;
2222
2370
  activeProfileFile = null;
2223
2371
  profile = {};
2224
- 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}` : ""}.
2225
2404
  ` + ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.
2226
2405
  ` + ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.
2227
2406
  `);
2228
- } else {
2229
- process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
2407
+ } else {
2408
+ process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
2230
2409
  `);
2410
+ }
2231
2411
  }
2232
2412
  } else if (identity.mode === "env-creds") {
2233
2413
  activeProfileFile = null;
@@ -2370,11 +2550,22 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
2370
2550
  }
2371
2551
  }
2372
2552
  if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
2373
- const activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
2374
- if (activeName && runtimeSession?.runtime === "antigravity" && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim()) {
2375
- const existingBoundSid = findBoundSessionForProfile(configDir, activeName, (sid) => /^[0-9a-f-]{36}$/i.test(sid));
2376
- if (existingBoundSid) {
2377
- 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
+ }
2378
2569
  }
2379
2570
  }
2380
2571
  acquireAgentLock({
@@ -2385,11 +2576,14 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
2385
2576
  runtime: runtimeSession?.runtime ?? "mcp"
2386
2577
  });
2387
2578
  if (runtimeSession?.sessionId && activeName) {
2388
- saveSessionBind(configDir, runtimeSession.sessionId, activeName);
2579
+ const existingBinds = loadSessionBinds(configDir);
2580
+ if (!isImplicitAgyBoot || existingBinds[runtimeSession.sessionId] === activeName) {
2581
+ saveSessionBind(configDir, runtimeSession.sessionId, activeName);
2582
+ }
2389
2583
  }
2390
2584
  }
2391
2585
  var identityGateMessage = "";
2392
- var identityGuardFile = join6(configDir, IDENTITY_GUARD_FILENAME);
2586
+ var identityGuardFile = join7(configDir, IDENTITY_GUARD_FILENAME);
2393
2587
  function persistGuardRecord(rec) {
2394
2588
  try {
2395
2589
  mkdirSync3(configDir, { recursive: true });
@@ -2408,7 +2602,7 @@ function confirmLiveIdentityTrusted() {
2408
2602
  }
2409
2603
  var guardRecord = (() => {
2410
2604
  try {
2411
- return parseGuardRecord(readFileSync7(identityGuardFile, "utf-8"));
2605
+ return parseGuardRecord(readFileSync9(identityGuardFile, "utf-8"));
2412
2606
  } catch {
2413
2607
  return emptyGuardRecord();
2414
2608
  }
@@ -3306,7 +3500,7 @@ var ALL_TOOL_DEFS = [
3306
3500
  },
3307
3501
  {
3308
3502
  name: "channel_brief",
3309
- 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.",
3310
3504
  inputSchema: {
3311
3505
  type: "object",
3312
3506
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -3315,7 +3509,7 @@ var ALL_TOOL_DEFS = [
3315
3509
  },
3316
3510
  {
3317
3511
  name: "list_members",
3318
- 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).",
3319
3513
  inputSchema: {
3320
3514
  type: "object",
3321
3515
  properties: {
@@ -3796,7 +3990,7 @@ async function uploadLocalFile(path, kindHint) {
3796
3990
  if (!existsSync7(path))
3797
3991
  throw new Error(`file not found: ${path}`);
3798
3992
  const mime = mimeFromPath(path, kindHint);
3799
- const buf = readFileSync7(path);
3993
+ const buf = readFileSync9(path);
3800
3994
  const name = path.split("/").pop() || "upload";
3801
3995
  const form = new FormData;
3802
3996
  form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
@@ -3996,7 +4190,7 @@ function loadGrokBinds() {
3996
4190
  if (!existsSync7(bindPath))
3997
4191
  return {};
3998
4192
  try {
3999
- return parseGrokBindsText(readFileSync7(bindPath, "utf-8")).binds;
4193
+ return parseGrokBindsText(readFileSync9(bindPath, "utf-8")).binds;
4000
4194
  } catch {
4001
4195
  return {};
4002
4196
  }
@@ -4031,7 +4225,7 @@ function scheduleSlotLastSeenMessageTsSave(slot) {
4031
4225
  slot.lastSeenMessageTsTimer.unref?.();
4032
4226
  }
4033
4227
  function createProfileSlot(opts) {
4034
- const lastSeenFile = join6(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
4228
+ const lastSeenFile = join7(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
4035
4229
  const slot = {
4036
4230
  profileName: opts.profileName,
4037
4231
  profileFile: opts.profileFile,
@@ -4113,6 +4307,28 @@ function setAnonymousCallerState(callerSession) {
4113
4307
  runtimeSession = callerSession;
4114
4308
  }
4115
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
+ }
4116
4332
  function teardownSlot(slot, opts) {
4117
4333
  try {
4118
4334
  flushSlotLastSeenMessageTs(slot);
@@ -4259,7 +4475,7 @@ function formatProfileList() {
4259
4475
  const lines = profileEntries.map((entry) => {
4260
4476
  let entryAgentId = "";
4261
4477
  try {
4262
- const parsed = JSON.parse(readFileSync7(entry.path, "utf-8"));
4478
+ const parsed = JSON.parse(readFileSync9(entry.path, "utf-8"));
4263
4479
  if (typeof parsed?.agent_id === "string")
4264
4480
  entryAgentId = parsed.agent_id;
4265
4481
  } catch {}
@@ -4267,7 +4483,8 @@ function formatProfileList() {
4267
4483
  const lock = entryAgentId ? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid }) : { locked: false };
4268
4484
  const slot = profileSlots.get(entry.name);
4269
4485
  const boundSid = findBoundSessionForProfile(configDir, entry.name);
4270
- 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}` : ""}]` : "";
4271
4488
  return `${isCurrent ? "\u2192 " : " "}${entry.name}${statusSuffix}`;
4272
4489
  });
4273
4490
  return `Current: ${current || "(anonymous / disconnected)"}
@@ -4280,6 +4497,42 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
4280
4497
  if (!cleanName) {
4281
4498
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
4282
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
+ }
4283
4536
  const caps = ["claude-code", "coding", "chat"];
4284
4537
  try {
4285
4538
  const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
@@ -4311,10 +4564,6 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
4311
4564
  validateIdentityProfile(newProfile, targetFile);
4312
4565
  mkdirSync3(dirname(targetFile), { recursive: true });
4313
4566
  safeWriteProfile2(targetFile, newProfile);
4314
- const defaultProfileFile = nameToPath("profile");
4315
- if (!existsSync7(defaultProfileFile)) {
4316
- safeWriteProfile2(defaultProfileFile, newProfile);
4317
- }
4318
4567
  applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
4319
4568
  const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
4320
4569
  return {
@@ -4382,6 +4631,18 @@ async function handleProfileSwitchOrConnect(args) {
4382
4631
  isError: true
4383
4632
  };
4384
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
+ }
4385
4646
  const newProfile = readIdentityProfile(targetFile);
4386
4647
  validateIdentityProfile(newProfile, targetFile);
4387
4648
  const effectiveSessionId = explicitSessionId ?? runtimeSession?.sessionId ?? null;
@@ -4556,16 +4817,32 @@ var handleToolCall = async (request) => {
4556
4817
  if (existsSync7(boundPath)) {
4557
4818
  try {
4558
4819
  const candidate = readIdentityProfile(boundPath);
4559
- const lock = checkAgentLock({
4560
- lockDir,
4561
- agentId: candidate?.agent_id,
4562
- currentSessionId: callerSession.sessionId,
4563
- lockOwnerPid
4564
- });
4565
- if (!lock.locked) {
4566
- applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
4567
- } else if (isPerCallSession) {
4568
- 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
+ }
4569
4846
  }
4570
4847
  } catch {}
4571
4848
  } else if (isPerCallSession) {
@@ -4577,7 +4854,7 @@ var handleToolCall = async (request) => {
4577
4854
  } else {
4578
4855
  let unboundSlot = null;
4579
4856
  for (const slot of profileSlots.values()) {
4580
- const slotBoundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
4857
+ const slotBoundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName) || resolveSessionForAgent(slot.agentId, { configDir })?.sessionId;
4581
4858
  if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
4582
4859
  unboundSlot = slot;
4583
4860
  break;
@@ -4830,7 +5107,7 @@ ${a.body || ""}`;
4830
5107
  const currentVersion = Number(meta.version ?? 0);
4831
5108
  let cachedVersion = null;
4832
5109
  try {
4833
- cachedVersion = Number(JSON.parse(readFileSync7(pMeta, "utf8")).version);
5110
+ cachedVersion = Number(JSON.parse(readFileSync9(pMeta, "utf8")).version);
4834
5111
  } catch {}
4835
5112
  if (cachedVersion !== null && cachedVersion === currentVersion) {
4836
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.` }] };
@@ -4864,7 +5141,7 @@ ${a.body || ""}`;
4864
5141
  const currentVersion = Number(meta.version ?? 0);
4865
5142
  let cachedVersion = null;
4866
5143
  try {
4867
- cachedVersion = Number(JSON.parse(readFileSync7(metaPath, "utf8")).version);
5144
+ cachedVersion = Number(JSON.parse(readFileSync9(metaPath, "utf8")).version);
4868
5145
  } catch {}
4869
5146
  if (cachedVersion !== null && cachedVersion === currentVersion) {
4870
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.` }] };
@@ -5193,7 +5470,7 @@ ${a.body || ""}`;
5193
5470
  }
5194
5471
  const data = await r.json();
5195
5472
  if (data.messages?.length > 0) {
5196
- 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(`
5197
5474
  `);
5198
5475
  return { content: [{ type: "text", text: `Found ${data.messages.length} results:
5199
5476
  ${results}` }] };
@@ -5241,6 +5518,44 @@ ${results}` }] };
5241
5518
  }
5242
5519
  return { content: [{ type: "text", text: "Not connected" }] };
5243
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
+ }
5244
5559
  async function channelBrief(chatId) {
5245
5560
  const get = async (path) => {
5246
5561
  try {
@@ -5250,26 +5565,45 @@ ${results}` }] };
5250
5565
  return null;
5251
5566
  }
5252
5567
  };
5253
- const [membersData, docsData, okrData] = await Promise.all([
5568
+ const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
5254
5569
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
5255
5570
  get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
5256
- get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`)
5571
+ get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
5572
+ fetchMcpChannelContext(chatId)
5257
5573
  ]);
5258
5574
  const membersReadable = membersData !== null;
5259
5575
  const memberIds = (membersData?.members || []).map((m) => m?.agent_id).filter(Boolean);
5576
+ const memberIdSet = new Set(memberIds);
5577
+ const rawOnlineSet = new Set;
5260
5578
  let online = [];
5261
5579
  if (memberIds.length > 0) {
5262
- const onlineSet = new Set;
5263
5580
  for (let i = 0;i < memberIds.length; i += 50) {
5264
5581
  const batch = memberIds.slice(i, i + 50);
5265
5582
  const pres = await get(`/api/presence?ids=${encodeURIComponent(batch.join(","))}`);
5266
5583
  for (const [k, v] of Object.entries(pres?.presence || {})) {
5267
- if (v === "online")
5268
- onlineSet.add(k);
5584
+ if (v === "online" && memberIdSet.has(k))
5585
+ rawOnlineSet.add(k);
5269
5586
  }
5270
5587
  }
5271
- online = [...onlineSet];
5272
- }
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
+ }));
5273
5607
  const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
5274
5608
  const skills = allDocs.filter(isSkillDoc).map((d) => ({ doc_id: d.id, title: d.title }));
5275
5609
  const docs = allDocs.filter((d) => !isSkillDoc(d)).slice(0, 10).map((d) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
@@ -5285,7 +5619,10 @@ ${results}` }] };
5285
5619
  }));
5286
5620
  return JSON.stringify({
5287
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) } : {},
5288
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 } : {},
5289
5626
  okr_objectives: objectives,
5290
5627
  skills,
5291
5628
  docs,
@@ -5655,15 +5992,38 @@ ${lines}` }] };
5655
5992
  if (name === "list_members") {
5656
5993
  const { chat_id } = args;
5657
5994
  try {
5658
- 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
+ ]);
5659
5999
  if (r.ok) {
5660
6000
  const data = await r.json();
5661
6001
  const members = data.members || [];
5662
6002
  if (members.length === 0)
5663
6003
  return { content: [{ type: "text", text: "No members found." }] };
5664
- 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(`
5665
6025
  `);
5666
- 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}:
5667
6027
  ${list}` }] };
5668
6028
  }
5669
6029
  return { content: [{ type: "text", text: `Failed to list members (${r.status})` }] };
@@ -5679,7 +6039,7 @@ ${list}` }] };
5679
6039
  const time = m.timestamp ? new Date(m.timestamp).toLocaleString() : "?";
5680
6040
  const rawContent = String(m.content ?? "");
5681
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]`;
5682
- let line = `[${time}] ${m.sender_id?.slice(0, 12)}: ${body}`;
6042
+ let line = `[${time}] ${redactParticipantPii(m.sender_id || "?")}: ${body}`;
5683
6043
  const atts = Array.isArray(m.attachments) ? m.attachments : [];
5684
6044
  for (const a of atts) {
5685
6045
  if (!a?.url)
@@ -6118,7 +6478,7 @@ ${list}` }] };
6118
6478
  }
6119
6479
  };
6120
6480
  server.setRequestHandler(CallToolRequestSchema, (request) => serializeCall(() => handleToolCall(request)));
6121
- var mentionTsFile = join6(configDir, `mention-ts-${AGENT_ID}.json`);
6481
+ var mentionTsFile = join7(configDir, `mention-ts-${AGENT_ID}.json`);
6122
6482
  function loadMentionTimestamps() {
6123
6483
  return loadCursor(mentionTsFile, safeStderrWrite);
6124
6484
  }
@@ -6265,6 +6625,7 @@ function clearFinishedHiddenIdentityGamesFromMessage(data) {
6265
6625
  }
6266
6626
  }
6267
6627
  }
6628
+ var processAgentMessageDedup = new MessageDedup;
6268
6629
  function deliverySource(data) {
6269
6630
  return typeof data?.__source === "string" ? data.__source : "live";
6270
6631
  }
@@ -6272,7 +6633,9 @@ function recordOrSkipDeliveredMessage(data, slot = activeSlot) {
6272
6633
  const key = messageDedupKey(data);
6273
6634
  if (!key || !slot)
6274
6635
  return false;
6275
- 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;
6276
6639
  if (skip) {
6277
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)}
6278
6641
  `);
@@ -6361,6 +6724,22 @@ function syncOpenBoundSessions() {
6361
6724
  try {
6362
6725
  const candidate = readIdentityProfile(boundPath);
6363
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
+ }
6364
6743
  const lock = checkAgentLock({
6365
6744
  lockDir,
6366
6745
  agentId: candidate.agent_id,
@@ -6369,7 +6748,6 @@ function syncOpenBoundSessions() {
6369
6748
  });
6370
6749
  if (lock.locked)
6371
6750
  continue;
6372
- const sess = { sessionId: cid, runtime: "antigravity" };
6373
6751
  acquireAgentLock({
6374
6752
  lockDir,
6375
6753
  agentId: candidate.agent_id,
@@ -6524,7 +6902,7 @@ function connectWS(slot = activeSlot) {
6524
6902
  }
6525
6903
  const truncatedMsgs = trimmed.length < msgs.length;
6526
6904
  if (trimmed.length > 0) {
6527
- 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(`
6528
6906
  `);
6529
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]`;
6530
6908
  contextPrefix = `${note}
@@ -6572,7 +6950,7 @@ ${context}
6572
6950
  if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
6573
6951
  (async () => {
6574
6952
  try {
6575
- const { readFileSync: readFileSync8, existsSync: existsSync8 } = await import("fs");
6953
+ const { readFileSync: readFileSync10, existsSync: existsSync8 } = await import("fs");
6576
6954
  const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync8);
6577
6955
  let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
6578
6956
  if (!agentId) {
@@ -6580,7 +6958,7 @@ ${context}
6580
6958
  explicitId: "",
6581
6959
  agentschatName: slot.profile.display_name || slot.agentId,
6582
6960
  listAgents: async () => {
6583
- const gwcfg = JSON.parse(readFileSync8(gwPath, "utf8"));
6961
+ const gwcfg = JSON.parse(readFileSync10(gwPath, "utf8"));
6584
6962
  const token = grokBearerFromGatewayConfig(gwcfg);
6585
6963
  const port = grokPortFromGatewayConfig(gwcfg);
6586
6964
  const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
@@ -6610,7 +6988,8 @@ ${context}
6610
6988
  targetSessionId
6611
6989
  });
6612
6990
  } else if (slotRuntime === "zcode" || process.env.AGENTCHAT_WAKE_MODE === "zcode" || Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")))) {
6613
- 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 : "") || "";
6614
6993
  if (zcodeSid) {
6615
6994
  fireZcodeWake(data, {
6616
6995
  sessionId: zcodeSid,
@@ -6623,7 +7002,8 @@ ${context}
6623
7002
  });
6624
7003
  }
6625
7004
  } else if (slotRuntime === "dsh" || isDshHostProcess() || Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")))) {
6626
- 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;
6627
7007
  const dshWakeUrl = process.env.DSH_WAKE_URL || process.env.AGENTSCHAT_DSH_WAKE_URL || "http://127.0.0.1:8799/wake";
6628
7008
  fireWake(data, {
6629
7009
  url: dshWakeUrl,
@@ -6638,14 +7018,28 @@ ${context}
6638
7018
  const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
6639
7019
  if (!agyHost && !lsAddress)
6640
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);
6641
7022
  const allBinds = loadSessionBinds(configDir);
6642
- 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 : "") || "";
6643
7024
  if (!targetCid && agyHost) {
6644
7025
  if (agyHost.openConversations.length === 1) {
6645
- 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
+ }
6646
7040
  } else if (agyHost.openConversations.length > 1) {
6647
- const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] === slotProfName);
6648
- 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
+ `);
6649
7043
  }
6650
7044
  }
6651
7045
  if (targetCid && csrfToken) {
@@ -6825,6 +7219,13 @@ async function main() {
6825
7219
  installStdioLifecycleGuards();
6826
7220
  if (!toolOnlyMode) {
6827
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
+ }
6828
7229
  }
6829
7230
  if (anonymousMode && profileSlots.size === 0) {
6830
7231
  process.stderr.write(`[agentchat] Anonymous \u2014 not connecting to the hub.