agentschat-mcp 0.36.13 → 0.36.16
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 +7 -7
- package/dist/codex-bridge.js +197 -62
- package/dist/connector.js +5 -5
- package/dist/server.js +1096 -203
- 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 +614 -129
- package/src/session-bind.ts +388 -0
- package/src/terms.ts +10 -65
- package/src/tool-annotations.ts +2 -0
- package/src/wake.ts +237 -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,496 @@ 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 channel = msg.channel_id ?? "chat";
|
|
700
|
+
const sender = msg.sender_id ?? "channel";
|
|
701
|
+
const body = JSON.stringify({
|
|
702
|
+
recipient: conversationId,
|
|
703
|
+
senderId: `agentschat:${sender}`,
|
|
704
|
+
displayTitle: `AgentsChat #${channel}`,
|
|
705
|
+
content: prompt
|
|
706
|
+
});
|
|
707
|
+
const f = cfg.fetchImpl ?? fetch;
|
|
708
|
+
for (const addr of addresses) {
|
|
709
|
+
const url = `http://${addr}/exa.language_server_pb.LanguageServerService/SendAgentMessage`;
|
|
710
|
+
const ctrl = new AbortController;
|
|
711
|
+
const t = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 5000);
|
|
712
|
+
try {
|
|
713
|
+
const res = await f(url, {
|
|
714
|
+
method: "POST",
|
|
715
|
+
headers: {
|
|
716
|
+
"Content-Type": "application/json",
|
|
717
|
+
"Connect-Protocol-Version": "1",
|
|
718
|
+
"x-codeium-csrf-token": csrfToken
|
|
719
|
+
},
|
|
720
|
+
body,
|
|
721
|
+
signal: ctrl.signal
|
|
722
|
+
});
|
|
723
|
+
if (res.ok) {
|
|
724
|
+
return true;
|
|
725
|
+
}
|
|
726
|
+
log(`[agentchat] antigravity wake POST ${url} → HTTP ${res.status}`);
|
|
727
|
+
} catch {} finally {
|
|
728
|
+
clearTimeout(t);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
log(`[agentchat] antigravity wake: all candidate ports (${addresses.join(", ")}) failed for ${conversationId}`);
|
|
732
|
+
return false;
|
|
733
|
+
}
|
|
734
|
+
var zcodeSessionQueues = new Map;
|
|
735
|
+
async function resolveZcodeCommand(explicitBin) {
|
|
736
|
+
const fromArg = (explicitBin ?? process.env.ZCODE_BIN ?? "").trim();
|
|
737
|
+
if (fromArg) {
|
|
738
|
+
if (fromArg.endsWith(".cjs") || fromArg.endsWith(".js")) {
|
|
739
|
+
return { cmd: "node", prefixArgs: [fromArg] };
|
|
740
|
+
}
|
|
741
|
+
return { cmd: fromArg, prefixArgs: [] };
|
|
742
|
+
}
|
|
743
|
+
const macAppBundleCjs = "/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs";
|
|
744
|
+
try {
|
|
745
|
+
const { existsSync: existsSync2 } = await import("node:fs");
|
|
746
|
+
if (existsSync2(macAppBundleCjs)) {
|
|
747
|
+
return { cmd: "node", prefixArgs: [macAppBundleCjs] };
|
|
748
|
+
}
|
|
749
|
+
} catch {}
|
|
750
|
+
return { cmd: "zcode", prefixArgs: [] };
|
|
751
|
+
}
|
|
752
|
+
function fireZcodeWake(msg, cfg) {
|
|
753
|
+
const log = cfg.logger ?? (() => {});
|
|
754
|
+
const sessionId = (cfg.sessionId ?? "").trim();
|
|
755
|
+
if (!sessionId) {
|
|
756
|
+
log(`[agentchat] zcode wake: missing sessionId, skipping`);
|
|
757
|
+
return Promise.resolve(false);
|
|
758
|
+
}
|
|
759
|
+
const prompt = cfg.promptOverride ?? buildWakePrompt(msg);
|
|
760
|
+
const prev = zcodeSessionQueues.get(sessionId) ?? Promise.resolve();
|
|
761
|
+
let succeeded = false;
|
|
762
|
+
const runTurn = async () => {
|
|
763
|
+
try {
|
|
764
|
+
const { cmd, prefixArgs } = await resolveZcodeCommand(cfg.zcodeBin);
|
|
765
|
+
const args = [...prefixArgs, "-p", prompt, "--resume", sessionId];
|
|
766
|
+
if (cfg.workspacePath && cfg.workspacePath.trim()) {
|
|
767
|
+
args.push("--cwd", cfg.workspacePath.trim());
|
|
768
|
+
}
|
|
769
|
+
const env = {
|
|
770
|
+
...process.env,
|
|
771
|
+
AGENTSCHAT_TOOL_ONLY: "1",
|
|
772
|
+
AGENTSCHAT_LOCK_OWNER_PID: String(cfg.lockOwnerPid ?? process.pid),
|
|
773
|
+
ZCODE_SESSION_ID: sessionId,
|
|
774
|
+
...cfg.profileName ? { AGENTSCHAT_PROFILE: cfg.profileName } : {}
|
|
775
|
+
};
|
|
776
|
+
const timeoutMs = cfg.timeoutMs ?? 180000;
|
|
777
|
+
if (cfg.runCommandImpl) {
|
|
778
|
+
const res = await cfg.runCommandImpl(cmd, args, { cwd: cfg.workspacePath, env, timeoutMs });
|
|
779
|
+
succeeded = res.code === 0;
|
|
780
|
+
if (!succeeded) {
|
|
781
|
+
log(`[agentchat] zcode wake (${sessionId}) exited with code ${res.code}${res.stderr ? `: ${res.stderr.slice(0, 200)}` : ""}`);
|
|
782
|
+
}
|
|
783
|
+
return;
|
|
784
|
+
}
|
|
785
|
+
const { spawn } = await import("node:child_process");
|
|
786
|
+
await new Promise((resolve2) => {
|
|
787
|
+
const child = spawn(cmd, args, {
|
|
788
|
+
cwd: cfg.workspacePath || process.cwd(),
|
|
789
|
+
env,
|
|
790
|
+
stdio: ["ignore", "ignore", "pipe"]
|
|
791
|
+
});
|
|
792
|
+
let stderr = "";
|
|
793
|
+
child.stderr?.on("data", (chunk) => {
|
|
794
|
+
if (stderr.length < 500)
|
|
795
|
+
stderr += String(chunk);
|
|
796
|
+
});
|
|
797
|
+
const timer = setTimeout(() => {
|
|
798
|
+
try {
|
|
799
|
+
child.kill("SIGTERM");
|
|
800
|
+
} catch {}
|
|
801
|
+
}, timeoutMs);
|
|
802
|
+
child.on("error", (err) => {
|
|
803
|
+
clearTimeout(timer);
|
|
804
|
+
log(`[agentchat] zcode wake spawn error (${sessionId}): ${err}`);
|
|
805
|
+
resolve2();
|
|
806
|
+
});
|
|
807
|
+
child.on("close", (code) => {
|
|
808
|
+
clearTimeout(timer);
|
|
809
|
+
succeeded = code === 0;
|
|
810
|
+
if (!succeeded) {
|
|
811
|
+
log(`[agentchat] zcode wake (${sessionId}) exited code=${code}${stderr ? `: ${stderr.trim().slice(0, 200)}` : ""}`);
|
|
812
|
+
}
|
|
813
|
+
resolve2();
|
|
814
|
+
});
|
|
815
|
+
});
|
|
816
|
+
} catch (e) {
|
|
817
|
+
log(`[agentchat] zcode wake failed (${sessionId}): ${e}`);
|
|
818
|
+
}
|
|
819
|
+
};
|
|
820
|
+
const next = prev.then(runTurn, runTurn);
|
|
821
|
+
zcodeSessionQueues.set(sessionId, next);
|
|
822
|
+
return next.then(() => {
|
|
823
|
+
if (zcodeSessionQueues.get(sessionId) === next) {
|
|
824
|
+
zcodeSessionQueues.delete(sessionId);
|
|
825
|
+
}
|
|
826
|
+
return succeeded;
|
|
827
|
+
});
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// src/session-bind.ts
|
|
831
|
+
import { createHash } from "node:crypto";
|
|
832
|
+
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, unlinkSync as unlinkSync2 } from "node:fs";
|
|
833
|
+
import { tmpdir } from "node:os";
|
|
834
|
+
import { join as join3 } from "node:path";
|
|
835
|
+
import { spawnSync } from "node:child_process";
|
|
836
|
+
|
|
837
|
+
// src/profile-store.ts
|
|
838
|
+
import { existsSync as existsSync2, writeFileSync, renameSync, chmodSync, unlinkSync, statSync } from "fs";
|
|
839
|
+
var defaultWarn = (m) => process.stderr.write(m);
|
|
840
|
+
function safeWriteProfile(path, data, warn = defaultWarn) {
|
|
841
|
+
const tmp = path + ".tmp";
|
|
842
|
+
try {
|
|
843
|
+
if (existsSync2(tmp))
|
|
844
|
+
unlinkSync(tmp);
|
|
845
|
+
} catch (e) {
|
|
846
|
+
warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
|
|
847
|
+
`);
|
|
848
|
+
}
|
|
849
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2), { mode: 384 });
|
|
850
|
+
renameSync(tmp, path);
|
|
851
|
+
try {
|
|
852
|
+
chmodSync(path, 384);
|
|
853
|
+
} catch (e) {
|
|
854
|
+
warn(`[agentchat] WARNING: could not chmod ${path} to 0600: ${e}
|
|
855
|
+
`);
|
|
856
|
+
}
|
|
857
|
+
try {
|
|
858
|
+
const mode = statSync(path).mode & 511;
|
|
859
|
+
if (mode !== 384) {
|
|
860
|
+
warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
|
|
861
|
+
`);
|
|
862
|
+
}
|
|
863
|
+
} catch (e) {
|
|
864
|
+
warn(`[agentchat] WARNING: could not verify permissions of ${path}: ${e}
|
|
865
|
+
`);
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
|
|
869
|
+
// src/session-bind.ts
|
|
870
|
+
var DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
|
|
871
|
+
var LEGACY_AGY_BINDS_FILENAME = "agy-binds.json";
|
|
872
|
+
function isPidAlive(pid) {
|
|
873
|
+
if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0)
|
|
874
|
+
return false;
|
|
875
|
+
try {
|
|
876
|
+
process.kill(pid, 0);
|
|
877
|
+
return true;
|
|
878
|
+
} catch (e) {
|
|
879
|
+
if (e && typeof e === "object" && e.code === "EPERM")
|
|
880
|
+
return true;
|
|
881
|
+
return false;
|
|
882
|
+
}
|
|
883
|
+
}
|
|
884
|
+
function resolveLockDir(homeDir, env = process.env) {
|
|
885
|
+
const explicit = env.AGENTSCHAT_LOCK_DIR?.trim();
|
|
886
|
+
if (explicit)
|
|
887
|
+
return explicit;
|
|
888
|
+
const hash = createHash("sha256").update(homeDir || ".").digest("hex").slice(0, 12);
|
|
889
|
+
const baseTmp = process.platform === "win32" ? tmpdir() : "/tmp";
|
|
890
|
+
return join3(baseTmp, `agentschat-locks-${hash}`);
|
|
891
|
+
}
|
|
892
|
+
function lockFilePath(lockDir, agentId) {
|
|
893
|
+
const safe = String(agentId || "").trim().replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
894
|
+
return join3(lockDir, `${safe}.lock`);
|
|
895
|
+
}
|
|
896
|
+
function readAgentLock(lockDir, agentId) {
|
|
897
|
+
if (!agentId)
|
|
898
|
+
return null;
|
|
899
|
+
const file = lockFilePath(lockDir, agentId);
|
|
900
|
+
if (!existsSync3(file))
|
|
901
|
+
return null;
|
|
902
|
+
try {
|
|
903
|
+
const raw = JSON.parse(readFileSync3(file, "utf8"));
|
|
904
|
+
if (!raw || typeof raw !== "object" || typeof raw.pid !== "number" || typeof raw.agentId !== "string") {
|
|
905
|
+
return null;
|
|
906
|
+
}
|
|
907
|
+
return raw;
|
|
908
|
+
} catch {
|
|
909
|
+
return null;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
function checkAgentLock(opts) {
|
|
913
|
+
const { lockDir, agentId } = opts;
|
|
914
|
+
const currentPid = opts.currentPid ?? process.pid;
|
|
915
|
+
if (!agentId)
|
|
916
|
+
return { locked: false };
|
|
917
|
+
const record = readAgentLock(lockDir, agentId);
|
|
918
|
+
if (!record)
|
|
919
|
+
return { locked: false };
|
|
920
|
+
if (!isPidAlive(record.pid)) {
|
|
921
|
+
try {
|
|
922
|
+
unlinkSync2(lockFilePath(lockDir, agentId));
|
|
923
|
+
} catch {}
|
|
924
|
+
return { locked: false, stale: true };
|
|
925
|
+
}
|
|
926
|
+
if (record.pid === currentPid)
|
|
927
|
+
return { locked: false, holder: record };
|
|
928
|
+
if (opts.lockOwnerPid && record.pid === opts.lockOwnerPid)
|
|
929
|
+
return { locked: false, holder: record };
|
|
930
|
+
if (opts.currentSessionId && record.sessionId && opts.currentSessionId === record.sessionId) {
|
|
931
|
+
return { locked: false, holder: record };
|
|
932
|
+
}
|
|
933
|
+
return { locked: true, holder: record };
|
|
934
|
+
}
|
|
935
|
+
function acquireAgentLock(opts) {
|
|
936
|
+
if (!opts.agentId)
|
|
937
|
+
return null;
|
|
938
|
+
const record = {
|
|
939
|
+
pid: opts.currentPid ?? process.pid,
|
|
940
|
+
agentId: opts.agentId,
|
|
941
|
+
profileName: opts.profileName ?? null,
|
|
942
|
+
sessionId: opts.sessionId ?? null,
|
|
943
|
+
runtime: opts.runtime ?? "mcp",
|
|
944
|
+
updatedAt: new Date().toISOString()
|
|
945
|
+
};
|
|
946
|
+
try {
|
|
947
|
+
mkdirSync(opts.lockDir, { recursive: true, mode: 448 });
|
|
948
|
+
safeWriteProfile(lockFilePath(opts.lockDir, opts.agentId), record);
|
|
949
|
+
return record;
|
|
950
|
+
} catch {
|
|
951
|
+
return null;
|
|
952
|
+
}
|
|
953
|
+
}
|
|
954
|
+
function releaseAgentLock(opts) {
|
|
955
|
+
if (!opts.agentId)
|
|
956
|
+
return false;
|
|
957
|
+
const currentPid = opts.currentPid ?? process.pid;
|
|
958
|
+
const existing = readAgentLock(opts.lockDir, opts.agentId);
|
|
959
|
+
if (!existing)
|
|
960
|
+
return false;
|
|
961
|
+
const samePid = existing.pid === currentPid;
|
|
962
|
+
const sameSession = Boolean(opts.currentSessionId && existing.sessionId && opts.currentSessionId === existing.sessionId);
|
|
963
|
+
const dead = !isPidAlive(existing.pid);
|
|
964
|
+
if (!samePid && !sameSession && !dead)
|
|
965
|
+
return false;
|
|
966
|
+
try {
|
|
967
|
+
unlinkSync2(lockFilePath(opts.lockDir, opts.agentId));
|
|
968
|
+
return true;
|
|
969
|
+
} catch {
|
|
970
|
+
return false;
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
function parseSessionBinds(raw) {
|
|
974
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
975
|
+
return {};
|
|
976
|
+
const out = {};
|
|
977
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
978
|
+
const key = k.trim();
|
|
979
|
+
if (!key)
|
|
980
|
+
continue;
|
|
981
|
+
if (typeof v === "string" && v.trim()) {
|
|
982
|
+
out[key] = v.trim();
|
|
983
|
+
} else if (v && typeof v === "object" && typeof v.profile === "string" && v.profile.trim()) {
|
|
984
|
+
out[key] = v.profile.trim();
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
return out;
|
|
988
|
+
}
|
|
989
|
+
function loadSessionBinds(configDir) {
|
|
990
|
+
const merged = {};
|
|
991
|
+
for (const filename of [LEGACY_AGY_BINDS_FILENAME, DEFAULT_SESSION_BINDS_FILENAME]) {
|
|
992
|
+
const path = join3(configDir, filename);
|
|
993
|
+
if (!existsSync3(path))
|
|
994
|
+
continue;
|
|
995
|
+
try {
|
|
996
|
+
Object.assign(merged, parseSessionBinds(JSON.parse(readFileSync3(path, "utf8"))));
|
|
997
|
+
} catch {}
|
|
998
|
+
}
|
|
999
|
+
return merged;
|
|
1000
|
+
}
|
|
1001
|
+
function saveSessionBind(configDir, sessionId, profileName) {
|
|
1002
|
+
const sid = sessionId.trim();
|
|
1003
|
+
const prof = profileName.trim();
|
|
1004
|
+
if (!sid || !prof)
|
|
1005
|
+
return;
|
|
1006
|
+
const path = join3(configDir, DEFAULT_SESSION_BINDS_FILENAME);
|
|
1007
|
+
let current = {};
|
|
1008
|
+
if (existsSync3(path)) {
|
|
1009
|
+
try {
|
|
1010
|
+
current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
|
|
1011
|
+
} catch {}
|
|
1012
|
+
}
|
|
1013
|
+
current[sid] = prof;
|
|
1014
|
+
mkdirSync(configDir, { recursive: true });
|
|
1015
|
+
safeWriteProfile(path, current);
|
|
1016
|
+
}
|
|
1017
|
+
function removeSessionBind(configDir, sessionId) {
|
|
1018
|
+
const sid = sessionId.trim();
|
|
1019
|
+
if (!sid)
|
|
1020
|
+
return false;
|
|
1021
|
+
let removed = false;
|
|
1022
|
+
for (const filename of [DEFAULT_SESSION_BINDS_FILENAME, LEGACY_AGY_BINDS_FILENAME]) {
|
|
1023
|
+
const path = join3(configDir, filename);
|
|
1024
|
+
if (!existsSync3(path))
|
|
1025
|
+
continue;
|
|
1026
|
+
try {
|
|
1027
|
+
const current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
|
|
1028
|
+
if (sid in current) {
|
|
1029
|
+
delete current[sid];
|
|
1030
|
+
safeWriteProfile(path, current);
|
|
1031
|
+
removed = true;
|
|
1032
|
+
}
|
|
1033
|
+
} catch {}
|
|
1034
|
+
}
|
|
1035
|
+
return removed;
|
|
1036
|
+
}
|
|
1037
|
+
function findBoundSessionForProfile(configDir, profileName, filter) {
|
|
1038
|
+
if (!profileName)
|
|
1039
|
+
return null;
|
|
1040
|
+
const target = profileName.trim();
|
|
1041
|
+
if (!target)
|
|
1042
|
+
return null;
|
|
1043
|
+
const binds = loadSessionBinds(configDir);
|
|
1044
|
+
const matches = [];
|
|
1045
|
+
for (const [sid, prof] of Object.entries(binds)) {
|
|
1046
|
+
if (prof === target && (!filter || filter(sid)))
|
|
1047
|
+
matches.push(sid);
|
|
1048
|
+
}
|
|
1049
|
+
return matches.length > 0 ? matches[matches.length - 1] : null;
|
|
1050
|
+
}
|
|
1051
|
+
function detectRuntimeSession(env = process.env, meta) {
|
|
1052
|
+
const zcodeCtx = meta?.["com.zcode/request-context"];
|
|
1053
|
+
const metaSessionId = typeof meta?.session_id === "string" && meta.session_id.trim() || typeof zcodeCtx?.session_id === "string" && zcodeCtx.session_id.trim() || "";
|
|
1054
|
+
if (metaSessionId) {
|
|
1055
|
+
const workspacePath = typeof meta?.workspace_path === "string" && meta.workspace_path.trim() || typeof zcodeCtx?.workspace_path === "string" && zcodeCtx.workspace_path.trim() || undefined;
|
|
1056
|
+
return { sessionId: metaSessionId, runtime: "zcode", ...workspacePath ? { workspacePath } : {} };
|
|
1057
|
+
}
|
|
1058
|
+
const zcodeEnvSid = env.ZCODE_SESSION_ID?.trim();
|
|
1059
|
+
if (zcodeEnvSid) {
|
|
1060
|
+
const workspacePath = env.ZCODE_PROJECT_DIR?.trim() || undefined;
|
|
1061
|
+
return { sessionId: zcodeEnvSid, runtime: "zcode", ...workspacePath ? { workspacePath } : {} };
|
|
1062
|
+
}
|
|
1063
|
+
const agySid = env.ANTIGRAVITY_CONVERSATION_ID?.trim();
|
|
1064
|
+
if (agySid) {
|
|
1065
|
+
return { sessionId: agySid, runtime: "antigravity" };
|
|
1066
|
+
}
|
|
1067
|
+
if (env.__CFBundleIdentifier === "com.google.antigravity" || env.AGY_BROWSER_WS_URL) {
|
|
1068
|
+
const agyHost = discoverAntigravityHost();
|
|
1069
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
1070
|
+
return { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
|
|
1071
|
+
}
|
|
1072
|
+
}
|
|
1073
|
+
const claudeSid = (env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || "").trim();
|
|
1074
|
+
if (claudeSid) {
|
|
1075
|
+
const workspacePath = env.CLAUDE_PROJECT_DIR?.trim() || undefined;
|
|
1076
|
+
return { sessionId: claudeSid, runtime: "claude-code", ...workspacePath ? { workspacePath } : {} };
|
|
1077
|
+
}
|
|
1078
|
+
const explicitSid = (env.AGENTSCHAT_SESSION_ID || env.AGENTCHAT_SESSION_ID || "").trim();
|
|
1079
|
+
if (explicitSid) {
|
|
1080
|
+
return { sessionId: explicitSid, runtime: "custom" };
|
|
1081
|
+
}
|
|
1082
|
+
return null;
|
|
1083
|
+
}
|
|
1084
|
+
var cachedAgyHost = null;
|
|
1085
|
+
function discoverAntigravityHost(opts) {
|
|
1086
|
+
const now = Date.now();
|
|
1087
|
+
const cacheMs = opts?.cacheMs ?? 5000;
|
|
1088
|
+
if (cachedAgyHost && now - cachedAgyHost.at < cacheMs)
|
|
1089
|
+
return cachedAgyHost.info;
|
|
1090
|
+
try {
|
|
1091
|
+
let pid = opts?.currentPid ?? process.pid;
|
|
1092
|
+
let lsPid = 0;
|
|
1093
|
+
let lsCmd = "";
|
|
1094
|
+
for (let hop = 0;hop < 4 && pid > 1; hop++) {
|
|
1095
|
+
const ps = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "ppid=,command="], { encoding: "utf8", timeout: 1000 });
|
|
1096
|
+
if (ps.status !== 0 || !ps.stdout)
|
|
1097
|
+
break;
|
|
1098
|
+
const line = ps.stdout.trim().split(/\r?\n/)[0]?.trim() || "";
|
|
1099
|
+
const m = line.match(/^(\d+)\s+(.*)$/);
|
|
1100
|
+
if (!m)
|
|
1101
|
+
break;
|
|
1102
|
+
const ppid = Number(m[1]);
|
|
1103
|
+
const cmd = m[2];
|
|
1104
|
+
if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test")))
|
|
1105
|
+
break;
|
|
1106
|
+
if (cmd.includes("language_server") && cmd.includes("--csrf_token")) {
|
|
1107
|
+
lsPid = pid;
|
|
1108
|
+
lsCmd = cmd;
|
|
1109
|
+
break;
|
|
1110
|
+
}
|
|
1111
|
+
pid = ppid;
|
|
1112
|
+
}
|
|
1113
|
+
if (!lsPid) {
|
|
1114
|
+
cachedAgyHost = { at: now, info: null };
|
|
1115
|
+
return null;
|
|
1116
|
+
}
|
|
1117
|
+
const csrfMatch = lsCmd.match(/--csrf_token[=\s]+([^\s]+)/);
|
|
1118
|
+
const csrfToken = csrfMatch?.[1]?.trim() || "";
|
|
1119
|
+
if (!csrfToken) {
|
|
1120
|
+
cachedAgyHost = { at: now, info: null };
|
|
1121
|
+
return null;
|
|
1122
|
+
}
|
|
1123
|
+
const lsof = spawnSync("lsof", ["-Pan", "-p", String(lsPid)], { encoding: "utf8", timeout: 1500 });
|
|
1124
|
+
const ports = [];
|
|
1125
|
+
const openConversations = [];
|
|
1126
|
+
if (lsof.status === 0 && lsof.stdout) {
|
|
1127
|
+
for (const line of lsof.stdout.split(/\r?\n/)) {
|
|
1128
|
+
const portMatch = line.match(/127\.0\.0\.1:(\d+)\s+\(LISTEN\)/);
|
|
1129
|
+
if (portMatch) {
|
|
1130
|
+
const p = Number(portMatch[1]);
|
|
1131
|
+
if (p > 0 && !ports.includes(p))
|
|
1132
|
+
ports.push(p);
|
|
1133
|
+
}
|
|
1134
|
+
const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/);
|
|
1135
|
+
if (presMatch) {
|
|
1136
|
+
const cid = presMatch[1];
|
|
1137
|
+
if (!openConversations.includes(cid))
|
|
1138
|
+
openConversations.push(cid);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
ports.sort((a, b) => b - a);
|
|
1143
|
+
const info = { lsPid, csrfToken, ports, openConversations };
|
|
1144
|
+
cachedAgyHost = { at: now, info };
|
|
1145
|
+
return info;
|
|
1146
|
+
} catch {
|
|
1147
|
+
cachedAgyHost = { at: now, info: null };
|
|
1148
|
+
return null;
|
|
1149
|
+
}
|
|
1150
|
+
}
|
|
675
1151
|
// package.json
|
|
676
1152
|
var package_default = {
|
|
677
1153
|
name: "agentschat-mcp",
|
|
678
1154
|
mcpName: "io.github.swswordholy-tech/agentschat-mcp",
|
|
679
|
-
version: "0.36.
|
|
1155
|
+
version: "0.36.16",
|
|
680
1156
|
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
1157
|
type: "module",
|
|
682
1158
|
bin: {
|
|
@@ -752,6 +1228,7 @@ var package_default = {
|
|
|
752
1228
|
"src/identity.ts",
|
|
753
1229
|
"src/profile-selection.ts",
|
|
754
1230
|
"src/grok-bind.ts",
|
|
1231
|
+
"src/session-bind.ts",
|
|
755
1232
|
"src/tool-annotations.ts",
|
|
756
1233
|
"src/identity-guard.ts",
|
|
757
1234
|
"src/terms.ts",
|
|
@@ -792,31 +1269,31 @@ import {
|
|
|
792
1269
|
CallToolRequestSchema,
|
|
793
1270
|
ListToolsRequestSchema
|
|
794
1271
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
795
|
-
import { readFileSync as
|
|
796
|
-
import { join as
|
|
1272
|
+
import { readFileSync as readFileSync5, existsSync as existsSync5, writeFileSync as writeFileSync4, mkdirSync as mkdirSync2, readdirSync as readdirSync2 } from "fs";
|
|
1273
|
+
import { join as join4, dirname } from "path";
|
|
797
1274
|
|
|
798
1275
|
// src/profile-store.ts
|
|
799
|
-
import { existsSync as
|
|
800
|
-
var
|
|
801
|
-
function
|
|
1276
|
+
import { existsSync as existsSync4, writeFileSync as writeFileSync2, renameSync as renameSync2, chmodSync as chmodSync2, unlinkSync as unlinkSync3, statSync as statSync2 } from "fs";
|
|
1277
|
+
var defaultWarn2 = (m) => process.stderr.write(m);
|
|
1278
|
+
function safeWriteProfile2(path, data, warn = defaultWarn2) {
|
|
802
1279
|
const tmp = path + ".tmp";
|
|
803
1280
|
try {
|
|
804
|
-
if (
|
|
805
|
-
|
|
1281
|
+
if (existsSync4(tmp))
|
|
1282
|
+
unlinkSync3(tmp);
|
|
806
1283
|
} catch (e) {
|
|
807
1284
|
warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
|
|
808
1285
|
`);
|
|
809
1286
|
}
|
|
810
|
-
|
|
811
|
-
|
|
1287
|
+
writeFileSync2(tmp, JSON.stringify(data, null, 2), { mode: 384 });
|
|
1288
|
+
renameSync2(tmp, path);
|
|
812
1289
|
try {
|
|
813
|
-
|
|
1290
|
+
chmodSync2(path, 384);
|
|
814
1291
|
} catch (e) {
|
|
815
1292
|
warn(`[agentchat] WARNING: could not chmod ${path} to 0600: ${e}
|
|
816
1293
|
`);
|
|
817
1294
|
}
|
|
818
1295
|
try {
|
|
819
|
-
const mode =
|
|
1296
|
+
const mode = statSync2(path).mode & 511;
|
|
820
1297
|
if (mode !== 384) {
|
|
821
1298
|
warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
|
|
822
1299
|
`);
|
|
@@ -899,7 +1376,7 @@ function expectedAgentIdFromEnv(env) {
|
|
|
899
1376
|
}
|
|
900
1377
|
return null;
|
|
901
1378
|
}
|
|
902
|
-
var EXPECT_PIN_EXEMPT_TOOLS = new Set(["whoami", "switch_profile"]);
|
|
1379
|
+
var EXPECT_PIN_EXEMPT_TOOLS = new Set(["whoami", "switch_profile", "connect_profile", "disconnect_profile"]);
|
|
903
1380
|
function expectedAgentIdViolation(expected, liveAgentId) {
|
|
904
1381
|
if (!expected)
|
|
905
1382
|
return null;
|
|
@@ -909,10 +1386,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
|
|
|
909
1386
|
}
|
|
910
1387
|
|
|
911
1388
|
// src/read-cursor.ts
|
|
912
|
-
import { readFileSync as
|
|
1389
|
+
import { readFileSync as readFileSync4, writeFileSync as writeFileSync3 } from "fs";
|
|
913
1390
|
function loadCursor(file, warn) {
|
|
914
1391
|
try {
|
|
915
|
-
return new Map(Object.entries(JSON.parse(
|
|
1392
|
+
return new Map(Object.entries(JSON.parse(readFileSync4(file, "utf-8"))));
|
|
916
1393
|
} catch (e) {
|
|
917
1394
|
if (e?.code !== "ENOENT") {
|
|
918
1395
|
warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
|
|
@@ -923,7 +1400,7 @@ function loadCursor(file, warn) {
|
|
|
923
1400
|
}
|
|
924
1401
|
function persistCursor(file, cursor, warn) {
|
|
925
1402
|
try {
|
|
926
|
-
|
|
1403
|
+
writeFileSync3(file, JSON.stringify(Object.fromEntries(cursor)));
|
|
927
1404
|
return true;
|
|
928
1405
|
} catch (e) {
|
|
929
1406
|
warn(`[agentchat] WARNING: failed to persist read cursor to ${file}: ${e}
|
|
@@ -1040,10 +1517,8 @@ function parseArgs() {
|
|
|
1040
1517
|
parsed.registerOnly = "1";
|
|
1041
1518
|
continue;
|
|
1042
1519
|
}
|
|
1043
|
-
if (arg === "--accept-terms")
|
|
1044
|
-
parsed.acceptTerms = "1";
|
|
1520
|
+
if (arg === "--accept-terms")
|
|
1045
1521
|
continue;
|
|
1046
|
-
}
|
|
1047
1522
|
const equal = arg.indexOf("=");
|
|
1048
1523
|
const key = (equal < 0 ? arg : arg.slice(0, equal)).slice(2);
|
|
1049
1524
|
if (!arg.startsWith("--") || !values.has(key)) {
|
|
@@ -1084,8 +1559,8 @@ Options:
|
|
|
1084
1559
|
--profile <name> Use specific profile (~/.agentschat/<name>.json, falls back to ~/.agentchat)
|
|
1085
1560
|
--register-only Save/inspect the selected identity and print a private setup result (includes a credential-bearing claim link), then exit.
|
|
1086
1561
|
--register Explicitly opt in to registering a new agent (implied by --name)
|
|
1087
|
-
--accept-terms
|
|
1088
|
-
|
|
1562
|
+
--accept-terms Deprecated compatibility flag; Terms are a nonblocking notice.
|
|
1563
|
+
No acceptance flag or AGENTSCHAT_ACCEPT_TERMS is needed.
|
|
1089
1564
|
--id <id> Existing agent ID paired with the token (or AGENTCHAT_AGENT_ID)
|
|
1090
1565
|
--url <url> Server URL (default: production)
|
|
1091
1566
|
--token <token> Auth token (or AGENTCHAT_TOKEN); requires its paired ID or an
|
|
@@ -1128,41 +1603,45 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
|
|
|
1128
1603
|
process.exit(0);
|
|
1129
1604
|
}
|
|
1130
1605
|
var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
1131
|
-
var configDir =
|
|
1132
|
-
var legacyConfigDir =
|
|
1606
|
+
var configDir = join4(homeDir, ".agentschat");
|
|
1607
|
+
var legacyConfigDir = join4(homeDir, ".agentchat");
|
|
1133
1608
|
var profileDirs = [configDir, legacyConfigDir];
|
|
1609
|
+
var lockDir = resolveLockDir(homeDir, process.env);
|
|
1610
|
+
var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
|
|
1611
|
+
var toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
|
|
1612
|
+
var runtimeSession = detectRuntimeSession(process.env);
|
|
1134
1613
|
function profileNameToPaths(name) {
|
|
1135
1614
|
if (name.startsWith("~/"))
|
|
1136
|
-
return [
|
|
1615
|
+
return [join4(homeDir, name.slice(2))];
|
|
1137
1616
|
if (name.includes("/") || name.includes("\\"))
|
|
1138
1617
|
return [name];
|
|
1139
1618
|
name = name.replace(/\.json$/, "");
|
|
1140
1619
|
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1141
|
-
return profileDirs.map((dir) =>
|
|
1620
|
+
return profileDirs.map((dir) => join4(dir, `${safeName}.json`));
|
|
1142
1621
|
}
|
|
1143
1622
|
function nameToPath(name) {
|
|
1144
1623
|
const candidates = profileNameToPaths(name);
|
|
1145
|
-
const nested =
|
|
1146
|
-
if (!name.includes("/") && !name.includes("\\") &&
|
|
1624
|
+
const nested = join4(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
|
|
1625
|
+
if (!name.includes("/") && !name.includes("\\") && existsSync5(nested))
|
|
1147
1626
|
return nested;
|
|
1148
|
-
return candidates.find((path) =>
|
|
1627
|
+
return candidates.find((path) => existsSync5(path)) || candidates[0];
|
|
1149
1628
|
}
|
|
1150
1629
|
function listProfileFiles() {
|
|
1151
1630
|
const seen = new Set;
|
|
1152
1631
|
const profiles = [];
|
|
1153
|
-
for (const dir of [
|
|
1632
|
+
for (const dir of [join4(configDir, "profiles"), ...profileDirs]) {
|
|
1154
1633
|
let files = [];
|
|
1155
1634
|
try {
|
|
1156
|
-
files =
|
|
1635
|
+
files = readdirSync2(dir).filter((f) => f.endsWith(".json"));
|
|
1157
1636
|
} catch {}
|
|
1158
1637
|
for (const file of files) {
|
|
1159
|
-
if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME)
|
|
1638
|
+
if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME || file === DEFAULT_SESSION_BINDS_FILENAME || file === LEGACY_AGY_BINDS_FILENAME)
|
|
1160
1639
|
continue;
|
|
1161
1640
|
const name = file.replace(/\.json$/, "");
|
|
1162
1641
|
if (seen.has(name))
|
|
1163
1642
|
continue;
|
|
1164
1643
|
seen.add(name);
|
|
1165
|
-
profiles.push({ name, path:
|
|
1644
|
+
profiles.push({ name, path: join4(dir, file) });
|
|
1166
1645
|
}
|
|
1167
1646
|
}
|
|
1168
1647
|
return profiles;
|
|
@@ -1187,9 +1666,9 @@ function resolveProfile() {
|
|
|
1187
1666
|
let binds = {};
|
|
1188
1667
|
if (!grokToken && conversationId) {
|
|
1189
1668
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
1190
|
-
if (
|
|
1669
|
+
if (existsSync5(bindPath)) {
|
|
1191
1670
|
try {
|
|
1192
|
-
const parsed = parseGrokBindsText(
|
|
1671
|
+
const parsed = parseGrokBindsText(readFileSync5(bindPath, "utf-8"));
|
|
1193
1672
|
binds = parsed.binds;
|
|
1194
1673
|
if (parsed.malformed) {
|
|
1195
1674
|
process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
|
|
@@ -1219,6 +1698,18 @@ function resolveProfile() {
|
|
|
1219
1698
|
return { path: nameToPath(process.env.AGENTSCHAT_PROFILE), source: "env", declaredName: process.env.AGENTSCHAT_PROFILE };
|
|
1220
1699
|
if (process.env.AGENTCHAT_PROFILE)
|
|
1221
1700
|
return { path: nameToPath(process.env.AGENTCHAT_PROFILE), source: "legacy-env", declaredName: process.env.AGENTCHAT_PROFILE };
|
|
1701
|
+
if (!grokToken && runtimeSession?.sessionId) {
|
|
1702
|
+
const sessionBinds = loadSessionBinds(configDir);
|
|
1703
|
+
const boundProfile = sessionBinds[runtimeSession.sessionId];
|
|
1704
|
+
if (boundProfile) {
|
|
1705
|
+
const boundPath = nameToPath(boundProfile);
|
|
1706
|
+
if (existsSync5(boundPath)) {
|
|
1707
|
+
process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} \u2192 profile "${boundProfile}"
|
|
1708
|
+
`);
|
|
1709
|
+
return { path: boundPath, source: "session-bind", declaredName: boundProfile };
|
|
1710
|
+
}
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1222
1713
|
return { path: nameToPath("profile"), source: "default" };
|
|
1223
1714
|
}
|
|
1224
1715
|
var { path: profileFile, source: profileSource, declaredName, agentId: projectAgentId, apiUrl: projectApiUrl, wsUrl: projectWsUrl } = resolveProfile();
|
|
@@ -1257,7 +1748,7 @@ if (hasToken && !explicitAgentId && profileSource === "default") {
|
|
|
1257
1748
|
process.exit(1);
|
|
1258
1749
|
}
|
|
1259
1750
|
var identity = decideIdentity({
|
|
1260
|
-
profileExists:
|
|
1751
|
+
profileExists: existsSync5(profileFile),
|
|
1261
1752
|
source: profileSource,
|
|
1262
1753
|
profileFile,
|
|
1263
1754
|
cliName: cliArgs.name,
|
|
@@ -1268,7 +1759,7 @@ var identity = decideIdentity({
|
|
|
1268
1759
|
});
|
|
1269
1760
|
function readIdentityProfile(file) {
|
|
1270
1761
|
try {
|
|
1271
|
-
return JSON.parse(
|
|
1762
|
+
return JSON.parse(readFileSync5(file, "utf-8"));
|
|
1272
1763
|
} catch {
|
|
1273
1764
|
throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
|
|
1274
1765
|
}
|
|
@@ -1290,8 +1781,25 @@ if (identity.mode === "profile") {
|
|
|
1290
1781
|
`);
|
|
1291
1782
|
process.exit(1);
|
|
1292
1783
|
}
|
|
1293
|
-
process.
|
|
1784
|
+
const candidateAgentId = cliArgs.id ?? process.env.AGENTCHAT_AGENT_ID ?? profile?.agent_id ?? "";
|
|
1785
|
+
const lockCheck = !cliArgs.registerOnly && !toolOnlyMode && !hasToken && candidateAgentId && profile.token !== "dev-token" ? checkAgentLock({
|
|
1786
|
+
lockDir,
|
|
1787
|
+
agentId: candidateAgentId,
|
|
1788
|
+
currentSessionId: runtimeSession?.sessionId ?? null,
|
|
1789
|
+
lockOwnerPid
|
|
1790
|
+
}) : { locked: false };
|
|
1791
|
+
if (lockCheck.locked) {
|
|
1792
|
+
anonymousMode = true;
|
|
1793
|
+
activeProfileFile = null;
|
|
1794
|
+
profile = {};
|
|
1795
|
+
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}` : ""}.
|
|
1796
|
+
` + ` Starting in ANONYMOUS (disconnected) mode so this window does not collide with the active session.
|
|
1797
|
+
` + ` Use connect_profile or switch_profile to connect an idle profile or register a new agent for this window.
|
|
1294
1798
|
`);
|
|
1799
|
+
} else {
|
|
1800
|
+
process.stderr.write(`[agentchat] Profile loaded: ${profileFile}
|
|
1801
|
+
`);
|
|
1802
|
+
}
|
|
1295
1803
|
} else if (identity.mode === "env-creds") {
|
|
1296
1804
|
activeProfileFile = null;
|
|
1297
1805
|
process.stderr.write(`[agentchat] Using credentials from environment \u2014 not registering.
|
|
@@ -1308,15 +1816,8 @@ if (identity.mode === "profile") {
|
|
|
1308
1816
|
} else {
|
|
1309
1817
|
const displayName = identity.displayName;
|
|
1310
1818
|
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}
|
|
1819
|
+
process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}
|
|
1317
1820
|
`);
|
|
1318
|
-
process.exit(1);
|
|
1319
|
-
}
|
|
1320
1821
|
process.stderr.write(`[agentchat] Registering "${displayName}" with server...
|
|
1321
1822
|
`);
|
|
1322
1823
|
try {
|
|
@@ -1328,8 +1829,7 @@ if (identity.mode === "profile") {
|
|
|
1328
1829
|
type: "agent",
|
|
1329
1830
|
capabilities: caps,
|
|
1330
1831
|
source: "mcp",
|
|
1331
|
-
|
|
1332
|
-
terms_version: consent.version
|
|
1832
|
+
terms_notice_version: TERMS_VERSION
|
|
1333
1833
|
})
|
|
1334
1834
|
});
|
|
1335
1835
|
if (regRes.ok) {
|
|
@@ -1340,28 +1840,29 @@ if (identity.mode === "profile") {
|
|
|
1340
1840
|
token: data.key,
|
|
1341
1841
|
capabilities: caps
|
|
1342
1842
|
};
|
|
1843
|
+
validateIdentityProfile(profile, profileFile);
|
|
1343
1844
|
process.stderr.write(`[agentchat] Registered! ID: ${data.id}
|
|
1344
1845
|
`);
|
|
1345
1846
|
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
1847
|
`);
|
|
1347
|
-
process.stderr.write(`[agentchat] Next steps:
|
|
1848
|
+
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
1849
|
`);
|
|
1349
1850
|
} else {
|
|
1350
1851
|
const body = await regRes.text().catch(() => "");
|
|
1351
1852
|
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
|
|
1853
|
+
` + ` No profile was written. Check the service response before retrying registration. Nothing is running.
|
|
1854
|
+
` + ` If the service requires accepted_terms, its agent onboarding must be updated; this client does not fabricate acceptance.
|
|
1354
1855
|
`);
|
|
1355
1856
|
process.exit(1);
|
|
1356
1857
|
}
|
|
1357
1858
|
} catch (e) {
|
|
1358
1859
|
process.stderr.write(`[agentchat] ERROR: Registration failed: ${e}
|
|
1359
|
-
` + ` No profile was written
|
|
1860
|
+
` + ` No profile was written. Registration may have completed on the service; check the result before retrying. Nothing is running.
|
|
1360
1861
|
`);
|
|
1361
1862
|
process.exit(1);
|
|
1362
1863
|
}
|
|
1363
|
-
|
|
1364
|
-
|
|
1864
|
+
mkdirSync2(dirname(profileFile), { recursive: true });
|
|
1865
|
+
safeWriteProfile2(profileFile, profile);
|
|
1365
1866
|
process.stderr.write(`[agentchat] Profile saved: ${profileFile}
|
|
1366
1867
|
`);
|
|
1367
1868
|
}
|
|
@@ -1369,61 +1870,59 @@ if (!hasToken && profile.token === "dev-token" && !shouldMigrateDevToken({ sourc
|
|
|
1369
1870
|
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
1871
|
`);
|
|
1371
1872
|
} 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}
|
|
1873
|
+
process.stderr.write(`[agentchat] ${TERMS_NOTICE_TEXT}
|
|
1379
1874
|
`);
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
process.stderr.write(`[agentchat] Migrating dev-token profile \u2014 registering with server...
|
|
1875
|
+
const terms = { terms_notice_version: TERMS_VERSION };
|
|
1876
|
+
process.stderr.write(`[agentchat] Migrating dev-token profile \u2014 registering with server...
|
|
1383
1877
|
`);
|
|
1384
|
-
|
|
1385
|
-
|
|
1878
|
+
try {
|
|
1879
|
+
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
1880
|
+
method: "POST",
|
|
1881
|
+
headers: { "Content-Type": "application/json" },
|
|
1882
|
+
body: JSON.stringify({ id: profile.agent_id, name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
|
|
1883
|
+
});
|
|
1884
|
+
if (regRes.ok) {
|
|
1885
|
+
const data = await regRes.json();
|
|
1886
|
+
const repaired = { ...profile, agent_id: data.id, token: data.key };
|
|
1887
|
+
validateIdentityProfile(repaired, profileFile);
|
|
1888
|
+
safeWriteProfile2(profileFile, repaired);
|
|
1889
|
+
profile = repaired;
|
|
1890
|
+
process.stderr.write(`[agentchat] Migrated! New key saved. ID: ${data.id}
|
|
1891
|
+
`);
|
|
1892
|
+
} else if (regRes.status === 409) {
|
|
1893
|
+
const regRes2 = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
1386
1894
|
method: "POST",
|
|
1387
1895
|
headers: { "Content-Type": "application/json" },
|
|
1388
|
-
body: JSON.stringify({
|
|
1896
|
+
body: JSON.stringify({ name: profile.display_name, type: "agent", capabilities: profile.capabilities || [], ...terms })
|
|
1389
1897
|
});
|
|
1390
|
-
if (
|
|
1391
|
-
const data = await
|
|
1392
|
-
profile
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1898
|
+
if (regRes2.ok) {
|
|
1899
|
+
const data = await regRes2.json();
|
|
1900
|
+
const repaired = { ...profile, agent_id: data.id, token: data.key };
|
|
1901
|
+
validateIdentityProfile(repaired, profileFile);
|
|
1902
|
+
safeWriteProfile2(profileFile, repaired);
|
|
1903
|
+
profile = repaired;
|
|
1904
|
+
process.stderr.write(`[agentchat] Migrated with new ID: ${data.id}
|
|
1396
1905
|
`);
|
|
1397
1906
|
} 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)}
|
|
1907
|
+
const body = await regRes2.text().catch(() => "");
|
|
1908
|
+
process.stderr.write(`[agentchat] WARNING: dev-token migration refused \u2014 HTTP ${regRes2.status} ${body.slice(0, 200)}
|
|
1413
1909
|
` + ` This profile still holds a placeholder token; authenticated calls will fail.
|
|
1414
1910
|
`);
|
|
1415
|
-
}
|
|
1416
1911
|
}
|
|
1417
|
-
}
|
|
1418
|
-
|
|
1912
|
+
} else {
|
|
1913
|
+
const body = await regRes.text().catch(() => "");
|
|
1914
|
+
process.stderr.write(`[agentchat] WARNING: dev-token migration refused \u2014 HTTP ${regRes.status} ${body.slice(0, 200)}; no alternate identity was registered.
|
|
1419
1915
|
`);
|
|
1420
1916
|
}
|
|
1917
|
+
} catch (e) {
|
|
1918
|
+
process.stderr.write(`[agentchat] dev-token migration failed: ${e}. Check the registration result before retrying; the saved placeholder profile is unchanged.
|
|
1919
|
+
`);
|
|
1421
1920
|
}
|
|
1422
1921
|
}
|
|
1423
1922
|
if (!hasToken && profile.token === "dev-token") {
|
|
1424
1923
|
process.stderr.write(`[agentchat] ERROR: profile ${profileFile} holds a placeholder dev-token, which cannot authenticate.
|
|
1425
1924
|
` + ` Not starting \u2014 a server that lists tools it cannot use is worse than one that fails.
|
|
1426
|
-
` + `
|
|
1925
|
+
` + ` Repair it: --profile <name> (registers a real account for this declared placeholder)
|
|
1427
1926
|
` + ` Or replace: register at https://agents-chat.com/join, then use --profile <name>
|
|
1428
1927
|
` + ` or AGENTCHAT_TOKEN=<token>
|
|
1429
1928
|
`);
|
|
@@ -1441,12 +1940,26 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
|
|
|
1441
1940
|
process.exit(1);
|
|
1442
1941
|
}
|
|
1443
1942
|
}
|
|
1943
|
+
if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
|
|
1944
|
+
acquireAgentLock({
|
|
1945
|
+
lockDir,
|
|
1946
|
+
agentId: AGENT_ID,
|
|
1947
|
+
profileName: profileNameFromPath(activeProfileFile) ?? declaredName ?? null,
|
|
1948
|
+
sessionId: runtimeSession?.sessionId ?? null,
|
|
1949
|
+
runtime: runtimeSession?.runtime ?? "mcp"
|
|
1950
|
+
});
|
|
1951
|
+
if (runtimeSession?.sessionId && activeProfileFile) {
|
|
1952
|
+
const activeName = profileNameFromPath(activeProfileFile);
|
|
1953
|
+
if (activeName)
|
|
1954
|
+
saveSessionBind(configDir, runtimeSession.sessionId, activeName);
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
1444
1957
|
var identityGateMessage = "";
|
|
1445
|
-
var identityGuardFile =
|
|
1958
|
+
var identityGuardFile = join4(configDir, IDENTITY_GUARD_FILENAME);
|
|
1446
1959
|
function persistGuardRecord(rec) {
|
|
1447
1960
|
try {
|
|
1448
|
-
|
|
1449
|
-
|
|
1961
|
+
mkdirSync2(configDir, { recursive: true });
|
|
1962
|
+
safeWriteProfile2(identityGuardFile, rec);
|
|
1450
1963
|
} catch {}
|
|
1451
1964
|
}
|
|
1452
1965
|
function confirmLiveIdentityTrusted() {
|
|
@@ -1461,7 +1974,7 @@ function confirmLiveIdentityTrusted() {
|
|
|
1461
1974
|
}
|
|
1462
1975
|
var guardRecord = (() => {
|
|
1463
1976
|
try {
|
|
1464
|
-
return parseGuardRecord(
|
|
1977
|
+
return parseGuardRecord(readFileSync5(identityGuardFile, "utf-8"));
|
|
1465
1978
|
} catch {
|
|
1466
1979
|
return emptyGuardRecord();
|
|
1467
1980
|
}
|
|
@@ -1502,7 +2015,7 @@ if (cliArgs.name && profile.display_name !== cliArgs.name) {
|
|
|
1502
2015
|
profile.display_name = cliArgs.name;
|
|
1503
2016
|
}
|
|
1504
2017
|
if (cliArgs.registerOnly && !TOKEN) {
|
|
1505
|
-
process.stderr.write(`[agentchat] Select an existing profile or use --name
|
|
2018
|
+
process.stderr.write(`[agentchat] Select an existing profile or use --name <name> / --register to self-register.
|
|
1506
2019
|
`);
|
|
1507
2020
|
process.exit(1);
|
|
1508
2021
|
}
|
|
@@ -1511,7 +2024,7 @@ if (TOKEN && TOKEN !== "dev-token") {
|
|
|
1511
2024
|
process.stderr.write(`[agentchat] ${claimSummary(status)}
|
|
1512
2025
|
`);
|
|
1513
2026
|
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 }));
|
|
2027
|
+
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
2028
|
process.exit(0);
|
|
1516
2029
|
}
|
|
1517
2030
|
}
|
|
@@ -1660,6 +2173,8 @@ var CORE_TOOL_NAMES = new Set([
|
|
|
1660
2173
|
"leave_channel",
|
|
1661
2174
|
"mark_read",
|
|
1662
2175
|
"switch_profile",
|
|
2176
|
+
"connect_profile",
|
|
2177
|
+
"disconnect_profile",
|
|
1663
2178
|
"list_skills",
|
|
1664
2179
|
"load_skill",
|
|
1665
2180
|
"save_skill",
|
|
@@ -2348,12 +2863,13 @@ var ALL_TOOL_DEFS = [
|
|
|
2348
2863
|
},
|
|
2349
2864
|
{
|
|
2350
2865
|
name: "get_history",
|
|
2351
|
-
description: "Get recent message history from a channel.",
|
|
2866
|
+
description: "Get recent message history from a channel, or pass message_id to fetch a single message in full.",
|
|
2352
2867
|
inputSchema: {
|
|
2353
2868
|
type: "object",
|
|
2354
2869
|
properties: {
|
|
2355
2870
|
chat_id: { type: "string", description: "The channel_id" },
|
|
2356
|
-
limit: { type: "number", description: "Max messages (default 20, max 100)" }
|
|
2871
|
+
limit: { type: "number", description: "Max messages (default 20, max 100)" },
|
|
2872
|
+
message_id: { type: "string", description: "Optional exact message_id to read a single message in full without truncation" }
|
|
2357
2873
|
},
|
|
2358
2874
|
required: ["chat_id"]
|
|
2359
2875
|
}
|
|
@@ -2572,11 +3088,38 @@ var ALL_TOOL_DEFS = [
|
|
|
2572
3088
|
},
|
|
2573
3089
|
{
|
|
2574
3090
|
name: "switch_profile",
|
|
2575
|
-
description: "Switch to a different AgentsChat profile at runtime. Lists available profiles if no name given.",
|
|
3091
|
+
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.",
|
|
3092
|
+
inputSchema: {
|
|
3093
|
+
type: "object",
|
|
3094
|
+
properties: {
|
|
3095
|
+
profile_name: { type: "string", description: "Existing profile name to switch to (omit to list available profiles)" },
|
|
3096
|
+
register_name: { type: "string", description: "Display name to register a brand-new AgentsChat agent and connect this window to it" },
|
|
3097
|
+
register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
|
|
3098
|
+
disconnect: { type: "boolean", description: "If true, disconnect this window from its current profile and release its lock" },
|
|
3099
|
+
conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" }
|
|
3100
|
+
}
|
|
3101
|
+
}
|
|
3102
|
+
},
|
|
3103
|
+
{
|
|
3104
|
+
name: "connect_profile",
|
|
3105
|
+
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.",
|
|
3106
|
+
inputSchema: {
|
|
3107
|
+
type: "object",
|
|
3108
|
+
properties: {
|
|
3109
|
+
profile_name: { type: "string", description: "Existing profile name to connect to (omit to list available profiles and lock status)" },
|
|
3110
|
+
register_name: { type: "string", description: "Display name to register a new agent and connect this window to it" },
|
|
3111
|
+
register: { type: "boolean", description: "If true, register profile_name as a new agent when it does not exist" },
|
|
3112
|
+
conversation_id: { type: "string", description: "Optional session/conversation ID to bind to this profile in session-binds.json" }
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
},
|
|
3116
|
+
{
|
|
3117
|
+
name: "disconnect_profile",
|
|
3118
|
+
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.",
|
|
2576
3119
|
inputSchema: {
|
|
2577
3120
|
type: "object",
|
|
2578
3121
|
properties: {
|
|
2579
|
-
|
|
3122
|
+
keep_binding: { type: "boolean", description: "If true, keep the session-binds.json entry while releasing the active process lock" }
|
|
2580
3123
|
}
|
|
2581
3124
|
}
|
|
2582
3125
|
},
|
|
@@ -2756,10 +3299,10 @@ function mimeFromPath(p) {
|
|
|
2756
3299
|
return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
|
|
2757
3300
|
}
|
|
2758
3301
|
async function uploadLocalFile(path) {
|
|
2759
|
-
if (!
|
|
3302
|
+
if (!existsSync5(path))
|
|
2760
3303
|
throw new Error(`file not found: ${path}`);
|
|
2761
3304
|
const mime = mimeFromPath(path);
|
|
2762
|
-
const buf =
|
|
3305
|
+
const buf = readFileSync5(path);
|
|
2763
3306
|
const name = path.split("/").pop() || "upload";
|
|
2764
3307
|
const form = new FormData;
|
|
2765
3308
|
form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
|
|
@@ -2946,10 +3489,10 @@ HANDLERS.set("transcribe", async (args) => {
|
|
|
2946
3489
|
});
|
|
2947
3490
|
function loadGrokBinds() {
|
|
2948
3491
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
2949
|
-
if (!
|
|
3492
|
+
if (!existsSync5(bindPath))
|
|
2950
3493
|
return {};
|
|
2951
3494
|
try {
|
|
2952
|
-
return parseGrokBindsText(
|
|
3495
|
+
return parseGrokBindsText(readFileSync5(bindPath, "utf-8")).binds;
|
|
2953
3496
|
} catch {
|
|
2954
3497
|
return {};
|
|
2955
3498
|
}
|
|
@@ -2963,9 +3506,13 @@ function currentGrokBindApplicability(binds) {
|
|
|
2963
3506
|
binds
|
|
2964
3507
|
});
|
|
2965
3508
|
}
|
|
2966
|
-
function applyIdentityFromProfile(newProfile, targetFile) {
|
|
3509
|
+
function applyIdentityFromProfile(newProfile, targetFile, bindSessionId) {
|
|
2967
3510
|
validateIdentityProfile(newProfile, targetFile);
|
|
3511
|
+
if (AGENT_ID && AGENT_ID !== newProfile.agent_id) {
|
|
3512
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
3513
|
+
}
|
|
2968
3514
|
heartbeat.stop();
|
|
3515
|
+
stopAllTypingHeartbeats();
|
|
2969
3516
|
if (backfillTimer) {
|
|
2970
3517
|
clearTimeout(backfillTimer);
|
|
2971
3518
|
backfillTimer = null;
|
|
@@ -2988,12 +3535,243 @@ function applyIdentityFromProfile(newProfile, targetFile) {
|
|
|
2988
3535
|
profile = newProfile;
|
|
2989
3536
|
activeProfileFile = targetFile;
|
|
2990
3537
|
anonymousMode = false;
|
|
3538
|
+
if (bindSessionId && bindSessionId.trim()) {
|
|
3539
|
+
runtimeSession = {
|
|
3540
|
+
sessionId: bindSessionId.trim(),
|
|
3541
|
+
runtime: runtimeSession?.runtime ?? "custom",
|
|
3542
|
+
...runtimeSession?.workspacePath ? { workspacePath: runtimeSession.workspacePath } : {}
|
|
3543
|
+
};
|
|
3544
|
+
} else if (!runtimeSession?.sessionId) {
|
|
3545
|
+
const agyHost = discoverAntigravityHost();
|
|
3546
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
3547
|
+
runtimeSession = { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
|
|
3548
|
+
}
|
|
3549
|
+
}
|
|
3550
|
+
if (!toolOnlyMode) {
|
|
3551
|
+
acquireAgentLock({
|
|
3552
|
+
lockDir,
|
|
3553
|
+
agentId: AGENT_ID,
|
|
3554
|
+
profileName: profileNameFromPath(targetFile),
|
|
3555
|
+
sessionId: runtimeSession?.sessionId ?? null,
|
|
3556
|
+
runtime: runtimeSession?.runtime ?? "mcp"
|
|
3557
|
+
});
|
|
3558
|
+
if (runtimeSession?.sessionId) {
|
|
3559
|
+
const pName = profileNameFromPath(targetFile);
|
|
3560
|
+
if (pName)
|
|
3561
|
+
saveSessionBind(configDir, runtimeSession.sessionId, pName);
|
|
3562
|
+
}
|
|
3563
|
+
}
|
|
2991
3564
|
guardRecord = advanceGuardRecord(guardRecord, { agentId: AGENT_ID, source: "switch_profile", ...profileNameFromPath(targetFile) ? { declaredName: profileNameFromPath(targetFile) } : {} }, new Date().toISOString(), true);
|
|
2992
3565
|
persistGuardRecord(guardRecord);
|
|
2993
3566
|
wsReconnectAttempt = 0;
|
|
2994
|
-
|
|
2995
|
-
|
|
3567
|
+
if (!toolOnlyMode) {
|
|
3568
|
+
heartbeat.start();
|
|
3569
|
+
connectWS();
|
|
3570
|
+
}
|
|
2996
3571
|
}
|
|
3572
|
+
function disconnectCurrentProfile(opts) {
|
|
3573
|
+
const prevAgentId = AGENT_ID;
|
|
3574
|
+
const prevProfileName = profileNameFromPath(activeProfileFile) || profile?.display_name || AGENT_ID || "(none)";
|
|
3575
|
+
heartbeat.stop();
|
|
3576
|
+
stopAllTypingHeartbeats();
|
|
3577
|
+
if (backfillTimer) {
|
|
3578
|
+
clearTimeout(backfillTimer);
|
|
3579
|
+
backfillTimer = null;
|
|
3580
|
+
}
|
|
3581
|
+
if (reconnectTimer) {
|
|
3582
|
+
clearTimeout(reconnectTimer);
|
|
3583
|
+
reconnectTimer = null;
|
|
3584
|
+
}
|
|
3585
|
+
if (ws) {
|
|
3586
|
+
ws.onclose = null;
|
|
3587
|
+
try {
|
|
3588
|
+
ws.close();
|
|
3589
|
+
} catch {}
|
|
3590
|
+
ws = null;
|
|
3591
|
+
}
|
|
3592
|
+
if (prevAgentId) {
|
|
3593
|
+
releaseAgentLock({ lockDir, agentId: prevAgentId, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
3594
|
+
}
|
|
3595
|
+
if (!opts?.keepBinding && runtimeSession?.sessionId) {
|
|
3596
|
+
removeSessionBind(configDir, runtimeSession.sessionId);
|
|
3597
|
+
}
|
|
3598
|
+
sessionId = null;
|
|
3599
|
+
AGENT_ID = "";
|
|
3600
|
+
TOKEN = "";
|
|
3601
|
+
profile = {};
|
|
3602
|
+
activeProfileFile = null;
|
|
3603
|
+
anonymousMode = true;
|
|
3604
|
+
return { prevAgentId, prevProfileName };
|
|
3605
|
+
}
|
|
3606
|
+
function formatProfileList() {
|
|
3607
|
+
const profileEntries = listProfileFiles();
|
|
3608
|
+
const current = AGENT_ID;
|
|
3609
|
+
const currentProfileName = profileNameFromPath(activeProfileFile);
|
|
3610
|
+
const lines = profileEntries.map((entry) => {
|
|
3611
|
+
let entryAgentId = "";
|
|
3612
|
+
try {
|
|
3613
|
+
const parsed = JSON.parse(readFileSync5(entry.path, "utf-8"));
|
|
3614
|
+
if (typeof parsed?.agent_id === "string")
|
|
3615
|
+
entryAgentId = parsed.agent_id;
|
|
3616
|
+
} catch {}
|
|
3617
|
+
const isCurrent = current && (entry.name === current || entryAgentId === current) || currentProfileName && entry.name === currentProfileName;
|
|
3618
|
+
const lock = entryAgentId ? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid }) : { locked: false };
|
|
3619
|
+
const statusSuffix = lock.locked ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}]` : "";
|
|
3620
|
+
return `${isCurrent ? "\u2192 " : " "}${entry.name}${statusSuffix}`;
|
|
3621
|
+
});
|
|
3622
|
+
return `Current: ${current || "(anonymous / disconnected)"}
|
|
3623
|
+
Available profiles:
|
|
3624
|
+
${lines.join(`
|
|
3625
|
+
`)}`;
|
|
3626
|
+
}
|
|
3627
|
+
async function registerAndConnectProfile(displayName, bindSessionId) {
|
|
3628
|
+
const cleanName = displayName.trim();
|
|
3629
|
+
if (!cleanName) {
|
|
3630
|
+
return { content: [{ type: "text", text: "Error: register_name / profile_name must be a non-empty string." }], isError: true };
|
|
3631
|
+
}
|
|
3632
|
+
const caps = ["claude-code", "coding", "chat"];
|
|
3633
|
+
try {
|
|
3634
|
+
const regRes = await apiFetch(`${REST_URL}/api/account/register`, {
|
|
3635
|
+
method: "POST",
|
|
3636
|
+
headers: { "Content-Type": "application/json" },
|
|
3637
|
+
body: JSON.stringify({
|
|
3638
|
+
name: cleanName,
|
|
3639
|
+
type: "agent",
|
|
3640
|
+
capabilities: caps,
|
|
3641
|
+
source: "mcp",
|
|
3642
|
+
terms_notice_version: TERMS_VERSION
|
|
3643
|
+
})
|
|
3644
|
+
});
|
|
3645
|
+
if (!regRes.ok) {
|
|
3646
|
+
const body = await regRes.text().catch(() => "");
|
|
3647
|
+
return {
|
|
3648
|
+
content: [{ type: "text", text: `Registration refused by ${REST_URL} \u2014 HTTP ${regRes.status} ${body.slice(0, 240)}` }],
|
|
3649
|
+
isError: true
|
|
3650
|
+
};
|
|
3651
|
+
}
|
|
3652
|
+
const data = await regRes.json();
|
|
3653
|
+
const newProfile = {
|
|
3654
|
+
agent_id: data.id,
|
|
3655
|
+
display_name: cleanName,
|
|
3656
|
+
token: data.key,
|
|
3657
|
+
capabilities: caps
|
|
3658
|
+
};
|
|
3659
|
+
const targetFile = nameToPath(cleanName);
|
|
3660
|
+
validateIdentityProfile(newProfile, targetFile);
|
|
3661
|
+
mkdirSync2(dirname(targetFile), { recursive: true });
|
|
3662
|
+
safeWriteProfile2(targetFile, newProfile);
|
|
3663
|
+
const defaultProfileFile = nameToPath("profile");
|
|
3664
|
+
if (!existsSync5(defaultProfileFile)) {
|
|
3665
|
+
safeWriteProfile2(defaultProfileFile, newProfile);
|
|
3666
|
+
}
|
|
3667
|
+
applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
|
|
3668
|
+
const claimEntry = `${REST_URL}/chat/${encodeURIComponent(data.id)}?claim=1`;
|
|
3669
|
+
return {
|
|
3670
|
+
content: [{
|
|
3671
|
+
type: "text",
|
|
3672
|
+
text: `Registered and connected profile "${cleanName}" (${AGENT_ID}).
|
|
3673
|
+
` + `Profile saved: ${targetFile}
|
|
3674
|
+
` + `Claim entry: ${claimEntry} \u2014 enter the key from your private profile in the browser.
|
|
3675
|
+
` + `${TERMS_NOTICE_TEXT}`
|
|
3676
|
+
}]
|
|
3677
|
+
};
|
|
3678
|
+
} catch (e) {
|
|
3679
|
+
return {
|
|
3680
|
+
content: [{ type: "text", text: `Registration failed: ${String(e?.message || e).slice(0, 200)}` }],
|
|
3681
|
+
isError: true
|
|
3682
|
+
};
|
|
3683
|
+
}
|
|
3684
|
+
}
|
|
3685
|
+
async function handleProfileSwitchOrConnect(args) {
|
|
3686
|
+
const {
|
|
3687
|
+
profile_name,
|
|
3688
|
+
register_name,
|
|
3689
|
+
register,
|
|
3690
|
+
disconnect,
|
|
3691
|
+
conversation_id
|
|
3692
|
+
} = args || {};
|
|
3693
|
+
if (disconnect) {
|
|
3694
|
+
const { prevAgentId, prevProfileName } = disconnectCurrentProfile();
|
|
3695
|
+
return {
|
|
3696
|
+
content: [{
|
|
3697
|
+
type: "text",
|
|
3698
|
+
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).`
|
|
3699
|
+
}]
|
|
3700
|
+
};
|
|
3701
|
+
}
|
|
3702
|
+
const explicitSessionId = typeof conversation_id === "string" && conversation_id.trim() ? conversation_id.trim() : null;
|
|
3703
|
+
if (typeof register_name === "string" && register_name.trim()) {
|
|
3704
|
+
return await registerAndConnectProfile(register_name.trim(), explicitSessionId);
|
|
3705
|
+
}
|
|
3706
|
+
if (!profile_name) {
|
|
3707
|
+
return { content: [{ type: "text", text: formatProfileList() }] };
|
|
3708
|
+
}
|
|
3709
|
+
const switchBinds = loadGrokBinds();
|
|
3710
|
+
const bindApplies = currentGrokBindApplicability(switchBinds);
|
|
3711
|
+
const switchGate = !bindApplies.applies ? { kind: "allow" } : gateSwitchProfile({
|
|
3712
|
+
conversationId: process.env.CURSOR_CONVERSATION_ID,
|
|
3713
|
+
binds: switchBinds,
|
|
3714
|
+
requestedProfileName: profile_name,
|
|
3715
|
+
currentProfileName: profileNameFromPath(activeProfileFile)
|
|
3716
|
+
});
|
|
3717
|
+
if (switchGate.kind === "locked") {
|
|
3718
|
+
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
3719
|
+
}
|
|
3720
|
+
const targetFile = nameToPath(profile_name);
|
|
3721
|
+
if (!existsSync5(targetFile)) {
|
|
3722
|
+
if (register) {
|
|
3723
|
+
return await registerAndConnectProfile(profile_name, explicitSessionId);
|
|
3724
|
+
}
|
|
3725
|
+
const available = listProfileFiles().map((entry) => entry.name);
|
|
3726
|
+
return {
|
|
3727
|
+
content: [{
|
|
3728
|
+
type: "text",
|
|
3729
|
+
text: `Profile "${profile_name}" not found. Available: ${available.join(", ")} (or pass register_name="${profile_name}" / register=true to create a new agent)`
|
|
3730
|
+
}],
|
|
3731
|
+
isError: true
|
|
3732
|
+
};
|
|
3733
|
+
}
|
|
3734
|
+
const newProfile = readIdentityProfile(targetFile);
|
|
3735
|
+
validateIdentityProfile(newProfile, targetFile);
|
|
3736
|
+
const effectiveSessionId = explicitSessionId ?? runtimeSession?.sessionId ?? null;
|
|
3737
|
+
const lockCheck = checkAgentLock({
|
|
3738
|
+
lockDir,
|
|
3739
|
+
agentId: newProfile.agent_id,
|
|
3740
|
+
currentSessionId: effectiveSessionId,
|
|
3741
|
+
lockOwnerPid
|
|
3742
|
+
});
|
|
3743
|
+
if (lockCheck.locked) {
|
|
3744
|
+
return {
|
|
3745
|
+
content: [{
|
|
3746
|
+
type: "text",
|
|
3747
|
+
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.`
|
|
3748
|
+
}],
|
|
3749
|
+
isError: true
|
|
3750
|
+
};
|
|
3751
|
+
}
|
|
3752
|
+
applyIdentityFromProfile(newProfile, targetFile, explicitSessionId);
|
|
3753
|
+
const pinNote = EXPECTED_AGENT_ID && AGENT_ID !== EXPECTED_AGENT_ID ? `
|
|
3754
|
+
\uD83D\uDEA8 Still not the expected agent "${EXPECTED_AGENT_ID}" (AGENTCHAT_EXPECT_AGENT_ID) \u2014 write tools stay refused.` : "";
|
|
3755
|
+
const bindNote = runtimeSession?.sessionId ? ` Session "${runtimeSession.sessionId}" is bound to "${profile_name}" in session-binds.json.` : "";
|
|
3756
|
+
return {
|
|
3757
|
+
content: [{
|
|
3758
|
+
type: "text",
|
|
3759
|
+
text: `Switched to profile "${profile_name}" (${AGENT_ID}). Reconnecting...
|
|
3760
|
+
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}`
|
|
3761
|
+
}]
|
|
3762
|
+
};
|
|
3763
|
+
}
|
|
3764
|
+
HANDLERS.set("connect_profile", async (args) => handleProfileSwitchOrConnect(args));
|
|
3765
|
+
HANDLERS.set("disconnect_profile", async (args) => {
|
|
3766
|
+
const { keep_binding } = args || {};
|
|
3767
|
+
const { prevAgentId, prevProfileName } = disconnectCurrentProfile({ keepBinding: keep_binding });
|
|
3768
|
+
return {
|
|
3769
|
+
content: [{
|
|
3770
|
+
type: "text",
|
|
3771
|
+
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).`
|
|
3772
|
+
}]
|
|
3773
|
+
};
|
|
3774
|
+
});
|
|
2997
3775
|
function ensureGrokBoundIdentity() {
|
|
2998
3776
|
if (profileSource !== "grok-bind" || hasToken || cliArgs.id || process.env.AGENTCHAT_AGENT_ID)
|
|
2999
3777
|
return;
|
|
@@ -3004,7 +3782,7 @@ function ensureGrokBoundIdentity() {
|
|
|
3004
3782
|
if (!boundName)
|
|
3005
3783
|
return;
|
|
3006
3784
|
const boundPath = nameToPath(boundName);
|
|
3007
|
-
if (!
|
|
3785
|
+
if (!existsSync5(boundPath))
|
|
3008
3786
|
return;
|
|
3009
3787
|
let boundProfile;
|
|
3010
3788
|
try {
|
|
@@ -3029,6 +3807,41 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3029
3807
|
let { name, arguments: args } = request.params;
|
|
3030
3808
|
let viaExtendedCompat = false;
|
|
3031
3809
|
try {
|
|
3810
|
+
const metaSession = detectRuntimeSession(process.env, request.params?._meta);
|
|
3811
|
+
if (metaSession && (!runtimeSession || runtimeSession.sessionId !== metaSession.sessionId || !runtimeSession.workspacePath && metaSession.workspacePath)) {
|
|
3812
|
+
runtimeSession = metaSession;
|
|
3813
|
+
if (anonymousMode && name !== "connect_profile" && name !== "switch_profile" && name !== "disconnect_profile") {
|
|
3814
|
+
const boundProfile = loadSessionBinds(configDir)[metaSession.sessionId];
|
|
3815
|
+
if (boundProfile) {
|
|
3816
|
+
const boundPath = nameToPath(boundProfile);
|
|
3817
|
+
if (existsSync5(boundPath)) {
|
|
3818
|
+
try {
|
|
3819
|
+
const candidate = readIdentityProfile(boundPath);
|
|
3820
|
+
const lock = checkAgentLock({
|
|
3821
|
+
lockDir,
|
|
3822
|
+
agentId: candidate?.agent_id,
|
|
3823
|
+
currentSessionId: metaSession.sessionId,
|
|
3824
|
+
lockOwnerPid
|
|
3825
|
+
});
|
|
3826
|
+
if (!lock.locked) {
|
|
3827
|
+
applyIdentityFromProfile(candidate, boundPath, metaSession.sessionId);
|
|
3828
|
+
}
|
|
3829
|
+
} catch {}
|
|
3830
|
+
}
|
|
3831
|
+
}
|
|
3832
|
+
} else if (!anonymousMode && AGENT_ID && activeProfileFile && !toolOnlyMode) {
|
|
3833
|
+
acquireAgentLock({
|
|
3834
|
+
lockDir,
|
|
3835
|
+
agentId: AGENT_ID,
|
|
3836
|
+
profileName: profileNameFromPath(activeProfileFile),
|
|
3837
|
+
sessionId: metaSession.sessionId,
|
|
3838
|
+
runtime: metaSession.runtime
|
|
3839
|
+
});
|
|
3840
|
+
const pName = profileNameFromPath(activeProfileFile);
|
|
3841
|
+
if (pName)
|
|
3842
|
+
saveSessionBind(configDir, metaSession.sessionId, pName);
|
|
3843
|
+
}
|
|
3844
|
+
}
|
|
3032
3845
|
if (TOOL_INPUT_SCHEMAS.has(name)) {
|
|
3033
3846
|
const argErr = validateToolArgs(TOOL_INPUT_SCHEMAS.get(name), args);
|
|
3034
3847
|
if (argErr)
|
|
@@ -3255,7 +4068,7 @@ ${a.body || ""}`;
|
|
|
3255
4068
|
const currentVersion = Number(meta.version ?? 0);
|
|
3256
4069
|
let cachedVersion = null;
|
|
3257
4070
|
try {
|
|
3258
|
-
cachedVersion = Number(JSON.parse(
|
|
4071
|
+
cachedVersion = Number(JSON.parse(readFileSync5(pMeta, "utf8")).version);
|
|
3259
4072
|
} catch {}
|
|
3260
4073
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
3261
4074
|
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 +4077,9 @@ ${a.body || ""}`;
|
|
|
3264
4077
|
if (!bodyR.ok)
|
|
3265
4078
|
return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
|
|
3266
4079
|
const doc = JSON.parse(await bodyR.text());
|
|
3267
|
-
|
|
3268
|
-
|
|
3269
|
-
|
|
4080
|
+
mkdirSync2(dirname(pMd), { recursive: true });
|
|
4081
|
+
writeFileSync4(pMd, String(doc?.body_markdown ?? ""));
|
|
4082
|
+
writeFileSync4(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
|
|
3270
4083
|
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
4084
|
} catch (e) {
|
|
3272
4085
|
return { content: [{ type: "text", text: `sync_skill (personal) error: ${String(e?.message || e).slice(0, 140)}` }], isError: true };
|
|
@@ -3289,7 +4102,7 @@ ${a.body || ""}`;
|
|
|
3289
4102
|
const currentVersion = Number(meta.version ?? 0);
|
|
3290
4103
|
let cachedVersion = null;
|
|
3291
4104
|
try {
|
|
3292
|
-
cachedVersion = Number(JSON.parse(
|
|
4105
|
+
cachedVersion = Number(JSON.parse(readFileSync5(metaPath, "utf8")).version);
|
|
3293
4106
|
} catch {}
|
|
3294
4107
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
3295
4108
|
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 +4112,9 @@ ${a.body || ""}`;
|
|
|
3299
4112
|
return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
|
|
3300
4113
|
const doc = JSON.parse(await docR.text());
|
|
3301
4114
|
const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
4115
|
+
mkdirSync2(dirname(mdPath), { recursive: true });
|
|
4116
|
+
writeFileSync4(mdPath, body);
|
|
4117
|
+
writeFileSync4(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
|
|
3305
4118
|
const was = cachedVersion === null ? "missing" : `stale v${cachedVersion}`;
|
|
3306
4119
|
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
4120
|
} catch (e) {
|
|
@@ -3917,6 +4730,9 @@ ${brief}` }] };
|
|
|
3917
4730
|
}));
|
|
3918
4731
|
return { content: [{ type: "text", text: `Read cursor update dispatched (up to ${last_read_id.slice(0, 8)})` }] };
|
|
3919
4732
|
}
|
|
4733
|
+
if (toolOnlyMode) {
|
|
4734
|
+
return { content: [{ type: "text", text: `Read cursor noted (up to ${last_read_id.slice(0, 8)})` }] };
|
|
4735
|
+
}
|
|
3920
4736
|
return { content: [{ type: "text", text: "Not connected" }] };
|
|
3921
4737
|
}
|
|
3922
4738
|
if (name === "whoami") {
|
|
@@ -4090,39 +4906,83 @@ ${list}` }] };
|
|
|
4090
4906
|
}
|
|
4091
4907
|
}
|
|
4092
4908
|
if (name === "get_history") {
|
|
4093
|
-
const { chat_id, limit = 20 } = args;
|
|
4094
|
-
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
|
|
4100
|
-
|
|
4101
|
-
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
if (a.type === "audio") {
|
|
4109
|
-
const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
|
|
4110
|
-
line += `
|
|
4909
|
+
const { chat_id, limit = 20, message_id } = args;
|
|
4910
|
+
const targetMsgId = typeof message_id === "string" && message_id.trim() ? message_id.trim() : null;
|
|
4911
|
+
const MAX_HISTORY_MESSAGE_CHARS = 4000;
|
|
4912
|
+
const formatHistoryMessage = (m, full = false) => {
|
|
4913
|
+
const time = m.timestamp ? new Date(m.timestamp).toLocaleString() : "?";
|
|
4914
|
+
const rawContent = String(m.content ?? "");
|
|
4915
|
+
const body = full || rawContent.length <= MAX_HISTORY_MESSAGE_CHARS ? rawContent : `${rawContent.slice(0, MAX_HISTORY_MESSAGE_CHARS)}\u2026 [truncated ${rawContent.length - MAX_HISTORY_MESSAGE_CHARS} chars; pass message_id="${m.id || ""}" to get_history for full text]`;
|
|
4916
|
+
let line = `[${time}] ${m.sender_id?.slice(0, 12)}: ${body}`;
|
|
4917
|
+
const atts = Array.isArray(m.attachments) ? m.attachments : [];
|
|
4918
|
+
for (const a of atts) {
|
|
4919
|
+
if (!a?.url)
|
|
4920
|
+
continue;
|
|
4921
|
+
if (a.type === "audio") {
|
|
4922
|
+
const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
|
|
4923
|
+
line += `
|
|
4111
4924
|
\uD83D\uDD0A audio${dur}: ${a.url}`;
|
|
4112
|
-
|
|
4925
|
+
line += a.transcript ? `
|
|
4113
4926
|
transcript: "${String(a.transcript).slice(0, 400)}"` : `
|
|
4114
4927
|
(no transcript \u2014 call transcribe(url) to read what was said)`;
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4928
|
+
} else if (a.type === "image") {
|
|
4929
|
+
const dim = a.width && a.height ? ` ${a.width}\xD7${a.height}` : "";
|
|
4930
|
+
line += `
|
|
4118
4931
|
\uD83D\uDDBC image${dim}: ${a.url}`;
|
|
4119
|
-
|
|
4120
|
-
|
|
4932
|
+
} else {
|
|
4933
|
+
line += `
|
|
4121
4934
|
\uD83D\uDCCE ${a.type || "file"}: ${a.url}`;
|
|
4122
|
-
|
|
4935
|
+
}
|
|
4936
|
+
}
|
|
4937
|
+
return line;
|
|
4938
|
+
};
|
|
4939
|
+
try {
|
|
4940
|
+
const fetchLimit = targetMsgId ? 100 : Math.max(1, Math.min(Number(limit) || 20, 100));
|
|
4941
|
+
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages?limit=${fetchLimit}`, { headers: { Authorization: `Bearer ${TOKEN}` } });
|
|
4942
|
+
if (r.ok) {
|
|
4943
|
+
const data = await r.json();
|
|
4944
|
+
const msgs = (data.messages || []).filter((m) => m.content !== "__typing__");
|
|
4945
|
+
if (targetMsgId) {
|
|
4946
|
+
let exact = msgs.find((m) => m.id === targetMsgId);
|
|
4947
|
+
if (!exact) {
|
|
4948
|
+
try {
|
|
4949
|
+
const mcpRes = await apiFetch(`${REST_URL}/mcp`, {
|
|
4950
|
+
method: "POST",
|
|
4951
|
+
headers: {
|
|
4952
|
+
Authorization: `Bearer ${TOKEN}`,
|
|
4953
|
+
"Content-Type": "application/json",
|
|
4954
|
+
...AGENT_ID ? { "X-Agent-Id": AGENT_ID } : {}
|
|
4955
|
+
},
|
|
4956
|
+
body: JSON.stringify({
|
|
4957
|
+
jsonrpc: "2.0",
|
|
4958
|
+
id: 1,
|
|
4959
|
+
method: "tools/call",
|
|
4960
|
+
params: {
|
|
4961
|
+
name: "agentschat_read_messages",
|
|
4962
|
+
arguments: { channel_id: chat_id, message_id: targetMsgId }
|
|
4963
|
+
}
|
|
4964
|
+
})
|
|
4965
|
+
});
|
|
4966
|
+
if (mcpRes.ok) {
|
|
4967
|
+
const rpcData = await mcpRes.json();
|
|
4968
|
+
const structured = rpcData?.result?.structuredContent;
|
|
4969
|
+
const textPayload = rpcData?.result?.content?.[0]?.text;
|
|
4970
|
+
const parsed = structured || (typeof textPayload === "string" ? JSON.parse(textPayload) : null);
|
|
4971
|
+
if (Array.isArray(parsed?.messages) && parsed.messages.length > 0) {
|
|
4972
|
+
exact = parsed.messages[0];
|
|
4973
|
+
}
|
|
4974
|
+
}
|
|
4975
|
+
} catch {}
|
|
4123
4976
|
}
|
|
4124
|
-
|
|
4125
|
-
|
|
4977
|
+
if (!exact) {
|
|
4978
|
+
return { content: [{ type: "text", text: `Message ${targetMsgId} not found in channel ${chat_id}.` }], isError: true };
|
|
4979
|
+
}
|
|
4980
|
+
return { content: [{ type: "text", text: `1 message (id=${exact.id}):
|
|
4981
|
+
${formatHistoryMessage(exact, true)}` }] };
|
|
4982
|
+
}
|
|
4983
|
+
if (msgs.length === 0)
|
|
4984
|
+
return { content: [{ type: "text", text: "No messages in this channel." }] };
|
|
4985
|
+
const list = msgs.map((m) => formatHistoryMessage(m, false)).join(`
|
|
4126
4986
|
`);
|
|
4127
4987
|
return { content: [{ type: "text", text: `${msgs.length} messages:
|
|
4128
4988
|
${list}` }] };
|
|
@@ -4133,38 +4993,7 @@ ${list}` }] };
|
|
|
4133
4993
|
}
|
|
4134
4994
|
}
|
|
4135
4995
|
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}` }] };
|
|
4996
|
+
return await handleProfileSwitchOrConnect(args);
|
|
4168
4997
|
}
|
|
4169
4998
|
if (name === "list_channel_docs") {
|
|
4170
4999
|
const { chat_id, level } = args;
|
|
@@ -4513,7 +5342,7 @@ Scope: this switch applies only to THIS MCP process. It is not saved \u2014 a ne
|
|
|
4513
5342
|
return { content: [{ type: "text", text: `${name} failed: ${String(e?.message || e).slice(0, 300)}` }], isError: true };
|
|
4514
5343
|
}
|
|
4515
5344
|
});
|
|
4516
|
-
var mentionTsFile =
|
|
5345
|
+
var mentionTsFile = join4(configDir, `mention-ts-${AGENT_ID}.json`);
|
|
4517
5346
|
function loadMentionTimestamps() {
|
|
4518
5347
|
return loadCursor(mentionTsFile, safeStderrWrite);
|
|
4519
5348
|
}
|
|
@@ -4521,7 +5350,7 @@ function saveMentionTimestamps(m) {
|
|
|
4521
5350
|
persistCursor(mentionTsFile, m, safeStderrWrite);
|
|
4522
5351
|
}
|
|
4523
5352
|
var lastMentionTimestamp = loadMentionTimestamps();
|
|
4524
|
-
var lastSeenMessageTsFile =
|
|
5353
|
+
var lastSeenMessageTsFile = join4(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
|
|
4525
5354
|
function loadLastSeenMessageTs() {
|
|
4526
5355
|
return loadCursor(lastSeenMessageTsFile, safeStderrWrite);
|
|
4527
5356
|
}
|
|
@@ -4935,15 +5764,15 @@ ${context}
|
|
|
4935
5764
|
if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
|
|
4936
5765
|
(async () => {
|
|
4937
5766
|
try {
|
|
4938
|
-
const { readFileSync:
|
|
4939
|
-
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY,
|
|
5767
|
+
const { readFileSync: readFileSync6, existsSync: existsSync6 } = await import("fs");
|
|
5768
|
+
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync6);
|
|
4940
5769
|
let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
|
|
4941
5770
|
if (!agentId) {
|
|
4942
5771
|
agentId = await resolveGrokAgentId({
|
|
4943
5772
|
explicitId: "",
|
|
4944
5773
|
agentschatName: profile.display_name || AGENT_ID,
|
|
4945
5774
|
listAgents: async () => {
|
|
4946
|
-
const gwcfg = JSON.parse(
|
|
5775
|
+
const gwcfg = JSON.parse(readFileSync6(gwPath, "utf8"));
|
|
4947
5776
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
4948
5777
|
const port = grokPortFromGatewayConfig(gwcfg);
|
|
4949
5778
|
const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
|
|
@@ -4964,11 +5793,58 @@ ${context}
|
|
|
4964
5793
|
`);
|
|
4965
5794
|
}
|
|
4966
5795
|
})();
|
|
4967
|
-
} else {
|
|
5796
|
+
} else if (process.env.AGENTCHAT_WAKE_URL) {
|
|
4968
5797
|
fireWake(data, {
|
|
4969
5798
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
4970
5799
|
secret: process.env.AGENTCHAT_WAKE_SECRET
|
|
4971
5800
|
});
|
|
5801
|
+
} else if (runtimeSession?.runtime === "zcode" || process.env.AGENTCHAT_WAKE_MODE === "zcode") {
|
|
5802
|
+
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
5803
|
+
const zcodeSid = runtimeSession?.sessionId || findBoundSessionForProfile(configDir, activeProfName, (sid) => sid.startsWith("sess_")) || "";
|
|
5804
|
+
if (zcodeSid) {
|
|
5805
|
+
fireZcodeWake(data, {
|
|
5806
|
+
sessionId: zcodeSid,
|
|
5807
|
+
workspacePath: runtimeSession?.workspacePath,
|
|
5808
|
+
profileName: activeProfName ?? undefined,
|
|
5809
|
+
lockOwnerPid: process.pid,
|
|
5810
|
+
logger: (m) => process.stderr.write(`${m}
|
|
5811
|
+
`)
|
|
5812
|
+
});
|
|
5813
|
+
}
|
|
5814
|
+
} else {
|
|
5815
|
+
(async () => {
|
|
5816
|
+
try {
|
|
5817
|
+
const agyHost = discoverAntigravityHost();
|
|
5818
|
+
const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
|
|
5819
|
+
const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
|
|
5820
|
+
if (!agyHost && !lsAddress)
|
|
5821
|
+
return;
|
|
5822
|
+
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
5823
|
+
const allBinds = loadSessionBinds(configDir);
|
|
5824
|
+
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)) || "";
|
|
5825
|
+
if (!targetCid && agyHost) {
|
|
5826
|
+
if (agyHost.openConversations.length === 1) {
|
|
5827
|
+
targetCid = agyHost.openConversations[0];
|
|
5828
|
+
} else if (agyHost.openConversations.length > 1) {
|
|
5829
|
+
const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] === activeProfName);
|
|
5830
|
+
targetCid = unboundOrSame || agyHost.openConversations[0];
|
|
5831
|
+
}
|
|
5832
|
+
}
|
|
5833
|
+
if (targetCid && csrfToken) {
|
|
5834
|
+
await fireAntigravityWake(data, {
|
|
5835
|
+
conversationId: targetCid,
|
|
5836
|
+
csrfToken,
|
|
5837
|
+
lsAddress: lsAddress || undefined,
|
|
5838
|
+
ports: agyHost?.ports,
|
|
5839
|
+
logger: (m) => process.stderr.write(`${m}
|
|
5840
|
+
`)
|
|
5841
|
+
});
|
|
5842
|
+
}
|
|
5843
|
+
} catch (e) {
|
|
5844
|
+
process.stderr.write(`[agentchat] antigravity wake error: ${e}
|
|
5845
|
+
`);
|
|
5846
|
+
}
|
|
5847
|
+
})();
|
|
4972
5848
|
}
|
|
4973
5849
|
if (activeHi)
|
|
4974
5850
|
clearFinishedHiddenIdentityGamesFromMessage(data);
|
|
@@ -5051,7 +5927,16 @@ var heartbeat = new HeartbeatMonitor({
|
|
|
5051
5927
|
},
|
|
5052
5928
|
getReadyState: () => ws?.readyState ?? WS_CLOSED
|
|
5053
5929
|
}, 15000, 45000, 30000);
|
|
5054
|
-
|
|
5930
|
+
if (!anonymousMode && !toolOnlyMode) {
|
|
5931
|
+
heartbeat.start();
|
|
5932
|
+
}
|
|
5933
|
+
function releaseLiveLock() {
|
|
5934
|
+
if (AGENT_ID && !toolOnlyMode) {
|
|
5935
|
+
try {
|
|
5936
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
5937
|
+
} catch {}
|
|
5938
|
+
}
|
|
5939
|
+
}
|
|
5055
5940
|
function shutdownFromStdio(reason) {
|
|
5056
5941
|
if (shuttingDown)
|
|
5057
5942
|
return;
|
|
@@ -5064,6 +5949,7 @@ function shutdownFromStdio(reason) {
|
|
|
5064
5949
|
safeStderrWrite(`[agentchat] WARNING: read-cursor flush failed on shutdown: ${e}
|
|
5065
5950
|
`);
|
|
5066
5951
|
}
|
|
5952
|
+
releaseLiveLock();
|
|
5067
5953
|
try {
|
|
5068
5954
|
heartbeat.stop();
|
|
5069
5955
|
} catch {}
|
|
@@ -5105,6 +5991,7 @@ function installStdioLifecycleGuards() {
|
|
|
5105
5991
|
process.stderr.on("error", handleOutputError);
|
|
5106
5992
|
process.on("SIGPIPE", () => shutdownFromStdio("SIGPIPE"));
|
|
5107
5993
|
process.on("beforeExit", () => {
|
|
5994
|
+
releaseLiveLock();
|
|
5108
5995
|
try {
|
|
5109
5996
|
flushLastSeenMessageTs();
|
|
5110
5997
|
} catch (e) {
|
|
@@ -5112,6 +5999,9 @@ function installStdioLifecycleGuards() {
|
|
|
5112
5999
|
`);
|
|
5113
6000
|
}
|
|
5114
6001
|
});
|
|
6002
|
+
process.on("exit", () => {
|
|
6003
|
+
releaseLiveLock();
|
|
6004
|
+
});
|
|
5115
6005
|
}
|
|
5116
6006
|
async function checkVersionStaleness() {
|
|
5117
6007
|
const controller = new AbortController;
|
|
@@ -5133,6 +6023,9 @@ async function main() {
|
|
|
5133
6023
|
installStdioLifecycleGuards();
|
|
5134
6024
|
if (anonymousMode) {
|
|
5135
6025
|
process.stderr.write(`[agentchat] Anonymous \u2014 not connecting to the hub.
|
|
6026
|
+
`);
|
|
6027
|
+
} else if (toolOnlyMode) {
|
|
6028
|
+
process.stderr.write(`[agentchat] Tool-only mode (AGENTSCHAT_TOOL_ONLY=1) \u2014 skipping duplicate WS connection.
|
|
5136
6029
|
`);
|
|
5137
6030
|
} else {
|
|
5138
6031
|
connectWS();
|