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/src/server.ts
CHANGED
|
@@ -15,19 +15,24 @@ import { TEAM_LEAD_SKILL_ID, TEAM_LEAD_SKILL_TITLE, TEAM_LEAD_SKILL_SUMMARY, TEA
|
|
|
15
15
|
// degrades to a reconnect log rather than crashing stdio/tools-list. Node 22+
|
|
16
16
|
// (global WebSocket/fetch/FormData) gets full functionality.
|
|
17
17
|
|
|
18
|
-
// ── Proxy bypass
|
|
19
|
-
//
|
|
20
|
-
//
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
18
|
+
// ── Proxy bypass & loopback safety ────────────────────────────────
|
|
19
|
+
// Ensure local loopback wakes (127.0.0.1 / localhost Connect-RPC or Grok
|
|
20
|
+
// gateway) always bypass HTTP_PROXY / HTTPS_PROXY even when NODE_USE_ENV_PROXY=1
|
|
21
|
+
// is active in proxied container environments.
|
|
22
|
+
for (const key of ["NO_PROXY", "no_proxy"] as const) {
|
|
23
|
+
const cur = process.env[key]?.trim() || "";
|
|
24
|
+
const items = cur ? cur.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
25
|
+
for (const host of ["localhost", "127.0.0.1", "::1", "[::1]"]) {
|
|
26
|
+
if (!items.includes(host)) items.push(host);
|
|
27
|
+
}
|
|
28
|
+
process.env[key] = items.join(",");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Controlled by AGENTCHAT_NO_PROXY=1 (set in .mcp.json env) for hosts where
|
|
32
|
+
// HTTP_PROXY/HTTPS_PROXY is only needed by the parent process and breaks WS
|
|
33
|
+
// upgrades when agents-chat.com is directly reachable. In cloud sandboxes that
|
|
34
|
+
// require an egress proxy via NODE_USE_ENV_PROXY=1, preserve HTTP(S)_PROXY.
|
|
35
|
+
if (process.env.AGENTCHAT_NO_PROXY === "1" && process.env.NODE_USE_ENV_PROXY !== "1") {
|
|
31
36
|
delete process.env.HTTP_PROXY;
|
|
32
37
|
delete process.env.HTTPS_PROXY;
|
|
33
38
|
delete process.env.http_proxy;
|
|
@@ -65,6 +70,7 @@ import {
|
|
|
65
70
|
fireGrokWake,
|
|
66
71
|
fireAntigravityWake,
|
|
67
72
|
fireZcodeWake,
|
|
73
|
+
formatWakeAttachments,
|
|
68
74
|
resolveGrokAgentId,
|
|
69
75
|
resolveGrokGatewayPath,
|
|
70
76
|
grokBearerFromGatewayConfig,
|
|
@@ -83,8 +89,13 @@ import {
|
|
|
83
89
|
findBoundSessionForProfile,
|
|
84
90
|
detectRuntimeSession,
|
|
85
91
|
discoverAntigravityHost,
|
|
92
|
+
detectAntigravityCallerSession,
|
|
93
|
+
detectDshCallerSession,
|
|
94
|
+
isDshHostProcess,
|
|
86
95
|
type DetectedSession,
|
|
87
96
|
} from "./session-bind.ts";
|
|
97
|
+
import { resolveSessionForAgent } from "./session-route.ts";
|
|
98
|
+
import { HeartbeatMonitor, WS_OPEN, WS_CLOSED, WS_CONNECTING, WS_CLOSING } from "./heartbeat.ts";
|
|
88
99
|
import pkg from "../package.json";
|
|
89
100
|
import {
|
|
90
101
|
CallToolRequestSchema,
|
|
@@ -142,16 +153,15 @@ function parseArgs() {
|
|
|
142
153
|
const cliArgs = parseArgs();
|
|
143
154
|
|
|
144
155
|
if (process.argv.includes("--help") || process.argv.includes("-h")) {
|
|
145
|
-
console.log(`agentschat-mcp — AgentsChat MCP and host bridges
|
|
156
|
+
console.log(`agentschat-mcp v${pkg.version} — AgentsChat MCP and host bridges
|
|
146
157
|
|
|
147
|
-
Usage: claude mcp add agentschat -- npx -y agentschat-mcp
|
|
158
|
+
Usage: claude mcp add agentschat -- npx -y agentschat-mcp@latest --profile <Bot> [options]
|
|
148
159
|
claude --dangerously-load-development-channels server:agentschat
|
|
149
|
-
One MCP server entry per bot, each pinning --profile
|
|
150
|
-
(not @latest, which drifts).
|
|
160
|
+
One MCP server entry per bot, each pinning --profile.
|
|
151
161
|
|
|
152
162
|
Setup guide for every supported host:
|
|
153
163
|
Read skills/onboarding.md relative to this installed package root.
|
|
154
|
-
Online
|
|
164
|
+
Online: https://unpkg.com/agentschat-mcp@latest/skills/onboarding.md
|
|
155
165
|
Newest release (first install): npx -y agentschat-mcp@latest --help
|
|
156
166
|
The guide selects Claude Code, Codex, OpenClaw, Hermes, Grok Bot, URL wake,
|
|
157
167
|
or the separately deployed dot remote MCP + Events integration.
|
|
@@ -217,6 +227,8 @@ const lockDir = resolveLockDir(homeDir, process.env);
|
|
|
217
227
|
const lockOwnerPid = Number(process.env.AGENTSCHAT_LOCK_OWNER_PID) || null;
|
|
218
228
|
const toolOnlyMode = process.env.AGENTSCHAT_TOOL_ONLY === "1";
|
|
219
229
|
let runtimeSession: DetectedSession | null = detectRuntimeSession(process.env);
|
|
230
|
+
/** One-shot notice when DSH is detected but no session can be resolved (see the DSH branch). */
|
|
231
|
+
let dshRouteWarned = false;
|
|
220
232
|
|
|
221
233
|
function profileNameToPaths(name: string): string[] {
|
|
222
234
|
if (name.startsWith("~/")) return [join(homeDir, name.slice(2))];
|
|
@@ -748,27 +760,36 @@ let ws: WebSocket | null = null;
|
|
|
748
760
|
const TYPING_HEARTBEAT_MS = 2_000;
|
|
749
761
|
const TYPING_HEARTBEAT_MAX_MS = 120_000;
|
|
750
762
|
const typingHeartbeats = new Map<string, { interval: ReturnType<typeof setInterval>; cap: ReturnType<typeof setTimeout> }>();
|
|
751
|
-
function
|
|
752
|
-
|
|
763
|
+
function typingHeartbeatKey(channelId: string, agentId: string = AGENT_ID): string {
|
|
764
|
+
return `${agentId || "default"}:${channelId}`;
|
|
765
|
+
}
|
|
766
|
+
function sendTypingFrame(channelId: string, slot: ProfileSlot | null = activeSlot) {
|
|
767
|
+
const targetWs = slot ? slot.ws : ws;
|
|
768
|
+
const senderId = slot ? slot.agentId : AGENT_ID;
|
|
769
|
+
if (targetWs && targetWs.readyState === WebSocket.OPEN && senderId) {
|
|
753
770
|
try {
|
|
754
|
-
|
|
771
|
+
targetWs.send(JSON.stringify({ type: "typing", channel_id: channelId, sender_id: senderId, cross_pod: true }));
|
|
755
772
|
} catch {}
|
|
756
773
|
}
|
|
757
774
|
}
|
|
758
|
-
function startTypingHeartbeat(channelId: string) {
|
|
775
|
+
function startTypingHeartbeat(channelId: string, slot: ProfileSlot | null = activeSlot) {
|
|
759
776
|
if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0") return;
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
const
|
|
764
|
-
|
|
777
|
+
const agentId = slot ? slot.agentId : AGENT_ID;
|
|
778
|
+
stopTypingHeartbeat(channelId, slot); // reset if one is already running for this channel
|
|
779
|
+
sendTypingFrame(channelId, slot); // immediate first pulse
|
|
780
|
+
const interval = setInterval(() => sendTypingFrame(channelId, slot), TYPING_HEARTBEAT_MS);
|
|
781
|
+
const cap = setTimeout(() => stopTypingHeartbeat(channelId, slot), TYPING_HEARTBEAT_MAX_MS);
|
|
782
|
+
typingHeartbeats.set(typingHeartbeatKey(channelId, agentId), { interval, cap });
|
|
765
783
|
}
|
|
766
|
-
function stopTypingHeartbeat(channelId: string) {
|
|
767
|
-
const
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
784
|
+
function stopTypingHeartbeat(channelId: string, slot: ProfileSlot | null = activeSlot) {
|
|
785
|
+
const agentId = slot ? slot.agentId : AGENT_ID;
|
|
786
|
+
for (const key of [typingHeartbeatKey(channelId, agentId), channelId]) {
|
|
787
|
+
const h = typingHeartbeats.get(key);
|
|
788
|
+
if (!h) continue;
|
|
789
|
+
clearInterval(h.interval);
|
|
790
|
+
clearTimeout(h.cap);
|
|
791
|
+
typingHeartbeats.delete(key);
|
|
792
|
+
}
|
|
772
793
|
}
|
|
773
794
|
function stopAllTypingHeartbeats() {
|
|
774
795
|
for (const h of typingHeartbeats.values()) {
|
|
@@ -781,6 +802,32 @@ let sessionId: string | null = null;
|
|
|
781
802
|
let shuttingDown = false;
|
|
782
803
|
let transport: StdioServerTransport | null = null;
|
|
783
804
|
|
|
805
|
+
interface ProfileSlot {
|
|
806
|
+
profileName: string;
|
|
807
|
+
profileFile: string | null;
|
|
808
|
+
profile: any;
|
|
809
|
+
agentId: string;
|
|
810
|
+
token: string;
|
|
811
|
+
capabilities: string[];
|
|
812
|
+
ws: WebSocket | null;
|
|
813
|
+
sessionId: string | null;
|
|
814
|
+
runtimeSession: DetectedSession | null;
|
|
815
|
+
knownChannels: Set<string>;
|
|
816
|
+
wsReconnectAttempt: number;
|
|
817
|
+
reconnectTimer: ReturnType<typeof setTimeout> | null;
|
|
818
|
+
backfillTimer: ReturnType<typeof setTimeout> | null;
|
|
819
|
+
heartbeat: HeartbeatMonitor;
|
|
820
|
+
lastSeenMessageTsFile: string;
|
|
821
|
+
lastSeenMessageTs: Map<string, string>;
|
|
822
|
+
cursorState: { dirty: boolean };
|
|
823
|
+
lastSeenMessageTsTimer: ReturnType<typeof setTimeout> | null;
|
|
824
|
+
messageDedup: MessageDedup;
|
|
825
|
+
handleWSMessage: ((data: any) => Promise<void>) | null;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
const profileSlots = new Map<string, ProfileSlot>();
|
|
829
|
+
let activeSlot: ProfileSlot | null = null;
|
|
830
|
+
|
|
784
831
|
const debugLogsEnabled = /^(1|true|yes|debug)$/i.test(
|
|
785
832
|
process.env.AGENTSCHAT_MCP_DEBUG || process.env.AGENTCHAT_DEBUG || "",
|
|
786
833
|
);
|
|
@@ -1003,10 +1050,10 @@ const TOOL_GROUPS: ToolGroupMeta[] = [
|
|
|
1003
1050
|
},
|
|
1004
1051
|
{
|
|
1005
1052
|
name: "media",
|
|
1006
|
-
summary: "Send images and voice/audio clips into channels (upload a local file or attach an already-hosted url).",
|
|
1053
|
+
summary: "Send images, videos, and voice/audio clips into channels (upload a local file or attach an already-hosted url).",
|
|
1007
1054
|
tags: ["chat", "media"],
|
|
1008
|
-
estimated_tokens:
|
|
1009
|
-
tools: ["send_image", "send_voice", "set_voice", "list_voices", "transcribe"],
|
|
1055
|
+
estimated_tokens: 750,
|
|
1056
|
+
tools: ["send_image", "send_video", "send_voice", "set_voice", "list_voices", "transcribe"],
|
|
1010
1057
|
},
|
|
1011
1058
|
];
|
|
1012
1059
|
|
|
@@ -1082,6 +1129,24 @@ const ALL_TOOL_DEFS = [
|
|
|
1082
1129
|
required: ["chat_id"],
|
|
1083
1130
|
},
|
|
1084
1131
|
},
|
|
1132
|
+
{
|
|
1133
|
+
name: "send_video",
|
|
1134
|
+
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.",
|
|
1135
|
+
inputSchema: {
|
|
1136
|
+
type: "object" as const,
|
|
1137
|
+
properties: {
|
|
1138
|
+
chat_id: { type: "string", description: "Channel id to post into" },
|
|
1139
|
+
path: { type: "string", description: "Local video file to upload (mp4/mov/webm/m4v; ≤50MB). Provide this OR url." },
|
|
1140
|
+
url: { type: "string", description: "Already-uploaded proxy url (/api/file/uploads/<name>). Provide this OR path." },
|
|
1141
|
+
caption: { type: "string", description: "Optional text shown alongside the video" },
|
|
1142
|
+
width: { type: "number", description: "Video width in px (optional)" },
|
|
1143
|
+
height: { type: "number", description: "Video height in px (optional)" },
|
|
1144
|
+
duration_ms: { type: "number", description: "Video duration in milliseconds (optional)" },
|
|
1145
|
+
transcript: { type: "string", description: "Optional transcript or summary of the video" },
|
|
1146
|
+
},
|
|
1147
|
+
required: ["chat_id"],
|
|
1148
|
+
},
|
|
1149
|
+
},
|
|
1085
1150
|
{
|
|
1086
1151
|
name: "send_voice",
|
|
1087
1152
|
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 — this is the natural way for an agent to \"talk\"; optional `voice` overrides your configured voice). Optional `caption`, `duration_ms`, `transcript`.",
|
|
@@ -1933,11 +1998,16 @@ const TOOL_INPUT_SCHEMAS: Map<string, any> = new Map(
|
|
|
1933
1998
|
* a newly-joined member's display_name would be resolvable.
|
|
1934
1999
|
*/
|
|
1935
2000
|
const MEMBER_CACHE_TTL_MS = 5 * 60_000;
|
|
1936
|
-
const memberCache = new Map<string, { at: number; members: { agent_id: string; display_name?: string }[] }>();
|
|
2001
|
+
const memberCache = new Map<string, { at: number; members: { agent_id: string; display_name?: string }[]; sameOwnerDirect?: boolean }>();
|
|
2002
|
+
|
|
2003
|
+
function memberCacheKey(chatId: string): string {
|
|
2004
|
+
return `${AGENT_ID || "anon"}:${chatId}`;
|
|
2005
|
+
}
|
|
1937
2006
|
|
|
1938
2007
|
async function fetchChannelMembers(chatId: string): Promise<{ agent_id: string; display_name?: string }[]> {
|
|
1939
2008
|
const now = Date.now();
|
|
1940
|
-
const
|
|
2009
|
+
const key = memberCacheKey(chatId);
|
|
2010
|
+
const hit = memberCache.get(key);
|
|
1941
2011
|
if (hit && now - hit.at < MEMBER_CACHE_TTL_MS) return hit.members;
|
|
1942
2012
|
try {
|
|
1943
2013
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chatId)}/members`, {
|
|
@@ -1946,13 +2016,34 @@ async function fetchChannelMembers(chatId: string): Promise<{ agent_id: string;
|
|
|
1946
2016
|
if (!r.ok) return hit?.members || [];
|
|
1947
2017
|
const body = await r.json() as any;
|
|
1948
2018
|
const members = Array.isArray(body?.members) ? body.members : [];
|
|
1949
|
-
|
|
2019
|
+
const sameOwnerDirect = body?.same_owner_direct === true;
|
|
2020
|
+
memberCache.set(key, { at: now, members, sameOwnerDirect });
|
|
1950
2021
|
return members;
|
|
1951
2022
|
} catch {
|
|
1952
2023
|
return hit?.members || [];
|
|
1953
2024
|
}
|
|
1954
2025
|
}
|
|
1955
2026
|
|
|
2027
|
+
async function isSameOwnerDirectChannel(chatId: string): Promise<boolean> {
|
|
2028
|
+
const now = Date.now();
|
|
2029
|
+
const key = memberCacheKey(chatId);
|
|
2030
|
+
const hit = memberCache.get(key);
|
|
2031
|
+
if (hit && now - hit.at < MEMBER_CACHE_TTL_MS && typeof hit.sameOwnerDirect === "boolean") {
|
|
2032
|
+
return hit.sameOwnerDirect;
|
|
2033
|
+
}
|
|
2034
|
+
await fetchChannelMembers(chatId);
|
|
2035
|
+
return memberCache.get(key)?.sameOwnerDirect === true;
|
|
2036
|
+
}
|
|
2037
|
+
|
|
2038
|
+
async function redactOutboundForChannel(chatId: string, text: string): Promise<string> {
|
|
2039
|
+
if (!text) return text;
|
|
2040
|
+
if (/ac_[A-Za-z0-9_-]{16,}/.test(text)) {
|
|
2041
|
+
const preserveAcKeys = await isSameOwnerDirectChannel(chatId);
|
|
2042
|
+
return redactSecrets(text, { preserveAcKeys });
|
|
2043
|
+
}
|
|
2044
|
+
return redactSecrets(text);
|
|
2045
|
+
}
|
|
2046
|
+
|
|
1956
2047
|
/**
|
|
1957
2048
|
* Resolve bare `@<display_name>` tokens in outgoing message text to the
|
|
1958
2049
|
* paren form `@<display_name>(<agent_id>)` so receiving MCP plugins'
|
|
@@ -2070,19 +2161,22 @@ HANDLERS.set("list_my_channels", async (args) => {
|
|
|
2070
2161
|
const MEDIA_MIME_BY_EXT: Record<string, string> = {
|
|
2071
2162
|
jpg: "image/jpeg", jpeg: "image/jpeg", png: "image/png", gif: "image/gif",
|
|
2072
2163
|
webp: "image/webp", heic: "image/heic", heif: "image/heif", avif: "image/avif",
|
|
2073
|
-
|
|
2074
|
-
|
|
2164
|
+
mp4: "video/mp4", mov: "video/quicktime", m4v: "video/x-m4v", webm: "video/webm", "3gp": "video/3gpp",
|
|
2165
|
+
m4a: "audio/mp4", aac: "audio/aac", mp3: "audio/mpeg",
|
|
2166
|
+
wav: "audio/wav", weba: "audio/webm", ogg: "audio/ogg", oga: "audio/ogg",
|
|
2075
2167
|
};
|
|
2076
|
-
function mimeFromPath(p: string): string {
|
|
2168
|
+
function mimeFromPath(p: string, kindHint?: "image" | "video" | "audio"): string {
|
|
2077
2169
|
const ext = p.split(".").pop()?.toLowerCase() ?? "";
|
|
2170
|
+
if (kindHint === "audio" && ext === "mp4") return "audio/mp4";
|
|
2171
|
+
if (kindHint === "audio" && ext === "webm") return "audio/webm";
|
|
2078
2172
|
return MEDIA_MIME_BY_EXT[ext] ?? "application/octet-stream";
|
|
2079
2173
|
}
|
|
2080
2174
|
// Upload a local file via multipart POST /api/upload → { url, mime, size }.
|
|
2081
|
-
async function uploadLocalFile(path: string): Promise<{ url: string; mime: string; size: number }> {
|
|
2175
|
+
async function uploadLocalFile(path: string, kindHint?: "image" | "video" | "audio"): Promise<{ url: string; mime: string; size: number }> {
|
|
2082
2176
|
// node:fs (not Bun.file) so this runs on plain Node too — Bun supports node:fs
|
|
2083
2177
|
// identically, and the Node path is what registry introspection (Glama) uses.
|
|
2084
2178
|
if (!existsSync(path)) throw new Error(`file not found: ${path}`);
|
|
2085
|
-
const mime = mimeFromPath(path);
|
|
2179
|
+
const mime = mimeFromPath(path, kindHint);
|
|
2086
2180
|
const buf = readFileSync(path);
|
|
2087
2181
|
const name = path.split("/").pop() || "upload";
|
|
2088
2182
|
const form = new FormData();
|
|
@@ -2096,8 +2190,8 @@ async function uploadLocalFile(path: string): Promise<{ url: string; mime: strin
|
|
|
2096
2190
|
if (!data?.url) throw new Error(`upload response missing url: ${text.slice(0, 120)}`);
|
|
2097
2191
|
return { url: data.url as string, mime: (data.type as string) || mime, size: (data.size as number) ?? buf.byteLength };
|
|
2098
2192
|
}
|
|
2099
|
-
// Post a message carrying exactly one media attachment (image|audio).
|
|
2100
|
-
async function sendMediaMessage(kind: "image" | "audio", args: any): Promise<{ content: any[]; isError?: boolean }> {
|
|
2193
|
+
// Post a message carrying exactly one media attachment (image|video|audio).
|
|
2194
|
+
async function sendMediaMessage(kind: "image" | "video" | "audio", args: any): Promise<{ content: any[]; isError?: boolean }> {
|
|
2101
2195
|
const { chat_id, path, url, caption } = (args || {}) as { chat_id?: string; path?: string; url?: string; caption?: string };
|
|
2102
2196
|
if (!chat_id) return { content: [{ type: "text", text: "Error: chat_id required" }], isError: true };
|
|
2103
2197
|
// `text` (speak-via-TTS) is an audio-only third source, alongside path/url.
|
|
@@ -2131,11 +2225,11 @@ async function sendMediaMessage(kind: "image" | "audio", args: any): Promise<{ c
|
|
|
2131
2225
|
mime = (d.mime as string) || "audio/mpeg";
|
|
2132
2226
|
ttsDuration = typeof d.duration_ms === "number" ? d.duration_ms : undefined;
|
|
2133
2227
|
} else if (path) {
|
|
2134
|
-
const up = await uploadLocalFile(path);
|
|
2228
|
+
const up = await uploadLocalFile(path, kind);
|
|
2135
2229
|
finalUrl = up.url; mime = up.mime; size = up.size;
|
|
2136
2230
|
} else {
|
|
2137
2231
|
finalUrl = url as string;
|
|
2138
|
-
mime = mimeFromPath(finalUrl);
|
|
2232
|
+
mime = mimeFromPath(finalUrl, kind);
|
|
2139
2233
|
}
|
|
2140
2234
|
const attachment: Record<string, any> = { type: kind, url: finalUrl };
|
|
2141
2235
|
if (mime && mime !== "application/octet-stream") attachment.mime = mime;
|
|
@@ -2143,13 +2237,18 @@ async function sendMediaMessage(kind: "image" | "audio", args: any): Promise<{ c
|
|
|
2143
2237
|
if (kind === "image") {
|
|
2144
2238
|
if (typeof args.width === "number") attachment.width = args.width;
|
|
2145
2239
|
if (typeof args.height === "number") attachment.height = args.height;
|
|
2240
|
+
} else if (kind === "video") {
|
|
2241
|
+
if (typeof args.width === "number") attachment.width = args.width;
|
|
2242
|
+
if (typeof args.height === "number") attachment.height = args.height;
|
|
2243
|
+
if (typeof args.duration_ms === "number") attachment.duration_ms = args.duration_ms;
|
|
2244
|
+
if (typeof args.transcript === "string" && args.transcript) attachment.transcript = args.transcript;
|
|
2146
2245
|
} else {
|
|
2147
2246
|
const dur = typeof args.duration_ms === "number" ? args.duration_ms : ttsDuration;
|
|
2148
2247
|
if (dur != null) attachment.duration_ms = dur;
|
|
2149
2248
|
if (typeof args.transcript === "string" && args.transcript) attachment.transcript = args.transcript;
|
|
2150
2249
|
else if (text) attachment.transcript = text; // the spoken text is its own transcript
|
|
2151
2250
|
}
|
|
2152
|
-
const content = caption ?
|
|
2251
|
+
const content = caption ? await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, caption)) : "";
|
|
2153
2252
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages`, {
|
|
2154
2253
|
method: "POST",
|
|
2155
2254
|
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${TOKEN}` },
|
|
@@ -2165,6 +2264,7 @@ async function sendMediaMessage(kind: "image" | "audio", args: any): Promise<{ c
|
|
|
2165
2264
|
}
|
|
2166
2265
|
}
|
|
2167
2266
|
HANDLERS.set("send_image", (args) => sendMediaMessage("image", args));
|
|
2267
|
+
HANDLERS.set("send_video", (args) => sendMediaMessage("video", args));
|
|
2168
2268
|
HANDLERS.set("send_voice", (args) => sendMediaMessage("audio", args));
|
|
2169
2269
|
|
|
2170
2270
|
// list_voices — the server's curated TTS voice catalog (GET /api/voices), so an
|
|
@@ -2274,62 +2374,242 @@ function currentGrokBindApplicability(binds: Record<string, string>) {
|
|
|
2274
2374
|
});
|
|
2275
2375
|
}
|
|
2276
2376
|
|
|
2377
|
+
const cursorFlushIntervalMs = Math.max(
|
|
2378
|
+
500,
|
|
2379
|
+
Number(process.env.AGENTSCHAT_MCP_CURSOR_FLUSH_MS || 5000),
|
|
2380
|
+
);
|
|
2381
|
+
|
|
2382
|
+
function flushSlotLastSeenMessageTs(slot: ProfileSlot) {
|
|
2383
|
+
if (!slot.cursorState.dirty) return;
|
|
2384
|
+
if (slot.lastSeenMessageTsTimer) {
|
|
2385
|
+
clearTimeout(slot.lastSeenMessageTsTimer);
|
|
2386
|
+
slot.lastSeenMessageTsTimer = null;
|
|
2387
|
+
}
|
|
2388
|
+
flushCursor(slot.cursorState, () => persistCursor(slot.lastSeenMessageTsFile, slot.lastSeenMessageTs, safeStderrWrite));
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
function scheduleSlotLastSeenMessageTsSave(slot: ProfileSlot) {
|
|
2392
|
+
slot.cursorState.dirty = true;
|
|
2393
|
+
if (slot.lastSeenMessageTsTimer) return;
|
|
2394
|
+
slot.lastSeenMessageTsTimer = setTimeout(() => {
|
|
2395
|
+
slot.lastSeenMessageTsTimer = null;
|
|
2396
|
+
flushSlotLastSeenMessageTs(slot);
|
|
2397
|
+
}, cursorFlushIntervalMs);
|
|
2398
|
+
(slot.lastSeenMessageTsTimer as any).unref?.();
|
|
2399
|
+
}
|
|
2400
|
+
|
|
2401
|
+
function createProfileSlot(opts: {
|
|
2402
|
+
profileName: string;
|
|
2403
|
+
profileFile: string | null;
|
|
2404
|
+
profile: any;
|
|
2405
|
+
agentId: string;
|
|
2406
|
+
token: string;
|
|
2407
|
+
capabilities: string[];
|
|
2408
|
+
runtimeSession: DetectedSession | null;
|
|
2409
|
+
}): ProfileSlot {
|
|
2410
|
+
const lastSeenFile = join(configDir, `last-seen-msg-ts-${opts.agentId}.json`);
|
|
2411
|
+
const slot: ProfileSlot = {
|
|
2412
|
+
profileName: opts.profileName,
|
|
2413
|
+
profileFile: opts.profileFile,
|
|
2414
|
+
profile: opts.profile,
|
|
2415
|
+
agentId: opts.agentId,
|
|
2416
|
+
token: opts.token,
|
|
2417
|
+
capabilities: opts.capabilities,
|
|
2418
|
+
ws: null,
|
|
2419
|
+
sessionId: null,
|
|
2420
|
+
runtimeSession: opts.runtimeSession,
|
|
2421
|
+
knownChannels: new Set<string>(),
|
|
2422
|
+
wsReconnectAttempt: 0,
|
|
2423
|
+
reconnectTimer: null,
|
|
2424
|
+
backfillTimer: null,
|
|
2425
|
+
heartbeat: null as any,
|
|
2426
|
+
lastSeenMessageTsFile: lastSeenFile,
|
|
2427
|
+
lastSeenMessageTs: loadCursor(lastSeenFile, safeStderrWrite),
|
|
2428
|
+
cursorState: { dirty: false },
|
|
2429
|
+
lastSeenMessageTsTimer: null,
|
|
2430
|
+
messageDedup: new MessageDedup(),
|
|
2431
|
+
handleWSMessage: null,
|
|
2432
|
+
};
|
|
2433
|
+
slot.heartbeat = new HeartbeatMonitor({
|
|
2434
|
+
sendPing: () => {
|
|
2435
|
+
try { slot.ws?.send(JSON.stringify({ type: "ping", timestamp: new Date().toISOString() })); } catch {}
|
|
2436
|
+
},
|
|
2437
|
+
reconnect: () => {
|
|
2438
|
+
process.stderr.write("[agentchat] Heartbeat timeout, forcing reconnect\n");
|
|
2439
|
+
if (slot.ws) { slot.ws.onclose = null; try { slot.ws.close(); } catch {} }
|
|
2440
|
+
slot.ws = null;
|
|
2441
|
+
slot.sessionId = null;
|
|
2442
|
+
if (activeSlot === slot) {
|
|
2443
|
+
ws = null;
|
|
2444
|
+
sessionId = null;
|
|
2445
|
+
}
|
|
2446
|
+
slot.wsReconnectAttempt = 0;
|
|
2447
|
+
scheduleReconnect(500, slot);
|
|
2448
|
+
},
|
|
2449
|
+
getReadyState: () => slot.ws?.readyState ?? WS_CLOSED,
|
|
2450
|
+
}, 15_000, 45_000, 30_000);
|
|
2451
|
+
return slot;
|
|
2452
|
+
}
|
|
2453
|
+
|
|
2454
|
+
function activateSlot(slot: ProfileSlot, callerSession?: DetectedSession | null): void {
|
|
2455
|
+
if (callerSession) {
|
|
2456
|
+
slot.runtimeSession = {
|
|
2457
|
+
...callerSession,
|
|
2458
|
+
...(callerSession.workspacePath || slot.runtimeSession?.workspacePath
|
|
2459
|
+
? { workspacePath: callerSession.workspacePath ?? slot.runtimeSession?.workspacePath }
|
|
2460
|
+
: {}),
|
|
2461
|
+
};
|
|
2462
|
+
}
|
|
2463
|
+
activeSlot = slot;
|
|
2464
|
+
AGENT_ID = slot.agentId;
|
|
2465
|
+
TOKEN = slot.token;
|
|
2466
|
+
CAPABILITIES = slot.capabilities;
|
|
2467
|
+
profile = slot.profile;
|
|
2468
|
+
activeProfileFile = slot.profileFile;
|
|
2469
|
+
anonymousMode = false;
|
|
2470
|
+
ws = slot.ws;
|
|
2471
|
+
sessionId = slot.sessionId;
|
|
2472
|
+
runtimeSession = slot.runtimeSession;
|
|
2473
|
+
}
|
|
2474
|
+
|
|
2475
|
+
function setAnonymousCallerState(callerSession?: DetectedSession | null): void {
|
|
2476
|
+
activeSlot = null;
|
|
2477
|
+
AGENT_ID = "";
|
|
2478
|
+
TOKEN = "";
|
|
2479
|
+
profile = {};
|
|
2480
|
+
activeProfileFile = null;
|
|
2481
|
+
anonymousMode = true;
|
|
2482
|
+
ws = null;
|
|
2483
|
+
sessionId = null;
|
|
2484
|
+
if (callerSession !== undefined) {
|
|
2485
|
+
runtimeSession = callerSession;
|
|
2486
|
+
}
|
|
2487
|
+
}
|
|
2488
|
+
|
|
2489
|
+
function teardownSlot(slot: ProfileSlot, opts?: { releaseLock?: boolean }): void {
|
|
2490
|
+
try { flushSlotLastSeenMessageTs(slot); } catch {}
|
|
2491
|
+
try { slot.heartbeat.stop(); } catch {}
|
|
2492
|
+
if (slot.backfillTimer) { clearTimeout(slot.backfillTimer); slot.backfillTimer = null; }
|
|
2493
|
+
if (slot.reconnectTimer) { clearTimeout(slot.reconnectTimer); slot.reconnectTimer = null; }
|
|
2494
|
+
if (slot.ws) {
|
|
2495
|
+
slot.ws.onclose = null;
|
|
2496
|
+
try { slot.ws.close(); } catch {}
|
|
2497
|
+
slot.ws = null;
|
|
2498
|
+
}
|
|
2499
|
+
slot.sessionId = null;
|
|
2500
|
+
if (opts?.releaseLock !== false && slot.agentId && !toolOnlyMode) {
|
|
2501
|
+
const boundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName) || null;
|
|
2502
|
+
releaseAgentLock({ lockDir, agentId: slot.agentId, currentSessionId: boundSid });
|
|
2503
|
+
}
|
|
2504
|
+
profileSlots.delete(slot.profileName);
|
|
2505
|
+
if (activeSlot === slot) {
|
|
2506
|
+
activeSlot = null;
|
|
2507
|
+
ws = null;
|
|
2508
|
+
sessionId = null;
|
|
2509
|
+
}
|
|
2510
|
+
}
|
|
2511
|
+
|
|
2512
|
+
if (!anonymousMode && AGENT_ID) {
|
|
2513
|
+
const bootProfName = profileNameFromPath(activeProfileFile) ?? declaredName ?? AGENT_ID;
|
|
2514
|
+
const bootSlot = createProfileSlot({
|
|
2515
|
+
profileName: bootProfName,
|
|
2516
|
+
profileFile: activeProfileFile,
|
|
2517
|
+
profile,
|
|
2518
|
+
agentId: AGENT_ID,
|
|
2519
|
+
token: TOKEN,
|
|
2520
|
+
capabilities: CAPABILITIES,
|
|
2521
|
+
runtimeSession,
|
|
2522
|
+
});
|
|
2523
|
+
profileSlots.set(bootProfName, bootSlot);
|
|
2524
|
+
activateSlot(bootSlot, runtimeSession);
|
|
2525
|
+
}
|
|
2526
|
+
|
|
2277
2527
|
/**
|
|
2278
2528
|
* Apply a profile file as the live identity and reconnect WS.
|
|
2279
2529
|
* Shared by `switch_profile`, `connect_profile`, and grok-bind heal.
|
|
2530
|
+
* Supports single-process multi-agent multiplexing: when called by a different
|
|
2531
|
+
* session (`bindSessionId` / `runtimeSession.sessionId`), other sessions'
|
|
2532
|
+
* connected `ProfileSlot`s remain alive and online.
|
|
2280
2533
|
*/
|
|
2281
2534
|
function applyIdentityFromProfile(newProfile: any, targetFile: string, bindSessionId?: string | null): void {
|
|
2282
2535
|
validateIdentityProfile(newProfile, targetFile);
|
|
2283
|
-
|
|
2284
|
-
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
2285
|
-
}
|
|
2286
|
-
heartbeat.stop();
|
|
2287
|
-
stopAllTypingHeartbeats();
|
|
2288
|
-
if (backfillTimer) { clearTimeout(backfillTimer); backfillTimer = null; }
|
|
2289
|
-
if (reconnectTimer) { clearTimeout(reconnectTimer); reconnectTimer = null; }
|
|
2290
|
-
if (ws) {
|
|
2291
|
-
ws.onclose = null;
|
|
2292
|
-
try { ws.close(); } catch {}
|
|
2293
|
-
ws = null;
|
|
2294
|
-
}
|
|
2295
|
-
sessionId = null;
|
|
2296
|
-
AGENT_ID = newProfile.agent_id;
|
|
2297
|
-
TOKEN = newProfile.token;
|
|
2298
|
-
CAPABILITIES = newProfile.capabilities || ["claude-code", "coding", "chat"];
|
|
2299
|
-
profile = newProfile;
|
|
2300
|
-
activeProfileFile = targetFile;
|
|
2301
|
-
anonymousMode = false;
|
|
2536
|
+
const targetProfName = profileNameFromPath(targetFile) || newProfile.display_name || newProfile.agent_id;
|
|
2302
2537
|
|
|
2303
|
-
|
|
2538
|
+
let targetSession: DetectedSession | null = runtimeSession ? { ...runtimeSession } : null;
|
|
2304
2539
|
if (bindSessionId && bindSessionId.trim()) {
|
|
2305
2540
|
const cleanSid = bindSessionId.trim();
|
|
2306
2541
|
const isAgyEnv =
|
|
2307
2542
|
process.env.__CFBundleIdentifier === "com.google.antigravity" ||
|
|
2308
2543
|
Boolean(process.env.AGY_BROWSER_WS_URL) ||
|
|
2544
|
+
Boolean(process.env.AGENTSCHAT_AGY_BRAIN_DIR) ||
|
|
2309
2545
|
Boolean(discoverAntigravityHost());
|
|
2310
|
-
|
|
2546
|
+
targetSession = {
|
|
2311
2547
|
sessionId: cleanSid,
|
|
2312
|
-
runtime:
|
|
2313
|
-
|
|
2548
|
+
runtime:
|
|
2549
|
+
targetSession?.runtime ??
|
|
2550
|
+
(isAgyEnv && /^[0-9a-f-]{36}$/i.test(cleanSid)
|
|
2551
|
+
? "antigravity"
|
|
2552
|
+
: cleanSid.startsWith("sess_")
|
|
2553
|
+
? "zcode"
|
|
2554
|
+
: cleanSid.startsWith("session-")
|
|
2555
|
+
? "dsh"
|
|
2556
|
+
: "custom"),
|
|
2557
|
+
...(targetSession?.workspacePath ? { workspacePath: targetSession.workspacePath } : {}),
|
|
2314
2558
|
};
|
|
2315
2559
|
} else {
|
|
2316
2560
|
const existingBoundSid = findBoundSessionForProfile(configDir, targetProfName);
|
|
2317
|
-
if (existingBoundSid) {
|
|
2318
|
-
|
|
2561
|
+
if (existingBoundSid && !targetSession?.sessionId) {
|
|
2562
|
+
targetSession = {
|
|
2319
2563
|
sessionId: existingBoundSid,
|
|
2320
2564
|
runtime:
|
|
2321
|
-
|
|
2322
|
-
|
|
2323
|
-
|
|
2565
|
+
/^[0-9a-f-]{36}$/i.test(existingBoundSid)
|
|
2566
|
+
? "antigravity"
|
|
2567
|
+
: existingBoundSid.startsWith("sess_")
|
|
2568
|
+
? "zcode"
|
|
2569
|
+
: existingBoundSid.startsWith("session-")
|
|
2570
|
+
? "dsh"
|
|
2571
|
+
: "custom",
|
|
2324
2572
|
};
|
|
2325
|
-
} else if (!
|
|
2573
|
+
} else if (!targetSession?.sessionId) {
|
|
2326
2574
|
const agyHost = discoverAntigravityHost();
|
|
2327
2575
|
if (agyHost && agyHost.openConversations.length === 1) {
|
|
2328
|
-
|
|
2576
|
+
targetSession = { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" };
|
|
2577
|
+
}
|
|
2578
|
+
}
|
|
2579
|
+
}
|
|
2580
|
+
|
|
2581
|
+
// Only tear down existing slot(s) that belong to THIS session (or the same profile),
|
|
2582
|
+
// preserving other sessions' connected slots in profileSlots.
|
|
2583
|
+
for (const existingSlot of [...profileSlots.values()]) {
|
|
2584
|
+
if (existingSlot.profileName === targetProfName || existingSlot.agentId === newProfile.agent_id) {
|
|
2585
|
+
teardownSlot(existingSlot, { releaseLock: existingSlot.agentId !== newProfile.agent_id });
|
|
2586
|
+
continue;
|
|
2587
|
+
}
|
|
2588
|
+
const existingSid =
|
|
2589
|
+
existingSlot.runtimeSession?.sessionId ||
|
|
2590
|
+
findBoundSessionForProfile(configDir, existingSlot.profileName) ||
|
|
2591
|
+
null;
|
|
2592
|
+
if (targetSession?.sessionId) {
|
|
2593
|
+
if (existingSid === targetSession.sessionId) {
|
|
2594
|
+
teardownSlot(existingSlot, { releaseLock: true });
|
|
2329
2595
|
}
|
|
2596
|
+
} else if (!existingSid && profileSlots.size === 1) {
|
|
2597
|
+
teardownSlot(existingSlot, { releaseLock: true });
|
|
2330
2598
|
}
|
|
2331
2599
|
}
|
|
2332
2600
|
|
|
2601
|
+
const newSlot = createProfileSlot({
|
|
2602
|
+
profileName: targetProfName,
|
|
2603
|
+
profileFile: targetFile,
|
|
2604
|
+
profile: newProfile,
|
|
2605
|
+
agentId: newProfile.agent_id,
|
|
2606
|
+
token: newProfile.token,
|
|
2607
|
+
capabilities: newProfile.capabilities || ["claude-code", "coding", "chat"],
|
|
2608
|
+
runtimeSession: targetSession,
|
|
2609
|
+
});
|
|
2610
|
+
profileSlots.set(targetProfName, newSlot);
|
|
2611
|
+
activateSlot(newSlot, targetSession);
|
|
2612
|
+
|
|
2333
2613
|
if (!toolOnlyMode) {
|
|
2334
2614
|
acquireAgentLock({
|
|
2335
2615
|
lockDir,
|
|
@@ -2353,37 +2633,34 @@ function applyIdentityFromProfile(newProfile: any, targetFile: string, bindSessi
|
|
|
2353
2633
|
true,
|
|
2354
2634
|
);
|
|
2355
2635
|
persistGuardRecord(guardRecord);
|
|
2356
|
-
wsReconnectAttempt = 0;
|
|
2357
2636
|
if (!toolOnlyMode) {
|
|
2358
|
-
heartbeat.start();
|
|
2359
|
-
connectWS();
|
|
2637
|
+
newSlot.heartbeat.start();
|
|
2638
|
+
connectWS(newSlot);
|
|
2360
2639
|
}
|
|
2361
2640
|
}
|
|
2362
2641
|
|
|
2363
2642
|
function disconnectCurrentProfile(opts?: { keepBinding?: boolean }): { prevAgentId: string; prevProfileName: string } {
|
|
2364
|
-
const
|
|
2365
|
-
const
|
|
2366
|
-
|
|
2367
|
-
|
|
2368
|
-
|
|
2369
|
-
|
|
2370
|
-
|
|
2371
|
-
|
|
2372
|
-
|
|
2373
|
-
|
|
2374
|
-
|
|
2375
|
-
|
|
2376
|
-
|
|
2643
|
+
const slot = activeSlot;
|
|
2644
|
+
const prevAgentId = slot?.agentId || AGENT_ID;
|
|
2645
|
+
const prevProfileName =
|
|
2646
|
+
slot?.profileName ||
|
|
2647
|
+
profileNameFromPath(activeProfileFile) ||
|
|
2648
|
+
profile?.display_name ||
|
|
2649
|
+
AGENT_ID ||
|
|
2650
|
+
"(none)";
|
|
2651
|
+
const sidToRemove = slot?.runtimeSession?.sessionId || runtimeSession?.sessionId || null;
|
|
2652
|
+
if (slot) {
|
|
2653
|
+
teardownSlot(slot, { releaseLock: true });
|
|
2654
|
+
} else {
|
|
2655
|
+
stopAllTypingHeartbeats();
|
|
2656
|
+
if (prevAgentId) {
|
|
2657
|
+
releaseAgentLock({ lockDir, agentId: prevAgentId, currentSessionId: sidToRemove });
|
|
2658
|
+
}
|
|
2377
2659
|
}
|
|
2378
|
-
if (!opts?.keepBinding &&
|
|
2379
|
-
removeSessionBind(configDir,
|
|
2660
|
+
if (!opts?.keepBinding && sidToRemove) {
|
|
2661
|
+
removeSessionBind(configDir, sidToRemove);
|
|
2380
2662
|
}
|
|
2381
|
-
|
|
2382
|
-
AGENT_ID = "";
|
|
2383
|
-
TOKEN = "";
|
|
2384
|
-
profile = {};
|
|
2385
|
-
activeProfileFile = null;
|
|
2386
|
-
anonymousMode = true;
|
|
2663
|
+
setAnonymousCallerState(runtimeSession);
|
|
2387
2664
|
return { prevAgentId, prevProfileName };
|
|
2388
2665
|
}
|
|
2389
2666
|
|
|
@@ -2401,9 +2678,13 @@ function formatProfileList(): string {
|
|
|
2401
2678
|
const lock = entryAgentId
|
|
2402
2679
|
? checkAgentLock({ lockDir, agentId: entryAgentId, currentSessionId: runtimeSession?.sessionId ?? null, lockOwnerPid })
|
|
2403
2680
|
: { locked: false };
|
|
2681
|
+
const slot = profileSlots.get(entry.name);
|
|
2682
|
+
const boundSid = findBoundSessionForProfile(configDir, entry.name);
|
|
2404
2683
|
const statusSuffix = lock.locked
|
|
2405
|
-
? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}]`
|
|
2406
|
-
:
|
|
2684
|
+
? ` [in use by pid=${lock.holder?.pid}${lock.holder?.runtime ? ` (${lock.holder.runtime})` : ""}${lock.holder?.sessionId ? ` session=${lock.holder.sessionId}` : ""}]`
|
|
2685
|
+
: slot && slot.ws?.readyState === WebSocket.OPEN
|
|
2686
|
+
? ` [online${boundSid ? ` session=${boundSid}` : ""}]`
|
|
2687
|
+
: "";
|
|
2407
2688
|
return `${isCurrent ? "→ " : " "}${entry.name}${statusSuffix}`;
|
|
2408
2689
|
});
|
|
2409
2690
|
return `Current: ${current || "(anonymous / disconnected)"}\nAvailable profiles:\n${lines.join("\n")}`;
|
|
@@ -2631,7 +2912,148 @@ function ensureGrokBoundIdentity(): void {
|
|
|
2631
2912
|
}
|
|
2632
2913
|
|
|
2633
2914
|
|
|
2634
|
-
|
|
2915
|
+
async function resolveCallerSessionForToolCall(
|
|
2916
|
+
toolName: string,
|
|
2917
|
+
toolArgs: Record<string, any> | undefined,
|
|
2918
|
+
rawMeta: Record<string, any> | undefined,
|
|
2919
|
+
): Promise<{ session: DetectedSession | null; isPerCallSession: boolean }> {
|
|
2920
|
+
// 1. Explicit conversation_id / session_id in tool arguments
|
|
2921
|
+
const explicitArgSid =
|
|
2922
|
+
(typeof toolArgs?.conversation_id === "string" && toolArgs.conversation_id.trim()) ||
|
|
2923
|
+
(typeof toolArgs?.session_id === "string" && toolArgs.session_id.trim()) ||
|
|
2924
|
+
"";
|
|
2925
|
+
if (explicitArgSid) {
|
|
2926
|
+
const isAgy =
|
|
2927
|
+
/^[0-9a-f-]{36}$/i.test(explicitArgSid) &&
|
|
2928
|
+
(process.env.__CFBundleIdentifier === "com.google.antigravity" ||
|
|
2929
|
+
Boolean(process.env.AGY_BROWSER_WS_URL) ||
|
|
2930
|
+
Boolean(process.env.AGENTSCHAT_AGY_BRAIN_DIR) ||
|
|
2931
|
+
Boolean(discoverAntigravityHost()));
|
|
2932
|
+
const runtime = isAgy
|
|
2933
|
+
? "antigravity"
|
|
2934
|
+
: explicitArgSid.startsWith("sess_")
|
|
2935
|
+
? "zcode"
|
|
2936
|
+
: explicitArgSid.startsWith("session-")
|
|
2937
|
+
? "dsh"
|
|
2938
|
+
: runtimeSession?.runtime ?? "custom";
|
|
2939
|
+
return {
|
|
2940
|
+
session: {
|
|
2941
|
+
sessionId: explicitArgSid,
|
|
2942
|
+
runtime,
|
|
2943
|
+
...(runtimeSession?.workspacePath ? { workspacePath: runtimeSession.workspacePath } : {}),
|
|
2944
|
+
},
|
|
2945
|
+
isPerCallSession: true,
|
|
2946
|
+
};
|
|
2947
|
+
}
|
|
2948
|
+
|
|
2949
|
+
// 2. ZCode per-request _meta.session_id
|
|
2950
|
+
const hasExplicitMetaSession = Boolean(
|
|
2951
|
+
(typeof rawMeta?.session_id === "string" && rawMeta.session_id.trim()) ||
|
|
2952
|
+
(typeof rawMeta?.["com.zcode/request-context"]?.session_id === "string" &&
|
|
2953
|
+
rawMeta["com.zcode/request-context"].session_id.trim()),
|
|
2954
|
+
);
|
|
2955
|
+
if (hasExplicitMetaSession) {
|
|
2956
|
+
return {
|
|
2957
|
+
session: detectRuntimeSession(process.env, rawMeta),
|
|
2958
|
+
isPerCallSession: true,
|
|
2959
|
+
};
|
|
2960
|
+
}
|
|
2961
|
+
|
|
2962
|
+
// 3. Process-pinned session env vars (Claude Code, ZCode wake child, explicit env)
|
|
2963
|
+
if (
|
|
2964
|
+
process.env.CLAUDE_CODE_SESSION_ID?.trim() ||
|
|
2965
|
+
process.env.CLAUDE_SESSION_ID?.trim() ||
|
|
2966
|
+
process.env.ZCODE_SESSION_ID?.trim() ||
|
|
2967
|
+
process.env.ANTIGRAVITY_CONVERSATION_ID?.trim() ||
|
|
2968
|
+
process.env.AGENTSCHAT_SESSION_ID?.trim() ||
|
|
2969
|
+
process.env.AGENTCHAT_SESSION_ID?.trim()
|
|
2970
|
+
) {
|
|
2971
|
+
return {
|
|
2972
|
+
session: detectRuntimeSession(process.env, rawMeta),
|
|
2973
|
+
isPerCallSession: false,
|
|
2974
|
+
};
|
|
2975
|
+
}
|
|
2976
|
+
|
|
2977
|
+
// 4. Antigravity multi-conversation caller detection via transcript.jsonl
|
|
2978
|
+
if (
|
|
2979
|
+
process.env.AGENTSCHAT_AGY_BRAIN_DIR?.trim() ||
|
|
2980
|
+
process.env.__CFBundleIdentifier === "com.google.antigravity" ||
|
|
2981
|
+
Boolean(process.env.AGY_BROWSER_WS_URL) ||
|
|
2982
|
+
Boolean(discoverAntigravityHost())
|
|
2983
|
+
) {
|
|
2984
|
+
const agyHost = discoverAntigravityHost();
|
|
2985
|
+
const agyCid = detectAntigravityCallerSession({
|
|
2986
|
+
toolName,
|
|
2987
|
+
args: toolArgs ?? null,
|
|
2988
|
+
openConversations: agyHost?.openConversations,
|
|
2989
|
+
});
|
|
2990
|
+
if (agyCid) {
|
|
2991
|
+
return {
|
|
2992
|
+
session: { sessionId: agyCid, runtime: "antigravity" },
|
|
2993
|
+
isPerCallSession: true,
|
|
2994
|
+
};
|
|
2995
|
+
}
|
|
2996
|
+
if (agyHost && agyHost.openConversations.length === 1) {
|
|
2997
|
+
return {
|
|
2998
|
+
session: { sessionId: agyHost.openConversations[0]!, runtime: "antigravity" },
|
|
2999
|
+
isPerCallSession: false,
|
|
3000
|
+
};
|
|
3001
|
+
}
|
|
3002
|
+
}
|
|
3003
|
+
|
|
3004
|
+
// 5. DeepSeek Harness (DSH) caller session detection
|
|
3005
|
+
if (isDshHostProcess()) {
|
|
3006
|
+
const dshSid = await detectDshCallerSession();
|
|
3007
|
+
if (dshSid) {
|
|
3008
|
+
return {
|
|
3009
|
+
session: { sessionId: dshSid, runtime: "dsh" },
|
|
3010
|
+
isPerCallSession: true,
|
|
3011
|
+
};
|
|
3012
|
+
}
|
|
3013
|
+
// Silence here reads as "multi-account is working" while every call keeps
|
|
3014
|
+
// using the boot identity. Say it once per process instead.
|
|
3015
|
+
if (!dshRouteWarned) {
|
|
3016
|
+
dshRouteWarned = true;
|
|
3017
|
+
process.stderr.write(
|
|
3018
|
+
"[agentchat] DSH detected but no session could be routed to this call: " +
|
|
3019
|
+
"the local /health (roots[].status) was unreachable and no session log matched. " +
|
|
3020
|
+
"Per-session identity is disabled for now; install the DSH inbound plugin or set AGENTSCHAT_DSH_HEALTH_URL.\n",
|
|
3021
|
+
);
|
|
3022
|
+
}
|
|
3023
|
+
}
|
|
3024
|
+
|
|
3025
|
+
return { session: runtimeSession, isPerCallSession: false };
|
|
3026
|
+
}
|
|
3027
|
+
|
|
3028
|
+
/**
|
|
3029
|
+
* Serialize `tools/call` execution.
|
|
3030
|
+
*
|
|
3031
|
+
* Identity is process-global by construction: `activateSlot()` swaps
|
|
3032
|
+
* `AGENT_ID` / `TOKEN` / `ws` / `runtimeSession`, and handlers read those
|
|
3033
|
+
* globals *after* awaiting the network. MCP transports dispatch requests
|
|
3034
|
+
* concurrently, so two calls from different bound sessions can interleave —
|
|
3035
|
+
* A activates, awaits, B activates, A then formats/answers as B. That is
|
|
3036
|
+
* cross-identity leakage in exactly the scenario multi-account multiplexing
|
|
3037
|
+
* exists for, so this queue is a correctness requirement whenever more than one
|
|
3038
|
+
* identity is live, not a throughput trade-off.
|
|
3039
|
+
*
|
|
3040
|
+
* Every tool here is a short REST/WS round trip (no long-poll tool), so
|
|
3041
|
+
* serializing costs latency, not liveness.
|
|
3042
|
+
*/
|
|
3043
|
+
let callTail: Promise<unknown> = Promise.resolve();
|
|
3044
|
+
function serializeCall<T>(run: () => Promise<T>): Promise<T> {
|
|
3045
|
+
const started = callTail.then(
|
|
3046
|
+
() => run(),
|
|
3047
|
+
() => run(),
|
|
3048
|
+
);
|
|
3049
|
+
callTail = started.then(
|
|
3050
|
+
() => undefined,
|
|
3051
|
+
() => undefined,
|
|
3052
|
+
);
|
|
3053
|
+
return started;
|
|
3054
|
+
}
|
|
3055
|
+
|
|
3056
|
+
const handleToolCall = async (request: any): Promise<any> => {
|
|
2635
3057
|
let { name, arguments: args } = request.params;
|
|
2636
3058
|
let viaExtendedCompat = false;
|
|
2637
3059
|
// Central failure boundary: any handler that throws (network, JSON, ws.send,
|
|
@@ -2639,52 +3061,85 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
2639
3061
|
// SDK error, so the calling agent always learns the call failed. Explicit
|
|
2640
3062
|
// error returns below carry isError:true individually.
|
|
2641
3063
|
try {
|
|
2642
|
-
//
|
|
2643
|
-
//
|
|
2644
|
-
// currently-focused window heuristic (`discoverAntigravityHost`) to overwrite
|
|
2645
|
-
// an already-bound `runtimeSession` when another tab calls a tool.
|
|
3064
|
+
// Resolve the calling session/conversation and automatically route to its
|
|
3065
|
+
// bound ProfileSlot in profileSlots (`session_id -> profile -> agent_id`).
|
|
2646
3066
|
const rawMeta = (request.params as any)?._meta;
|
|
2647
|
-
const
|
|
2648
|
-
|
|
2649
|
-
|
|
2650
|
-
|
|
3067
|
+
const { session: callerSession, isPerCallSession } = await resolveCallerSessionForToolCall(
|
|
3068
|
+
name,
|
|
3069
|
+
args as Record<string, any> | undefined,
|
|
3070
|
+
rawMeta,
|
|
2651
3071
|
);
|
|
2652
|
-
|
|
2653
|
-
|
|
2654
|
-
|
|
2655
|
-
|
|
2656
|
-
|
|
2657
|
-
|
|
2658
|
-
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
3072
|
+
if (callerSession) {
|
|
3073
|
+
runtimeSession = callerSession;
|
|
3074
|
+
const binds = loadSessionBinds(configDir);
|
|
3075
|
+
const boundProfileName = binds[callerSession.sessionId];
|
|
3076
|
+
const isProfileControlTool =
|
|
3077
|
+
name === "connect_profile" || name === "switch_profile" || name === "disconnect_profile";
|
|
3078
|
+
|
|
3079
|
+
if (boundProfileName) {
|
|
3080
|
+
const existingSlot = profileSlots.get(boundProfileName);
|
|
3081
|
+
if (existingSlot) {
|
|
3082
|
+
activateSlot(existingSlot, callerSession);
|
|
3083
|
+
if (!toolOnlyMode) {
|
|
3084
|
+
acquireAgentLock({
|
|
3085
|
+
lockDir,
|
|
3086
|
+
agentId: existingSlot.agentId,
|
|
3087
|
+
profileName: existingSlot.profileName,
|
|
3088
|
+
sessionId: callerSession.sessionId,
|
|
3089
|
+
runtime: callerSession.runtime,
|
|
3090
|
+
});
|
|
3091
|
+
}
|
|
3092
|
+
} else if (!isProfileControlTool || name === "disconnect_profile") {
|
|
3093
|
+
const boundPath = nameToPath(boundProfileName);
|
|
2662
3094
|
if (existsSync(boundPath)) {
|
|
2663
3095
|
try {
|
|
2664
3096
|
const candidate = readIdentityProfile(boundPath);
|
|
2665
3097
|
const lock = checkAgentLock({
|
|
2666
3098
|
lockDir,
|
|
2667
3099
|
agentId: candidate?.agent_id,
|
|
2668
|
-
currentSessionId:
|
|
3100
|
+
currentSessionId: callerSession.sessionId,
|
|
2669
3101
|
lockOwnerPid,
|
|
2670
3102
|
});
|
|
2671
3103
|
if (!lock.locked) {
|
|
2672
|
-
applyIdentityFromProfile(candidate, boundPath,
|
|
3104
|
+
applyIdentityFromProfile(candidate, boundPath, callerSession.sessionId);
|
|
3105
|
+
} else if (isPerCallSession) {
|
|
3106
|
+
setAnonymousCallerState(callerSession);
|
|
2673
3107
|
}
|
|
2674
3108
|
} catch {}
|
|
3109
|
+
} else if (isPerCallSession) {
|
|
3110
|
+
setAnonymousCallerState(callerSession);
|
|
2675
3111
|
}
|
|
3112
|
+
} else if (isPerCallSession) {
|
|
3113
|
+
setAnonymousCallerState(callerSession);
|
|
2676
3114
|
}
|
|
2677
|
-
} else
|
|
2678
|
-
|
|
2679
|
-
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
|
|
2684
|
-
|
|
2685
|
-
|
|
2686
|
-
|
|
2687
|
-
|
|
3115
|
+
} else {
|
|
3116
|
+
let unboundSlot: ProfileSlot | null = null;
|
|
3117
|
+
for (const slot of profileSlots.values()) {
|
|
3118
|
+
const slotBoundSid =
|
|
3119
|
+
slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName);
|
|
3120
|
+
if (!slotBoundSid || slotBoundSid === callerSession.sessionId) {
|
|
3121
|
+
unboundSlot = slot;
|
|
3122
|
+
break;
|
|
3123
|
+
}
|
|
3124
|
+
}
|
|
3125
|
+
if (unboundSlot && !isProfileControlTool) {
|
|
3126
|
+
activateSlot(unboundSlot, callerSession);
|
|
3127
|
+
if (!toolOnlyMode) {
|
|
3128
|
+
acquireAgentLock({
|
|
3129
|
+
lockDir,
|
|
3130
|
+
agentId: unboundSlot.agentId,
|
|
3131
|
+
profileName: unboundSlot.profileName,
|
|
3132
|
+
sessionId: callerSession.sessionId,
|
|
3133
|
+
runtime: callerSession.runtime,
|
|
3134
|
+
});
|
|
3135
|
+
if (unboundSlot.profileName && !findBoundSessionForProfile(configDir, unboundSlot.profileName)) {
|
|
3136
|
+
saveSessionBind(configDir, callerSession.sessionId, unboundSlot.profileName);
|
|
3137
|
+
}
|
|
3138
|
+
}
|
|
3139
|
+
} else if (unboundSlot && isProfileControlTool) {
|
|
3140
|
+
activateSlot(unboundSlot, callerSession);
|
|
3141
|
+
} else if (isPerCallSession) {
|
|
3142
|
+
setAnonymousCallerState(callerSession);
|
|
2688
3143
|
}
|
|
2689
3144
|
}
|
|
2690
3145
|
}
|
|
@@ -3047,7 +3502,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3047
3502
|
// receiving MCP plugin's regex triggers), then redact secrets so
|
|
3048
3503
|
// an accidental `ac_xxx` in the text gets masked regardless of
|
|
3049
3504
|
// how it arrived.
|
|
3050
|
-
const text =
|
|
3505
|
+
const text = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawText));
|
|
3051
3506
|
// Use REST API for reliable delivery (WebSocket may be half-open after deploy)
|
|
3052
3507
|
try {
|
|
3053
3508
|
const r = await apiFetch(`${REST_URL}/api/channels/${encodeURIComponent(chat_id)}/messages`, {
|
|
@@ -3095,7 +3550,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3095
3550
|
|
|
3096
3551
|
if (name === "thread_reply") {
|
|
3097
3552
|
const { chat_id, parent_id, text: rawText } = args as any;
|
|
3098
|
-
const text =
|
|
3553
|
+
const text = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawText));
|
|
3099
3554
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
3100
3555
|
ws.send(JSON.stringify({
|
|
3101
3556
|
type: "thread_reply", id: crypto.randomUUID(), parent_id,
|
|
@@ -3128,7 +3583,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3128
3583
|
// Mirror reply(): resolve bare @mentions then redact secrets so an
|
|
3129
3584
|
// accidental ac_/JWT in edited content is masked like every other
|
|
3130
3585
|
// outbound content path (this was the one hole that bypassed it).
|
|
3131
|
-
const new_content =
|
|
3586
|
+
const new_content = await redactOutboundForChannel(chat_id, await resolveBareMentions(chat_id, rawNewContent));
|
|
3132
3587
|
ws.send(JSON.stringify({
|
|
3133
3588
|
type: "edit_message", message_id, channel_id: chat_id,
|
|
3134
3589
|
sender_id: AGENT_ID, new_content, timestamp: new Date().toISOString(),
|
|
@@ -3432,8 +3887,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3432
3887
|
// Prune so knownChannels / lastSeenMessageTs don't grow unbounded and
|
|
3433
3888
|
// turn every reconnect backfill into a serial REST fetch over channels
|
|
3434
3889
|
// we've already left.
|
|
3435
|
-
|
|
3436
|
-
|
|
3890
|
+
if (activeSlot) {
|
|
3891
|
+
activeSlot.knownChannels.delete(chat_id);
|
|
3892
|
+
if (activeSlot.lastSeenMessageTs.delete(chat_id)) scheduleSlotLastSeenMessageTsSave(activeSlot);
|
|
3893
|
+
}
|
|
3437
3894
|
const data = await r.json().catch(() => ({})) as any;
|
|
3438
3895
|
if (data.note === "not a member") {
|
|
3439
3896
|
return { content: [{ type: "text", text: `Already not a member of ${chat_id.slice(0, 8)}` }] };
|
|
@@ -3448,8 +3905,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3448
3905
|
// REST unreachable — fall back to WS leave so at least in-memory state updates
|
|
3449
3906
|
if (ws && ws.readyState === WebSocket.OPEN) {
|
|
3450
3907
|
try { ws.send(JSON.stringify({ type: "leave_channel", channel_id: chat_id, agent_id: AGENT_ID })); } catch {}
|
|
3451
|
-
|
|
3452
|
-
|
|
3908
|
+
if (activeSlot) {
|
|
3909
|
+
activeSlot.knownChannels.delete(chat_id);
|
|
3910
|
+
if (activeSlot.lastSeenMessageTs.delete(chat_id)) scheduleSlotLastSeenMessageTsSave(activeSlot);
|
|
3911
|
+
}
|
|
3453
3912
|
return { content: [{ type: "text", text: `Leave sent via WS (REST unreachable: ${String(e?.message || e).slice(0, 60)})` }] };
|
|
3454
3913
|
}
|
|
3455
3914
|
return { content: [{ type: "text", text: `Leave failed — no connectivity` }] };
|
|
@@ -3791,6 +4250,13 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
3791
4250
|
} else if (a.type === "image") {
|
|
3792
4251
|
const dim = a.width && a.height ? ` ${a.width}×${a.height}` : "";
|
|
3793
4252
|
line += `\n 🖼 image${dim}: ${a.url}`;
|
|
4253
|
+
} else if (a.type === "video") {
|
|
4254
|
+
const dim = a.width && a.height ? ` ${a.width}×${a.height}` : "";
|
|
4255
|
+
const dur = typeof a.duration_ms === "number" ? ` ${(a.duration_ms / 1000).toFixed(1)}s` : "";
|
|
4256
|
+
line += `\n 🎬 video${dim}${dur}: ${a.url}`;
|
|
4257
|
+
if (a.transcript) {
|
|
4258
|
+
line += `\n transcript: "${String(a.transcript).slice(0, 400)}"`;
|
|
4259
|
+
}
|
|
3794
4260
|
} else {
|
|
3795
4261
|
line += `\n 📎 ${a.type || "file"}: ${a.url}`;
|
|
3796
4262
|
}
|
|
@@ -4211,7 +4677,10 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
|
4211
4677
|
} catch (e: any) {
|
|
4212
4678
|
return { content: [{ type: "text", text: `${name} failed: ${String(e?.message || e).slice(0, 300)}` }], isError: true };
|
|
4213
4679
|
}
|
|
4214
|
-
}
|
|
4680
|
+
};
|
|
4681
|
+
|
|
4682
|
+
// One tool call at a time: identity is process-global (see serializeCall).
|
|
4683
|
+
server.setRequestHandler(CallToolRequestSchema, (request) => serializeCall(() => handleToolCall(request)));
|
|
4215
4684
|
|
|
4216
4685
|
// --- WebSocket Connection ---
|
|
4217
4686
|
|
|
@@ -4243,37 +4712,10 @@ const lastMentionTimestamp = loadMentionTimestamps();
|
|
|
4243
4712
|
// disconnect event — so the "reconnect" trigger alone doesn't
|
|
4244
4713
|
// cover this class. Backfill runs on every auth_ok whether first
|
|
4245
4714
|
// connect or reconnect; if we missed anything, we find it.
|
|
4246
|
-
const lastSeenMessageTsFile = join(configDir, `last-seen-msg-ts-${AGENT_ID}.json`);
|
|
4247
|
-
function loadLastSeenMessageTs(): Map<string, string> {
|
|
4248
|
-
return loadCursor(lastSeenMessageTsFile, safeStderrWrite);
|
|
4249
|
-
}
|
|
4250
|
-
const lastSeenMessageTs = loadLastSeenMessageTs();
|
|
4251
|
-
const cursorFlushIntervalMs = Math.max(
|
|
4252
|
-
500,
|
|
4253
|
-
Number(process.env.AGENTSCHAT_MCP_CURSOR_FLUSH_MS || 5000),
|
|
4254
|
-
);
|
|
4255
|
-
/** Dirty flag lives in an object so flushCursor can clear it only on a landed write. */
|
|
4256
|
-
const cursorState = { dirty: false };
|
|
4257
|
-
let lastSeenMessageTsTimer: ReturnType<typeof setTimeout> | null = null;
|
|
4258
|
-
|
|
4259
4715
|
function flushLastSeenMessageTs() {
|
|
4260
|
-
|
|
4261
|
-
|
|
4262
|
-
clearTimeout(lastSeenMessageTsTimer);
|
|
4263
|
-
lastSeenMessageTsTimer = null;
|
|
4716
|
+
for (const slot of profileSlots.values()) {
|
|
4717
|
+
flushSlotLastSeenMessageTs(slot);
|
|
4264
4718
|
}
|
|
4265
|
-
// Stays dirty if the write fails, so the shutdown fallback flush actually retries.
|
|
4266
|
-
flushCursor(cursorState, () => persistCursor(lastSeenMessageTsFile, lastSeenMessageTs, safeStderrWrite));
|
|
4267
|
-
}
|
|
4268
|
-
|
|
4269
|
-
function scheduleLastSeenMessageTsSave() {
|
|
4270
|
-
cursorState.dirty = true;
|
|
4271
|
-
if (lastSeenMessageTsTimer) return;
|
|
4272
|
-
lastSeenMessageTsTimer = setTimeout(() => {
|
|
4273
|
-
lastSeenMessageTsTimer = null;
|
|
4274
|
-
flushLastSeenMessageTs();
|
|
4275
|
-
}, cursorFlushIntervalMs);
|
|
4276
|
-
(lastSeenMessageTsTimer as any).unref?.();
|
|
4277
4719
|
}
|
|
4278
4720
|
|
|
4279
4721
|
// normalizeTimestampForCursor now lives in ./timestamps.ts (imported above),
|
|
@@ -4424,14 +4866,13 @@ function clearFinishedHiddenIdentityGamesFromMessage(data: any) {
|
|
|
4424
4866
|
// duplicate or drop older out-of-order messages that were never processed.
|
|
4425
4867
|
// Dedup core (key derivation + bounded set) lives in ./dedup.ts; this file
|
|
4426
4868
|
// keeps the thin logging wrapper so call sites and stderr output are unchanged.
|
|
4427
|
-
const messageDedup = new MessageDedup();
|
|
4428
4869
|
function deliverySource(data: any): string {
|
|
4429
4870
|
return typeof data?.__source === "string" ? data.__source : "live";
|
|
4430
4871
|
}
|
|
4431
|
-
function recordOrSkipDeliveredMessage(data: any): boolean {
|
|
4872
|
+
function recordOrSkipDeliveredMessage(data: any, slot: ProfileSlot | null = activeSlot): boolean {
|
|
4432
4873
|
const key = messageDedupKey(data);
|
|
4433
|
-
if (!key) return false;
|
|
4434
|
-
const skip = messageDedup.recordOrSkip(key);
|
|
4874
|
+
if (!key || !slot) return false;
|
|
4875
|
+
const skip = slot.messageDedup.recordOrSkip(key);
|
|
4435
4876
|
if (skip) {
|
|
4436
4877
|
process.stderr.write(
|
|
4437
4878
|
`[agentchat] Duplicate message skipped source=${deliverySource(data)} chat=${String(data.channel_id).slice(0, 12)} id=${String(data.id).slice(0, 12)}\n`,
|
|
@@ -4439,24 +4880,13 @@ function recordOrSkipDeliveredMessage(data: any): boolean {
|
|
|
4439
4880
|
}
|
|
4440
4881
|
return skip;
|
|
4441
4882
|
}
|
|
4442
|
-
|
|
4443
|
-
|
|
4444
|
-
|
|
4445
|
-
|
|
4446
|
-
|
|
4447
|
-
|
|
4448
|
-
|
|
4449
|
-
let wsReconnectAttempt = 0;
|
|
4450
|
-
let reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
4451
|
-
// Tracked so shutdown / switchIdentity can cancel a pending auth_ok backfill.
|
|
4452
|
-
let backfillTimer: ReturnType<typeof setTimeout> | null = null;
|
|
4453
|
-
|
|
4454
|
-
function scheduleReconnect(delayMs: number) {
|
|
4455
|
-
if (shuttingDown) return; // don't resurrect the socket after shutdown
|
|
4456
|
-
if (reconnectTimer) clearTimeout(reconnectTimer);
|
|
4457
|
-
reconnectTimer = setTimeout(() => {
|
|
4458
|
-
reconnectTimer = null;
|
|
4459
|
-
connectWS();
|
|
4883
|
+
|
|
4884
|
+
function scheduleReconnect(delayMs: number, slot: ProfileSlot | null = activeSlot) {
|
|
4885
|
+
if (shuttingDown || !slot) return; // don't resurrect the socket after shutdown
|
|
4886
|
+
if (slot.reconnectTimer) clearTimeout(slot.reconnectTimer);
|
|
4887
|
+
slot.reconnectTimer = setTimeout(() => {
|
|
4888
|
+
slot.reconnectTimer = null;
|
|
4889
|
+
connectWS(slot);
|
|
4460
4890
|
}, delayMs);
|
|
4461
4891
|
}
|
|
4462
4892
|
|
|
@@ -4465,37 +4895,20 @@ function scheduleReconnect(delayMs: number) {
|
|
|
4465
4895
|
* was unreliable or down. Invoked 2s after every auth_ok — covers
|
|
4466
4896
|
* both cold start (empty cursors = no backfill) and reconnect
|
|
4467
4897
|
* (cursor points to last-seen, REST returns the gap).
|
|
4468
|
-
*
|
|
4469
|
-
* Iterates channels we believe we're in (populated from the
|
|
4470
|
-
* channel_created events that follow auth_ok). For each, GETs
|
|
4471
|
-
* /api/channels/:id/messages?after=<lastSeenTs> and re-injects
|
|
4472
|
-
* every message through handleWSMessage — same code path as live
|
|
4473
|
-
* delivery, so @mention detection + notification emission go
|
|
4474
|
-
* through the same gate. Self-messages are filtered by the handler
|
|
4475
|
-
* (sender_id !== AGENT_ID).
|
|
4476
|
-
*
|
|
4477
|
-
* Deduplication is by message id in handleWSMessage. Timestamp cursors
|
|
4478
|
-
* decide what backfill requests should ask for, but they are not a safe
|
|
4479
|
-
* identity check under live/backfill races or out-of-order delivery.
|
|
4480
4898
|
*/
|
|
4481
|
-
async function backfillAllChannels(): Promise<void> {
|
|
4482
|
-
if (knownChannels.size === 0) return;
|
|
4483
|
-
for (const channelId of knownChannels) {
|
|
4899
|
+
async function backfillAllChannels(slot: ProfileSlot | null = activeSlot): Promise<void> {
|
|
4900
|
+
if (!slot || slot.knownChannels.size === 0) return;
|
|
4901
|
+
for (const channelId of slot.knownChannels) {
|
|
4484
4902
|
try {
|
|
4485
|
-
const after = lastSeenMessageTs.get(channelId);
|
|
4903
|
+
const after = slot.lastSeenMessageTs.get(channelId);
|
|
4486
4904
|
const params = after ? `?after=${encodeURIComponent(after)}&limit=50` : `?limit=1`;
|
|
4487
4905
|
const url = `${REST_URL}/api/channels/${encodeURIComponent(channelId)}/messages${params}`;
|
|
4488
4906
|
const res = await apiFetch(url, {
|
|
4489
|
-
headers:
|
|
4907
|
+
headers: slot.token ? { "Authorization": `Bearer ${slot.token}` } : {},
|
|
4490
4908
|
});
|
|
4491
4909
|
if (!res.ok) continue;
|
|
4492
4910
|
const data = await res.json() as { messages?: any[] };
|
|
4493
4911
|
const msgs = data.messages || [];
|
|
4494
|
-
// No cursor yet (cold start / freshly joined channel): DON'T replay —
|
|
4495
|
-
// seed the cursor from the newest message so later backfills fetch only
|
|
4496
|
-
// genuinely new messages. Replaying here would surface a possibly
|
|
4497
|
-
// hours-old DM/@mention as a live notification (contract: empty cursor
|
|
4498
|
-
// = no backfill).
|
|
4499
4912
|
if (!after) {
|
|
4500
4913
|
let newestTs = "";
|
|
4501
4914
|
for (const m of msgs) {
|
|
@@ -4503,16 +4916,13 @@ async function backfillAllChannels(): Promise<void> {
|
|
|
4503
4916
|
if (t > newestTs) newestTs = t;
|
|
4504
4917
|
}
|
|
4505
4918
|
if (newestTs) {
|
|
4506
|
-
lastSeenMessageTs.set(channelId, newestTs);
|
|
4507
|
-
|
|
4919
|
+
slot.lastSeenMessageTs.set(channelId, newestTs);
|
|
4920
|
+
scheduleSlotLastSeenMessageTsSave(slot);
|
|
4508
4921
|
}
|
|
4509
4922
|
continue;
|
|
4510
4923
|
}
|
|
4511
|
-
// Filter out self-messages upfront (faster than re-entering the
|
|
4512
|
-
// handler just to bail) and typing placeholders (plugin ignores
|
|
4513
|
-
// them anyway).
|
|
4514
4924
|
const replay = msgs.filter((m: any) =>
|
|
4515
|
-
m && m.sender_id !==
|
|
4925
|
+
m && m.sender_id !== slot.agentId && m.content !== "__typing__");
|
|
4516
4926
|
const dedupedReplay = after
|
|
4517
4927
|
? replay.filter((m: any) => {
|
|
4518
4928
|
const msgTs = normalizeTimestampForCursor(m?.timestamp, "after");
|
|
@@ -4522,14 +4932,11 @@ async function backfillAllChannels(): Promise<void> {
|
|
|
4522
4932
|
: replay;
|
|
4523
4933
|
if (dedupedReplay.length === 0) continue;
|
|
4524
4934
|
process.stderr.write(`[agentchat] Backfill ${channelId.slice(0, 12)}: ${dedupedReplay.length} missed msg(s)\n`);
|
|
4525
|
-
// Sort ascending so replay order matches live chronology —
|
|
4526
|
-
// lastSeenMessageTs advances monotonically.
|
|
4527
4935
|
dedupedReplay.sort((a: any, b: any) => String(a.timestamp).localeCompare(String(b.timestamp)));
|
|
4528
4936
|
for (const m of dedupedReplay) {
|
|
4529
4937
|
try {
|
|
4530
|
-
|
|
4531
|
-
|
|
4532
|
-
await currentHandleWSMessage({ ...m, type: "message", __source: "backfill" });
|
|
4938
|
+
if (slot.handleWSMessage) {
|
|
4939
|
+
await slot.handleWSMessage({ ...m, type: "message", __source: "backfill" });
|
|
4533
4940
|
}
|
|
4534
4941
|
} catch (e) {
|
|
4535
4942
|
process.stderr.write(`[agentchat] Backfill replay error: ${e}\n`);
|
|
@@ -4541,42 +4948,85 @@ async function backfillAllChannels(): Promise<void> {
|
|
|
4541
4948
|
}
|
|
4542
4949
|
}
|
|
4543
4950
|
|
|
4544
|
-
|
|
4545
|
-
|
|
4546
|
-
|
|
4547
|
-
|
|
4951
|
+
/**
|
|
4952
|
+
* Automatically connect any additional unlocked profiles in `session-binds.json`
|
|
4953
|
+
* that are bound to currently open Antigravity conversations.
|
|
4954
|
+
*/
|
|
4955
|
+
function syncOpenBoundSessions(): void {
|
|
4956
|
+
if (toolOnlyMode || shuttingDown) return;
|
|
4957
|
+
const agyHost = discoverAntigravityHost();
|
|
4958
|
+
if (!agyHost || agyHost.openConversations.length === 0) return;
|
|
4959
|
+
const binds = loadSessionBinds(configDir);
|
|
4960
|
+
for (const cid of agyHost.openConversations) {
|
|
4961
|
+
const boundProf = binds[cid];
|
|
4962
|
+
if (!boundProf || profileSlots.has(boundProf)) continue;
|
|
4963
|
+
const boundPath = nameToPath(boundProf);
|
|
4964
|
+
if (!existsSync(boundPath)) continue;
|
|
4965
|
+
try {
|
|
4966
|
+
const candidate = readIdentityProfile(boundPath);
|
|
4967
|
+
validateIdentityProfile(candidate, boundPath);
|
|
4968
|
+
const lock = checkAgentLock({
|
|
4969
|
+
lockDir,
|
|
4970
|
+
agentId: candidate.agent_id,
|
|
4971
|
+
currentSessionId: cid,
|
|
4972
|
+
lockOwnerPid,
|
|
4973
|
+
});
|
|
4974
|
+
if (lock.locked) continue;
|
|
4975
|
+
const sess: DetectedSession = { sessionId: cid, runtime: "antigravity" };
|
|
4976
|
+
acquireAgentLock({
|
|
4977
|
+
lockDir,
|
|
4978
|
+
agentId: candidate.agent_id,
|
|
4979
|
+
profileName: boundProf,
|
|
4980
|
+
sessionId: cid,
|
|
4981
|
+
runtime: "antigravity",
|
|
4982
|
+
});
|
|
4983
|
+
const slot = createProfileSlot({
|
|
4984
|
+
profileName: boundProf,
|
|
4985
|
+
profileFile: boundPath,
|
|
4986
|
+
profile: candidate,
|
|
4987
|
+
agentId: candidate.agent_id,
|
|
4988
|
+
token: candidate.token,
|
|
4989
|
+
capabilities: candidate.capabilities || ["claude-code", "coding", "chat"],
|
|
4990
|
+
runtimeSession: sess,
|
|
4991
|
+
});
|
|
4992
|
+
profileSlots.set(boundProf, slot);
|
|
4993
|
+
slot.heartbeat.start();
|
|
4994
|
+
connectWS(slot);
|
|
4995
|
+
if (!activeSlot) activateSlot(slot, sess);
|
|
4996
|
+
} catch {}
|
|
4997
|
+
}
|
|
4998
|
+
}
|
|
4999
|
+
|
|
5000
|
+
function connectWS(slot: ProfileSlot | null = activeSlot) {
|
|
5001
|
+
if (shuttingDown || !slot) return;
|
|
4548
5002
|
|
|
4549
|
-
// Capture THIS socket locally. Every handler below guards on
|
|
4550
|
-
// `ws !== socket`, so a superseded socket (e.g. a dead-TCP connection
|
|
4551
|
-
// whose close event is delayed past the point a replacement is already
|
|
4552
|
-
// live) can never clobber the current session or schedule a duplicate
|
|
4553
|
-
// reconnect — the root cause of the orphan/double-connection race.
|
|
4554
5003
|
let socket: WebSocket;
|
|
4555
5004
|
try {
|
|
4556
5005
|
socket = new WebSocket(WS_URL);
|
|
4557
|
-
ws = socket;
|
|
5006
|
+
slot.ws = socket;
|
|
5007
|
+
if (activeSlot === slot) ws = socket;
|
|
4558
5008
|
} catch (e) {
|
|
4559
5009
|
process.stderr.write(`[agentchat] WebSocket constructor failed: ${e}, retrying in 5s\n`);
|
|
4560
|
-
scheduleReconnect(5000);
|
|
5010
|
+
scheduleReconnect(5000, slot);
|
|
4561
5011
|
return;
|
|
4562
5012
|
}
|
|
4563
5013
|
|
|
4564
|
-
|
|
4565
|
-
if (ws !== socket) return;
|
|
5014
|
+
socket.onopen = () => {
|
|
5015
|
+
if (slot.ws !== socket) return;
|
|
4566
5016
|
try {
|
|
4567
5017
|
socket.send(JSON.stringify({
|
|
4568
5018
|
type: "auth",
|
|
4569
|
-
agent_id:
|
|
4570
|
-
token:
|
|
4571
|
-
capabilities:
|
|
5019
|
+
agent_id: slot.agentId,
|
|
5020
|
+
token: slot.token,
|
|
5021
|
+
capabilities: slot.capabilities,
|
|
4572
5022
|
}));
|
|
4573
5023
|
} catch (e) {
|
|
4574
5024
|
process.stderr.write(`[agentchat] Auth send failed: ${e}\n`);
|
|
4575
5025
|
}
|
|
4576
5026
|
};
|
|
4577
5027
|
|
|
4578
|
-
|
|
4579
|
-
if (ws !== socket) return;
|
|
5028
|
+
socket.onmessage = async (event) => {
|
|
5029
|
+
if (slot.ws !== socket) return;
|
|
4580
5030
|
let data: any;
|
|
4581
5031
|
try { data = JSON.parse(String(event.data)); } catch { return; }
|
|
4582
5032
|
if (data && typeof data === "object" && !data.__source) data.__source = "live";
|
|
@@ -4585,11 +5035,11 @@ function connectWS() {
|
|
|
4585
5035
|
}
|
|
4586
5036
|
};
|
|
4587
5037
|
|
|
4588
|
-
|
|
5038
|
+
slot.handleWSMessage = handleWSMessage;
|
|
4589
5039
|
async function handleWSMessage(data: any) {
|
|
4590
|
-
|
|
4591
5040
|
if (data.type === "pong") {
|
|
4592
|
-
heartbeat.receivedPong();
|
|
5041
|
+
slot!.heartbeat.receivedPong();
|
|
5042
|
+
syncOpenBoundSessions();
|
|
4593
5043
|
return;
|
|
4594
5044
|
}
|
|
4595
5045
|
if ((data.type === "hidden_identity.reveal" || data.type === "hidden_identity.finished") && typeof data.game_id === "string") {
|
|
@@ -4597,58 +5047,29 @@ function connectWS() {
|
|
|
4597
5047
|
}
|
|
4598
5048
|
|
|
4599
5049
|
if (data.type === "auth_ok") {
|
|
4600
|
-
sessionId = data.session_id;
|
|
4601
|
-
|
|
4602
|
-
|
|
4603
|
-
|
|
4604
|
-
|
|
4605
|
-
|
|
4606
|
-
|
|
4607
|
-
|
|
4608
|
-
|
|
4609
|
-
// per-channel REST fetch and re-injects each missed message
|
|
4610
|
-
// through handleWSMessage so @mention detection + notification
|
|
4611
|
-
// path is identical to live delivery — no divergent code paths.
|
|
4612
|
-
if (backfillTimer) clearTimeout(backfillTimer);
|
|
4613
|
-
backfillTimer = setTimeout(() => {
|
|
4614
|
-
backfillTimer = null;
|
|
4615
|
-
if (!shuttingDown) void backfillAllChannels();
|
|
5050
|
+
slot!.sessionId = data.session_id;
|
|
5051
|
+
if (activeSlot === slot) sessionId = data.session_id;
|
|
5052
|
+
slot!.wsReconnectAttempt = 0;
|
|
5053
|
+
slot!.heartbeat.receivedPong();
|
|
5054
|
+
process.stderr.write(`[agentchat] Connected as ${slot!.agentId}\n`);
|
|
5055
|
+
if (slot!.backfillTimer) clearTimeout(slot!.backfillTimer);
|
|
5056
|
+
slot!.backfillTimer = setTimeout(() => {
|
|
5057
|
+
slot!.backfillTimer = null;
|
|
5058
|
+
if (!shuttingDown) void backfillAllChannels(slot!);
|
|
4616
5059
|
}, 2000);
|
|
4617
5060
|
} else if ((data.type === "message" || data.type === "thread_reply") &&
|
|
4618
|
-
data.sender_id ===
|
|
5061
|
+
data.sender_id === slot!.agentId && typeof data.content === "string" && data.content !== "__typing__" &&
|
|
4619
5062
|
!["loop_tick", "slash_input", "loop_status", "slash_response"].includes(data.meta?.kind)) {
|
|
4620
|
-
|
|
4621
|
-
stopTypingHeartbeat(data.channel_id);
|
|
5063
|
+
stopTypingHeartbeat(data.channel_id, slot!);
|
|
4622
5064
|
} else if (
|
|
4623
|
-
// thread_reply is a bidirectional protocol frame (Server -> Client too).
|
|
4624
|
-
// Route it through the same @mention / notification / cursor path as a
|
|
4625
|
-
// plain message, otherwise thread @mentions are silently invisible.
|
|
4626
5065
|
(data.type === "message" || data.type === "thread_reply") &&
|
|
4627
|
-
|
|
4628
|
-
// equals AGENT_ID when the loop owner is THIS plugin. Without this
|
|
4629
|
-
// exception the outer "skip own messages" gate swallows every tick
|
|
4630
|
-
// before the slash filter below ever sees it, so /loop silently
|
|
4631
|
-
// never fires the LLM for the loop creator. Empirically confirmed
|
|
4632
|
-
// 2026-05-03 in dm-dsplvj (loop_39d587464e3c): tick landed in
|
|
4633
|
-
// history but never surfaced to the plugin's LLM path.
|
|
4634
|
-
(data.sender_id !== AGENT_ID ||
|
|
5066
|
+
(data.sender_id !== slot!.agentId ||
|
|
4635
5067
|
(data.meta &&
|
|
4636
5068
|
typeof data.meta === "object" &&
|
|
4637
5069
|
(data.meta as { kind?: unknown }).kind === "loop_tick"))
|
|
4638
5070
|
) {
|
|
4639
|
-
// 跳过 typing 状态消息
|
|
4640
5071
|
if (data.content === "__typing__") return;
|
|
4641
5072
|
|
|
4642
|
-
// Slash side-channel skip (boss directive 2026-05-03 msg:caf95079).
|
|
4643
|
-
// /loop, /show-loop, /stop-loop are command channels — LLM must NOT
|
|
4644
|
-
// be invoked by them. Server tags envelopes server-authoritatively:
|
|
4645
|
-
// • meta.kind="slash_input" — user's literal slash text (hub.ts
|
|
4646
|
-
// preprocessSlashCommand, force-overwrite to prevent client spoof)
|
|
4647
|
-
// • meta.kind="loop_status" — system reply from slash-router
|
|
4648
|
-
// (success/error/placeholder for /loop /stop-loop /show-loop)
|
|
4649
|
-
// loop_tick (broadcastLoopTick) is intentionally NOT filtered —
|
|
4650
|
-
// that's the engine firing the loop owner's LLM and IS meant for
|
|
4651
|
-
// consumption.
|
|
4652
5073
|
const metaKind = (data.meta && typeof data.meta === "object")
|
|
4653
5074
|
? (data.meta as { kind?: unknown }).kind
|
|
4654
5075
|
: undefined;
|
|
@@ -4660,70 +5081,40 @@ function connectWS() {
|
|
|
4660
5081
|
return;
|
|
4661
5082
|
}
|
|
4662
5083
|
|
|
4663
|
-
if (recordOrSkipDeliveredMessage(data)) return;
|
|
5084
|
+
if (recordOrSkipDeliveredMessage(data, slot!)) return;
|
|
4664
5085
|
|
|
4665
|
-
// Task #119: record the timestamp so a future auth_ok backfill
|
|
4666
|
-
// knows where to resume. Only advance forward (defensive against
|
|
4667
|
-
// out-of-order delivery from Redis subscribe vs REST backfill replay).
|
|
4668
|
-
// Persist on a short debounce so busy public channels do not turn
|
|
4669
|
-
// every silent message into a synchronous disk write.
|
|
4670
5086
|
if (typeof data.channel_id === "string" && typeof data.timestamp === "string") {
|
|
4671
|
-
const prev = lastSeenMessageTs.get(data.channel_id) || "";
|
|
5087
|
+
const prev = slot!.lastSeenMessageTs.get(data.channel_id) || "";
|
|
4672
5088
|
const currentTs = normalizeTimestampForCursor(data.timestamp, "after") || data.timestamp;
|
|
4673
5089
|
const prevTs = normalizeTimestampForCursor(prev, "after") || prev;
|
|
4674
5090
|
if (currentTs > prevTs) {
|
|
4675
|
-
lastSeenMessageTs.set(data.channel_id, data.timestamp);
|
|
4676
|
-
|
|
5091
|
+
slot!.lastSeenMessageTs.set(data.channel_id, data.timestamp);
|
|
5092
|
+
scheduleSlotLastSeenMessageTsSave(slot!);
|
|
4677
5093
|
}
|
|
4678
5094
|
}
|
|
4679
5095
|
|
|
4680
5096
|
const isDM = data.channel_id?.startsWith("dm-");
|
|
4681
|
-
|
|
4682
|
-
// (mentions.ts) for why the second clause must not fire on incidental
|
|
4683
|
-
// `(<id>)` substrings like "User joined: name (acc_xyz)".
|
|
4684
|
-
const isMentioned = matchesMention(data.content || "", AGENT_ID || "");
|
|
5097
|
+
const isMentioned = matchesMention(data.content || "", slot!.agentId || "");
|
|
4685
5098
|
const activeHi = activeHiddenIdentityForChannel(data.channel_id);
|
|
4686
|
-
|
|
4687
|
-
// in this same channel for both MCP notifications and host wake transports.
|
|
4688
|
-
// Another bot's tick does not grant this exception.
|
|
4689
|
-
const isOwnLoopTick = metaKind === "loop_tick" && data.sender_id === AGENT_ID;
|
|
5099
|
+
const isOwnLoopTick = metaKind === "loop_tick" && data.sender_id === slot!.agentId;
|
|
4690
5100
|
|
|
4691
5101
|
if (isDM || isMentioned || activeHi || isOwnLoopTick) {
|
|
4692
|
-
|
|
4693
|
-
|
|
4694
|
-
// The hub now cross-pod-broadcasts agent typing frames (cross_pod:true)
|
|
4695
|
-
// and never persists them, so this is ephemeral + zero-write. Stops when
|
|
4696
|
-
// we reply to the channel (reply handler), at the 120s cap, or on shutdown.
|
|
4697
|
-
if (isDM || isMentioned) startTypingHeartbeat(data.channel_id);
|
|
4698
|
-
|
|
4699
|
-
// For @mention in channels, fetch context since last mention
|
|
5102
|
+
if (isDM || isMentioned) startTypingHeartbeat(data.channel_id, slot!);
|
|
5103
|
+
|
|
4700
5104
|
let contextPrefix = "";
|
|
4701
5105
|
if (!isDM && isMentioned) {
|
|
4702
5106
|
try {
|
|
4703
|
-
const
|
|
4704
|
-
|
|
4705
|
-
// and per-message-content trimming below. Boss msg:fc8b9b1a —
|
|
4706
|
-
// long-silent agents would pull a 200-message backlog on first
|
|
4707
|
-
// @mention, blowing up small-context models. 50 + 15KB +
|
|
4708
|
-
// per-msg 2KB matches "recent conversation" without overshoot.
|
|
5107
|
+
const mentionKey = `${slot!.agentId}:${data.channel_id}`;
|
|
5108
|
+
const lastTs = lastMentionTimestamp.get(mentionKey) || lastMentionTimestamp.get(data.channel_id) || "";
|
|
4709
5109
|
const params = `limit=50${lastTs ? '&after=' + encodeURIComponent(lastTs) : ''}`;
|
|
4710
5110
|
const historyUrl = `${REST_URL}/api/channels/${encodeURIComponent(data.channel_id)}/messages?${params}`;
|
|
4711
|
-
// Channel reads are auth-gated (login for public channels,
|
|
4712
|
-
// membership for private). Without the Bearer header the
|
|
4713
|
-
// MCP agent would get 401/403 and answer the @mention
|
|
4714
|
-
// without any conversation context.
|
|
4715
5111
|
const historyRes = await apiFetch(historyUrl, {
|
|
4716
|
-
headers:
|
|
5112
|
+
headers: slot!.token ? { "Authorization": `Bearer ${slot!.token}` } : {},
|
|
4717
5113
|
});
|
|
4718
5114
|
if (historyRes.ok) {
|
|
4719
5115
|
const historyData = await historyRes.json() as any;
|
|
4720
5116
|
let msgs = (historyData.messages || [])
|
|
4721
5117
|
.filter((m: any) => m.id !== data.id && m.content !== "__typing__");
|
|
4722
|
-
// Cumulative byte cap (newest-first walk so we keep the most
|
|
4723
|
-
// recent messages when total exceeds the budget). Per-message
|
|
4724
|
-
// content also clipped to 2KB to defang occasional copy-paste
|
|
4725
|
-
// walls of text — a single mega-message no longer eats the
|
|
4726
|
-
// whole budget alone.
|
|
4727
5118
|
let totalBytes = 0;
|
|
4728
5119
|
const maxBytes = 15_000;
|
|
4729
5120
|
const maxPerMsg = 2_000;
|
|
@@ -4733,7 +5124,7 @@ function connectWS() {
|
|
|
4733
5124
|
const clipped = raw.length > maxPerMsg
|
|
4734
5125
|
? raw.slice(0, maxPerMsg) + " …[truncated]"
|
|
4735
5126
|
: raw;
|
|
4736
|
-
const size = Buffer.byteLength(clipped, "utf8");
|
|
5127
|
+
const size = Buffer.byteLength(clipped, "utf8");
|
|
4737
5128
|
if (totalBytes + size > maxBytes) break;
|
|
4738
5129
|
totalBytes += size;
|
|
4739
5130
|
trimmed.unshift({ ...msgs[i], content: clipped });
|
|
@@ -4741,7 +5132,7 @@ function connectWS() {
|
|
|
4741
5132
|
const truncatedMsgs = trimmed.length < msgs.length;
|
|
4742
5133
|
if (trimmed.length > 0) {
|
|
4743
5134
|
const context = trimmed
|
|
4744
|
-
.map((m: any) => `${m.sender_id}: ${m.content}`)
|
|
5135
|
+
.map((m: any) => `${m.sender_id}: ${m.content}${formatWakeAttachments(m.attachments)}`)
|
|
4745
5136
|
.join("\n");
|
|
4746
5137
|
const note = truncatedMsgs
|
|
4747
5138
|
? `[频道上下文 - 最近 ${trimmed.length} 条消息(更早的已截断保护上下文窗口)]`
|
|
@@ -4749,7 +5140,7 @@ function connectWS() {
|
|
|
4749
5140
|
contextPrefix = `${note}\n${context}\n\n[你被 @mention 了,请回复]\n`;
|
|
4750
5141
|
}
|
|
4751
5142
|
}
|
|
4752
|
-
|
|
5143
|
+
lastMentionTimestamp.set(mentionKey, data.timestamp);
|
|
4753
5144
|
lastMentionTimestamp.set(data.channel_id, data.timestamp);
|
|
4754
5145
|
saveMentionTimestamps(lastMentionTimestamp);
|
|
4755
5146
|
} catch (e) {
|
|
@@ -4762,12 +5153,12 @@ function connectWS() {
|
|
|
4762
5153
|
|
|
4763
5154
|
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)}\n`);
|
|
4764
5155
|
|
|
4765
|
-
// 推送给 Claude Code
|
|
4766
5156
|
try {
|
|
5157
|
+
const notifAtt = formatWakeAttachments(data.attachments);
|
|
4767
5158
|
await server.notification({
|
|
4768
5159
|
method: process.env.CLAUDE_CODE_ENTRYPOINT ? "notifications/claude/channel" : "notifications/chat/channel",
|
|
4769
5160
|
params: {
|
|
4770
|
-
content: contextPrefix + data.content,
|
|
5161
|
+
content: contextPrefix + (data.content || "") + notifAtt,
|
|
4771
5162
|
meta: {
|
|
4772
5163
|
chat_id: data.channel_id,
|
|
4773
5164
|
sender_id: data.sender_id,
|
|
@@ -4779,30 +5170,20 @@ function connectWS() {
|
|
|
4779
5170
|
} catch (notifErr) {
|
|
4780
5171
|
process.stderr.write(`[agentchat] Notification FAILED: ${notifErr}\n`);
|
|
4781
5172
|
}
|
|
4782
|
-
|
|
4783
|
-
|
|
4784
|
-
|
|
4785
|
-
|
|
4786
|
-
// + an HMAC signature (AGENTCHAT_WAKE_SECRET) so the receiver can verify.
|
|
4787
|
-
// Grok mode (AGENTCHAT_WAKE_MODE=grok): a same-machine Grok gateway expects
|
|
4788
|
-
// loopback /api/sendPrompt with its own Bearer (read from gateway.json) and
|
|
4789
|
-
// a {agentId, prompt} body — a different transport, same trigger.
|
|
5173
|
+
|
|
5174
|
+
const slotProfName = slot!.profileName || profileNameFromPath(slot!.profileFile);
|
|
5175
|
+
const slotRuntime = slot!.runtimeSession?.runtime;
|
|
5176
|
+
|
|
4790
5177
|
if (process.env.AGENTCHAT_WAKE_MODE === "grok") {
|
|
4791
|
-
// 1:1 mapping: this plugin instance (one AgentsChat agent) wakes ONE Grok
|
|
4792
|
-
// agent. Explicit AGENTCHAT_GROK_AGENT_ID wins; else resolve by matching
|
|
4793
|
-
// the AgentsChat display name against the gateway's listAgents (warns);
|
|
4794
|
-
// else fail closed (no wake). The gateway token/port come from gateway.json.
|
|
4795
5178
|
void (async () => {
|
|
4796
5179
|
try {
|
|
4797
5180
|
const { readFileSync, existsSync } = await import("node:fs");
|
|
4798
|
-
// env override wins; else first existing candidate (~/.grok default,
|
|
4799
|
-
// production GrokBot /home/box/sand-data) — never guess a path blindly.
|
|
4800
5181
|
const gwPath = resolveGrokGatewayPath(process.env.AGENTCHAT_GROK_GATEWAY, existsSync);
|
|
4801
5182
|
let agentId = process.env.AGENTCHAT_GROK_AGENT_ID || "";
|
|
4802
5183
|
if (!agentId) {
|
|
4803
5184
|
agentId = (await resolveGrokAgentId({
|
|
4804
5185
|
explicitId: "",
|
|
4805
|
-
agentschatName: profile.display_name ||
|
|
5186
|
+
agentschatName: slot!.profile.display_name || slot!.agentId,
|
|
4806
5187
|
listAgents: async () => {
|
|
4807
5188
|
const gwcfg = JSON.parse(readFileSync(gwPath, "utf8"));
|
|
4808
5189
|
const token = grokBearerFromGatewayConfig(gwcfg);
|
|
@@ -4824,26 +5205,55 @@ function connectWS() {
|
|
|
4824
5205
|
}
|
|
4825
5206
|
})();
|
|
4826
5207
|
} else if (process.env.AGENTCHAT_WAKE_URL) {
|
|
5208
|
+
const route = resolveSessionForAgent(slot!.agentId, { configDir });
|
|
5209
|
+
const targetSessionId =
|
|
5210
|
+
route?.sessionId ||
|
|
5211
|
+
findBoundSessionForProfile(configDir, slotProfName) ||
|
|
5212
|
+
slot!.runtimeSession?.sessionId ||
|
|
5213
|
+
undefined;
|
|
4827
5214
|
void fireWake(data, {
|
|
4828
5215
|
url: process.env.AGENTCHAT_WAKE_URL,
|
|
4829
5216
|
secret: process.env.AGENTCHAT_WAKE_SECRET,
|
|
5217
|
+
targetSessionId,
|
|
4830
5218
|
});
|
|
4831
|
-
} else if (
|
|
4832
|
-
|
|
5219
|
+
} else if (
|
|
5220
|
+
slotRuntime === "zcode" ||
|
|
5221
|
+
process.env.AGENTCHAT_WAKE_MODE === "zcode" ||
|
|
5222
|
+
Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")))
|
|
5223
|
+
) {
|
|
4833
5224
|
const zcodeSid =
|
|
4834
|
-
|
|
4835
|
-
|
|
5225
|
+
findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("sess_")) ||
|
|
5226
|
+
(slotRuntime === "zcode" ? slot!.runtimeSession?.sessionId : "") ||
|
|
4836
5227
|
"";
|
|
4837
5228
|
if (zcodeSid) {
|
|
4838
5229
|
void fireZcodeWake(data, {
|
|
4839
5230
|
sessionId: zcodeSid,
|
|
4840
|
-
workspacePath: runtimeSession?.workspacePath,
|
|
4841
|
-
profileName:
|
|
5231
|
+
workspacePath: slot!.runtimeSession?.workspacePath,
|
|
5232
|
+
profileName: slotProfName ?? undefined,
|
|
4842
5233
|
lockOwnerPid: process.pid,
|
|
4843
5234
|
contextPrefix,
|
|
4844
5235
|
logger: (m) => process.stderr.write(`${m}\n`),
|
|
4845
5236
|
});
|
|
4846
5237
|
}
|
|
5238
|
+
} else if (
|
|
5239
|
+
slotRuntime === "dsh" ||
|
|
5240
|
+
isDshHostProcess() ||
|
|
5241
|
+
Boolean(findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")))
|
|
5242
|
+
) {
|
|
5243
|
+
const dshSid =
|
|
5244
|
+
findBoundSessionForProfile(configDir, slotProfName, (sid) => sid.startsWith("session-")) ||
|
|
5245
|
+
resolveSessionForAgent(slot!.agentId, { configDir })?.sessionId ||
|
|
5246
|
+
(slotRuntime === "dsh" ? slot!.runtimeSession?.sessionId : "") ||
|
|
5247
|
+
undefined;
|
|
5248
|
+
const dshWakeUrl =
|
|
5249
|
+
process.env.DSH_WAKE_URL ||
|
|
5250
|
+
process.env.AGENTSCHAT_DSH_WAKE_URL ||
|
|
5251
|
+
"http://127.0.0.1:8799/wake";
|
|
5252
|
+
void fireWake(data, {
|
|
5253
|
+
url: dshWakeUrl,
|
|
5254
|
+
secret: process.env.DSH_WAKE_SECRET ?? process.env.AGENTCHAT_WAKE_SECRET,
|
|
5255
|
+
targetSessionId: dshSid,
|
|
5256
|
+
});
|
|
4847
5257
|
} else {
|
|
4848
5258
|
// Native Antigravity (agy) Connect-RPC wake when running under language_server
|
|
4849
5259
|
void (async () => {
|
|
@@ -4852,18 +5262,17 @@ function connectWS() {
|
|
|
4852
5262
|
const lsAddress = process.env.ANTIGRAVITY_LS_ADDRESS?.trim() || "";
|
|
4853
5263
|
const csrfToken = (process.env.ANTIGRAVITY_CSRF_TOKEN || agyHost?.csrfToken || "").trim();
|
|
4854
5264
|
if (!agyHost && !lsAddress) return;
|
|
4855
|
-
const activeProfName = profileNameFromPath(activeProfileFile);
|
|
4856
5265
|
const allBinds = loadSessionBinds(configDir);
|
|
4857
5266
|
let targetCid =
|
|
4858
|
-
findBoundSessionForProfile(configDir,
|
|
4859
|
-
(
|
|
5267
|
+
findBoundSessionForProfile(configDir, slotProfName, (sid) => /^[0-9a-f-]{36}$/i.test(sid)) ||
|
|
5268
|
+
(slotRuntime === "antigravity" ? slot!.runtimeSession?.sessionId : "") ||
|
|
4860
5269
|
"";
|
|
4861
5270
|
if (!targetCid && agyHost) {
|
|
4862
5271
|
if (agyHost.openConversations.length === 1) {
|
|
4863
5272
|
targetCid = agyHost.openConversations[0]!;
|
|
4864
5273
|
} else if (agyHost.openConversations.length > 1) {
|
|
4865
5274
|
const unboundOrSame = agyHost.openConversations.find(
|
|
4866
|
-
(cid) => !allBinds[cid] || allBinds[cid] ===
|
|
5275
|
+
(cid) => !allBinds[cid] || allBinds[cid] === slotProfName,
|
|
4867
5276
|
);
|
|
4868
5277
|
targetCid = unboundOrSame || agyHost.openConversations[0]!;
|
|
4869
5278
|
}
|
|
@@ -4885,94 +5294,70 @@ function connectWS() {
|
|
|
4885
5294
|
}
|
|
4886
5295
|
if (activeHi) clearFinishedHiddenIdentityGamesFromMessage(data);
|
|
4887
5296
|
} else {
|
|
4888
|
-
// Channel message without @mention → silent (just log)
|
|
4889
5297
|
rateLimitedLog(
|
|
4890
5298
|
"silent-channel-message",
|
|
4891
5299
|
`[agentchat] [silent] ${String(data.sender_id ?? "?").slice(0, 8)} in ${String(data.channel_id ?? "?").slice(0, 12)}: ${String(data.content ?? "").slice(0, 30)}\n`,
|
|
4892
5300
|
);
|
|
4893
5301
|
}
|
|
4894
5302
|
} else if (data.type === "channel_created") {
|
|
4895
|
-
// 自动加入新频道
|
|
4896
5303
|
try {
|
|
4897
|
-
ws?.send(JSON.stringify({
|
|
5304
|
+
slot!.ws?.send(JSON.stringify({
|
|
4898
5305
|
type: "join_channel",
|
|
4899
5306
|
channel_id: data.channel_id,
|
|
4900
|
-
agent_id:
|
|
5307
|
+
agent_id: slot!.agentId,
|
|
4901
5308
|
}));
|
|
4902
5309
|
} catch {}
|
|
4903
5310
|
process.stderr.write(`[agentchat] Joined channel: ${data.name}\n`);
|
|
4904
|
-
|
|
4905
|
-
if (typeof data.channel_id === "string") knownChannels.add(data.channel_id);
|
|
5311
|
+
if (typeof data.channel_id === "string") slot!.knownChannels.add(data.channel_id);
|
|
4906
5312
|
} else if (data.type === "shard_moved") {
|
|
4907
|
-
// Server instance shutting down or channel moved — a PLANNED hop.
|
|
4908
|
-
// Detach the socket's onclose so it can't also run the unplanned
|
|
4909
|
-
// backoff path, reset the backoff counter, and fast-reconnect. This
|
|
4910
|
-
// keeps a rolling deploy (several pods closing in sequence) from
|
|
4911
|
-
// pushing each successive reconnect 2s, 4s, 6s ... further out.
|
|
4912
5313
|
process.stderr.write(`[agentchat] Shard moved, reconnecting...\n`);
|
|
4913
5314
|
if (data.redirect_url) {
|
|
4914
5315
|
const newUrl = data.redirect_url.replace(/^https/, "wss").replace(/^http/, "ws") + "/ws";
|
|
4915
5316
|
process.stderr.write(`[agentchat] Redirecting to: ${newUrl}\n`);
|
|
4916
|
-
// Note: for simplicity we reconnect to original URL and let /api/shard handle routing
|
|
4917
5317
|
}
|
|
4918
|
-
if (ws) { ws.onclose = null; try { ws.close(); } catch {} }
|
|
4919
|
-
ws = null;
|
|
4920
|
-
sessionId = null;
|
|
4921
|
-
|
|
4922
|
-
|
|
5318
|
+
if (slot!.ws) { slot!.ws.onclose = null; try { slot!.ws.close(); } catch {} }
|
|
5319
|
+
slot!.ws = null;
|
|
5320
|
+
slot!.sessionId = null;
|
|
5321
|
+
if (activeSlot === slot) { ws = null; sessionId = null; }
|
|
5322
|
+
slot!.wsReconnectAttempt = 0;
|
|
5323
|
+
scheduleReconnect(500, slot!);
|
|
4923
5324
|
} else if (data.type === "error") {
|
|
4924
5325
|
process.stderr.write(`[agentchat] Error: ${data.message}\n`);
|
|
4925
5326
|
}
|
|
4926
5327
|
}
|
|
4927
5328
|
|
|
4928
|
-
|
|
4929
|
-
if (ws !== socket) return;
|
|
4930
|
-
sessionId = null;
|
|
4931
|
-
|
|
4932
|
-
|
|
4933
|
-
|
|
4934
|
-
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
const delay = computeReconnectDelay(wsReconnectAttempt);
|
|
4938
|
-
process.stderr.write(`[agentchat] Disconnected (code=${(event as any)?.code ?? "?"}), reconnecting in ${Math.round(delay/100)/10}s (attempt ${wsReconnectAttempt})...\n`);
|
|
4939
|
-
scheduleReconnect(delay);
|
|
5329
|
+
socket.onclose = (event) => {
|
|
5330
|
+
if (slot.ws !== socket) return;
|
|
5331
|
+
slot.sessionId = null;
|
|
5332
|
+
if (activeSlot === slot) sessionId = null;
|
|
5333
|
+
slot.heartbeat.resetReconnecting();
|
|
5334
|
+
slot.wsReconnectAttempt++;
|
|
5335
|
+
const delay = computeReconnectDelay(slot.wsReconnectAttempt);
|
|
5336
|
+
process.stderr.write(`[agentchat] Disconnected (code=${(event as any)?.code ?? "?"}), reconnecting in ${Math.round(delay/100)/10}s (attempt ${slot.wsReconnectAttempt})...\n`);
|
|
5337
|
+
scheduleReconnect(delay, slot);
|
|
4940
5338
|
};
|
|
4941
5339
|
|
|
4942
|
-
|
|
4943
|
-
if (ws !== socket) return;
|
|
5340
|
+
socket.onerror = (err) => {
|
|
5341
|
+
if (slot.ws !== socket) return;
|
|
4944
5342
|
process.stderr.write(`[agentchat] WebSocket error: ${err}\n`);
|
|
4945
5343
|
};
|
|
4946
5344
|
}
|
|
4947
5345
|
|
|
4948
|
-
// Heartbeat with dead-connection detection (15s ping, 45s timeout for faster recovery)
|
|
4949
|
-
import { HeartbeatMonitor, WS_OPEN, WS_CLOSED, WS_CONNECTING, WS_CLOSING } from "./heartbeat.ts";
|
|
4950
|
-
|
|
4951
|
-
const heartbeat = new HeartbeatMonitor({
|
|
4952
|
-
sendPing: () => {
|
|
4953
|
-
try { ws?.send(JSON.stringify({ type: "ping", timestamp: new Date().toISOString() })); } catch {}
|
|
4954
|
-
},
|
|
4955
|
-
reconnect: () => {
|
|
4956
|
-
process.stderr.write("[agentchat] Heartbeat timeout, forcing reconnect\n");
|
|
4957
|
-
// Detach onclose so the forced close doesn't also run the unplanned
|
|
4958
|
-
// backoff path and downgrade this fast 500ms recovery to 2-5s.
|
|
4959
|
-
if (ws) { ws.onclose = null; try { ws.close(); } catch {} }
|
|
4960
|
-
ws = null;
|
|
4961
|
-
sessionId = null;
|
|
4962
|
-
wsReconnectAttempt = 0; // reset backoff for heartbeat-triggered reconnect
|
|
4963
|
-
scheduleReconnect(500); // short delay to avoid tight loop
|
|
4964
|
-
},
|
|
4965
|
-
getReadyState: () => ws?.readyState ?? WS_CLOSED,
|
|
4966
|
-
}, 15_000, 45_000, 30_000); // 15s ping, 45s pong timeout, 30s connect timeout
|
|
4967
|
-
if (!anonymousMode && !toolOnlyMode) {
|
|
4968
|
-
heartbeat.start();
|
|
4969
|
-
}
|
|
4970
|
-
|
|
4971
5346
|
function releaseLiveLock() {
|
|
4972
|
-
if (
|
|
4973
|
-
|
|
4974
|
-
|
|
4975
|
-
|
|
5347
|
+
if (!toolOnlyMode) {
|
|
5348
|
+
for (const slot of profileSlots.values()) {
|
|
5349
|
+
if (slot.agentId) {
|
|
5350
|
+
try {
|
|
5351
|
+
const boundSid = slot.runtimeSession?.sessionId || findBoundSessionForProfile(configDir, slot.profileName) || null;
|
|
5352
|
+
releaseAgentLock({ lockDir, agentId: slot.agentId, currentSessionId: boundSid });
|
|
5353
|
+
} catch {}
|
|
5354
|
+
}
|
|
5355
|
+
}
|
|
5356
|
+
if (AGENT_ID) {
|
|
5357
|
+
try {
|
|
5358
|
+
releaseAgentLock({ lockDir, agentId: AGENT_ID, currentSessionId: runtimeSession?.sessionId ?? null });
|
|
5359
|
+
} catch {}
|
|
5360
|
+
}
|
|
4976
5361
|
}
|
|
4977
5362
|
}
|
|
4978
5363
|
|
|
@@ -4980,18 +5365,11 @@ function shutdownFromStdio(reason: string) {
|
|
|
4980
5365
|
if (shuttingDown) return;
|
|
4981
5366
|
shuttingDown = true;
|
|
4982
5367
|
safeStderrWrite(`[agentchat] Stdio closed (${reason}), shutting down\n`);
|
|
4983
|
-
// Persisting the read cursor is a state change, not teardown: report, never swallow.
|
|
4984
5368
|
try { flushLastSeenMessageTs(); } catch (e) { safeStderrWrite(`[agentchat] WARNING: read-cursor flush failed on shutdown: ${e}\n`); }
|
|
4985
5369
|
releaseLiveLock();
|
|
4986
|
-
try { heartbeat.stop(); } catch {}
|
|
4987
5370
|
try { stopAllTypingHeartbeats(); } catch {}
|
|
4988
|
-
|
|
4989
|
-
|
|
4990
|
-
reconnectTimer = null;
|
|
4991
|
-
}
|
|
4992
|
-
if (backfillTimer) {
|
|
4993
|
-
clearTimeout(backfillTimer);
|
|
4994
|
-
backfillTimer = null;
|
|
5371
|
+
for (const slot of [...profileSlots.values()]) {
|
|
5372
|
+
teardownSlot(slot, { releaseLock: false });
|
|
4995
5373
|
}
|
|
4996
5374
|
try { ws?.close(); } catch {}
|
|
4997
5375
|
ws = null;
|
|
@@ -5056,14 +5434,22 @@ async function checkVersionStaleness(): Promise<void> {
|
|
|
5056
5434
|
// --- Start ---
|
|
5057
5435
|
async function main() {
|
|
5058
5436
|
installStdioLifecycleGuards();
|
|
5437
|
+
if (!toolOnlyMode) {
|
|
5438
|
+
syncOpenBoundSessions();
|
|
5439
|
+
}
|
|
5059
5440
|
// Anonymous = no credentials to present. Connecting would just fail auth in a
|
|
5060
5441
|
// reconnect loop; stdio (initialize/tools/list) is served either way.
|
|
5061
|
-
if (anonymousMode) {
|
|
5442
|
+
if (anonymousMode && profileSlots.size === 0) {
|
|
5062
5443
|
process.stderr.write(`[agentchat] Anonymous — not connecting to the hub.\n`);
|
|
5063
5444
|
} else if (toolOnlyMode) {
|
|
5064
5445
|
process.stderr.write(`[agentchat] Tool-only mode (AGENTSCHAT_TOOL_ONLY=1) — skipping duplicate WS connection.\n`);
|
|
5065
5446
|
} else {
|
|
5066
|
-
|
|
5447
|
+
for (const slot of profileSlots.values()) {
|
|
5448
|
+
if (!slot.ws) {
|
|
5449
|
+
slot.heartbeat.start();
|
|
5450
|
+
connectWS(slot);
|
|
5451
|
+
}
|
|
5452
|
+
}
|
|
5067
5453
|
}
|
|
5068
5454
|
|
|
5069
5455
|
// Stdio is the only supported transport. The --port HTTP SSE path was
|