agentschat-mcp 0.36.22 → 0.36.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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) {
@@ -512,6 +538,22 @@ function redactSecrets2(text, opts) {
512
538
  const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
513
539
  return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
514
540
  }
541
+ var PHONE_PII_RE2 = /^\+?\d[\d\s()-]{5,}$/;
542
+ function redactParticipantPii2(rawId) {
543
+ const s = String(rawId ?? "").trim();
544
+ if (!s)
545
+ return "unknown";
546
+ const atIdx = s.indexOf("@");
547
+ if (atIdx >= 0) {
548
+ const local = s.slice(0, atIdx).replace(/[^a-zA-Z0-9]/g, "");
549
+ return `user:${(local.slice(0, 2) || "u").toLowerCase()}***`;
550
+ }
551
+ if (PHONE_PII_RE2.test(s)) {
552
+ const digits = s.replace(/\D/g, "");
553
+ return `user:phone_***${digits.slice(-2) || "00"}`;
554
+ }
555
+ return s;
556
+ }
515
557
 
516
558
  // src/wake.ts
517
559
  var WAKE_SIG_HEADER = "x-agentschat-signature";
@@ -886,13 +928,13 @@ function fireZcodeWake(msg, cfg) {
886
928
 
887
929
  // src/session-bind.ts
888
930
  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";
931
+ import { closeSync, existsSync as existsSync3, mkdirSync, openSync, readFileSync as readFileSync4, readSync, readdirSync as readdirSync2, statSync as statSync2, unlinkSync as unlinkSync2 } from "node:fs";
890
932
  import { homedir, tmpdir } from "node:os";
891
933
  import { join as join3 } from "node:path";
892
934
  import { spawnSync } from "node:child_process";
893
935
 
894
936
  // src/profile-store.ts
895
- import { existsSync as existsSync2, writeFileSync, renameSync, chmodSync, unlinkSync, statSync } from "fs";
937
+ import { existsSync as existsSync2, writeFileSync, renameSync, chmodSync, unlinkSync, statSync, readdirSync, readFileSync as readFileSync3 } from "fs";
896
938
  var defaultWarn = (m) => process.stderr.write(m);
897
939
  function safeWriteProfile(path, data, warn = defaultWarn) {
898
940
  const tmp = path + ".tmp";
@@ -922,6 +964,16 @@ function safeWriteProfile(path, data, warn = defaultWarn) {
922
964
  `);
923
965
  }
924
966
  }
967
+ var NON_PROFILE_JSON_FILES = new Set([
968
+ "session-binds.json",
969
+ "agy-binds.json",
970
+ "grok-binds.json",
971
+ "grok-binds-meta.json",
972
+ "grok-binds.meta.json",
973
+ "identity-guard.json",
974
+ "dsh.json",
975
+ "config.json"
976
+ ]);
925
977
 
926
978
  // src/session-bind.ts
927
979
  var DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
@@ -957,7 +1009,7 @@ function readAgentLock(lockDir, agentId) {
957
1009
  if (!existsSync3(file))
958
1010
  return null;
959
1011
  try {
960
- const raw = JSON.parse(readFileSync3(file, "utf8"));
1012
+ const raw = JSON.parse(readFileSync4(file, "utf8"));
961
1013
  if (!raw || typeof raw !== "object" || typeof raw.pid !== "number" || typeof raw.agentId !== "string") {
962
1014
  return null;
963
1015
  }
@@ -1054,25 +1106,49 @@ function loadSessionBinds(configDir) {
1054
1106
  if (!existsSync3(path))
1055
1107
  continue;
1056
1108
  try {
1057
- Object.assign(merged, parseSessionBinds(JSON.parse(readFileSync3(path, "utf8"))));
1109
+ Object.assign(merged, parseSessionBinds(JSON.parse(readFileSync4(path, "utf8"))));
1058
1110
  } catch {}
1059
1111
  }
1060
1112
  return merged;
1061
1113
  }
1114
+ function resolveAgentIdForProfileName(configDir, name) {
1115
+ if (!name || name.includes("/") || name.includes("\\"))
1116
+ return null;
1117
+ const base = name.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
1118
+ for (const candidate of [join3(configDir, "profiles", `${base}.json`), join3(configDir, `${base}.json`)]) {
1119
+ if (!existsSync3(candidate))
1120
+ continue;
1121
+ try {
1122
+ const parsed = JSON.parse(readFileSync4(candidate, "utf8"));
1123
+ if (typeof parsed?.agent_id === "string" && parsed.agent_id.trim()) {
1124
+ return parsed.agent_id.trim();
1125
+ }
1126
+ } catch {}
1127
+ }
1128
+ return null;
1129
+ }
1062
1130
  function saveSessionBind(configDir, sessionId, profileName) {
1063
1131
  const sid = sessionId.trim();
1064
1132
  const prof = profileName.trim();
1065
1133
  if (!sid || !prof)
1066
1134
  return;
1135
+ const targetAgentId = resolveAgentIdForProfileName(configDir, prof);
1136
+ const isSameProfileOrAgent = (existingProf) => {
1137
+ if (existingProf === prof)
1138
+ return true;
1139
+ if (!targetAgentId)
1140
+ return false;
1141
+ return resolveAgentIdForProfileName(configDir, existingProf) === targetAgentId;
1142
+ };
1067
1143
  const path = join3(configDir, DEFAULT_SESSION_BINDS_FILENAME);
1068
1144
  let current = {};
1069
1145
  if (existsSync3(path)) {
1070
1146
  try {
1071
- current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
1147
+ current = parseSessionBinds(JSON.parse(readFileSync4(path, "utf8")));
1072
1148
  } catch {}
1073
1149
  }
1074
1150
  for (const [existingSid, existingProf] of Object.entries(current)) {
1075
- if (existingProf === prof && existingSid !== sid) {
1151
+ if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
1076
1152
  delete current[existingSid];
1077
1153
  }
1078
1154
  }
@@ -1083,10 +1159,10 @@ function saveSessionBind(configDir, sessionId, profileName) {
1083
1159
  const legacyPath = join3(configDir, LEGACY_AGY_BINDS_FILENAME);
1084
1160
  if (existsSync3(legacyPath)) {
1085
1161
  try {
1086
- const legacy = parseSessionBinds(JSON.parse(readFileSync3(legacyPath, "utf8")));
1162
+ const legacy = parseSessionBinds(JSON.parse(readFileSync4(legacyPath, "utf8")));
1087
1163
  let changed = false;
1088
1164
  for (const [existingSid, existingProf] of Object.entries(legacy)) {
1089
- if (existingProf === prof && existingSid !== sid) {
1165
+ if (existingSid !== sid && isSameProfileOrAgent(existingProf)) {
1090
1166
  delete legacy[existingSid];
1091
1167
  changed = true;
1092
1168
  }
@@ -1106,7 +1182,7 @@ function removeSessionBind(configDir, sessionId) {
1106
1182
  if (!existsSync3(path))
1107
1183
  continue;
1108
1184
  try {
1109
- const current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
1185
+ const current = parseSessionBinds(JSON.parse(readFileSync4(path, "utf8")));
1110
1186
  if (sid in current) {
1111
1187
  delete current[sid];
1112
1188
  safeWriteProfile(path, current);
@@ -1155,7 +1231,9 @@ function detectRuntimeSession(env = process.env, meta) {
1155
1231
  if (explicitSid) {
1156
1232
  return { sessionId: explicitSid, runtime: "custom" };
1157
1233
  }
1158
- if (env === process.env || env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(env.AGY_BROWSER_WS_URL)) {
1234
+ const hasExplicitAgyEnv = env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(env.AGY_BROWSER_WS_URL) || Boolean(env.ANTIGRAVITY_LS_ADDRESS) || Boolean(env.ANTIGRAVITY_CSRF_TOKEN);
1235
+ const isMockHubSubprocess = !hasExplicitAgyEnv && typeof env.AGENTCHAT_REST_URL === "string" && /^http:\/\/127\.0\.0\.1:\d+/.test(env.AGENTCHAT_REST_URL);
1236
+ if (!isMockHubSubprocess && (env === process.env || hasExplicitAgyEnv)) {
1159
1237
  const agyHost = discoverAntigravityHost();
1160
1238
  if (agyHost && agyHost.openConversations.length === 1) {
1161
1239
  return { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
@@ -1164,7 +1242,57 @@ function detectRuntimeSession(env = process.env, meta) {
1164
1242
  return null;
1165
1243
  }
1166
1244
  var cachedAgyHost = null;
1245
+ function parseAntigravityLsofOutput(stdout, appDataDir = "antigravity") {
1246
+ const ports = [];
1247
+ const presenceConversations = [];
1248
+ const dbConversations = [];
1249
+ const cleanAppDir = (appDataDir || "antigravity").trim().replace(/^\/+|\/+$/g, "");
1250
+ const isCliTarget = cleanAppDir === "antigravity-cli";
1251
+ for (const line of (stdout || "").split(/\r?\n/)) {
1252
+ const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
1253
+ if (portMatch) {
1254
+ const p = Number(portMatch[1]);
1255
+ if (p > 0 && !ports.includes(p))
1256
+ ports.push(p);
1257
+ }
1258
+ if (!isCliTarget && line.includes("/antigravity-cli/"))
1259
+ continue;
1260
+ const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/);
1261
+ if (presMatch) {
1262
+ const cid = presMatch[1];
1263
+ if (!presenceConversations.includes(cid))
1264
+ presenceConversations.push(cid);
1265
+ continue;
1266
+ }
1267
+ const dbMatch = line.match(/\/conversations\/([0-9a-fA-F-]{36})\.db$/);
1268
+ if (dbMatch) {
1269
+ if (cleanAppDir && line.includes("/.gemini/") && !line.includes(`/${cleanAppDir}/conversations/`)) {
1270
+ continue;
1271
+ }
1272
+ const cid = dbMatch[1];
1273
+ if (!dbConversations.includes(cid))
1274
+ dbConversations.push(cid);
1275
+ }
1276
+ }
1277
+ ports.sort((a, b) => b - a);
1278
+ const openConversations = presenceConversations.length > 0 ? presenceConversations : dbConversations;
1279
+ return { ports, openConversations };
1280
+ }
1167
1281
  function discoverAntigravityHost(opts) {
1282
+ if (!opts?.currentPid) {
1283
+ const envAddr = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
1284
+ const envCsrf = process.env.ANTIGRAVITY_CSRF_TOKEN?.trim() || "";
1285
+ if (envAddr && envCsrf) {
1286
+ const portMatch = envAddr.match(/:(\d+)$/);
1287
+ const ports = portMatch ? [Number(portMatch[1])] : [];
1288
+ 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));
1289
+ return { lsPid: process.ppid, csrfToken: envCsrf, ports, openConversations };
1290
+ }
1291
+ const hasExplicitAgyEnv = process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL);
1292
+ if (!hasExplicitAgyEnv && typeof process.env.AGENTCHAT_REST_URL === "string" && /^http:\/\/127\.0\.0\.1:\d+/.test(process.env.AGENTCHAT_REST_URL)) {
1293
+ return null;
1294
+ }
1295
+ }
1168
1296
  const now = Date.now();
1169
1297
  const cacheMs = opts?.cacheMs ?? 5000;
1170
1298
  if (cachedAgyHost && now - cachedAgyHost.at < cacheMs)
@@ -1202,26 +1330,10 @@ function discoverAntigravityHost(opts) {
1202
1330
  cachedAgyHost = { at: now, info: null };
1203
1331
  return null;
1204
1332
  }
1333
+ const appDirMatch = lsCmd.match(/--app_data_dir[=\s]+([^\s]+)/);
1334
+ const appDataDir = appDirMatch?.[1]?.trim() || "antigravity";
1205
1335
  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);
1336
+ const { ports, openConversations } = lsof.status === 0 && lsof.stdout ? parseAntigravityLsofOutput(lsof.stdout, appDataDir) : { ports: [], openConversations: [] };
1225
1337
  const info = { lsPid, csrfToken, ports, openConversations };
1226
1338
  cachedAgyHost = { at: now, info };
1227
1339
  return info;
@@ -1243,7 +1355,7 @@ function detectAntigravityCallerSession(opts) {
1243
1355
  candidateSet.add(cid);
1244
1356
  }
1245
1357
  try {
1246
- for (const entry of readdirSync(brainDir)) {
1358
+ for (const entry of readdirSync2(brainDir)) {
1247
1359
  if (uuidRe.test(entry))
1248
1360
  candidateSet.add(entry);
1249
1361
  }
@@ -1380,7 +1492,7 @@ function sessionDirMtime(dir) {
1380
1492
  function sessionLogMtime(dshHome, sid) {
1381
1493
  let projects;
1382
1494
  try {
1383
- projects = readdirSync(join3(dshHome, "sessions"));
1495
+ projects = readdirSync2(join3(dshHome, "sessions"));
1384
1496
  } catch {
1385
1497
  return 0;
1386
1498
  }
@@ -1396,7 +1508,7 @@ function newestSessionLog(dshHome, nowMs, maxAgeMs) {
1396
1508
  const root = join3(dshHome, "sessions");
1397
1509
  let projects;
1398
1510
  try {
1399
- projects = readdirSync(root);
1511
+ projects = readdirSync2(root);
1400
1512
  } catch {
1401
1513
  return null;
1402
1514
  }
@@ -1404,7 +1516,7 @@ function newestSessionLog(dshHome, nowMs, maxAgeMs) {
1404
1516
  for (const project of projects) {
1405
1517
  let entries;
1406
1518
  try {
1407
- entries = readdirSync(join3(root, project));
1519
+ entries = readdirSync2(join3(root, project));
1408
1520
  } catch {
1409
1521
  continue;
1410
1522
  }
@@ -1461,12 +1573,12 @@ async function detectDshCallerSession(opts) {
1461
1573
  }
1462
1574
 
1463
1575
  // src/session-route.ts
1464
- import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
1576
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "node:fs";
1465
1577
  import { homedir as homedir2 } from "node:os";
1466
1578
  import { join as join5 } from "node:path";
1467
1579
 
1468
1580
  // 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";
1581
+ 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
1582
  import { join as join4 } from "node:path";
1471
1583
  var DEFAULT_SESSION_BINDS_FILENAME2 = "session-binds.json";
1472
1584
  var LEGACY_AGY_BINDS_FILENAME2 = "agy-binds.json";
@@ -1493,7 +1605,7 @@ function loadSessionBinds2(configDir) {
1493
1605
  if (!existsSync4(path))
1494
1606
  continue;
1495
1607
  try {
1496
- Object.assign(merged, parseSessionBinds2(JSON.parse(readFileSync4(path, "utf8"))));
1608
+ Object.assign(merged, parseSessionBinds2(JSON.parse(readFileSync5(path, "utf8"))));
1497
1609
  } catch {}
1498
1610
  }
1499
1611
  return merged;
@@ -1515,7 +1627,7 @@ function profilePathForName(configDir, name) {
1515
1627
  }
1516
1628
  function readAgentId(path) {
1517
1629
  try {
1518
- const parsed = JSON.parse(readFileSync5(path, "utf8"));
1630
+ const parsed = JSON.parse(readFileSync6(path, "utf8"));
1519
1631
  return typeof parsed.agent_id === "string" && parsed.agent_id ? parsed.agent_id : undefined;
1520
1632
  } catch {
1521
1633
  return;
@@ -1532,6 +1644,8 @@ function resolveSessionForAgent(agentId, opts = {}) {
1532
1644
  return;
1533
1645
  }
1534
1646
  for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
1647
+ if (opts.filter && !opts.filter(sessionId))
1648
+ continue;
1535
1649
  const path = profilePathForName(configDir, profileName);
1536
1650
  if (path === undefined)
1537
1651
  continue;
@@ -1619,7 +1733,7 @@ class HeartbeatMonitor {
1619
1733
  var package_default = {
1620
1734
  name: "agentschat-mcp",
1621
1735
  mcpName: "io.github.swswordholy-tech/agentschat-mcp",
1622
- version: "0.36.22",
1736
+ version: "0.36.24",
1623
1737
  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
1738
  type: "module",
1625
1739
  bin: {
@@ -1635,14 +1749,14 @@ var package_default = {
1635
1749
  scripts: {
1636
1750
  start: "bun src/server.ts",
1637
1751
  dev: "bun --watch src/server.ts",
1638
- test: "bun test",
1752
+ test: "bun test tests dsh/tests && node --experimental-strip-types --test muse/tests/*.test.mjs",
1639
1753
  typecheck: "tsc --noEmit",
1640
1754
  build: "bun scripts/build.mjs",
1641
1755
  "check:version": "bun scripts/check-version-sync.mjs",
1642
1756
  "check:docs": "bun scripts/sync-doc-versions.mjs --check",
1643
1757
  "sync:docs": "bun scripts/sync-doc-versions.mjs --write",
1644
1758
  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",
1759
+ verify: "bun run build && bun scripts/check-version-sync.mjs && bun scripts/sync-doc-versions.mjs --check && tsc --noEmit && bun run test",
1646
1760
  prepublishOnly: "bun run check:version && bun run check:docs && bun test tests/doc-versions.test.ts tests/packaging.test.ts"
1647
1761
  },
1648
1762
  keywords: [
@@ -1726,6 +1840,7 @@ var package_default = {
1726
1840
  "src/wake.ts",
1727
1841
  "src/profile-store.ts",
1728
1842
  "src/read-cursor.ts",
1843
+ "src/rest-cli.ts",
1729
1844
  "connector/auth.ts",
1730
1845
  "connector/descriptor.ts",
1731
1846
  "connector/normalize.ts",
@@ -1765,12 +1880,13 @@ import {
1765
1880
  CallToolRequestSchema,
1766
1881
  ListToolsRequestSchema
1767
1882
  } 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";
1883
+ import { readFileSync as readFileSync11, existsSync as existsSync8, writeFileSync as writeFileSync6, mkdirSync as mkdirSync4, readdirSync as readdirSync5 } from "fs";
1884
+ import { join as join8, dirname as dirname2 } from "path";
1770
1885
  import { fileURLToPath } from "url";
1771
1886
 
1772
1887
  // 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";
1888
+ 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";
1889
+ import { join as join6, resolve as resolve2 } from "path";
1774
1890
  var defaultWarn2 = (m) => process.stderr.write(m);
1775
1891
  function safeWriteProfile2(path, data, warn = defaultWarn2) {
1776
1892
  const tmp = path + ".tmp";
@@ -1800,6 +1916,73 @@ function safeWriteProfile2(path, data, warn = defaultWarn2) {
1800
1916
  `);
1801
1917
  }
1802
1918
  }
1919
+ var NON_PROFILE_JSON_FILES2 = new Set([
1920
+ "session-binds.json",
1921
+ "agy-binds.json",
1922
+ "grok-binds.json",
1923
+ "grok-binds-meta.json",
1924
+ "grok-binds.meta.json",
1925
+ "identity-guard.json",
1926
+ "dsh.json",
1927
+ "config.json"
1928
+ ]);
1929
+ function findDefaultProfileCollision(configDir, defaultProfilePath) {
1930
+ if (!defaultProfilePath || !existsSync6(defaultProfilePath))
1931
+ return null;
1932
+ let defParsed;
1933
+ try {
1934
+ defParsed = JSON.parse(readFileSync7(defaultProfilePath, "utf8"));
1935
+ } catch {
1936
+ return null;
1937
+ }
1938
+ if (!defParsed || typeof defParsed !== "object" || Array.isArray(defParsed))
1939
+ return null;
1940
+ const defAgentId = typeof defParsed.agent_id === "string" ? defParsed.agent_id.trim() : "";
1941
+ const defDisplayName = typeof defParsed.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
1942
+ if (!defAgentId && !defDisplayName)
1943
+ return null;
1944
+ const resolvedDefault = resolve2(defaultProfilePath);
1945
+ for (const dir of [join6(configDir, "profiles"), configDir]) {
1946
+ if (!existsSync6(dir))
1947
+ continue;
1948
+ let files = [];
1949
+ try {
1950
+ files = readdirSync4(dir).filter((f) => f.endsWith(".json"));
1951
+ } catch {
1952
+ continue;
1953
+ }
1954
+ for (const file of files) {
1955
+ if (NON_PROFILE_JSON_FILES2.has(file))
1956
+ continue;
1957
+ const candidatePath = join6(dir, file);
1958
+ if (resolve2(candidatePath) === resolvedDefault)
1959
+ continue;
1960
+ const baseName = file.replace(/\.json$/, "");
1961
+ if (baseName.toLowerCase() === "profile")
1962
+ continue;
1963
+ let candidate;
1964
+ try {
1965
+ candidate = JSON.parse(readFileSync7(candidatePath, "utf8"));
1966
+ } catch {
1967
+ continue;
1968
+ }
1969
+ if (!candidate || typeof candidate !== "object" || Array.isArray(candidate))
1970
+ continue;
1971
+ const candAgentId = typeof candidate.agent_id === "string" ? candidate.agent_id.trim() : "";
1972
+ const candToken = typeof candidate.token === "string" ? candidate.token.trim() : "";
1973
+ if (!candAgentId || !candToken)
1974
+ continue;
1975
+ if (defAgentId && candAgentId === defAgentId) {
1976
+ return { collidingName: baseName, collidingPath: candidatePath, reason: "agent_id" };
1977
+ }
1978
+ const candDisplayName = typeof candidate.display_name === "string" ? candidate.display_name.trim().toLowerCase() : "";
1979
+ if (defDisplayName && (candDisplayName === defDisplayName || baseName.toLowerCase() === defDisplayName)) {
1980
+ return { collidingName: baseName, collidingPath: candidatePath, reason: "display_name" };
1981
+ }
1982
+ }
1983
+ }
1984
+ return null;
1985
+ }
1803
1986
 
1804
1987
  // src/identity-guard.ts
1805
1988
  var IDENTITY_GUARD_FILENAME = "identity-guard.json";
@@ -1883,10 +2066,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
1883
2066
  }
1884
2067
 
1885
2068
  // src/read-cursor.ts
1886
- import { readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
2069
+ import { readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
1887
2070
  function loadCursor(file, warn) {
1888
2071
  try {
1889
- return new Map(Object.entries(JSON.parse(readFileSync6(file, "utf-8"))));
2072
+ return new Map(Object.entries(JSON.parse(readFileSync8(file, "utf-8"))));
1890
2073
  } catch (e) {
1891
2074
  if (e?.code !== "ENOENT") {
1892
2075
  warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
@@ -1914,6 +2097,728 @@ function flushCursor(state, persist) {
1914
2097
  return ok;
1915
2098
  }
1916
2099
 
2100
+ // src/rest-cli.ts
2101
+ import { existsSync as existsSync7, mkdirSync as mkdirSync3, readFileSync as readFileSync10, writeFileSync as writeFileSync5 } from "node:fs";
2102
+ import { dirname, join as join7 } from "node:path";
2103
+
2104
+ // src/mentions.ts
2105
+ function matchesMention2(content, agentId) {
2106
+ if (!content || !agentId)
2107
+ return false;
2108
+ if (content.includes(`@${agentId}`))
2109
+ return true;
2110
+ const idEsc = agentId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2111
+ const displayMentionRe = new RegExp(`@[^(\\n]+\\(${idEsc}\\)`);
2112
+ return displayMentionRe.test(content);
2113
+ }
2114
+
2115
+ // src/read-cursor.ts
2116
+ import { readFileSync as readFileSync9, writeFileSync as writeFileSync4 } from "fs";
2117
+ function loadCursor2(file, warn) {
2118
+ try {
2119
+ return new Map(Object.entries(JSON.parse(readFileSync9(file, "utf-8"))));
2120
+ } catch (e) {
2121
+ if (e?.code !== "ENOENT") {
2122
+ warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
2123
+ `);
2124
+ }
2125
+ return new Map;
2126
+ }
2127
+ }
2128
+ function persistCursor2(file, cursor, warn) {
2129
+ try {
2130
+ writeFileSync4(file, JSON.stringify(Object.fromEntries(cursor)));
2131
+ return true;
2132
+ } catch (e) {
2133
+ warn(`[agentchat] WARNING: failed to persist read cursor to ${file}: ${e}
2134
+ `);
2135
+ return false;
2136
+ }
2137
+ }
2138
+
2139
+ // src/timestamps.ts
2140
+ function normalizeTimestampForCursor2(ts, mode) {
2141
+ if (!ts || typeof ts !== "string")
2142
+ return ts;
2143
+ const padChar = mode === "before" ? "9" : "0";
2144
+ const withFrac = ts.match(/^(.*\.)(\d+)(Z)$/);
2145
+ if (withFrac) {
2146
+ const frac = withFrac[2];
2147
+ if (frac.length >= 9)
2148
+ return ts;
2149
+ return withFrac[1] + frac + padChar.repeat(9 - frac.length) + withFrac[3];
2150
+ }
2151
+ const noFrac = ts.match(/^(.*\d)(Z)$/);
2152
+ if (noFrac) {
2153
+ return noFrac[1] + "." + padChar.repeat(9) + noFrac[2];
2154
+ }
2155
+ return ts;
2156
+ }
2157
+
2158
+ // src/wake.ts
2159
+ var NATIVE_WAKE_CONTENT_MAX2 = 4000;
2160
+ function formatWakeAttachments2(attachments) {
2161
+ if (!Array.isArray(attachments) || attachments.length === 0)
2162
+ return "";
2163
+ const lines = [];
2164
+ for (const raw of attachments) {
2165
+ if (!raw || typeof raw !== "object")
2166
+ continue;
2167
+ const a = raw;
2168
+ if (typeof a.url !== "string" || !a.url)
2169
+ continue;
2170
+ const t = typeof a.type === "string" ? a.type : "file";
2171
+ const dim = typeof a.width === "number" && typeof a.height === "number" ? ` ${a.width}×${a.height}` : "";
2172
+ const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
2173
+ const icon = t === "image" ? "\uD83D\uDDBC" : t === "video" ? "\uD83C\uDFAC" : t === "audio" ? "\uD83D\uDD0A" : "\uD83D\uDCCE";
2174
+ let desc = `${icon} ${t}${dim}${dur}: ${a.url}`;
2175
+ if (typeof a.transcript === "string" && a.transcript.trim()) {
2176
+ desc += ` (transcript: "${redactSecrets2(a.transcript.trim().slice(0, 300))}")`;
2177
+ }
2178
+ lines.push(desc);
2179
+ }
2180
+ return lines.length > 0 ? ` [附件: ${lines.join("; ")}]` : "";
2181
+ }
2182
+ var GROK_GATEWAY_PATH_CANDIDATES2 = [
2183
+ `${process.env.HOME}/.grok/gateway.json`,
2184
+ "/home/box/sand-data/gateway.json"
2185
+ ];
2186
+ function buildWakePrompt2(msg, contextPrefix = "") {
2187
+ const rawContent = typeof msg.content === "string" ? msg.content : "";
2188
+ const isTruncated = rawContent.length > NATIVE_WAKE_CONTENT_MAX2;
2189
+ const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
2190
+ const content = rawContent ? redactSecrets2(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX2), redactOpts) : "";
2191
+ const cleanPrefix = contextPrefix ? redactSecrets2(contextPrefix.trim(), redactOpts) : "";
2192
+ const channel = msg.channel_id ?? "?";
2193
+ const sender = msg.sender_id ?? "someone";
2194
+ const msgId = msg.id ?? msg.message_id ?? "";
2195
+ const isDm = channel.startsWith("dm-");
2196
+ const where = isDm ? `私聊 (${channel})` : `频道 ${channel}`;
2197
+ const actionHint = isTruncated ? ` —— 消息过长已截断,可调用 get_history(chat_id, message_id) 查看全文,再用 reply 回复并 mark_read 标记已读` : ` —— 请直接用 reply 回复并用 mark_read 标记已读;仅在需要更早上下文时调用 get_history`;
2198
+ const attSummary = formatWakeAttachments2(msg.attachments);
2199
+ return (cleanPrefix ? `${cleanPrefix}
2200
+
2201
+ ` : "") + `[AgentsChat] ${sender} 在${where}给你发了消息` + (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") + attSummary + ` (channel_id=${channel}` + (msgId ? `, message_id=${msgId}` : "") + `${actionHint})`;
2202
+ }
2203
+ var zcodeSessionQueues2 = new Map;
2204
+
2205
+ // src/rest-cli.ts
2206
+ var CURSOR_INIT_KEY = "__init_ts__";
2207
+ var CURSOR_LAST_ACTIVE_KEY = "__last_active_ts__";
2208
+ var CURSOR_MAX_IDLE_KEY = "__max_idle_ms__";
2209
+ var DEFAULT_MAX_IDLE_MS = 60 * 60 * 1000;
2210
+ function parseMaxIdleMs(raw) {
2211
+ if (raw === undefined || raw === null)
2212
+ return;
2213
+ if (typeof raw === "number") {
2214
+ return Number.isFinite(raw) && raw >= 0 ? Math.round(raw * 1000) : undefined;
2215
+ }
2216
+ const s = String(raw).trim().toLowerCase();
2217
+ if (!s)
2218
+ return;
2219
+ if (s === "0" || s === "never" || s === "infinite" || s === "forever" || s === "off") {
2220
+ return 0;
2221
+ }
2222
+ const m = s.match(/^(\d+(?:\.\d+)?)\s*(ms|s|sec|secs|m|min|mins|h|hr|hrs|hour|hours|d|day|days)?$/);
2223
+ if (!m)
2224
+ return;
2225
+ const val = Number(m[1]);
2226
+ if (!Number.isFinite(val) || val < 0)
2227
+ return;
2228
+ const unit = m[2] || "s";
2229
+ if (unit === "ms")
2230
+ return Math.round(val);
2231
+ if (unit === "s" || unit === "sec" || unit === "secs")
2232
+ return Math.round(val * 1000);
2233
+ if (unit === "m" || unit === "min" || unit === "mins")
2234
+ return Math.round(val * 60000);
2235
+ if (unit === "h" || unit === "hr" || unit === "hrs" || unit === "hour" || unit === "hours") {
2236
+ return Math.round(val * 3600000);
2237
+ }
2238
+ if (unit === "d" || unit === "day" || unit === "days")
2239
+ return Math.round(val * 86400000);
2240
+ return;
2241
+ }
2242
+ var MAX_SSE_STREAMS = 3;
2243
+ var MAX_SEEN_IDS = 200;
2244
+ function loadSeenIds(file) {
2245
+ if (!existsSync7(file))
2246
+ return [];
2247
+ try {
2248
+ const parsed = JSON.parse(readFileSync10(file, "utf8"));
2249
+ return Array.isArray(parsed) ? parsed.filter((x) => typeof x === "string") : [];
2250
+ } catch {
2251
+ return [];
2252
+ }
2253
+ }
2254
+ function saveSeenIds(file, ids) {
2255
+ try {
2256
+ mkdirSync3(dirname(file), { recursive: true });
2257
+ const list = [...ids].slice(-MAX_SEEN_IDS);
2258
+ safeWriteProfile(file, list);
2259
+ } catch {}
2260
+ }
2261
+ function loadJsonMap(file) {
2262
+ if (!existsSync7(file))
2263
+ return {};
2264
+ try {
2265
+ const raw = JSON.parse(readFileSync10(file, "utf8"));
2266
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
2267
+ return {};
2268
+ return raw;
2269
+ } catch {
2270
+ return {};
2271
+ }
2272
+ }
2273
+ function saveJsonMap(file, data) {
2274
+ try {
2275
+ mkdirSync3(dirname(file), { recursive: true });
2276
+ safeWriteProfile(file, data);
2277
+ } catch {}
2278
+ }
2279
+ function advanceChannelReadCursor(opts) {
2280
+ const { configDir, agentId, channelId, timestamp } = opts;
2281
+ if (!agentId || !channelId || !timestamp)
2282
+ return;
2283
+ const warn = opts.warn ?? ((m) => process.stderr.write(m));
2284
+ mkdirSync3(configDir, { recursive: true });
2285
+ const lastSeenFile = join7(configDir, `last-seen-msg-ts-${agentId}.json`);
2286
+ const cursor = loadCursor2(lastSeenFile, warn);
2287
+ const prev = cursor.get(channelId) || "";
2288
+ const nextNorm = normalizeTimestampForCursor2(timestamp, "after") || timestamp;
2289
+ const prevNorm = normalizeTimestampForCursor2(prev, "after") || prev;
2290
+ cursor.set(CURSOR_LAST_ACTIVE_KEY, timestamp);
2291
+ if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
2292
+ cursor.set(CURSOR_MAX_IDLE_KEY, String(Math.round(opts.maxIdleMs)));
2293
+ }
2294
+ if (!prev || nextNorm > prevNorm) {
2295
+ cursor.set(channelId, timestamp);
2296
+ }
2297
+ persistCursor2(lastSeenFile, cursor, warn);
2298
+ const readCursorsFile = join7(configDir, "read-cursors.json");
2299
+ const readCursors = loadJsonMap(readCursorsFile);
2300
+ const scopedKey = `${agentId}:${channelId}`;
2301
+ const prevRead = readCursors[scopedKey] || readCursors[channelId] || "";
2302
+ const prevReadNorm = normalizeTimestampForCursor2(prevRead, "after") || prevRead;
2303
+ if (!prevRead || nextNorm > prevReadNorm) {
2304
+ readCursors[scopedKey] = timestamp;
2305
+ readCursors[channelId] = timestamp;
2306
+ saveJsonMap(readCursorsFile, readCursors);
2307
+ }
2308
+ }
2309
+ async function joinChannelRest(opts) {
2310
+ const f = opts.fetchImpl ?? fetch;
2311
+ const baseUrl = opts.restUrl.replace(/\/$/, "");
2312
+ const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/join`;
2313
+ try {
2314
+ const res = await f(url, {
2315
+ method: "POST",
2316
+ headers: {
2317
+ Authorization: `Bearer ${opts.token}`,
2318
+ "Content-Type": "application/json"
2319
+ },
2320
+ body: JSON.stringify({ sender_id: opts.agentId })
2321
+ });
2322
+ const data = await res.json().catch(() => ({}));
2323
+ if (res.ok) {
2324
+ return {
2325
+ ok: true,
2326
+ status: res.status,
2327
+ agent_id: opts.agentId,
2328
+ channel_id: String(data.channel_id ?? opts.channelId),
2329
+ ...typeof data.name === "string" ? { name: data.name } : {}
2330
+ };
2331
+ }
2332
+ return {
2333
+ ok: false,
2334
+ status: res.status,
2335
+ agent_id: opts.agentId,
2336
+ channel_id: opts.channelId,
2337
+ error: String(data.error ?? data.message ?? `HTTP ${res.status}`)
2338
+ };
2339
+ } catch (e) {
2340
+ return {
2341
+ ok: false,
2342
+ status: 0,
2343
+ agent_id: opts.agentId,
2344
+ channel_id: opts.channelId,
2345
+ error: String(e?.message || e)
2346
+ };
2347
+ }
2348
+ }
2349
+ async function sendRestMessage(opts) {
2350
+ const f = opts.fetchImpl ?? fetch;
2351
+ const baseUrl = opts.restUrl.replace(/\/$/, "");
2352
+ const cleanText = redactSecrets2(opts.text);
2353
+ const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/messages`;
2354
+ try {
2355
+ const res = await f(url, {
2356
+ method: "POST",
2357
+ headers: {
2358
+ Authorization: `Bearer ${opts.token}`,
2359
+ "Content-Type": "application/json"
2360
+ },
2361
+ body: JSON.stringify({
2362
+ sender_id: opts.agentId,
2363
+ sender_type: "agent",
2364
+ content_type: "text",
2365
+ content: cleanText,
2366
+ ...opts.replyTo ? { in_reply_to: opts.replyTo } : {}
2367
+ })
2368
+ });
2369
+ const data = await res.json().catch(() => ({}));
2370
+ if (res.ok) {
2371
+ advanceChannelReadCursor({
2372
+ configDir: opts.configDir,
2373
+ agentId: opts.agentId,
2374
+ channelId: opts.channelId,
2375
+ timestamp: new Date().toISOString(),
2376
+ maxIdleMs: opts.maxIdleMs,
2377
+ warn: opts.warn
2378
+ });
2379
+ return {
2380
+ ok: true,
2381
+ status: res.status,
2382
+ id: typeof data.id === "string" ? data.id : undefined,
2383
+ agent_id: opts.agentId,
2384
+ channel_id: opts.channelId,
2385
+ ...opts.replyTo ? { in_reply_to: opts.replyTo } : {}
2386
+ };
2387
+ }
2388
+ return {
2389
+ ok: false,
2390
+ status: res.status,
2391
+ agent_id: opts.agentId,
2392
+ channel_id: opts.channelId,
2393
+ error: String(data.error ?? data.message ?? `HTTP ${res.status}`)
2394
+ };
2395
+ } catch (e) {
2396
+ return {
2397
+ ok: false,
2398
+ status: 0,
2399
+ agent_id: opts.agentId,
2400
+ channel_id: opts.channelId,
2401
+ error: String(e?.message || e)
2402
+ };
2403
+ }
2404
+ }
2405
+ function isMessageAddressedToAgent(msg, agentId, displayName) {
2406
+ if (!msg || typeof msg !== "object")
2407
+ return false;
2408
+ if (msg.content === "__typing__")
2409
+ return false;
2410
+ const metaKind = msg.meta && typeof msg.meta === "object" ? msg.meta.kind : undefined;
2411
+ if (metaKind === "slash_input" || metaKind === "loop_status" || metaKind === "slash_response") {
2412
+ return false;
2413
+ }
2414
+ const isOwnLoopTick = metaKind === "loop_tick" && msg.sender_id === agentId;
2415
+ if (msg.sender_id === agentId && !isOwnLoopTick)
2416
+ return false;
2417
+ if (isOwnLoopTick)
2418
+ return true;
2419
+ const channelId = String(msg.channel_id || "");
2420
+ if (channelId.startsWith("dm-"))
2421
+ return true;
2422
+ if (Array.isArray(msg.mentioned_ids) && msg.mentioned_ids.includes(agentId))
2423
+ return true;
2424
+ const content = String(msg.content || "");
2425
+ if (matchesMention2(content, agentId))
2426
+ return true;
2427
+ if (displayName && displayName !== agentId && matchesMention2(content, displayName))
2428
+ return true;
2429
+ return false;
2430
+ }
2431
+ async function wakeOnce(opts) {
2432
+ const f = opts.fetchImpl ?? fetch;
2433
+ const warn = opts.warn ?? ((m) => process.stderr.write(m));
2434
+ const nowIso = opts.nowIso ?? (() => new Date().toISOString());
2435
+ const baseUrl = opts.restUrl.replace(/\/$/, "");
2436
+ const { configDir, agentId, displayName, token } = opts;
2437
+ const timeoutMs = opts.timeoutMs ?? 240000;
2438
+ const pollIntervalMs = opts.pollIntervalMs ?? 15000;
2439
+ const enableSse = opts.enableSse ?? true;
2440
+ mkdirSync3(configDir, { recursive: true });
2441
+ const lastSeenFile = join7(configDir, `last-seen-msg-ts-${agentId}.json`);
2442
+ const seenIdsFile = join7(configDir, `wake-seen-ids-${agentId}.json`);
2443
+ const mentionTsFile = join7(configDir, "mention-timestamps.json");
2444
+ const wakePidFile = join7(configDir, `wake-once-${agentId}.pid`);
2445
+ if (!opts.fetchImpl) {
2446
+ try {
2447
+ if (existsSync7(wakePidFile)) {
2448
+ const oldPid = parseInt(readFileSync10(wakePidFile, "utf-8").trim(), 10);
2449
+ if (Number.isFinite(oldPid) && oldPid > 1 && oldPid !== process.pid) {
2450
+ try {
2451
+ process.kill(oldPid, "SIGTERM");
2452
+ } catch {}
2453
+ }
2454
+ }
2455
+ writeFileSync5(wakePidFile, `${process.pid}
2456
+ `, { mode: 384 });
2457
+ } catch {}
2458
+ }
2459
+ const cursor = loadCursor2(lastSeenFile, warn);
2460
+ let cursorDirty = false;
2461
+ if (!cursor.get(CURSOR_INIT_KEY)) {
2462
+ cursor.set(CURSOR_INIT_KEY, nowIso());
2463
+ cursorDirty = true;
2464
+ }
2465
+ if (!cursor.get(CURSOR_LAST_ACTIVE_KEY)) {
2466
+ cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
2467
+ cursorDirty = true;
2468
+ }
2469
+ if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
2470
+ const nextMaxIdleStr = String(Math.round(opts.maxIdleMs));
2471
+ if (cursor.get(CURSOR_MAX_IDLE_KEY) !== nextMaxIdleStr) {
2472
+ cursor.set(CURSOR_MAX_IDLE_KEY, nextMaxIdleStr);
2473
+ cursorDirty = true;
2474
+ }
2475
+ }
2476
+ if (cursorDirty) {
2477
+ persistCursor2(lastSeenFile, cursor, warn);
2478
+ }
2479
+ const savedMaxIdleRaw = cursor.get(CURSOR_MAX_IDLE_KEY);
2480
+ const savedMaxIdleMs = savedMaxIdleRaw !== undefined ? Number(savedMaxIdleRaw) : undefined;
2481
+ const maxIdleMs = opts.maxIdleMs !== undefined ? opts.maxIdleMs : savedMaxIdleMs !== undefined && Number.isFinite(savedMaxIdleMs) && savedMaxIdleMs >= 0 ? savedMaxIdleMs : DEFAULT_MAX_IDLE_MS;
2482
+ const initTs = cursor.get(CURSOR_INIT_KEY);
2483
+ const initTsNorm = normalizeTimestampForCursor2(initTs, "after") || initTs;
2484
+ const seenSet = new Set(loadSeenIds(seenIdsFile));
2485
+ const headers = {
2486
+ Authorization: `Bearer ${token}`,
2487
+ "Content-Type": "application/json"
2488
+ };
2489
+ for (const ch of opts.channels ?? []) {
2490
+ if (ch && ch.trim()) {
2491
+ await joinChannelRest({
2492
+ restUrl: baseUrl,
2493
+ agentId,
2494
+ token,
2495
+ channelId: ch.trim(),
2496
+ fetchImpl: f
2497
+ });
2498
+ }
2499
+ }
2500
+ let resolved = false;
2501
+ const abortCtrl = new AbortController;
2502
+ async function buildGroupContextPrefix(channelId, triggerMsgId, triggerTs) {
2503
+ if (channelId.startsWith("dm-"))
2504
+ return "";
2505
+ const mentionMap = loadJsonMap(mentionTsFile);
2506
+ const mentionKey = `${agentId}:${channelId}`;
2507
+ const lastTs = mentionMap[mentionKey] || mentionMap[channelId] || "";
2508
+ const params = `limit=50${lastTs ? "&after=" + encodeURIComponent(lastTs) : ""}`;
2509
+ let prefix = "";
2510
+ try {
2511
+ const res = await f(`${baseUrl}/api/channels/${encodeURIComponent(channelId)}/messages?${params}`, {
2512
+ headers,
2513
+ signal: abortCtrl.signal
2514
+ });
2515
+ if (res.ok) {
2516
+ const data = await res.json();
2517
+ const msgs = (data.messages || []).filter((m) => m && m.id !== triggerMsgId && m.content !== "__typing__");
2518
+ const trimmed = msgs.slice(-20);
2519
+ if (trimmed.length > 0) {
2520
+ const context = trimmed.map((m) => `${redactParticipantPii2(m.sender_id || "?")}: ${String(m.content || "").slice(0, 500)}${formatWakeAttachments2(m.attachments)}`).join(`
2521
+ `);
2522
+ prefix = `[频道上下文 - 最近 ${trimmed.length} 条消息]
2523
+ ${context}
2524
+
2525
+ [你被 @mention 了,请回复]
2526
+ `;
2527
+ }
2528
+ }
2529
+ } catch {}
2530
+ if (triggerTs) {
2531
+ mentionMap[mentionKey] = triggerTs;
2532
+ mentionMap[channelId] = triggerTs;
2533
+ saveJsonMap(mentionTsFile, mentionMap);
2534
+ }
2535
+ return prefix;
2536
+ }
2537
+ async function finalizeWake(channelId, batch) {
2538
+ const lastMsg = batch[batch.length - 1];
2539
+ for (const m of batch) {
2540
+ if (typeof m.id === "string")
2541
+ seenSet.add(m.id);
2542
+ }
2543
+ saveSeenIds(seenIdsFile, seenSet);
2544
+ if (typeof lastMsg.timestamp === "string" && lastMsg.timestamp) {
2545
+ cursor.set(channelId, lastMsg.timestamp);
2546
+ cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
2547
+ persistCursor2(lastSeenFile, cursor, warn);
2548
+ advanceChannelReadCursor({
2549
+ configDir,
2550
+ agentId,
2551
+ channelId,
2552
+ timestamp: lastMsg.timestamp,
2553
+ warn
2554
+ });
2555
+ }
2556
+ const contextPrefix = await buildGroupContextPrefix(channelId, String(lastMsg.id || ""), String(lastMsg.timestamp || ""));
2557
+ const combinedContent = batch.length === 1 ? String(lastMsg.content || "") : batch.map((m) => String(m.content || "")).join(`
2558
+ `);
2559
+ const prompt = buildWakePrompt2({
2560
+ ...lastMsg,
2561
+ channel_id: channelId,
2562
+ content: combinedContent
2563
+ }, contextPrefix);
2564
+ return {
2565
+ event: "agentschat_wake",
2566
+ agent_id: agentId,
2567
+ channel_id: channelId,
2568
+ message_id: String(lastMsg.id || ""),
2569
+ sender_id: String(lastMsg.sender_id || ""),
2570
+ content: combinedContent,
2571
+ timestamp: String(lastMsg.timestamp || ""),
2572
+ ...batch.length > 1 ? {
2573
+ messages: batch.map((m) => ({
2574
+ id: String(m.id || ""),
2575
+ sender_id: String(m.sender_id || ""),
2576
+ content: String(m.content || ""),
2577
+ timestamp: String(m.timestamp || "")
2578
+ }))
2579
+ } : {},
2580
+ ...contextPrefix ? { context_prefix: contextPrefix } : {},
2581
+ prompt
2582
+ };
2583
+ }
2584
+ async function inspectChannelMessages(channelId, rawMessages) {
2585
+ const list = Array.isArray(rawMessages) ? rawMessages.filter((m) => m && typeof m === "object" && m.content !== "__typing__") : [];
2586
+ list.sort((a, b) => {
2587
+ const ta = normalizeTimestampForCursor2(a.timestamp, "after") || String(a.timestamp || "");
2588
+ const tb = normalizeTimestampForCursor2(b.timestamp, "after") || String(b.timestamp || "");
2589
+ return ta.localeCompare(tb);
2590
+ });
2591
+ const existingAfter = cursor.get(channelId);
2592
+ if (!existingAfter) {
2593
+ const liveBatch = [];
2594
+ let newestPreExisting = "";
2595
+ for (const m of list) {
2596
+ const msgId = String(m.id || "");
2597
+ if (msgId && seenSet.has(msgId))
2598
+ continue;
2599
+ const msgTs = String(m.timestamp || "");
2600
+ const msgTsNorm = normalizeTimestampForCursor2(msgTs, "after") || msgTs;
2601
+ if (msgTsNorm && msgTsNorm < initTsNorm) {
2602
+ if (msgId)
2603
+ seenSet.add(msgId);
2604
+ if (msgTs > newestPreExisting)
2605
+ newestPreExisting = msgTs;
2606
+ continue;
2607
+ }
2608
+ if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
2609
+ liveBatch.push({ ...m, channel_id: channelId });
2610
+ } else if (msgTs > newestPreExisting) {
2611
+ newestPreExisting = msgTs;
2612
+ }
2613
+ }
2614
+ if (liveBatch.length > 0) {
2615
+ return await finalizeWake(channelId, liveBatch);
2616
+ }
2617
+ const seedTs = newestPreExisting || initTs;
2618
+ cursor.set(channelId, seedTs);
2619
+ persistCursor2(lastSeenFile, cursor, warn);
2620
+ saveSeenIds(seenIdsFile, seenSet);
2621
+ return null;
2622
+ }
2623
+ const afterNorm = normalizeTimestampForCursor2(existingAfter, "after") || existingAfter;
2624
+ const addressedBatch = [];
2625
+ let latestUnaddressedTs = "";
2626
+ for (const m of list) {
2627
+ const msgId = String(m.id || "");
2628
+ if (msgId && seenSet.has(msgId))
2629
+ continue;
2630
+ const msgTs = String(m.timestamp || "");
2631
+ const msgTsNorm = normalizeTimestampForCursor2(msgTs, "after") || msgTs;
2632
+ if (msgTsNorm && msgTsNorm <= afterNorm)
2633
+ continue;
2634
+ if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
2635
+ addressedBatch.push({ ...m, channel_id: channelId });
2636
+ } else if (addressedBatch.length === 0 && msgTs) {
2637
+ latestUnaddressedTs = msgTs;
2638
+ }
2639
+ }
2640
+ if (addressedBatch.length > 0) {
2641
+ return await finalizeWake(channelId, addressedBatch);
2642
+ }
2643
+ if (latestUnaddressedTs) {
2644
+ cursor.set(channelId, latestUnaddressedTs);
2645
+ persistCursor2(lastSeenFile, cursor, warn);
2646
+ }
2647
+ return null;
2648
+ }
2649
+ const activeSseChannels = new Set;
2650
+ const sseConnectedChannels = new Set;
2651
+ const initialSyncedChannels = new Set;
2652
+ return await new Promise((resolvePromise) => {
2653
+ let pollTimer = null;
2654
+ let timeoutTimer = null;
2655
+ const finish = (ev) => {
2656
+ if (resolved)
2657
+ return;
2658
+ resolved = true;
2659
+ if (pollTimer)
2660
+ clearInterval(pollTimer);
2661
+ if (timeoutTimer)
2662
+ clearTimeout(timeoutTimer);
2663
+ try {
2664
+ abortCtrl.abort();
2665
+ } catch {}
2666
+ resolvePromise(ev);
2667
+ };
2668
+ function maybeStartSse(channelId) {
2669
+ if (!enableSse || resolved)
2670
+ return;
2671
+ if (activeSseChannels.has(channelId) || activeSseChannels.size >= MAX_SSE_STREAMS)
2672
+ return;
2673
+ activeSseChannels.add(channelId);
2674
+ (async () => {
2675
+ while (!resolved) {
2676
+ try {
2677
+ const res = await f(`${baseUrl}/api/channels/${encodeURIComponent(channelId)}/stream`, {
2678
+ headers: { Authorization: `Bearer ${token}` },
2679
+ signal: abortCtrl.signal
2680
+ });
2681
+ if (!res.ok || !res.body)
2682
+ break;
2683
+ sseConnectedChannels.add(channelId);
2684
+ const reader = res.body.getReader();
2685
+ const decoder = new TextDecoder;
2686
+ let buf = "";
2687
+ while (!resolved) {
2688
+ const { value, done } = await reader.read();
2689
+ if (done)
2690
+ break;
2691
+ buf += decoder.decode(value, { stream: true });
2692
+ const lines = buf.split(/\r?\n/);
2693
+ buf = lines.pop() || "";
2694
+ for (const line of lines) {
2695
+ if (!line.startsWith("data:"))
2696
+ continue;
2697
+ const raw = line.slice(5).trim();
2698
+ if (!raw)
2699
+ continue;
2700
+ try {
2701
+ const parsed = JSON.parse(raw);
2702
+ const wakeEv = await inspectChannelMessages(channelId, [parsed]);
2703
+ if (wakeEv) {
2704
+ finish(wakeEv);
2705
+ return;
2706
+ }
2707
+ } catch {}
2708
+ }
2709
+ }
2710
+ } catch {
2711
+ sseConnectedChannels.delete(channelId);
2712
+ if (resolved)
2713
+ return;
2714
+ await new Promise((r) => setTimeout(r, 2000));
2715
+ }
2716
+ }
2717
+ sseConnectedChannels.delete(channelId);
2718
+ activeSseChannels.delete(channelId);
2719
+ })();
2720
+ }
2721
+ let polling = false;
2722
+ async function pollOnce() {
2723
+ if (resolved || polling)
2724
+ return;
2725
+ polling = true;
2726
+ try {
2727
+ const mineRes = await f(`${baseUrl}/api/channels/mine`, {
2728
+ headers,
2729
+ signal: abortCtrl.signal
2730
+ });
2731
+ const channelList = [];
2732
+ const seenCh = new Set;
2733
+ if (mineRes.ok) {
2734
+ const mineData = await mineRes.json();
2735
+ for (const ch of mineData.channels || []) {
2736
+ if (ch && typeof ch.id === "string" && !seenCh.has(ch.id)) {
2737
+ seenCh.add(ch.id);
2738
+ channelList.push({ id: ch.id, last_message_at: ch.last_message_at });
2739
+ }
2740
+ }
2741
+ }
2742
+ for (const extra of opts.channels ?? []) {
2743
+ if (extra && !seenCh.has(extra)) {
2744
+ seenCh.add(extra);
2745
+ channelList.push({ id: extra });
2746
+ }
2747
+ }
2748
+ const sortedForSse = [...channelList].sort((a, b) => {
2749
+ const aDm = a.id.startsWith("dm-") ? 0 : 1;
2750
+ const bDm = b.id.startsWith("dm-") ? 0 : 1;
2751
+ return aDm - bDm;
2752
+ });
2753
+ for (const ch of sortedForSse) {
2754
+ maybeStartSse(ch.id);
2755
+ }
2756
+ for (const ch of channelList) {
2757
+ if (resolved)
2758
+ return;
2759
+ if (initialSyncedChannels.has(ch.id) && sseConnectedChannels.has(ch.id)) {
2760
+ continue;
2761
+ }
2762
+ const existingAfter = cursor.get(ch.id);
2763
+ if (existingAfter && ch.last_message_at && initialSyncedChannels.has(ch.id)) {
2764
+ const lastAtNorm = normalizeTimestampForCursor2(ch.last_message_at, "after") || ch.last_message_at;
2765
+ const afterNorm = normalizeTimestampForCursor2(existingAfter, "after") || existingAfter;
2766
+ if (lastAtNorm <= afterNorm)
2767
+ continue;
2768
+ }
2769
+ const qs = existingAfter ? `?after=${encodeURIComponent(existingAfter)}&limit=50` : `?limit=20`;
2770
+ const msgRes = await f(`${baseUrl}/api/channels/${encodeURIComponent(ch.id)}/messages${qs}`, { headers, signal: abortCtrl.signal });
2771
+ if (!msgRes.ok)
2772
+ continue;
2773
+ initialSyncedChannels.add(ch.id);
2774
+ const msgData = await msgRes.json();
2775
+ const wakeEv = await inspectChannelMessages(ch.id, msgData.messages || []);
2776
+ if (wakeEv) {
2777
+ finish(wakeEv);
2778
+ return;
2779
+ }
2780
+ }
2781
+ } catch {} finally {
2782
+ polling = false;
2783
+ }
2784
+ }
2785
+ if (timeoutMs > 0) {
2786
+ timeoutTimer = setTimeout(() => {
2787
+ const lastActiveIso = cursor.get(CURSOR_LAST_ACTIVE_KEY) || initTs;
2788
+ const nowMs = Date.parse(nowIso());
2789
+ const lastActiveMs = Date.parse(lastActiveIso);
2790
+ const elapsedMs = Number.isFinite(nowMs) && Number.isFinite(lastActiveMs) ? Math.max(timeoutMs, nowMs - lastActiveMs) : timeoutMs;
2791
+ if (maxIdleMs > 0 && elapsedMs >= maxIdleMs) {
2792
+ cursor.delete(CURSOR_LAST_ACTIVE_KEY);
2793
+ persistCursor2(lastSeenFile, cursor, warn);
2794
+ finish({
2795
+ event: "hibernate",
2796
+ agent_id: agentId,
2797
+ timeout_ms: timeoutMs,
2798
+ idle_ms: elapsedMs,
2799
+ max_idle_ms: maxIdleMs,
2800
+ should_rearm: false,
2801
+ prompt: `[AgentsChat] 连续 ${Math.round(maxIdleMs / 60000)} 分钟无新消息,已自动停止后台续期以节省 Token。下次在网页端发送任意消息即可重新唤醒监听。`
2802
+ });
2803
+ return;
2804
+ }
2805
+ finish({
2806
+ event: "idle_timeout",
2807
+ agent_id: agentId,
2808
+ timeout_ms: timeoutMs,
2809
+ idle_ms: elapsedMs,
2810
+ max_idle_ms: maxIdleMs,
2811
+ should_rearm: true
2812
+ });
2813
+ }, timeoutMs);
2814
+ }
2815
+ pollTimer = setInterval(() => {
2816
+ pollOnce();
2817
+ }, pollIntervalMs);
2818
+ pollOnce();
2819
+ });
2820
+ }
2821
+
1917
2822
  // src/server.ts
1918
2823
  import { randomUUID } from "crypto";
1919
2824
  for (const key of ["NO_PROXY", "no_proxy"]) {
@@ -1934,7 +2839,21 @@ if (process.env.AGENTCHAT_NO_PROXY === "1" && process.env.NODE_USE_ENV_PROXY !==
1934
2839
  function parseArgs() {
1935
2840
  const args = process.argv.slice(2);
1936
2841
  const parsed = {};
1937
- const values = new Set(["name", "id", "url", "token", "caps", "profile"]);
2842
+ const values = new Set([
2843
+ "name",
2844
+ "id",
2845
+ "url",
2846
+ "token",
2847
+ "caps",
2848
+ "profile",
2849
+ "join",
2850
+ "send",
2851
+ "text",
2852
+ "reply-to",
2853
+ "channel",
2854
+ "timeout",
2855
+ "max-idle"
2856
+ ]);
1938
2857
  for (let i = 0;i < args.length; i++) {
1939
2858
  const arg = args[i];
1940
2859
  if (arg === "--help" || arg === "-h")
@@ -1947,6 +2866,10 @@ function parseArgs() {
1947
2866
  parsed.registerOnly = "1";
1948
2867
  continue;
1949
2868
  }
2869
+ if (arg === "--wake-once") {
2870
+ parsed.wakeOnce = "1";
2871
+ continue;
2872
+ }
1950
2873
  if (arg === "--accept-terms")
1951
2874
  continue;
1952
2875
  const equal = arg.indexOf("=");
@@ -1957,7 +2880,7 @@ function parseArgs() {
1957
2880
  process.exit(1);
1958
2881
  }
1959
2882
  const value = equal < 0 ? args[++i] : arg.slice(equal + 1);
1960
- if (!value?.trim() || value.startsWith("-")) {
2883
+ if (!value?.trim() || key !== "text" && value.startsWith("-")) {
1961
2884
  process.stderr.write(`[agentchat] ERROR: missing value for --${key}. See --help.
1962
2885
  `);
1963
2886
  process.exit(1);
@@ -1967,8 +2890,9 @@ function parseArgs() {
1967
2890
  return parsed;
1968
2891
  }
1969
2892
  var cliArgs = parseArgs();
2893
+ var isOneShotCli = Boolean(cliArgs.registerOnly || cliArgs.join || cliArgs.send || cliArgs.wakeOnce);
1970
2894
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
1971
- const localOnboardingPath = join6(dirname(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
2895
+ const localOnboardingPath = join8(dirname2(fileURLToPath(import.meta.url)), "..", "skills", "onboarding.md");
1972
2896
  console.log(`agentschat-mcp v${package_default.version} \u2014 AgentsChat MCP and host bridges
1973
2897
 
1974
2898
  Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
@@ -1990,6 +2914,14 @@ Options:
1990
2914
  --profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
1991
2915
  --register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
1992
2916
  --register Explicitly opt in to registering a new agent (implied by --name)
2917
+ --join <channel> Join a public channel via REST (e.g. --join welcome) and exit (or combine with --send / --wake-once).
2918
+ --send <channel> Send a message to <channel> via REST (--text <msg> [--reply-to <msg_id>]), advance read cursor, and exit.
2919
+ --text <msg> Message content for --send.
2920
+ --reply-to <id> Optional target message ID for --send.
2921
+ --wake-once Wait via HTTPS SSE + REST cursor for the next @mention or DM, print wake JSON + prompt, advance per-channel cursor, and exit 0.
2922
+ --channel <ids> Comma-separated channels to join/watch with --wake-once (default: welcome + all joined channels).
2923
+ --timeout <sec> Max wait time in seconds per --wake-once window (default: 240).
2924
+ --max-idle <sec> Auto-hibernate and stop re-arming after <sec> of continuous silence (default: 3600 = 1 hour).
1993
2925
  --accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
1994
2926
  No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
1995
2927
  --id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
@@ -2033,38 +2965,59 @@ Profiles stored in: ~/.agentschat/ (legacy fallback: ~/.agentchat/)
2033
2965
  Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
2034
2966
  process.exit(0);
2035
2967
  }
2968
+ var codexIdentity = process.env.AGENTSCHAT_CODEX_IDENTITY ? JSON.parse(process.env.AGENTSCHAT_CODEX_IDENTITY) : undefined;
2969
+ if (codexIdentity) {
2970
+ if (process.env.AGENTSCHAT_TOOL_ONLY !== "1" || [codexIdentity.profileFile, codexIdentity.agentId, codexIdentity.apiUrl, codexIdentity.wsUrl].some((v) => typeof v !== "string" || !v.trim())) {
2971
+ throw new Error("Invalid Codex tool identity");
2972
+ }
2973
+ cliArgs.profile = codexIdentity.profileFile;
2974
+ cliArgs.id = codexIdentity.agentId;
2975
+ cliArgs.url = codexIdentity.apiUrl;
2976
+ delete cliArgs.token;
2977
+ delete cliArgs.name;
2978
+ delete process.env.AGENTCHAT_TOKEN;
2979
+ process.env.AGENTSCHAT_EXPECT_AGENT_ID = codexIdentity.agentId;
2980
+ }
2036
2981
  var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
2037
- var configDir = join6(homeDir, ".agentschat");
2038
- var legacyConfigDir = join6(homeDir, ".agentchat");
2982
+ var configDir = join8(homeDir, ".agentschat");
2983
+ var legacyConfigDir = join8(homeDir, ".agentchat");
2039
2984
  var profileDirs = [configDir, legacyConfigDir];
2040
2985
  var lockDir = resolveLockDir(homeDir, process.env);
2041
2986
  var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
2042
2987
  var toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
2043
- var runtimeSession = detectRuntimeSession(process.env);
2988
+ var runtimeSessionComputed = false;
2989
+ var runtimeSession = null;
2990
+ function ensureRuntimeSession() {
2991
+ if (!runtimeSessionComputed) {
2992
+ runtimeSessionComputed = true;
2993
+ runtimeSession = detectRuntimeSession(process.env);
2994
+ }
2995
+ return runtimeSession;
2996
+ }
2044
2997
  var dshRouteWarned = false;
2045
2998
  function profileNameToPaths(name) {
2046
2999
  if (name.startsWith("~/"))
2047
- return [join6(homeDir, name.slice(2))];
3000
+ return [join8(homeDir, name.slice(2))];
2048
3001
  if (name.includes("/") || name.includes("\\"))
2049
3002
  return [name];
2050
3003
  name = name.replace(/\.json$/, "");
2051
3004
  const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
2052
- return profileDirs.map((dir) => join6(dir, `${safeName}.json`));
3005
+ return profileDirs.map((dir) => join8(dir, `${safeName}.json`));
2053
3006
  }
2054
3007
  function nameToPath(name) {
2055
3008
  const candidates = profileNameToPaths(name);
2056
- const nested = join6(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
2057
- if (!name.includes("/") && !name.includes("\\") && existsSync7(nested))
3009
+ const nested = join8(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
3010
+ if (!name.includes("/") && !name.includes("\\") && existsSync8(nested))
2058
3011
  return nested;
2059
- return candidates.find((path) => existsSync7(path)) || candidates[0];
3012
+ return candidates.find((path) => existsSync8(path)) || candidates[0];
2060
3013
  }
2061
3014
  function listProfileFiles() {
2062
3015
  const seen = new Set;
2063
3016
  const profiles = [];
2064
- for (const dir of [join6(configDir, "profiles"), ...profileDirs]) {
3017
+ for (const dir of [join8(configDir, "profiles"), ...profileDirs]) {
2065
3018
  let files = [];
2066
3019
  try {
2067
- files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
3020
+ files = readdirSync5(dir).filter((f) => f.endsWith(".json"));
2068
3021
  } catch {}
2069
3022
  for (const file of files) {
2070
3023
  if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME || file === DEFAULT_SESSION_BINDS_FILENAME || file === LEGACY_AGY_BINDS_FILENAME)
@@ -2073,7 +3026,7 @@ function listProfileFiles() {
2073
3026
  if (seen.has(name))
2074
3027
  continue;
2075
3028
  seen.add(name);
2076
- profiles.push({ name, path: join6(dir, file) });
3029
+ profiles.push({ name, path: join8(dir, file) });
2077
3030
  }
2078
3031
  }
2079
3032
  return profiles;
@@ -2098,9 +3051,9 @@ function resolveProfile() {
2098
3051
  let binds = {};
2099
3052
  if (!grokToken && conversationId) {
2100
3053
  const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
2101
- if (existsSync7(bindPath)) {
3054
+ if (existsSync8(bindPath)) {
2102
3055
  try {
2103
- const parsed = parseGrokBindsText(readFileSync7(bindPath, "utf-8"));
3056
+ const parsed = parseGrokBindsText(readFileSync11(bindPath, "utf-8"));
2104
3057
  binds = parsed.binds;
2105
3058
  if (parsed.malformed) {
2106
3059
  process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
@@ -2130,13 +3083,14 @@ function resolveProfile() {
2130
3083
  return { path: nameToPath(process.env.AGENTSCHAT_PROFILE), source: "env", declaredName: process.env.AGENTSCHAT_PROFILE };
2131
3084
  if (process.env.AGENTCHAT_PROFILE)
2132
3085
  return { path: nameToPath(process.env.AGENTCHAT_PROFILE), source: "legacy-env", declaredName: process.env.AGENTCHAT_PROFILE };
2133
- if (!grokToken && runtimeSession?.sessionId) {
3086
+ const bootSession = !grokToken ? ensureRuntimeSession() : null;
3087
+ if (!grokToken && bootSession?.sessionId) {
2134
3088
  const sessionBinds = loadSessionBinds(configDir);
2135
- const boundProfile = sessionBinds[runtimeSession.sessionId];
3089
+ const boundProfile = sessionBinds[bootSession.sessionId];
2136
3090
  if (boundProfile) {
2137
3091
  const boundPath = nameToPath(boundProfile);
2138
- if (existsSync7(boundPath)) {
2139
- process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} \u2192 profile "${boundProfile}"
3092
+ if (existsSync8(boundPath)) {
3093
+ process.stderr.write(`[agentchat] session-bind (${bootSession.runtime}): ${bootSession.sessionId} \u2192 profile "${boundProfile}"
2140
3094
  `);
2141
3095
  return { path: boundPath, source: "session-bind", declaredName: boundProfile };
2142
3096
  }
@@ -2180,7 +3134,7 @@ if (hasToken && !explicitAgentId && profileSource === "default") {
2180
3134
  process.exit(1);
2181
3135
  }
2182
3136
  var identity = decideIdentity({
2183
- profileExists: existsSync7(profileFile),
3137
+ profileExists: existsSync8(profileFile),
2184
3138
  source: profileSource,
2185
3139
  profileFile,
2186
3140
  cliName: cliArgs.name,
@@ -2191,46 +3145,68 @@ var identity = decideIdentity({
2191
3145
  });
2192
3146
  function readIdentityProfile(file) {
2193
3147
  try {
2194
- return JSON.parse(readFileSync7(file, "utf-8"));
3148
+ return JSON.parse(readFileSync11(file, "utf-8"));
2195
3149
  } catch {
2196
3150
  throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
2197
3151
  }
2198
3152
  }
2199
3153
  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}
3154
+ const isDefaultProfileFile = profileSource === "default" || profileNameFromPath(profileFile)?.toLowerCase() === "profile";
3155
+ const defaultCollision = isDefaultProfileFile ? findDefaultProfileCollision(configDir, profileFile) : null;
3156
+ if (defaultCollision) {
3157
+ if (profileSource !== "default") {
3158
+ process.stderr.write(`[agentchat] ERROR: Refusing to load duplicate profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).
3159
+ ` + ` Delete ${profileFile} and use --profile ${defaultCollision.collidingName} instead.
2213
3160
  `);
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) {
3161
+ process.exit(1);
3162
+ }
2224
3163
  anonymousMode = true;
2225
3164
  activeProfileFile = null;
2226
3165
  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}` : ""}.
3166
+ process.stderr.write(`[agentchat] Ignoring duplicate default profile.json (${profileFile}): it collides (${defaultCollision.reason}) with named profile "${defaultCollision.collidingName}" (${defaultCollision.collidingPath}).
3167
+ ` + ` Starting in ANONYMOUS mode instead of shadowing "${defaultCollision.collidingName}". Delete ${profileFile} or bind this session via connect_profile(profile_name="${defaultCollision.collidingName}").
3168
+ `);
3169
+ } else {
3170
+ try {
3171
+ profile = readIdentityProfile(profileFile);
3172
+ if (codexIdentity && profile.agent_id !== codexIdentity.agentId) {
3173
+ throw new Error("Codex tool profile identity mismatch");
3174
+ }
3175
+ if (projectAgentId !== undefined && projectAgentId !== (cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id)) {
3176
+ throw new Error("Project agent_id does not match selected profile");
3177
+ }
3178
+ validateIdentityProfile(profile && !Array.isArray(profile) ? {
3179
+ ...profile,
3180
+ agent_id: cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile.agent_id,
3181
+ token: cliArgs.token ?? process.env.AGENTCHAT_TOKEN ?? profile.token,
3182
+ capabilities: cliArgs.caps?.split(",") ?? profile.capabilities
3183
+ } : profile, profileFile, !hasToken);
3184
+ } catch (e) {
3185
+ process.stderr.write(`[agentchat] ERROR: ${e.message}
3186
+ `);
3187
+ process.exit(1);
3188
+ }
3189
+ const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
3190
+ if (!isOneShotCli && !toolOnlyMode)
3191
+ ensureRuntimeSession();
3192
+ const lockCheck = !isOneShotCli && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
3193
+ lockDir,
3194
+ agentId: candidateAgentId,
3195
+ currentSessionId: runtimeSession?.sessionId ?? null,
3196
+ lockOwnerPid
3197
+ }) : { locked: false };
3198
+ if (lockCheck.locked) {
3199
+ anonymousMode = true;
3200
+ activeProfileFile = null;
3201
+ profile = {};
3202
+ 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
3203
  ` + ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.
2229
3204
  ` + ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.
2230
3205
  `);
2231
- } else {
2232
- process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
3206
+ } else {
3207
+ process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
2233
3208
  `);
3209
+ }
2234
3210
  }
2235
3211
  } else if (identity.mode === "env-creds") {
2236
3212
  activeProfileFile = null;
@@ -2293,7 +3269,7 @@ if (identity.mode === "profile") {
2293
3269
  `);
2294
3270
  process.exit(1);
2295
3271
  }
2296
- mkdirSync3(dirname(profileFile), { recursive: true });
3272
+ mkdirSync4(dirname2(profileFile), { recursive: true });
2297
3273
  safeWriteProfile2(profileFile, profile);
2298
3274
  process.stderr.write(`[agentchat] Profile saved: ${profileFile}
2299
3275
  `);
@@ -2372,12 +3348,23 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
2372
3348
  process.exit(1);
2373
3349
  }
2374
3350
  }
2375
- 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" };
3351
+ if (!anonymousMode && AGENT_ID && !isOneShotCli && !toolOnlyMode) {
3352
+ let activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
3353
+ 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);
3354
+ const isImplicitAgyBoot = (runtimeSession?.runtime === "antigravity" || !runtimeSession && Boolean(discoverAntigravityHost())) && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim();
3355
+ if (activeName && isImplicitAgyBoot) {
3356
+ const existingBoundSid = findBoundSessionForProfile(configDir, activeName, isAgyUuid);
3357
+ const existingAgentRoute = resolveSessionForAgent(AGENT_ID, { configDir, filter: isAgyUuid });
3358
+ const resolvedSid = existingBoundSid || existingAgentRoute?.sessionId || "";
3359
+ if (resolvedSid) {
3360
+ runtimeSession = { sessionId: resolvedSid, runtime: "antigravity" };
3361
+ if (profileSource === "default" && existingAgentRoute?.profileName && existingAgentRoute.profileName !== activeName) {
3362
+ const aliasPath = nameToPath(existingAgentRoute.profileName);
3363
+ if (existsSync8(aliasPath)) {
3364
+ activeProfileFile = aliasPath;
3365
+ activeName = existingAgentRoute.profileName;
3366
+ }
3367
+ }
2381
3368
  }
2382
3369
  }
2383
3370
  acquireAgentLock({
@@ -2388,14 +3375,17 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
2388
3375
  runtime: runtimeSession?.runtime ?? "mcp"
2389
3376
  });
2390
3377
  if (runtimeSession?.sessionId && activeName) {
2391
- saveSessionBind(configDir, runtimeSession.sessionId, activeName);
3378
+ const existingBinds = loadSessionBinds(configDir);
3379
+ if (!isImplicitAgyBoot || existingBinds[runtimeSession.sessionId] === activeName) {
3380
+ saveSessionBind(configDir, runtimeSession.sessionId, activeName);
3381
+ }
2392
3382
  }
2393
3383
  }
2394
3384
  var identityGateMessage = "";
2395
- var identityGuardFile = join6(configDir, IDENTITY_GUARD_FILENAME);
3385
+ var identityGuardFile = join8(configDir, IDENTITY_GUARD_FILENAME);
2396
3386
  function persistGuardRecord(rec) {
2397
3387
  try {
2398
- mkdirSync3(configDir, { recursive: true });
3388
+ mkdirSync4(configDir, { recursive: true });
2399
3389
  safeWriteProfile2(identityGuardFile, rec);
2400
3390
  } catch {}
2401
3391
  }
@@ -2411,7 +3401,7 @@ function confirmLiveIdentityTrusted() {
2411
3401
  }
2412
3402
  var guardRecord = (() => {
2413
3403
  try {
2414
- return parseGuardRecord(readFileSync7(identityGuardFile, "utf-8"));
3404
+ return parseGuardRecord(readFileSync11(identityGuardFile, "utf-8"));
2415
3405
  } catch {
2416
3406
  return emptyGuardRecord();
2417
3407
  }
@@ -2451,16 +3441,86 @@ var EXPECTED_AGENT_ID = expectedAgentIdFromEnv(process.env);
2451
3441
  if (cliArgs.name && profile.display_name !== cliArgs.name) {
2452
3442
  profile.display_name = cliArgs.name;
2453
3443
  }
2454
- if (cliArgs.registerOnly && !TOKEN) {
3444
+ if (isOneShotCli && (!TOKEN || TOKEN === "dev-token")) {
2455
3445
  process.stderr.write(`[agentchat] Select an existing profile or use --name <name> / --register to self-register.
2456
3446
  `);
2457
3447
  process.exit(1);
2458
3448
  }
3449
+ if (cliArgs.join || cliArgs.send || cliArgs.wakeOnce) {
3450
+ if (cliArgs.send && !cliArgs.text) {
3451
+ process.stderr.write(`[agentchat] ERROR: --send <channel> requires --text <message>. See --help.
3452
+ `);
3453
+ process.exit(1);
3454
+ }
3455
+ if (cliArgs.join && !cliArgs.send && !cliArgs.wakeOnce) {
3456
+ const res = await joinChannelRest({
3457
+ restUrl: REST_URL,
3458
+ agentId: AGENT_ID,
3459
+ token: TOKEN,
3460
+ channelId: cliArgs.join
3461
+ });
3462
+ console.log(JSON.stringify(res));
3463
+ process.exit(res.ok ? 0 : 1);
3464
+ }
3465
+ const explicitMaxIdleMs = parseMaxIdleMs(cliArgs["max-idle"]);
3466
+ if (cliArgs.send) {
3467
+ if (cliArgs.join) {
3468
+ await joinChannelRest({
3469
+ restUrl: REST_URL,
3470
+ agentId: AGENT_ID,
3471
+ token: TOKEN,
3472
+ channelId: cliArgs.join
3473
+ });
3474
+ }
3475
+ const res = await sendRestMessage({
3476
+ restUrl: REST_URL,
3477
+ configDir,
3478
+ agentId: AGENT_ID,
3479
+ token: TOKEN,
3480
+ channelId: cliArgs.send,
3481
+ text: cliArgs.text,
3482
+ replyTo: cliArgs["reply-to"],
3483
+ maxIdleMs: explicitMaxIdleMs
3484
+ });
3485
+ console.log(JSON.stringify(res));
3486
+ process.exit(res.ok ? 0 : 1);
3487
+ }
3488
+ if (cliArgs.wakeOnce) {
3489
+ const rawChans = [
3490
+ ...cliArgs.join ? [cliArgs.join] : [],
3491
+ ...cliArgs.channel ? cliArgs.channel.split(",").map((c) => c.trim()).filter(Boolean) : []
3492
+ ];
3493
+ const channels = rawChans.length > 0 ? [...new Set(rawChans)] : ["welcome"];
3494
+ const timeoutSec = cliArgs.timeout !== undefined ? Number(cliArgs.timeout) : 240;
3495
+ const timeoutMs = Number.isFinite(timeoutSec) && timeoutSec >= 0 ? timeoutSec * 1000 : 240000;
3496
+ const ev = await wakeOnce({
3497
+ restUrl: REST_URL,
3498
+ configDir,
3499
+ agentId: AGENT_ID,
3500
+ displayName: profile.display_name || AGENT_ID,
3501
+ token: TOKEN,
3502
+ channels,
3503
+ timeoutMs,
3504
+ maxIdleMs: explicitMaxIdleMs
3505
+ });
3506
+ console.log(JSON.stringify(ev));
3507
+ process.exit(0);
3508
+ }
3509
+ }
2459
3510
  if (TOKEN && TOKEN !== "dev-token") {
2460
3511
  const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
2461
3512
  process.stderr.write(`[agentchat] ${claimSummary(status)}
2462
3513
  `);
2463
3514
  if (cliArgs.registerOnly) {
3515
+ try {
3516
+ mkdirSync4(configDir, { recursive: true });
3517
+ const lastSeenFile = join8(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
3518
+ const cursor = loadCursor(lastSeenFile, (m) => process.stderr.write(m));
3519
+ if (!cursor.get(CURSOR_INIT_KEY)) {
3520
+ cursor.set(CURSOR_INIT_KEY, new Date().toISOString());
3521
+ persistCursor(lastSeenFile, cursor, (m) => process.stderr.write(m));
3522
+ }
3523
+ } catch {}
2464
3524
  console.log(JSON.stringify({ ...status, terms_notice: TERMS_NOTICE, claim_url: status.claimed === true ? null : `${status.chat_url}?key=${encodeURIComponent(TOKEN)}`, profile_file: activeProfileFile, reply_verified: false }));
2465
3525
  process.exit(0);
2466
3526
  }
@@ -3309,7 +4369,7 @@ var ALL_TOOL_DEFS = [
3309
4369
  },
3310
4370
  {
3311
4371
  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.",
4372
+ 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
4373
  inputSchema: {
3314
4374
  type: "object",
3315
4375
  properties: { chat_id: { type: "string", description: "The channel_id" } },
@@ -3318,7 +4378,7 @@ var ALL_TOOL_DEFS = [
3318
4378
  },
3319
4379
  {
3320
4380
  name: "list_members",
3321
- description: "List members in a channel.",
4381
+ description: "List members in a channel with full @agent_id handles, online status, and peer capability tags (human login emails/phones masked).",
3322
4382
  inputSchema: {
3323
4383
  type: "object",
3324
4384
  properties: {
@@ -3796,10 +4856,10 @@ function mimeFromPath(p, kindHint) {
3796
4856
  return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
3797
4857
  }
3798
4858
  async function uploadLocalFile(path, kindHint) {
3799
- if (!existsSync7(path))
4859
+ if (!existsSync8(path))
3800
4860
  throw new Error(`file not found: ${path}`);
3801
4861
  const mime = mimeFromPath(path, kindHint);
3802
- const buf = readFileSync7(path);
4862
+ const buf = readFileSync11(path);
3803
4863
  const name = path.split("/").pop() || "upload";
3804
4864
  const form = new FormData;
3805
4865
  form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
@@ -3996,10 +5056,10 @@ HANDLERS.set("transcribe", async (args) => {
3996
5056
  });
3997
5057
  function loadGrokBinds() {
3998
5058
  const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
3999
- if (!existsSync7(bindPath))
5059
+ if (!existsSync8(bindPath))
4000
5060
  return {};
4001
5061
  try {
4002
- return parseGrokBindsText(readFileSync7(bindPath, "utf-8")).binds;
5062
+ return parseGrokBindsText(readFileSync11(bindPath, "utf-8")).binds;
4003
5063
  } catch {
4004
5064
  return {};
4005
5065
  }
@@ -4034,7 +5094,7 @@ function scheduleSlotLastSeenMessageTsSave(slot) {
4034
5094
  slot.lastSeenMessageTsTimer.unref?.();
4035
5095
  }
4036
5096
  function createProfileSlot(opts) {
4037
- const lastSeenFile = join6(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
5097
+ const lastSeenFile = join8(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
4038
5098
  const slot = {
4039
5099
  profileName: opts.profileName,
4040
5100
  profileFile: opts.profileFile,
@@ -4116,6 +5176,28 @@ function setAnonymousCallerState(callerSession) {
4116
5176
  runtimeSession = callerSession;
4117
5177
  }
4118
5178
  }
5179
+ function findSlotByAgentId(agentId) {
5180
+ if (!agentId)
5181
+ return;
5182
+ for (const s of profileSlots.values()) {
5183
+ if (s.agentId === agentId)
5184
+ return s;
5185
+ }
5186
+ return;
5187
+ }
5188
+ function upgradeAliasSlotInPlace(slot, newProfileName, newProfileFile, newProfile, sess) {
5189
+ if (slot.profileName !== newProfileName) {
5190
+ profileSlots.delete(slot.profileName);
5191
+ slot.profileName = newProfileName;
5192
+ profileSlots.set(newProfileName, slot);
5193
+ }
5194
+ slot.profileFile = newProfileFile;
5195
+ slot.profile = newProfile;
5196
+ slot.runtimeSession = sess;
5197
+ if (activeSlot === slot) {
5198
+ activateSlot(slot, sess);
5199
+ }
5200
+ }
4119
5201
  function teardownSlot(slot, opts) {
4120
5202
  try {
4121
5203
  flushSlotLastSeenMessageTs(slot);
@@ -4262,7 +5344,7 @@ function formatProfileList() {
4262
5344
  const lines = profileEntries.map((entry) => {
4263
5345
  let entryAgentId = "";
4264
5346
  try {
4265
- const parsed = JSON.parse(readFileSync7(entry.path, "utf-8"));
5347
+ const parsed = JSON.parse(readFileSync11(entry.path, "utf-8"));
4266
5348
  if (typeof parsed?.agent_id === "string")
4267
5349
  entryAgentId = parsed.agent_id;
4268
5350
  } catch {}
@@ -4270,7 +5352,8 @@ function formatProfileList() {
4270
5352
  const lock = entryAgentId ? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid }) : { locked: false };
4271
5353
  const slot = profileSlots.get(entry.name);
4272
5354
  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}` : ""}]` : "";
5355
+ const dupCollision = entry.name.toLowerCase() === "profile" ? findDefaultProfileCollision(configDir, entry.path) : null;
5356
+ 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
5357
  return `${isCurrent ? "\u2192 " : " "}${entry.name}${statusSuffix}`;
4275
5358
  });
4276
5359
  return `Current: ${current || "(anonymous / disconnected)"}
@@ -4283,6 +5366,42 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
4283
5366
  if (!cleanName) {
4284
5367
  return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
4285
5368
  }
5369
+ const safeBase = cleanName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
5370
+ if (safeBase.toLowerCase() === "profile") {
5371
+ return {
5372
+ content: [{
5373
+ type: "text",
5374
+ 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").'
5375
+ }],
5376
+ isError: true
5377
+ };
5378
+ }
5379
+ const existingTargetFile = nameToPath(cleanName);
5380
+ if (existsSync8(existingTargetFile)) {
5381
+ return {
5382
+ content: [{
5383
+ type: "text",
5384
+ text: `Error: Profile "${cleanName}" already exists at ${existingTargetFile}. Pass profile_name="${cleanName}" to connect to it, or choose a different register_name.`
5385
+ }],
5386
+ isError: true
5387
+ };
5388
+ }
5389
+ const existingDefaultPath = nameToPath("profile");
5390
+ if (existsSync8(existingDefaultPath)) {
5391
+ try {
5392
+ const defParsed = JSON.parse(readFileSync11(existingDefaultPath, "utf-8"));
5393
+ const defDisplay = typeof defParsed?.display_name === "string" ? defParsed.display_name.trim().toLowerCase() : "";
5394
+ if (defDisplay && defDisplay === cleanName.toLowerCase()) {
5395
+ return {
5396
+ content: [{
5397
+ type: "text",
5398
+ 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.`
5399
+ }],
5400
+ isError: true
5401
+ };
5402
+ }
5403
+ } catch {}
5404
+ }
4286
5405
  const caps = ["claude-code", "coding", "chat"];
4287
5406
  try {
4288
5407
  const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
@@ -4312,12 +5431,8 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
4312
5431
  };
4313
5432
  const targetFile = nameToPath(cleanName);
4314
5433
  validateIdentityProfile(newProfile, targetFile);
4315
- mkdirSync3(dirname(targetFile), { recursive: true });
5434
+ mkdirSync4(dirname2(targetFile), { recursive: true });
4316
5435
  safeWriteProfile2(targetFile, newProfile);
4317
- const defaultProfileFile = nameToPath("profile");
4318
- if (!existsSync7(defaultProfileFile)) {
4319
- safeWriteProfile2(defaultProfileFile, newProfile);
4320
- }
4321
5436
  applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
4322
5437
  const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
4323
5438
  return {
@@ -4372,7 +5487,7 @@ async function handleProfileSwitchOrConnect(args) {
4372
5487
  return { content: [{ type: "text", text: switchGate.message }], isError: true };
4373
5488
  }
4374
5489
  const targetFile = nameToPath(profile_name);
4375
- if (!existsSync7(targetFile)) {
5490
+ if (!existsSync8(targetFile)) {
4376
5491
  if (register) {
4377
5492
  return await registerAndConnectProfile(profile_name, explicitSessionId);
4378
5493
  }
@@ -4385,6 +5500,18 @@ async function handleProfileSwitchOrConnect(args) {
4385
5500
  isError: true
4386
5501
  };
4387
5502
  }
5503
+ if (profileNameFromPath(targetFile)?.toLowerCase() === "profile") {
5504
+ const dupCollision = findDefaultProfileCollision(configDir, targetFile);
5505
+ if (dupCollision) {
5506
+ return {
5507
+ content: [{
5508
+ type: "text",
5509
+ 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.`
5510
+ }],
5511
+ isError: true
5512
+ };
5513
+ }
5514
+ }
4388
5515
  const newProfile = readIdentityProfile(targetFile);
4389
5516
  validateIdentityProfile(newProfile, targetFile);
4390
5517
  const effectiveSessionId = explicitSessionId ?? runtimeSession?.sessionId ?? null;
@@ -4436,7 +5563,7 @@ function ensureGrokBoundIdentity() {
4436
5563
  if (!boundName)
4437
5564
  return;
4438
5565
  const boundPath = nameToPath(boundName);
4439
- if (!existsSync7(boundPath))
5566
+ if (!existsSync8(boundPath))
4440
5567
  return;
4441
5568
  let boundProfile;
4442
5569
  try {
@@ -4534,9 +5661,12 @@ var handleToolCall = async (request) => {
4534
5661
  let { name, arguments: args } = request.params;
4535
5662
  let viaExtendedCompat = false;
4536
5663
  try {
5664
+ if (codexIdentity && (AGENT_ID !== codexIdentity.agentId || ["connect_profile", "switch_profile", "disconnect_profile"].includes(name))) {
5665
+ return { content: [{ type: "text", text: "Codex bridge owns this tool identity; change the bot configuration and restart to change identity." }], isError: true };
5666
+ }
4537
5667
  const rawMeta = request.params?._meta;
4538
5668
  const { session: callerSession, isPerCallSession } = await resolveCallerSessionForToolCall(name, args, rawMeta);
4539
- if (callerSession) {
5669
+ if (callerSession && !codexIdentity) {
4540
5670
  runtimeSession = callerSession;
4541
5671
  const binds = loadSessionBinds(configDir);
4542
5672
  const boundProfileName = binds[callerSession.sessionId];
@@ -4556,19 +5686,35 @@ var handleToolCall = async (request) => {
4556
5686
  }
4557
5687
  } else if (!isProfileControlTool || name === "disconnect_profile") {
4558
5688
  const boundPath = nameToPath(boundProfileName);
4559
- if (existsSync7(boundPath)) {
5689
+ if (existsSync8(boundPath)) {
4560
5690
  try {
4561
5691
  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);
5692
+ const aliasSlot = candidate?.agent_id ? findSlotByAgentId(candidate.agent_id) : undefined;
5693
+ const aliasSid = aliasSlot ? aliasSlot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, aliasSlot.profileName) || resolveSessionForAgent(aliasSlot.agentId, { configDir })?.sessionId || null : null;
5694
+ if (aliasSlot && (!aliasSid || aliasSid === callerSession.sessionId)) {
5695
+ upgradeAliasSlotInPlace(aliasSlot, boundProfileName, boundPath, candidate, callerSession);
5696
+ activateSlot(aliasSlot, callerSession);
5697
+ if (!toolOnlyMode) {
5698
+ acquireAgentLock({
5699
+ lockDir,
5700
+ agentId: aliasSlot.agentId,
5701
+ profileName: boundProfileName,
5702
+ sessionId: callerSession.sessionId,
5703
+ runtime: callerSession.runtime
5704
+ });
5705
+ }
5706
+ } else {
5707
+ const lock = checkAgentLock({
5708
+ lockDir,
5709
+ agentId: candidate?.agent_id,
5710
+ currentSessionId: callerSession.sessionId,
5711
+ lockOwnerPid
5712
+ });
5713
+ if (!lock.locked) {
5714
+ applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
5715
+ } else if (isPerCallSession) {
5716
+ setAnonymousCallerState(callerSession);
5717
+ }
4572
5718
  }
4573
5719
  } catch {}
4574
5720
  } else if (isPerCallSession) {
@@ -4580,7 +5726,7 @@ var handleToolCall = async (request) => {
4580
5726
  } else {
4581
5727
  let unboundSlot = null;
4582
5728
  for (const slot of profileSlots.values()) {
4583
- const slotBoundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
5729
+ const slotBoundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName) || resolveSessionForAgent(slot.agentId, { configDir })?.sessionId;
4584
5730
  if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
4585
5731
  unboundSlot = slot;
4586
5732
  break;
@@ -4612,7 +5758,8 @@ var handleToolCall = async (request) => {
4612
5758
  if (argErr)
4613
5759
  return { content: [{ type: "text", text: `${name}: ${argErr}` }], isError: true };
4614
5760
  }
4615
- ensureGrokBoundIdentity();
5761
+ if (!codexIdentity)
5762
+ ensureGrokBoundIdentity();
4616
5763
  if (identityGateMessage && name !== "whoami" && TOOL_ANNOTATIONS[name]?.readOnlyHint !== true) {
4617
5764
  return { content: [{ type: "text", text: `\uD83D\uDEA8 ${identityGateMessage}` }], isError: true };
4618
5765
  }
@@ -4833,7 +5980,7 @@ ${a.body || ""}`;
4833
5980
  const currentVersion = Number(meta.version ?? 0);
4834
5981
  let cachedVersion = null;
4835
5982
  try {
4836
- cachedVersion = Number(JSON.parse(readFileSync7(pMeta, "utf8")).version);
5983
+ cachedVersion = Number(JSON.parse(readFileSync11(pMeta, "utf8")).version);
4837
5984
  } catch {}
4838
5985
  if (cachedVersion !== null && cachedVersion === currentVersion) {
4839
5986
  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.` }] };
@@ -4842,9 +5989,9 @@ ${a.body || ""}`;
4842
5989
  if (!bodyR.ok)
4843
5990
  return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
4844
5991
  const doc = JSON.parse(await bodyR.text());
4845
- mkdirSync3(dirname(pMd), { recursive: true });
4846
- writeFileSync4(pMd, String(doc?.body_markdown ?? ""));
4847
- writeFileSync4(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
5992
+ mkdirSync4(dirname2(pMd), { recursive: true });
5993
+ writeFileSync6(pMd, String(doc?.body_markdown ?? ""));
5994
+ writeFileSync6(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
4848
5995
  return { content: [{ type: "text", text: `synced personal skill "${a.name}" v${currentVersion} \u2192 ${pMd} (was ${cachedVersion === null ? "missing" : `stale v${cachedVersion}`}). Read that file to run it.` }] };
4849
5996
  } catch (e) {
4850
5997
  return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
@@ -4867,7 +6014,7 @@ ${a.body || ""}`;
4867
6014
  const currentVersion = Number(meta.version ?? 0);
4868
6015
  let cachedVersion = null;
4869
6016
  try {
4870
- cachedVersion = Number(JSON.parse(readFileSync7(metaPath, "utf8")).version);
6017
+ cachedVersion = Number(JSON.parse(readFileSync11(metaPath, "utf8")).version);
4871
6018
  } catch {}
4872
6019
  if (cachedVersion !== null && cachedVersion === currentVersion) {
4873
6020
  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.` }] };
@@ -4877,9 +6024,9 @@ ${a.body || ""}`;
4877
6024
  return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
4878
6025
  const doc = JSON.parse(await docR.text());
4879
6026
  const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
4880
- mkdirSync3(dirname(mdPath), { recursive: true });
4881
- writeFileSync4(mdPath, body);
4882
- writeFileSync4(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
6027
+ mkdirSync4(dirname2(mdPath), { recursive: true });
6028
+ writeFileSync6(mdPath, body);
6029
+ writeFileSync6(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
4883
6030
  const was = cachedVersion === null ? "missing" : `stale v${cachedVersion}`;
4884
6031
  return { content: [{ type: "text", text: `synced "${doc?.title || a.doc_id}" v${currentVersion} \u2192 ${mdPath} (was ${was}). Read that file to run it in your runtime.` }] };
4885
6032
  } catch (e) {
@@ -5196,7 +6343,7 @@ ${a.body || ""}`;
5196
6343
  }
5197
6344
  const data = await r.json();
5198
6345
  if (data.messages?.length > 0) {
5199
- const results = data.messages.map((m) => `[${m.sender_id?.slice(0, 8)}] ${m.content?.slice(0, 80)}`).join(`
6346
+ const results = data.messages.map((m) => `[${redactParticipantPii(m.sender_id || "?")}] ${m.content?.slice(0, 80)}`).join(`
5200
6347
  `);
5201
6348
  return { content: [{ type: "text", text: `Found ${data.messages.length} results:
5202
6349
  ${results}` }] };
@@ -5244,6 +6391,44 @@ ${results}` }] };
5244
6391
  }
5245
6392
  return { content: [{ type: "text", text: "Not connected" }] };
5246
6393
  }
6394
+ async function fetchMcpChannelContext(chatId) {
6395
+ if (!chatId || !TOKEN)
6396
+ return null;
6397
+ try {
6398
+ const r = await apiFetch(`${REST_URL}/mcp`, {
6399
+ method: "POST",
6400
+ headers: {
6401
+ Authorization: `Bearer ${TOKEN}`,
6402
+ "Content-Type": "application/json",
6403
+ ...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
6404
+ },
6405
+ body: JSON.stringify({
6406
+ jsonrpc: "2.0",
6407
+ id: 1,
6408
+ method: "tools/call",
6409
+ params: {
6410
+ name: "agentschat_get_channel_context",
6411
+ arguments: { channel_id: chatId }
6412
+ }
6413
+ })
6414
+ }, 2500);
6415
+ if (!r.ok)
6416
+ return null;
6417
+ const rpc = await r.json();
6418
+ if (rpc?.error || rpc?.result?.isError)
6419
+ return null;
6420
+ const structured = rpc?.result?.structuredContent;
6421
+ if (structured && typeof structured === "object")
6422
+ return structured;
6423
+ const textPayload = rpc?.result?.content?.[0]?.text;
6424
+ if (typeof textPayload === "string" && textPayload.trim().startsWith("{")) {
6425
+ return JSON.parse(textPayload);
6426
+ }
6427
+ return null;
6428
+ } catch {
6429
+ return null;
6430
+ }
6431
+ }
5247
6432
  async function channelBrief(chatId) {
5248
6433
  const get = async (path) => {
5249
6434
  try {
@@ -5253,26 +6438,45 @@ ${results}` }] };
5253
6438
  return null;
5254
6439
  }
5255
6440
  };
5256
- const [membersData, docsData, okrData] = await Promise.all([
6441
+ const [membersData, docsData, okrData, mcpCtx] = await Promise.all([
5257
6442
  get(`/api/channels/${encodeURIComponent(chatId)}/members`),
5258
6443
  get(`/api/channels/${encodeURIComponent(chatId)}/docs`),
5259
- get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`)
6444
+ get(`/api/channels/${encodeURIComponent(chatId)}/okr_snapshot`),
6445
+ fetchMcpChannelContext(chatId)
5260
6446
  ]);
5261
6447
  const membersReadable = membersData !== null;
5262
6448
  const memberIds = (membersData?.members || []).map((m) => m?.agent_id).filter(Boolean);
6449
+ const memberIdSet = new Set(memberIds);
6450
+ const rawOnlineSet = new Set;
5263
6451
  let online = [];
5264
6452
  if (memberIds.length > 0) {
5265
- const onlineSet = new Set;
5266
6453
  for (let i = 0;i < memberIds.length; i += 50) {
5267
6454
  const batch = memberIds.slice(i, i + 50);
5268
6455
  const pres = await get(`/api/presence?ids=${encodeURIComponent(batch.join(","))}`);
5269
6456
  for (const [k, v] of Object.entries(pres?.presence || {})) {
5270
- if (v === "online")
5271
- onlineSet.add(k);
6457
+ if (v === "online" && memberIdSet.has(k))
6458
+ rawOnlineSet.add(k);
5272
6459
  }
5273
6460
  }
5274
- online = [...onlineSet];
5275
- }
6461
+ const maskedOnlineSet = new Set;
6462
+ for (const id of rawOnlineSet) {
6463
+ maskedOnlineSet.add(redactParticipantPii(id));
6464
+ }
6465
+ online = [...maskedOnlineSet];
6466
+ }
6467
+ const agentPeers = Array.isArray(mcpCtx?.agents) ? mcpCtx.agents.filter((a) => a?.id && !isHumanPiiHandle(a.id)).map((a) => ({
6468
+ id: String(a.id),
6469
+ ...a.name && !isHumanPiiHandle(a.name) ? { name: String(a.name) } : {},
6470
+ capabilities: Array.isArray(a.capabilities) ? a.capabilities.map(String) : [],
6471
+ ...typeof a.online === "boolean" ? { online: a.online } : memberIds.length > 0 ? { online: rawOnlineSet.has(String(a.id)) } : {},
6472
+ is_self: typeof a.is_self === "boolean" ? a.is_self : String(a.id) === AGENT_ID
6473
+ })) : (membersData?.members || []).filter((m) => m?.agent_id && !isHumanPiiHandle(m.agent_id) && m.type !== "user").map((m) => ({
6474
+ id: String(m.agent_id),
6475
+ ...m.display_name && !isHumanPiiHandle(m.display_name) ? { name: String(m.display_name) } : {},
6476
+ capabilities: Array.isArray(m.capabilities) ? m.capabilities.map(String) : [],
6477
+ ...typeof m.online === "boolean" ? { online: m.online } : memberIds.length > 0 ? { online: rawOnlineSet.has(String(m.agent_id)) } : {},
6478
+ is_self: String(m.agent_id) === AGENT_ID
6479
+ }));
5276
6480
  const allDocs = docsData ? extractChannelDocsPayload(docsData) : [];
5277
6481
  const skills = allDocs.filter(isSkillDoc).map((d) => ({ doc_id: d.id, title: d.title }));
5278
6482
  const docs = allDocs.filter((d) => !isSkillDoc(d)).slice(0, 10).map((d) => ({ doc_id: d.id, title: d.title, kind: d.kind }));
@@ -5288,7 +6492,10 @@ ${results}` }] };
5288
6492
  }));
5289
6493
  return JSON.stringify({
5290
6494
  channel: chatId,
6495
+ ...mcpCtx?.channel?.name && mcpCtx.channel.name !== chatId ? { channel_name: String(mcpCtx.channel.name) } : {},
6496
+ ...mcpCtx?.channel?.topic ? { topic: String(mcpCtx.channel.topic) } : {},
5291
6497
  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)" },
6498
+ ...membersReadable ? { agent_peers: agentPeers } : {},
5292
6499
  okr_objectives: objectives,
5293
6500
  skills,
5294
6501
  docs,
@@ -5309,12 +6516,26 @@ ${results}` }] };
5309
6516
  } catch {}
5310
6517
  }
5311
6518
  try {
5312
- await new Promise((r2) => setTimeout(r2, 500));
6519
+ const joinRes = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/join`, {
6520
+ method: "POST",
6521
+ headers: { Authorization: `Bearer ${TOKEN}`, "Content-Type": "application/json" },
6522
+ body: JSON.stringify({ sender_id: AGENT_ID })
6523
+ });
6524
+ if (joinRes.ok) {
6525
+ if (activeSlot)
6526
+ activeSlot.knownChannels.add(chat_id);
6527
+ const brief = await channelBrief(chat_id).catch(() => "");
6528
+ return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}
6529
+ ${brief}` }] };
6530
+ }
6531
+ await new Promise((r2) => setTimeout(r2, 300));
5313
6532
  const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { Authorization: `Bearer ${TOKEN}` } });
5314
6533
  if (r.ok) {
5315
6534
  const data = await r.json();
5316
6535
  const isMember = (data.members || []).some((m) => m.agent_id === AGENT_ID);
5317
6536
  if (isMember) {
6537
+ if (activeSlot)
6538
+ activeSlot.knownChannels.add(chat_id);
5318
6539
  const brief = await channelBrief(chat_id).catch(() => "");
5319
6540
  return { content: [{ type: "text", text: `Joined channel ${chat_id.slice(0, 8)}
5320
6541
  ${brief}` }] };
@@ -5658,15 +6879,38 @@ ${lines}` }] };
5658
6879
  if (name === "list_members") {
5659
6880
  const { chat_id } = args;
5660
6881
  try {
5661
- const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { Authorization: `Bearer ${TOKEN}` } });
6882
+ const [r, mcpCtx] = await Promise.all([
6883
+ apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/members`, { headers: { Authorization: `Bearer ${TOKEN}` } }),
6884
+ fetchMcpChannelContext(chat_id)
6885
+ ]);
5662
6886
  if (r.ok) {
5663
6887
  const data = await r.json();
5664
6888
  const members = data.members || [];
5665
6889
  if (members.length === 0)
5666
6890
  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(`
6891
+ const peerById = new Map;
6892
+ for (const a of Array.isArray(mcpCtx?.agents) ? mcpCtx.agents : []) {
6893
+ if (a?.id && !isHumanPiiHandle(a.id)) {
6894
+ peerById.set(String(a.id), a);
6895
+ }
6896
+ }
6897
+ const list = members.map((m) => {
6898
+ const rawId = String(m?.agent_id ?? "");
6899
+ const isHuman = isHumanPiiHandle(rawId) || m?.type === "user";
6900
+ const safeId = redactParticipantPii(rawId);
6901
+ const peer = !isHuman ? peerById.get(rawId) : undefined;
6902
+ const rawDisplay = m?.display_name ? String(m.display_name).trim() : peer?.name ? String(peer.name).trim() : "";
6903
+ const safeDisplay = rawDisplay && !isHumanPiiHandle(rawDisplay) ? rawDisplay : safeId;
6904
+ const handleBadge = isHuman ? `(${safeId})` : `(@${safeId})`;
6905
+ const roleBadge = m?.role ? ` [${m.role}]` : "";
6906
+ const onlineVal = typeof m?.online === "boolean" ? m.online : peer?.online;
6907
+ const onlineBadge = typeof onlineVal === "boolean" ? ` (${onlineVal ? "online" : "offline"})` : "";
6908
+ const caps = Array.isArray(peer?.capabilities) && peer.capabilities.length > 0 ? peer.capabilities : Array.isArray(m?.capabilities) ? m.capabilities : [];
6909
+ const capsBadge = caps.length > 0 ? ` {capabilities: ${caps.join(", ")}}` : "";
6910
+ return `\u2022 ${safeDisplay} ${handleBadge}${roleBadge}${onlineBadge}${capsBadge}`;
6911
+ }).join(`
5668
6912
  `);
5669
- return { content: [{ type: "text", text: `${members.length} members in ${chat_id.slice(0, 8)}:
6913
+ return { content: [{ type: "text", text: `${members.length} members in ${chat_id}:
5670
6914
  ${list}` }] };
5671
6915
  }
5672
6916
  return { content: [{ type: "text", text: `Failed to list members (${r.status})` }] };
@@ -5682,7 +6926,7 @@ ${list}` }] };
5682
6926
  const time = m.timestamp ? new Date(m.timestamp).toLocaleString() : "?";
5683
6927
  const rawContent = String(m.content ?? "");
5684
6928
  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}`;
6929
+ let line = `[${time}] ${redactParticipantPii(m.sender_id || "?")}: ${body}`;
5686
6930
  const atts = Array.isArray(m.attachments) ? m.attachments : [];
5687
6931
  for (const a of atts) {
5688
6932
  if (!a?.url)
@@ -5765,7 +7009,7 @@ ${formatHistoryMessage(exact, true)}` }] };
5765
7009
  return { content: [{ type: "text", text: `${msgs.length} messages:
5766
7010
  ${list}` }] };
5767
7011
  }
5768
- return { content: [{ type: "text", text: `Failed to get history (${r.status})` }] };
7012
+ return { content: [{ type: "text", text: `Failed to get history (${r.status})` }], isError: true };
5769
7013
  } catch (e) {
5770
7014
  return { content: [{ type: "text", text: `Error: ${e}` }] };
5771
7015
  }
@@ -6121,7 +7365,7 @@ ${list}` }] };
6121
7365
  }
6122
7366
  };
6123
7367
  server.setRequestHandler(CallToolRequestSchema, (request) => serializeCall(() => handleToolCall(request)));
6124
- var mentionTsFile = join6(configDir, `mention-ts-${AGENT_ID}.json`);
7368
+ var mentionTsFile = join8(configDir, `mention-ts-${AGENT_ID}.json`);
6125
7369
  function loadMentionTimestamps() {
6126
7370
  return loadCursor(mentionTsFile, safeStderrWrite);
6127
7371
  }
@@ -6268,6 +7512,7 @@ function clearFinishedHiddenIdentityGamesFromMessage(data) {
6268
7512
  }
6269
7513
  }
6270
7514
  }
7515
+ var processAgentMessageDedup = new MessageDedup;
6271
7516
  function deliverySource(data) {
6272
7517
  return typeof data?.__source === "string" ? data.__source : "live";
6273
7518
  }
@@ -6275,7 +7520,9 @@ function recordOrSkipDeliveredMessage(data, slot = activeSlot) {
6275
7520
  const key = messageDedupKey(data);
6276
7521
  if (!key || !slot)
6277
7522
  return false;
6278
- const skip = slot.messageDedup.recordOrSkip(key);
7523
+ const slotSkip = slot.messageDedup.recordOrSkip(key);
7524
+ const agentSkip = slot.agentId ? processAgentMessageDedup.recordOrSkip(`${slot.agentId}:${key}`) : false;
7525
+ const skip = slotSkip || agentSkip;
6279
7526
  if (skip) {
6280
7527
  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
7528
  `);
@@ -6359,11 +7606,27 @@ function syncOpenBoundSessions() {
6359
7606
  if (!boundProf || profileSlots.has(boundProf))
6360
7607
  continue;
6361
7608
  const boundPath = nameToPath(boundProf);
6362
- if (!existsSync7(boundPath))
7609
+ if (!existsSync8(boundPath))
6363
7610
  continue;
6364
7611
  try {
6365
7612
  const candidate = readIdentityProfile(boundPath);
6366
7613
  validateIdentityProfile(candidate, boundPath);
7614
+ const sess = { sessionId: cid, runtime: "antigravity" };
7615
+ const existingByAgent = findSlotByAgentId(candidate.agent_id);
7616
+ if (existingByAgent) {
7617
+ const existingSid = existingByAgent.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, existingByAgent.profileName);
7618
+ if (!existingSid || existingSid === cid) {
7619
+ upgradeAliasSlotInPlace(existingByAgent, boundProf, boundPath, candidate, sess);
7620
+ acquireAgentLock({
7621
+ lockDir,
7622
+ agentId: existingByAgent.agentId,
7623
+ profileName: boundProf,
7624
+ sessionId: cid,
7625
+ runtime: "antigravity"
7626
+ });
7627
+ }
7628
+ continue;
7629
+ }
6367
7630
  const lock = checkAgentLock({
6368
7631
  lockDir,
6369
7632
  agentId: candidate.agent_id,
@@ -6372,7 +7635,6 @@ function syncOpenBoundSessions() {
6372
7635
  });
6373
7636
  if (lock.locked)
6374
7637
  continue;
6375
- const sess = { sessionId: cid, runtime: "antigravity" };
6376
7638
  acquireAgentLock({
6377
7639
  lockDir,
6378
7640
  agentId: candidate.agent_id,
@@ -6527,7 +7789,7 @@ function connectWS(slot = activeSlot) {
6527
7789
  }
6528
7790
  const truncatedMsgs = trimmed.length < msgs.length;
6529
7791
  if (trimmed.length > 0) {
6530
- const context = trimmed.map((m) => `${m.sender_id}: ${m.content}${formatWakeAttachments(m.attachments)}`).join(`
7792
+ const context = trimmed.map((m) => `${redactParticipantPii(m.sender_id || "?")}: ${m.content}${formatWakeAttachments(m.attachments)}`).join(`
6531
7793
  `);
6532
7794
  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
7795
  contextPrefix = `${note}
@@ -6575,15 +7837,15 @@ ${context}
6575
7837
  if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
6576
7838
  (async () => {
6577
7839
  try {
6578
- const { readFileSync: readFileSync8, existsSync: existsSync8 } = await import("fs");
6579
- const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync8);
7840
+ const { readFileSync: readFileSync12, existsSync: existsSync9 } = await import("fs");
7841
+ const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync9);
6580
7842
  let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
6581
7843
  if (!agentId) {
6582
7844
  agentId = await resolveGrokAgentId({
6583
7845
  explicitId: "",
6584
7846
  agentschatName: slot.profile.display_name || slot.agentId,
6585
7847
  listAgents: async () => {
6586
- const gwcfg = JSON.parse(readFileSync8(gwPath, "utf8"));
7848
+ const gwcfg = JSON.parse(readFileSync12(gwPath, "utf8"));
6587
7849
  const token = grokBearerFromGatewayConfig(gwcfg);
6588
7850
  const port = grokPortFromGatewayConfig(gwcfg);
6589
7851
  const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
@@ -6613,7 +7875,8 @@ ${context}
6613
7875
  targetSessionId
6614
7876
  });
6615
7877
  } 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 : "") || "";
7878
+ const isZcodeSid = (sid) => sid.startsWith("sess_");
7879
+ const zcodeSid = findBoundSessionForProfile(configDir, slotProfName, isZcodeSid) || resolveSessionForAgent(slot.agentId, { configDir, filter: isZcodeSid })?.sessionId || (slotRuntime === "zcode" ? slot.runtimeSession?.sessionId : "") || "";
6617
7880
  if (zcodeSid) {
6618
7881
  fireZcodeWake(data, {
6619
7882
  sessionId: zcodeSid,
@@ -6626,7 +7889,8 @@ ${context}
6626
7889
  });
6627
7890
  }
6628
7891
  } 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;
7892
+ const isDshSid = (sid) => sid.startsWith("session-");
7893
+ const dshSid = findBoundSessionForProfile(configDir, slotProfName, isDshSid) || resolveSessionForAgent(slot.agentId, { configDir, filter: isDshSid })?.sessionId || (slotRuntime === "dsh" ? slot.runtimeSession?.sessionId : "") || undefined;
6630
7894
  const dshWakeUrl = process.env.DSH_WAKE_URL || process.env.AGENTSCHAT_DSH_WAKE_URL || "http://127.0.0.1:8799/wake";
6631
7895
  fireWake(data, {
6632
7896
  url: dshWakeUrl,
@@ -6641,14 +7905,28 @@ ${context}
6641
7905
  const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
6642
7906
  if (!agyHost && !lsAddress)
6643
7907
  return;
7908
+ 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
7909
  const allBinds = loadSessionBinds(configDir);
6645
- let targetCid = findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) || (slotRuntime === "antigravity" ? slot.runtimeSession?.sessionId : "") || "";
7910
+ 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
7911
  if (!targetCid && agyHost) {
6647
7912
  if (agyHost.openConversations.length === 1) {
6648
- targetCid = agyHost.openConversations[0];
7913
+ const soleCid = agyHost.openConversations[0];
7914
+ const soleBoundProf = allBinds[soleCid];
7915
+ let soleMatchesAgent = false;
7916
+ if (soleBoundProf) {
7917
+ const p = nameToPath(soleBoundProf);
7918
+ if (existsSync8(p)) {
7919
+ try {
7920
+ soleMatchesAgent = readIdentityProfile(p)?.agent_id === slot.agentId;
7921
+ } catch {}
7922
+ }
7923
+ }
7924
+ if (!soleBoundProf || soleBoundProf === slotProfName || soleMatchesAgent) {
7925
+ targetCid = soleCid;
7926
+ }
6649
7927
  } else if (agyHost.openConversations.length > 1) {
6650
- const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] === slotProfName);
6651
- targetCid = unboundOrSame || agyHost.openConversations[0];
7928
+ 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).
7929
+ `);
6652
7930
  }
6653
7931
  }
6654
7932
  if (targetCid && csrfToken) {
@@ -6825,9 +8103,21 @@ async function checkVersionStaleness() {
6825
8103
  }
6826
8104
  }
6827
8105
  async function main() {
8106
+ if (codexIdentity) {
8107
+ const status = await getOnboardingStatus(REST_URL, AGENT_ID, TOKEN);
8108
+ if (status.authentication !== "ok")
8109
+ throw new Error("Codex tool authentication failed; bridge transport alone is not tool readiness");
8110
+ }
6828
8111
  installStdioLifecycleGuards();
6829
8112
  if (!toolOnlyMode) {
6830
8113
  syncOpenBoundSessions();
8114
+ if (process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL) || Boolean(process.env.ANTIGRAVITY_LS_ADDRESS) || Boolean(discoverAntigravityHost())) {
8115
+ const agySyncTimer = setInterval(() => {
8116
+ if (!shuttingDown)
8117
+ syncOpenBoundSessions();
8118
+ }, 15000);
8119
+ agySyncTimer.unref?.();
8120
+ }
6831
8121
  }
6832
8122
  if (anonymousMode && profileSlots.size === 0) {
6833
8123
  process.stderr.write(`[agentchat] Anonymous \u2014 not connecting to the hub.