agentschat-mcp 0.36.13 → 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/CHANGELOG.md +15 -0
- package/README.md +63 -45
- package/codex/README.md +25 -16
- package/codex/app-server.ts +2 -0
- package/codex/bridge.ts +20 -1
- package/connector/README.md +10 -2
- package/dist/codex-bots.js +419 -512
- package/dist/codex-bridge.js +609 -567
- package/dist/connector.js +5 -5
- package/dist/server.js +1019 -174
- package/package.json +2 -1
- package/skills/grok-wake-keepalive.md +1 -1
- package/skills/onboarding.md +184 -108
- package/src/cli.mjs +5 -3
- package/src/identity-guard.ts +1 -1
- package/src/identity.ts +1 -1
- package/src/onboarding-status.ts +4 -4
- package/src/server.ts +540 -102
- package/src/session-bind.ts +382 -0
- package/src/terms.ts +10 -65
- package/src/tool-annotations.ts +2 -0
- package/src/wake.ts +240 -0
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" : "
|
|
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
|
|
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
|
|
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
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
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.
|
|
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: {
|
|
@@ -752,6 +1225,7 @@ var package_default = {
|
|
|
752
1225
|
"src/identity.ts",
|
|
753
1226
|
"src/profile-selection.ts",
|
|
754
1227
|
"src/grok-bind.ts",
|
|
1228
|
+
"src/session-bind.ts",
|
|
755
1229
|
"src/tool-annotations.ts",
|
|
756
1230
|
"src/identity-guard.ts",
|
|
757
1231
|
"src/terms.ts",
|
|
@@ -792,31 +1266,31 @@ import {
|
|
|
792
1266
|
CallToolRequestSchema,
|
|
793
1267
|
ListToolsRequestSchema
|
|
794
1268
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
795
|
-
import { readFileSync as
|
|
796
|
-
import { join as
|
|
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";
|
|
797
1271
|
|
|
798
1272
|
// src/profile-store.ts
|
|
799
|
-
import { existsSync as
|
|
800
|
-
var
|
|
801
|
-
function
|
|
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) {
|
|
802
1276
|
const tmp = path + ".tmp";
|
|
803
1277
|
try {
|
|
804
|
-
if (
|
|
805
|
-
|
|
1278
|
+
if (existsSync4(tmp))
|
|
1279
|
+
unlinkSync3(tmp);
|
|
806
1280
|
} catch (e) {
|
|
807
1281
|
warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
|
|
808
1282
|
`);
|
|
809
1283
|
}
|
|
810
|
-
|
|
811
|
-
|
|
1284
|
+
writeFileSync2(tmp, JSON.stringify(data, null, 2), { mode: 384 });
|
|
1285
|
+
renameSync2(tmp, path);
|
|
812
1286
|
try {
|
|
813
|
-
|
|
1287
|
+
chmodSync2(path, 384);
|
|
814
1288
|
} catch (e) {
|
|
815
1289
|
warn(`[agentchat] WARNING: could not chmod ${path} to 0600: ${e}
|
|
816
1290
|
`);
|
|
817
1291
|
}
|
|
818
1292
|
try {
|
|
819
|
-
const mode =
|
|
1293
|
+
const mode = statSync2(path).mode & 511;
|
|
820
1294
|
if (mode !== 384) {
|
|
821
1295
|
warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
|
|
822
1296
|
`);
|
|
@@ -899,7 +1373,7 @@ function expectedAgentIdFromEnv(env) {
|
|
|
899
1373
|
}
|
|
900
1374
|
return null;
|
|
901
1375
|
}
|
|
902
|
-
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"]);
|
|
903
1377
|
function expectedAgentIdViolation(expected, liveAgentId) {
|
|
904
1378
|
if (!expected)
|
|
905
1379
|
return null;
|
|
@@ -909,10 +1383,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
|
|
|
909
1383
|
}
|
|
910
1384
|
|
|
911
1385
|
// src/read-cursor.ts
|
|
912
|
-
import { readFileSync as
|
|
1386
|
+
import { readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
|
|
913
1387
|
function loadCursor(file, warn) {
|
|
914
1388
|
try {
|
|
915
|
-
return new Map(Object.entries(JSON.parse(
|
|
1389
|
+
return new Map(Object.entries(JSON.parse(readFileSync4(file, "utf-8"))));
|
|
916
1390
|
} catch (e) {
|
|
917
1391
|
if (e?.code !== "ENOENT") {
|
|
918
1392
|
warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
|
|
@@ -923,7 +1397,7 @@ function loadCursor(file, warn) {
|
|
|
923
1397
|
}
|
|
924
1398
|
function persistCursor(file, cursor, warn) {
|
|
925
1399
|
try {
|
|
926
|
-
|
|
1400
|
+
writeFileSync3(file, JSON.stringify(Object.fromEntries(cursor)));
|
|
927
1401
|
return true;
|
|
928
1402
|
} catch (e) {
|
|
929
1403
|
warn(`[agentchat] WARNING: failed to persist read cursor to ${file}: ${e}
|
|
@@ -1040,10 +1514,8 @@ function parseArgs() {
|
|
|
1040
1514
|
parsed.registerOnly = "1";
|
|
1041
1515
|
continue;
|
|
1042
1516
|
}
|
|
1043
|
-
if (arg === "--accept-terms")
|
|
1044
|
-
parsed.acceptTerms = "1";
|
|
1517
|
+
if (arg === "--accept-terms")
|
|
1045
1518
|
continue;
|
|
1046
|
-
}
|
|
1047
1519
|
const equal = arg.indexOf("=");
|
|
1048
1520
|
const key = (equal < 0 ? arg : arg.slice(0, equal)).slice(2);
|
|
1049
1521
|
if (!arg.startsWith("--") || !values.has(key)) {
|
|
@@ -1084,8 +1556,8 @@ Options:
|
|
|
1084
1556
|
--profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
|
|
1085
1557
|
--register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
|
|
1086
1558
|
--register Explicitly opt in to registering a new agent (implied by --name)
|
|
1087
|
-
--accept-terms
|
|
1088
|
-
|
|
1559
|
+
--accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
|
|
1560
|
+
No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
|
|
1089
1561
|
--id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
|
|
1090
1562
|
--url <url> Server URL (default: production)
|
|
1091
1563
|
--token <token> Auth token (or AGENTCHAT_TOKEN); requires its paired ID or an
|
|
@@ -1128,41 +1600,45 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
|
|
|
1128
1600
|
process.exit(0);
|
|
1129
1601
|
}
|
|
1130
1602
|
var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
1131
|
-
var configDir =
|
|
1132
|
-
var legacyConfigDir =
|
|
1603
|
+
var configDir = join4(homeDir, ".agentschat");
|
|
1604
|
+
var legacyConfigDir = join4(homeDir, ".agentchat");
|
|
1133
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);
|
|
1134
1610
|
function profileNameToPaths(name) {
|
|
1135
1611
|
if (name.startsWith("~/"))
|
|
1136
|
-
return [
|
|
1612
|
+
return [join4(homeDir, name.slice(2))];
|
|
1137
1613
|
if (name.includes("/") || name.includes("\\"))
|
|
1138
1614
|
return [name];
|
|
1139
1615
|
name = name.replace(/\.json$/, "");
|
|
1140
1616
|
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1141
|
-
return profileDirs.map((dir) =>
|
|
1617
|
+
return profileDirs.map((dir) => join4(dir, `${safeName}.json`));
|
|
1142
1618
|
}
|
|
1143
1619
|
function nameToPath(name) {
|
|
1144
1620
|
const candidates = profileNameToPaths(name);
|
|
1145
|
-
const nested =
|
|
1146
|
-
if (!name.includes("/") && !name.includes("\\") &&
|
|
1621
|
+
const nested = join4(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
|
|
1622
|
+
if (!name.includes("/") && !name.includes("\\") && existsSync5(nested))
|
|
1147
1623
|
return nested;
|
|
1148
|
-
return candidates.find((path) =>
|
|
1624
|
+
return candidates.find((path) => existsSync5(path)) || candidates[0];
|
|
1149
1625
|
}
|
|
1150
1626
|
function listProfileFiles() {
|
|
1151
1627
|
const seen = new Set;
|
|
1152
1628
|
const profiles = [];
|
|
1153
|
-
for (const dir of [
|
|
1629
|
+
for (const dir of [join4(configDir, "profiles"), ...profileDirs]) {
|
|
1154
1630
|
let files = [];
|
|
1155
1631
|
try {
|
|
1156
|
-
files =
|
|
1632
|
+
files = readdirSync2(dir).filter((f) => f.endsWith(".json"));
|
|
1157
1633
|
} catch {}
|
|
1158
1634
|
for (const file of files) {
|
|
1159
|
-
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)
|
|
1160
1636
|
continue;
|
|
1161
1637
|
const name = file.replace(/\.json$/, "");
|
|
1162
1638
|
if (seen.has(name))
|
|
1163
1639
|
continue;
|
|
1164
1640
|
seen.add(name);
|
|
1165
|
-
profiles.push({ name, path:
|
|
1641
|
+
profiles.push({ name, path: join4(dir, file) });
|
|
1166
1642
|
}
|
|
1167
1643
|
}
|
|
1168
1644
|
return profiles;
|
|
@@ -1187,9 +1663,9 @@ function resolveProfile() {
|
|
|
1187
1663
|
let binds = {};
|
|
1188
1664
|
if (!grokToken && conversationId) {
|
|
1189
1665
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
1190
|
-
if (
|
|
1666
|
+
if (existsSync5(bindPath)) {
|
|
1191
1667
|
try {
|
|
1192
|
-
const parsed = parseGrokBindsText(
|
|
1668
|
+
const parsed = parseGrokBindsText(readFileSync5(bindPath, "utf-8"));
|
|
1193
1669
|
binds = parsed.binds;
|
|
1194
1670
|
if (parsed.malformed) {
|
|
1195
1671
|
process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
|
|
@@ -1219,6 +1695,18 @@ function resolveProfile() {
|
|
|
1219
1695
|
return { path: nameToPath(process.env.AGENTSCHAT_PROFILE), source: "env", declaredName: process.env.AGENTSCHAT_PROFILE };
|
|
1220
1696
|
if (process.env.AGENTCHAT_PROFILE)
|
|
1221
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
|
+
}
|
|
1222
1710
|
return { path: nameToPath("profile"), source: "default" };
|
|
1223
1711
|
}
|
|
1224
1712
|
var { path: profileFile, source: profileSource, declaredName, agentId: projectAgentId, apiUrl: projectApiUrl, wsUrl: projectWsUrl } = resolveProfile();
|
|
@@ -1257,7 +1745,7 @@ if (hasToken && !explicitAgentId && profileSource === "default") {
|
|
|
1257
1745
|
process.exit(1);
|
|
1258
1746
|
}
|
|
1259
1747
|
var identity = decideIdentity({
|
|
1260
|
-
profileExists:
|
|
1748
|
+
profileExists: existsSync5(profileFile),
|
|
1261
1749
|
source: profileSource,
|
|
1262
1750
|
profileFile,
|
|
1263
1751
|
cliName: cliArgs.name,
|
|
@@ -1268,7 +1756,7 @@ var identity = decideIdentity({
|
|
|
1268
1756
|
});
|
|
1269
1757
|
function readIdentityProfile(file) {
|
|
1270
1758
|
try {
|
|
1271
|
-
return JSON.parse(
|
|
1759
|
+
return JSON.parse(readFileSync5(file, "utf-8"));
|
|
1272
1760
|
} catch {
|
|
1273
1761
|
throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
|
|
1274
1762
|
}
|
|
@@ -1290,8 +1778,25 @@ if (identity.mode === "profile") {
|
|
|
1290
1778
|
`);
|
|
1291
1779
|
process.exit(1);
|
|
1292
1780
|
}
|
|
1293
|
-
process.
|
|
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}
|
|
1294
1798
|
`);
|
|
1799
|
+
}
|
|
1295
1800
|
} else if (identity.mode === "env-creds") {
|
|
1296
1801
|
activeProfileFile = null;
|
|
1297
1802
|
process.stderr.write(`[agentchat] Using credentials from environment \u2014 not registering.
|
|
@@ -1308,15 +1813,8 @@ if (identity.mode === "profile") {
|
|
|
1308
1813
|
} else {
|
|
1309
1814
|
const displayName = identity.displayName;
|
|
1310
1815
|
const caps = ["claude-code", "coding", "chat"];
|
|
1311
|
-
|
|
1312
|
-
acceptFlag: !!cliArgs.acceptTerms,
|
|
1313
|
-
acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS
|
|
1314
|
-
});
|
|
1315
|
-
if (consent.mode === "refused") {
|
|
1316
|
-
process.stderr.write(`[agentchat] ERROR: ${consent.message}
|
|
1816
|
+
process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}
|
|
1317
1817
|
`);
|
|
1318
|
-
process.exit(1);
|
|
1319
|
-
}
|
|
1320
1818
|
process.stderr.write(`[agentchat] Registering "${displayName}" with server...
|
|
1321
1819
|
`);
|
|
1322
1820
|
try {
|
|
@@ -1328,8 +1826,7 @@ if (identity.mode === "profile") {
|
|
|
1328
1826
|
type: "agent",
|
|
1329
1827
|
capabilities: caps,
|
|
1330
1828
|
source: "mcp",
|
|
1331
|
-
|
|
1332
|
-
terms_version: consent.version
|
|
1829
|
+
terms_notice_version: TERMS_VERSION
|
|
1333
1830
|
})
|
|
1334
1831
|
});
|
|
1335
1832
|
if (regRes.ok) {
|
|
@@ -1340,28 +1837,29 @@ if (identity.mode === "profile") {
|
|
|
1340
1837
|
token: data.key,
|
|
1341
1838
|
capabilities: caps
|
|
1342
1839
|
};
|
|
1840
|
+
validateIdentityProfile(profile, profileFile);
|
|
1343
1841
|
process.stderr.write(`[agentchat] Registered! ID: ${data.id}
|
|
1344
1842
|
`);
|
|
1345
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.
|
|
1346
1844
|
`);
|
|
1347
|
-
process.stderr.write(`[agentchat] Next steps:
|
|
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.
|
|
1348
1846
|
`);
|
|
1349
1847
|
} else {
|
|
1350
1848
|
const body = await regRes.text().catch(() => "");
|
|
1351
1849
|
process.stderr.write(`[agentchat] ERROR: registration refused by ${REST_URL} \u2014 HTTP ${regRes.status} ${body.slice(0, 300)}
|
|
1352
|
-
` + ` No profile was written
|
|
1353
|
-
` + ` If
|
|
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.
|
|
1354
1852
|
`);
|
|
1355
1853
|
process.exit(1);
|
|
1356
1854
|
}
|
|
1357
1855
|
} catch (e) {
|
|
1358
1856
|
process.stderr.write(`[agentchat] ERROR: Registration failed: ${e}
|
|
1359
|
-
` + ` No profile was written
|
|
1857
|
+
` + ` No profile was written. Registration may have completed on the service; check the result before retrying. Nothing is running.
|
|
1360
1858
|
`);
|
|
1361
1859
|
process.exit(1);
|
|
1362
1860
|
}
|
|
1363
|
-
|
|
1364
|
-
|
|
1861
|
+
mkdirSync2(dirname(profileFile), { recursive: true });
|
|
1862
|
+
safeWriteProfile2(profileFile, profile);
|
|
1365
1863
|
process.stderr.write(`[agentchat] Profile saved: ${profileFile}
|
|
1366
1864
|
`);
|
|
1367
1865
|
}
|
|
@@ -1369,61 +1867,59 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
1369
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.
|
|
1370
1868
|
`);
|
|
1371
1869
|
} else if (!hasToken && profile.token === "dev-token") {
|
|
1372
|
-
|
|
1373
|
-
acceptFlag: !!cliArgs.acceptTerms,
|
|
1374
|
-
acceptEnv: process.env.AGENTSCHAT_ACCEPT_TERMS
|
|
1375
|
-
});
|
|
1376
|
-
if (migrationConsent.mode === "refused") {
|
|
1377
|
-
process.stderr.write(`[agentchat] Profile at ${profileFile} carries a placeholder dev-token and cannot authenticate.
|
|
1378
|
-
` + ` Healing it registers a real account: ${migrationConsent.message}
|
|
1870
|
+
process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}
|
|
1379
1871
|
`);
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
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...
|
|
1383
1874
|
`);
|
|
1384
|
-
|
|
1385
|
-
|
|
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`, {
|
|
1386
1891
|
method: "POST",
|
|
1387
1892
|
headers: { "Content-Type": "application/json" },
|
|
1388
|
-
body: JSON.stringify({
|
|
1893
|
+
body: JSON.stringify({ name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
|
|
1389
1894
|
});
|
|
1390
|
-
if (
|
|
1391
|
-
const data = await
|
|
1392
|
-
profile
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
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}
|
|
1396
1902
|
`);
|
|
1397
1903
|
} else {
|
|
1398
|
-
const
|
|
1399
|
-
|
|
1400
|
-
headers: { "Content-Type": "application/json" },
|
|
1401
|
-
body: JSON.stringify({ name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
|
|
1402
|
-
});
|
|
1403
|
-
if (regRes2.ok) {
|
|
1404
|
-
const data = await regRes2.json();
|
|
1405
|
-
profile.agent_id = data.id;
|
|
1406
|
-
profile.token = data.key;
|
|
1407
|
-
safeWriteProfile(profileFile, profile);
|
|
1408
|
-
process.stderr.write(`[agentchat] Migrated with new ID: ${data.id}
|
|
1409
|
-
`);
|
|
1410
|
-
} else {
|
|
1411
|
-
const body = await regRes2.text().catch(() => "");
|
|
1412
|
-
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)}
|
|
1413
1906
|
` + ` This profile still holds a placeholder token; authenticated calls will fail.
|
|
1414
1907
|
`);
|
|
1415
|
-
}
|
|
1416
1908
|
}
|
|
1417
|
-
}
|
|
1418
|
-
|
|
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.
|
|
1419
1912
|
`);
|
|
1420
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
|
+
`);
|
|
1421
1917
|
}
|
|
1422
1918
|
}
|
|
1423
1919
|
if (!hasToken && profile.token === "dev-token") {
|
|
1424
1920
|
process.stderr.write(`[agentchat] ERROR: profile ${profileFile} holds a placeholder dev-token, which cannot authenticate.
|
|
1425
1921
|
` + ` Not starting \u2014 a server that lists tools it cannot use is worse than one that fails.
|
|
1426
|
-
` + `
|
|
1922
|
+
` + ` Repair it: --profile <name> (registers a real account for this declared placeholder)
|
|
1427
1923
|
` + ` Or replace: register at https://agents-chat.com/join, then use --profile <name>
|
|
1428
1924
|
` + ` or AGENTCHAT_TOKEN=<token>
|
|
1429
1925
|
`);
|
|
@@ -1441,12 +1937,26 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
|
|
|
1441
1937
|
process.exit(1);
|
|
1442
1938
|
}
|
|
1443
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
|
+
}
|
|
1444
1954
|
var identityGateMessage = "";
|
|
1445
|
-
var identityGuardFile =
|
|
1955
|
+
var identityGuardFile = join4(configDir, IDENTITY_GUARD_FILENAME);
|
|
1446
1956
|
function persistGuardRecord(rec) {
|
|
1447
1957
|
try {
|
|
1448
|
-
|
|
1449
|
-
|
|
1958
|
+
mkdirSync2(configDir, { recursive: true });
|
|
1959
|
+
safeWriteProfile2(identityGuardFile, rec);
|
|
1450
1960
|
} catch {}
|
|
1451
1961
|
}
|
|
1452
1962
|
function confirmLiveIdentityTrusted() {
|
|
@@ -1461,7 +1971,7 @@ function confirmLiveIdentityTrusted() {
|
|
|
1461
1971
|
}
|
|
1462
1972
|
var guardRecord = (() => {
|
|
1463
1973
|
try {
|
|
1464
|
-
return parseGuardRecord(
|
|
1974
|
+
return parseGuardRecord(readFileSync5(identityGuardFile, "utf-8"));
|
|
1465
1975
|
} catch {
|
|
1466
1976
|
return emptyGuardRecord();
|
|
1467
1977
|
}
|
|
@@ -1502,7 +2012,7 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
|
|
|
1502
2012
|
profile.display_name = cliArgs.name;
|
|
1503
2013
|
}
|
|
1504
2014
|
if (cliArgs.registerOnly && !TOKEN) {
|
|
1505
|
-
process.stderr.write(`[agentchat] Select an existing profile or use --name
|
|
2015
|
+
process.stderr.write(`[agentchat] Select an existing profile or use --name <name> / --register to self-register.
|
|
1506
2016
|
`);
|
|
1507
2017
|
process.exit(1);
|
|
1508
2018
|
}
|
|
@@ -1511,7 +2021,7 @@ if (TOKEN && TOKEN !== "dev-token") {
|
|
|
1511
2021
|
process.stderr.write(`[agentchat] ${claimSummary(status)}
|
|
1512
2022
|
`);
|
|
1513
2023
|
if (cliArgs.registerOnly) {
|
|
1514
|
-
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 }));
|
|
1515
2025
|
process.exit(0);
|
|
1516
2026
|
}
|
|
1517
2027
|
}
|
|
@@ -1660,6 +2170,8 @@ var CORE_TOOL_NAMES = new Set([
|
|
|
1660
2170
|
"leave_channel",
|
|
1661
2171
|
"mark_read",
|
|
1662
2172
|
"switch_profile",
|
|
2173
|
+
"connect_profile",
|
|
2174
|
+
"disconnect_profile",
|
|
1663
2175
|
"list_skills",
|
|
1664
2176
|
"load_skill",
|
|
1665
2177
|
"save_skill",
|
|
@@ -2572,11 +3084,38 @@ var ALL_TOOL_DEFS = [
|
|
|
2572
3084
|
},
|
|
2573
3085
|
{
|
|
2574
3086
|
name: "switch_profile",
|
|
2575
|
-
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.",
|
|
2576
3102
|
inputSchema: {
|
|
2577
3103
|
type: "object",
|
|
2578
3104
|
properties: {
|
|
2579
|
-
profile_name: { type: "string", description: "
|
|
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" }
|
|
2580
3119
|
}
|
|
2581
3120
|
}
|
|
2582
3121
|
},
|
|
@@ -2756,10 +3295,10 @@ function mimeFromPath(p) {
|
|
|
2756
3295
|
return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
|
|
2757
3296
|
}
|
|
2758
3297
|
async function uploadLocalFile(path) {
|
|
2759
|
-
if (!
|
|
3298
|
+
if (!existsSync5(path))
|
|
2760
3299
|
throw new Error(`file not found: ${path}`);
|
|
2761
3300
|
const mime = mimeFromPath(path);
|
|
2762
|
-
const buf =
|
|
3301
|
+
const buf = readFileSync5(path);
|
|
2763
3302
|
const name = path.split("/").pop() || "upload";
|
|
2764
3303
|
const form = new FormData;
|
|
2765
3304
|
form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
|
|
@@ -2946,10 +3485,10 @@ HANDLERS.set("transcribe", async (args) => {
|
|
|
2946
3485
|
});
|
|
2947
3486
|
function loadGrokBinds() {
|
|
2948
3487
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
2949
|
-
if (!
|
|
3488
|
+
if (!existsSync5(bindPath))
|
|
2950
3489
|
return {};
|
|
2951
3490
|
try {
|
|
2952
|
-
return parseGrokBindsText(
|
|
3491
|
+
return parseGrokBindsText(readFileSync5(bindPath, "utf-8")).binds;
|
|
2953
3492
|
} catch {
|
|
2954
3493
|
return {};
|
|
2955
3494
|
}
|
|
@@ -2963,9 +3502,13 @@ function currentGrokBindApplicability(binds) {
|
|
|
2963
3502
|
binds
|
|
2964
3503
|
});
|
|
2965
3504
|
}
|
|
2966
|
-
function applyIdentityFromProfile(newProfile, targetFile) {
|
|
3505
|
+
function applyIdentityFromProfile(newProfile, targetFile, bindSessionId) {
|
|
2967
3506
|
validateIdentityProfile(newProfile, targetFile);
|
|
3507
|
+
if (AGENT_ID && AGENT_ID !== newProfile.agent_id) {
|
|
3508
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
3509
|
+
}
|
|
2968
3510
|
heartbeat.stop();
|
|
3511
|
+
stopAllTypingHeartbeats();
|
|
2969
3512
|
if (backfillTimer) {
|
|
2970
3513
|
clearTimeout(backfillTimer);
|
|
2971
3514
|
backfillTimer = null;
|
|
@@ -2988,12 +3531,243 @@ function applyIdentityFromProfile(newProfile, targetFile) {
|
|
|
2988
3531
|
profile = newProfile;
|
|
2989
3532
|
activeProfileFile = targetFile;
|
|
2990
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
|
+
}
|
|
2991
3560
|
guardRecord = advanceGuardRecord(guardRecord, { agentId: AGENT_ID, source: "switch_profile", ...profileNameFromPath(targetFile) ? { declaredName: profileNameFromPath(targetFile) } : {} }, new Date().toISOString(), true);
|
|
2992
3561
|
persistGuardRecord(guardRecord);
|
|
2993
3562
|
wsReconnectAttempt = 0;
|
|
2994
|
-
|
|
2995
|
-
|
|
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
|
+
};
|
|
2996
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
|
+
});
|
|
2997
3771
|
function ensureGrokBoundIdentity() {
|
|
2998
3772
|
if (profileSource !== "grok-bind" || hasToken || cliArgs.id || process.env.AGENTCHAT_AGENT_ID)
|
|
2999
3773
|
return;
|
|
@@ -3004,7 +3778,7 @@ function ensureGrokBoundIdentity() {
|
|
|
3004
3778
|
if (!boundName)
|
|
3005
3779
|
return;
|
|
3006
3780
|
const boundPath = nameToPath(boundName);
|
|
3007
|
-
if (!
|
|
3781
|
+
if (!existsSync5(boundPath))
|
|
3008
3782
|
return;
|
|
3009
3783
|
let boundProfile;
|
|
3010
3784
|
try {
|
|
@@ -3029,6 +3803,41 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3029
3803
|
let { name, arguments: args } = request.params;
|
|
3030
3804
|
let viaExtendedCompat = false;
|
|
3031
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
|
+
}
|
|
3032
3841
|
if (TOOL_INPUT_SCHEMAS.has(name)) {
|
|
3033
3842
|
const argErr = validateToolArgs(TOOL_INPUT_SCHEMAS.get(name), args);
|
|
3034
3843
|
if (argErr)
|
|
@@ -3255,7 +4064,7 @@ ${a.body || ""}`;
|
|
|
3255
4064
|
const currentVersion = Number(meta.version ?? 0);
|
|
3256
4065
|
let cachedVersion = null;
|
|
3257
4066
|
try {
|
|
3258
|
-
cachedVersion = Number(JSON.parse(
|
|
4067
|
+
cachedVersion = Number(JSON.parse(readFileSync5(pMeta, "utf8")).version);
|
|
3259
4068
|
} catch {}
|
|
3260
4069
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
3261
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.` }] };
|
|
@@ -3264,9 +4073,9 @@ ${a.body || ""}`;
|
|
|
3264
4073
|
if (!bodyR.ok)
|
|
3265
4074
|
return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
|
|
3266
4075
|
const doc = JSON.parse(await bodyR.text());
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
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() }));
|
|
3270
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.` }] };
|
|
3271
4080
|
} catch (e) {
|
|
3272
4081
|
return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
|
|
@@ -3289,7 +4098,7 @@ ${a.body || ""}`;
|
|
|
3289
4098
|
const currentVersion = Number(meta.version ?? 0);
|
|
3290
4099
|
let cachedVersion = null;
|
|
3291
4100
|
try {
|
|
3292
|
-
cachedVersion = Number(JSON.parse(
|
|
4101
|
+
cachedVersion = Number(JSON.parse(readFileSync5(metaPath, "utf8")).version);
|
|
3293
4102
|
} catch {}
|
|
3294
4103
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
3295
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.` }] };
|
|
@@ -3299,9 +4108,9 @@ ${a.body || ""}`;
|
|
|
3299
4108
|
return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
|
|
3300
4109
|
const doc = JSON.parse(await docR.text());
|
|
3301
4110
|
const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
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() }));
|
|
3305
4114
|
const was = cachedVersion === null ? "missing" : `stale v${cachedVersion}`;
|
|
3306
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.` }] };
|
|
3307
4116
|
} catch (e) {
|
|
@@ -3917,6 +4726,9 @@ ${brief}` }] };
|
|
|
3917
4726
|
}));
|
|
3918
4727
|
return { content: [{ type: "text", text: `Read cursor update dispatched (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3919
4728
|
}
|
|
4729
|
+
if (toolOnlyMode) {
|
|
4730
|
+
return { content: [{ type: "text", text: `Read cursor noted (up to ${last_read_id.slice(0, 8)})` }] };
|
|
4731
|
+
}
|
|
3920
4732
|
return { content: [{ type: "text", text: "Not connected" }] };
|
|
3921
4733
|
}
|
|
3922
4734
|
if (name === "whoami") {
|
|
@@ -4133,38 +4945,7 @@ ${list}` }] };
|
|
|
4133
4945
|
}
|
|
4134
4946
|
}
|
|
4135
4947
|
if (name === "switch_profile") {
|
|
4136
|
-
|
|
4137
|
-
const profileEntries = listProfileFiles();
|
|
4138
|
-
const available = profileEntries.map((entry) => entry.name);
|
|
4139
|
-
if (!profile_name) {
|
|
4140
|
-
const current = AGENT_ID;
|
|
4141
|
-
const list = available.map((p) => `${p === current ? "\u2192 " : " "}${p}`).join(`
|
|
4142
|
-
`);
|
|
4143
|
-
return { content: [{ type: "text", text: `Current: ${current}
|
|
4144
|
-
Available profiles:
|
|
4145
|
-
${list}` }] };
|
|
4146
|
-
}
|
|
4147
|
-
const switchBinds = loadGrokBinds();
|
|
4148
|
-
const bindApplies = currentGrokBindApplicability(switchBinds);
|
|
4149
|
-
const switchGate = !bindApplies.applies ? { kind: "allow" } : gateSwitchProfile({
|
|
4150
|
-
conversationId: process.env.CURSOR_CONVERSATION_ID,
|
|
4151
|
-
binds: switchBinds,
|
|
4152
|
-
requestedProfileName: profile_name,
|
|
4153
|
-
currentProfileName: profileNameFromPath(activeProfileFile)
|
|
4154
|
-
});
|
|
4155
|
-
if (switchGate.kind === "locked") {
|
|
4156
|
-
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
4157
|
-
}
|
|
4158
|
-
const targetFile = nameToPath(profile_name);
|
|
4159
|
-
if (!existsSync3(targetFile)) {
|
|
4160
|
-
return { content: [{ type: "text", text: `Profile "${profile_name}" not found. Available: ${available.join(", ")}` }], isError: true };
|
|
4161
|
-
}
|
|
4162
|
-
const newProfile = readIdentityProfile(targetFile);
|
|
4163
|
-
applyIdentityFromProfile(newProfile, targetFile);
|
|
4164
|
-
const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID ? `
|
|
4165
|
-
\uD83D\uDEA8 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) \u2014 write tools stay refused.` : "";
|
|
4166
|
-
return { content: [{ type: "text", text: `Switched to profile "${profile_name}" (${AGENT_ID}). Reconnecting...
|
|
4167
|
-
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);
|
|
4168
4949
|
}
|
|
4169
4950
|
if (name === "list_channel_docs") {
|
|
4170
4951
|
const { chat_id, level } = args;
|
|
@@ -4513,7 +5294,7 @@ Scope: this switch applies only to THIS MCP process. It is not saved \u2014 a ne
|
|
|
4513
5294
|
return { content: [{ type: "text", text: `${name} failed: ${String(e?.message || e).slice(0, 300)}` }], isError: true };
|
|
4514
5295
|
}
|
|
4515
5296
|
});
|
|
4516
|
-
var mentionTsFile =
|
|
5297
|
+
var mentionTsFile = join4(configDir, `mention-ts-${AGENT_ID}.json`);
|
|
4517
5298
|
function loadMentionTimestamps() {
|
|
4518
5299
|
return loadCursor(mentionTsFile, safeStderrWrite);
|
|
4519
5300
|
}
|
|
@@ -4521,7 +5302,7 @@ function saveMentionTimestamps(m) {
|
|
|
4521
5302
|
persistCursor(mentionTsFile, m, safeStderrWrite);
|
|
4522
5303
|
}
|
|
4523
5304
|
var lastMentionTimestamp = loadMentionTimestamps();
|
|
4524
|
-
var lastSeenMessageTsFile =
|
|
5305
|
+
var lastSeenMessageTsFile = join4(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
|
|
4525
5306
|
function loadLastSeenMessageTs() {
|
|
4526
5307
|
return loadCursor(lastSeenMessageTsFile, safeStderrWrite);
|
|
4527
5308
|
}
|
|
@@ -4935,15 +5716,15 @@ ${context}
|
|
|
4935
5716
|
if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
|
|
4936
5717
|
(async () => {
|
|
4937
5718
|
try {
|
|
4938
|
-
const { readFileSync:
|
|
4939
|
-
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY,
|
|
5719
|
+
const { readFileSync: readFileSync6, existsSync: existsSync6 } = await import("fs");
|
|
5720
|
+
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync6);
|
|
4940
5721
|
let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
|
|
4941
5722
|
if (!agentId) {
|
|
4942
5723
|
agentId = await resolveGrokAgentId({
|
|
4943
5724
|
explicitId: "",
|
|
4944
5725
|
agentschatName: profile.display_name || AGENT_ID,
|
|
4945
5726
|
listAgents: async () => {
|
|
4946
|
-
const gwcfg = JSON.parse(
|
|
5727
|
+
const gwcfg = JSON.parse(readFileSync6(gwPath, "utf8"));
|
|
4947
5728
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
4948
5729
|
const port = grokPortFromGatewayConfig(gwcfg);
|
|
4949
5730
|
const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
|
|
@@ -4964,11 +5745,58 @@ ${context}
|
|
|
4964
5745
|
`);
|
|
4965
5746
|
}
|
|
4966
5747
|
})();
|
|
4967
|
-
} else {
|
|
5748
|
+
} else if (process.env.AGENTCHAT_WAKE_URL) {
|
|
4968
5749
|
fireWake(data, {
|
|
4969
5750
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
4970
5751
|
secret: process.env.AGENTCHAT_WAKE_SECRET
|
|
4971
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
|
+
})();
|
|
4972
5800
|
}
|
|
4973
5801
|
if (activeHi)
|
|
4974
5802
|
clearFinishedHiddenIdentityGamesFromMessage(data);
|
|
@@ -5051,7 +5879,16 @@ var heartbeat = new HeartbeatMonitor({
|
|
|
5051
5879
|
},
|
|
5052
5880
|
getReadyState: () => ws?.readyState ?? WS_CLOSED
|
|
5053
5881
|
}, 15000, 45000, 30000);
|
|
5054
|
-
|
|
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
|
+
}
|
|
5055
5892
|
function shutdownFromStdio(reason) {
|
|
5056
5893
|
if (shuttingDown)
|
|
5057
5894
|
return;
|
|
@@ -5064,6 +5901,7 @@ function shutdownFromStdio(reason) {
|
|
|
5064
5901
|
safeStderrWrite(`[agentchat] WARNING: read-cursor flush failed on shutdown: ${e}
|
|
5065
5902
|
`);
|
|
5066
5903
|
}
|
|
5904
|
+
releaseLiveLock();
|
|
5067
5905
|
try {
|
|
5068
5906
|
heartbeat.stop();
|
|
5069
5907
|
} catch {}
|
|
@@ -5105,6 +5943,7 @@ function installStdioLifecycleGuards() {
|
|
|
5105
5943
|
process.stderr.on("error", handleOutputError);
|
|
5106
5944
|
process.on("SIGPIPE", () => shutdownFromStdio("SIGPIPE"));
|
|
5107
5945
|
process.on("beforeExit", () => {
|
|
5946
|
+
releaseLiveLock();
|
|
5108
5947
|
try {
|
|
5109
5948
|
flushLastSeenMessageTs();
|
|
5110
5949
|
} catch (e) {
|
|
@@ -5112,6 +5951,9 @@ function installStdioLifecycleGuards() {
|
|
|
5112
5951
|
`);
|
|
5113
5952
|
}
|
|
5114
5953
|
});
|
|
5954
|
+
process.on("exit", () => {
|
|
5955
|
+
releaseLiveLock();
|
|
5956
|
+
});
|
|
5115
5957
|
}
|
|
5116
5958
|
async function checkVersionStaleness() {
|
|
5117
5959
|
const controller = new AbortController;
|
|
@@ -5133,6 +5975,9 @@ async function main() {
|
|
|
5133
5975
|
installStdioLifecycleGuards();
|
|
5134
5976
|
if (anonymousMode) {
|
|
5135
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.
|
|
5136
5981
|
`);
|
|
5137
5982
|
} else {
|
|
5138
5983
|
connectWS();
|