agentschat-mcp 0.36.18 → 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 +1173 -435
- 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 +817 -431
- package/src/session-bind.ts +325 -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) {
|
|
@@ -1099,12 +1146,6 @@ function detectRuntimeSession(env = process.env, meta) {
|
|
|
1099
1146
|
if (agySid) {
|
|
1100
1147
|
return { sessionId: agySid, runtime: "antigravity" };
|
|
1101
1148
|
}
|
|
1102
|
-
if (env.__CFBundleIdentifier === "com.google.antigravity" || env.AGY_BROWSER_WS_URL) {
|
|
1103
|
-
const agyHost = discoverAntigravityHost();
|
|
1104
|
-
if (agyHost && agyHost.openConversations.length === 1) {
|
|
1105
|
-
return { sessionId: agyHost.openConversations[0], runtime: "antigravity" };
|
|
1106
|
-
}
|
|
1107
|
-
}
|
|
1108
1149
|
const claudeSid = (env.CLAUDE_CODE_SESSION_ID || env.CLAUDE_SESSION_ID || "").trim();
|
|
1109
1150
|
if (claudeSid) {
|
|
1110
1151
|
const workspacePath = env.CLAUDE_PROJECT_DIR?.trim() || undefined;
|
|
@@ -1114,6 +1155,12 @@ function detectRuntimeSession(env = process.env, meta) {
|
|
|
1114
1155
|
if (explicitSid) {
|
|
1115
1156
|
return { sessionId: explicitSid, runtime: "custom" };
|
|
1116
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
|
+
}
|
|
1117
1164
|
return null;
|
|
1118
1165
|
}
|
|
1119
1166
|
var cachedAgyHost = null;
|
|
@@ -1166,7 +1213,7 @@ function discoverAntigravityHost(opts) {
|
|
|
1166
1213
|
if (p > 0 && !ports.includes(p))
|
|
1167
1214
|
ports.push(p);
|
|
1168
1215
|
}
|
|
1169
|
-
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$/);
|
|
1170
1217
|
if (presMatch) {
|
|
1171
1218
|
const cid = presMatch[1];
|
|
1172
1219
|
if (!openConversations.includes(cid))
|
|
@@ -1183,11 +1230,396 @@ function discoverAntigravityHost(opts) {
|
|
|
1183
1230
|
return null;
|
|
1184
1231
|
}
|
|
1185
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
|
+
}
|
|
1186
1618
|
// package.json
|
|
1187
1619
|
var package_default = {
|
|
1188
1620
|
name: "agentschat-mcp",
|
|
1189
1621
|
mcpName: "io.github.swswordholy-tech/agentschat-mcp",
|
|
1190
|
-
version: "0.36.
|
|
1622
|
+
version: "0.36.19",
|
|
1191
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.",
|
|
1192
1624
|
type: "module",
|
|
1193
1625
|
bin: {
|
|
@@ -1228,8 +1660,16 @@ var package_default = {
|
|
|
1228
1660
|
"chat",
|
|
1229
1661
|
"social-network",
|
|
1230
1662
|
"multi-agent",
|
|
1231
|
-
"real-time"
|
|
1663
|
+
"real-time",
|
|
1664
|
+
"dsh",
|
|
1665
|
+
"dsh-plugin",
|
|
1666
|
+
"deepseek-harness"
|
|
1232
1667
|
],
|
|
1668
|
+
dsh: {
|
|
1669
|
+
bundle: {
|
|
1670
|
+
patch: "./cordis.patch.yml"
|
|
1671
|
+
}
|
|
1672
|
+
},
|
|
1233
1673
|
author: "AgentsChat",
|
|
1234
1674
|
license: "Apache-2.0",
|
|
1235
1675
|
repository: {
|
|
@@ -1264,6 +1704,7 @@ var package_default = {
|
|
|
1264
1704
|
"src/profile-selection.ts",
|
|
1265
1705
|
"src/grok-bind.ts",
|
|
1266
1706
|
"src/session-bind.ts",
|
|
1707
|
+
"src/session-route.ts",
|
|
1267
1708
|
"src/tool-annotations.ts",
|
|
1268
1709
|
"src/identity-guard.ts",
|
|
1269
1710
|
"src/terms.ts",
|
|
@@ -1295,7 +1736,12 @@ var package_default = {
|
|
|
1295
1736
|
"scripts/example-url-wake-receiver.mjs",
|
|
1296
1737
|
"scripts/example-url-wake-ensure.sh",
|
|
1297
1738
|
"scripts/example-agy-mcp-wrapper.sh",
|
|
1298
|
-
"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"
|
|
1299
1745
|
]
|
|
1300
1746
|
};
|
|
1301
1747
|
|
|
@@ -1304,17 +1750,17 @@ import {
|
|
|
1304
1750
|
CallToolRequestSchema,
|
|
1305
1751
|
ListToolsRequestSchema
|
|
1306
1752
|
} from "@modelcontextprotocol/sdk/types.js";
|
|
1307
|
-
import { readFileSync as
|
|
1308
|
-
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";
|
|
1309
1755
|
|
|
1310
1756
|
// src/profile-store.ts
|
|
1311
|
-
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";
|
|
1312
1758
|
var defaultWarn2 = (m) => process.stderr.write(m);
|
|
1313
1759
|
function safeWriteProfile2(path, data, warn = defaultWarn2) {
|
|
1314
1760
|
const tmp = path + ".tmp";
|
|
1315
1761
|
try {
|
|
1316
|
-
if (
|
|
1317
|
-
|
|
1762
|
+
if (existsSync6(tmp))
|
|
1763
|
+
unlinkSync4(tmp);
|
|
1318
1764
|
} catch (e) {
|
|
1319
1765
|
warn(`[agentchat] WARNING: stale ${tmp} could not be removed: ${e}
|
|
1320
1766
|
`);
|
|
@@ -1328,7 +1774,7 @@ function safeWriteProfile2(path, data, warn = defaultWarn2) {
|
|
|
1328
1774
|
`);
|
|
1329
1775
|
}
|
|
1330
1776
|
try {
|
|
1331
|
-
const mode =
|
|
1777
|
+
const mode = statSync4(path).mode & 511;
|
|
1332
1778
|
if (mode !== 384) {
|
|
1333
1779
|
warn(`[agentchat] WARNING: ${path} is mode ${mode.toString(8)}, expected 600 — it holds your agent key. Fix: chmod 600 ${path}
|
|
1334
1780
|
`);
|
|
@@ -1421,10 +1867,10 @@ function expectedAgentIdViolation(expected, liveAgentId) {
|
|
|
1421
1867
|
}
|
|
1422
1868
|
|
|
1423
1869
|
// src/read-cursor.ts
|
|
1424
|
-
import { readFileSync as
|
|
1870
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync3 } from "fs";
|
|
1425
1871
|
function loadCursor(file, warn) {
|
|
1426
1872
|
try {
|
|
1427
|
-
return new Map(Object.entries(JSON.parse(
|
|
1873
|
+
return new Map(Object.entries(JSON.parse(readFileSync6(file, "utf-8"))));
|
|
1428
1874
|
} catch (e) {
|
|
1429
1875
|
if (e?.code !== "ENOENT") {
|
|
1430
1876
|
warn(`[agentchat] WARNING: could not read ${file} — resetting that state: ${e}
|
|
@@ -1454,83 +1900,16 @@ function flushCursor(state, persist) {
|
|
|
1454
1900
|
|
|
1455
1901
|
// src/server.ts
|
|
1456
1902
|
import { randomUUID } from "crypto";
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
class HeartbeatMonitor {
|
|
1465
|
-
deps;
|
|
1466
|
-
pingInterval;
|
|
1467
|
-
pongTimeout;
|
|
1468
|
-
connectTimeout;
|
|
1469
|
-
lastPong;
|
|
1470
|
-
timer = null;
|
|
1471
|
-
connectingSince = null;
|
|
1472
|
-
reconnecting = false;
|
|
1473
|
-
constructor(deps, pingInterval = 30000, pongTimeout = 90000, connectTimeout = 30000) {
|
|
1474
|
-
this.deps = deps;
|
|
1475
|
-
this.pingInterval = pingInterval;
|
|
1476
|
-
this.pongTimeout = pongTimeout;
|
|
1477
|
-
this.connectTimeout = connectTimeout;
|
|
1478
|
-
this.lastPong = Date.now();
|
|
1479
|
-
}
|
|
1480
|
-
receivedPong() {
|
|
1481
|
-
this.lastPong = Date.now();
|
|
1482
|
-
this.connectingSince = null;
|
|
1483
|
-
this.reconnecting = false;
|
|
1484
|
-
}
|
|
1485
|
-
start() {
|
|
1486
|
-
this.stop();
|
|
1487
|
-
this.lastPong = Date.now();
|
|
1488
|
-
this.connectingSince = null;
|
|
1489
|
-
this.reconnecting = false;
|
|
1490
|
-
this.timer = setInterval(() => this.tick(), this.pingInterval);
|
|
1491
|
-
}
|
|
1492
|
-
stop() {
|
|
1493
|
-
if (this.timer) {
|
|
1494
|
-
clearInterval(this.timer);
|
|
1495
|
-
this.timer = null;
|
|
1496
|
-
}
|
|
1497
|
-
}
|
|
1498
|
-
resetReconnecting() {
|
|
1499
|
-
this.reconnecting = false;
|
|
1500
|
-
}
|
|
1501
|
-
tick() {
|
|
1502
|
-
const state = this.deps.getReadyState();
|
|
1503
|
-
if (state === WS_OPEN) {
|
|
1504
|
-
this.connectingSince = null;
|
|
1505
|
-
if (Date.now() - this.lastPong > this.pongTimeout) {
|
|
1506
|
-
this.safeReconnect("pong timeout");
|
|
1507
|
-
return;
|
|
1508
|
-
}
|
|
1509
|
-
this.deps.sendPing();
|
|
1510
|
-
return;
|
|
1511
|
-
}
|
|
1512
|
-
if (state === WS_CONNECTING) {
|
|
1513
|
-
if (!this.connectingSince) {
|
|
1514
|
-
this.connectingSince = Date.now();
|
|
1515
|
-
} else if (Date.now() - this.connectingSince > this.connectTimeout) {
|
|
1516
|
-
this.connectingSince = null;
|
|
1517
|
-
this.safeReconnect("connect timeout");
|
|
1518
|
-
}
|
|
1519
|
-
return;
|
|
1520
|
-
}
|
|
1521
|
-
this.connectingSince = null;
|
|
1522
|
-
this.safeReconnect(state === WS_CLOSING ? "stuck closing" : "closed");
|
|
1523
|
-
}
|
|
1524
|
-
safeReconnect(reason) {
|
|
1525
|
-
if (this.reconnecting)
|
|
1526
|
-
return;
|
|
1527
|
-
this.reconnecting = true;
|
|
1528
|
-
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);
|
|
1529
1909
|
}
|
|
1910
|
+
process.env[key] = items.join(",");
|
|
1530
1911
|
}
|
|
1531
|
-
|
|
1532
|
-
// src/server.ts
|
|
1533
|
-
if (process.env.AGENTCHAT_NO_PROXY === "1") {
|
|
1912
|
+
if (process.env.AGENTCHAT_NO_PROXY === "1" && process.env.NODE_USE_ENV_PROXY !== "1") {
|
|
1534
1913
|
delete process.env.HTTP_PROXY;
|
|
1535
1914
|
delete process.env.HTTPS_PROXY;
|
|
1536
1915
|
delete process.env.http_proxy;
|
|
@@ -1573,16 +1952,15 @@ function parseArgs() {
|
|
|
1573
1952
|
}
|
|
1574
1953
|
var cliArgs = parseArgs();
|
|
1575
1954
|
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
1576
|
-
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
|
|
1577
1956
|
|
|
1578
|
-
Usage: claude mcp add agentschat -- npx -y agentschat-mcp
|
|
1957
|
+
Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
|
|
1579
1958
|
claude --dangerously-load-development-channels server:agentschat
|
|
1580
|
-
One MCP server entry per bot, each pinning --profile
|
|
1581
|
-
(not @latest, which drifts).
|
|
1959
|
+
One MCP server entry per bot, each pinning --profile.
|
|
1582
1960
|
|
|
1583
1961
|
Setup guide for every supported host:
|
|
1584
1962
|
Read skills/onboarding.md relative to this installed package root.
|
|
1585
|
-
Online
|
|
1963
|
+
Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
|
|
1586
1964
|
Newest release (first install): npx -y agentschat-mcp@latest --help
|
|
1587
1965
|
The guide selects Claude Code, Codex, OpenClaw, Hermes, Grok Bot, URL wake,
|
|
1588
1966
|
or the separately deployed dot remote MCP + Events integration.
|
|
@@ -1638,36 +2016,37 @@ Docs: https://github.com/swswordholy-tech/AgentsChatProtocol`);
|
|
|
1638
2016
|
process.exit(0);
|
|
1639
2017
|
}
|
|
1640
2018
|
var homeDir = process.env.HOME || process.env.USERPROFILE || ".";
|
|
1641
|
-
var configDir =
|
|
1642
|
-
var legacyConfigDir =
|
|
2019
|
+
var configDir = join6(homeDir, ".agentschat");
|
|
2020
|
+
var legacyConfigDir = join6(homeDir, ".agentchat");
|
|
1643
2021
|
var profileDirs = [configDir, legacyConfigDir];
|
|
1644
2022
|
var lockDir = resolveLockDir(homeDir, process.env);
|
|
1645
2023
|
var lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
|
|
1646
2024
|
var toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
|
|
1647
2025
|
var runtimeSession = detectRuntimeSession(process.env);
|
|
2026
|
+
var dshRouteWarned = false;
|
|
1648
2027
|
function profileNameToPaths(name) {
|
|
1649
2028
|
if (name.startsWith("~/"))
|
|
1650
|
-
return [
|
|
2029
|
+
return [join6(homeDir, name.slice(2))];
|
|
1651
2030
|
if (name.includes("/") || name.includes("\\"))
|
|
1652
2031
|
return [name];
|
|
1653
2032
|
name = name.replace(/\.json$/, "");
|
|
1654
2033
|
const safeName = name.replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
1655
|
-
return profileDirs.map((dir) =>
|
|
2034
|
+
return profileDirs.map((dir) => join6(dir, `${safeName}.json`));
|
|
1656
2035
|
}
|
|
1657
2036
|
function nameToPath(name) {
|
|
1658
2037
|
const candidates = profileNameToPaths(name);
|
|
1659
|
-
const nested =
|
|
1660
|
-
if (!name.includes("/") && !name.includes("\\") &&
|
|
2038
|
+
const nested = join6(configDir, "profiles", name.replace(/\.json$/, "") + ".json");
|
|
2039
|
+
if (!name.includes("/") && !name.includes("\\") && existsSync7(nested))
|
|
1661
2040
|
return nested;
|
|
1662
|
-
return candidates.find((path) =>
|
|
2041
|
+
return candidates.find((path) => existsSync7(path)) || candidates[0];
|
|
1663
2042
|
}
|
|
1664
2043
|
function listProfileFiles() {
|
|
1665
2044
|
const seen = new Set;
|
|
1666
2045
|
const profiles = [];
|
|
1667
|
-
for (const dir of [
|
|
2046
|
+
for (const dir of [join6(configDir, "profiles"), ...profileDirs]) {
|
|
1668
2047
|
let files = [];
|
|
1669
2048
|
try {
|
|
1670
|
-
files =
|
|
2049
|
+
files = readdirSync3(dir).filter((f) => f.endsWith(".json"));
|
|
1671
2050
|
} catch {}
|
|
1672
2051
|
for (const file of files) {
|
|
1673
2052
|
if (file === DEFAULT_GROK_BINDS_FILENAME || file === GROK_BINDS_META_FILENAME || file === DEFAULT_SESSION_BINDS_FILENAME || file === LEGACY_AGY_BINDS_FILENAME)
|
|
@@ -1676,7 +2055,7 @@ function listProfileFiles() {
|
|
|
1676
2055
|
if (seen.has(name))
|
|
1677
2056
|
continue;
|
|
1678
2057
|
seen.add(name);
|
|
1679
|
-
profiles.push({ name, path:
|
|
2058
|
+
profiles.push({ name, path: join6(dir, file) });
|
|
1680
2059
|
}
|
|
1681
2060
|
}
|
|
1682
2061
|
return profiles;
|
|
@@ -1701,9 +2080,9 @@ function resolveProfile() {
|
|
|
1701
2080
|
let binds = {};
|
|
1702
2081
|
if (!grokToken && conversationId) {
|
|
1703
2082
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
1704
|
-
if (
|
|
2083
|
+
if (existsSync7(bindPath)) {
|
|
1705
2084
|
try {
|
|
1706
|
-
const parsed = parseGrokBindsText(
|
|
2085
|
+
const parsed = parseGrokBindsText(readFileSync7(bindPath, "utf-8"));
|
|
1707
2086
|
binds = parsed.binds;
|
|
1708
2087
|
if (parsed.malformed) {
|
|
1709
2088
|
process.stderr.write(`[agentchat] WARNING: grok-binds file is malformed (${bindPath}); ignoring.
|
|
@@ -1738,7 +2117,7 @@ function resolveProfile() {
|
|
|
1738
2117
|
const boundProfile = sessionBinds[runtimeSession.sessionId];
|
|
1739
2118
|
if (boundProfile) {
|
|
1740
2119
|
const boundPath = nameToPath(boundProfile);
|
|
1741
|
-
if (
|
|
2120
|
+
if (existsSync7(boundPath)) {
|
|
1742
2121
|
process.stderr.write(`[agentchat] session-bind (${runtimeSession.runtime}): ${runtimeSession.sessionId} \u2192 profile "${boundProfile}"
|
|
1743
2122
|
`);
|
|
1744
2123
|
return { path: boundPath, source: "session-bind", declaredName: boundProfile };
|
|
@@ -1783,7 +2162,7 @@ if (hasToken && !explicitAgentId && profileSource === "default") {
|
|
|
1783
2162
|
process.exit(1);
|
|
1784
2163
|
}
|
|
1785
2164
|
var identity = decideIdentity({
|
|
1786
|
-
profileExists:
|
|
2165
|
+
profileExists: existsSync7(profileFile),
|
|
1787
2166
|
source: profileSource,
|
|
1788
2167
|
profileFile,
|
|
1789
2168
|
cliName: cliArgs.name,
|
|
@@ -1794,7 +2173,7 @@ var identity = decideIdentity({
|
|
|
1794
2173
|
});
|
|
1795
2174
|
function readIdentityProfile(file) {
|
|
1796
2175
|
try {
|
|
1797
|
-
return JSON.parse(
|
|
2176
|
+
return JSON.parse(readFileSync7(file, "utf-8"));
|
|
1798
2177
|
} catch {
|
|
1799
2178
|
throw new Error(`Cannot read identity profile at ${file}. Repair its JSON/permissions or select --profile <valid-name>.`);
|
|
1800
2179
|
}
|
|
@@ -1896,7 +2275,7 @@ if (identity.mode === "profile") {
|
|
|
1896
2275
|
`);
|
|
1897
2276
|
process.exit(1);
|
|
1898
2277
|
}
|
|
1899
|
-
|
|
2278
|
+
mkdirSync3(dirname(profileFile), { recursive: true });
|
|
1900
2279
|
safeWriteProfile2(profileFile, profile);
|
|
1901
2280
|
process.stderr.write(`[agentchat] Profile saved: ${profileFile}
|
|
1902
2281
|
`);
|
|
@@ -1995,10 +2374,10 @@ if (!anonymousMode && AGENT_ID && !cliArgs.registerOnly && !toolOnlyMode) {
|
|
|
1995
2374
|
}
|
|
1996
2375
|
}
|
|
1997
2376
|
var identityGateMessage = "";
|
|
1998
|
-
var identityGuardFile =
|
|
2377
|
+
var identityGuardFile = join6(configDir, IDENTITY_GUARD_FILENAME);
|
|
1999
2378
|
function persistGuardRecord(rec) {
|
|
2000
2379
|
try {
|
|
2001
|
-
|
|
2380
|
+
mkdirSync3(configDir, { recursive: true });
|
|
2002
2381
|
safeWriteProfile2(identityGuardFile, rec);
|
|
2003
2382
|
} catch {}
|
|
2004
2383
|
}
|
|
@@ -2014,7 +2393,7 @@ function confirmLiveIdentityTrusted() {
|
|
|
2014
2393
|
}
|
|
2015
2394
|
var guardRecord = (() => {
|
|
2016
2395
|
try {
|
|
2017
|
-
return parseGuardRecord(
|
|
2396
|
+
return parseGuardRecord(readFileSync7(identityGuardFile, "utf-8"));
|
|
2018
2397
|
} catch {
|
|
2019
2398
|
return emptyGuardRecord();
|
|
2020
2399
|
}
|
|
@@ -2081,29 +2460,38 @@ var ws = null;
|
|
|
2081
2460
|
var TYPING_HEARTBEAT_MS = 2000;
|
|
2082
2461
|
var TYPING_HEARTBEAT_MAX_MS = 120000;
|
|
2083
2462
|
var typingHeartbeats = new Map;
|
|
2084
|
-
function
|
|
2085
|
-
|
|
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) {
|
|
2086
2470
|
try {
|
|
2087
|
-
|
|
2471
|
+
targetWs.send(JSON.stringify({ type: "typing", channel_id: channelId, sender_id: senderId, cross_pod: true }));
|
|
2088
2472
|
} catch {}
|
|
2089
2473
|
}
|
|
2090
2474
|
}
|
|
2091
|
-
function startTypingHeartbeat(channelId) {
|
|
2475
|
+
function startTypingHeartbeat(channelId, slot = activeSlot) {
|
|
2092
2476
|
if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0")
|
|
2093
2477
|
return;
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
const
|
|
2098
|
-
|
|
2099
|
-
}
|
|
2100
|
-
|
|
2101
|
-
|
|
2102
|
-
|
|
2103
|
-
|
|
2104
|
-
|
|
2105
|
-
|
|
2106
|
-
|
|
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
|
+
}
|
|
2107
2495
|
}
|
|
2108
2496
|
function stopAllTypingHeartbeats() {
|
|
2109
2497
|
for (const h of typingHeartbeats.values()) {
|
|
@@ -2115,6 +2503,8 @@ function stopAllTypingHeartbeats() {
|
|
|
2115
2503
|
var sessionId = null;
|
|
2116
2504
|
var shuttingDown = false;
|
|
2117
2505
|
var transport = null;
|
|
2506
|
+
var profileSlots = new Map;
|
|
2507
|
+
var activeSlot = null;
|
|
2118
2508
|
var debugLogsEnabled = /^(1|true|yes|debug)$/i.test(process.env.AGENTSCHAT_MCP_DEBUG || process.env.AGENTCHAT_DEBUG || "");
|
|
2119
2509
|
var defaultLogRateMs = Math.max(1000, Number(process.env.AGENTSCHAT_MCP_LOG_RATE_MS || 60000));
|
|
2120
2510
|
var rateLimitedLogState = new Map;
|
|
@@ -2312,10 +2702,10 @@ var TOOL_GROUPS = [
|
|
|
2312
2702
|
},
|
|
2313
2703
|
{
|
|
2314
2704
|
name: "media",
|
|
2315
|
-
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).",
|
|
2316
2706
|
tags: ["chat", "media"],
|
|
2317
|
-
estimated_tokens:
|
|
2318
|
-
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"]
|
|
2319
2709
|
}
|
|
2320
2710
|
];
|
|
2321
2711
|
var TOOL_NAME_TO_GROUP = new Map;
|
|
@@ -2382,6 +2772,24 @@ var ALL_TOOL_DEFS = [
|
|
|
2382
2772
|
required: ["chat_id"]
|
|
2383
2773
|
}
|
|
2384
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
|
+
},
|
|
2385
2793
|
{
|
|
2386
2794
|
name: "send_voice",
|
|
2387
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`.',
|
|
@@ -3221,9 +3629,13 @@ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: annotateT
|
|
|
3221
3629
|
var TOOL_INPUT_SCHEMAS = new Map(ALL_TOOL_DEFS.map((t) => [t.name, t.inputSchema]));
|
|
3222
3630
|
var MEMBER_CACHE_TTL_MS = 5 * 60000;
|
|
3223
3631
|
var memberCache = new Map;
|
|
3632
|
+
function memberCacheKey(chatId) {
|
|
3633
|
+
return `${AGENT_ID || "anon"}:${chatId}`;
|
|
3634
|
+
}
|
|
3224
3635
|
async function fetchChannelMembers(chatId) {
|
|
3225
3636
|
const now = Date.now();
|
|
3226
|
-
const
|
|
3637
|
+
const key = memberCacheKey(chatId);
|
|
3638
|
+
const hit = memberCache.get(key);
|
|
3227
3639
|
if (hit && now - hit.at < MEMBER_CACHE_TTL_MS)
|
|
3228
3640
|
return hit.members;
|
|
3229
3641
|
try {
|
|
@@ -3234,12 +3646,32 @@ async function fetchChannelMembers(chatId) {
|
|
|
3234
3646
|
return hit?.members || [];
|
|
3235
3647
|
const body = await r.json();
|
|
3236
3648
|
const members = Array.isArray(body?.members) ? body.members : [];
|
|
3237
|
-
|
|
3649
|
+
const sameOwnerDirect = body?.same_owner_direct === true;
|
|
3650
|
+
memberCache.set(key, { at: now, members, sameOwnerDirect });
|
|
3238
3651
|
return members;
|
|
3239
3652
|
} catch {
|
|
3240
3653
|
return hit?.members || [];
|
|
3241
3654
|
}
|
|
3242
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
|
+
}
|
|
3243
3675
|
async function resolveBareMentions(chatId, text) {
|
|
3244
3676
|
if (!text || !text.includes("@"))
|
|
3245
3677
|
return text;
|
|
@@ -3324,25 +3756,32 @@ var MEDIA_MIME_BY_EXT = {
|
|
|
3324
3756
|
heic: "image/heic",
|
|
3325
3757
|
heif: "image/heif",
|
|
3326
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",
|
|
3327
3764
|
m4a: "audio/mp4",
|
|
3328
|
-
mp4: "audio/mp4",
|
|
3329
3765
|
aac: "audio/aac",
|
|
3330
3766
|
mp3: "audio/mpeg",
|
|
3331
3767
|
wav: "audio/wav",
|
|
3332
3768
|
weba: "audio/webm",
|
|
3333
|
-
webm: "audio/webm",
|
|
3334
3769
|
ogg: "audio/ogg",
|
|
3335
3770
|
oga: "audio/ogg"
|
|
3336
3771
|
};
|
|
3337
|
-
function mimeFromPath(p) {
|
|
3772
|
+
function mimeFromPath(p, kindHint) {
|
|
3338
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";
|
|
3339
3778
|
return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
|
|
3340
3779
|
}
|
|
3341
|
-
async function uploadLocalFile(path) {
|
|
3342
|
-
if (!
|
|
3780
|
+
async function uploadLocalFile(path, kindHint) {
|
|
3781
|
+
if (!existsSync7(path))
|
|
3343
3782
|
throw new Error(`file not found: ${path}`);
|
|
3344
|
-
const mime = mimeFromPath(path);
|
|
3345
|
-
const buf =
|
|
3783
|
+
const mime = mimeFromPath(path, kindHint);
|
|
3784
|
+
const buf = readFileSync7(path);
|
|
3346
3785
|
const name = path.split("/").pop() || "upload";
|
|
3347
3786
|
const form = new FormData;
|
|
3348
3787
|
form.append("file", new Blob([new Uint8Array(buf)], { type: mime }), name);
|
|
@@ -3403,13 +3842,13 @@ async function sendMediaMessage(kind, args) {
|
|
|
3403
3842
|
mime = d.mime || "audio/mpeg";
|
|
3404
3843
|
ttsDuration = typeof d.duration_ms === "number" ? d.duration_ms : undefined;
|
|
3405
3844
|
} else if (path) {
|
|
3406
|
-
const up = await uploadLocalFile(path);
|
|
3845
|
+
const up = await uploadLocalFile(path, kind);
|
|
3407
3846
|
finalUrl = up.url;
|
|
3408
3847
|
mime = up.mime;
|
|
3409
3848
|
size = up.size;
|
|
3410
3849
|
} else {
|
|
3411
3850
|
finalUrl = url;
|
|
3412
|
-
mime = mimeFromPath(finalUrl);
|
|
3851
|
+
mime = mimeFromPath(finalUrl, kind);
|
|
3413
3852
|
}
|
|
3414
3853
|
const attachment = { type: kind, url: finalUrl };
|
|
3415
3854
|
if (mime && mime !== "application/octet-stream")
|
|
@@ -3421,6 +3860,15 @@ async function sendMediaMessage(kind, args) {
|
|
|
3421
3860
|
attachment.width = args.width;
|
|
3422
3861
|
if (typeof args.height === "number")
|
|
3423
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;
|
|
3424
3872
|
} else {
|
|
3425
3873
|
const dur = typeof args.duration_ms === "number" ? args.duration_ms : ttsDuration;
|
|
3426
3874
|
if (dur != null)
|
|
@@ -3430,7 +3878,7 @@ async function sendMediaMessage(kind, args) {
|
|
|
3430
3878
|
else if (text)
|
|
3431
3879
|
attachment.transcript = text;
|
|
3432
3880
|
}
|
|
3433
|
-
const content = caption ?
|
|
3881
|
+
const content = caption ? await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, caption)) : "";
|
|
3434
3882
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages`, {
|
|
3435
3883
|
method: "POST",
|
|
3436
3884
|
headers: { "Content-Type": "application/json", Authorization: `Bearer ${TOKEN}` },
|
|
@@ -3446,6 +3894,7 @@ async function sendMediaMessage(kind, args) {
|
|
|
3446
3894
|
}
|
|
3447
3895
|
}
|
|
3448
3896
|
HANDLERS.set("send_image", (args) => sendMediaMessage("image", args));
|
|
3897
|
+
HANDLERS.set("send_video", (args) => sendMediaMessage("video", args));
|
|
3449
3898
|
HANDLERS.set("send_voice", (args) => sendMediaMessage("audio", args));
|
|
3450
3899
|
HANDLERS.set("list_voices", async (args) => {
|
|
3451
3900
|
const { language } = args || {};
|
|
@@ -3529,10 +3978,10 @@ HANDLERS.set("transcribe", async (args) => {
|
|
|
3529
3978
|
});
|
|
3530
3979
|
function loadGrokBinds() {
|
|
3531
3980
|
const bindPath = resolveGrokBindsPath(configDir, process.env.AGENTCHAT_GROK_BINDS);
|
|
3532
|
-
if (!
|
|
3981
|
+
if (!existsSync7(bindPath))
|
|
3533
3982
|
return {};
|
|
3534
3983
|
try {
|
|
3535
|
-
return parseGrokBindsText(
|
|
3984
|
+
return parseGrokBindsText(readFileSync7(bindPath, "utf-8")).binds;
|
|
3536
3985
|
} catch {
|
|
3537
3986
|
return {};
|
|
3538
3987
|
}
|
|
@@ -3546,59 +3995,208 @@ function currentGrokBindApplicability(binds) {
|
|
|
3546
3995
|
binds
|
|
3547
3996
|
});
|
|
3548
3997
|
}
|
|
3549
|
-
|
|
3550
|
-
|
|
3551
|
-
if (
|
|
3552
|
-
|
|
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
|
+
};
|
|
3553
4076
|
}
|
|
3554
|
-
|
|
3555
|
-
|
|
3556
|
-
|
|
3557
|
-
|
|
3558
|
-
|
|
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;
|
|
3559
4099
|
}
|
|
3560
|
-
|
|
3561
|
-
|
|
3562
|
-
|
|
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;
|
|
3563
4111
|
}
|
|
3564
|
-
if (
|
|
3565
|
-
|
|
4112
|
+
if (slot.reconnectTimer) {
|
|
4113
|
+
clearTimeout(slot.reconnectTimer);
|
|
4114
|
+
slot.reconnectTimer = null;
|
|
4115
|
+
}
|
|
4116
|
+
if (slot.ws) {
|
|
4117
|
+
slot.ws.onclose = null;
|
|
3566
4118
|
try {
|
|
3567
|
-
ws.close();
|
|
4119
|
+
slot.ws.close();
|
|
3568
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;
|
|
3569
4131
|
ws = null;
|
|
4132
|
+
sessionId = null;
|
|
3570
4133
|
}
|
|
3571
|
-
|
|
3572
|
-
|
|
3573
|
-
|
|
3574
|
-
|
|
3575
|
-
|
|
3576
|
-
|
|
3577
|
-
|
|
3578
|
-
|
|
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;
|
|
3579
4153
|
if (bindSessionId && bindSessionId.trim()) {
|
|
3580
4154
|
const cleanSid = bindSessionId.trim();
|
|
3581
|
-
const isAgyEnv = process.env.__CFBundleIdentifier === "com.google.antigravity" || Boolean(process.env.AGY_BROWSER_WS_URL) || Boolean(discoverAntigravityHost());
|
|
3582
|
-
|
|
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 = {
|
|
3583
4157
|
sessionId: cleanSid,
|
|
3584
|
-
runtime:
|
|
3585
|
-
...
|
|
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 } : {}
|
|
3586
4160
|
};
|
|
3587
4161
|
} else {
|
|
3588
4162
|
const existingBoundSid = findBoundSessionForProfile(configDir, targetProfName);
|
|
3589
|
-
if (existingBoundSid) {
|
|
3590
|
-
|
|
4163
|
+
if (existingBoundSid && !targetSession?.sessionId) {
|
|
4164
|
+
targetSession = {
|
|
3591
4165
|
sessionId: existingBoundSid,
|
|
3592
|
-
runtime:
|
|
3593
|
-
...runtimeSession?.workspacePath ? { workspacePath: runtimeSession.workspacePath } : {}
|
|
4166
|
+
runtime: /^[0-9a-f-]{36}$/i.test(existingBoundSid) ? "antigravity" : existingBoundSid.startsWith("sess_") ? "zcode" : existingBoundSid.startsWith("session-") ? "dsh" : "custom"
|
|
3594
4167
|
};
|
|
3595
|
-
} else if (!
|
|
4168
|
+
} else if (!targetSession?.sessionId) {
|
|
3596
4169
|
const agyHost = discoverAntigravityHost();
|
|
3597
4170
|
if (agyHost && agyHost.openConversations.length === 1) {
|
|
3598
|
-
|
|
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 });
|
|
3599
4184
|
}
|
|
4185
|
+
} else if (!existingSid && profileSlots.size === 1) {
|
|
4186
|
+
teardownSlot(existingSlot, { releaseLock: true });
|
|
3600
4187
|
}
|
|
3601
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);
|
|
3602
4200
|
if (!toolOnlyMode) {
|
|
3603
4201
|
acquireAgentLock({
|
|
3604
4202
|
lockDir,
|
|
@@ -3615,44 +4213,28 @@ function applyIdentityFromProfile(newProfile, targetFile, bindSessionId) {
|
|
|
3615
4213
|
}
|
|
3616
4214
|
guardRecord = advanceGuardRecord(guardRecord, { agentId: AGENT_ID, source: "switch_profile", ...profileNameFromPath(targetFile) ? { declaredName: profileNameFromPath(targetFile) } : {} }, new Date().toISOString(), true);
|
|
3617
4215
|
persistGuardRecord(guardRecord);
|
|
3618
|
-
wsReconnectAttempt = 0;
|
|
3619
4216
|
if (!toolOnlyMode) {
|
|
3620
|
-
heartbeat.start();
|
|
3621
|
-
connectWS();
|
|
4217
|
+
newSlot.heartbeat.start();
|
|
4218
|
+
connectWS(newSlot);
|
|
3622
4219
|
}
|
|
3623
4220
|
}
|
|
3624
4221
|
function disconnectCurrentProfile(opts) {
|
|
3625
|
-
const
|
|
3626
|
-
const
|
|
3627
|
-
|
|
3628
|
-
|
|
3629
|
-
if (
|
|
3630
|
-
|
|
3631
|
-
|
|
3632
|
-
|
|
3633
|
-
|
|
3634
|
-
|
|
3635
|
-
|
|
3636
|
-
}
|
|
3637
|
-
if (ws) {
|
|
3638
|
-
ws.onclose = null;
|
|
3639
|
-
try {
|
|
3640
|
-
ws.close();
|
|
3641
|
-
} catch {}
|
|
3642
|
-
ws = null;
|
|
3643
|
-
}
|
|
3644
|
-
if (prevAgentId) {
|
|
3645
|
-
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
|
+
}
|
|
3646
4233
|
}
|
|
3647
|
-
if (!opts?.keepBinding &&
|
|
3648
|
-
removeSessionBind(configDir,
|
|
4234
|
+
if (!opts?.keepBinding && sidToRemove) {
|
|
4235
|
+
removeSessionBind(configDir, sidToRemove);
|
|
3649
4236
|
}
|
|
3650
|
-
|
|
3651
|
-
AGENT_ID = "";
|
|
3652
|
-
TOKEN = "";
|
|
3653
|
-
profile = {};
|
|
3654
|
-
activeProfileFile = null;
|
|
3655
|
-
anonymousMode = true;
|
|
4237
|
+
setAnonymousCallerState(runtimeSession);
|
|
3656
4238
|
return { prevAgentId, prevProfileName };
|
|
3657
4239
|
}
|
|
3658
4240
|
function formatProfileList() {
|
|
@@ -3662,13 +4244,15 @@ function formatProfileList() {
|
|
|
3662
4244
|
const lines = profileEntries.map((entry) => {
|
|
3663
4245
|
let entryAgentId = "";
|
|
3664
4246
|
try {
|
|
3665
|
-
const parsed = JSON.parse(
|
|
4247
|
+
const parsed = JSON.parse(readFileSync7(entry.path, "utf-8"));
|
|
3666
4248
|
if (typeof parsed?.agent_id === "string")
|
|
3667
4249
|
entryAgentId = parsed.agent_id;
|
|
3668
4250
|
} catch {}
|
|
3669
4251
|
const isCurrent = current && (entry.name === current || entryAgentId === current) || currentProfileName && entry.name === currentProfileName;
|
|
3670
4252
|
const lock = entryAgentId ? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid }) : { locked: false };
|
|
3671
|
-
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}` : ""}]` : "";
|
|
3672
4256
|
return `${isCurrent ? "\u2192 " : " "}${entry.name}${statusSuffix}`;
|
|
3673
4257
|
});
|
|
3674
4258
|
return `Current: ${current || "(anonymous / disconnected)"}
|
|
@@ -3710,10 +4294,10 @@ async function registerAndConnectProfile(displayName, bindSessionId) {
|
|
|
3710
4294
|
};
|
|
3711
4295
|
const targetFile = nameToPath(cleanName);
|
|
3712
4296
|
validateIdentityProfile(newProfile, targetFile);
|
|
3713
|
-
|
|
4297
|
+
mkdirSync3(dirname(targetFile), { recursive: true });
|
|
3714
4298
|
safeWriteProfile2(targetFile, newProfile);
|
|
3715
4299
|
const defaultProfileFile = nameToPath("profile");
|
|
3716
|
-
if (!
|
|
4300
|
+
if (!existsSync7(defaultProfileFile)) {
|
|
3717
4301
|
safeWriteProfile2(defaultProfileFile, newProfile);
|
|
3718
4302
|
}
|
|
3719
4303
|
applyIdentityFromProfile(newProfile, targetFile, bindSessionId);
|
|
@@ -3770,7 +4354,7 @@ async function handleProfileSwitchOrConnect(args) {
|
|
|
3770
4354
|
return { content: [{ type: "text", text: switchGate.message }], isError: true };
|
|
3771
4355
|
}
|
|
3772
4356
|
const targetFile = nameToPath(profile_name);
|
|
3773
|
-
if (!
|
|
4357
|
+
if (!existsSync7(targetFile)) {
|
|
3774
4358
|
if (register) {
|
|
3775
4359
|
return await registerAndConnectProfile(profile_name, explicitSessionId);
|
|
3776
4360
|
}
|
|
@@ -3834,7 +4418,7 @@ function ensureGrokBoundIdentity() {
|
|
|
3834
4418
|
if (!boundName)
|
|
3835
4419
|
return;
|
|
3836
4420
|
const boundPath = nameToPath(boundName);
|
|
3837
|
-
if (!
|
|
4421
|
+
if (!existsSync7(boundPath))
|
|
3838
4422
|
return;
|
|
3839
4423
|
let boundProfile;
|
|
3840
4424
|
try {
|
|
@@ -3855,45 +4439,153 @@ function ensureGrokBoundIdentity() {
|
|
|
3855
4439
|
`);
|
|
3856
4440
|
applyIdentityFromProfile(boundProfile, boundPath);
|
|
3857
4441
|
}
|
|
3858
|
-
|
|
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) => {
|
|
3859
4516
|
let { name, arguments: args } = request.params;
|
|
3860
4517
|
let viaExtendedCompat = false;
|
|
3861
4518
|
try {
|
|
3862
4519
|
const rawMeta = request.params?._meta;
|
|
3863
|
-
const
|
|
3864
|
-
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
3870
|
-
|
|
3871
|
-
|
|
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)) {
|
|
3872
4542
|
try {
|
|
3873
4543
|
const candidate = readIdentityProfile(boundPath);
|
|
3874
4544
|
const lock = checkAgentLock({
|
|
3875
4545
|
lockDir,
|
|
3876
4546
|
agentId: candidate?.agent_id,
|
|
3877
|
-
currentSessionId:
|
|
4547
|
+
currentSessionId: callerSession.sessionId,
|
|
3878
4548
|
lockOwnerPid
|
|
3879
4549
|
});
|
|
3880
4550
|
if (!lock.locked) {
|
|
3881
|
-
applyIdentityFromProfile(candidate, boundPath,
|
|
4551
|
+
applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
|
|
4552
|
+
} else if (isPerCallSession) {
|
|
4553
|
+
setAnonymousCallerState(callerSession);
|
|
3882
4554
|
}
|
|
3883
4555
|
} catch {}
|
|
4556
|
+
} else if (isPerCallSession) {
|
|
4557
|
+
setAnonymousCallerState(callerSession);
|
|
3884
4558
|
}
|
|
4559
|
+
} else if (isPerCallSession) {
|
|
4560
|
+
setAnonymousCallerState(callerSession);
|
|
3885
4561
|
}
|
|
3886
|
-
} else
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
|
|
3895
|
-
if (
|
|
3896
|
-
|
|
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);
|
|
3897
4589
|
}
|
|
3898
4590
|
}
|
|
3899
4591
|
}
|
|
@@ -4123,7 +4815,7 @@ ${a.body || ""}`;
|
|
|
4123
4815
|
const currentVersion = Number(meta.version ?? 0);
|
|
4124
4816
|
let cachedVersion = null;
|
|
4125
4817
|
try {
|
|
4126
|
-
cachedVersion = Number(JSON.parse(
|
|
4818
|
+
cachedVersion = Number(JSON.parse(readFileSync7(pMeta, "utf8")).version);
|
|
4127
4819
|
} catch {}
|
|
4128
4820
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
4129
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.` }] };
|
|
@@ -4132,7 +4824,7 @@ ${a.body || ""}`;
|
|
|
4132
4824
|
if (!bodyR.ok)
|
|
4133
4825
|
return { content: [{ type: "text", text: `sync_skill (personal): body fetch failed (${bodyR.status})` }], isError: true };
|
|
4134
4826
|
const doc = JSON.parse(await bodyR.text());
|
|
4135
|
-
|
|
4827
|
+
mkdirSync3(dirname(pMd), { recursive: true });
|
|
4136
4828
|
writeFileSync4(pMd, String(doc?.body_markdown ?? ""));
|
|
4137
4829
|
writeFileSync4(pMeta, JSON.stringify({ version: currentVersion, name: a.name, syncedAt: new Date().toISOString() }));
|
|
4138
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.` }] };
|
|
@@ -4157,7 +4849,7 @@ ${a.body || ""}`;
|
|
|
4157
4849
|
const currentVersion = Number(meta.version ?? 0);
|
|
4158
4850
|
let cachedVersion = null;
|
|
4159
4851
|
try {
|
|
4160
|
-
cachedVersion = Number(JSON.parse(
|
|
4852
|
+
cachedVersion = Number(JSON.parse(readFileSync7(metaPath, "utf8")).version);
|
|
4161
4853
|
} catch {}
|
|
4162
4854
|
if (cachedVersion !== null && cachedVersion === currentVersion) {
|
|
4163
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.` }] };
|
|
@@ -4167,7 +4859,7 @@ ${a.body || ""}`;
|
|
|
4167
4859
|
return { content: [{ type: "text", text: `sync_skill: fetch body failed (${docR.status})` }], isError: true };
|
|
4168
4860
|
const doc = JSON.parse(await docR.text());
|
|
4169
4861
|
const body = String(doc?.body_markdown ?? doc?.bodyMarkdown ?? "");
|
|
4170
|
-
|
|
4862
|
+
mkdirSync3(dirname(mdPath), { recursive: true });
|
|
4171
4863
|
writeFileSync4(mdPath, body);
|
|
4172
4864
|
writeFileSync4(metaPath, JSON.stringify({ version: currentVersion, title: doc?.title, doc_id: a.doc_id, chat_id: a.chat_id, syncedAt: new Date().toISOString() }));
|
|
4173
4865
|
const was = cachedVersion === null ? "missing" : `stale v${cachedVersion}`;
|
|
@@ -4247,7 +4939,7 @@ ${a.body || ""}`;
|
|
|
4247
4939
|
if (name === "reply") {
|
|
4248
4940
|
const { chat_id, text: rawText } = args;
|
|
4249
4941
|
stopTypingHeartbeat(chat_id);
|
|
4250
|
-
const text =
|
|
4942
|
+
const text = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawText));
|
|
4251
4943
|
try {
|
|
4252
4944
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages`, {
|
|
4253
4945
|
method: "POST",
|
|
@@ -4299,7 +4991,7 @@ ${a.body || ""}`;
|
|
|
4299
4991
|
}
|
|
4300
4992
|
if (name === "thread_reply") {
|
|
4301
4993
|
const { chat_id, parent_id, text: rawText } = args;
|
|
4302
|
-
const text =
|
|
4994
|
+
const text = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawText));
|
|
4303
4995
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
4304
4996
|
ws.send(JSON.stringify({
|
|
4305
4997
|
type: "thread_reply",
|
|
@@ -4335,7 +5027,7 @@ ${a.body || ""}`;
|
|
|
4335
5027
|
return { content: [{ type: "text", text: "Error: new_content (string) required" }] };
|
|
4336
5028
|
}
|
|
4337
5029
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
4338
|
-
const new_content =
|
|
5030
|
+
const new_content = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawNewContent));
|
|
4339
5031
|
ws.send(JSON.stringify({
|
|
4340
5032
|
type: "edit_message",
|
|
4341
5033
|
message_id,
|
|
@@ -4624,9 +5316,11 @@ ${brief}` }] };
|
|
|
4624
5316
|
body: "{}"
|
|
4625
5317
|
});
|
|
4626
5318
|
if (r.ok) {
|
|
4627
|
-
|
|
4628
|
-
|
|
4629
|
-
|
|
5319
|
+
if (activeSlot) {
|
|
5320
|
+
activeSlot.knownChannels.delete(chat_id);
|
|
5321
|
+
if (activeSlot.lastSeenMessageTs.delete(chat_id))
|
|
5322
|
+
scheduleSlotLastSeenMessageTsSave(activeSlot);
|
|
5323
|
+
}
|
|
4630
5324
|
const data = await r.json().catch(() => ({}));
|
|
4631
5325
|
if (data.note === "not a member") {
|
|
4632
5326
|
return { content: [{ type: "text", text: `Already not a member of ${chat_id.slice(0, 8)}` }] };
|
|
@@ -4642,9 +5336,11 @@ ${brief}` }] };
|
|
|
4642
5336
|
try {
|
|
4643
5337
|
ws.send(JSON.stringify({ type: "leave_channel", channel_id: chat_id, agent_id: AGENT_ID }));
|
|
4644
5338
|
} catch {}
|
|
4645
|
-
|
|
4646
|
-
|
|
4647
|
-
|
|
5339
|
+
if (activeSlot) {
|
|
5340
|
+
activeSlot.knownChannels.delete(chat_id);
|
|
5341
|
+
if (activeSlot.lastSeenMessageTs.delete(chat_id))
|
|
5342
|
+
scheduleSlotLastSeenMessageTsSave(activeSlot);
|
|
5343
|
+
}
|
|
4648
5344
|
return { content: [{ type: "text", text: `Leave sent via WS (REST unreachable: ${String(e?.message || e).slice(0, 60)})` }] };
|
|
4649
5345
|
}
|
|
4650
5346
|
return { content: [{ type: "text", text: `Leave failed \u2014 no connectivity` }] };
|
|
@@ -4984,6 +5680,15 @@ ${list}` }] };
|
|
|
4984
5680
|
const dim = a.width && a.height ? ` ${a.width}\xD7${a.height}` : "";
|
|
4985
5681
|
line += `
|
|
4986
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
|
+
}
|
|
4987
5692
|
} else {
|
|
4988
5693
|
line += `
|
|
4989
5694
|
\uD83D\uDCCE ${a.type || "file"}: ${a.url}`;
|
|
@@ -5396,8 +6101,9 @@ ${list}` }] };
|
|
|
5396
6101
|
} catch (e) {
|
|
5397
6102
|
return { content: [{ type: "text", text: `${name} failed: ${String(e?.message || e).slice(0, 300)}` }], isError: true };
|
|
5398
6103
|
}
|
|
5399
|
-
}
|
|
5400
|
-
|
|
6104
|
+
};
|
|
6105
|
+
server.setRequestHandler(CallToolRequestSchema, (request) => serializeCall(() => handleToolCall(request)));
|
|
6106
|
+
var mentionTsFile = join6(configDir, `mention-ts-${AGENT_ID}.json`);
|
|
5401
6107
|
function loadMentionTimestamps() {
|
|
5402
6108
|
return loadCursor(mentionTsFile, safeStderrWrite);
|
|
5403
6109
|
}
|
|
@@ -5405,32 +6111,10 @@ function saveMentionTimestamps(m) {
|
|
|
5405
6111
|
persistCursor(mentionTsFile, m, safeStderrWrite);
|
|
5406
6112
|
}
|
|
5407
6113
|
var lastMentionTimestamp = loadMentionTimestamps();
|
|
5408
|
-
var lastSeenMessageTsFile = join4(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
|
|
5409
|
-
function loadLastSeenMessageTs() {
|
|
5410
|
-
return loadCursor(lastSeenMessageTsFile, safeStderrWrite);
|
|
5411
|
-
}
|
|
5412
|
-
var lastSeenMessageTs = loadLastSeenMessageTs();
|
|
5413
|
-
var cursorFlushIntervalMs = Math.max(500, Number(process.env.AGENTSCHAT_MCP_CURSOR_FLUSH_MS || 5000));
|
|
5414
|
-
var cursorState = { dirty: false };
|
|
5415
|
-
var lastSeenMessageTsTimer = null;
|
|
5416
6114
|
function flushLastSeenMessageTs() {
|
|
5417
|
-
|
|
5418
|
-
|
|
5419
|
-
if (lastSeenMessageTsTimer) {
|
|
5420
|
-
clearTimeout(lastSeenMessageTsTimer);
|
|
5421
|
-
lastSeenMessageTsTimer = null;
|
|
6115
|
+
for (const slot of profileSlots.values()) {
|
|
6116
|
+
flushSlotLastSeenMessageTs(slot);
|
|
5422
6117
|
}
|
|
5423
|
-
flushCursor(cursorState, () => persistCursor(lastSeenMessageTsFile, lastSeenMessageTs, safeStderrWrite));
|
|
5424
|
-
}
|
|
5425
|
-
function scheduleLastSeenMessageTsSave() {
|
|
5426
|
-
cursorState.dirty = true;
|
|
5427
|
-
if (lastSeenMessageTsTimer)
|
|
5428
|
-
return;
|
|
5429
|
-
lastSeenMessageTsTimer = setTimeout(() => {
|
|
5430
|
-
lastSeenMessageTsTimer = null;
|
|
5431
|
-
flushLastSeenMessageTs();
|
|
5432
|
-
}, cursorFlushIntervalMs);
|
|
5433
|
-
lastSeenMessageTsTimer.unref?.();
|
|
5434
6118
|
}
|
|
5435
6119
|
function normalizeChannelDocLevel(level) {
|
|
5436
6120
|
if (typeof level === "number" && Number.isInteger(level) && level >= 1 && level <= 4) {
|
|
@@ -5566,46 +6250,40 @@ function clearFinishedHiddenIdentityGamesFromMessage(data) {
|
|
|
5566
6250
|
}
|
|
5567
6251
|
}
|
|
5568
6252
|
}
|
|
5569
|
-
var messageDedup = new MessageDedup;
|
|
5570
6253
|
function deliverySource(data) {
|
|
5571
6254
|
return typeof data?.__source === "string" ? data.__source : "live";
|
|
5572
6255
|
}
|
|
5573
|
-
function recordOrSkipDeliveredMessage(data) {
|
|
6256
|
+
function recordOrSkipDeliveredMessage(data, slot = activeSlot) {
|
|
5574
6257
|
const key = messageDedupKey(data);
|
|
5575
|
-
if (!key)
|
|
6258
|
+
if (!key || !slot)
|
|
5576
6259
|
return false;
|
|
5577
|
-
const skip = messageDedup.recordOrSkip(key);
|
|
6260
|
+
const skip = slot.messageDedup.recordOrSkip(key);
|
|
5578
6261
|
if (skip) {
|
|
5579
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)}
|
|
5580
6263
|
`);
|
|
5581
6264
|
}
|
|
5582
6265
|
return skip;
|
|
5583
6266
|
}
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
var wsReconnectAttempt = 0;
|
|
5587
|
-
var reconnectTimer = null;
|
|
5588
|
-
var backfillTimer = null;
|
|
5589
|
-
function scheduleReconnect(delayMs) {
|
|
5590
|
-
if (shuttingDown)
|
|
6267
|
+
function scheduleReconnect(delayMs, slot = activeSlot) {
|
|
6268
|
+
if (shuttingDown || !slot)
|
|
5591
6269
|
return;
|
|
5592
|
-
if (reconnectTimer)
|
|
5593
|
-
clearTimeout(reconnectTimer);
|
|
5594
|
-
reconnectTimer = setTimeout(() => {
|
|
5595
|
-
reconnectTimer = null;
|
|
5596
|
-
connectWS();
|
|
6270
|
+
if (slot.reconnectTimer)
|
|
6271
|
+
clearTimeout(slot.reconnectTimer);
|
|
6272
|
+
slot.reconnectTimer = setTimeout(() => {
|
|
6273
|
+
slot.reconnectTimer = null;
|
|
6274
|
+
connectWS(slot);
|
|
5597
6275
|
}, delayMs);
|
|
5598
6276
|
}
|
|
5599
|
-
async function backfillAllChannels() {
|
|
5600
|
-
if (knownChannels.size === 0)
|
|
6277
|
+
async function backfillAllChannels(slot = activeSlot) {
|
|
6278
|
+
if (!slot || slot.knownChannels.size === 0)
|
|
5601
6279
|
return;
|
|
5602
|
-
for (const channelId of knownChannels) {
|
|
6280
|
+
for (const channelId of slot.knownChannels) {
|
|
5603
6281
|
try {
|
|
5604
|
-
const after = lastSeenMessageTs.get(channelId);
|
|
6282
|
+
const after = slot.lastSeenMessageTs.get(channelId);
|
|
5605
6283
|
const params = after ? `?after=${encodeURIComponent(after)}&limit=50` : `?limit=1`;
|
|
5606
6284
|
const url = `${REST_URL}/api/channels/${encodeURIComponent(channelId)}/messages${params}`;
|
|
5607
6285
|
const res = await apiFetch(url, {
|
|
5608
|
-
headers:
|
|
6286
|
+
headers: slot.token ? { Authorization: `Bearer ${slot.token}` } : {}
|
|
5609
6287
|
});
|
|
5610
6288
|
if (!res.ok)
|
|
5611
6289
|
continue;
|
|
@@ -5619,12 +6297,12 @@ async function backfillAllChannels() {
|
|
|
5619
6297
|
newestTs = t;
|
|
5620
6298
|
}
|
|
5621
6299
|
if (newestTs) {
|
|
5622
|
-
lastSeenMessageTs.set(channelId, newestTs);
|
|
5623
|
-
|
|
6300
|
+
slot.lastSeenMessageTs.set(channelId, newestTs);
|
|
6301
|
+
scheduleSlotLastSeenMessageTsSave(slot);
|
|
5624
6302
|
}
|
|
5625
6303
|
continue;
|
|
5626
6304
|
}
|
|
5627
|
-
const replay = msgs.filter((m) => m && m.sender_id !==
|
|
6305
|
+
const replay = msgs.filter((m) => m && m.sender_id !== slot.agentId && m.content !== "__typing__");
|
|
5628
6306
|
const dedupedReplay = after ? replay.filter((m) => {
|
|
5629
6307
|
const msgTs = normalizeTimestampForCursor(m?.timestamp, "after");
|
|
5630
6308
|
const afterTs = normalizeTimestampForCursor(after, "after");
|
|
@@ -5637,8 +6315,8 @@ async function backfillAllChannels() {
|
|
|
5637
6315
|
dedupedReplay.sort((a, b) => String(a.timestamp).localeCompare(String(b.timestamp)));
|
|
5638
6316
|
for (const m of dedupedReplay) {
|
|
5639
6317
|
try {
|
|
5640
|
-
if (
|
|
5641
|
-
await
|
|
6318
|
+
if (slot.handleWSMessage) {
|
|
6319
|
+
await slot.handleWSMessage({ ...m, type: "message", __source: "backfill" });
|
|
5642
6320
|
}
|
|
5643
6321
|
} catch (e) {
|
|
5644
6322
|
process.stderr.write(`[agentchat] Backfill replay error: ${e}
|
|
@@ -5651,36 +6329,88 @@ async function backfillAllChannels() {
|
|
|
5651
6329
|
}
|
|
5652
6330
|
}
|
|
5653
6331
|
}
|
|
5654
|
-
function
|
|
5655
|
-
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)
|
|
5656
6384
|
return;
|
|
5657
6385
|
let socket;
|
|
5658
6386
|
try {
|
|
5659
6387
|
socket = new WebSocket(WS_URL);
|
|
5660
|
-
ws = socket;
|
|
6388
|
+
slot.ws = socket;
|
|
6389
|
+
if (activeSlot === slot)
|
|
6390
|
+
ws = socket;
|
|
5661
6391
|
} catch (e) {
|
|
5662
6392
|
process.stderr.write(`[agentchat] WebSocket constructor failed: ${e}, retrying in 5s
|
|
5663
6393
|
`);
|
|
5664
|
-
scheduleReconnect(5000);
|
|
6394
|
+
scheduleReconnect(5000, slot);
|
|
5665
6395
|
return;
|
|
5666
6396
|
}
|
|
5667
|
-
|
|
5668
|
-
if (ws !== socket)
|
|
6397
|
+
socket.onopen = () => {
|
|
6398
|
+
if (slot.ws !== socket)
|
|
5669
6399
|
return;
|
|
5670
6400
|
try {
|
|
5671
6401
|
socket.send(JSON.stringify({
|
|
5672
6402
|
type: "auth",
|
|
5673
|
-
agent_id:
|
|
5674
|
-
token:
|
|
5675
|
-
capabilities:
|
|
6403
|
+
agent_id: slot.agentId,
|
|
6404
|
+
token: slot.token,
|
|
6405
|
+
capabilities: slot.capabilities
|
|
5676
6406
|
}));
|
|
5677
6407
|
} catch (e) {
|
|
5678
6408
|
process.stderr.write(`[agentchat] Auth send failed: ${e}
|
|
5679
6409
|
`);
|
|
5680
6410
|
}
|
|
5681
6411
|
};
|
|
5682
|
-
|
|
5683
|
-
if (ws !== socket)
|
|
6412
|
+
socket.onmessage = async (event) => {
|
|
6413
|
+
if (slot.ws !== socket)
|
|
5684
6414
|
return;
|
|
5685
6415
|
let data;
|
|
5686
6416
|
try {
|
|
@@ -5697,31 +6427,34 @@ function connectWS() {
|
|
|
5697
6427
|
`);
|
|
5698
6428
|
}
|
|
5699
6429
|
};
|
|
5700
|
-
|
|
6430
|
+
slot.handleWSMessage = handleWSMessage;
|
|
5701
6431
|
async function handleWSMessage(data) {
|
|
5702
6432
|
if (data.type === "pong") {
|
|
5703
|
-
heartbeat.receivedPong();
|
|
6433
|
+
slot.heartbeat.receivedPong();
|
|
6434
|
+
syncOpenBoundSessions();
|
|
5704
6435
|
return;
|
|
5705
6436
|
}
|
|
5706
6437
|
if ((data.type === "hidden_identity.reveal" || data.type === "hidden_identity.finished") && typeof data.game_id === "string") {
|
|
5707
6438
|
clearActiveHiddenIdentityGame(data.game_id, data.type);
|
|
5708
6439
|
}
|
|
5709
6440
|
if (data.type === "auth_ok") {
|
|
5710
|
-
sessionId = data.session_id;
|
|
5711
|
-
|
|
5712
|
-
|
|
5713
|
-
|
|
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}
|
|
5714
6447
|
`);
|
|
5715
|
-
if (backfillTimer)
|
|
5716
|
-
clearTimeout(backfillTimer);
|
|
5717
|
-
backfillTimer = setTimeout(() => {
|
|
5718
|
-
backfillTimer = null;
|
|
6448
|
+
if (slot.backfillTimer)
|
|
6449
|
+
clearTimeout(slot.backfillTimer);
|
|
6450
|
+
slot.backfillTimer = setTimeout(() => {
|
|
6451
|
+
slot.backfillTimer = null;
|
|
5719
6452
|
if (!shuttingDown)
|
|
5720
|
-
backfillAllChannels();
|
|
6453
|
+
backfillAllChannels(slot);
|
|
5721
6454
|
}, 2000);
|
|
5722
|
-
} else if ((data.type === "message" || data.type === "thread_reply") && data.sender_id ===
|
|
5723
|
-
stopTypingHeartbeat(data.channel_id);
|
|
5724
|
-
} 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")) {
|
|
5725
6458
|
if (data.content === "__typing__")
|
|
5726
6459
|
return;
|
|
5727
6460
|
const metaKind = data.meta && typeof data.meta === "object" ? data.meta.kind : undefined;
|
|
@@ -5730,32 +6463,33 @@ function connectWS() {
|
|
|
5730
6463
|
`);
|
|
5731
6464
|
return;
|
|
5732
6465
|
}
|
|
5733
|
-
if (recordOrSkipDeliveredMessage(data))
|
|
6466
|
+
if (recordOrSkipDeliveredMessage(data, slot))
|
|
5734
6467
|
return;
|
|
5735
6468
|
if (typeof data.channel_id === "string" && typeof data.timestamp === "string") {
|
|
5736
|
-
const prev = lastSeenMessageTs.get(data.channel_id) || "";
|
|
6469
|
+
const prev = slot.lastSeenMessageTs.get(data.channel_id) || "";
|
|
5737
6470
|
const currentTs = normalizeTimestampForCursor(data.timestamp, "after") || data.timestamp;
|
|
5738
6471
|
const prevTs = normalizeTimestampForCursor(prev, "after") || prev;
|
|
5739
6472
|
if (currentTs > prevTs) {
|
|
5740
|
-
lastSeenMessageTs.set(data.channel_id, data.timestamp);
|
|
5741
|
-
|
|
6473
|
+
slot.lastSeenMessageTs.set(data.channel_id, data.timestamp);
|
|
6474
|
+
scheduleSlotLastSeenMessageTsSave(slot);
|
|
5742
6475
|
}
|
|
5743
6476
|
}
|
|
5744
6477
|
const isDM = data.channel_id?.startsWith("dm-");
|
|
5745
|
-
const isMentioned = matchesMention(data.content || "",
|
|
6478
|
+
const isMentioned = matchesMention(data.content || "", slot.agentId || "");
|
|
5746
6479
|
const activeHi = activeHiddenIdentityForChannel(data.channel_id);
|
|
5747
|
-
const isOwnLoopTick = metaKind === "loop_tick" && data.sender_id ===
|
|
6480
|
+
const isOwnLoopTick = metaKind === "loop_tick" && data.sender_id === slot.agentId;
|
|
5748
6481
|
if (isDM || isMentioned || activeHi || isOwnLoopTick) {
|
|
5749
6482
|
if (isDM || isMentioned)
|
|
5750
|
-
startTypingHeartbeat(data.channel_id);
|
|
6483
|
+
startTypingHeartbeat(data.channel_id, slot);
|
|
5751
6484
|
let contextPrefix = "";
|
|
5752
6485
|
if (!isDM && isMentioned) {
|
|
5753
6486
|
try {
|
|
5754
|
-
const
|
|
6487
|
+
const mentionKey = `${slot.agentId}:${data.channel_id}`;
|
|
6488
|
+
const lastTs = lastMentionTimestamp.get(mentionKey) || lastMentionTimestamp.get(data.channel_id) || "";
|
|
5755
6489
|
const params = `limit=50${lastTs ? "&after=" + encodeURIComponent(lastTs) : ""}`;
|
|
5756
6490
|
const historyUrl = `${REST_URL}/api/channels/${encodeURIComponent(data.channel_id)}/messages?${params}`;
|
|
5757
6491
|
const historyRes = await apiFetch(historyUrl, {
|
|
5758
|
-
headers:
|
|
6492
|
+
headers: slot.token ? { Authorization: `Bearer ${slot.token}` } : {}
|
|
5759
6493
|
});
|
|
5760
6494
|
if (historyRes.ok) {
|
|
5761
6495
|
const historyData = await historyRes.json();
|
|
@@ -5775,7 +6509,7 @@ function connectWS() {
|
|
|
5775
6509
|
}
|
|
5776
6510
|
const truncatedMsgs = trimmed.length < msgs.length;
|
|
5777
6511
|
if (trimmed.length > 0) {
|
|
5778
|
-
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(`
|
|
5779
6513
|
`);
|
|
5780
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]`;
|
|
5781
6515
|
contextPrefix = `${note}
|
|
@@ -5785,6 +6519,7 @@ ${context}
|
|
|
5785
6519
|
`;
|
|
5786
6520
|
}
|
|
5787
6521
|
}
|
|
6522
|
+
lastMentionTimestamp.set(mentionKey, data.timestamp);
|
|
5788
6523
|
lastMentionTimestamp.set(data.channel_id, data.timestamp);
|
|
5789
6524
|
saveMentionTimestamps(lastMentionTimestamp);
|
|
5790
6525
|
} catch (e) {
|
|
@@ -5799,10 +6534,11 @@ ${context}
|
|
|
5799
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)}
|
|
5800
6535
|
`);
|
|
5801
6536
|
try {
|
|
6537
|
+
const notifAtt = formatWakeAttachments(data.attachments);
|
|
5802
6538
|
await server.notification({
|
|
5803
6539
|
method: process.env.CLAUDE_CODE_ENTRYPOINT ? "notifications/claude/channel" : "notifications/chat/channel",
|
|
5804
6540
|
params: {
|
|
5805
|
-
content: contextPrefix + data.content,
|
|
6541
|
+
content: contextPrefix + (data.content || "") + notifAtt,
|
|
5806
6542
|
meta: {
|
|
5807
6543
|
chat_id: data.channel_id,
|
|
5808
6544
|
sender_id: data.sender_id,
|
|
@@ -5816,18 +6552,20 @@ ${context}
|
|
|
5816
6552
|
process.stderr.write(`[agentchat] Notification FAILED: ${notifErr}
|
|
5817
6553
|
`);
|
|
5818
6554
|
}
|
|
6555
|
+
const slotProfName = slot.profileName || profileNameFromPath(slot.profileFile);
|
|
6556
|
+
const slotRuntime = slot.runtimeSession?.runtime;
|
|
5819
6557
|
if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
|
|
5820
6558
|
(async () => {
|
|
5821
6559
|
try {
|
|
5822
|
-
const { readFileSync:
|
|
5823
|
-
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);
|
|
5824
6562
|
let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
|
|
5825
6563
|
if (!agentId) {
|
|
5826
6564
|
agentId = await resolveGrokAgentId({
|
|
5827
6565
|
explicitId: "",
|
|
5828
|
-
agentschatName: profile.display_name ||
|
|
6566
|
+
agentschatName: slot.profile.display_name || slot.agentId,
|
|
5829
6567
|
listAgents: async () => {
|
|
5830
|
-
const gwcfg = JSON.parse(
|
|
6568
|
+
const gwcfg = JSON.parse(readFileSync8(gwPath, "utf8"));
|
|
5831
6569
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
5832
6570
|
const port = grokPortFromGatewayConfig(gwcfg);
|
|
5833
6571
|
const res = await fetch(`http://127.0.0.1:${port}/api/listAgents`, {
|
|
@@ -5849,24 +6587,34 @@ ${context}
|
|
|
5849
6587
|
}
|
|
5850
6588
|
})();
|
|
5851
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;
|
|
5852
6592
|
fireWake(data, {
|
|
5853
6593
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
5854
|
-
secret: process.env.AGENTCHAT_WAKE_SECRET
|
|
6594
|
+
secret: process.env.AGENTCHAT_WAKE_SECRET,
|
|
6595
|
+
targetSessionId
|
|
5855
6596
|
});
|
|
5856
|
-
} else if (
|
|
5857
|
-
const
|
|
5858
|
-
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 : "") || "";
|
|
5859
6599
|
if (zcodeSid) {
|
|
5860
6600
|
fireZcodeWake(data, {
|
|
5861
6601
|
sessionId: zcodeSid,
|
|
5862
|
-
workspacePath: runtimeSession?.workspacePath,
|
|
5863
|
-
profileName:
|
|
6602
|
+
workspacePath: slot.runtimeSession?.workspacePath,
|
|
6603
|
+
profileName: slotProfName ?? undefined,
|
|
5864
6604
|
lockOwnerPid: process.pid,
|
|
5865
6605
|
contextPrefix,
|
|
5866
6606
|
logger: (m) => process.stderr.write(`${m}
|
|
5867
6607
|
`)
|
|
5868
6608
|
});
|
|
5869
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
|
+
});
|
|
5870
6618
|
} else {
|
|
5871
6619
|
(async () => {
|
|
5872
6620
|
try {
|
|
@@ -5875,14 +6623,13 @@ ${context}
|
|
|
5875
6623
|
const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
|
|
5876
6624
|
if (!agyHost && !lsAddress)
|
|
5877
6625
|
return;
|
|
5878
|
-
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
5879
6626
|
const allBinds = loadSessionBinds(configDir);
|
|
5880
|
-
let targetCid = findBoundSessionForProfile(configDir,
|
|
6627
|
+
let targetCid = findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) || (slotRuntime === "antigravity" ? slot.runtimeSession?.sessionId : "") || "";
|
|
5881
6628
|
if (!targetCid && agyHost) {
|
|
5882
6629
|
if (agyHost.openConversations.length === 1) {
|
|
5883
6630
|
targetCid = agyHost.openConversations[0];
|
|
5884
6631
|
} else if (agyHost.openConversations.length > 1) {
|
|
5885
|
-
const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] ===
|
|
6632
|
+
const unboundOrSame = agyHost.openConversations.find((cid) => !allBinds[cid] || allBinds[cid] === slotProfName);
|
|
5886
6633
|
targetCid = unboundOrSame || agyHost.openConversations[0];
|
|
5887
6634
|
}
|
|
5888
6635
|
}
|
|
@@ -5911,16 +6658,16 @@ ${context}
|
|
|
5911
6658
|
}
|
|
5912
6659
|
} else if (data.type === "channel_created") {
|
|
5913
6660
|
try {
|
|
5914
|
-
ws?.send(JSON.stringify({
|
|
6661
|
+
slot.ws?.send(JSON.stringify({
|
|
5915
6662
|
type: "join_channel",
|
|
5916
6663
|
channel_id: data.channel_id,
|
|
5917
|
-
agent_id:
|
|
6664
|
+
agent_id: slot.agentId
|
|
5918
6665
|
}));
|
|
5919
6666
|
} catch {}
|
|
5920
6667
|
process.stderr.write(`[agentchat] Joined channel: ${data.name}
|
|
5921
6668
|
`);
|
|
5922
6669
|
if (typeof data.channel_id === "string")
|
|
5923
|
-
knownChannels.add(data.channel_id);
|
|
6670
|
+
slot.knownChannels.add(data.channel_id);
|
|
5924
6671
|
} else if (data.type === "shard_moved") {
|
|
5925
6672
|
process.stderr.write(`[agentchat] Shard moved, reconnecting...
|
|
5926
6673
|
`);
|
|
@@ -5929,69 +6676,60 @@ ${context}
|
|
|
5929
6676
|
process.stderr.write(`[agentchat] Redirecting to: ${newUrl}
|
|
5930
6677
|
`);
|
|
5931
6678
|
}
|
|
5932
|
-
if (ws) {
|
|
5933
|
-
ws.onclose = null;
|
|
6679
|
+
if (slot.ws) {
|
|
6680
|
+
slot.ws.onclose = null;
|
|
5934
6681
|
try {
|
|
5935
|
-
ws.close();
|
|
6682
|
+
slot.ws.close();
|
|
5936
6683
|
} catch {}
|
|
5937
6684
|
}
|
|
5938
|
-
ws = null;
|
|
5939
|
-
sessionId = null;
|
|
5940
|
-
|
|
5941
|
-
|
|
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);
|
|
5942
6693
|
} else if (data.type === "error") {
|
|
5943
6694
|
process.stderr.write(`[agentchat] Error: ${data.message}
|
|
5944
6695
|
`);
|
|
5945
6696
|
}
|
|
5946
6697
|
}
|
|
5947
|
-
|
|
5948
|
-
if (ws !== socket)
|
|
6698
|
+
socket.onclose = (event) => {
|
|
6699
|
+
if (slot.ws !== socket)
|
|
5949
6700
|
return;
|
|
5950
|
-
sessionId = null;
|
|
5951
|
-
|
|
5952
|
-
|
|
5953
|
-
|
|
5954
|
-
|
|
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})...
|
|
5955
6708
|
`);
|
|
5956
|
-
scheduleReconnect(delay);
|
|
6709
|
+
scheduleReconnect(delay, slot);
|
|
5957
6710
|
};
|
|
5958
|
-
|
|
5959
|
-
if (ws !== socket)
|
|
6711
|
+
socket.onerror = (err) => {
|
|
6712
|
+
if (slot.ws !== socket)
|
|
5960
6713
|
return;
|
|
5961
6714
|
process.stderr.write(`[agentchat] WebSocket error: ${err}
|
|
5962
6715
|
`);
|
|
5963
6716
|
};
|
|
5964
6717
|
}
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
5971
|
-
|
|
5972
|
-
|
|
5973
|
-
|
|
5974
|
-
|
|
5975
|
-
|
|
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) {
|
|
5976
6729
|
try {
|
|
5977
|
-
|
|
6730
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
5978
6731
|
} catch {}
|
|
5979
6732
|
}
|
|
5980
|
-
ws = null;
|
|
5981
|
-
sessionId = null;
|
|
5982
|
-
wsReconnectAttempt = 0;
|
|
5983
|
-
scheduleReconnect(500);
|
|
5984
|
-
},
|
|
5985
|
-
getReadyState: () => ws?.readyState ?? WS_CLOSED
|
|
5986
|
-
}, 15000, 45000, 30000);
|
|
5987
|
-
if (!anonymousMode && !toolOnlyMode) {
|
|
5988
|
-
heartbeat.start();
|
|
5989
|
-
}
|
|
5990
|
-
function releaseLiveLock() {
|
|
5991
|
-
if (AGENT_ID && !toolOnlyMode) {
|
|
5992
|
-
try {
|
|
5993
|
-
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
5994
|
-
} catch {}
|
|
5995
6733
|
}
|
|
5996
6734
|
}
|
|
5997
6735
|
function shutdownFromStdio(reason) {
|
|
@@ -6007,19 +6745,11 @@ function shutdownFromStdio(reason) {
|
|
|
6007
6745
|
`);
|
|
6008
6746
|
}
|
|
6009
6747
|
releaseLiveLock();
|
|
6010
|
-
try {
|
|
6011
|
-
heartbeat.stop();
|
|
6012
|
-
} catch {}
|
|
6013
6748
|
try {
|
|
6014
6749
|
stopAllTypingHeartbeats();
|
|
6015
6750
|
} catch {}
|
|
6016
|
-
|
|
6017
|
-
|
|
6018
|
-
reconnectTimer = null;
|
|
6019
|
-
}
|
|
6020
|
-
if (backfillTimer) {
|
|
6021
|
-
clearTimeout(backfillTimer);
|
|
6022
|
-
backfillTimer = null;
|
|
6751
|
+
for (const slot of [...profileSlots.values()]) {
|
|
6752
|
+
teardownSlot(slot, { releaseLock: false });
|
|
6023
6753
|
}
|
|
6024
6754
|
try {
|
|
6025
6755
|
ws?.close();
|
|
@@ -6078,14 +6808,22 @@ async function checkVersionStaleness() {
|
|
|
6078
6808
|
}
|
|
6079
6809
|
async function main() {
|
|
6080
6810
|
installStdioLifecycleGuards();
|
|
6081
|
-
if (
|
|
6811
|
+
if (!toolOnlyMode) {
|
|
6812
|
+
syncOpenBoundSessions();
|
|
6813
|
+
}
|
|
6814
|
+
if (anonymousMode && profileSlots.size === 0) {
|
|
6082
6815
|
process.stderr.write(`[agentchat] Anonymous \u2014 not connecting to the hub.
|
|
6083
6816
|
`);
|
|
6084
6817
|
} else if (toolOnlyMode) {
|
|
6085
6818
|
process.stderr.write(`[agentchat] Tool-only mode (AGENTSCHAT_TOOL_ONLY=1) \u2014 skipping duplicate WS connection.
|
|
6086
6819
|
`);
|
|
6087
6820
|
} else {
|
|
6088
|
-
|
|
6821
|
+
for (const slot of profileSlots.values()) {
|
|
6822
|
+
if (!slot.ws) {
|
|
6823
|
+
slot.heartbeat.start();
|
|
6824
|
+
connectWS(slot);
|
|
6825
|
+
}
|
|
6826
|
+
}
|
|
6089
6827
|
}
|
|
6090
6828
|
transport = new StdioServerTransport;
|
|
6091
6829
|
await server.connect(transport);
|