agentschat-mcp 0.36.12 → 0.36.14

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
@@ -32,15 +32,15 @@ async function getOnboardingStatus(base, agentId, token, request = fetch) {
32
32
  return result;
33
33
  result.authentication = "ok";
34
34
  result.claimed = data.claimed;
35
- result.next_step = data.claimed ? "verify_reply" : "claim_agent";
35
+ result.next_step = data.claimed ? "verify_reply" : "join_public_chat";
36
36
  } catch {}
37
37
  return result;
38
38
  }
39
39
  function claimSummary(status) {
40
40
  if (status.claimed === true)
41
- return "Claimed: yes — verify an actual DM/reply before marking setup complete.";
41
+ return "Claimed: yes — verify an actual message/reply in the authorized conversation before marking setup complete.";
42
42
  if (status.claimed === false)
43
- return `Claimed: NO — open ${status.claim_url} and enter the token from your private profile. Claiming unlocks DMs and private channels.`;
43
+ return `Claimed: NO — public group chat can proceed within the authorized scope and service limits. Claiming unlocks DMs, private channels and owner features: open ${status.claim_url} and enter the token from your private profile.`;
44
44
  return `Claimed: unknown — ownership could not be verified. Check the service and account; do not register a replacement. Claim entry: ${status.claim_url}`;
45
45
  }
46
46
 
@@ -416,23 +416,12 @@ function grokBindApplies(input) {
416
416
  // src/terms.ts
417
417
  var TERMS_URL = "https://agents-chat.com/terms";
418
418
  var TERMS_VERSION = "2026-05-29";
419
- function isTruthy(v) {
420
- return typeof v === "string" && /^(1|true|yes)$/i.test(v.trim());
421
- }
422
- function decideTermsConsent(i) {
423
- if (i.acceptFlag || isTruthy(i.acceptEnv)) {
424
- return { mode: "accepted", version: TERMS_VERSION };
425
- }
426
- return {
427
- mode: "refused",
428
- message: `registering an agent requires accepting the AgentsChat terms (version ${TERMS_VERSION}).
429
- ` + ` Read them: ${TERMS_URL}
430
- ` + ` Then re-run with: --accept-terms (or AGENTSCHAT_ACCEPT_TERMS=1)
431
- ` + ` Prefer a browser? Register at https://agents-chat.com/join and pass the
432
- ` + ` resulting credentials via --profile <name> or AGENTCHAT_TOKEN=<token>.
433
- ` + ` Refusing to send acceptance you did not give — no account was created.`
434
- };
435
- }
419
+ var TERMS_NOTICE = {
420
+ url: TERMS_URL,
421
+ version: TERMS_VERSION,
422
+ requires_acceptance: false
423
+ };
424
+ var TERMS_NOTICE_TEXT = `Terms notice: ${TERMS_URL} (version ${TERMS_VERSION}). ` + "Registration continues without an acceptance prompt.";
436
425
 
437
426
  // src/tool-annotations.ts
438
427
  var R = { readOnlyHint: true, openWorldHint: true };
@@ -502,6 +491,8 @@ var TOOL_ANNOTATIONS = {
502
491
  okr_add_task_comment: W,
503
492
  okr_set_links: W,
504
493
  switch_profile: W,
494
+ connect_profile: W,
495
+ disconnect_profile: W,
505
496
  list_channel_docs: R,
506
497
  get_channel_doc: R,
507
498
  upsert_channel_doc: W,
@@ -672,11 +663,493 @@ async function fireGrokWake(msg, cfg) {
672
663
  }
673
664
  }
674
665
  }
666
+ function buildWakePrompt(msg) {
667
+ const content = typeof msg.content === "string" ? redactSecrets2(msg.content.slice(0, WAKE_CONTENT_MAX)) : "";
668
+ const channel = msg.channel_id ?? "?";
669
+ const sender = msg.sender_id ?? "someone";
670
+ const msgId = msg.id ?? msg.message_id ?? "";
671
+ const isDm = channel.startsWith("dm-");
672
+ const where = isDm ? `私聊 (${channel})` : `频道 ${channel}`;
673
+ return `[AgentsChat] ${sender} 在${where}给你发了消息` + (content ? `:"${content}"` : "。") + ` (channel_id=${channel}` + (msgId ? `, message_id=${msgId}` : "") + ` —— 请调用 get_history 查看上下文并用 reply 回复,然后用 mark_read 标记已读)`;
674
+ }
675
+ async function fireAntigravityWake(msg, cfg) {
676
+ const log = cfg.logger ?? (() => {});
677
+ const conversationId = (cfg.conversationId ?? "").trim();
678
+ const csrfToken = (cfg.csrfToken ?? "").trim();
679
+ if (!conversationId || !csrfToken) {
680
+ log(`[agentchat] antigravity wake: missing conversationId or csrfToken, skipping`);
681
+ return false;
682
+ }
683
+ const addresses = [];
684
+ if (cfg.lsAddress && cfg.lsAddress.trim()) {
685
+ addresses.push(cfg.lsAddress.trim());
686
+ }
687
+ for (const p of cfg.ports ?? []) {
688
+ if (typeof p === "number" && p > 0) {
689
+ const addr = `127.0.0.1:${p}`;
690
+ if (!addresses.includes(addr))
691
+ addresses.push(addr);
692
+ }
693
+ }
694
+ if (addresses.length === 0) {
695
+ log(`[agentchat] antigravity wake: no language_server ports found, skipping`);
696
+ return false;
697
+ }
698
+ const prompt = cfg.promptOverride ?? buildWakePrompt(msg);
699
+ const body = JSON.stringify({
700
+ metadata: {
701
+ ideName: "antigravity",
702
+ apiKey: "",
703
+ locale: "en",
704
+ ideVersion: "1.23.2",
705
+ extensionName: "antigravity"
706
+ },
707
+ recipient: conversationId,
708
+ message: prompt
709
+ });
710
+ const f = cfg.fetchImpl ?? fetch;
711
+ for (const addr of addresses) {
712
+ const url = `http://${addr}/exa.language_server_pb.LanguageServerService/SendAgentMessage`;
713
+ const ctrl = new AbortController;
714
+ const t = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 5000);
715
+ try {
716
+ const res = await f(url, {
717
+ method: "POST",
718
+ headers: {
719
+ "Content-Type": "application/json",
720
+ "Connect-Protocol-Version": "1",
721
+ "x-codeium-csrf-token": csrfToken
722
+ },
723
+ body,
724
+ signal: ctrl.signal
725
+ });
726
+ if (res.ok) {
727
+ return true;
728
+ }
729
+ log(`[agentchat] antigravity wake POST ${url} → HTTP ${res.status}`);
730
+ } catch {} finally {
731
+ clearTimeout(t);
732
+ }
733
+ }
734
+ log(`[agentchat] antigravity wake: all candidate ports (${addresses.join(", ")}) failed for ${conversationId}`);
735
+ return false;
736
+ }
737
+ var zcodeSessionQueues = new Map;
738
+ async function resolveZcodeCommand(explicitBin) {
739
+ const fromArg = (explicitBin ?? process.env.ZCODE_BIN ?? "").trim();
740
+ if (fromArg) {
741
+ if (fromArg.endsWith(".cjs") || fromArg.endsWith(".js")) {
742
+ return { cmd: "node", prefixArgs: [fromArg] };
743
+ }
744
+ return { cmd: fromArg, prefixArgs: [] };
745
+ }
746
+ const macAppBundleCjs = "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs";
747
+ try {
748
+ const { existsSync: existsSync2 } = await import("node:fs");
749
+ if (existsSync2(macAppBundleCjs)) {
750
+ return { cmd: "node", prefixArgs: [macAppBundleCjs] };
751
+ }
752
+ } catch {}
753
+ return { cmd: "zcode", prefixArgs: [] };
754
+ }
755
+ function fireZcodeWake(msg, cfg) {
756
+ const log = cfg.logger ?? (() => {});
757
+ const sessionId = (cfg.sessionId ?? "").trim();
758
+ if (!sessionId) {
759
+ log(`[agentchat] zcode wake: missing sessionId, skipping`);
760
+ return Promise.resolve(false);
761
+ }
762
+ const prompt = cfg.promptOverride ?? buildWakePrompt(msg);
763
+ const prev = zcodeSessionQueues.get(sessionId) ?? Promise.resolve();
764
+ let succeeded = false;
765
+ const runTurn = async () => {
766
+ try {
767
+ const { cmd, prefixArgs } = await resolveZcodeCommand(cfg.zcodeBin);
768
+ const args = [...prefixArgs, "-p", prompt, "--resume", sessionId];
769
+ if (cfg.workspacePath && cfg.workspacePath.trim()) {
770
+ args.push("--cwd", cfg.workspacePath.trim());
771
+ }
772
+ const env = {
773
+ ...process.env,
774
+ AGENTSCHAT_TOOL_ONLY: "1",
775
+ AGENTSCHAT_LOCK_OWNER_PID: String(cfg.lockOwnerPid ?? process.pid),
776
+ ZCODE_SESSION_ID: sessionId,
777
+ ...cfg.profileName ? { AGENTSCHAT_PROFILE: cfg.profileName } : {}
778
+ };
779
+ const timeoutMs = cfg.timeoutMs ?? 180000;
780
+ if (cfg.runCommandImpl) {
781
+ const res = await cfg.runCommandImpl(cmd, args, { cwd: cfg.workspacePath, env, timeoutMs });
782
+ succeeded = res.code === 0;
783
+ if (!succeeded) {
784
+ log(`[agentchat] zcode wake (${sessionId}) exited with code ${res.code}${res.stderr ? `: ${res.stderr.slice(0, 200)}` : ""}`);
785
+ }
786
+ return;
787
+ }
788
+ const { spawn } = await import("node:child_process");
789
+ await new Promise((resolve2) => {
790
+ const child = spawn(cmd, args, {
791
+ cwd: cfg.workspacePath || process.cwd(),
792
+ env,
793
+ stdio: ["ignore", "ignore", "pipe"]
794
+ });
795
+ let stderr = "";
796
+ child.stderr?.on("data", (chunk) => {
797
+ if (stderr.length < 500)
798
+ stderr += String(chunk);
799
+ });
800
+ const timer = setTimeout(() => {
801
+ try {
802
+ child.kill("SIGTERM");
803
+ } catch {}
804
+ }, timeoutMs);
805
+ child.on("error", (err) => {
806
+ clearTimeout(timer);
807
+ log(`[agentchat] zcode wake spawn error (${sessionId}): ${err}`);
808
+ resolve2();
809
+ });
810
+ child.on("close", (code) => {
811
+ clearTimeout(timer);
812
+ succeeded = code === 0;
813
+ if (!succeeded) {
814
+ log(`[agentchat] zcode wake (${sessionId}) exited code=${code}${stderr ? `: ${stderr.trim().slice(0, 200)}` : ""}`);
815
+ }
816
+ resolve2();
817
+ });
818
+ });
819
+ } catch (e) {
820
+ log(`[agentchat] zcode wake failed (${sessionId}): ${e}`);
821
+ }
822
+ };
823
+ const next = prev.then(runTurn, runTurn);
824
+ zcodeSessionQueues.set(sessionId, next);
825
+ return next.then(() => {
826
+ if (zcodeSessionQueues.get(sessionId) === next) {
827
+ zcodeSessionQueues.delete(sessionId);
828
+ }
829
+ return succeeded;
830
+ });
831
+ }
832
+
833
+ // src/session-bind.ts
834
+ import { createHash } from "node:crypto";
835
+ import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, unlinkSync as unlinkSync2 } from "node:fs";
836
+ import { tmpdir } from "node:os";
837
+ import { join as join3 } from "node:path";
838
+ import { spawnSync } from "node:child_process";
839
+
840
+ // src/profile-store.ts
841
+ import { existsSync as existsSync2, writeFileSync, renameSync, chmodSync, unlinkSync, statSync } from "fs";
842
+ var defaultWarn = (m) => process.stderr.write(m);
843
+ function safeWriteProfile(path, data, warn = defaultWarn) {
844
+ const tmp = path + ".tmp";
845
+ try {
846
+ if (existsSync2(tmp))
847
+ unlinkSync(tmp);
848
+ } catch (e) {
849
+ warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
850
+ `);
851
+ }
852
+ writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
853
+ renameSync(tmp, path);
854
+ try {
855
+ chmodSync(path, 384);
856
+ } catch (e) {
857
+ warn(`[agentchat] WARNING: could not chmod ${path} to 0600: ${e}
858
+ `);
859
+ }
860
+ try {
861
+ const mode = statSync(path).mode & 511;
862
+ if (mode !== 384) {
863
+ warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
864
+ `);
865
+ }
866
+ } catch (e) {
867
+ warn(`[agentchat] WARNING: could not verify permissions of ${path}: ${e}
868
+ `);
869
+ }
870
+ }
871
+
872
+ // src/session-bind.ts
873
+ var DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
874
+ var LEGACY_AGY_BINDS_FILENAME = "agy-binds.json";
875
+ function isPidAlive(pid) {
876
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
877
+ return false;
878
+ try {
879
+ process.kill(pid, 0);
880
+ return true;
881
+ } catch (e) {
882
+ if (e && typeof e === "object" && e.code === "EPERM")
883
+ return true;
884
+ return false;
885
+ }
886
+ }
887
+ function resolveLockDir(homeDir, env = process.env) {
888
+ const explicit = env.AGENTSCHAT_LOCK_DIR?.trim();
889
+ if (explicit)
890
+ return explicit;
891
+ const hash = createHash("sha256").update(homeDir || ".").digest("hex").slice(0, 12);
892
+ const baseTmp = process.platform === "win32" ? tmpdir() : "/tmp";
893
+ return join3(baseTmp, `agentschat-locks-${hash}`);
894
+ }
895
+ function lockFilePath(lockDir, agentId) {
896
+ const safe = String(agentId || "").trim().replace(/[^a-zA-Z0-9_-]/g, "_");
897
+ return join3(lockDir, `${safe}.lock`);
898
+ }
899
+ function readAgentLock(lockDir, agentId) {
900
+ if (!agentId)
901
+ return null;
902
+ const file = lockFilePath(lockDir, agentId);
903
+ if (!existsSync3(file))
904
+ return null;
905
+ try {
906
+ const raw = JSON.parse(readFileSync3(file, "utf8"));
907
+ if (!raw || typeof raw !== "object" || typeof raw.pid !== "number" || typeof raw.agentId !== "string") {
908
+ return null;
909
+ }
910
+ return raw;
911
+ } catch {
912
+ return null;
913
+ }
914
+ }
915
+ function checkAgentLock(opts) {
916
+ const { lockDir, agentId } = opts;
917
+ const currentPid = opts.currentPid ?? process.pid;
918
+ if (!agentId)
919
+ return { locked: false };
920
+ const record = readAgentLock(lockDir, agentId);
921
+ if (!record)
922
+ return { locked: false };
923
+ if (!isPidAlive(record.pid)) {
924
+ try {
925
+ unlinkSync2(lockFilePath(lockDir, agentId));
926
+ } catch {}
927
+ return { locked: false, stale: true };
928
+ }
929
+ if (record.pid === currentPid)
930
+ return { locked: false, holder: record };
931
+ if (opts.lockOwnerPid && record.pid === opts.lockOwnerPid)
932
+ return { locked: false, holder: record };
933
+ if (opts.currentSessionId && record.sessionId && opts.currentSessionId === record.sessionId) {
934
+ return { locked: false, holder: record };
935
+ }
936
+ return { locked: true, holder: record };
937
+ }
938
+ function acquireAgentLock(opts) {
939
+ if (!opts.agentId)
940
+ return null;
941
+ const record = {
942
+ pid: opts.currentPid ?? process.pid,
943
+ agentId: opts.agentId,
944
+ profileName: opts.profileName ?? null,
945
+ sessionId: opts.sessionId ?? null,
946
+ runtime: opts.runtime ?? "mcp",
947
+ updatedAt: new Date().toISOString()
948
+ };
949
+ try {
950
+ mkdirSync(opts.lockDir, { recursive: true, mode: 448 });
951
+ safeWriteProfile(lockFilePath(opts.lockDir, opts.agentId), record);
952
+ return record;
953
+ } catch {
954
+ return null;
955
+ }
956
+ }
957
+ function releaseAgentLock(opts) {
958
+ if (!opts.agentId)
959
+ return false;
960
+ const currentPid = opts.currentPid ?? process.pid;
961
+ const existing = readAgentLock(opts.lockDir, opts.agentId);
962
+ if (!existing)
963
+ return false;
964
+ const samePid = existing.pid === currentPid;
965
+ const sameSession = Boolean(opts.currentSessionId && existing.sessionId && opts.currentSessionId === existing.sessionId);
966
+ const dead = !isPidAlive(existing.pid);
967
+ if (!samePid && !sameSession && !dead)
968
+ return false;
969
+ try {
970
+ unlinkSync2(lockFilePath(opts.lockDir, opts.agentId));
971
+ return true;
972
+ } catch {
973
+ return false;
974
+ }
975
+ }
976
+ function parseSessionBinds(raw) {
977
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
978
+ return {};
979
+ const out = {};
980
+ for (const [k, v] of Object.entries(raw)) {
981
+ const key = k.trim();
982
+ if (!key)
983
+ continue;
984
+ if (typeof v === "string" && v.trim()) {
985
+ out[key] = v.trim();
986
+ } else if (v && typeof v === "object" && typeof v.profile === "string" && v.profile.trim()) {
987
+ out[key] = v.profile.trim();
988
+ }
989
+ }
990
+ return out;
991
+ }
992
+ function loadSessionBinds(configDir) {
993
+ const merged = {};
994
+ for (const filename of [LEGACY_AGY_BINDS_FILENAME, DEFAULT_SESSION_BINDS_FILENAME]) {
995
+ const path = join3(configDir, filename);
996
+ if (!existsSync3(path))
997
+ continue;
998
+ try {
999
+ Object.assign(merged, parseSessionBinds(JSON.parse(readFileSync3(path, "utf8"))));
1000
+ } catch {}
1001
+ }
1002
+ return merged;
1003
+ }
1004
+ function saveSessionBind(configDir, sessionId, profileName) {
1005
+ const sid = sessionId.trim();
1006
+ const prof = profileName.trim();
1007
+ if (!sid || !prof)
1008
+ return;
1009
+ const path = join3(configDir, DEFAULT_SESSION_BINDS_FILENAME);
1010
+ let current = {};
1011
+ if (existsSync3(path)) {
1012
+ try {
1013
+ current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
1014
+ } catch {}
1015
+ }
1016
+ current[sid] = prof;
1017
+ mkdirSync(configDir, { recursive: true });
1018
+ safeWriteProfile(path, current);
1019
+ }
1020
+ function removeSessionBind(configDir, sessionId) {
1021
+ const sid = sessionId.trim();
1022
+ if (!sid)
1023
+ return false;
1024
+ let removed = false;
1025
+ for (const filename of [DEFAULT_SESSION_BINDS_FILENAME, LEGACY_AGY_BINDS_FILENAME]) {
1026
+ const path = join3(configDir, filename);
1027
+ if (!existsSync3(path))
1028
+ continue;
1029
+ try {
1030
+ const current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
1031
+ if (sid in current) {
1032
+ delete current[sid];
1033
+ safeWriteProfile(path, current);
1034
+ removed = true;
1035
+ }
1036
+ } catch {}
1037
+ }
1038
+ return removed;
1039
+ }
1040
+ function findBoundSessionForProfile(configDir, profileName, filter) {
1041
+ if (!profileName)
1042
+ return null;
1043
+ const target = profileName.trim();
1044
+ if (!target)
1045
+ return null;
1046
+ const binds = loadSessionBinds(configDir);
1047
+ const matches = [];
1048
+ for (const [sid, prof] of Object.entries(binds)) {
1049
+ if (prof === target && (!filter || filter(sid)))
1050
+ matches.push(sid);
1051
+ }
1052
+ return matches.length > 0 ? matches[matches.length - 1] : null;
1053
+ }
1054
+ function detectRuntimeSession(env = process.env, meta) {
1055
+ const zcodeCtx = meta?.["com.zcode/request-context"];
1056
+ const metaSessionId = typeof meta?.session_id === "string" && meta.session_id.trim() || typeof zcodeCtx?.session_id === "string" && zcodeCtx.session_id.trim() || "";
1057
+ if (metaSessionId) {
1058
+ const workspacePath = typeof meta?.workspace_path === "string" && meta.workspace_path.trim() || typeof zcodeCtx?.workspace_path === "string" && zcodeCtx.workspace_path.trim() || undefined;
1059
+ return { sessionId: metaSessionId, runtime: "zcode", ...workspacePath ? { workspacePath } : {} };
1060
+ }
1061
+ const zcodeEnvSid = env.ZCODE_SESSION_ID?.trim();
1062
+ if (zcodeEnvSid) {
1063
+ const workspacePath = env.ZCODE_PROJECT_DIR?.trim() || undefined;
1064
+ return { sessionId: zcodeEnvSid, runtime: "zcode", ...workspacePath ? { workspacePath } : {} };
1065
+ }
1066
+ const agySid = env.ANTIGRAVITY_CONVERSATION_ID?.trim();
1067
+ if (agySid) {
1068
+ return { sessionId: agySid, runtime: "antigravity" };
1069
+ }
1070
+ const claudeSid = (env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || "").trim();
1071
+ if (claudeSid) {
1072
+ const workspacePath = env.CLAUDE_PROJECT_DIR?.trim() || undefined;
1073
+ return { sessionId: claudeSid, runtime: "claude-code", ...workspacePath ? { workspacePath } : {} };
1074
+ }
1075
+ const explicitSid = (env.AGENTSCHAT_SESSION_ID || env.AGENTCHAT_SESSION_ID || "").trim();
1076
+ if (explicitSid) {
1077
+ return { sessionId: explicitSid, runtime: "custom" };
1078
+ }
1079
+ return null;
1080
+ }
1081
+ var cachedAgyHost = null;
1082
+ function discoverAntigravityHost(opts) {
1083
+ const now = Date.now();
1084
+ const cacheMs = opts?.cacheMs ?? 5000;
1085
+ if (cachedAgyHost && now - cachedAgyHost.at < cacheMs)
1086
+ return cachedAgyHost.info;
1087
+ try {
1088
+ let pid = opts?.currentPid ?? process.pid;
1089
+ let lsPid = 0;
1090
+ let lsCmd = "";
1091
+ for (let hop = 0;hop < 3 && pid > 1; hop++) {
1092
+ const ps = spawnSync("ps", ["-p", String(pid), "-o", "ppid=,command="], { encoding: "utf8", timeout: 1000 });
1093
+ if (ps.status !== 0 || !ps.stdout)
1094
+ break;
1095
+ const line = ps.stdout.trim().split(/\r?\n/)[0]?.trim() || "";
1096
+ const m = line.match(/^(\d+)\s+(.*)$/);
1097
+ if (!m)
1098
+ break;
1099
+ const ppid = Number(m[1]);
1100
+ const cmd = m[2];
1101
+ if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test")))
1102
+ break;
1103
+ if (cmd.includes("language_server") && cmd.includes("--csrf_token")) {
1104
+ lsPid = pid;
1105
+ lsCmd = cmd;
1106
+ break;
1107
+ }
1108
+ pid = ppid;
1109
+ }
1110
+ if (!lsPid) {
1111
+ cachedAgyHost = { at: now, info: null };
1112
+ return null;
1113
+ }
1114
+ const csrfMatch = lsCmd.match(/--csrf_token[=\s]+([^\s]+)/);
1115
+ const csrfToken = csrfMatch?.[1]?.trim() || "";
1116
+ if (!csrfToken) {
1117
+ cachedAgyHost = { at: now, info: null };
1118
+ return null;
1119
+ }
1120
+ const lsof = spawnSync("lsof", ["-Pan", "-p", String(lsPid)], { encoding: "utf8", timeout: 1500 });
1121
+ const ports = [];
1122
+ const openConversations = [];
1123
+ if (lsof.status === 0 && lsof.stdout) {
1124
+ for (const line of lsof.stdout.split(/\r?\n/)) {
1125
+ const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
1126
+ if (portMatch) {
1127
+ const p = Number(portMatch[1]);
1128
+ if (p > 0 && !ports.includes(p))
1129
+ ports.push(p);
1130
+ }
1131
+ const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/);
1132
+ if (presMatch) {
1133
+ const cid = presMatch[1];
1134
+ if (!openConversations.includes(cid))
1135
+ openConversations.push(cid);
1136
+ }
1137
+ }
1138
+ }
1139
+ ports.sort((a, b) => b - a);
1140
+ const info = { lsPid, csrfToken, ports, openConversations };
1141
+ cachedAgyHost = { at: now, info };
1142
+ return info;
1143
+ } catch {
1144
+ cachedAgyHost = { at: now, info: null };
1145
+ return null;
1146
+ }
1147
+ }
675
1148
  // package.json
676
1149
  var package_default = {
677
1150
  name: "agentschat-mcp",
678
1151
  mcpName: "io.github.swswordholy-tech/agentschat-mcp",
679
- version: "0.36.12",
1152
+ version: "0.36.14",
680
1153
  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.",
681
1154
  type: "module",
682
1155
  bin: {
@@ -696,8 +1169,11 @@ var package_default = {
696
1169
  typecheck: "tsc --noEmit",
697
1170
  build: "bun scripts/build.mjs",
698
1171
  "check:version": "bun scripts/check-version-sync.mjs",
699
- verify: "bun run build && bun scripts/check-version-sync.mjs && tsc --noEmit && bun test",
700
- prepublishOnly: "bun run build"
1172
+ "check:docs": "bun scripts/sync-doc-versions.mjs --check",
1173
+ "sync:docs": "bun scripts/sync-doc-versions.mjs --write",
1174
+ version: "bun run build && bun scripts/sync-doc-versions.mjs --write --git-add",
1175
+ verify: "bun run build && bun scripts/check-version-sync.mjs && bun scripts/sync-doc-versions.mjs --check && tsc --noEmit && bun test",
1176
+ prepublishOnly: "bun run check:version && bun run check:docs && bun test tests/doc-versions.test.ts tests/packaging.test.ts"
701
1177
  },
702
1178
  keywords: [
703
1179
  "agentchat",
@@ -749,6 +1225,7 @@ var package_default = {
749
1225
  "src/identity.ts",
750
1226
  "src/profile-selection.ts",
751
1227
  "src/grok-bind.ts",
1228
+ "src/session-bind.ts",
752
1229
  "src/tool-annotations.ts",
753
1230
  "src/identity-guard.ts",
754
1231
  "src/terms.ts",
@@ -789,31 +1266,31 @@ import {
789
1266
  CallToolRequestSchema,
790
1267
  ListToolsRequestSchema
791
1268
  } from "@modelcontextprotocol/sdk/types.js";
792
- import { readFileSync as readFileSync4, existsSync as existsSync3, writeFileSync as writeFileSync3, mkdirSync, readdirSync } from "fs";
793
- import { join as join3, dirname } from "path";
1269
+ import { readFileSync as readFileSync5, existsSync as existsSync5, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, readdirSync as readdirSync2 } from "fs";
1270
+ import { join as join4, dirname } from "path";
794
1271
 
795
1272
  // src/profile-store.ts
796
- import { existsSync as existsSync2, writeFileSync, renameSync, chmodSync, unlinkSync, statSync } from "fs";
797
- var defaultWarn = (m) => process.stderr.write(m);
798
- function safeWriteProfile(path, data, warn = defaultWarn) {
1273
+ import { existsSync as existsSync4, writeFileSync as writeFileSync2, renameSync as renameSync2, chmodSync as chmodSync2, unlinkSync as unlinkSync3, statSync as statSync2 } from "fs";
1274
+ var defaultWarn2 = (m) => process.stderr.write(m);
1275
+ function safeWriteProfile2(path, data, warn = defaultWarn2) {
799
1276
  const tmp = path + ".tmp";
800
1277
  try {
801
- if (existsSync2(tmp))
802
- unlinkSync(tmp);
1278
+ if (existsSync4(tmp))
1279
+ unlinkSync3(tmp);
803
1280
  } catch (e) {
804
1281
  warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
805
1282
  `);
806
1283
  }
807
- writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
808
- renameSync(tmp, path);
1284
+ writeFileSync2(tmp, JSON.stringify(data, null, 2), { mode: 384 });
1285
+ renameSync2(tmp, path);
809
1286
  try {
810
- chmodSync(path, 384);
1287
+ chmodSync2(path, 384);
811
1288
  } catch (e) {
812
1289
  warn(`[agentchat] WARNING: could not chmod ${path} to 0600: ${e}
813
1290
  `);
814
1291
  }
815
1292
  try {
816
- const mode = statSync(path).mode & 511;
1293
+ const mode = statSync2(path).mode & 511;
817
1294
  if (mode !== 384) {
818
1295
  warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
819
1296
  `);
@@ -896,7 +1373,7 @@ function expectedAgentIdFromEnv(env) {
896
1373
  }
897
1374
  return null;
898
1375
  }
899
- var EXPECT_PIN_EXEMPT_TOOLS = new Set(["whoami", "switch_profile"]);
1376
+ var EXPECT_PIN_EXEMPT_TOOLS = new Set(["whoami", "switch_profile", "connect_profile", "disconnect_profile"]);
900
1377
  function expectedAgentIdViolation(expected, liveAgentId) {
901
1378
  if (!expected)
902
1379
  return null;
@@ -906,10 +1383,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
906
1383
  }
907
1384
 
908
1385
  // src/read-cursor.ts
909
- import { readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
1386
+ import { readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
910
1387
  function loadCursor(file, warn) {
911
1388
  try {
912
- return new Map(Object.entries(JSON.parse(readFileSync3(file, "utf-8"))));
1389
+ return new Map(Object.entries(JSON.parse(readFileSync4(file, "utf-8"))));
913
1390
  } catch (e) {
914
1391
  if (e?.code !== "ENOENT") {
915
1392
  warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
@@ -920,7 +1397,7 @@ function loadCursor(file, warn) {
920
1397
  }
921
1398
  function persistCursor(file, cursor, warn) {
922
1399
  try {
923
- writeFileSync2(file, JSON.stringify(Object.fromEntries(cursor)));
1400
+ writeFileSync3(file, JSON.stringify(Object.fromEntries(cursor)));
924
1401
  return true;
925
1402
  } catch (e) {
926
1403
  warn(`[agentchat] WARNING: failed to persist read cursor to ${file}: ${e}
@@ -1037,10 +1514,8 @@ function parseArgs() {
1037
1514
  parsed.registerOnly = "1";
1038
1515
  continue;
1039
1516
  }
1040
- if (arg === "--accept-terms") {
1041
- parsed.acceptTerms = "1";
1517
+ if (arg === "--accept-terms")
1042
1518
  continue;
1043
- }
1044
1519
  const equal = arg.indexOf("=");
1045
1520
  const key = (equal < 0 ? arg : arg.slice(0, equal)).slice(2);
1046
1521
  if (!arg.startsWith("--") || !values.has(key)) {
@@ -1062,13 +1537,15 @@ var cliArgs = parseArgs();
1062
1537
  if (process.argv.includes("--help") || process.argv.includes("-h")) {
1063
1538
  console.log(`agentschat-mcp \u2014 AgentsChat MCP and host bridges
1064
1539
 
1065
- Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest [options]
1540
+ Usage: claude mcp add agentschat -- npx -y agentschat-mcp@${package_default.version} --profile <Bot> [options]
1066
1541
  claude --dangerously-load-development-channels server:agentschat
1542
+ One MCP server entry per bot, each pinning --profile and this version
1543
+ (not @latest, which drifts).
1067
1544
 
1068
1545
  Setup guide for every supported host:
1069
1546
  Read skills/onboarding.md relative to this installed package root.
1070
- Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
1071
- Start with: npx -y agentschat-mcp@latest --help
1547
+ Online (this version): https://unpkg.com/agentschat-mcp@${package_default.version}/skills/onboarding.md
1548
+ Newest release (first install): npx -y agentschat-mcp@latest --help
1072
1549
  The guide selects Claude Code, Codex, OpenClaw, Hermes, Grok Bot, URL wake,
1073
1550
  or the separately deployed dot remote MCP + Events integration.
1074
1551
  Help only prints instructions; follow the guide and verify a real reply.
@@ -1079,8 +1556,8 @@ Options:
1079
1556
  --profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
1080
1557
  --register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
1081
1558
  --register Explicitly opt in to registering a new agent (implied by --name)
1082
- --accept-terms Accept the terms at https://agents-chat.com/terms. REQUIRED to
1083
- register (or AGENTSCHAT_ACCEPT_TERMS=1); never assumed for you.
1559
+ --accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
1560
+ No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
1084
1561
  --id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
1085
1562
  --url <url> Server URL (default: production)
1086
1563
  --token <token> Auth token (or AGENTCHAT_TOKEN); requires its paired ID or an
@@ -1104,12 +1581,13 @@ Wake a host that has no channel-notification surface (Grok Bot, generic MCP clie
1104
1581
  Start any missing Grok wake daemons from grok-binds.json
1105
1582
  (node scripts/ensure-grok-wakes.mjs).
1106
1583
 
1107
- Grok multi-bot identity bind (Cursor / Grok Bot, no --profile):
1108
- ~/.agentschat/grok-binds.json maps CURSOR_CONVERSATION_ID (Grok uuid) \u2192 profile name.
1109
- AGENTCHAT_GROK_BINDS overrides that path. Profile names resolve like --profile.
1110
- Auto-bind does NOT set AGENTCHAT_WAKE_MODE \u2014 a Cursor-tool MCP should unset it
1111
- (per-identity wake daemons already POST sendPrompt). If the operator set
1112
- WAKE_MODE, it is left as-is.
1584
+ Grok multi-bot outbound identity: one MCP connection per Grok bot, each with
1585
+ its own --profile (e.g. agentschat-jack \u2192 --profile Jack). Do NOT pick the send
1586
+ identity from grok-binds.json / select-profile-mcp.sh: account-level MCP
1587
+ connections are shared across chats and get no CURSOR_CONVERSATION_ID, so they
1588
+ would run anonymous. ~/.agentschat/grok-binds.json (CURSOR_CONVERSATION_ID \u2192
1589
+ profile; AGENTCHAT_GROK_BINDS overrides the path) is the inbound wake-daemon
1590
+ table only.
1113
1591
 
1114
1592
  Hermes relay connector (no Hermes patch): run with --connector. See --connector --help.
1115
1593
 
@@ -1122,41 +1600,45 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
1122
1600
  process.exit(0);
1123
1601
  }
1124
1602
  var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
1125
- var configDir = join3(homeDir, ".agentschat");
1126
- var legacyConfigDir = join3(homeDir, ".agentchat");
1603
+ var configDir = join4(homeDir, ".agentschat");
1604
+ var legacyConfigDir = join4(homeDir, ".agentchat");
1127
1605
  var profileDirs = [configDir, legacyConfigDir];
1606
+ var lockDir = resolveLockDir(homeDir, process.env);
1607
+ var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
1608
+ var toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
1609
+ var runtimeSession = detectRuntimeSession(process.env);
1128
1610
  function profileNameToPaths(name) {
1129
1611
  if (name.startsWith("~/"))
1130
- return [join3(homeDir, name.slice(2))];
1612
+ return [join4(homeDir, name.slice(2))];
1131
1613
  if (name.includes("/") || name.includes("\\"))
1132
1614
  return [name];
1133
1615
  name = name.replace(/\.json$/, "");
1134
1616
  const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
1135
- return profileDirs.map((dir) => join3(dir, `${safeName}.json`));
1617
+ return profileDirs.map((dir) => join4(dir, `${safeName}.json`));
1136
1618
  }
1137
1619
  function nameToPath(name) {
1138
1620
  const candidates = profileNameToPaths(name);
1139
- const nested = join3(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
1140
- if (!name.includes("/") && !name.includes("\\") && existsSync3(nested))
1621
+ const nested = join4(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
1622
+ if (!name.includes("/") && !name.includes("\\") && existsSync5(nested))
1141
1623
  return nested;
1142
- return candidates.find((path) => existsSync3(path)) || candidates[0];
1624
+ return candidates.find((path) => existsSync5(path)) || candidates[0];
1143
1625
  }
1144
1626
  function listProfileFiles() {
1145
1627
  const seen = new Set;
1146
1628
  const profiles = [];
1147
- for (const dir of [join3(configDir, "profiles"), ...profileDirs]) {
1629
+ for (const dir of [join4(configDir, "profiles"), ...profileDirs]) {
1148
1630
  let files = [];
1149
1631
  try {
1150
- files = readdirSync(dir).filter((f) => f.endsWith(".json"));
1632
+ files = readdirSync2(dir).filter((f) => f.endsWith(".json"));
1151
1633
  } catch {}
1152
1634
  for (const file of files) {
1153
- if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME)
1635
+ if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME || file === DEFAULT_SESSION_BINDS_FILENAME || file === LEGACY_AGY_BINDS_FILENAME)
1154
1636
  continue;
1155
1637
  const name = file.replace(/\.json$/, "");
1156
1638
  if (seen.has(name))
1157
1639
  continue;
1158
1640
  seen.add(name);
1159
- profiles.push({ name, path: join3(dir, file) });
1641
+ profiles.push({ name, path: join4(dir, file) });
1160
1642
  }
1161
1643
  }
1162
1644
  return profiles;
@@ -1181,9 +1663,9 @@ function resolveProfile() {
1181
1663
  let binds = {};
1182
1664
  if (!grokToken && conversationId) {
1183
1665
  const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
1184
- if (existsSync3(bindPath)) {
1666
+ if (existsSync5(bindPath)) {
1185
1667
  try {
1186
- const parsed = parseGrokBindsText(readFileSync4(bindPath, "utf-8"));
1668
+ const parsed = parseGrokBindsText(readFileSync5(bindPath, "utf-8"));
1187
1669
  binds = parsed.binds;
1188
1670
  if (parsed.malformed) {
1189
1671
  process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
@@ -1213,6 +1695,18 @@ function resolveProfile() {
1213
1695
  return { path: nameToPath(process.env.AGENTSCHAT_PROFILE), source: "env", declaredName: process.env.AGENTSCHAT_PROFILE };
1214
1696
  if (process.env.AGENTCHAT_PROFILE)
1215
1697
  return { path: nameToPath(process.env.AGENTCHAT_PROFILE), source: "legacy-env", declaredName: process.env.AGENTCHAT_PROFILE };
1698
+ if (!grokToken && runtimeSession?.sessionId) {
1699
+ const sessionBinds = loadSessionBinds(configDir);
1700
+ const boundProfile = sessionBinds[runtimeSession.sessionId];
1701
+ if (boundProfile) {
1702
+ const boundPath = nameToPath(boundProfile);
1703
+ if (existsSync5(boundPath)) {
1704
+ process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} \u2192 profile "${boundProfile}"
1705
+ `);
1706
+ return { path: boundPath, source: "session-bind", declaredName: boundProfile };
1707
+ }
1708
+ }
1709
+ }
1216
1710
  return { path: nameToPath("profile"), source: "default" };
1217
1711
  }
1218
1712
  var { path: profileFile, source: profileSource, declaredName, agentId: projectAgentId, apiUrl: projectApiUrl, wsUrl: projectWsUrl } = resolveProfile();
@@ -1251,7 +1745,7 @@ if (hasToken && !explicitAgentId && profileSource === "default") {
1251
1745
  process.exit(1);
1252
1746
  }
1253
1747
  var identity = decideIdentity({
1254
- profileExists: existsSync3(profileFile),
1748
+ profileExists: existsSync5(profileFile),
1255
1749
  source: profileSource,
1256
1750
  profileFile,
1257
1751
  cliName: cliArgs.name,
@@ -1262,7 +1756,7 @@ var identity = decideIdentity({
1262
1756
  });
1263
1757
  function readIdentityProfile(file) {
1264
1758
  try {
1265
- return JSON.parse(readFileSync4(file, "utf-8"));
1759
+ return JSON.parse(readFileSync5(file, "utf-8"));
1266
1760
  } catch {
1267
1761
  throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
1268
1762
  }
@@ -1284,8 +1778,25 @@ if (identity.mode === "profile") {
1284
1778
  `);
1285
1779
  process.exit(1);
1286
1780
  }
1287
- process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
1781
+ const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
1782
+ const lockCheck = !cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
1783
+ lockDir,
1784
+ agentId: candidateAgentId,
1785
+ currentSessionId: runtimeSession?.sessionId ?? null,
1786
+ lockOwnerPid
1787
+ }) : { locked: false };
1788
+ if (lockCheck.locked) {
1789
+ anonymousMode = true;
1790
+ activeProfileFile = null;
1791
+ profile = {};
1792
+ 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}` : ""}.
1793
+ ` + ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.
1794
+ ` + ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.
1795
+ `);
1796
+ } else {
1797
+ process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
1288
1798
  `);
1799
+ }
1289
1800
  } else if (identity.mode === "env-creds") {
1290
1801
  activeProfileFile = null;
1291
1802
  process.stderr.write(`[agentchat] Using credentials from environment \u2014 not registering.
@@ -1302,15 +1813,8 @@ if (identity.mode === "profile") {
1302
1813
  } else {
1303
1814
  const displayName = identity.displayName;
1304
1815
  const caps = ["claude-code", "coding", "chat"];
1305
- const consent = decideTermsConsent({
1306
- acceptFlag: !!cliArgs.acceptTerms,
1307
- acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS
1308
- });
1309
- if (consent.mode === "refused") {
1310
- process.stderr.write(`[agentchat] ERROR: ${consent.message}
1816
+ process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}
1311
1817
  `);
1312
- process.exit(1);
1313
- }
1314
1818
  process.stderr.write(`[agentchat] Registering "${displayName}" with server...
1315
1819
  `);
1316
1820
  try {
@@ -1322,8 +1826,7 @@ if (identity.mode === "profile") {
1322
1826
  type: "agent",
1323
1827
  capabilities: caps,
1324
1828
  source: "mcp",
1325
- accepted_terms: true,
1326
- terms_version: consent.version
1829
+ terms_notice_version: TERMS_VERSION
1327
1830
  })
1328
1831
  });
1329
1832
  if (regRes.ok) {
@@ -1334,28 +1837,29 @@ if (identity.mode === "profile") {
1334
1837
  token: data.key,
1335
1838
  capabilities: caps
1336
1839
  };
1840
+ validateIdentityProfile(profile, profileFile);
1337
1841
  process.stderr.write(`[agentchat] Registered! ID: ${data.id}
1338
1842
  `);
1339
1843
  process.stderr.write(`[agentchat] Claim entry: ${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1 \u2014 enter the key from your private profile in the browser.
1340
1844
  `);
1341
- process.stderr.write(`[agentchat] Next steps: confirm ownership, configure your runtime, then verify one real reply. Registration alone is not setup completion.
1845
+ process.stderr.write(`[agentchat] Next steps: configure your runtime, join the authorized public conversation and verify a real message/reply. Claiming is only needed for private access and owner features.
1342
1846
  `);
1343
1847
  } else {
1344
1848
  const body = await regRes.text().catch(() => "");
1345
1849
  process.stderr.write(`[agentchat] ERROR: registration refused by ${REST_URL} \u2014 HTTP ${regRes.status} ${body.slice(0, 300)}
1346
- ` + ` No profile was written and no account exists. Nothing is running.
1347
- ` + ` If this mentions terms, read ${TERMS_URL} and re-run with --accept-terms.
1850
+ ` + ` No profile was written. Check the service response before retrying registration. Nothing is running.
1851
+ ` + ` If the service requires accepted_terms, its agent onboarding must be updated; this client does not fabricate acceptance.
1348
1852
  `);
1349
1853
  process.exit(1);
1350
1854
  }
1351
1855
  } catch (e) {
1352
1856
  process.stderr.write(`[agentchat] ERROR: Registration failed: ${e}
1353
- ` + ` No profile was written and no account exists. Nothing is running.
1857
+ ` + ` No profile was written. Registration may have completed on the service; check the result before retrying. Nothing is running.
1354
1858
  `);
1355
1859
  process.exit(1);
1356
1860
  }
1357
- mkdirSync(dirname(profileFile), { recursive: true });
1358
- safeWriteProfile(profileFile, profile);
1861
+ mkdirSync2(dirname(profileFile), { recursive: true });
1862
+ safeWriteProfile2(profileFile, profile);
1359
1863
  process.stderr.write(`[agentchat] Profile saved: ${profileFile}
1360
1864
  `);
1361
1865
  }
@@ -1363,61 +1867,59 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
1363
1867
  process.stderr.write(`[agentchat] Profile at ${profileFile} carries a dev-token but no identity was declared \u2014 ` + `refusing to auto-register. Pass --name <name> or --register to create a real agent.
1364
1868
  `);
1365
1869
  } else if (!hasToken && profile.token === "dev-token") {
1366
- const migrationConsent = decideTermsConsent({
1367
- acceptFlag: !!cliArgs.acceptTerms,
1368
- acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS
1369
- });
1370
- if (migrationConsent.mode === "refused") {
1371
- process.stderr.write(`[agentchat] Profile at ${profileFile} carries a placeholder dev-token and cannot authenticate.
1372
- ` + ` Healing it registers a real account: ${migrationConsent.message}
1870
+ process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}
1373
1871
  `);
1374
- } else {
1375
- const terms = { accepted_terms: true, terms_version: migrationConsent.version };
1376
- process.stderr.write(`[agentchat] Migrating dev-token profile \u2014 registering with server...
1872
+ const terms = { terms_notice_version: TERMS_VERSION };
1873
+ process.stderr.write(`[agentchat] Migrating dev-token profile \u2014 registering with server...
1377
1874
  `);
1378
- try {
1379
- const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
1875
+ try {
1876
+ const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
1877
+ method: "POST",
1878
+ headers: { "Content-Type": "application/json" },
1879
+ body: JSON.stringify({ id: profile.agent_id, name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
1880
+ });
1881
+ if (regRes.ok) {
1882
+ const data = await regRes.json();
1883
+ const repaired = { ...profile, agent_id: data.id, token: data.key };
1884
+ validateIdentityProfile(repaired, profileFile);
1885
+ safeWriteProfile2(profileFile, repaired);
1886
+ profile = repaired;
1887
+ process.stderr.write(`[agentchat] Migrated! New key saved. ID: ${data.id}
1888
+ `);
1889
+ } else if (regRes.status === 409) {
1890
+ const regRes2 = await apiFetch(`${REST_URL}/api/account/register`, {
1380
1891
  method: "POST",
1381
1892
  headers: { "Content-Type": "application/json" },
1382
- body: JSON.stringify({ id: profile.agent_id, name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
1893
+ body: JSON.stringify({ name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
1383
1894
  });
1384
- if (regRes.ok) {
1385
- const data = await regRes.json();
1386
- profile.agent_id = data.id;
1387
- profile.token = data.key;
1388
- safeWriteProfile(profileFile, profile);
1389
- process.stderr.write(`[agentchat] Migrated! New key saved. ID: ${data.id}
1895
+ if (regRes2.ok) {
1896
+ const data = await regRes2.json();
1897
+ const repaired = { ...profile, agent_id: data.id, token: data.key };
1898
+ validateIdentityProfile(repaired, profileFile);
1899
+ safeWriteProfile2(profileFile, repaired);
1900
+ profile = repaired;
1901
+ process.stderr.write(`[agentchat] Migrated with new ID: ${data.id}
1390
1902
  `);
1391
1903
  } else {
1392
- const regRes2 = await apiFetch(`${REST_URL}/api/account/register`, {
1393
- method: "POST",
1394
- headers: { "Content-Type": "application/json" },
1395
- body: JSON.stringify({ name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
1396
- });
1397
- if (regRes2.ok) {
1398
- const data = await regRes2.json();
1399
- profile.agent_id = data.id;
1400
- profile.token = data.key;
1401
- safeWriteProfile(profileFile, profile);
1402
- process.stderr.write(`[agentchat] Migrated with new ID: ${data.id}
1403
- `);
1404
- } else {
1405
- const body = await regRes2.text().catch(() => "");
1406
- process.stderr.write(`[agentchat] WARNING: dev-token migration refused \u2014 HTTP ${regRes2.status} ${body.slice(0, 200)}
1904
+ const body = await regRes2.text().catch(() => "");
1905
+ process.stderr.write(`[agentchat] WARNING: dev-token migration refused \u2014 HTTP ${regRes2.status} ${body.slice(0, 200)}
1407
1906
  ` + ` This profile still holds a placeholder token; authenticated calls will fail.
1408
1907
  `);
1409
- }
1410
1908
  }
1411
- } catch (e) {
1412
- process.stderr.write(`[agentchat] dev-token migration failed: ${e}
1909
+ } else {
1910
+ const body = await regRes.text().catch(() => "");
1911
+ process.stderr.write(`[agentchat] WARNING: dev-token migration refused \u2014 HTTP ${regRes.status} ${body.slice(0, 200)}; no alternate identity was registered.
1413
1912
  `);
1414
1913
  }
1914
+ } catch (e) {
1915
+ process.stderr.write(`[agentchat] dev-token migration failed: ${e}. Check the registration result before retrying; the saved placeholder profile is unchanged.
1916
+ `);
1415
1917
  }
1416
1918
  }
1417
1919
  if (!hasToken && profile.token === "dev-token") {
1418
1920
  process.stderr.write(`[agentchat] ERROR: profile ${profileFile} holds a placeholder dev-token, which cannot authenticate.
1419
1921
  ` + ` Not starting \u2014 a server that lists tools it cannot use is worse than one that fails.
1420
- ` + ` Heal it: --accept-terms (registers a real account for this profile)
1922
+ ` + ` Repair it: --profile <name> (registers a real account for this declared placeholder)
1421
1923
  ` + ` Or replace: register at https://agents-chat.com/join, then use --profile <name>
1422
1924
  ` + ` or AGENTCHAT_TOKEN=<token>
1423
1925
  `);
@@ -1435,12 +1937,26 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
1435
1937
  process.exit(1);
1436
1938
  }
1437
1939
  }
1940
+ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
1941
+ acquireAgentLock({
1942
+ lockDir,
1943
+ agentId: AGENT_ID,
1944
+ profileName: profileNameFromPath(activeProfileFile) ?? declaredName ?? null,
1945
+ sessionId: runtimeSession?.sessionId ?? null,
1946
+ runtime: runtimeSession?.runtime ?? "mcp"
1947
+ });
1948
+ if (runtimeSession?.sessionId && activeProfileFile) {
1949
+ const activeName = profileNameFromPath(activeProfileFile);
1950
+ if (activeName)
1951
+ saveSessionBind(configDir, runtimeSession.sessionId, activeName);
1952
+ }
1953
+ }
1438
1954
  var identityGateMessage = "";
1439
- var identityGuardFile = join3(configDir, IDENTITY_GUARD_FILENAME);
1955
+ var identityGuardFile = join4(configDir, IDENTITY_GUARD_FILENAME);
1440
1956
  function persistGuardRecord(rec) {
1441
1957
  try {
1442
- mkdirSync(configDir, { recursive: true });
1443
- safeWriteProfile(identityGuardFile, rec);
1958
+ mkdirSync2(configDir, { recursive: true });
1959
+ safeWriteProfile2(identityGuardFile, rec);
1444
1960
  } catch {}
1445
1961
  }
1446
1962
  function confirmLiveIdentityTrusted() {
@@ -1455,7 +1971,7 @@ function confirmLiveIdentityTrusted() {
1455
1971
  }
1456
1972
  var guardRecord = (() => {
1457
1973
  try {
1458
- return parseGuardRecord(readFileSync4(identityGuardFile, "utf-8"));
1974
+ return parseGuardRecord(readFileSync5(identityGuardFile, "utf-8"));
1459
1975
  } catch {
1460
1976
  return emptyGuardRecord();
1461
1977
  }
@@ -1496,7 +2012,7 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
1496
2012
  profile.display_name = cliArgs.name;
1497
2013
  }
1498
2014
  if (cliArgs.registerOnly && !TOKEN) {
1499
- process.stderr.write(`[agentchat] Select an existing profile or use --name with explicit --accept-terms.
2015
+ process.stderr.write(`[agentchat] Select an existing profile or use --name <name> / --register to self-register.
1500
2016
  `);
1501
2017
  process.exit(1);
1502
2018
  }
@@ -1505,7 +2021,7 @@ if (TOKEN && TOKEN !== "dev-token") {
1505
2021
  process.stderr.write(`[agentchat] ${claimSummary(status)}
1506
2022
  `);
1507
2023
  if (cliArgs.registerOnly) {
1508
- console.log(JSON.stringify({ ...status, claim_url: status.claimed === true ? null : `${status.chat_url}?key=${encodeURIComponent(TOKEN)}`, profile_file: activeProfileFile, reply_verified: false }));
2024
+ 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 }));
1509
2025
  process.exit(0);
1510
2026
  }
1511
2027
  }
@@ -1654,6 +2170,8 @@ var CORE_TOOL_NAMES = new Set([
1654
2170
  "leave_channel",
1655
2171
  "mark_read",
1656
2172
  "switch_profile",
2173
+ "connect_profile",
2174
+ "disconnect_profile",
1657
2175
  "list_skills",
1658
2176
  "load_skill",
1659
2177
  "save_skill",
@@ -2566,11 +3084,38 @@ var ALL_TOOL_DEFS = [
2566
3084
  },
2567
3085
  {
2568
3086
  name: "switch_profile",
2569
- description: "Switch to a different AgentsChat profile at runtime. Lists available profiles if no name given.",
3087
+ description: "Switch to a different AgentsChat profile at runtime, register a new profile for this window, or disconnect. Lists available profiles and their lock status if no name is given.",
3088
+ inputSchema: {
3089
+ type: "object",
3090
+ properties: {
3091
+ profile_name: { type: "string", description: "Existing profile name to switch to (omit to list available profiles)" },
3092
+ register_name: { type: "string", description: "Display name to register a brand-new AgentsChat agent and connect this window to it" },
3093
+ register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
3094
+ disconnect: { type: "boolean", description: "If true, disconnect this window from its current profile and release its lock" },
3095
+ conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" }
3096
+ }
3097
+ }
3098
+ },
3099
+ {
3100
+ name: "connect_profile",
3101
+ description: "Connect this window to an existing idle AgentsChat profile or register a brand-new agent identity, acquiring the single-active-instance lock and binding this session.",
2570
3102
  inputSchema: {
2571
3103
  type: "object",
2572
3104
  properties: {
2573
- profile_name: { type: "string", description: "Profile name to switch to (omit to list available profiles)" }
3105
+ profile_name: { type: "string", description: "Existing profile name to connect to (omit to list available profiles and lock status)" },
3106
+ register_name: { type: "string", description: "Display name to register a new agent and connect this window to it" },
3107
+ register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
3108
+ conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" }
3109
+ }
3110
+ }
3111
+ },
3112
+ {
3113
+ name: "disconnect_profile",
3114
+ description: "Disconnect this window from its current AgentsChat profile and release the single-active-instance lock so another window or background bridge can connect to it.",
3115
+ inputSchema: {
3116
+ type: "object",
3117
+ properties: {
3118
+ keep_binding: { type: "boolean", description: "If true, keep the session-binds.json entry while releasing the active process lock" }
2574
3119
  }
2575
3120
  }
2576
3121
  },
@@ -2750,10 +3295,10 @@ function mimeFromPath(p) {
2750
3295
  return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
2751
3296
  }
2752
3297
  async function uploadLocalFile(path) {
2753
- if (!existsSync3(path))
3298
+ if (!existsSync5(path))
2754
3299
  throw new Error(`file not found: ${path}`);
2755
3300
  const mime = mimeFromPath(path);
2756
- const buf = readFileSync4(path);
3301
+ const buf = readFileSync5(path);
2757
3302
  const name = path.split("/").pop() || "upload";
2758
3303
  const form = new FormData;
2759
3304
  form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
@@ -2940,10 +3485,10 @@ HANDLERS.set("transcribe", async (args) => {
2940
3485
  });
2941
3486
  function loadGrokBinds() {
2942
3487
  const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
2943
- if (!existsSync3(bindPath))
3488
+ if (!existsSync5(bindPath))
2944
3489
  return {};
2945
3490
  try {
2946
- return parseGrokBindsText(readFileSync4(bindPath, "utf-8")).binds;
3491
+ return parseGrokBindsText(readFileSync5(bindPath, "utf-8")).binds;
2947
3492
  } catch {
2948
3493
  return {};
2949
3494
  }
@@ -2957,9 +3502,13 @@ function currentGrokBindApplicability(binds) {
2957
3502
  binds
2958
3503
  });
2959
3504
  }
2960
- function applyIdentityFromProfile(newProfile, targetFile) {
3505
+ function applyIdentityFromProfile(newProfile, targetFile, bindSessionId) {
2961
3506
  validateIdentityProfile(newProfile, targetFile);
3507
+ if (AGENT_ID && AGENT_ID !== newProfile.agent_id) {
3508
+ releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
3509
+ }
2962
3510
  heartbeat.stop();
3511
+ stopAllTypingHeartbeats();
2963
3512
  if (backfillTimer) {
2964
3513
  clearTimeout(backfillTimer);
2965
3514
  backfillTimer = null;
@@ -2982,12 +3531,243 @@ function applyIdentityFromProfile(newProfile, targetFile) {
2982
3531
  profile = newProfile;
2983
3532
  activeProfileFile = targetFile;
2984
3533
  anonymousMode = false;
3534
+ if (bindSessionId && bindSessionId.trim()) {
3535
+ runtimeSession = {
3536
+ sessionId: bindSessionId.trim(),
3537
+ runtime: runtimeSession?.runtime ?? "custom",
3538
+ ...runtimeSession?.workspacePath ? { workspacePath: runtimeSession.workspacePath } : {}
3539
+ };
3540
+ } else if (!runtimeSession?.sessionId) {
3541
+ const agyHost = discoverAntigravityHost();
3542
+ if (agyHost && agyHost.openConversations.length === 1) {
3543
+ runtimeSession = { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
3544
+ }
3545
+ }
3546
+ if (!toolOnlyMode) {
3547
+ acquireAgentLock({
3548
+ lockDir,
3549
+ agentId: AGENT_ID,
3550
+ profileName: profileNameFromPath(targetFile),
3551
+ sessionId: runtimeSession?.sessionId ?? null,
3552
+ runtime: runtimeSession?.runtime ?? "mcp"
3553
+ });
3554
+ if (runtimeSession?.sessionId) {
3555
+ const pName = profileNameFromPath(targetFile);
3556
+ if (pName)
3557
+ saveSessionBind(configDir, runtimeSession.sessionId, pName);
3558
+ }
3559
+ }
2985
3560
  guardRecord = advanceGuardRecord(guardRecord, { agentId: AGENT_ID, source: "switch_profile", ...profileNameFromPath(targetFile) ? { declaredName: profileNameFromPath(targetFile) } : {} }, new Date().toISOString(), true);
2986
3561
  persistGuardRecord(guardRecord);
2987
3562
  wsReconnectAttempt = 0;
2988
- heartbeat.start();
2989
- connectWS();
3563
+ if (!toolOnlyMode) {
3564
+ heartbeat.start();
3565
+ connectWS();
3566
+ }
3567
+ }
3568
+ function disconnectCurrentProfile(opts) {
3569
+ const prevAgentId = AGENT_ID;
3570
+ const prevProfileName = profileNameFromPath(activeProfileFile) || profile?.display_name || AGENT_ID || "(none)";
3571
+ heartbeat.stop();
3572
+ stopAllTypingHeartbeats();
3573
+ if (backfillTimer) {
3574
+ clearTimeout(backfillTimer);
3575
+ backfillTimer = null;
3576
+ }
3577
+ if (reconnectTimer) {
3578
+ clearTimeout(reconnectTimer);
3579
+ reconnectTimer = null;
3580
+ }
3581
+ if (ws) {
3582
+ ws.onclose = null;
3583
+ try {
3584
+ ws.close();
3585
+ } catch {}
3586
+ ws = null;
3587
+ }
3588
+ if (prevAgentId) {
3589
+ releaseAgentLock({ lockDir, agentId: prevAgentId, currentSessionId: runtimeSession?.sessionId ?? null });
3590
+ }
3591
+ if (!opts?.keepBinding && runtimeSession?.sessionId) {
3592
+ removeSessionBind(configDir, runtimeSession.sessionId);
3593
+ }
3594
+ sessionId = null;
3595
+ AGENT_ID = "";
3596
+ TOKEN = "";
3597
+ profile = {};
3598
+ activeProfileFile = null;
3599
+ anonymousMode = true;
3600
+ return { prevAgentId, prevProfileName };
3601
+ }
3602
+ function formatProfileList() {
3603
+ const profileEntries = listProfileFiles();
3604
+ const current = AGENT_ID;
3605
+ const currentProfileName = profileNameFromPath(activeProfileFile);
3606
+ const lines = profileEntries.map((entry) => {
3607
+ let entryAgentId = "";
3608
+ try {
3609
+ const parsed = JSON.parse(readFileSync5(entry.path, "utf-8"));
3610
+ if (typeof parsed?.agent_id === "string")
3611
+ entryAgentId = parsed.agent_id;
3612
+ } catch {}
3613
+ const isCurrent = current && (entry.name === current || entryAgentId === current) || currentProfileName && entry.name === currentProfileName;
3614
+ const lock = entryAgentId ? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid }) : { locked: false };
3615
+ const statusSuffix = lock.locked ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}]` : "";
3616
+ return `${isCurrent ? "\u2192 " : " "}${entry.name}${statusSuffix}`;
3617
+ });
3618
+ return `Current: ${current || "(anonymous / disconnected)"}
3619
+ Available profiles:
3620
+ ${lines.join(`
3621
+ `)}`;
3622
+ }
3623
+ async function registerAndConnectProfile(displayName, bindSessionId) {
3624
+ const cleanName = displayName.trim();
3625
+ if (!cleanName) {
3626
+ return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
3627
+ }
3628
+ const caps = ["claude-code", "coding", "chat"];
3629
+ try {
3630
+ const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
3631
+ method: "POST",
3632
+ headers: { "Content-Type": "application/json" },
3633
+ body: JSON.stringify({
3634
+ name: cleanName,
3635
+ type: "agent",
3636
+ capabilities: caps,
3637
+ source: "mcp",
3638
+ terms_notice_version: TERMS_VERSION
3639
+ })
3640
+ });
3641
+ if (!regRes.ok) {
3642
+ const body = await regRes.text().catch(() => "");
3643
+ return {
3644
+ content: [{ type: "text", text: `Registration refused by ${REST_URL} \u2014 HTTP ${regRes.status} ${body.slice(0, 240)}` }],
3645
+ isError: true
3646
+ };
3647
+ }
3648
+ const data = await regRes.json();
3649
+ const newProfile = {
3650
+ agent_id: data.id,
3651
+ display_name: cleanName,
3652
+ token: data.key,
3653
+ capabilities: caps
3654
+ };
3655
+ const targetFile = nameToPath(cleanName);
3656
+ validateIdentityProfile(newProfile, targetFile);
3657
+ mkdirSync2(dirname(targetFile), { recursive: true });
3658
+ safeWriteProfile2(targetFile, newProfile);
3659
+ const defaultProfileFile = nameToPath("profile");
3660
+ if (!existsSync5(defaultProfileFile)) {
3661
+ safeWriteProfile2(defaultProfileFile, newProfile);
3662
+ }
3663
+ applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
3664
+ const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
3665
+ return {
3666
+ content: [{
3667
+ type: "text",
3668
+ text: `Registered and connected profile "${cleanName}" (${AGENT_ID}).
3669
+ ` + `Profile saved: ${targetFile}
3670
+ ` + `Claim entry: ${claimEntry} \u2014 enter the key from your private profile in the browser.
3671
+ ` + `${TERMS_NOTICE_TEXT}`
3672
+ }]
3673
+ };
3674
+ } catch (e) {
3675
+ return {
3676
+ content: [{ type: "text", text: `Registration failed: ${String(e?.message || e).slice(0, 200)}` }],
3677
+ isError: true
3678
+ };
3679
+ }
3680
+ }
3681
+ async function handleProfileSwitchOrConnect(args) {
3682
+ const {
3683
+ profile_name,
3684
+ register_name,
3685
+ register,
3686
+ disconnect,
3687
+ conversation_id
3688
+ } = args || {};
3689
+ if (disconnect) {
3690
+ const { prevAgentId, prevProfileName } = disconnectCurrentProfile();
3691
+ return {
3692
+ content: [{
3693
+ type: "text",
3694
+ text: prevAgentId ? `Disconnected from profile "${prevProfileName}" (${prevAgentId}). Single-active-instance lock released; another window or bridge can now connect to it.` : `Already disconnected (anonymous mode).`
3695
+ }]
3696
+ };
3697
+ }
3698
+ const explicitSessionId = typeof conversation_id === "string" && conversation_id.trim() ? conversation_id.trim() : null;
3699
+ if (typeof register_name === "string" && register_name.trim()) {
3700
+ return await registerAndConnectProfile(register_name.trim(), explicitSessionId);
3701
+ }
3702
+ if (!profile_name) {
3703
+ return { content: [{ type: "text", text: formatProfileList() }] };
3704
+ }
3705
+ const switchBinds = loadGrokBinds();
3706
+ const bindApplies = currentGrokBindApplicability(switchBinds);
3707
+ const switchGate = !bindApplies.applies ? { kind: "allow" } : gateSwitchProfile({
3708
+ conversationId: process.env.CURSOR_CONVERSATION_ID,
3709
+ binds: switchBinds,
3710
+ requestedProfileName: profile_name,
3711
+ currentProfileName: profileNameFromPath(activeProfileFile)
3712
+ });
3713
+ if (switchGate.kind === "locked") {
3714
+ return { content: [{ type: "text", text: switchGate.message }], isError: true };
3715
+ }
3716
+ const targetFile = nameToPath(profile_name);
3717
+ if (!existsSync5(targetFile)) {
3718
+ if (register) {
3719
+ return await registerAndConnectProfile(profile_name, explicitSessionId);
3720
+ }
3721
+ const available = listProfileFiles().map((entry) => entry.name);
3722
+ return {
3723
+ content: [{
3724
+ type: "text",
3725
+ text: `Profile "${profile_name}" not found. Available: ${available.join(", ")} (or pass register_name="${profile_name}" / register=true to create a new agent)`
3726
+ }],
3727
+ isError: true
3728
+ };
3729
+ }
3730
+ const newProfile = readIdentityProfile(targetFile);
3731
+ validateIdentityProfile(newProfile, targetFile);
3732
+ const effectiveSessionId = explicitSessionId ?? runtimeSession?.sessionId ?? null;
3733
+ const lockCheck = checkAgentLock({
3734
+ lockDir,
3735
+ agentId: newProfile.agent_id,
3736
+ currentSessionId: effectiveSessionId,
3737
+ lockOwnerPid
3738
+ });
3739
+ if (lockCheck.locked) {
3740
+ return {
3741
+ content: [{
3742
+ type: "text",
3743
+ text: `Profile "${profile_name}" (${newProfile.agent_id}) is currently in use by another active process ` + `(pid=${lockCheck.holder?.pid}${lockCheck.holder?.runtime ? `, ${lockCheck.holder.runtime}` : ""}` + `${lockCheck.holder?.sessionId ? `, session=${lockCheck.holder.sessionId}` : ""}). ` + `Call disconnect_profile in that window first, or connect/register a different profile.`
3744
+ }],
3745
+ isError: true
3746
+ };
3747
+ }
3748
+ applyIdentityFromProfile(newProfile, targetFile, explicitSessionId);
3749
+ const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID ? `
3750
+ \uD83D\uDEA8 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) \u2014 write tools stay refused.` : "";
3751
+ const bindNote = runtimeSession?.sessionId ? ` Session "${runtimeSession.sessionId}" is bound to "${profile_name}" in session-binds.json.` : "";
3752
+ return {
3753
+ content: [{
3754
+ type: "text",
3755
+ text: `Switched to profile "${profile_name}" (${AGENT_ID}). Reconnecting...
3756
+ Scope: this switch applies only to THIS MCP process.${bindNote} It is not saved \u2014 a new or restarted MCP process starts again from its launch profile (--profile / AGENTSCHAT_PROFILE). Re-check with whoami at the start of every wake.${pinNote}`
3757
+ }]
3758
+ };
2990
3759
  }
3760
+ HANDLERS.set("connect_profile", async (args) => handleProfileSwitchOrConnect(args));
3761
+ HANDLERS.set("disconnect_profile", async (args) => {
3762
+ const { keep_binding } = args || {};
3763
+ const { prevAgentId, prevProfileName } = disconnectCurrentProfile({ keepBinding: keep_binding });
3764
+ return {
3765
+ content: [{
3766
+ type: "text",
3767
+ text: prevAgentId ? `Disconnected from profile "${prevProfileName}" (${prevAgentId}). Single-active-instance lock released; another window or bridge can now connect to it.` : `Already disconnected (anonymous mode).`
3768
+ }]
3769
+ };
3770
+ });
2991
3771
  function ensureGrokBoundIdentity() {
2992
3772
  if (profileSource !== "grok-bind" || hasToken || cliArgs.id || process.env.AGENTCHAT_AGENT_ID)
2993
3773
  return;
@@ -2998,7 +3778,7 @@ function ensureGrokBoundIdentity() {
2998
3778
  if (!boundName)
2999
3779
  return;
3000
3780
  const boundPath = nameToPath(boundName);
3001
- if (!existsSync3(boundPath))
3781
+ if (!existsSync5(boundPath))
3002
3782
  return;
3003
3783
  let boundProfile;
3004
3784
  try {
@@ -3023,6 +3803,41 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
3023
3803
  let { name, arguments: args } = request.params;
3024
3804
  let viaExtendedCompat = false;
3025
3805
  try {
3806
+ const metaSession = detectRuntimeSession(process.env, request.params?._meta);
3807
+ if (metaSession && (!runtimeSession || runtimeSession.sessionId !== metaSession.sessionId || !runtimeSession.workspacePath && metaSession.workspacePath)) {
3808
+ runtimeSession = metaSession;
3809
+ if (anonymousMode && name !== "connect_profile" && name !== "switch_profile" && name !== "disconnect_profile") {
3810
+ const boundProfile = loadSessionBinds(configDir)[metaSession.sessionId];
3811
+ if (boundProfile) {
3812
+ const boundPath = nameToPath(boundProfile);
3813
+ if (existsSync5(boundPath)) {
3814
+ try {
3815
+ const candidate = readIdentityProfile(boundPath);
3816
+ const lock = checkAgentLock({
3817
+ lockDir,
3818
+ agentId: candidate?.agent_id,
3819
+ currentSessionId: metaSession.sessionId,
3820
+ lockOwnerPid
3821
+ });
3822
+ if (!lock.locked) {
3823
+ applyIdentityFromProfile(candidate, boundPath, metaSession.sessionId);
3824
+ }
3825
+ } catch {}
3826
+ }
3827
+ }
3828
+ } else if (!anonymousMode && AGENT_ID && activeProfileFile && !toolOnlyMode) {
3829
+ acquireAgentLock({
3830
+ lockDir,
3831
+ agentId: AGENT_ID,
3832
+ profileName: profileNameFromPath(activeProfileFile),
3833
+ sessionId: metaSession.sessionId,
3834
+ runtime: metaSession.runtime
3835
+ });
3836
+ const pName = profileNameFromPath(activeProfileFile);
3837
+ if (pName)
3838
+ saveSessionBind(configDir, metaSession.sessionId, pName);
3839
+ }
3840
+ }
3026
3841
  if (TOOL_INPUT_SCHEMAS.has(name)) {
3027
3842
  const argErr = validateToolArgs(TOOL_INPUT_SCHEMAS.get(name), args);
3028
3843
  if (argErr)
@@ -3249,7 +4064,7 @@ ${a.body || ""}`;
3249
4064
  const currentVersion = Number(meta.version ?? 0);
3250
4065
  let cachedVersion = null;
3251
4066
  try {
3252
- cachedVersion = Number(JSON.parse(readFileSync4(pMeta, "utf8")).version);
4067
+ cachedVersion = Number(JSON.parse(readFileSync5(pMeta, "utf8")).version);
3253
4068
  } catch {}
3254
4069
  if (cachedVersion !== null && cachedVersion === currentVersion) {
3255
4070
  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.` }] };
@@ -3258,9 +4073,9 @@ ${a.body || ""}`;
3258
4073
  if (!bodyR.ok)
3259
4074
  return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
3260
4075
  const doc = JSON.parse(await bodyR.text());
3261
- mkdirSync(dirname(pMd), { recursive: true });
3262
- writeFileSync3(pMd, String(doc?.body_markdown ?? ""));
3263
- writeFileSync3(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
4076
+ mkdirSync2(dirname(pMd), { recursive: true });
4077
+ writeFileSync4(pMd, String(doc?.body_markdown ?? ""));
4078
+ writeFileSync4(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
3264
4079
  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.` }] };
3265
4080
  } catch (e) {
3266
4081
  return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
@@ -3283,7 +4098,7 @@ ${a.body || ""}`;
3283
4098
  const currentVersion = Number(meta.version ?? 0);
3284
4099
  let cachedVersion = null;
3285
4100
  try {
3286
- cachedVersion = Number(JSON.parse(readFileSync4(metaPath, "utf8")).version);
4101
+ cachedVersion = Number(JSON.parse(readFileSync5(metaPath, "utf8")).version);
3287
4102
  } catch {}
3288
4103
  if (cachedVersion !== null && cachedVersion === currentVersion) {
3289
4104
  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.` }] };
@@ -3293,9 +4108,9 @@ ${a.body || ""}`;
3293
4108
  return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
3294
4109
  const doc = JSON.parse(await docR.text());
3295
4110
  const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
3296
- mkdirSync(dirname(mdPath), { recursive: true });
3297
- writeFileSync3(mdPath, body);
3298
- writeFileSync3(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
4111
+ mkdirSync2(dirname(mdPath), { recursive: true });
4112
+ writeFileSync4(mdPath, body);
4113
+ writeFileSync4(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
3299
4114
  const was = cachedVersion === null ? "missing" : `stale v${cachedVersion}`;
3300
4115
  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.` }] };
3301
4116
  } catch (e) {
@@ -3911,6 +4726,9 @@ ${brief}` }] };
3911
4726
  }));
3912
4727
  return { content: [{ type: "text", text: `Read cursor update dispatched (up to ${last_read_id.slice(0, 8)})` }] };
3913
4728
  }
4729
+ if (toolOnlyMode) {
4730
+ return { content: [{ type: "text", text: `Read cursor noted (up to ${last_read_id.slice(0, 8)})` }] };
4731
+ }
3914
4732
  return { content: [{ type: "text", text: "Not connected" }] };
3915
4733
  }
3916
4734
  if (name === "whoami") {
@@ -4127,38 +4945,7 @@ ${list}` }] };
4127
4945
  }
4128
4946
  }
4129
4947
  if (name === "switch_profile") {
4130
- const { profile_name } = args;
4131
- const profileEntries = listProfileFiles();
4132
- const available = profileEntries.map((entry) => entry.name);
4133
- if (!profile_name) {
4134
- const current = AGENT_ID;
4135
- const list = available.map((p) => `${p === current ? "\u2192 " : " "}${p}`).join(`
4136
- `);
4137
- return { content: [{ type: "text", text: `Current: ${current}
4138
- Available profiles:
4139
- ${list}` }] };
4140
- }
4141
- const switchBinds = loadGrokBinds();
4142
- const bindApplies = currentGrokBindApplicability(switchBinds);
4143
- const switchGate = !bindApplies.applies ? { kind: "allow" } : gateSwitchProfile({
4144
- conversationId: process.env.CURSOR_CONVERSATION_ID,
4145
- binds: switchBinds,
4146
- requestedProfileName: profile_name,
4147
- currentProfileName: profileNameFromPath(activeProfileFile)
4148
- });
4149
- if (switchGate.kind === "locked") {
4150
- return { content: [{ type: "text", text: switchGate.message }], isError: true };
4151
- }
4152
- const targetFile = nameToPath(profile_name);
4153
- if (!existsSync3(targetFile)) {
4154
- return { content: [{ type: "text", text: `Profile "${profile_name}" not found. Available: ${available.join(", ")}` }], isError: true };
4155
- }
4156
- const newProfile = readIdentityProfile(targetFile);
4157
- applyIdentityFromProfile(newProfile, targetFile);
4158
- const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID ? `
4159
- \uD83D\uDEA8 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) \u2014 write tools stay refused.` : "";
4160
- return { content: [{ type: "text", text: `Switched to profile "${profile_name}" (${AGENT_ID}). Reconnecting...
4161
- Scope: this switch applies only to THIS MCP process. It is not saved \u2014 a new or restarted MCP process starts again from its launch profile (--profile / AGENTSCHAT_PROFILE). Re-check with whoami at the start of every wake.${pinNote}` }] };
4948
+ return await handleProfileSwitchOrConnect(args);
4162
4949
  }
4163
4950
  if (name === "list_channel_docs") {
4164
4951
  const { chat_id, level } = args;
@@ -4507,7 +5294,7 @@ Scope: this switch applies only to THIS MCP process. It is not saved \u2014 a ne
4507
5294
  return { content: [{ type: "text", text: `${name} failed: ${String(e?.message || e).slice(0, 300)}` }], isError: true };
4508
5295
  }
4509
5296
  });
4510
- var mentionTsFile = join3(configDir, `mention-ts-${AGENT_ID}.json`);
5297
+ var mentionTsFile = join4(configDir, `mention-ts-${AGENT_ID}.json`);
4511
5298
  function loadMentionTimestamps() {
4512
5299
  return loadCursor(mentionTsFile, safeStderrWrite);
4513
5300
  }
@@ -4515,7 +5302,7 @@ function saveMentionTimestamps(m) {
4515
5302
  persistCursor(mentionTsFile, m, safeStderrWrite);
4516
5303
  }
4517
5304
  var lastMentionTimestamp = loadMentionTimestamps();
4518
- var lastSeenMessageTsFile = join3(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
5305
+ var lastSeenMessageTsFile = join4(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
4519
5306
  function loadLastSeenMessageTs() {
4520
5307
  return loadCursor(lastSeenMessageTsFile, safeStderrWrite);
4521
5308
  }
@@ -4929,15 +5716,15 @@ ${context}
4929
5716
  if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
4930
5717
  (async () => {
4931
5718
  try {
4932
- const { readFileSync: readFileSync5, existsSync: existsSync4 } = await import("fs");
4933
- const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync4);
5719
+ const { readFileSync: readFileSync6, existsSync: existsSync6 } = await import("fs");
5720
+ const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync6);
4934
5721
  let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
4935
5722
  if (!agentId) {
4936
5723
  agentId = await resolveGrokAgentId({
4937
5724
  explicitId: "",
4938
5725
  agentschatName: profile.display_name || AGENT_ID,
4939
5726
  listAgents: async () => {
4940
- const gwcfg = JSON.parse(readFileSync5(gwPath, "utf8"));
5727
+ const gwcfg = JSON.parse(readFileSync6(gwPath, "utf8"));
4941
5728
  const token = grokBearerFromGatewayConfig(gwcfg);
4942
5729
  const port = grokPortFromGatewayConfig(gwcfg);
4943
5730
  const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
@@ -4958,11 +5745,58 @@ ${context}
4958
5745
  `);
4959
5746
  }
4960
5747
  })();
4961
- } else {
5748
+ } else if (process.env.AGENTCHAT_WAKE_URL) {
4962
5749
  fireWake(data, {
4963
5750
  url: process.env.AGENTCHAT_WAKE_URL,
4964
5751
  secret: process.env.AGENTCHAT_WAKE_SECRET
4965
5752
  });
5753
+ } else if (runtimeSession?.runtime === "zcode" || process.env.AGENTCHAT_WAKE_MODE === "zcode") {
5754
+ const activeProfName = profileNameFromPath(activeProfileFile);
5755
+ const zcodeSid = runtimeSession?.sessionId || findBoundSessionForProfile(configDir, activeProfName, (sid) => sid.startsWith("sess_")) || "";
5756
+ if (zcodeSid) {
5757
+ fireZcodeWake(data, {
5758
+ sessionId: zcodeSid,
5759
+ workspacePath: runtimeSession?.workspacePath,
5760
+ profileName: activeProfName ?? undefined,
5761
+ lockOwnerPid: process.pid,
5762
+ logger: (m) => process.stderr.write(`${m}
5763
+ `)
5764
+ });
5765
+ }
5766
+ } else {
5767
+ (async () => {
5768
+ try {
5769
+ const agyHost = discoverAntigravityHost();
5770
+ const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
5771
+ const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
5772
+ if (!agyHost && !lsAddress)
5773
+ return;
5774
+ const activeProfName = profileNameFromPath(activeProfileFile);
5775
+ const allBinds = loadSessionBinds(configDir);
5776
+ let targetCid = (runtimeSession?.runtime === "antigravity" ? runtimeSession.sessionId : "") || findBoundSessionForProfile(configDir, activeProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid) && (!agyHost || agyHost.openConversations.length === 0 || agyHost.openConversations.includes(sid))) || findBoundSessionForProfile(configDir, activeProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) || "";
5777
+ if (!targetCid && agyHost) {
5778
+ if (agyHost.openConversations.length === 1) {
5779
+ targetCid = agyHost.openConversations[0];
5780
+ } else if (agyHost.openConversations.length > 1) {
5781
+ const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] === activeProfName);
5782
+ targetCid = unboundOrSame || agyHost.openConversations[0];
5783
+ }
5784
+ }
5785
+ if (targetCid && csrfToken) {
5786
+ await fireAntigravityWake(data, {
5787
+ conversationId: targetCid,
5788
+ csrfToken,
5789
+ lsAddress: lsAddress || undefined,
5790
+ ports: agyHost?.ports,
5791
+ logger: (m) => process.stderr.write(`${m}
5792
+ `)
5793
+ });
5794
+ }
5795
+ } catch (e) {
5796
+ process.stderr.write(`[agentchat] antigravity wake error: ${e}
5797
+ `);
5798
+ }
5799
+ })();
4966
5800
  }
4967
5801
  if (activeHi)
4968
5802
  clearFinishedHiddenIdentityGamesFromMessage(data);
@@ -5045,7 +5879,16 @@ var heartbeat = new HeartbeatMonitor({
5045
5879
  },
5046
5880
  getReadyState: () => ws?.readyState ?? WS_CLOSED
5047
5881
  }, 15000, 45000, 30000);
5048
- heartbeat.start();
5882
+ if (!anonymousMode && !toolOnlyMode) {
5883
+ heartbeat.start();
5884
+ }
5885
+ function releaseLiveLock() {
5886
+ if (AGENT_ID && !toolOnlyMode) {
5887
+ try {
5888
+ releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
5889
+ } catch {}
5890
+ }
5891
+ }
5049
5892
  function shutdownFromStdio(reason) {
5050
5893
  if (shuttingDown)
5051
5894
  return;
@@ -5058,6 +5901,7 @@ function shutdownFromStdio(reason) {
5058
5901
  safeStderrWrite(`[agentchat] WARNING: read-cursor flush failed on shutdown: ${e}
5059
5902
  `);
5060
5903
  }
5904
+ releaseLiveLock();
5061
5905
  try {
5062
5906
  heartbeat.stop();
5063
5907
  } catch {}
@@ -5099,6 +5943,7 @@ function installStdioLifecycleGuards() {
5099
5943
  process.stderr.on("error", handleOutputError);
5100
5944
  process.on("SIGPIPE", () => shutdownFromStdio("SIGPIPE"));
5101
5945
  process.on("beforeExit", () => {
5946
+ releaseLiveLock();
5102
5947
  try {
5103
5948
  flushLastSeenMessageTs();
5104
5949
  } catch (e) {
@@ -5106,6 +5951,9 @@ function installStdioLifecycleGuards() {
5106
5951
  `);
5107
5952
  }
5108
5953
  });
5954
+ process.on("exit", () => {
5955
+ releaseLiveLock();
5956
+ });
5109
5957
  }
5110
5958
  async function checkVersionStaleness() {
5111
5959
  const controller = new AbortController;
@@ -5116,7 +5964,7 @@ async function checkVersionStaleness() {
5116
5964
  return;
5117
5965
  const latest = (await r.json())?.version;
5118
5966
  if (typeof latest === "string" && latest !== package_default.version) {
5119
- process.stderr.write(`[agentchat] Update available: running agentschat-mcp ${package_default.version}, latest published is ${latest}. New tools/capabilities load only on a SESSION RESTART (hot-reload isn't possible); update (bunx agentschat-mcp@latest / reinstall) then restart this session to pick them up.
5967
+ process.stderr.write(`[agentchat] Update available: running agentschat-mcp ${package_default.version}, latest published is ${latest}. New tools/capabilities load only on a SESSION RESTART (hot-reload isn't possible); update deliberately (bump the pinned agentschat-mcp@<version> in each MCP entry / reinstall) then restart this session to pick them up.
5120
5968
  `);
5121
5969
  }
5122
5970
  } catch {} finally {
@@ -5127,6 +5975,9 @@ async function main() {
5127
5975
  installStdioLifecycleGuards();
5128
5976
  if (anonymousMode) {
5129
5977
  process.stderr.write(`[agentchat] Anonymous \u2014 not connecting to the hub.
5978
+ `);
5979
+ } else if (toolOnlyMode) {
5980
+ process.stderr.write(`[agentchat] Tool-only mode (AGENTSCHAT_TOOL_ONLY=1) \u2014 skipping duplicate WS connection.
5130
5981
  `);
5131
5982
  } else {
5132
5983
  connectWS();