agentschat-mcp 0.36.17 → 0.36.19
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/README.md +25 -14
- package/codex/README.md +2 -2
- package/cordis.patch.yml +23 -0
- package/dist/codex-bridge.js +10 -9
- package/dist/connector.js +3 -2
- package/dist/dsh.js +932 -0
- package/dist/muse.js +612 -0
- package/dist/server.js +1215 -436
- package/dsh/README.md +83 -0
- package/dsh/identity-ui/README.md +76 -0
- package/dsh/identity-ui/client.js +260 -0
- package/dsh/identity-ui/cordis.patch.yml +11 -0
- package/dsh/identity-ui/index.js +21 -0
- package/dsh/identity-ui/package.json +29 -0
- package/dsh/inbound-bridge/README.md +84 -0
- package/dsh/inbound-bridge/index.js +716 -0
- package/dsh/inbound-bridge/package.json +14 -0
- package/dsh/src/cli.ts +374 -0
- package/dsh/src/patch.ts +117 -0
- package/dsh/tests/dsh.test.ts +113 -0
- package/muse/README.md +179 -0
- package/muse/scripts/ensure-muse-wakes.mjs +108 -0
- package/muse/scripts/keepalive-hook.sh +45 -0
- package/muse/scripts/muse-wake-receiver.mjs +51 -0
- package/muse/scripts/setup-muse-keepalive.sh +68 -0
- package/muse/scripts/smoke.mjs +17 -0
- package/muse/skills/muse-keepalive.md +95 -0
- package/muse/skills/onboarding.md +137 -0
- package/muse/src/bridge.ts +83 -0
- package/muse/src/cli.ts +155 -0
- package/muse/src/client.ts +241 -0
- package/muse/src/config.ts +79 -0
- package/muse/src/index.ts +10 -0
- package/muse/src/policy.ts +68 -0
- package/muse/src/types.ts +38 -0
- package/muse/src/typing.ts +51 -0
- package/muse/src/wake.ts +176 -0
- package/muse/tests/bridge.test.mjs +51 -0
- package/muse/tests/client.test.mjs +178 -0
- package/muse/tests/config.test.mjs +24 -0
- package/muse/tests/policy.test.mjs +47 -0
- package/muse/tests/typing.test.mjs +26 -0
- package/muse/tests/wake.test.mjs +81 -0
- package/package.json +17 -3
- package/skills/grok-wake-keepalive.md +1 -1
- package/skills/onboarding.md +40 -34
- package/src/cli.mjs +17 -7
- package/src/redact.ts +10 -4
- package/src/server.ts +852 -430
- package/src/session-bind.ts +348 -12
- package/src/session-route.ts +87 -0
- package/src/tool-annotations.ts +1 -0
- package/src/wake.ts +75 -8
package/dist/server.js
CHANGED
|
@@ -56,8 +56,9 @@ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
|
56
56
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
57
57
|
|
|
58
58
|
// src/redact.ts
|
|
59
|
-
function redactSecrets(text) {
|
|
60
|
-
|
|
59
|
+
function redactSecrets(text, opts) {
|
|
60
|
+
const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
|
|
61
|
+
return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
// src/mentions.ts
|
|
@@ -430,6 +431,7 @@ var D = { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
|
|
|
430
431
|
var TOOL_ANNOTATIONS = {
|
|
431
432
|
reply: W,
|
|
432
433
|
send_image: W,
|
|
434
|
+
send_video: W,
|
|
433
435
|
send_voice: W,
|
|
434
436
|
transcribe: R,
|
|
435
437
|
list_voices: R,
|
|
@@ -506,24 +508,61 @@ function annotateTools(tools) {
|
|
|
506
508
|
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
507
509
|
|
|
508
510
|
// src/redact.ts
|
|
509
|
-
function redactSecrets2(text) {
|
|
510
|
-
|
|
511
|
+
function redactSecrets2(text, opts) {
|
|
512
|
+
const step = opts?.preserveAcKeys ? text : text.replace(/ac_[A-Za-z0-9_-]{16,}/g, "ac_***REDACTED***");
|
|
513
|
+
return step.replace(/eyJ[A-Za-z0-9_-]{20,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "***JWT_REDACTED***");
|
|
511
514
|
}
|
|
512
515
|
|
|
513
516
|
// src/wake.ts
|
|
514
517
|
var WAKE_SIG_HEADER = "x-agentschat-signature";
|
|
515
518
|
var WAKE_CONTENT_MAX = 500;
|
|
516
519
|
var NATIVE_WAKE_CONTENT_MAX = 4000;
|
|
517
|
-
function
|
|
518
|
-
|
|
520
|
+
function formatWakeAttachments(attachments) {
|
|
521
|
+
if (!Array.isArray(attachments) || attachments.length === 0)
|
|
522
|
+
return "";
|
|
523
|
+
const lines = [];
|
|
524
|
+
for (const raw of attachments) {
|
|
525
|
+
if (!raw || typeof raw !== "object")
|
|
526
|
+
continue;
|
|
527
|
+
const a = raw;
|
|
528
|
+
if (typeof a.url !== "string" || !a.url)
|
|
529
|
+
continue;
|
|
530
|
+
const t = typeof a.type === "string" ? a.type : "file";
|
|
531
|
+
const dim = typeof a.width === "number" && typeof a.height === "number" ? ` ${a.width}×${a.height}` : "";
|
|
532
|
+
const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
|
|
533
|
+
const icon = t === "image" ? "\uD83D\uDDBC" : t === "video" ? "\uD83C\uDFAC" : t === "audio" ? "\uD83D\uDD0A" : "\uD83D\uDCCE";
|
|
534
|
+
let desc = `${icon} ${t}${dim}${dur}: ${a.url}`;
|
|
535
|
+
if (typeof a.transcript === "string" && a.transcript.trim()) {
|
|
536
|
+
desc += ` (transcript: "${redactSecrets2(a.transcript.trim().slice(0, 300))}")`;
|
|
537
|
+
}
|
|
538
|
+
lines.push(desc);
|
|
539
|
+
}
|
|
540
|
+
return lines.length > 0 ? ` [附件: ${lines.join("; ")}]` : "";
|
|
541
|
+
}
|
|
542
|
+
function buildWakePayload(msg, opts = {}) {
|
|
543
|
+
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
544
|
+
const content = typeof msg.content === "string" ? redactSecrets2(msg.content.slice(0, WAKE_CONTENT_MAX), redactOpts) : undefined;
|
|
545
|
+
const attachments = Array.isArray(msg.attachments) && msg.attachments.length > 0 ? msg.attachments.filter((a) => a && typeof a === "object" && typeof a.url === "string").map((a) => ({
|
|
546
|
+
type: typeof a.type === "string" ? a.type : undefined,
|
|
547
|
+
url: a.url,
|
|
548
|
+
mime: typeof a.mime === "string" ? a.mime : undefined,
|
|
549
|
+
size: typeof a.size === "number" ? a.size : undefined,
|
|
550
|
+
width: typeof a.width === "number" ? a.width : undefined,
|
|
551
|
+
height: typeof a.height === "number" ? a.height : undefined,
|
|
552
|
+
duration_ms: typeof a.duration_ms === "number" ? a.duration_ms : undefined,
|
|
553
|
+
transcript: typeof a.transcript === "string" ? redactSecrets2(a.transcript.slice(0, 300), redactOpts) : undefined
|
|
554
|
+
})) : undefined;
|
|
555
|
+
const targetSessionId = typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
|
|
519
556
|
return {
|
|
520
557
|
type: typeof msg.type === "string" ? msg.type : "message",
|
|
521
558
|
channel_id: msg.channel_id,
|
|
522
559
|
message_id: msg.id,
|
|
523
560
|
sender_id: msg.sender_id,
|
|
524
561
|
content,
|
|
562
|
+
...attachments && attachments.length > 0 ? { attachments } : {},
|
|
525
563
|
mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string") : undefined,
|
|
526
|
-
timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined
|
|
564
|
+
timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined,
|
|
565
|
+
...targetSessionId ? { target_session_id: targetSessionId } : {}
|
|
527
566
|
};
|
|
528
567
|
}
|
|
529
568
|
function signWakeBody(body, secret) {
|
|
@@ -534,7 +573,7 @@ async function fireWake(msg, cfg) {
|
|
|
534
573
|
const url = (cfg.url ?? "").trim();
|
|
535
574
|
if (!url)
|
|
536
575
|
return;
|
|
537
|
-
const payload = buildWakePayload(msg);
|
|
576
|
+
const payload = buildWakePayload(msg, { targetSessionId: cfg.targetSessionId });
|
|
538
577
|
const body = JSON.stringify(payload);
|
|
539
578
|
const headers = { "Content-Type": "application/json" };
|
|
540
579
|
if (cfg.secret)
|
|
@@ -564,17 +603,19 @@ async function fireWake(msg, cfg) {
|
|
|
564
603
|
function buildGrokPrompt(msg, agentId, contextPrefix = "") {
|
|
565
604
|
const rawContent = typeof msg.content === "string" ? msg.content : "";
|
|
566
605
|
const isTruncated = rawContent.length > NATIVE_WAKE_CONTENT_MAX;
|
|
567
|
-
const
|
|
568
|
-
const
|
|
606
|
+
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
607
|
+
const content = rawContent ? redactSecrets2(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
|
|
608
|
+
const cleanPrefix = contextPrefix ? redactSecrets2(contextPrefix.trim(), redactOpts) : "";
|
|
569
609
|
const channel = msg.channel_id ?? "?";
|
|
570
610
|
const sender = msg.sender_id ?? "someone";
|
|
571
611
|
const msgId = msg.id ?? msg.message_id ?? "";
|
|
572
612
|
const isDm = channel.startsWith("dm-");
|
|
573
613
|
const where = isDm ? "私聊 (DM)" : `频道 ${channel}`;
|
|
574
614
|
const actionHint = isTruncated ? `——消息已截断,可调 get_history 查看全文,再用 reply 回复` : `——请直接用 reply 回复;仅需更早历史时调 get_history`;
|
|
615
|
+
const attSummary = formatWakeAttachments(msg.attachments);
|
|
575
616
|
const prompt = (cleanPrefix ? `${cleanPrefix}
|
|
576
617
|
|
|
577
|
-
` : "") + `[AgentsChat] ${sender} 在${where}提到了你` + (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") + (msgId ? ` (channel_id=${channel}, message_id=${msgId}${actionHint})` : "");
|
|
618
|
+
` : "") + `[AgentsChat] ${sender} 在${where}提到了你` + (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") + attSummary + (msgId ? ` (channel_id=${channel}, message_id=${msgId}${actionHint})` : "");
|
|
578
619
|
return { agentId, prompt };
|
|
579
620
|
}
|
|
580
621
|
function grokBearerFromGatewayConfig(cfg) {
|
|
@@ -674,17 +715,19 @@ async function fireGrokWake(msg, cfg) {
|
|
|
674
715
|
function buildWakePrompt(msg, contextPrefix = "") {
|
|
675
716
|
const rawContent = typeof msg.content === "string" ? msg.content : "";
|
|
676
717
|
const isTruncated = rawContent.length > NATIVE_WAKE_CONTENT_MAX;
|
|
677
|
-
const
|
|
678
|
-
const
|
|
718
|
+
const redactOpts = msg.same_owner_direct === true ? { preserveAcKeys: true } : undefined;
|
|
719
|
+
const content = rawContent ? redactSecrets2(rawContent.slice(0, NATIVE_WAKE_CONTENT_MAX), redactOpts) : "";
|
|
720
|
+
const cleanPrefix = contextPrefix ? redactSecrets2(contextPrefix.trim(), redactOpts) : "";
|
|
679
721
|
const channel = msg.channel_id ?? "?";
|
|
680
722
|
const sender = msg.sender_id ?? "someone";
|
|
681
723
|
const msgId = msg.id ?? msg.message_id ?? "";
|
|
682
724
|
const isDm = channel.startsWith("dm-");
|
|
683
725
|
const where = isDm ? `私聊 (${channel})` : `频道 ${channel}`;
|
|
684
726
|
const actionHint = isTruncated ? ` —— 消息过长已截断,可调用 get_history(chat_id, message_id) 查看全文,再用 reply 回复并 mark_read 标记已读` : ` —— 请直接用 reply 回复并用 mark_read 标记已读;仅在需要更早上下文时调用 get_history`;
|
|
727
|
+
const attSummary = formatWakeAttachments(msg.attachments);
|
|
685
728
|
return (cleanPrefix ? `${cleanPrefix}
|
|
686
729
|
|
|
687
|
-
` : "") + `[AgentsChat] ${sender} 在${where}给你发了消息` + (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") + ` (channel_id=${channel}` + (msgId ? `, message_id=${msgId}` : "") + `${actionHint})`;
|
|
730
|
+
` : "") + `[AgentsChat] ${sender} 在${where}给你发了消息` + (content ? `:"${content}${isTruncated ? " …[truncated]" : ""}"` : "。") + attSummary + ` (channel_id=${channel}` + (msgId ? `, message_id=${msgId}` : "") + `${actionHint})`;
|
|
688
731
|
}
|
|
689
732
|
async function fireAntigravityWake(msg, cfg) {
|
|
690
733
|
const log = cfg.logger ?? (() => {});
|
|
@@ -843,8 +886,8 @@ function fireZcodeWake(msg, cfg) {
|
|
|
843
886
|
|
|
844
887
|
// src/session-bind.ts
|
|
845
888
|
import { createHash } from "node:crypto";
|
|
846
|
-
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync3, unlinkSync as unlinkSync2 } from "node:fs";
|
|
847
|
-
import { tmpdir } from "node:os";
|
|
889
|
+
import { closeSync, existsSync as existsSync3, mkdirSync, openSync, readFileSync as readFileSync3, readSync, readdirSync, statSync as statSync2, unlinkSync as unlinkSync2 } from "node:fs";
|
|
890
|
+
import { homedir, tmpdir } from "node:os";
|
|
848
891
|
import { join as join3 } from "node:path";
|
|
849
892
|
import { spawnSync } from "node:child_process";
|
|
850
893
|
|
|
@@ -937,8 +980,12 @@ function checkAgentLock(opts) {
|
|
|
937
980
|
} catch {}
|
|
938
981
|
return { locked: false, stale: true };
|
|
939
982
|
}
|
|
940
|
-
if (record.pid === currentPid)
|
|
983
|
+
if (record.pid === currentPid) {
|
|
984
|
+
if (opts.currentSessionId && record.sessionId && opts.currentSessionId !== record.sessionId) {
|
|
985
|
+
return { locked: true, holder: record };
|
|
986
|
+
}
|
|
941
987
|
return { locked: false, holder: record };
|
|
988
|
+
}
|
|
942
989
|
if (opts.lockOwnerPid && record.pid === opts.lockOwnerPid)
|
|
943
990
|
return { locked: false, holder: record };
|
|
944
991
|
if (opts.currentSessionId && record.sessionId && opts.currentSessionId === record.sessionId) {
|
|
@@ -1024,9 +1071,30 @@ function saveSessionBind(configDir, sessionId, profileName) {
|
|
|
1024
1071
|
current = parseSessionBinds(JSON.parse(readFileSync3(path, "utf8")));
|
|
1025
1072
|
} catch {}
|
|
1026
1073
|
}
|
|
1074
|
+
for (const [existingSid, existingProf] of Object.entries(current)) {
|
|
1075
|
+
if (existingProf === prof && existingSid !== sid) {
|
|
1076
|
+
delete current[existingSid];
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
delete current[sid];
|
|
1027
1080
|
current[sid] = prof;
|
|
1028
1081
|
mkdirSync(configDir, { recursive: true });
|
|
1029
1082
|
safeWriteProfile(path, current);
|
|
1083
|
+
const legacyPath = join3(configDir, LEGACY_AGY_BINDS_FILENAME);
|
|
1084
|
+
if (existsSync3(legacyPath)) {
|
|
1085
|
+
try {
|
|
1086
|
+
const legacy = parseSessionBinds(JSON.parse(readFileSync3(legacyPath, "utf8")));
|
|
1087
|
+
let changed = false;
|
|
1088
|
+
for (const [existingSid, existingProf] of Object.entries(legacy)) {
|
|
1089
|
+
if (existingProf === prof && existingSid !== sid) {
|
|
1090
|
+
delete legacy[existingSid];
|
|
1091
|
+
changed = true;
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
if (changed)
|
|
1095
|
+
safeWriteProfile(legacyPath, legacy);
|
|
1096
|
+
} catch {}
|
|
1097
|
+
}
|
|
1030
1098
|
}
|
|
1031
1099
|
function removeSessionBind(configDir, sessionId) {
|
|
1032
1100
|
const sid = sessionId.trim();
|
|
@@ -1078,12 +1146,6 @@ function detectRuntimeSession(env = process.env, meta) {
|
|
|
1078
1146
|
if (agySid) {
|
|
1079
1147
|
return { sessionId: agySid, runtime: "antigravity" };
|
|
1080
1148
|
}
|
|
1081
|
-
if (env.__CFBundleIdentifier === "com.google.antigravity" || env.AGY_BROWSER_WS_URL) {
|
|
1082
|
-
const agyHost = discoverAntigravityHost();
|
|
1083
|
-
if (agyHost && agyHost.openConversations.length === 1) {
|
|
1084
|
-
return { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
|
|
1085
|
-
}
|
|
1086
|
-
}
|
|
1087
1149
|
const claudeSid = (env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || "").trim();
|
|
1088
1150
|
if (claudeSid) {
|
|
1089
1151
|
const workspacePath = env.CLAUDE_PROJECT_DIR?.trim() || undefined;
|
|
@@ -1093,6 +1155,12 @@ function detectRuntimeSession(env = process.env, meta) {
|
|
|
1093
1155
|
if (explicitSid) {
|
|
1094
1156
|
return { sessionId: explicitSid, runtime: "custom" };
|
|
1095
1157
|
}
|
|
1158
|
+
if (env === process.env || env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(env.AGY_BROWSER_WS_URL)) {
|
|
1159
|
+
const agyHost = discoverAntigravityHost();
|
|
1160
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
1161
|
+
return { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1096
1164
|
return null;
|
|
1097
1165
|
}
|
|
1098
1166
|
var cachedAgyHost = null;
|
|
@@ -1145,7 +1213,7 @@ function discoverAntigravityHost(opts) {
|
|
|
1145
1213
|
if (p > 0 && !ports.includes(p))
|
|
1146
1214
|
ports.push(p);
|
|
1147
1215
|
}
|
|
1148
|
-
const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/);
|
|
1216
|
+
const presMatch = line.match(/\/presence\/([0-9a-fA-F-]{36})\.lock$/) || line.match(/\/conversations\/([0-9a-fA-F-]{36})\.db$/);
|
|
1149
1217
|
if (presMatch) {
|
|
1150
1218
|
const cid = presMatch[1];
|
|
1151
1219
|
if (!openConversations.includes(cid))
|
|
@@ -1162,11 +1230,396 @@ function discoverAntigravityHost(opts) {
|
|
|
1162
1230
|
return null;
|
|
1163
1231
|
}
|
|
1164
1232
|
}
|
|
1233
|
+
function detectAntigravityCallerSession(opts) {
|
|
1234
|
+
const brainDir = opts?.brainDir?.trim() || process.env.AGENTSCHAT_AGY_BRAIN_DIR?.trim() || join3(homedir(), ".gemini", "antigravity", "brain");
|
|
1235
|
+
if (!existsSync3(brainDir))
|
|
1236
|
+
return null;
|
|
1237
|
+
const nowMs = opts?.nowMs ?? Date.now();
|
|
1238
|
+
const maxAgeMs = opts?.maxAgeMs ?? 30000;
|
|
1239
|
+
const uuidRe = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
1240
|
+
const candidateSet = new Set;
|
|
1241
|
+
for (const cid of opts?.openConversations ?? []) {
|
|
1242
|
+
if (uuidRe.test(cid))
|
|
1243
|
+
candidateSet.add(cid);
|
|
1244
|
+
}
|
|
1245
|
+
try {
|
|
1246
|
+
for (const entry of readdirSync(brainDir)) {
|
|
1247
|
+
if (uuidRe.test(entry))
|
|
1248
|
+
candidateSet.add(entry);
|
|
1249
|
+
}
|
|
1250
|
+
} catch {}
|
|
1251
|
+
if (candidateSet.size === 0)
|
|
1252
|
+
return null;
|
|
1253
|
+
const toolName = opts?.toolName?.trim() || "";
|
|
1254
|
+
const argStrings = [];
|
|
1255
|
+
if (opts?.args && typeof opts.args === "object") {
|
|
1256
|
+
for (const val of Object.values(opts.args)) {
|
|
1257
|
+
if (typeof val === "string") {
|
|
1258
|
+
const trimmed = val.trim();
|
|
1259
|
+
if (trimmed.length >= 2 && trimmed.length <= 200) {
|
|
1260
|
+
argStrings.push(trimmed);
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
}
|
|
1264
|
+
}
|
|
1265
|
+
let bestCid = null;
|
|
1266
|
+
let bestScore = -1;
|
|
1267
|
+
let bestMtime = -1;
|
|
1268
|
+
const recentCids = [];
|
|
1269
|
+
for (const cid of candidateSet) {
|
|
1270
|
+
const transcriptPath = join3(brainDir, cid, ".system_generated", "logs", "transcript.jsonl");
|
|
1271
|
+
let st;
|
|
1272
|
+
try {
|
|
1273
|
+
st = statSync2(transcriptPath);
|
|
1274
|
+
} catch {
|
|
1275
|
+
continue;
|
|
1276
|
+
}
|
|
1277
|
+
if (st.size <= 0 || nowMs - st.mtimeMs > maxAgeMs)
|
|
1278
|
+
continue;
|
|
1279
|
+
recentCids.push({ cid, mtimeMs: st.mtimeMs });
|
|
1280
|
+
let tail = "";
|
|
1281
|
+
let fd = null;
|
|
1282
|
+
try {
|
|
1283
|
+
fd = openSync(transcriptPath, "r");
|
|
1284
|
+
const readLen = Math.min(st.size, 16384);
|
|
1285
|
+
const buf = Buffer.allocUnsafe(readLen);
|
|
1286
|
+
const bytesRead = readSync(fd, buf, 0, readLen, st.size - readLen);
|
|
1287
|
+
tail = buf.toString("utf8", 0, bytesRead);
|
|
1288
|
+
} catch {
|
|
1289
|
+
continue;
|
|
1290
|
+
} finally {
|
|
1291
|
+
if (fd !== null) {
|
|
1292
|
+
try {
|
|
1293
|
+
closeSync(fd);
|
|
1294
|
+
} catch {}
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
const lines = tail.split(/\r?\n/).filter((l) => l.trim().length > 0);
|
|
1298
|
+
for (let i = lines.length - 1;i >= Math.max(0, lines.length - 12); i--) {
|
|
1299
|
+
const line = lines[i];
|
|
1300
|
+
if (!line.includes('"PLANNER_RESPONSE"'))
|
|
1301
|
+
continue;
|
|
1302
|
+
let score = 0;
|
|
1303
|
+
if (toolName) {
|
|
1304
|
+
const hasToolMatch = line.includes(`"mcp_agentschat_${toolName}"`) || line.includes(`\\"ToolName\\":\\"${toolName}\\"`) || line.includes(`"ToolName":"\\"${toolName}\\""`) || line.includes(`"ToolName":"${toolName}"`) || line.includes(`"name":"${toolName}"`) || line.includes(`\\"tool_name\\":\\"${toolName}\\"`) || line.includes(`"tool_name":"${toolName}"`);
|
|
1305
|
+
if (!hasToolMatch)
|
|
1306
|
+
continue;
|
|
1307
|
+
score += 1000;
|
|
1308
|
+
} else {
|
|
1309
|
+
score += 100;
|
|
1310
|
+
}
|
|
1311
|
+
if (i === lines.length - 1)
|
|
1312
|
+
score += 50;
|
|
1313
|
+
for (const s of argStrings) {
|
|
1314
|
+
if (line.includes(s))
|
|
1315
|
+
score += 200;
|
|
1316
|
+
}
|
|
1317
|
+
if (score > bestScore || score === bestScore && st.mtimeMs > bestMtime) {
|
|
1318
|
+
bestScore = score;
|
|
1319
|
+
bestMtime = st.mtimeMs;
|
|
1320
|
+
bestCid = cid;
|
|
1321
|
+
}
|
|
1322
|
+
break;
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
if (bestCid)
|
|
1326
|
+
return bestCid;
|
|
1327
|
+
if (recentCids.length === 1 && nowMs - recentCids[0].mtimeMs <= 5000) {
|
|
1328
|
+
return recentCids[0].cid;
|
|
1329
|
+
}
|
|
1330
|
+
return null;
|
|
1331
|
+
}
|
|
1332
|
+
var cachedIsDshHost = null;
|
|
1333
|
+
function isDshHostProcess(opts) {
|
|
1334
|
+
const env = opts?.env ?? process.env;
|
|
1335
|
+
if (env.AGENTSCHAT_DSH_HOME?.trim() || env.DSH_HOME?.trim() || env.AGENTSCHAT_DSH_HEALTH_URL?.trim()) {
|
|
1336
|
+
return true;
|
|
1337
|
+
}
|
|
1338
|
+
const now = Date.now();
|
|
1339
|
+
const cacheMs = opts?.cacheMs ?? 15000;
|
|
1340
|
+
if (cachedIsDshHost && now - cachedIsDshHost.at < cacheMs)
|
|
1341
|
+
return cachedIsDshHost.value;
|
|
1342
|
+
try {
|
|
1343
|
+
let pid = opts?.currentPid ?? process.pid;
|
|
1344
|
+
for (let hop = 0;hop < 4 && pid > 1; hop++) {
|
|
1345
|
+
const ps = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "ppid=,command="], {
|
|
1346
|
+
encoding: "utf8",
|
|
1347
|
+
timeout: 1000
|
|
1348
|
+
});
|
|
1349
|
+
if (ps.status !== 0 || !ps.stdout)
|
|
1350
|
+
break;
|
|
1351
|
+
const line = ps.stdout.trim().split(/\r?\n/)[0]?.trim() || "";
|
|
1352
|
+
const m = line.match(/^(\d+)\s+(.*)$/);
|
|
1353
|
+
if (!m)
|
|
1354
|
+
break;
|
|
1355
|
+
const ppid = Number(m[1]);
|
|
1356
|
+
const cmd = m[2];
|
|
1357
|
+
if (hop > 0 && (cmd.includes("bun test") || cmd.includes("node --test")))
|
|
1358
|
+
break;
|
|
1359
|
+
if (cmd.includes("@deepseek-ai") || cmd.includes("/.dsh/") || /\bdsh\b/.test(cmd)) {
|
|
1360
|
+
cachedIsDshHost = { at: now, value: true };
|
|
1361
|
+
return true;
|
|
1362
|
+
}
|
|
1363
|
+
pid = ppid;
|
|
1364
|
+
}
|
|
1365
|
+
} catch {}
|
|
1366
|
+
cachedIsDshHost = { at: now, value: false };
|
|
1367
|
+
return false;
|
|
1368
|
+
}
|
|
1369
|
+
function sessionDirMtime(dir) {
|
|
1370
|
+
let newest = 0;
|
|
1371
|
+
for (const file of ["session.v4.jsonl.zstd", "session.v4.jsonl"]) {
|
|
1372
|
+
try {
|
|
1373
|
+
const mtime = statSync2(join3(dir, file)).mtimeMs;
|
|
1374
|
+
if (mtime > newest)
|
|
1375
|
+
newest = mtime;
|
|
1376
|
+
} catch {}
|
|
1377
|
+
}
|
|
1378
|
+
return newest;
|
|
1379
|
+
}
|
|
1380
|
+
function sessionLogMtime(dshHome, sid) {
|
|
1381
|
+
let projects;
|
|
1382
|
+
try {
|
|
1383
|
+
projects = readdirSync(join3(dshHome, "sessions"));
|
|
1384
|
+
} catch {
|
|
1385
|
+
return 0;
|
|
1386
|
+
}
|
|
1387
|
+
let newest = 0;
|
|
1388
|
+
for (const project of projects) {
|
|
1389
|
+
const mtime = sessionDirMtime(join3(dshHome, "sessions", project, sid));
|
|
1390
|
+
if (mtime > newest)
|
|
1391
|
+
newest = mtime;
|
|
1392
|
+
}
|
|
1393
|
+
return newest;
|
|
1394
|
+
}
|
|
1395
|
+
function newestSessionLog(dshHome, nowMs, maxAgeMs) {
|
|
1396
|
+
const root = join3(dshHome, "sessions");
|
|
1397
|
+
let projects;
|
|
1398
|
+
try {
|
|
1399
|
+
projects = readdirSync(root);
|
|
1400
|
+
} catch {
|
|
1401
|
+
return null;
|
|
1402
|
+
}
|
|
1403
|
+
let best = null;
|
|
1404
|
+
for (const project of projects) {
|
|
1405
|
+
let entries;
|
|
1406
|
+
try {
|
|
1407
|
+
entries = readdirSync(join3(root, project));
|
|
1408
|
+
} catch {
|
|
1409
|
+
continue;
|
|
1410
|
+
}
|
|
1411
|
+
for (const entry of entries) {
|
|
1412
|
+
if (!entry.startsWith("session-"))
|
|
1413
|
+
continue;
|
|
1414
|
+
const mtime = sessionDirMtime(join3(root, project, entry));
|
|
1415
|
+
if (mtime === 0 || nowMs - mtime > maxAgeMs)
|
|
1416
|
+
continue;
|
|
1417
|
+
if (best === null || mtime > best.mtime)
|
|
1418
|
+
best = { sid: entry, mtime };
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
return best?.sid ?? null;
|
|
1422
|
+
}
|
|
1423
|
+
async function detectDshCallerSession(opts) {
|
|
1424
|
+
const env = opts?.env ?? process.env;
|
|
1425
|
+
if (!opts?.dshHome && !opts?.healthUrl && !isDshHostProcess({ env })) {
|
|
1426
|
+
return null;
|
|
1427
|
+
}
|
|
1428
|
+
const dshHome = opts?.dshHome?.trim() || env.AGENTSCHAT_DSH_HOME?.trim() || env.DSH_HOME?.trim() || join3(homedir(), ".dsh");
|
|
1429
|
+
const healthUrl = opts?.healthUrl?.trim() || env.AGENTSCHAT_DSH_HEALTH_URL?.trim() || "http://127.0.0.1:8799/health";
|
|
1430
|
+
const nowMs = opts?.nowMs ?? Date.now();
|
|
1431
|
+
try {
|
|
1432
|
+
const f = opts?.fetchImpl ?? fetch;
|
|
1433
|
+
const ctrl = new AbortController;
|
|
1434
|
+
const timer = setTimeout(() => ctrl.abort(), 150);
|
|
1435
|
+
try {
|
|
1436
|
+
const res = await f(healthUrl, { signal: ctrl.signal });
|
|
1437
|
+
if (res.ok) {
|
|
1438
|
+
const data = await res.json();
|
|
1439
|
+
const roots = Array.isArray(data?.roots) ? data.roots : [];
|
|
1440
|
+
const running = roots.filter((r) => typeof r?.id === "string" && r.id.startsWith("session-") && r.status === "running").map((r) => r.id);
|
|
1441
|
+
if (running.length === 1)
|
|
1442
|
+
return running[0];
|
|
1443
|
+
if (running.length > 1) {
|
|
1444
|
+
const ranked = running.map((sid) => ({ sid, mtime: sessionLogMtime(dshHome, sid) })).sort((a, b) => b.mtime - a.mtime);
|
|
1445
|
+
if (ranked[0].mtime > 0 && ranked[0].mtime >= ranked[1].mtime)
|
|
1446
|
+
return ranked[0].sid;
|
|
1447
|
+
return running[running.length - 1];
|
|
1448
|
+
}
|
|
1449
|
+
const allValid = roots.filter((r) => typeof r?.id === "string" && r.id.startsWith("session-")).map((r) => r.id);
|
|
1450
|
+
if (allValid.length === 1)
|
|
1451
|
+
return allValid[0];
|
|
1452
|
+
}
|
|
1453
|
+
} finally {
|
|
1454
|
+
clearTimeout(timer);
|
|
1455
|
+
}
|
|
1456
|
+
} catch {}
|
|
1457
|
+
const newestByLog = newestSessionLog(dshHome, nowMs, 30000);
|
|
1458
|
+
if (newestByLog)
|
|
1459
|
+
return newestByLog;
|
|
1460
|
+
return null;
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
// src/session-route.ts
|
|
1464
|
+
import { existsSync as existsSync5, readFileSync as readFileSync5 } from "node:fs";
|
|
1465
|
+
import { homedir as homedir2 } from "node:os";
|
|
1466
|
+
import { join as join5 } from "node:path";
|
|
1467
|
+
|
|
1468
|
+
// src/session-bind.ts
|
|
1469
|
+
import { closeSync as closeSync2, existsSync as existsSync4, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync4, readSync as readSync2, readdirSync as readdirSync2, statSync as statSync3, unlinkSync as unlinkSync3 } from "node:fs";
|
|
1470
|
+
import { join as join4 } from "node:path";
|
|
1471
|
+
var DEFAULT_SESSION_BINDS_FILENAME2 = "session-binds.json";
|
|
1472
|
+
var LEGACY_AGY_BINDS_FILENAME2 = "agy-binds.json";
|
|
1473
|
+
function parseSessionBinds2(raw) {
|
|
1474
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
1475
|
+
return {};
|
|
1476
|
+
const out = {};
|
|
1477
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
1478
|
+
const key = k.trim();
|
|
1479
|
+
if (!key)
|
|
1480
|
+
continue;
|
|
1481
|
+
if (typeof v === "string" && v.trim()) {
|
|
1482
|
+
out[key] = v.trim();
|
|
1483
|
+
} else if (v && typeof v === "object" && typeof v.profile === "string" && v.profile.trim()) {
|
|
1484
|
+
out[key] = v.profile.trim();
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1487
|
+
return out;
|
|
1488
|
+
}
|
|
1489
|
+
function loadSessionBinds2(configDir) {
|
|
1490
|
+
const merged = {};
|
|
1491
|
+
for (const filename of [LEGACY_AGY_BINDS_FILENAME2, DEFAULT_SESSION_BINDS_FILENAME2]) {
|
|
1492
|
+
const path = join4(configDir, filename);
|
|
1493
|
+
if (!existsSync4(path))
|
|
1494
|
+
continue;
|
|
1495
|
+
try {
|
|
1496
|
+
Object.assign(merged, parseSessionBinds2(JSON.parse(readFileSync4(path, "utf8"))));
|
|
1497
|
+
} catch {}
|
|
1498
|
+
}
|
|
1499
|
+
return merged;
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// src/session-route.ts
|
|
1503
|
+
function agentschatConfigDir(env = process.env) {
|
|
1504
|
+
return env.AGENTSCHAT_CONFIG_DIR ?? join5(homedir2(), ".agentschat");
|
|
1505
|
+
}
|
|
1506
|
+
function profilePathForName(configDir, name) {
|
|
1507
|
+
if (!name || name.includes("/") || name.includes("\\"))
|
|
1508
|
+
return;
|
|
1509
|
+
const base = name.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1510
|
+
const nested = join5(configDir, "profiles", `${base}.json`);
|
|
1511
|
+
if (existsSync5(nested))
|
|
1512
|
+
return nested;
|
|
1513
|
+
const flat = join5(configDir, `${base}.json`);
|
|
1514
|
+
return existsSync5(flat) ? flat : undefined;
|
|
1515
|
+
}
|
|
1516
|
+
function readAgentId(path) {
|
|
1517
|
+
try {
|
|
1518
|
+
const parsed = JSON.parse(readFileSync5(path, "utf8"));
|
|
1519
|
+
return typeof parsed.agent_id === "string" && parsed.agent_id ? parsed.agent_id : undefined;
|
|
1520
|
+
} catch {
|
|
1521
|
+
return;
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
function resolveSessionForAgent(agentId, opts = {}) {
|
|
1525
|
+
if (typeof agentId !== "string" || agentId.length === 0)
|
|
1526
|
+
return;
|
|
1527
|
+
const configDir = opts.configDir ?? agentschatConfigDir(opts.env);
|
|
1528
|
+
let binds;
|
|
1529
|
+
try {
|
|
1530
|
+
binds = loadSessionBinds2(configDir);
|
|
1531
|
+
} catch {
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
1534
|
+
for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
|
|
1535
|
+
const path = profilePathForName(configDir, profileName);
|
|
1536
|
+
if (path === undefined)
|
|
1537
|
+
continue;
|
|
1538
|
+
if (readAgentId(path) !== agentId)
|
|
1539
|
+
continue;
|
|
1540
|
+
return { sessionId, profileName, agentId };
|
|
1541
|
+
}
|
|
1542
|
+
return;
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
// src/heartbeat.ts
|
|
1546
|
+
var WS_CONNECTING = 0;
|
|
1547
|
+
var WS_OPEN = 1;
|
|
1548
|
+
var WS_CLOSING = 2;
|
|
1549
|
+
var WS_CLOSED = 3;
|
|
1550
|
+
|
|
1551
|
+
class HeartbeatMonitor {
|
|
1552
|
+
deps;
|
|
1553
|
+
pingInterval;
|
|
1554
|
+
pongTimeout;
|
|
1555
|
+
connectTimeout;
|
|
1556
|
+
lastPong;
|
|
1557
|
+
timer = null;
|
|
1558
|
+
connectingSince = null;
|
|
1559
|
+
reconnecting = false;
|
|
1560
|
+
constructor(deps, pingInterval = 30000, pongTimeout = 90000, connectTimeout = 30000) {
|
|
1561
|
+
this.deps = deps;
|
|
1562
|
+
this.pingInterval = pingInterval;
|
|
1563
|
+
this.pongTimeout = pongTimeout;
|
|
1564
|
+
this.connectTimeout = connectTimeout;
|
|
1565
|
+
this.lastPong = Date.now();
|
|
1566
|
+
}
|
|
1567
|
+
receivedPong() {
|
|
1568
|
+
this.lastPong = Date.now();
|
|
1569
|
+
this.connectingSince = null;
|
|
1570
|
+
this.reconnecting = false;
|
|
1571
|
+
}
|
|
1572
|
+
start() {
|
|
1573
|
+
this.stop();
|
|
1574
|
+
this.lastPong = Date.now();
|
|
1575
|
+
this.connectingSince = null;
|
|
1576
|
+
this.reconnecting = false;
|
|
1577
|
+
this.timer = setInterval(() => this.tick(), this.pingInterval);
|
|
1578
|
+
}
|
|
1579
|
+
stop() {
|
|
1580
|
+
if (this.timer) {
|
|
1581
|
+
clearInterval(this.timer);
|
|
1582
|
+
this.timer = null;
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
resetReconnecting() {
|
|
1586
|
+
this.reconnecting = false;
|
|
1587
|
+
}
|
|
1588
|
+
tick() {
|
|
1589
|
+
const state = this.deps.getReadyState();
|
|
1590
|
+
if (state === WS_OPEN) {
|
|
1591
|
+
this.connectingSince = null;
|
|
1592
|
+
if (Date.now() - this.lastPong > this.pongTimeout) {
|
|
1593
|
+
this.safeReconnect("pong timeout");
|
|
1594
|
+
return;
|
|
1595
|
+
}
|
|
1596
|
+
this.deps.sendPing();
|
|
1597
|
+
return;
|
|
1598
|
+
}
|
|
1599
|
+
if (state === WS_CONNECTING) {
|
|
1600
|
+
if (!this.connectingSince) {
|
|
1601
|
+
this.connectingSince = Date.now();
|
|
1602
|
+
} else if (Date.now() - this.connectingSince > this.connectTimeout) {
|
|
1603
|
+
this.connectingSince = null;
|
|
1604
|
+
this.safeReconnect("connect timeout");
|
|
1605
|
+
}
|
|
1606
|
+
return;
|
|
1607
|
+
}
|
|
1608
|
+
this.connectingSince = null;
|
|
1609
|
+
this.safeReconnect(state === WS_CLOSING ? "stuck closing" : "closed");
|
|
1610
|
+
}
|
|
1611
|
+
safeReconnect(reason) {
|
|
1612
|
+
if (this.reconnecting)
|
|
1613
|
+
return;
|
|
1614
|
+
this.reconnecting = true;
|
|
1615
|
+
this.deps.reconnect();
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1165
1618
|
// package.json
|
|
1166
1619
|
var package_default = {
|
|
1167
1620
|
name: "agentschat-mcp",
|
|
1168
1621
|
mcpName: "io.github.swswordholy-tech/agentschat-mcp",
|
|
1169
|
-
version: "0.36.
|
|
1622
|
+
version: "0.36.19",
|
|
1170
1623
|
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.",
|
|
1171
1624
|
type: "module",
|
|
1172
1625
|
bin: {
|
|
@@ -1207,8 +1660,16 @@ var package_default = {
|
|
|
1207
1660
|
"chat",
|
|
1208
1661
|
"social-network",
|
|
1209
1662
|
"multi-agent",
|
|
1210
|
-
"real-time"
|
|
1663
|
+
"real-time",
|
|
1664
|
+
"dsh",
|
|
1665
|
+
"dsh-plugin",
|
|
1666
|
+
"deepseek-harness"
|
|
1211
1667
|
],
|
|
1668
|
+
dsh: {
|
|
1669
|
+
bundle: {
|
|
1670
|
+
patch: "./cordis.patch.yml"
|
|
1671
|
+
}
|
|
1672
|
+
},
|
|
1212
1673
|
author: "AgentsChat",
|
|
1213
1674
|
license: "Apache-2.0",
|
|
1214
1675
|
repository: {
|
|
@@ -1243,6 +1704,7 @@ var package_default = {
|
|
|
1243
1704
|
"src/profile-selection.ts",
|
|
1244
1705
|
"src/grok-bind.ts",
|
|
1245
1706
|
"src/session-bind.ts",
|
|
1707
|
+
"src/session-route.ts",
|
|
1246
1708
|
"src/tool-annotations.ts",
|
|
1247
1709
|
"src/identity-guard.ts",
|
|
1248
1710
|
"src/terms.ts",
|
|
@@ -1274,7 +1736,12 @@ var package_default = {
|
|
|
1274
1736
|
"scripts/example-url-wake-receiver.mjs",
|
|
1275
1737
|
"scripts/example-url-wake-ensure.sh",
|
|
1276
1738
|
"scripts/example-agy-mcp-wrapper.sh",
|
|
1277
|
-
"skills/hermes-host-keepalive.md"
|
|
1739
|
+
"skills/hermes-host-keepalive.md",
|
|
1740
|
+
"muse/",
|
|
1741
|
+
"dist/muse.js",
|
|
1742
|
+
"cordis.patch.yml",
|
|
1743
|
+
"dsh/",
|
|
1744
|
+
"dist/dsh.js"
|
|
1278
1745
|
]
|
|
1279
1746
|
};
|
|
1280
1747
|
|
|
@@ -1283,17 +1750,17 @@ import {
|
|
|
1283
1750
|
CallToolRequestSchema,
|
|
1284
1751
|
ListToolsRequestSchema
|
|
1285
1752
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
1286
|
-
import { readFileSync as
|
|
1287
|
-
import { join as
|
|
1753
|
+
import { readFileSync as readFileSync7, existsSync as existsSync7, writeFileSync as writeFileSync4, mkdirSync as mkdirSync3, readdirSync as readdirSync3 } from "fs";
|
|
1754
|
+
import { join as join6, dirname } from "path";
|
|
1288
1755
|
|
|
1289
1756
|
// src/profile-store.ts
|
|
1290
|
-
import { existsSync as
|
|
1757
|
+
import { existsSync as existsSync6, writeFileSync as writeFileSync2, renameSync as renameSync2, chmodSync as chmodSync2, unlinkSync as unlinkSync4, statSync as statSync4 } from "fs";
|
|
1291
1758
|
var defaultWarn2 = (m) => process.stderr.write(m);
|
|
1292
1759
|
function safeWriteProfile2(path, data, warn = defaultWarn2) {
|
|
1293
1760
|
const tmp = path + ".tmp";
|
|
1294
1761
|
try {
|
|
1295
|
-
if (
|
|
1296
|
-
|
|
1762
|
+
if (existsSync6(tmp))
|
|
1763
|
+
unlinkSync4(tmp);
|
|
1297
1764
|
} catch (e) {
|
|
1298
1765
|
warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
|
|
1299
1766
|
`);
|
|
@@ -1307,7 +1774,7 @@ function safeWriteProfile2(path, data, warn = defaultWarn2) {
|
|
|
1307
1774
|
`);
|
|
1308
1775
|
}
|
|
1309
1776
|
try {
|
|
1310
|
-
const mode =
|
|
1777
|
+
const mode = statSync4(path).mode & 511;
|
|
1311
1778
|
if (mode !== 384) {
|
|
1312
1779
|
warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
|
|
1313
1780
|
`);
|
|
@@ -1400,10 +1867,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
|
|
|
1400
1867
|
}
|
|
1401
1868
|
|
|
1402
1869
|
// src/read-cursor.ts
|
|
1403
|
-
import { readFileSync as
|
|
1870
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
|
|
1404
1871
|
function loadCursor(file, warn) {
|
|
1405
1872
|
try {
|
|
1406
|
-
return new Map(Object.entries(JSON.parse(
|
|
1873
|
+
return new Map(Object.entries(JSON.parse(readFileSync6(file, "utf-8"))));
|
|
1407
1874
|
} catch (e) {
|
|
1408
1875
|
if (e?.code !== "ENOENT") {
|
|
1409
1876
|
warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
|
|
@@ -1433,83 +1900,16 @@ function flushCursor(state, persist) {
|
|
|
1433
1900
|
|
|
1434
1901
|
// src/server.ts
|
|
1435
1902
|
import { randomUUID } from "crypto";
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
class HeartbeatMonitor {
|
|
1444
|
-
deps;
|
|
1445
|
-
pingInterval;
|
|
1446
|
-
pongTimeout;
|
|
1447
|
-
connectTimeout;
|
|
1448
|
-
lastPong;
|
|
1449
|
-
timer = null;
|
|
1450
|
-
connectingSince = null;
|
|
1451
|
-
reconnecting = false;
|
|
1452
|
-
constructor(deps, pingInterval = 30000, pongTimeout = 90000, connectTimeout = 30000) {
|
|
1453
|
-
this.deps = deps;
|
|
1454
|
-
this.pingInterval = pingInterval;
|
|
1455
|
-
this.pongTimeout = pongTimeout;
|
|
1456
|
-
this.connectTimeout = connectTimeout;
|
|
1457
|
-
this.lastPong = Date.now();
|
|
1458
|
-
}
|
|
1459
|
-
receivedPong() {
|
|
1460
|
-
this.lastPong = Date.now();
|
|
1461
|
-
this.connectingSince = null;
|
|
1462
|
-
this.reconnecting = false;
|
|
1463
|
-
}
|
|
1464
|
-
start() {
|
|
1465
|
-
this.stop();
|
|
1466
|
-
this.lastPong = Date.now();
|
|
1467
|
-
this.connectingSince = null;
|
|
1468
|
-
this.reconnecting = false;
|
|
1469
|
-
this.timer = setInterval(() => this.tick(), this.pingInterval);
|
|
1470
|
-
}
|
|
1471
|
-
stop() {
|
|
1472
|
-
if (this.timer) {
|
|
1473
|
-
clearInterval(this.timer);
|
|
1474
|
-
this.timer = null;
|
|
1475
|
-
}
|
|
1476
|
-
}
|
|
1477
|
-
resetReconnecting() {
|
|
1478
|
-
this.reconnecting = false;
|
|
1479
|
-
}
|
|
1480
|
-
tick() {
|
|
1481
|
-
const state = this.deps.getReadyState();
|
|
1482
|
-
if (state === WS_OPEN) {
|
|
1483
|
-
this.connectingSince = null;
|
|
1484
|
-
if (Date.now() - this.lastPong > this.pongTimeout) {
|
|
1485
|
-
this.safeReconnect("pong timeout");
|
|
1486
|
-
return;
|
|
1487
|
-
}
|
|
1488
|
-
this.deps.sendPing();
|
|
1489
|
-
return;
|
|
1490
|
-
}
|
|
1491
|
-
if (state === WS_CONNECTING) {
|
|
1492
|
-
if (!this.connectingSince) {
|
|
1493
|
-
this.connectingSince = Date.now();
|
|
1494
|
-
} else if (Date.now() - this.connectingSince > this.connectTimeout) {
|
|
1495
|
-
this.connectingSince = null;
|
|
1496
|
-
this.safeReconnect("connect timeout");
|
|
1497
|
-
}
|
|
1498
|
-
return;
|
|
1499
|
-
}
|
|
1500
|
-
this.connectingSince = null;
|
|
1501
|
-
this.safeReconnect(state === WS_CLOSING ? "stuck closing" : "closed");
|
|
1502
|
-
}
|
|
1503
|
-
safeReconnect(reason) {
|
|
1504
|
-
if (this.reconnecting)
|
|
1505
|
-
return;
|
|
1506
|
-
this.reconnecting = true;
|
|
1507
|
-
this.deps.reconnect();
|
|
1903
|
+
for (const key of ["NO_PROXY", "no_proxy"]) {
|
|
1904
|
+
const cur = process.env[key]?.trim() || "";
|
|
1905
|
+
const items = cur ? cur.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
1906
|
+
for (const host of ["localhost", "127.0.0.1", "::1", "[::1]"]) {
|
|
1907
|
+
if (!items.includes(host))
|
|
1908
|
+
items.push(host);
|
|
1508
1909
|
}
|
|
1910
|
+
process.env[key] = items.join(",");
|
|
1509
1911
|
}
|
|
1510
|
-
|
|
1511
|
-
// src/server.ts
|
|
1512
|
-
if (process.env.AGENTCHAT_NO_PROXY === "1") {
|
|
1912
|
+
if (process.env.AGENTCHAT_NO_PROXY === "1" && process.env.NODE_USE_ENV_PROXY !== "1") {
|
|
1513
1913
|
delete process.env.HTTP_PROXY;
|
|
1514
1914
|
delete process.env.HTTPS_PROXY;
|
|
1515
1915
|
delete process.env.http_proxy;
|
|
@@ -1552,16 +1952,15 @@ function parseArgs() {
|
|
|
1552
1952
|
}
|
|
1553
1953
|
var cliArgs = parseArgs();
|
|
1554
1954
|
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
1555
|
-
console.log(`agentschat-mcp \u2014 AgentsChat MCP and host bridges
|
|
1955
|
+
console.log(`agentschat-mcp v${package_default.version} \u2014 AgentsChat MCP and host bridges
|
|
1556
1956
|
|
|
1557
|
-
Usage: claude mcp add agentschat -- npx -y agentschat-mcp
|
|
1957
|
+
Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
|
|
1558
1958
|
claude --dangerously-load-development-channels server:agentschat
|
|
1559
|
-
One MCP server entry per bot, each pinning --profile
|
|
1560
|
-
(not @latest, which drifts).
|
|
1959
|
+
One MCP server entry per bot, each pinning --profile.
|
|
1561
1960
|
|
|
1562
1961
|
Setup guide for every supported host:
|
|
1563
1962
|
Read skills/onboarding.md relative to this installed package root.
|
|
1564
|
-
Online
|
|
1963
|
+
Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
|
|
1565
1964
|
Newest release (first install): npx -y agentschat-mcp@latest --help
|
|
1566
1965
|
The guide selects Claude Code, Codex, OpenClaw, Hermes, Grok Bot, URL wake,
|
|
1567
1966
|
or the separately deployed dot remote MCP + Events integration.
|
|
@@ -1617,36 +2016,37 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
|
|
|
1617
2016
|
process.exit(0);
|
|
1618
2017
|
}
|
|
1619
2018
|
var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
1620
|
-
var configDir =
|
|
1621
|
-
var legacyConfigDir =
|
|
2019
|
+
var configDir = join6(homeDir, ".agentschat");
|
|
2020
|
+
var legacyConfigDir = join6(homeDir, ".agentchat");
|
|
1622
2021
|
var profileDirs = [configDir, legacyConfigDir];
|
|
1623
2022
|
var lockDir = resolveLockDir(homeDir, process.env);
|
|
1624
2023
|
var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
|
|
1625
2024
|
var toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
|
|
1626
2025
|
var runtimeSession = detectRuntimeSession(process.env);
|
|
2026
|
+
var dshRouteWarned = false;
|
|
1627
2027
|
function profileNameToPaths(name) {
|
|
1628
2028
|
if (name.startsWith("~/"))
|
|
1629
|
-
return [
|
|
2029
|
+
return [join6(homeDir, name.slice(2))];
|
|
1630
2030
|
if (name.includes("/") || name.includes("\\"))
|
|
1631
2031
|
return [name];
|
|
1632
2032
|
name = name.replace(/\.json$/, "");
|
|
1633
2033
|
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1634
|
-
return profileDirs.map((dir) =>
|
|
2034
|
+
return profileDirs.map((dir) => join6(dir, `${safeName}.json`));
|
|
1635
2035
|
}
|
|
1636
2036
|
function nameToPath(name) {
|
|
1637
2037
|
const candidates = profileNameToPaths(name);
|
|
1638
|
-
const nested =
|
|
1639
|
-
if (!name.includes("/") && !name.includes("\\") &&
|
|
2038
|
+
const nested = join6(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
|
|
2039
|
+
if (!name.includes("/") && !name.includes("\\") && existsSync7(nested))
|
|
1640
2040
|
return nested;
|
|
1641
|
-
return candidates.find((path) =>
|
|
2041
|
+
return candidates.find((path) => existsSync7(path)) || candidates[0];
|
|
1642
2042
|
}
|
|
1643
2043
|
function listProfileFiles() {
|
|
1644
2044
|
const seen = new Set;
|
|
1645
2045
|
const profiles = [];
|
|
1646
|
-
for (const dir of [
|
|
2046
|
+
for (const dir of [join6(configDir, "profiles"), ...profileDirs]) {
|
|
1647
2047
|
let files = [];
|
|
1648
2048
|
try {
|
|
1649
|
-
files =
|
|
2049
|
+
files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
|
|
1650
2050
|
} catch {}
|
|
1651
2051
|
for (const file of files) {
|
|
1652
2052
|
if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME || file === DEFAULT_SESSION_BINDS_FILENAME || file === LEGACY_AGY_BINDS_FILENAME)
|
|
@@ -1655,7 +2055,7 @@ function listProfileFiles() {
|
|
|
1655
2055
|
if (seen.has(name))
|
|
1656
2056
|
continue;
|
|
1657
2057
|
seen.add(name);
|
|
1658
|
-
profiles.push({ name, path:
|
|
2058
|
+
profiles.push({ name, path: join6(dir, file) });
|
|
1659
2059
|
}
|
|
1660
2060
|
}
|
|
1661
2061
|
return profiles;
|
|
@@ -1680,9 +2080,9 @@ function resolveProfile() {
|
|
|
1680
2080
|
let binds = {};
|
|
1681
2081
|
if (!grokToken && conversationId) {
|
|
1682
2082
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
1683
|
-
if (
|
|
2083
|
+
if (existsSync7(bindPath)) {
|
|
1684
2084
|
try {
|
|
1685
|
-
const parsed = parseGrokBindsText(
|
|
2085
|
+
const parsed = parseGrokBindsText(readFileSync7(bindPath, "utf-8"));
|
|
1686
2086
|
binds = parsed.binds;
|
|
1687
2087
|
if (parsed.malformed) {
|
|
1688
2088
|
process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
|
|
@@ -1717,7 +2117,7 @@ function resolveProfile() {
|
|
|
1717
2117
|
const boundProfile = sessionBinds[runtimeSession.sessionId];
|
|
1718
2118
|
if (boundProfile) {
|
|
1719
2119
|
const boundPath = nameToPath(boundProfile);
|
|
1720
|
-
if (
|
|
2120
|
+
if (existsSync7(boundPath)) {
|
|
1721
2121
|
process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} \u2192 profile "${boundProfile}"
|
|
1722
2122
|
`);
|
|
1723
2123
|
return { path: boundPath, source: "session-bind", declaredName: boundProfile };
|
|
@@ -1762,7 +2162,7 @@ if (hasToken && !explicitAgentId && profileSource === "default") {
|
|
|
1762
2162
|
process.exit(1);
|
|
1763
2163
|
}
|
|
1764
2164
|
var identity = decideIdentity({
|
|
1765
|
-
profileExists:
|
|
2165
|
+
profileExists: existsSync7(profileFile),
|
|
1766
2166
|
source: profileSource,
|
|
1767
2167
|
profileFile,
|
|
1768
2168
|
cliName: cliArgs.name,
|
|
@@ -1773,7 +2173,7 @@ var identity = decideIdentity({
|
|
|
1773
2173
|
});
|
|
1774
2174
|
function readIdentityProfile(file) {
|
|
1775
2175
|
try {
|
|
1776
|
-
return JSON.parse(
|
|
2176
|
+
return JSON.parse(readFileSync7(file, "utf-8"));
|
|
1777
2177
|
} catch {
|
|
1778
2178
|
throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
|
|
1779
2179
|
}
|
|
@@ -1875,7 +2275,7 @@ if (identity.mode === "profile") {
|
|
|
1875
2275
|
`);
|
|
1876
2276
|
process.exit(1);
|
|
1877
2277
|
}
|
|
1878
|
-
|
|
2278
|
+
mkdirSync3(dirname(profileFile), { recursive: true });
|
|
1879
2279
|
safeWriteProfile2(profileFile, profile);
|
|
1880
2280
|
process.stderr.write(`[agentchat] Profile saved: ${profileFile}
|
|
1881
2281
|
`);
|
|
@@ -1955,24 +2355,29 @@ if (!anonymousMode || explicitAgentId !== undefined || hasToken) {
|
|
|
1955
2355
|
}
|
|
1956
2356
|
}
|
|
1957
2357
|
if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
|
|
2358
|
+
const activeName = profileNameFromPath(activeProfileFile) ?? declaredName ?? null;
|
|
2359
|
+
if (activeName && runtimeSession?.runtime === "antigravity" && !process.env.ANTIGRAVITY_CONVERSATION_ID?.trim()) {
|
|
2360
|
+
const existingBoundSid = findBoundSessionForProfile(configDir, activeName, (sid) => /^[0-9a-f-]{36}$/i.test(sid));
|
|
2361
|
+
if (existingBoundSid) {
|
|
2362
|
+
runtimeSession = { sessionId: existingBoundSid, runtime: "antigravity" };
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
1958
2365
|
acquireAgentLock({
|
|
1959
2366
|
lockDir,
|
|
1960
2367
|
agentId: AGENT_ID,
|
|
1961
|
-
profileName:
|
|
2368
|
+
profileName: activeName,
|
|
1962
2369
|
sessionId: runtimeSession?.sessionId ?? null,
|
|
1963
2370
|
runtime: runtimeSession?.runtime ?? "mcp"
|
|
1964
2371
|
});
|
|
1965
|
-
if (runtimeSession?.sessionId &&
|
|
1966
|
-
|
|
1967
|
-
if (activeName)
|
|
1968
|
-
saveSessionBind(configDir, runtimeSession.sessionId, activeName);
|
|
2372
|
+
if (runtimeSession?.sessionId && activeName) {
|
|
2373
|
+
saveSessionBind(configDir, runtimeSession.sessionId, activeName);
|
|
1969
2374
|
}
|
|
1970
2375
|
}
|
|
1971
2376
|
var identityGateMessage = "";
|
|
1972
|
-
var identityGuardFile =
|
|
2377
|
+
var identityGuardFile = join6(configDir, IDENTITY_GUARD_FILENAME);
|
|
1973
2378
|
function persistGuardRecord(rec) {
|
|
1974
2379
|
try {
|
|
1975
|
-
|
|
2380
|
+
mkdirSync3(configDir, { recursive: true });
|
|
1976
2381
|
safeWriteProfile2(identityGuardFile, rec);
|
|
1977
2382
|
} catch {}
|
|
1978
2383
|
}
|
|
@@ -1988,7 +2393,7 @@ function confirmLiveIdentityTrusted() {
|
|
|
1988
2393
|
}
|
|
1989
2394
|
var guardRecord = (() => {
|
|
1990
2395
|
try {
|
|
1991
|
-
return parseGuardRecord(
|
|
2396
|
+
return parseGuardRecord(readFileSync7(identityGuardFile, "utf-8"));
|
|
1992
2397
|
} catch {
|
|
1993
2398
|
return emptyGuardRecord();
|
|
1994
2399
|
}
|
|
@@ -2055,29 +2460,38 @@ var ws = null;
|
|
|
2055
2460
|
var TYPING_HEARTBEAT_MS = 2000;
|
|
2056
2461
|
var TYPING_HEARTBEAT_MAX_MS = 120000;
|
|
2057
2462
|
var typingHeartbeats = new Map;
|
|
2058
|
-
function
|
|
2059
|
-
|
|
2463
|
+
function typingHeartbeatKey(channelId, agentId = AGENT_ID) {
|
|
2464
|
+
return `${agentId || "default"}:${channelId}`;
|
|
2465
|
+
}
|
|
2466
|
+
function sendTypingFrame(channelId, slot = activeSlot) {
|
|
2467
|
+
const targetWs = slot ? slot.ws : ws;
|
|
2468
|
+
const senderId = slot ? slot.agentId : AGENT_ID;
|
|
2469
|
+
if (targetWs && targetWs.readyState === WebSocket.OPEN && senderId) {
|
|
2060
2470
|
try {
|
|
2061
|
-
|
|
2471
|
+
targetWs.send(JSON.stringify({ type: "typing", channel_id: channelId, sender_id: senderId, cross_pod: true }));
|
|
2062
2472
|
} catch {}
|
|
2063
2473
|
}
|
|
2064
2474
|
}
|
|
2065
|
-
function startTypingHeartbeat(channelId) {
|
|
2475
|
+
function startTypingHeartbeat(channelId, slot = activeSlot) {
|
|
2066
2476
|
if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0")
|
|
2067
2477
|
return;
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
const
|
|
2072
|
-
|
|
2073
|
-
}
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2478
|
+
const agentId = slot ? slot.agentId : AGENT_ID;
|
|
2479
|
+
stopTypingHeartbeat(channelId, slot);
|
|
2480
|
+
sendTypingFrame(channelId, slot);
|
|
2481
|
+
const interval = setInterval(() => sendTypingFrame(channelId, slot), TYPING_HEARTBEAT_MS);
|
|
2482
|
+
const cap = setTimeout(() => stopTypingHeartbeat(channelId, slot), TYPING_HEARTBEAT_MAX_MS);
|
|
2483
|
+
typingHeartbeats.set(typingHeartbeatKey(channelId, agentId), { interval, cap });
|
|
2484
|
+
}
|
|
2485
|
+
function stopTypingHeartbeat(channelId, slot = activeSlot) {
|
|
2486
|
+
const agentId = slot ? slot.agentId : AGENT_ID;
|
|
2487
|
+
for (const key of [typingHeartbeatKey(channelId, agentId), channelId]) {
|
|
2488
|
+
const h = typingHeartbeats.get(key);
|
|
2489
|
+
if (!h)
|
|
2490
|
+
continue;
|
|
2491
|
+
clearInterval(h.interval);
|
|
2492
|
+
clearTimeout(h.cap);
|
|
2493
|
+
typingHeartbeats.delete(key);
|
|
2494
|
+
}
|
|
2081
2495
|
}
|
|
2082
2496
|
function stopAllTypingHeartbeats() {
|
|
2083
2497
|
for (const h of typingHeartbeats.values()) {
|
|
@@ -2089,6 +2503,8 @@ function stopAllTypingHeartbeats() {
|
|
|
2089
2503
|
var sessionId = null;
|
|
2090
2504
|
var shuttingDown = false;
|
|
2091
2505
|
var transport = null;
|
|
2506
|
+
var profileSlots = new Map;
|
|
2507
|
+
var activeSlot = null;
|
|
2092
2508
|
var debugLogsEnabled = /^(1|true|yes|debug)$/i.test(process.env.AGENTSCHAT_MCP_DEBUG || process.env.AGENTCHAT_DEBUG || "");
|
|
2093
2509
|
var defaultLogRateMs = Math.max(1000, Number(process.env.AGENTSCHAT_MCP_LOG_RATE_MS || 60000));
|
|
2094
2510
|
var rateLimitedLogState = new Map;
|
|
@@ -2286,10 +2702,10 @@ var TOOL_GROUPS = [
|
|
|
2286
2702
|
},
|
|
2287
2703
|
{
|
|
2288
2704
|
name: "media",
|
|
2289
|
-
summary: "Send images and voice/audio clips into channels (upload a local file or attach an already-hosted url).",
|
|
2705
|
+
summary: "Send images, videos, and voice/audio clips into channels (upload a local file or attach an already-hosted url).",
|
|
2290
2706
|
tags: ["chat", "media"],
|
|
2291
|
-
estimated_tokens:
|
|
2292
|
-
tools: ["send_image", "send_voice", "set_voice", "list_voices", "transcribe"]
|
|
2707
|
+
estimated_tokens: 750,
|
|
2708
|
+
tools: ["send_image", "send_video", "send_voice", "set_voice", "list_voices", "transcribe"]
|
|
2293
2709
|
}
|
|
2294
2710
|
];
|
|
2295
2711
|
var TOOL_NAME_TO_GROUP = new Map;
|
|
@@ -2356,6 +2772,24 @@ var ALL_TOOL_DEFS = [
|
|
|
2356
2772
|
required: ["chat_id"]
|
|
2357
2773
|
}
|
|
2358
2774
|
},
|
|
2775
|
+
{
|
|
2776
|
+
name: "send_video",
|
|
2777
|
+
description: "Send a video clip into a channel. Give a local file `path` (mp4/mov/webm/m4v; the plugin uploads it for you) OR an already-hosted `url` (/api/file/uploads/*). `caption` becomes the message text.",
|
|
2778
|
+
inputSchema: {
|
|
2779
|
+
type: "object",
|
|
2780
|
+
properties: {
|
|
2781
|
+
chat_id: { type: "string", description: "Channel id to post into" },
|
|
2782
|
+
path: { type: "string", description: "Local video file to upload (mp4/mov/webm/m4v; \u226450MB). Provide this OR url." },
|
|
2783
|
+
url: { type: "string", description: "Already-uploaded proxy url (/api/file/uploads/<name>). Provide this OR path." },
|
|
2784
|
+
caption: { type: "string", description: "Optional text shown alongside the video" },
|
|
2785
|
+
width: { type: "number", description: "Video width in px (optional)" },
|
|
2786
|
+
height: { type: "number", description: "Video height in px (optional)" },
|
|
2787
|
+
duration_ms: { type: "number", description: "Video duration in milliseconds (optional)" },
|
|
2788
|
+
transcript: { type: "string", description: "Optional transcript or summary of the video" }
|
|
2789
|
+
},
|
|
2790
|
+
required: ["chat_id"]
|
|
2791
|
+
}
|
|
2792
|
+
},
|
|
2359
2793
|
{
|
|
2360
2794
|
name: "send_voice",
|
|
2361
2795
|
description: 'Send a voice/audio clip into a channel. Provide exactly one of: a local file `path` (the plugin uploads it), an already-hosted `url`, or `text` to speak (the server runs text-to-speech and sends the resulting audio \u2014 this is the natural way for an agent to "talk"; optional `voice` overrides your configured voice). Optional `caption`, `duration_ms`, `transcript`.',
|
|
@@ -3195,9 +3629,13 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: annotateT
|
|
|
3195
3629
|
var TOOL_INPUT_SCHEMAS = new Map(ALL_TOOL_DEFS.map((t) => [t.name, t.inputSchema]));
|
|
3196
3630
|
var MEMBER_CACHE_TTL_MS = 5 * 60000;
|
|
3197
3631
|
var memberCache = new Map;
|
|
3632
|
+
function memberCacheKey(chatId) {
|
|
3633
|
+
return `${AGENT_ID || "anon"}:${chatId}`;
|
|
3634
|
+
}
|
|
3198
3635
|
async function fetchChannelMembers(chatId) {
|
|
3199
3636
|
const now = Date.now();
|
|
3200
|
-
const
|
|
3637
|
+
const key = memberCacheKey(chatId);
|
|
3638
|
+
const hit = memberCache.get(key);
|
|
3201
3639
|
if (hit && now - hit.at < MEMBER_CACHE_TTL_MS)
|
|
3202
3640
|
return hit.members;
|
|
3203
3641
|
try {
|
|
@@ -3208,12 +3646,32 @@ async function fetchChannelMembers(chatId) {
|
|
|
3208
3646
|
return hit?.members || [];
|
|
3209
3647
|
const body = await r.json();
|
|
3210
3648
|
const members = Array.isArray(body?.members) ? body.members : [];
|
|
3211
|
-
|
|
3649
|
+
const sameOwnerDirect = body?.same_owner_direct === true;
|
|
3650
|
+
memberCache.set(key, { at: now, members, sameOwnerDirect });
|
|
3212
3651
|
return members;
|
|
3213
3652
|
} catch {
|
|
3214
3653
|
return hit?.members || [];
|
|
3215
3654
|
}
|
|
3216
3655
|
}
|
|
3656
|
+
async function isSameOwnerDirectChannel(chatId) {
|
|
3657
|
+
const now = Date.now();
|
|
3658
|
+
const key = memberCacheKey(chatId);
|
|
3659
|
+
const hit = memberCache.get(key);
|
|
3660
|
+
if (hit && now - hit.at < MEMBER_CACHE_TTL_MS && typeof hit.sameOwnerDirect === "boolean") {
|
|
3661
|
+
return hit.sameOwnerDirect;
|
|
3662
|
+
}
|
|
3663
|
+
await fetchChannelMembers(chatId);
|
|
3664
|
+
return memberCache.get(key)?.sameOwnerDirect === true;
|
|
3665
|
+
}
|
|
3666
|
+
async function redactOutboundForChannel(chatId, text) {
|
|
3667
|
+
if (!text)
|
|
3668
|
+
return text;
|
|
3669
|
+
if (/ac_[A-Za-z0-9_-]{16,}/.test(text)) {
|
|
3670
|
+
const preserveAcKeys = await isSameOwnerDirectChannel(chatId);
|
|
3671
|
+
return redactSecrets(text, { preserveAcKeys });
|
|
3672
|
+
}
|
|
3673
|
+
return redactSecrets(text);
|
|
3674
|
+
}
|
|
3217
3675
|
async function resolveBareMentions(chatId, text) {
|
|
3218
3676
|
if (!text || !text.includes("@"))
|
|
3219
3677
|
return text;
|
|
@@ -3298,25 +3756,32 @@ var MEDIA_MIME_BY_EXT = {
|
|
|
3298
3756
|
heic: "image/heic",
|
|
3299
3757
|
heif: "image/heif",
|
|
3300
3758
|
avif: "image/avif",
|
|
3759
|
+
mp4: "video/mp4",
|
|
3760
|
+
mov: "video/quicktime",
|
|
3761
|
+
m4v: "video/x-m4v",
|
|
3762
|
+
webm: "video/webm",
|
|
3763
|
+
"3gp": "video/3gpp",
|
|
3301
3764
|
m4a: "audio/mp4",
|
|
3302
|
-
mp4: "audio/mp4",
|
|
3303
3765
|
aac: "audio/aac",
|
|
3304
3766
|
mp3: "audio/mpeg",
|
|
3305
3767
|
wav: "audio/wav",
|
|
3306
3768
|
weba: "audio/webm",
|
|
3307
|
-
webm: "audio/webm",
|
|
3308
3769
|
ogg: "audio/ogg",
|
|
3309
3770
|
oga: "audio/ogg"
|
|
3310
3771
|
};
|
|
3311
|
-
function mimeFromPath(p) {
|
|
3772
|
+
function mimeFromPath(p, kindHint) {
|
|
3312
3773
|
const ext = p.split(".").pop()?.toLowerCase() ?? "";
|
|
3774
|
+
if (kindHint === "audio" && ext === "mp4")
|
|
3775
|
+
return "audio/mp4";
|
|
3776
|
+
if (kindHint === "audio" && ext === "webm")
|
|
3777
|
+
return "audio/webm";
|
|
3313
3778
|
return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
|
|
3314
3779
|
}
|
|
3315
|
-
async function uploadLocalFile(path) {
|
|
3316
|
-
if (!
|
|
3780
|
+
async function uploadLocalFile(path, kindHint) {
|
|
3781
|
+
if (!existsSync7(path))
|
|
3317
3782
|
throw new Error(`file not found: ${path}`);
|
|
3318
|
-
const mime = mimeFromPath(path);
|
|
3319
|
-
const buf =
|
|
3783
|
+
const mime = mimeFromPath(path, kindHint);
|
|
3784
|
+
const buf = readFileSync7(path);
|
|
3320
3785
|
const name = path.split("/").pop() || "upload";
|
|
3321
3786
|
const form = new FormData;
|
|
3322
3787
|
form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
|
|
@@ -3377,13 +3842,13 @@ async function sendMediaMessage(kind, args) {
|
|
|
3377
3842
|
mime = d.mime || "audio/mpeg";
|
|
3378
3843
|
ttsDuration = typeof d.duration_ms === "number" ? d.duration_ms : undefined;
|
|
3379
3844
|
} else if (path) {
|
|
3380
|
-
const up = await uploadLocalFile(path);
|
|
3845
|
+
const up = await uploadLocalFile(path, kind);
|
|
3381
3846
|
finalUrl = up.url;
|
|
3382
3847
|
mime = up.mime;
|
|
3383
3848
|
size = up.size;
|
|
3384
3849
|
} else {
|
|
3385
3850
|
finalUrl = url;
|
|
3386
|
-
mime = mimeFromPath(finalUrl);
|
|
3851
|
+
mime = mimeFromPath(finalUrl, kind);
|
|
3387
3852
|
}
|
|
3388
3853
|
const attachment = { type: kind, url: finalUrl };
|
|
3389
3854
|
if (mime && mime !== "application/octet-stream")
|
|
@@ -3395,6 +3860,15 @@ async function sendMediaMessage(kind, args) {
|
|
|
3395
3860
|
attachment.width = args.width;
|
|
3396
3861
|
if (typeof args.height === "number")
|
|
3397
3862
|
attachment.height = args.height;
|
|
3863
|
+
} else if (kind === "video") {
|
|
3864
|
+
if (typeof args.width === "number")
|
|
3865
|
+
attachment.width = args.width;
|
|
3866
|
+
if (typeof args.height === "number")
|
|
3867
|
+
attachment.height = args.height;
|
|
3868
|
+
if (typeof args.duration_ms === "number")
|
|
3869
|
+
attachment.duration_ms = args.duration_ms;
|
|
3870
|
+
if (typeof args.transcript === "string" && args.transcript)
|
|
3871
|
+
attachment.transcript = args.transcript;
|
|
3398
3872
|
} else {
|
|
3399
3873
|
const dur = typeof args.duration_ms === "number" ? args.duration_ms : ttsDuration;
|
|
3400
3874
|
if (dur != null)
|
|
@@ -3404,7 +3878,7 @@ async function sendMediaMessage(kind, args) {
|
|
|
3404
3878
|
else if (text)
|
|
3405
3879
|
attachment.transcript = text;
|
|
3406
3880
|
}
|
|
3407
|
-
const content = caption ?
|
|
3881
|
+
const content = caption ? await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, caption)) : "";
|
|
3408
3882
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages`, {
|
|
3409
3883
|
method: "POST",
|
|
3410
3884
|
headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
|
|
@@ -3420,6 +3894,7 @@ async function sendMediaMessage(kind, args) {
|
|
|
3420
3894
|
}
|
|
3421
3895
|
}
|
|
3422
3896
|
HANDLERS.set("send_image", (args) => sendMediaMessage("image", args));
|
|
3897
|
+
HANDLERS.set("send_video", (args) => sendMediaMessage("video", args));
|
|
3423
3898
|
HANDLERS.set("send_voice", (args) => sendMediaMessage("audio", args));
|
|
3424
3899
|
HANDLERS.set("list_voices", async (args) => {
|
|
3425
3900
|
const { language } = args || {};
|
|
@@ -3503,10 +3978,10 @@ HANDLERS.set("transcribe", async (args) => {
|
|
|
3503
3978
|
});
|
|
3504
3979
|
function loadGrokBinds() {
|
|
3505
3980
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
3506
|
-
if (!
|
|
3981
|
+
if (!existsSync7(bindPath))
|
|
3507
3982
|
return {};
|
|
3508
3983
|
try {
|
|
3509
|
-
return parseGrokBindsText(
|
|
3984
|
+
return parseGrokBindsText(readFileSync7(bindPath, "utf-8")).binds;
|
|
3510
3985
|
} catch {
|
|
3511
3986
|
return {};
|
|
3512
3987
|
}
|
|
@@ -3520,47 +3995,208 @@ function currentGrokBindApplicability(binds) {
|
|
|
3520
3995
|
binds
|
|
3521
3996
|
});
|
|
3522
3997
|
}
|
|
3523
|
-
|
|
3524
|
-
|
|
3525
|
-
if (
|
|
3526
|
-
|
|
3998
|
+
var cursorFlushIntervalMs = Math.max(500, Number(process.env.AGENTSCHAT_MCP_CURSOR_FLUSH_MS || 5000));
|
|
3999
|
+
function flushSlotLastSeenMessageTs(slot) {
|
|
4000
|
+
if (!slot.cursorState.dirty)
|
|
4001
|
+
return;
|
|
4002
|
+
if (slot.lastSeenMessageTsTimer) {
|
|
4003
|
+
clearTimeout(slot.lastSeenMessageTsTimer);
|
|
4004
|
+
slot.lastSeenMessageTsTimer = null;
|
|
4005
|
+
}
|
|
4006
|
+
flushCursor(slot.cursorState, () => persistCursor(slot.lastSeenMessageTsFile, slot.lastSeenMessageTs, safeStderrWrite));
|
|
4007
|
+
}
|
|
4008
|
+
function scheduleSlotLastSeenMessageTsSave(slot) {
|
|
4009
|
+
slot.cursorState.dirty = true;
|
|
4010
|
+
if (slot.lastSeenMessageTsTimer)
|
|
4011
|
+
return;
|
|
4012
|
+
slot.lastSeenMessageTsTimer = setTimeout(() => {
|
|
4013
|
+
slot.lastSeenMessageTsTimer = null;
|
|
4014
|
+
flushSlotLastSeenMessageTs(slot);
|
|
4015
|
+
}, cursorFlushIntervalMs);
|
|
4016
|
+
slot.lastSeenMessageTsTimer.unref?.();
|
|
4017
|
+
}
|
|
4018
|
+
function createProfileSlot(opts) {
|
|
4019
|
+
const lastSeenFile = join6(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
|
|
4020
|
+
const slot = {
|
|
4021
|
+
profileName: opts.profileName,
|
|
4022
|
+
profileFile: opts.profileFile,
|
|
4023
|
+
profile: opts.profile,
|
|
4024
|
+
agentId: opts.agentId,
|
|
4025
|
+
token: opts.token,
|
|
4026
|
+
capabilities: opts.capabilities,
|
|
4027
|
+
ws: null,
|
|
4028
|
+
sessionId: null,
|
|
4029
|
+
runtimeSession: opts.runtimeSession,
|
|
4030
|
+
knownChannels: new Set,
|
|
4031
|
+
wsReconnectAttempt: 0,
|
|
4032
|
+
reconnectTimer: null,
|
|
4033
|
+
backfillTimer: null,
|
|
4034
|
+
heartbeat: null,
|
|
4035
|
+
lastSeenMessageTsFile: lastSeenFile,
|
|
4036
|
+
lastSeenMessageTs: loadCursor(lastSeenFile, safeStderrWrite),
|
|
4037
|
+
cursorState: { dirty: false },
|
|
4038
|
+
lastSeenMessageTsTimer: null,
|
|
4039
|
+
messageDedup: new MessageDedup,
|
|
4040
|
+
handleWSMessage: null
|
|
4041
|
+
};
|
|
4042
|
+
slot.heartbeat = new HeartbeatMonitor({
|
|
4043
|
+
sendPing: () => {
|
|
4044
|
+
try {
|
|
4045
|
+
slot.ws?.send(JSON.stringify({ type: "ping", timestamp: new Date().toISOString() }));
|
|
4046
|
+
} catch {}
|
|
4047
|
+
},
|
|
4048
|
+
reconnect: () => {
|
|
4049
|
+
process.stderr.write(`[agentchat] Heartbeat timeout, forcing reconnect
|
|
4050
|
+
`);
|
|
4051
|
+
if (slot.ws) {
|
|
4052
|
+
slot.ws.onclose = null;
|
|
4053
|
+
try {
|
|
4054
|
+
slot.ws.close();
|
|
4055
|
+
} catch {}
|
|
4056
|
+
}
|
|
4057
|
+
slot.ws = null;
|
|
4058
|
+
slot.sessionId = null;
|
|
4059
|
+
if (activeSlot === slot) {
|
|
4060
|
+
ws = null;
|
|
4061
|
+
sessionId = null;
|
|
4062
|
+
}
|
|
4063
|
+
slot.wsReconnectAttempt = 0;
|
|
4064
|
+
scheduleReconnect(500, slot);
|
|
4065
|
+
},
|
|
4066
|
+
getReadyState: () => slot.ws?.readyState ?? WS_CLOSED
|
|
4067
|
+
}, 15000, 45000, 30000);
|
|
4068
|
+
return slot;
|
|
4069
|
+
}
|
|
4070
|
+
function activateSlot(slot, callerSession) {
|
|
4071
|
+
if (callerSession) {
|
|
4072
|
+
slot.runtimeSession = {
|
|
4073
|
+
...callerSession,
|
|
4074
|
+
...callerSession.workspacePath || slot.runtimeSession?.workspacePath ? { workspacePath: callerSession.workspacePath ?? slot.runtimeSession?.workspacePath } : {}
|
|
4075
|
+
};
|
|
4076
|
+
}
|
|
4077
|
+
activeSlot = slot;
|
|
4078
|
+
AGENT_ID = slot.agentId;
|
|
4079
|
+
TOKEN = slot.token;
|
|
4080
|
+
CAPABILITIES = slot.capabilities;
|
|
4081
|
+
profile = slot.profile;
|
|
4082
|
+
activeProfileFile = slot.profileFile;
|
|
4083
|
+
anonymousMode = false;
|
|
4084
|
+
ws = slot.ws;
|
|
4085
|
+
sessionId = slot.sessionId;
|
|
4086
|
+
runtimeSession = slot.runtimeSession;
|
|
4087
|
+
}
|
|
4088
|
+
function setAnonymousCallerState(callerSession) {
|
|
4089
|
+
activeSlot = null;
|
|
4090
|
+
AGENT_ID = "";
|
|
4091
|
+
TOKEN = "";
|
|
4092
|
+
profile = {};
|
|
4093
|
+
activeProfileFile = null;
|
|
4094
|
+
anonymousMode = true;
|
|
4095
|
+
ws = null;
|
|
4096
|
+
sessionId = null;
|
|
4097
|
+
if (callerSession !== undefined) {
|
|
4098
|
+
runtimeSession = callerSession;
|
|
3527
4099
|
}
|
|
3528
|
-
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
|
|
3532
|
-
|
|
4100
|
+
}
|
|
4101
|
+
function teardownSlot(slot, opts) {
|
|
4102
|
+
try {
|
|
4103
|
+
flushSlotLastSeenMessageTs(slot);
|
|
4104
|
+
} catch {}
|
|
4105
|
+
try {
|
|
4106
|
+
slot.heartbeat.stop();
|
|
4107
|
+
} catch {}
|
|
4108
|
+
if (slot.backfillTimer) {
|
|
4109
|
+
clearTimeout(slot.backfillTimer);
|
|
4110
|
+
slot.backfillTimer = null;
|
|
3533
4111
|
}
|
|
3534
|
-
if (reconnectTimer) {
|
|
3535
|
-
clearTimeout(reconnectTimer);
|
|
3536
|
-
reconnectTimer = null;
|
|
4112
|
+
if (slot.reconnectTimer) {
|
|
4113
|
+
clearTimeout(slot.reconnectTimer);
|
|
4114
|
+
slot.reconnectTimer = null;
|
|
3537
4115
|
}
|
|
3538
|
-
if (ws) {
|
|
3539
|
-
ws.onclose = null;
|
|
4116
|
+
if (slot.ws) {
|
|
4117
|
+
slot.ws.onclose = null;
|
|
3540
4118
|
try {
|
|
3541
|
-
ws.close();
|
|
4119
|
+
slot.ws.close();
|
|
3542
4120
|
} catch {}
|
|
4121
|
+
slot.ws = null;
|
|
4122
|
+
}
|
|
4123
|
+
slot.sessionId = null;
|
|
4124
|
+
if (opts?.releaseLock !== false && slot.agentId && !toolOnlyMode) {
|
|
4125
|
+
const boundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName) || null;
|
|
4126
|
+
releaseAgentLock({ lockDir, agentId: slot.agentId, currentSessionId: boundSid });
|
|
4127
|
+
}
|
|
4128
|
+
profileSlots.delete(slot.profileName);
|
|
4129
|
+
if (activeSlot === slot) {
|
|
4130
|
+
activeSlot = null;
|
|
3543
4131
|
ws = null;
|
|
4132
|
+
sessionId = null;
|
|
3544
4133
|
}
|
|
3545
|
-
|
|
3546
|
-
|
|
3547
|
-
|
|
3548
|
-
|
|
3549
|
-
|
|
3550
|
-
|
|
3551
|
-
|
|
4134
|
+
}
|
|
4135
|
+
if (!anonymousMode && AGENT_ID) {
|
|
4136
|
+
const bootProfName = profileNameFromPath(activeProfileFile) ?? declaredName ?? AGENT_ID;
|
|
4137
|
+
const bootSlot = createProfileSlot({
|
|
4138
|
+
profileName: bootProfName,
|
|
4139
|
+
profileFile: activeProfileFile,
|
|
4140
|
+
profile,
|
|
4141
|
+
agentId: AGENT_ID,
|
|
4142
|
+
token: TOKEN,
|
|
4143
|
+
capabilities: CAPABILITIES,
|
|
4144
|
+
runtimeSession
|
|
4145
|
+
});
|
|
4146
|
+
profileSlots.set(bootProfName, bootSlot);
|
|
4147
|
+
activateSlot(bootSlot, runtimeSession);
|
|
4148
|
+
}
|
|
4149
|
+
function applyIdentityFromProfile(newProfile, targetFile, bindSessionId) {
|
|
4150
|
+
validateIdentityProfile(newProfile, targetFile);
|
|
4151
|
+
const targetProfName = profileNameFromPath(targetFile) || newProfile.display_name || newProfile.agent_id;
|
|
4152
|
+
let targetSession = runtimeSession ? { ...runtimeSession } : null;
|
|
3552
4153
|
if (bindSessionId && bindSessionId.trim()) {
|
|
3553
|
-
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
4154
|
+
const cleanSid = bindSessionId.trim();
|
|
4155
|
+
const isAgyEnv = process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL) || Boolean(process.env.AGENTSCHAT_AGY_BRAIN_DIR) || Boolean(discoverAntigravityHost());
|
|
4156
|
+
targetSession = {
|
|
4157
|
+
sessionId: cleanSid,
|
|
4158
|
+
runtime: targetSession?.runtime ?? (isAgyEnv && /^[0-9a-f-]{36}$/i.test(cleanSid) ? "antigravity" : cleanSid.startsWith("sess_") ? "zcode" : cleanSid.startsWith("session-") ? "dsh" : "custom"),
|
|
4159
|
+
...targetSession?.workspacePath ? { workspacePath: targetSession.workspacePath } : {}
|
|
3557
4160
|
};
|
|
3558
|
-
} else
|
|
3559
|
-
const
|
|
3560
|
-
if (
|
|
3561
|
-
|
|
4161
|
+
} else {
|
|
4162
|
+
const existingBoundSid = findBoundSessionForProfile(configDir, targetProfName);
|
|
4163
|
+
if (existingBoundSid && !targetSession?.sessionId) {
|
|
4164
|
+
targetSession = {
|
|
4165
|
+
sessionId: existingBoundSid,
|
|
4166
|
+
runtime: /^[0-9a-f-]{36}$/i.test(existingBoundSid) ? "antigravity" : existingBoundSid.startsWith("sess_") ? "zcode" : existingBoundSid.startsWith("session-") ? "dsh" : "custom"
|
|
4167
|
+
};
|
|
4168
|
+
} else if (!targetSession?.sessionId) {
|
|
4169
|
+
const agyHost = discoverAntigravityHost();
|
|
4170
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
4171
|
+
targetSession = { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
|
|
4172
|
+
}
|
|
4173
|
+
}
|
|
4174
|
+
}
|
|
4175
|
+
for (const existingSlot of [...profileSlots.values()]) {
|
|
4176
|
+
if (existingSlot.profileName === targetProfName || existingSlot.agentId === newProfile.agent_id) {
|
|
4177
|
+
teardownSlot(existingSlot, { releaseLock: existingSlot.agentId !== newProfile.agent_id });
|
|
4178
|
+
continue;
|
|
4179
|
+
}
|
|
4180
|
+
const existingSid = existingSlot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, existingSlot.profileName) || null;
|
|
4181
|
+
if (targetSession?.sessionId) {
|
|
4182
|
+
if (existingSid === targetSession.sessionId) {
|
|
4183
|
+
teardownSlot(existingSlot, { releaseLock: true });
|
|
4184
|
+
}
|
|
4185
|
+
} else if (!existingSid && profileSlots.size === 1) {
|
|
4186
|
+
teardownSlot(existingSlot, { releaseLock: true });
|
|
3562
4187
|
}
|
|
3563
4188
|
}
|
|
4189
|
+
const newSlot = createProfileSlot({
|
|
4190
|
+
profileName: targetProfName,
|
|
4191
|
+
profileFile: targetFile,
|
|
4192
|
+
profile: newProfile,
|
|
4193
|
+
agentId: newProfile.agent_id,
|
|
4194
|
+
token: newProfile.token,
|
|
4195
|
+
capabilities: newProfile.capabilities || ["claude-code", "coding", "chat"],
|
|
4196
|
+
runtimeSession: targetSession
|
|
4197
|
+
});
|
|
4198
|
+
profileSlots.set(targetProfName, newSlot);
|
|
4199
|
+
activateSlot(newSlot, targetSession);
|
|
3564
4200
|
if (!toolOnlyMode) {
|
|
3565
4201
|
acquireAgentLock({
|
|
3566
4202
|
lockDir,
|
|
@@ -3577,44 +4213,28 @@ function applyIdentityFromProfile(newProfile, targetFile, bindSessionId) {
|
|
|
3577
4213
|
}
|
|
3578
4214
|
guardRecord = advanceGuardRecord(guardRecord, { agentId: AGENT_ID, source: "switch_profile", ...profileNameFromPath(targetFile) ? { declaredName: profileNameFromPath(targetFile) } : {} }, new Date().toISOString(), true);
|
|
3579
4215
|
persistGuardRecord(guardRecord);
|
|
3580
|
-
wsReconnectAttempt = 0;
|
|
3581
4216
|
if (!toolOnlyMode) {
|
|
3582
|
-
heartbeat.start();
|
|
3583
|
-
connectWS();
|
|
4217
|
+
newSlot.heartbeat.start();
|
|
4218
|
+
connectWS(newSlot);
|
|
3584
4219
|
}
|
|
3585
4220
|
}
|
|
3586
4221
|
function disconnectCurrentProfile(opts) {
|
|
3587
|
-
const
|
|
3588
|
-
const
|
|
3589
|
-
|
|
3590
|
-
|
|
3591
|
-
if (
|
|
3592
|
-
|
|
3593
|
-
|
|
3594
|
-
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
}
|
|
3599
|
-
if (ws) {
|
|
3600
|
-
ws.onclose = null;
|
|
3601
|
-
try {
|
|
3602
|
-
ws.close();
|
|
3603
|
-
} catch {}
|
|
3604
|
-
ws = null;
|
|
3605
|
-
}
|
|
3606
|
-
if (prevAgentId) {
|
|
3607
|
-
releaseAgentLock({ lockDir, agentId: prevAgentId, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
4222
|
+
const slot = activeSlot;
|
|
4223
|
+
const prevAgentId = slot?.agentId || AGENT_ID;
|
|
4224
|
+
const prevProfileName = slot?.profileName || profileNameFromPath(activeProfileFile) || profile?.display_name || AGENT_ID || "(none)";
|
|
4225
|
+
const sidToRemove = slot?.runtimeSession?.sessionId || runtimeSession?.sessionId || null;
|
|
4226
|
+
if (slot) {
|
|
4227
|
+
teardownSlot(slot, { releaseLock: true });
|
|
4228
|
+
} else {
|
|
4229
|
+
stopAllTypingHeartbeats();
|
|
4230
|
+
if (prevAgentId) {
|
|
4231
|
+
releaseAgentLock({ lockDir, agentId: prevAgentId, currentSessionId: sidToRemove });
|
|
4232
|
+
}
|
|
3608
4233
|
}
|
|
3609
|
-
if (!opts?.keepBinding &&
|
|
3610
|
-
removeSessionBind(configDir,
|
|
4234
|
+
if (!opts?.keepBinding && sidToRemove) {
|
|
4235
|
+
removeSessionBind(configDir, sidToRemove);
|
|
3611
4236
|
}
|
|
3612
|
-
|
|
3613
|
-
AGENT_ID = "";
|
|
3614
|
-
TOKEN = "";
|
|
3615
|
-
profile = {};
|
|
3616
|
-
activeProfileFile = null;
|
|
3617
|
-
anonymousMode = true;
|
|
4237
|
+
setAnonymousCallerState(runtimeSession);
|
|
3618
4238
|
return { prevAgentId, prevProfileName };
|
|
3619
4239
|
}
|
|
3620
4240
|
function formatProfileList() {
|
|
@@ -3624,13 +4244,15 @@ function formatProfileList() {
|
|
|
3624
4244
|
const lines = profileEntries.map((entry) => {
|
|
3625
4245
|
let entryAgentId = "";
|
|
3626
4246
|
try {
|
|
3627
|
-
const parsed = JSON.parse(
|
|
4247
|
+
const parsed = JSON.parse(readFileSync7(entry.path, "utf-8"));
|
|
3628
4248
|
if (typeof parsed?.agent_id === "string")
|
|
3629
4249
|
entryAgentId = parsed.agent_id;
|
|
3630
4250
|
} catch {}
|
|
3631
4251
|
const isCurrent = current && (entry.name === current || entryAgentId === current) || currentProfileName && entry.name === currentProfileName;
|
|
3632
4252
|
const lock = entryAgentId ? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid }) : { locked: false };
|
|
3633
|
-
const
|
|
4253
|
+
const slot = profileSlots.get(entry.name);
|
|
4254
|
+
const boundSid = findBoundSessionForProfile(configDir, entry.name);
|
|
4255
|
+
const statusSuffix = lock.locked ? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]` : slot && slot.ws?.readyState === WebSocket.OPEN ? ` [online${boundSid ? ` session=${boundSid}` : ""}]` : "";
|
|
3634
4256
|
return `${isCurrent ? "\u2192 " : " "}${entry.name}${statusSuffix}`;
|
|
3635
4257
|
});
|
|
3636
4258
|
return `Current: ${current || "(anonymous / disconnected)"}
|
|
@@ -3672,10 +4294,10 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
|
|
|
3672
4294
|
};
|
|
3673
4295
|
const targetFile = nameToPath(cleanName);
|
|
3674
4296
|
validateIdentityProfile(newProfile, targetFile);
|
|
3675
|
-
|
|
4297
|
+
mkdirSync3(dirname(targetFile), { recursive: true });
|
|
3676
4298
|
safeWriteProfile2(targetFile, newProfile);
|
|
3677
4299
|
const defaultProfileFile = nameToPath("profile");
|
|
3678
|
-
if (!
|
|
4300
|
+
if (!existsSync7(defaultProfileFile)) {
|
|
3679
4301
|
safeWriteProfile2(defaultProfileFile, newProfile);
|
|
3680
4302
|
}
|
|
3681
4303
|
applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
|
|
@@ -3732,7 +4354,7 @@ async function handleProfileSwitchOrConnect(args) {
|
|
|
3732
4354
|
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
3733
4355
|
}
|
|
3734
4356
|
const targetFile = nameToPath(profile_name);
|
|
3735
|
-
if (!
|
|
4357
|
+
if (!existsSync7(targetFile)) {
|
|
3736
4358
|
if (register) {
|
|
3737
4359
|
return await registerAndConnectProfile(profile_name, explicitSessionId);
|
|
3738
4360
|
}
|
|
@@ -3796,7 +4418,7 @@ function ensureGrokBoundIdentity() {
|
|
|
3796
4418
|
if (!boundName)
|
|
3797
4419
|
return;
|
|
3798
4420
|
const boundPath = nameToPath(boundName);
|
|
3799
|
-
if (!
|
|
4421
|
+
if (!existsSync7(boundPath))
|
|
3800
4422
|
return;
|
|
3801
4423
|
let boundProfile;
|
|
3802
4424
|
try {
|
|
@@ -3817,43 +4439,154 @@ function ensureGrokBoundIdentity() {
|
|
|
3817
4439
|
`);
|
|
3818
4440
|
applyIdentityFromProfile(boundProfile, boundPath);
|
|
3819
4441
|
}
|
|
3820
|
-
|
|
4442
|
+
async function resolveCallerSessionForToolCall(toolName, toolArgs, rawMeta) {
|
|
4443
|
+
const explicitArgSid = typeof toolArgs?.conversation_id === "string" && toolArgs.conversation_id.trim() || typeof toolArgs?.session_id === "string" && toolArgs.session_id.trim() || "";
|
|
4444
|
+
if (explicitArgSid) {
|
|
4445
|
+
const isAgy = /^[0-9a-f-]{36}$/i.test(explicitArgSid) && (process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL) || Boolean(process.env.AGENTSCHAT_AGY_BRAIN_DIR) || Boolean(discoverAntigravityHost()));
|
|
4446
|
+
const runtime = isAgy ? "antigravity" : explicitArgSid.startsWith("sess_") ? "zcode" : explicitArgSid.startsWith("session-") ? "dsh" : runtimeSession?.runtime ?? "custom";
|
|
4447
|
+
return {
|
|
4448
|
+
session: {
|
|
4449
|
+
sessionId: explicitArgSid,
|
|
4450
|
+
runtime,
|
|
4451
|
+
...runtimeSession?.workspacePath ? { workspacePath: runtimeSession.workspacePath } : {}
|
|
4452
|
+
},
|
|
4453
|
+
isPerCallSession: true
|
|
4454
|
+
};
|
|
4455
|
+
}
|
|
4456
|
+
const hasExplicitMetaSession = Boolean(typeof rawMeta?.session_id === "string" && rawMeta.session_id.trim() || typeof rawMeta?.["com.zcode/request-context"]?.session_id === "string" && rawMeta["com.zcode/request-context"].session_id.trim());
|
|
4457
|
+
if (hasExplicitMetaSession) {
|
|
4458
|
+
return {
|
|
4459
|
+
session: detectRuntimeSession(process.env, rawMeta),
|
|
4460
|
+
isPerCallSession: true
|
|
4461
|
+
};
|
|
4462
|
+
}
|
|
4463
|
+
if (process.env.CLAUDE_CODE_SESSION_ID?.trim() || process.env.CLAUDE_SESSION_ID?.trim() || process.env.ZCODE_SESSION_ID?.trim() || process.env.ANTIGRAVITY_CONVERSATION_ID?.trim() || process.env.AGENTSCHAT_SESSION_ID?.trim() || process.env.AGENTCHAT_SESSION_ID?.trim()) {
|
|
4464
|
+
return {
|
|
4465
|
+
session: detectRuntimeSession(process.env, rawMeta),
|
|
4466
|
+
isPerCallSession: false
|
|
4467
|
+
};
|
|
4468
|
+
}
|
|
4469
|
+
if (process.env.AGENTSCHAT_AGY_BRAIN_DIR?.trim() || process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL) || Boolean(discoverAntigravityHost())) {
|
|
4470
|
+
const agyHost = discoverAntigravityHost();
|
|
4471
|
+
const agyCid = detectAntigravityCallerSession({
|
|
4472
|
+
toolName,
|
|
4473
|
+
args: toolArgs ?? null,
|
|
4474
|
+
openConversations: agyHost?.openConversations
|
|
4475
|
+
});
|
|
4476
|
+
if (agyCid) {
|
|
4477
|
+
return {
|
|
4478
|
+
session: { sessionId: agyCid, runtime: "antigravity" },
|
|
4479
|
+
isPerCallSession: true
|
|
4480
|
+
};
|
|
4481
|
+
}
|
|
4482
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
4483
|
+
return {
|
|
4484
|
+
session: { sessionId: agyHost.openConversations[0], runtime: "antigravity" },
|
|
4485
|
+
isPerCallSession: false
|
|
4486
|
+
};
|
|
4487
|
+
}
|
|
4488
|
+
}
|
|
4489
|
+
if (isDshHostProcess()) {
|
|
4490
|
+
const dshSid = await detectDshCallerSession();
|
|
4491
|
+
if (dshSid) {
|
|
4492
|
+
return {
|
|
4493
|
+
session: { sessionId: dshSid, runtime: "dsh" },
|
|
4494
|
+
isPerCallSession: true
|
|
4495
|
+
};
|
|
4496
|
+
}
|
|
4497
|
+
if (!dshRouteWarned) {
|
|
4498
|
+
dshRouteWarned = true;
|
|
4499
|
+
process.stderr.write("[agentchat] DSH detected but no session could be routed to this call: " + "the local /health (roots[].status) was unreachable and no session log matched. " + `Per-session identity is disabled for now; install the DSH inbound plugin or set AGENTSCHAT_DSH_HEALTH_URL.
|
|
4500
|
+
`);
|
|
4501
|
+
}
|
|
4502
|
+
}
|
|
4503
|
+
return { session: runtimeSession, isPerCallSession: false };
|
|
4504
|
+
}
|
|
4505
|
+
var callTail = Promise.resolve();
|
|
4506
|
+
function serializeCall(run) {
|
|
4507
|
+
const started = callTail.then(() => run(), () => run());
|
|
4508
|
+
callTail = started.then(() => {
|
|
4509
|
+
return;
|
|
4510
|
+
}, () => {
|
|
4511
|
+
return;
|
|
4512
|
+
});
|
|
4513
|
+
return started;
|
|
4514
|
+
}
|
|
4515
|
+
var handleToolCall = async (request) => {
|
|
3821
4516
|
let { name, arguments: args } = request.params;
|
|
3822
4517
|
let viaExtendedCompat = false;
|
|
3823
4518
|
try {
|
|
3824
|
-
const
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
4519
|
+
const rawMeta = request.params?._meta;
|
|
4520
|
+
const { session: callerSession, isPerCallSession } = await resolveCallerSessionForToolCall(name, args, rawMeta);
|
|
4521
|
+
if (callerSession) {
|
|
4522
|
+
runtimeSession = callerSession;
|
|
4523
|
+
const binds = loadSessionBinds(configDir);
|
|
4524
|
+
const boundProfileName = binds[callerSession.sessionId];
|
|
4525
|
+
const isProfileControlTool = name === "connect_profile" || name === "switch_profile" || name === "disconnect_profile";
|
|
4526
|
+
if (boundProfileName) {
|
|
4527
|
+
const existingSlot = profileSlots.get(boundProfileName);
|
|
4528
|
+
if (existingSlot) {
|
|
4529
|
+
activateSlot(existingSlot, callerSession);
|
|
4530
|
+
if (!toolOnlyMode) {
|
|
4531
|
+
acquireAgentLock({
|
|
4532
|
+
lockDir,
|
|
4533
|
+
agentId: existingSlot.agentId,
|
|
4534
|
+
profileName: existingSlot.profileName,
|
|
4535
|
+
sessionId: callerSession.sessionId,
|
|
4536
|
+
runtime: callerSession.runtime
|
|
4537
|
+
});
|
|
4538
|
+
}
|
|
4539
|
+
} else if (!isProfileControlTool || name === "disconnect_profile") {
|
|
4540
|
+
const boundPath = nameToPath(boundProfileName);
|
|
4541
|
+
if (existsSync7(boundPath)) {
|
|
3832
4542
|
try {
|
|
3833
4543
|
const candidate = readIdentityProfile(boundPath);
|
|
3834
4544
|
const lock = checkAgentLock({
|
|
3835
4545
|
lockDir,
|
|
3836
4546
|
agentId: candidate?.agent_id,
|
|
3837
|
-
currentSessionId:
|
|
4547
|
+
currentSessionId: callerSession.sessionId,
|
|
3838
4548
|
lockOwnerPid
|
|
3839
4549
|
});
|
|
3840
4550
|
if (!lock.locked) {
|
|
3841
|
-
applyIdentityFromProfile(candidate, boundPath,
|
|
4551
|
+
applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
|
|
4552
|
+
} else if (isPerCallSession) {
|
|
4553
|
+
setAnonymousCallerState(callerSession);
|
|
3842
4554
|
}
|
|
3843
4555
|
} catch {}
|
|
4556
|
+
} else if (isPerCallSession) {
|
|
4557
|
+
setAnonymousCallerState(callerSession);
|
|
3844
4558
|
}
|
|
4559
|
+
} else if (isPerCallSession) {
|
|
4560
|
+
setAnonymousCallerState(callerSession);
|
|
4561
|
+
}
|
|
4562
|
+
} else {
|
|
4563
|
+
let unboundSlot = null;
|
|
4564
|
+
for (const slot of profileSlots.values()) {
|
|
4565
|
+
const slotBoundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
|
|
4566
|
+
if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
|
|
4567
|
+
unboundSlot = slot;
|
|
4568
|
+
break;
|
|
4569
|
+
}
|
|
4570
|
+
}
|
|
4571
|
+
if (unboundSlot && !isProfileControlTool) {
|
|
4572
|
+
activateSlot(unboundSlot, callerSession);
|
|
4573
|
+
if (!toolOnlyMode) {
|
|
4574
|
+
acquireAgentLock({
|
|
4575
|
+
lockDir,
|
|
4576
|
+
agentId: unboundSlot.agentId,
|
|
4577
|
+
profileName: unboundSlot.profileName,
|
|
4578
|
+
sessionId: callerSession.sessionId,
|
|
4579
|
+
runtime: callerSession.runtime
|
|
4580
|
+
});
|
|
4581
|
+
if (unboundSlot.profileName && !findBoundSessionForProfile(configDir, unboundSlot.profileName)) {
|
|
4582
|
+
saveSessionBind(configDir, callerSession.sessionId, unboundSlot.profileName);
|
|
4583
|
+
}
|
|
4584
|
+
}
|
|
4585
|
+
} else if (unboundSlot && isProfileControlTool) {
|
|
4586
|
+
activateSlot(unboundSlot, callerSession);
|
|
4587
|
+
} else if (isPerCallSession) {
|
|
4588
|
+
setAnonymousCallerState(callerSession);
|
|
3845
4589
|
}
|
|
3846
|
-
} else if (!anonymousMode && AGENT_ID && activeProfileFile && !toolOnlyMode) {
|
|
3847
|
-
acquireAgentLock({
|
|
3848
|
-
lockDir,
|
|
3849
|
-
agentId: AGENT_ID,
|
|
3850
|
-
profileName: profileNameFromPath(activeProfileFile),
|
|
3851
|
-
sessionId: metaSession.sessionId,
|
|
3852
|
-
runtime: metaSession.runtime
|
|
3853
|
-
});
|
|
3854
|
-
const pName = profileNameFromPath(activeProfileFile);
|
|
3855
|
-
if (pName)
|
|
3856
|
-
saveSessionBind(configDir, metaSession.sessionId, pName);
|
|
3857
4590
|
}
|
|
3858
4591
|
}
|
|
3859
4592
|
if (TOOL_INPUT_SCHEMAS.has(name)) {
|
|
@@ -4082,7 +4815,7 @@ ${a.body || ""}`;
|
|
|
4082
4815
|
const currentVersion = Number(meta.version ?? 0);
|
|
4083
4816
|
let cachedVersion = null;
|
|
4084
4817
|
try {
|
|
4085
|
-
cachedVersion = Number(JSON.parse(
|
|
4818
|
+
cachedVersion = Number(JSON.parse(readFileSync7(pMeta, "utf8")).version);
|
|
4086
4819
|
} catch {}
|
|
4087
4820
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
4088
4821
|
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.` }] };
|
|
@@ -4091,7 +4824,7 @@ ${a.body || ""}`;
|
|
|
4091
4824
|
if (!bodyR.ok)
|
|
4092
4825
|
return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
|
|
4093
4826
|
const doc = JSON.parse(await bodyR.text());
|
|
4094
|
-
|
|
4827
|
+
mkdirSync3(dirname(pMd), { recursive: true });
|
|
4095
4828
|
writeFileSync4(pMd, String(doc?.body_markdown ?? ""));
|
|
4096
4829
|
writeFileSync4(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
|
|
4097
4830
|
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.` }] };
|
|
@@ -4116,7 +4849,7 @@ ${a.body || ""}`;
|
|
|
4116
4849
|
const currentVersion = Number(meta.version ?? 0);
|
|
4117
4850
|
let cachedVersion = null;
|
|
4118
4851
|
try {
|
|
4119
|
-
cachedVersion = Number(JSON.parse(
|
|
4852
|
+
cachedVersion = Number(JSON.parse(readFileSync7(metaPath, "utf8")).version);
|
|
4120
4853
|
} catch {}
|
|
4121
4854
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
4122
4855
|
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.` }] };
|
|
@@ -4126,7 +4859,7 @@ ${a.body || ""}`;
|
|
|
4126
4859
|
return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
|
|
4127
4860
|
const doc = JSON.parse(await docR.text());
|
|
4128
4861
|
const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
|
|
4129
|
-
|
|
4862
|
+
mkdirSync3(dirname(mdPath), { recursive: true });
|
|
4130
4863
|
writeFileSync4(mdPath, body);
|
|
4131
4864
|
writeFileSync4(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
|
|
4132
4865
|
const was = cachedVersion === null ? "missing" : `stale v${cachedVersion}`;
|
|
@@ -4206,7 +4939,7 @@ ${a.body || ""}`;
|
|
|
4206
4939
|
if (name === "reply") {
|
|
4207
4940
|
const { chat_id, text: rawText } = args;
|
|
4208
4941
|
stopTypingHeartbeat(chat_id);
|
|
4209
|
-
const text =
|
|
4942
|
+
const text = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawText));
|
|
4210
4943
|
try {
|
|
4211
4944
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages`, {
|
|
4212
4945
|
method: "POST",
|
|
@@ -4258,7 +4991,7 @@ ${a.body || ""}`;
|
|
|
4258
4991
|
}
|
|
4259
4992
|
if (name === "thread_reply") {
|
|
4260
4993
|
const { chat_id, parent_id, text: rawText } = args;
|
|
4261
|
-
const text =
|
|
4994
|
+
const text = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawText));
|
|
4262
4995
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
4263
4996
|
ws.send(JSON.stringify({
|
|
4264
4997
|
type: "thread_reply",
|
|
@@ -4294,7 +5027,7 @@ ${a.body || ""}`;
|
|
|
4294
5027
|
return { content: [{ type: "text", text: "Error: new_content (string) required" }] };
|
|
4295
5028
|
}
|
|
4296
5029
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
4297
|
-
const new_content =
|
|
5030
|
+
const new_content = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawNewContent));
|
|
4298
5031
|
ws.send(JSON.stringify({
|
|
4299
5032
|
type: "edit_message",
|
|
4300
5033
|
message_id,
|
|
@@ -4583,9 +5316,11 @@ ${brief}` }] };
|
|
|
4583
5316
|
body: "{}"
|
|
4584
5317
|
});
|
|
4585
5318
|
if (r.ok) {
|
|
4586
|
-
|
|
4587
|
-
|
|
4588
|
-
|
|
5319
|
+
if (activeSlot) {
|
|
5320
|
+
activeSlot.knownChannels.delete(chat_id);
|
|
5321
|
+
if (activeSlot.lastSeenMessageTs.delete(chat_id))
|
|
5322
|
+
scheduleSlotLastSeenMessageTsSave(activeSlot);
|
|
5323
|
+
}
|
|
4589
5324
|
const data = await r.json().catch(() => ({}));
|
|
4590
5325
|
if (data.note === "not a member") {
|
|
4591
5326
|
return { content: [{ type: "text", text: `Already not a member of ${chat_id.slice(0, 8)}` }] };
|
|
@@ -4601,9 +5336,11 @@ ${brief}` }] };
|
|
|
4601
5336
|
try {
|
|
4602
5337
|
ws.send(JSON.stringify({ type: "leave_channel", channel_id: chat_id, agent_id: AGENT_ID }));
|
|
4603
5338
|
} catch {}
|
|
4604
|
-
|
|
4605
|
-
|
|
4606
|
-
|
|
5339
|
+
if (activeSlot) {
|
|
5340
|
+
activeSlot.knownChannels.delete(chat_id);
|
|
5341
|
+
if (activeSlot.lastSeenMessageTs.delete(chat_id))
|
|
5342
|
+
scheduleSlotLastSeenMessageTsSave(activeSlot);
|
|
5343
|
+
}
|
|
4607
5344
|
return { content: [{ type: "text", text: `Leave sent via WS (REST unreachable: ${String(e?.message || e).slice(0, 60)})` }] };
|
|
4608
5345
|
}
|
|
4609
5346
|
return { content: [{ type: "text", text: `Leave failed \u2014 no connectivity` }] };
|
|
@@ -4943,6 +5680,15 @@ ${list}` }] };
|
|
|
4943
5680
|
const dim = a.width && a.height ? ` ${a.width}\xD7${a.height}` : "";
|
|
4944
5681
|
line += `
|
|
4945
5682
|
\uD83D\uDDBC image${dim}: ${a.url}`;
|
|
5683
|
+
} else if (a.type === "video") {
|
|
5684
|
+
const dim = a.width && a.height ? ` ${a.width}\xD7${a.height}` : "";
|
|
5685
|
+
const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
|
|
5686
|
+
line += `
|
|
5687
|
+
\uD83C\uDFAC video${dim}${dur}: ${a.url}`;
|
|
5688
|
+
if (a.transcript) {
|
|
5689
|
+
line += `
|
|
5690
|
+
transcript: "${String(a.transcript).slice(0, 400)}"`;
|
|
5691
|
+
}
|
|
4946
5692
|
} else {
|
|
4947
5693
|
line += `
|
|
4948
5694
|
\uD83D\uDCCE ${a.type || "file"}: ${a.url}`;
|
|
@@ -5355,8 +6101,9 @@ ${list}` }] };
|
|
|
5355
6101
|
} catch (e) {
|
|
5356
6102
|
return { content: [{ type: "text", text: `${name} failed: ${String(e?.message || e).slice(0, 300)}` }], isError: true };
|
|
5357
6103
|
}
|
|
5358
|
-
}
|
|
5359
|
-
|
|
6104
|
+
};
|
|
6105
|
+
server.setRequestHandler(CallToolRequestSchema, (request) => serializeCall(() => handleToolCall(request)));
|
|
6106
|
+
var mentionTsFile = join6(configDir, `mention-ts-${AGENT_ID}.json`);
|
|
5360
6107
|
function loadMentionTimestamps() {
|
|
5361
6108
|
return loadCursor(mentionTsFile, safeStderrWrite);
|
|
5362
6109
|
}
|
|
@@ -5364,32 +6111,10 @@ function saveMentionTimestamps(m) {
|
|
|
5364
6111
|
persistCursor(mentionTsFile, m, safeStderrWrite);
|
|
5365
6112
|
}
|
|
5366
6113
|
var lastMentionTimestamp = loadMentionTimestamps();
|
|
5367
|
-
var lastSeenMessageTsFile = join4(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
|
|
5368
|
-
function loadLastSeenMessageTs() {
|
|
5369
|
-
return loadCursor(lastSeenMessageTsFile, safeStderrWrite);
|
|
5370
|
-
}
|
|
5371
|
-
var lastSeenMessageTs = loadLastSeenMessageTs();
|
|
5372
|
-
var cursorFlushIntervalMs = Math.max(500, Number(process.env.AGENTSCHAT_MCP_CURSOR_FLUSH_MS || 5000));
|
|
5373
|
-
var cursorState = { dirty: false };
|
|
5374
|
-
var lastSeenMessageTsTimer = null;
|
|
5375
6114
|
function flushLastSeenMessageTs() {
|
|
5376
|
-
|
|
5377
|
-
|
|
5378
|
-
if (lastSeenMessageTsTimer) {
|
|
5379
|
-
clearTimeout(lastSeenMessageTsTimer);
|
|
5380
|
-
lastSeenMessageTsTimer = null;
|
|
6115
|
+
for (const slot of profileSlots.values()) {
|
|
6116
|
+
flushSlotLastSeenMessageTs(slot);
|
|
5381
6117
|
}
|
|
5382
|
-
flushCursor(cursorState, () => persistCursor(lastSeenMessageTsFile, lastSeenMessageTs, safeStderrWrite));
|
|
5383
|
-
}
|
|
5384
|
-
function scheduleLastSeenMessageTsSave() {
|
|
5385
|
-
cursorState.dirty = true;
|
|
5386
|
-
if (lastSeenMessageTsTimer)
|
|
5387
|
-
return;
|
|
5388
|
-
lastSeenMessageTsTimer = setTimeout(() => {
|
|
5389
|
-
lastSeenMessageTsTimer = null;
|
|
5390
|
-
flushLastSeenMessageTs();
|
|
5391
|
-
}, cursorFlushIntervalMs);
|
|
5392
|
-
lastSeenMessageTsTimer.unref?.();
|
|
5393
6118
|
}
|
|
5394
6119
|
function normalizeChannelDocLevel(level) {
|
|
5395
6120
|
if (typeof level === "number" && Number.isInteger(level) && level >= 1 && level <= 4) {
|
|
@@ -5525,46 +6250,40 @@ function clearFinishedHiddenIdentityGamesFromMessage(data) {
|
|
|
5525
6250
|
}
|
|
5526
6251
|
}
|
|
5527
6252
|
}
|
|
5528
|
-
var messageDedup = new MessageDedup;
|
|
5529
6253
|
function deliverySource(data) {
|
|
5530
6254
|
return typeof data?.__source === "string" ? data.__source : "live";
|
|
5531
6255
|
}
|
|
5532
|
-
function recordOrSkipDeliveredMessage(data) {
|
|
6256
|
+
function recordOrSkipDeliveredMessage(data, slot = activeSlot) {
|
|
5533
6257
|
const key = messageDedupKey(data);
|
|
5534
|
-
if (!key)
|
|
6258
|
+
if (!key || !slot)
|
|
5535
6259
|
return false;
|
|
5536
|
-
const skip = messageDedup.recordOrSkip(key);
|
|
6260
|
+
const skip = slot.messageDedup.recordOrSkip(key);
|
|
5537
6261
|
if (skip) {
|
|
5538
6262
|
process.stderr.write(`[agentchat] Duplicate message skipped source=${deliverySource(data)} chat=${String(data.channel_id).slice(0, 12)} id=${String(data.id).slice(0, 12)}
|
|
5539
6263
|
`);
|
|
5540
6264
|
}
|
|
5541
6265
|
return skip;
|
|
5542
6266
|
}
|
|
5543
|
-
|
|
5544
|
-
|
|
5545
|
-
var wsReconnectAttempt = 0;
|
|
5546
|
-
var reconnectTimer = null;
|
|
5547
|
-
var backfillTimer = null;
|
|
5548
|
-
function scheduleReconnect(delayMs) {
|
|
5549
|
-
if (shuttingDown)
|
|
6267
|
+
function scheduleReconnect(delayMs, slot = activeSlot) {
|
|
6268
|
+
if (shuttingDown || !slot)
|
|
5550
6269
|
return;
|
|
5551
|
-
if (reconnectTimer)
|
|
5552
|
-
clearTimeout(reconnectTimer);
|
|
5553
|
-
reconnectTimer = setTimeout(() => {
|
|
5554
|
-
reconnectTimer = null;
|
|
5555
|
-
connectWS();
|
|
6270
|
+
if (slot.reconnectTimer)
|
|
6271
|
+
clearTimeout(slot.reconnectTimer);
|
|
6272
|
+
slot.reconnectTimer = setTimeout(() => {
|
|
6273
|
+
slot.reconnectTimer = null;
|
|
6274
|
+
connectWS(slot);
|
|
5556
6275
|
}, delayMs);
|
|
5557
6276
|
}
|
|
5558
|
-
async function backfillAllChannels() {
|
|
5559
|
-
if (knownChannels.size === 0)
|
|
6277
|
+
async function backfillAllChannels(slot = activeSlot) {
|
|
6278
|
+
if (!slot || slot.knownChannels.size === 0)
|
|
5560
6279
|
return;
|
|
5561
|
-
for (const channelId of knownChannels) {
|
|
6280
|
+
for (const channelId of slot.knownChannels) {
|
|
5562
6281
|
try {
|
|
5563
|
-
const after = lastSeenMessageTs.get(channelId);
|
|
6282
|
+
const after = slot.lastSeenMessageTs.get(channelId);
|
|
5564
6283
|
const params = after ? `?after=${encodeURIComponent(after)}&limit=50` : `?limit=1`;
|
|
5565
6284
|
const url = `${REST_URL}/api/channels/${encodeURIComponent(channelId)}/messages${params}`;
|
|
5566
6285
|
const res = await apiFetch(url, {
|
|
5567
|
-
headers:
|
|
6286
|
+
headers: slot.token ? { Authorization: `Bearer ${slot.token}` } : {}
|
|
5568
6287
|
});
|
|
5569
6288
|
if (!res.ok)
|
|
5570
6289
|
continue;
|
|
@@ -5578,12 +6297,12 @@ async function backfillAllChannels() {
|
|
|
5578
6297
|
newestTs = t;
|
|
5579
6298
|
}
|
|
5580
6299
|
if (newestTs) {
|
|
5581
|
-
lastSeenMessageTs.set(channelId, newestTs);
|
|
5582
|
-
|
|
6300
|
+
slot.lastSeenMessageTs.set(channelId, newestTs);
|
|
6301
|
+
scheduleSlotLastSeenMessageTsSave(slot);
|
|
5583
6302
|
}
|
|
5584
6303
|
continue;
|
|
5585
6304
|
}
|
|
5586
|
-
const replay = msgs.filter((m) => m && m.sender_id !==
|
|
6305
|
+
const replay = msgs.filter((m) => m && m.sender_id !== slot.agentId && m.content !== "__typing__");
|
|
5587
6306
|
const dedupedReplay = after ? replay.filter((m) => {
|
|
5588
6307
|
const msgTs = normalizeTimestampForCursor(m?.timestamp, "after");
|
|
5589
6308
|
const afterTs = normalizeTimestampForCursor(after, "after");
|
|
@@ -5596,8 +6315,8 @@ async function backfillAllChannels() {
|
|
|
5596
6315
|
dedupedReplay.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp)));
|
|
5597
6316
|
for (const m of dedupedReplay) {
|
|
5598
6317
|
try {
|
|
5599
|
-
if (
|
|
5600
|
-
await
|
|
6318
|
+
if (slot.handleWSMessage) {
|
|
6319
|
+
await slot.handleWSMessage({ ...m, type: "message", __source: "backfill" });
|
|
5601
6320
|
}
|
|
5602
6321
|
} catch (e) {
|
|
5603
6322
|
process.stderr.write(`[agentchat] Backfill replay error: ${e}
|
|
@@ -5610,36 +6329,88 @@ async function backfillAllChannels() {
|
|
|
5610
6329
|
}
|
|
5611
6330
|
}
|
|
5612
6331
|
}
|
|
5613
|
-
function
|
|
5614
|
-
if (shuttingDown)
|
|
6332
|
+
function syncOpenBoundSessions() {
|
|
6333
|
+
if (toolOnlyMode || shuttingDown)
|
|
6334
|
+
return;
|
|
6335
|
+
const agyHost = discoverAntigravityHost();
|
|
6336
|
+
if (!agyHost || agyHost.openConversations.length === 0)
|
|
6337
|
+
return;
|
|
6338
|
+
const binds = loadSessionBinds(configDir);
|
|
6339
|
+
for (const cid of agyHost.openConversations) {
|
|
6340
|
+
const boundProf = binds[cid];
|
|
6341
|
+
if (!boundProf || profileSlots.has(boundProf))
|
|
6342
|
+
continue;
|
|
6343
|
+
const boundPath = nameToPath(boundProf);
|
|
6344
|
+
if (!existsSync7(boundPath))
|
|
6345
|
+
continue;
|
|
6346
|
+
try {
|
|
6347
|
+
const candidate = readIdentityProfile(boundPath);
|
|
6348
|
+
validateIdentityProfile(candidate, boundPath);
|
|
6349
|
+
const lock = checkAgentLock({
|
|
6350
|
+
lockDir,
|
|
6351
|
+
agentId: candidate.agent_id,
|
|
6352
|
+
currentSessionId: cid,
|
|
6353
|
+
lockOwnerPid
|
|
6354
|
+
});
|
|
6355
|
+
if (lock.locked)
|
|
6356
|
+
continue;
|
|
6357
|
+
const sess = { sessionId: cid, runtime: "antigravity" };
|
|
6358
|
+
acquireAgentLock({
|
|
6359
|
+
lockDir,
|
|
6360
|
+
agentId: candidate.agent_id,
|
|
6361
|
+
profileName: boundProf,
|
|
6362
|
+
sessionId: cid,
|
|
6363
|
+
runtime: "antigravity"
|
|
6364
|
+
});
|
|
6365
|
+
const slot = createProfileSlot({
|
|
6366
|
+
profileName: boundProf,
|
|
6367
|
+
profileFile: boundPath,
|
|
6368
|
+
profile: candidate,
|
|
6369
|
+
agentId: candidate.agent_id,
|
|
6370
|
+
token: candidate.token,
|
|
6371
|
+
capabilities: candidate.capabilities || ["claude-code", "coding", "chat"],
|
|
6372
|
+
runtimeSession: sess
|
|
6373
|
+
});
|
|
6374
|
+
profileSlots.set(boundProf, slot);
|
|
6375
|
+
slot.heartbeat.start();
|
|
6376
|
+
connectWS(slot);
|
|
6377
|
+
if (!activeSlot)
|
|
6378
|
+
activateSlot(slot, sess);
|
|
6379
|
+
} catch {}
|
|
6380
|
+
}
|
|
6381
|
+
}
|
|
6382
|
+
function connectWS(slot = activeSlot) {
|
|
6383
|
+
if (shuttingDown || !slot)
|
|
5615
6384
|
return;
|
|
5616
6385
|
let socket;
|
|
5617
6386
|
try {
|
|
5618
6387
|
socket = new WebSocket(WS_URL);
|
|
5619
|
-
ws = socket;
|
|
6388
|
+
slot.ws = socket;
|
|
6389
|
+
if (activeSlot === slot)
|
|
6390
|
+
ws = socket;
|
|
5620
6391
|
} catch (e) {
|
|
5621
6392
|
process.stderr.write(`[agentchat] WebSocket constructor failed: ${e}, retrying in 5s
|
|
5622
6393
|
`);
|
|
5623
|
-
scheduleReconnect(5000);
|
|
6394
|
+
scheduleReconnect(5000, slot);
|
|
5624
6395
|
return;
|
|
5625
6396
|
}
|
|
5626
|
-
|
|
5627
|
-
if (ws !== socket)
|
|
6397
|
+
socket.onopen = () => {
|
|
6398
|
+
if (slot.ws !== socket)
|
|
5628
6399
|
return;
|
|
5629
6400
|
try {
|
|
5630
6401
|
socket.send(JSON.stringify({
|
|
5631
6402
|
type: "auth",
|
|
5632
|
-
agent_id:
|
|
5633
|
-
token:
|
|
5634
|
-
capabilities:
|
|
6403
|
+
agent_id: slot.agentId,
|
|
6404
|
+
token: slot.token,
|
|
6405
|
+
capabilities: slot.capabilities
|
|
5635
6406
|
}));
|
|
5636
6407
|
} catch (e) {
|
|
5637
6408
|
process.stderr.write(`[agentchat] Auth send failed: ${e}
|
|
5638
6409
|
`);
|
|
5639
6410
|
}
|
|
5640
6411
|
};
|
|
5641
|
-
|
|
5642
|
-
if (ws !== socket)
|
|
6412
|
+
socket.onmessage = async (event) => {
|
|
6413
|
+
if (slot.ws !== socket)
|
|
5643
6414
|
return;
|
|
5644
6415
|
let data;
|
|
5645
6416
|
try {
|
|
@@ -5656,31 +6427,34 @@ function connectWS() {
|
|
|
5656
6427
|
`);
|
|
5657
6428
|
}
|
|
5658
6429
|
};
|
|
5659
|
-
|
|
6430
|
+
slot.handleWSMessage = handleWSMessage;
|
|
5660
6431
|
async function handleWSMessage(data) {
|
|
5661
6432
|
if (data.type === "pong") {
|
|
5662
|
-
heartbeat.receivedPong();
|
|
6433
|
+
slot.heartbeat.receivedPong();
|
|
6434
|
+
syncOpenBoundSessions();
|
|
5663
6435
|
return;
|
|
5664
6436
|
}
|
|
5665
6437
|
if ((data.type === "hidden_identity.reveal" || data.type === "hidden_identity.finished") && typeof data.game_id === "string") {
|
|
5666
6438
|
clearActiveHiddenIdentityGame(data.game_id, data.type);
|
|
5667
6439
|
}
|
|
5668
6440
|
if (data.type === "auth_ok") {
|
|
5669
|
-
sessionId = data.session_id;
|
|
5670
|
-
|
|
5671
|
-
|
|
5672
|
-
|
|
6441
|
+
slot.sessionId = data.session_id;
|
|
6442
|
+
if (activeSlot === slot)
|
|
6443
|
+
sessionId = data.session_id;
|
|
6444
|
+
slot.wsReconnectAttempt = 0;
|
|
6445
|
+
slot.heartbeat.receivedPong();
|
|
6446
|
+
process.stderr.write(`[agentchat] Connected as ${slot.agentId}
|
|
5673
6447
|
`);
|
|
5674
|
-
if (backfillTimer)
|
|
5675
|
-
clearTimeout(backfillTimer);
|
|
5676
|
-
backfillTimer = setTimeout(() => {
|
|
5677
|
-
backfillTimer = null;
|
|
6448
|
+
if (slot.backfillTimer)
|
|
6449
|
+
clearTimeout(slot.backfillTimer);
|
|
6450
|
+
slot.backfillTimer = setTimeout(() => {
|
|
6451
|
+
slot.backfillTimer = null;
|
|
5678
6452
|
if (!shuttingDown)
|
|
5679
|
-
backfillAllChannels();
|
|
6453
|
+
backfillAllChannels(slot);
|
|
5680
6454
|
}, 2000);
|
|
5681
|
-
} else if ((data.type === "message" || data.type === "thread_reply") && data.sender_id ===
|
|
5682
|
-
stopTypingHeartbeat(data.channel_id);
|
|
5683
|
-
} else if ((data.type === "message" || data.type === "thread_reply") && (data.sender_id !==
|
|
6455
|
+
} else if ((data.type === "message" || data.type === "thread_reply") && data.sender_id === slot.agentId && typeof data.content === "string" && data.content !== "__typing__" && !["loop_tick", "slash_input", "loop_status", "slash_response"].includes(data.meta?.kind)) {
|
|
6456
|
+
stopTypingHeartbeat(data.channel_id, slot);
|
|
6457
|
+
} else if ((data.type === "message" || data.type === "thread_reply") && (data.sender_id !== slot.agentId || data.meta && typeof data.meta === "object" && data.meta.kind === "loop_tick")) {
|
|
5684
6458
|
if (data.content === "__typing__")
|
|
5685
6459
|
return;
|
|
5686
6460
|
const metaKind = data.meta && typeof data.meta === "object" ? data.meta.kind : undefined;
|
|
@@ -5689,32 +6463,33 @@ function connectWS() {
|
|
|
5689
6463
|
`);
|
|
5690
6464
|
return;
|
|
5691
6465
|
}
|
|
5692
|
-
if (recordOrSkipDeliveredMessage(data))
|
|
6466
|
+
if (recordOrSkipDeliveredMessage(data, slot))
|
|
5693
6467
|
return;
|
|
5694
6468
|
if (typeof data.channel_id === "string" && typeof data.timestamp === "string") {
|
|
5695
|
-
const prev = lastSeenMessageTs.get(data.channel_id) || "";
|
|
6469
|
+
const prev = slot.lastSeenMessageTs.get(data.channel_id) || "";
|
|
5696
6470
|
const currentTs = normalizeTimestampForCursor(data.timestamp, "after") || data.timestamp;
|
|
5697
6471
|
const prevTs = normalizeTimestampForCursor(prev, "after") || prev;
|
|
5698
6472
|
if (currentTs > prevTs) {
|
|
5699
|
-
lastSeenMessageTs.set(data.channel_id, data.timestamp);
|
|
5700
|
-
|
|
6473
|
+
slot.lastSeenMessageTs.set(data.channel_id, data.timestamp);
|
|
6474
|
+
scheduleSlotLastSeenMessageTsSave(slot);
|
|
5701
6475
|
}
|
|
5702
6476
|
}
|
|
5703
6477
|
const isDM = data.channel_id?.startsWith("dm-");
|
|
5704
|
-
const isMentioned = matchesMention(data.content || "",
|
|
6478
|
+
const isMentioned = matchesMention(data.content || "", slot.agentId || "");
|
|
5705
6479
|
const activeHi = activeHiddenIdentityForChannel(data.channel_id);
|
|
5706
|
-
const isOwnLoopTick = metaKind === "loop_tick" && data.sender_id ===
|
|
6480
|
+
const isOwnLoopTick = metaKind === "loop_tick" && data.sender_id === slot.agentId;
|
|
5707
6481
|
if (isDM || isMentioned || activeHi || isOwnLoopTick) {
|
|
5708
6482
|
if (isDM || isMentioned)
|
|
5709
|
-
startTypingHeartbeat(data.channel_id);
|
|
6483
|
+
startTypingHeartbeat(data.channel_id, slot);
|
|
5710
6484
|
let contextPrefix = "";
|
|
5711
6485
|
if (!isDM && isMentioned) {
|
|
5712
6486
|
try {
|
|
5713
|
-
const
|
|
6487
|
+
const mentionKey = `${slot.agentId}:${data.channel_id}`;
|
|
6488
|
+
const lastTs = lastMentionTimestamp.get(mentionKey) || lastMentionTimestamp.get(data.channel_id) || "";
|
|
5714
6489
|
const params = `limit=50${lastTs ? "&after=" + encodeURIComponent(lastTs) : ""}`;
|
|
5715
6490
|
const historyUrl = `${REST_URL}/api/channels/${encodeURIComponent(data.channel_id)}/messages?${params}`;
|
|
5716
6491
|
const historyRes = await apiFetch(historyUrl, {
|
|
5717
|
-
headers:
|
|
6492
|
+
headers: slot.token ? { Authorization: `Bearer ${slot.token}` } : {}
|
|
5718
6493
|
});
|
|
5719
6494
|
if (historyRes.ok) {
|
|
5720
6495
|
const historyData = await historyRes.json();
|
|
@@ -5734,7 +6509,7 @@ function connectWS() {
|
|
|
5734
6509
|
}
|
|
5735
6510
|
const truncatedMsgs = trimmed.length < msgs.length;
|
|
5736
6511
|
if (trimmed.length > 0) {
|
|
5737
|
-
const context = trimmed.map((m) => `${m.sender_id}: ${m.content}`).join(`
|
|
6512
|
+
const context = trimmed.map((m) => `${m.sender_id}: ${m.content}${formatWakeAttachments(m.attachments)}`).join(`
|
|
5738
6513
|
`);
|
|
5739
6514
|
const note = truncatedMsgs ? `[\u9891\u9053\u4E0A\u4E0B\u6587 - \u6700\u8FD1 ${trimmed.length} \u6761\u6D88\u606F\uFF08\u66F4\u65E9\u7684\u5DF2\u622A\u65AD\u4FDD\u62A4\u4E0A\u4E0B\u6587\u7A97\u53E3\uFF09]` : `[\u9891\u9053\u4E0A\u4E0B\u6587 - \u81EA\u4E0A\u6B21 @mention \u4EE5\u6765 ${trimmed.length} \u6761\u6D88\u606F]`;
|
|
5740
6515
|
contextPrefix = `${note}
|
|
@@ -5744,6 +6519,7 @@ ${context}
|
|
|
5744
6519
|
`;
|
|
5745
6520
|
}
|
|
5746
6521
|
}
|
|
6522
|
+
lastMentionTimestamp.set(mentionKey, data.timestamp);
|
|
5747
6523
|
lastMentionTimestamp.set(data.channel_id, data.timestamp);
|
|
5748
6524
|
saveMentionTimestamps(lastMentionTimestamp);
|
|
5749
6525
|
} catch (e) {
|
|
@@ -5758,10 +6534,11 @@ ${context}
|
|
|
5758
6534
|
process.stderr.write(`[agentchat] ${isDM ? "DM" : isMentioned ? "@mention" : isOwnLoopTick ? "loop-tick" : "HI-active"} from ${String(data.sender_id ?? "?").slice(0, 8)}: ${String(data.content ?? "").slice(0, 50)}
|
|
5759
6535
|
`);
|
|
5760
6536
|
try {
|
|
6537
|
+
const notifAtt = formatWakeAttachments(data.attachments);
|
|
5761
6538
|
await server.notification({
|
|
5762
6539
|
method: process.env.CLAUDE_CODE_ENTRYPOINT ? "notifications/claude/channel" : "notifications/chat/channel",
|
|
5763
6540
|
params: {
|
|
5764
|
-
content: contextPrefix + data.content,
|
|
6541
|
+
content: contextPrefix + (data.content || "") + notifAtt,
|
|
5765
6542
|
meta: {
|
|
5766
6543
|
chat_id: data.channel_id,
|
|
5767
6544
|
sender_id: data.sender_id,
|
|
@@ -5775,18 +6552,20 @@ ${context}
|
|
|
5775
6552
|
process.stderr.write(`[agentchat] Notification FAILED: ${notifErr}
|
|
5776
6553
|
`);
|
|
5777
6554
|
}
|
|
6555
|
+
const slotProfName = slot.profileName || profileNameFromPath(slot.profileFile);
|
|
6556
|
+
const slotRuntime = slot.runtimeSession?.runtime;
|
|
5778
6557
|
if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
|
|
5779
6558
|
(async () => {
|
|
5780
6559
|
try {
|
|
5781
|
-
const { readFileSync:
|
|
5782
|
-
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY,
|
|
6560
|
+
const { readFileSync: readFileSync8, existsSync: existsSync8 } = await import("fs");
|
|
6561
|
+
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync8);
|
|
5783
6562
|
let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
|
|
5784
6563
|
if (!agentId) {
|
|
5785
6564
|
agentId = await resolveGrokAgentId({
|
|
5786
6565
|
explicitId: "",
|
|
5787
|
-
agentschatName: profile.display_name ||
|
|
6566
|
+
agentschatName: slot.profile.display_name || slot.agentId,
|
|
5788
6567
|
listAgents: async () => {
|
|
5789
|
-
const gwcfg = JSON.parse(
|
|
6568
|
+
const gwcfg = JSON.parse(readFileSync8(gwPath, "utf8"));
|
|
5790
6569
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
5791
6570
|
const port = grokPortFromGatewayConfig(gwcfg);
|
|
5792
6571
|
const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
|
|
@@ -5808,24 +6587,34 @@ ${context}
|
|
|
5808
6587
|
}
|
|
5809
6588
|
})();
|
|
5810
6589
|
} else if (process.env.AGENTCHAT_WAKE_URL) {
|
|
6590
|
+
const route = resolveSessionForAgent(slot.agentId, { configDir });
|
|
6591
|
+
const targetSessionId = route?.sessionId || findBoundSessionForProfile(configDir, slotProfName) || slot.runtimeSession?.sessionId || undefined;
|
|
5811
6592
|
fireWake(data, {
|
|
5812
6593
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
5813
|
-
secret: process.env.AGENTCHAT_WAKE_SECRET
|
|
6594
|
+
secret: process.env.AGENTCHAT_WAKE_SECRET,
|
|
6595
|
+
targetSessionId
|
|
5814
6596
|
});
|
|
5815
|
-
} else if (
|
|
5816
|
-
const
|
|
5817
|
-
const zcodeSid = runtimeSession?.sessionId || findBoundSessionForProfile(configDir, activeProfName, (sid) => sid.startsWith("sess_")) || "";
|
|
6597
|
+
} else if (slotRuntime === "zcode" || process.env.AGENTCHAT_WAKE_MODE === "zcode" || Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")))) {
|
|
6598
|
+
const zcodeSid = findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")) || (slotRuntime === "zcode" ? slot.runtimeSession?.sessionId : "") || "";
|
|
5818
6599
|
if (zcodeSid) {
|
|
5819
6600
|
fireZcodeWake(data, {
|
|
5820
6601
|
sessionId: zcodeSid,
|
|
5821
|
-
workspacePath: runtimeSession?.workspacePath,
|
|
5822
|
-
profileName:
|
|
6602
|
+
workspacePath: slot.runtimeSession?.workspacePath,
|
|
6603
|
+
profileName: slotProfName ?? undefined,
|
|
5823
6604
|
lockOwnerPid: process.pid,
|
|
5824
6605
|
contextPrefix,
|
|
5825
6606
|
logger: (m) => process.stderr.write(`${m}
|
|
5826
6607
|
`)
|
|
5827
6608
|
});
|
|
5828
6609
|
}
|
|
6610
|
+
} else if (slotRuntime === "dsh" || isDshHostProcess() || Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")))) {
|
|
6611
|
+
const dshSid = findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")) || resolveSessionForAgent(slot.agentId, { configDir })?.sessionId || (slotRuntime === "dsh" ? slot.runtimeSession?.sessionId : "") || undefined;
|
|
6612
|
+
const dshWakeUrl = process.env.DSH_WAKE_URL || process.env.AGENTSCHAT_DSH_WAKE_URL || "http://127.0.0.1:8799/wake";
|
|
6613
|
+
fireWake(data, {
|
|
6614
|
+
url: dshWakeUrl,
|
|
6615
|
+
secret: process.env.DSH_WAKE_SECRET ?? process.env.AGENTCHAT_WAKE_SECRET,
|
|
6616
|
+
targetSessionId: dshSid
|
|
6617
|
+
});
|
|
5829
6618
|
} else {
|
|
5830
6619
|
(async () => {
|
|
5831
6620
|
try {
|
|
@@ -5834,14 +6623,13 @@ ${context}
|
|
|
5834
6623
|
const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
|
|
5835
6624
|
if (!agyHost && !lsAddress)
|
|
5836
6625
|
return;
|
|
5837
|
-
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
5838
6626
|
const allBinds = loadSessionBinds(configDir);
|
|
5839
|
-
let targetCid =
|
|
6627
|
+
let targetCid = findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) || (slotRuntime === "antigravity" ? slot.runtimeSession?.sessionId : "") || "";
|
|
5840
6628
|
if (!targetCid && agyHost) {
|
|
5841
6629
|
if (agyHost.openConversations.length === 1) {
|
|
5842
6630
|
targetCid = agyHost.openConversations[0];
|
|
5843
6631
|
} else if (agyHost.openConversations.length > 1) {
|
|
5844
|
-
const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] ===
|
|
6632
|
+
const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] === slotProfName);
|
|
5845
6633
|
targetCid = unboundOrSame || agyHost.openConversations[0];
|
|
5846
6634
|
}
|
|
5847
6635
|
}
|
|
@@ -5870,16 +6658,16 @@ ${context}
|
|
|
5870
6658
|
}
|
|
5871
6659
|
} else if (data.type === "channel_created") {
|
|
5872
6660
|
try {
|
|
5873
|
-
ws?.send(JSON.stringify({
|
|
6661
|
+
slot.ws?.send(JSON.stringify({
|
|
5874
6662
|
type: "join_channel",
|
|
5875
6663
|
channel_id: data.channel_id,
|
|
5876
|
-
agent_id:
|
|
6664
|
+
agent_id: slot.agentId
|
|
5877
6665
|
}));
|
|
5878
6666
|
} catch {}
|
|
5879
6667
|
process.stderr.write(`[agentchat] Joined channel: ${data.name}
|
|
5880
6668
|
`);
|
|
5881
6669
|
if (typeof data.channel_id === "string")
|
|
5882
|
-
knownChannels.add(data.channel_id);
|
|
6670
|
+
slot.knownChannels.add(data.channel_id);
|
|
5883
6671
|
} else if (data.type === "shard_moved") {
|
|
5884
6672
|
process.stderr.write(`[agentchat] Shard moved, reconnecting...
|
|
5885
6673
|
`);
|
|
@@ -5888,69 +6676,60 @@ ${context}
|
|
|
5888
6676
|
process.stderr.write(`[agentchat] Redirecting to: ${newUrl}
|
|
5889
6677
|
`);
|
|
5890
6678
|
}
|
|
5891
|
-
if (ws) {
|
|
5892
|
-
ws.onclose = null;
|
|
6679
|
+
if (slot.ws) {
|
|
6680
|
+
slot.ws.onclose = null;
|
|
5893
6681
|
try {
|
|
5894
|
-
ws.close();
|
|
6682
|
+
slot.ws.close();
|
|
5895
6683
|
} catch {}
|
|
5896
6684
|
}
|
|
5897
|
-
ws = null;
|
|
5898
|
-
sessionId = null;
|
|
5899
|
-
|
|
5900
|
-
|
|
6685
|
+
slot.ws = null;
|
|
6686
|
+
slot.sessionId = null;
|
|
6687
|
+
if (activeSlot === slot) {
|
|
6688
|
+
ws = null;
|
|
6689
|
+
sessionId = null;
|
|
6690
|
+
}
|
|
6691
|
+
slot.wsReconnectAttempt = 0;
|
|
6692
|
+
scheduleReconnect(500, slot);
|
|
5901
6693
|
} else if (data.type === "error") {
|
|
5902
6694
|
process.stderr.write(`[agentchat] Error: ${data.message}
|
|
5903
6695
|
`);
|
|
5904
6696
|
}
|
|
5905
6697
|
}
|
|
5906
|
-
|
|
5907
|
-
if (ws !== socket)
|
|
6698
|
+
socket.onclose = (event) => {
|
|
6699
|
+
if (slot.ws !== socket)
|
|
5908
6700
|
return;
|
|
5909
|
-
sessionId = null;
|
|
5910
|
-
|
|
5911
|
-
|
|
5912
|
-
|
|
5913
|
-
|
|
6701
|
+
slot.sessionId = null;
|
|
6702
|
+
if (activeSlot === slot)
|
|
6703
|
+
sessionId = null;
|
|
6704
|
+
slot.heartbeat.resetReconnecting();
|
|
6705
|
+
slot.wsReconnectAttempt++;
|
|
6706
|
+
const delay = computeReconnectDelay(slot.wsReconnectAttempt);
|
|
6707
|
+
process.stderr.write(`[agentchat] Disconnected (code=${event?.code ?? "?"}), reconnecting in ${Math.round(delay / 100) / 10}s (attempt ${slot.wsReconnectAttempt})...
|
|
5914
6708
|
`);
|
|
5915
|
-
scheduleReconnect(delay);
|
|
6709
|
+
scheduleReconnect(delay, slot);
|
|
5916
6710
|
};
|
|
5917
|
-
|
|
5918
|
-
if (ws !== socket)
|
|
6711
|
+
socket.onerror = (err) => {
|
|
6712
|
+
if (slot.ws !== socket)
|
|
5919
6713
|
return;
|
|
5920
6714
|
process.stderr.write(`[agentchat] WebSocket error: ${err}
|
|
5921
6715
|
`);
|
|
5922
6716
|
};
|
|
5923
6717
|
}
|
|
5924
|
-
|
|
5925
|
-
|
|
5926
|
-
|
|
5927
|
-
|
|
5928
|
-
|
|
5929
|
-
|
|
5930
|
-
|
|
5931
|
-
|
|
5932
|
-
|
|
5933
|
-
|
|
5934
|
-
|
|
6718
|
+
function releaseLiveLock() {
|
|
6719
|
+
if (!toolOnlyMode) {
|
|
6720
|
+
for (const slot of profileSlots.values()) {
|
|
6721
|
+
if (slot.agentId) {
|
|
6722
|
+
try {
|
|
6723
|
+
const boundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName) || null;
|
|
6724
|
+
releaseAgentLock({ lockDir, agentId: slot.agentId, currentSessionId: boundSid });
|
|
6725
|
+
} catch {}
|
|
6726
|
+
}
|
|
6727
|
+
}
|
|
6728
|
+
if (AGENT_ID) {
|
|
5935
6729
|
try {
|
|
5936
|
-
|
|
6730
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
5937
6731
|
} catch {}
|
|
5938
6732
|
}
|
|
5939
|
-
ws = null;
|
|
5940
|
-
sessionId = null;
|
|
5941
|
-
wsReconnectAttempt = 0;
|
|
5942
|
-
scheduleReconnect(500);
|
|
5943
|
-
},
|
|
5944
|
-
getReadyState: () => ws?.readyState ?? WS_CLOSED
|
|
5945
|
-
}, 15000, 45000, 30000);
|
|
5946
|
-
if (!anonymousMode && !toolOnlyMode) {
|
|
5947
|
-
heartbeat.start();
|
|
5948
|
-
}
|
|
5949
|
-
function releaseLiveLock() {
|
|
5950
|
-
if (AGENT_ID && !toolOnlyMode) {
|
|
5951
|
-
try {
|
|
5952
|
-
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
5953
|
-
} catch {}
|
|
5954
6733
|
}
|
|
5955
6734
|
}
|
|
5956
6735
|
function shutdownFromStdio(reason) {
|
|
@@ -5966,19 +6745,11 @@ function shutdownFromStdio(reason) {
|
|
|
5966
6745
|
`);
|
|
5967
6746
|
}
|
|
5968
6747
|
releaseLiveLock();
|
|
5969
|
-
try {
|
|
5970
|
-
heartbeat.stop();
|
|
5971
|
-
} catch {}
|
|
5972
6748
|
try {
|
|
5973
6749
|
stopAllTypingHeartbeats();
|
|
5974
6750
|
} catch {}
|
|
5975
|
-
|
|
5976
|
-
|
|
5977
|
-
reconnectTimer = null;
|
|
5978
|
-
}
|
|
5979
|
-
if (backfillTimer) {
|
|
5980
|
-
clearTimeout(backfillTimer);
|
|
5981
|
-
backfillTimer = null;
|
|
6751
|
+
for (const slot of [...profileSlots.values()]) {
|
|
6752
|
+
teardownSlot(slot, { releaseLock: false });
|
|
5982
6753
|
}
|
|
5983
6754
|
try {
|
|
5984
6755
|
ws?.close();
|
|
@@ -6037,14 +6808,22 @@ async function checkVersionStaleness() {
|
|
|
6037
6808
|
}
|
|
6038
6809
|
async function main() {
|
|
6039
6810
|
installStdioLifecycleGuards();
|
|
6040
|
-
if (
|
|
6811
|
+
if (!toolOnlyMode) {
|
|
6812
|
+
syncOpenBoundSessions();
|
|
6813
|
+
}
|
|
6814
|
+
if (anonymousMode && profileSlots.size === 0) {
|
|
6041
6815
|
process.stderr.write(`[agentchat] Anonymous \u2014 not connecting to the hub.
|
|
6042
6816
|
`);
|
|
6043
6817
|
} else if (toolOnlyMode) {
|
|
6044
6818
|
process.stderr.write(`[agentchat] Tool-only mode (AGENTSCHAT_TOOL_ONLY=1) \u2014 skipping duplicate WS connection.
|
|
6045
6819
|
`);
|
|
6046
6820
|
} else {
|
|
6047
|
-
|
|
6821
|
+
for (const slot of profileSlots.values()) {
|
|
6822
|
+
if (!slot.ws) {
|
|
6823
|
+
slot.heartbeat.start();
|
|
6824
|
+
connectWS(slot);
|
|
6825
|
+
}
|
|
6826
|
+
}
|
|
6048
6827
|
}
|
|
6049
6828
|
transport = new StdioServerTransport;
|
|
6050
6829
|
await server.connect(transport);
|