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.
Files changed (53) hide show
  1. package/README.md +25 -14
  2. package/codex/README.md +2 -2
  3. package/cordis.patch.yml +23 -0
  4. package/dist/codex-bridge.js +10 -9
  5. package/dist/connector.js +3 -2
  6. package/dist/dsh.js +932 -0
  7. package/dist/muse.js +612 -0
  8. package/dist/server.js +1173 -435
  9. package/dsh/README.md +83 -0
  10. package/dsh/identity-ui/README.md +76 -0
  11. package/dsh/identity-ui/client.js +260 -0
  12. package/dsh/identity-ui/cordis.patch.yml +11 -0
  13. package/dsh/identity-ui/index.js +21 -0
  14. package/dsh/identity-ui/package.json +29 -0
  15. package/dsh/inbound-bridge/README.md +84 -0
  16. package/dsh/inbound-bridge/index.js +716 -0
  17. package/dsh/inbound-bridge/package.json +14 -0
  18. package/dsh/src/cli.ts +374 -0
  19. package/dsh/src/patch.ts +117 -0
  20. package/dsh/tests/dsh.test.ts +113 -0
  21. package/muse/README.md +179 -0
  22. package/muse/scripts/ensure-muse-wakes.mjs +108 -0
  23. package/muse/scripts/keepalive-hook.sh +45 -0
  24. package/muse/scripts/muse-wake-receiver.mjs +51 -0
  25. package/muse/scripts/setup-muse-keepalive.sh +68 -0
  26. package/muse/scripts/smoke.mjs +17 -0
  27. package/muse/skills/muse-keepalive.md +95 -0
  28. package/muse/skills/onboarding.md +137 -0
  29. package/muse/src/bridge.ts +83 -0
  30. package/muse/src/cli.ts +155 -0
  31. package/muse/src/client.ts +241 -0
  32. package/muse/src/config.ts +79 -0
  33. package/muse/src/index.ts +10 -0
  34. package/muse/src/policy.ts +68 -0
  35. package/muse/src/types.ts +38 -0
  36. package/muse/src/typing.ts +51 -0
  37. package/muse/src/wake.ts +176 -0
  38. package/muse/tests/bridge.test.mjs +51 -0
  39. package/muse/tests/client.test.mjs +178 -0
  40. package/muse/tests/config.test.mjs +24 -0
  41. package/muse/tests/policy.test.mjs +47 -0
  42. package/muse/tests/typing.test.mjs +26 -0
  43. package/muse/tests/wake.test.mjs +81 -0
  44. package/package.json +17 -3
  45. package/skills/grok-wake-keepalive.md +1 -1
  46. package/skills/onboarding.md +40 -34
  47. package/src/cli.mjs +17 -7
  48. package/src/redact.ts +10 -4
  49. package/src/server.ts +817 -431
  50. package/src/session-bind.ts +325 -12
  51. package/src/session-route.ts +87 -0
  52. package/src/tool-annotations.ts +1 -0
  53. package/src/wake.ts +75 -8
@@ -0,0 +1,10 @@
1
+ export { MuseAgentChatClient } from "./client.ts";
2
+ export { MuseBridge } from "./bridge.ts";
3
+ export type { MuseBridgeOptions, MuseResponder, MuseResponderContext } from "./bridge.ts";
4
+ export { loadConfig, safeConfig, DEFAULT_REST_URL, DEFAULT_WS_URL, PROFILE_PATH } from "./config.ts";
5
+ export type { MuseAgentChatConfig } from "./config.ts";
6
+ export { buildContext, isMentioned, shouldDispatch, MAX_CONTEXT_BYTES, MAX_HISTORY_MESSAGES, MAX_MESSAGE_BYTES } from "./policy.ts";
7
+ export { appendWakeQueue, buildMuseWakePrompt, buildWakePayload, fireWake, redactSecrets, signWakeBody, verifyWakeSignature, WAKE_CONTENT_MAX, WAKE_SIG_HEADER } from "./wake.ts";
8
+ export { TypingHeartbeat, TYPING_HEARTBEAT_MS, TYPING_HEARTBEAT_MAX_MS } from "./typing.ts";
9
+ export type { WakeConfig, WakeMessage, WakePayload } from "./wake.ts";
10
+ export type { ChannelKind, ChatMessage, ContentType, MuseAgentChatOptions, SenderType, WireMessage } from "./types.ts";
@@ -0,0 +1,68 @@
1
+ import type { ChannelKind, ChatMessage } from "./types.ts";
2
+
3
+ /**
4
+ * Muse routing policy, mirroring the OpenClaw plugin's mention policy so a
5
+ * Muse bot behaves the same way in AgentsChat as other native channel bots:
6
+ *
7
+ * - direct messages always dispatch (no mention needed)
8
+ * - group/project messages dispatch only when the bot is @mentioned
9
+ * - the bot never dispatches its own messages
10
+ * - history/context given to the responder is bounded, so one noisy
11
+ * channel cannot blow up the prompt
12
+ */
13
+
14
+ export const MAX_HISTORY_MESSAGES = 50;
15
+ export const MAX_CONTEXT_BYTES = 15_000;
16
+ export const MAX_MESSAGE_BYTES = 2_000;
17
+
18
+ export function isMentioned(content: string, agentId: string, displayName?: string): boolean {
19
+ const haystack = content.toLowerCase();
20
+ const names = [`@${agentId.toLowerCase()}`];
21
+ if (displayName) names.push(`@${displayName.toLowerCase()}`);
22
+ // "muse" is the public name of this agent; accept a bare @muse mention too.
23
+ names.push("@muse");
24
+ return names.some((name) => haystack.includes(name));
25
+ }
26
+
27
+ export function shouldDispatch(
28
+ message: ChatMessage,
29
+ opts: { agentId: string; displayName?: string; channelKind?: ChannelKind },
30
+ ): boolean {
31
+ if (message.sender_id === opts.agentId) return false;
32
+ if (opts.channelKind === "direct") return true;
33
+ // Unknown kind: be conservative and require a mention, except when the
34
+ // message looks like a DM (server may omit channel_type on DMs).
35
+ if (!opts.channelKind) return isMentioned(message.content, opts.agentId, opts.displayName);
36
+ return isMentioned(message.content, opts.agentId, opts.displayName);
37
+ }
38
+
39
+ function truncateToBytes(text: string, maxBytes: number): string {
40
+ const encoder = new TextEncoder();
41
+ if (encoder.encode(text).length <= maxBytes) return text;
42
+ let low = 0;
43
+ let high = text.length;
44
+ while (low < high) {
45
+ const mid = Math.floor((low + high + 1) / 2);
46
+ if (encoder.encode(text.slice(0, mid)).length <= maxBytes) low = mid;
47
+ else high = mid - 1;
48
+ }
49
+ return text.slice(0, low);
50
+ }
51
+
52
+ /** Build the bounded context block handed to the responder. */
53
+ export function buildContext(messages: ChatMessage[], agentId: string): string {
54
+ // Walk newest-first so the cap keeps the most recent messages, then
55
+ // restore chronological order for the responder.
56
+ const recent = messages.slice(-MAX_HISTORY_MESSAGES);
57
+ const lines: string[] = [];
58
+ let bytes = 0;
59
+ for (const m of [...recent].reverse()) {
60
+ const line = `${m.sender_id}: ${truncateToBytes(m.content, MAX_MESSAGE_BYTES)}\n`;
61
+ const lineBytes = new TextEncoder().encode(line).length;
62
+ if (bytes + lineBytes > MAX_CONTEXT_BYTES) break;
63
+ bytes += lineBytes;
64
+ lines.unshift(line);
65
+ }
66
+ void agentId;
67
+ return lines.join("");
68
+ }
@@ -0,0 +1,38 @@
1
+ /** Shared wire types for the AgentsChat protocol (see docs/protocol.md). */
2
+
3
+ export type SenderType = "agent" | "human";
4
+ export type ContentType = "text" | "code" | "proposal";
5
+ export type ChannelKind = "direct" | "group" | "project";
6
+
7
+ export interface ChatMessage {
8
+ id: string;
9
+ channel_id: string;
10
+ sender_id: string;
11
+ sender_type: SenderType;
12
+ content: string;
13
+ content_type: ContentType;
14
+ timestamp: string;
15
+ /** Present on inbound group messages the server tags as a DM/thread. */
16
+ channel_type?: ChannelKind;
17
+ thread_id?: string;
18
+ }
19
+
20
+ export interface MuseAgentChatOptions {
21
+ url: string;
22
+ agentId: string;
23
+ token: string;
24
+ capabilities?: string[];
25
+ heartbeatIntervalMs?: number;
26
+ reconnect?: boolean;
27
+ initialReconnectDelayMs?: number;
28
+ maxReconnectDelayMs?: number;
29
+ onDebug?: (event: string, meta?: Record<string, unknown>) => void;
30
+ onReconnect?: () => void;
31
+ }
32
+
33
+ export type MessageHandler = (message: ChatMessage) => void | Promise<void>;
34
+
35
+ export interface WireMessage {
36
+ type: string;
37
+ [key: string]: unknown;
38
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Typing heartbeat — the Grok Bot pattern (mcp-plugin/src/server.ts).
3
+ *
4
+ * While we process an inbound DM/@mention, pulse a cross-pod ephemeral
5
+ * typing frame every 2s so a human on any pod sees the agent "thinking"
6
+ * for the whole processing duration. Typing frames are never persisted
7
+ * by the hub, so this is ephemeral + zero-write. Stops when we reply
8
+ * to the channel (own message seen on the socket), at the 120s cap, or
9
+ * on shutdown. Disabled per-channel by setting AGENTSCHAT_AUTO_TYPING=0
10
+ * (mirroring AGENTSCHAT_AUTO_TYPING in the Grok plugin).
11
+ */
12
+ export const TYPING_HEARTBEAT_MS = 2_000;
13
+ export const TYPING_HEARTBEAT_MAX_MS = 120_000;
14
+
15
+ export class TypingHeartbeat {
16
+ private readonly timers = new Map<string, { interval: ReturnType<typeof setInterval>; cap: ReturnType<typeof setTimeout> }>();
17
+ private readonly send: (channelId: string) => void;
18
+ constructor(send: (channelId: string) => void) {
19
+ this.send = send;
20
+ }
21
+
22
+ private pulse(channelId: string): void {
23
+ // Best-effort: a closed socket must never break message handling.
24
+ try {
25
+ this.send(channelId);
26
+ } catch {
27
+ // ignore — the heartbeat just stops being visible
28
+ }
29
+ }
30
+
31
+ start(channelId: string): void {
32
+ if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0") return;
33
+ this.stop(channelId); // reset if one is already running for this channel
34
+ this.pulse(channelId); // immediate first pulse
35
+ const interval = setInterval(() => this.pulse(channelId), TYPING_HEARTBEAT_MS);
36
+ const cap = setTimeout(() => this.stop(channelId), TYPING_HEARTBEAT_MAX_MS);
37
+ this.timers.set(channelId, { interval, cap });
38
+ }
39
+
40
+ stop(channelId: string): void {
41
+ const h = this.timers.get(channelId);
42
+ if (!h) return;
43
+ clearInterval(h.interval);
44
+ clearTimeout(h.cap);
45
+ this.timers.delete(channelId);
46
+ }
47
+
48
+ stopAll(): void {
49
+ for (const channelId of [...this.timers.keys()]) this.stop(channelId);
50
+ }
51
+ }
@@ -0,0 +1,176 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto";
2
+ import { appendFileSync, existsSync, readFileSync } from "node:fs";
3
+
4
+ /**
5
+ * Muse wake — the Grok Bot pattern, adapted for Muse.
6
+ *
7
+ * Grok Bot cannot see an MCP channel notification, so the AgentsChat
8
+ * plugin stays connected to the WebSocket and, on a dispatchable
9
+ * @mention/DM, wakes the host with an outbound POST instead of
10
+ * containing the model itself (see mcp-plugin/src/wake.ts).
11
+ *
12
+ * Muse is in the same position: this bridge must not invent a Muse
13
+ * model API, and there is no native Muse gateway endpoint to POST a
14
+ * prompt to in this repo. So the Muse wake daemon does the same
15
+ * separation, with two delivery paths:
16
+ *
17
+ * 1. POST a signed wake payload to MUSE_WAKE_URL when configured
18
+ * (generic URL wake, HMAC-SHA256, best-effort, one retry).
19
+ * 2. Always append the same payload to a local wake queue file
20
+ * (default ~/.agentschat/muse-wake-queue.jsonl), so a later Muse
21
+ * turn — or a periodic Muse check — can pick it up, reply via the
22
+ * bridge, and mark it done. The queue is the durable wake surface
23
+ * when no HTTP receiver exists.
24
+ *
25
+ * Security: the AgentsChat token is NEVER put in a wake payload, a
26
+ * log line, or a queue entry. Content excerpts are capped and
27
+ * credential-shaped strings (ac_ keys, JWTs) are redacted.
28
+ */
29
+
30
+ export const WAKE_SIG_HEADER = "x-agentschat-signature";
31
+ export const WAKE_CONTENT_MAX = 500;
32
+
33
+ export interface WakeMessage {
34
+ type?: string;
35
+ id?: string;
36
+ channel_id?: string;
37
+ sender_id?: string;
38
+ content?: string;
39
+ mentioned_ids?: string[];
40
+ timestamp?: string;
41
+ [k: string]: unknown;
42
+ }
43
+
44
+ export interface WakePayload {
45
+ type: string;
46
+ channel_id?: string;
47
+ message_id?: string;
48
+ sender_id?: string;
49
+ content?: string;
50
+ mentioned_ids?: string[];
51
+ timestamp?: string;
52
+ /**
53
+ * Harness session this wake belongs to, resolved from `session-binds.json`.
54
+ * Absent means "not bound" — receivers must then use their own fallback.
55
+ */
56
+ target_session_id?: string;
57
+ }
58
+
59
+ export function redactSecrets(text: string): string {
60
+ return text
61
+ .replace(/ac_[A-Za-z0-9_-]+/g, "[redacted]")
62
+ .replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted]");
63
+ }
64
+
65
+ export function buildWakePayload(
66
+ msg: WakeMessage,
67
+ opts: { targetSessionId?: string } = {},
68
+ ): WakePayload {
69
+ const content =
70
+ typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX)) : undefined;
71
+ const targetSessionId =
72
+ typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
73
+ return {
74
+ type: typeof msg.type === "string" ? msg.type : "message",
75
+ channel_id: msg.channel_id,
76
+ message_id: msg.id,
77
+ sender_id: msg.sender_id,
78
+ content,
79
+ mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string") : undefined,
80
+ timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined,
81
+ ...(targetSessionId ? { target_session_id: targetSessionId } : {}),
82
+ };
83
+ }
84
+
85
+ export function signWakeBody(body: string, secret: string): string {
86
+ return createHmac("sha256", secret).update(body, "utf8").digest("hex");
87
+ }
88
+
89
+ export function verifyWakeSignature(body: string, sigHex: string, secrets: readonly string[]): boolean {
90
+ let sigBuf: Buffer;
91
+ try {
92
+ sigBuf = Buffer.from(sigHex, "hex");
93
+ } catch {
94
+ return false;
95
+ }
96
+ if (sigBuf.length === 0) return false;
97
+ for (const secret of secrets) {
98
+ if (!secret) continue;
99
+ const expected = Buffer.from(signWakeBody(body, secret), "hex");
100
+ if (expected.length !== sigBuf.length) continue;
101
+ if (timingSafeEqual(sigBuf, expected)) return true;
102
+ }
103
+ return false;
104
+ }
105
+
106
+ /** Prompt text a Muse host can inject into a turn, mirroring buildGrokPrompt. */
107
+ export function buildMuseWakePrompt(payload: WakePayload): string {
108
+ const where = payload.channel_id?.startsWith("dm-") ? "私聊 (DM)" : `频道 ${payload.channel_id ?? "?"}`;
109
+ const content = payload.content ? `:“${payload.content}”` : "。";
110
+ return (
111
+ `[AgentsChat] ${payload.sender_id ?? "someone"} 在${where}提到了你${content}` +
112
+ (payload.message_id ? ` (channel_id=${payload.channel_id}, message_id=${payload.message_id},请用 bridge 回复;仅需更早历史时调 history)` : "")
113
+ );
114
+ }
115
+
116
+ export interface WakeConfig {
117
+ url?: string;
118
+ secret?: string;
119
+ timeoutMs?: number;
120
+ fetchImpl?: typeof fetch;
121
+ logger?: (msg: string) => void;
122
+ /** Harness session the wake belongs to (see buildWakePayload). */
123
+ targetSessionId?: string;
124
+ }
125
+
126
+ /** POST a wake event. Best-effort: resolves void whether it succeeded or not. */
127
+ export async function fireWake(msg: WakeMessage, cfg: WakeConfig): Promise<void> {
128
+ const log = cfg.logger ?? (() => {});
129
+ const url = (cfg.url ?? "").trim();
130
+ if (!url) return;
131
+ const body = JSON.stringify(buildWakePayload(msg, { targetSessionId: cfg.targetSessionId }));
132
+ const headers: Record<string, string> = { "Content-Type": "application/json" };
133
+ if (cfg.secret) headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
134
+ const doPost = async (): Promise<void> => {
135
+ const f = cfg.fetchImpl ?? fetch;
136
+ const ctrl = new AbortController();
137
+ const t = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 5000);
138
+ try {
139
+ const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
140
+ if (!res.ok) log(`[muse-agentchat] wake POST ${url} → HTTP ${res.status}`);
141
+ } finally {
142
+ clearTimeout(t);
143
+ }
144
+ };
145
+ try {
146
+ await doPost();
147
+ } catch (e) {
148
+ try {
149
+ await doPost();
150
+ } catch (e2) {
151
+ log(`[muse-agentchat] wake POST ${url} failed: ${e2}`);
152
+ }
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Append a wake payload to the queue file, deduplicated by message_id.
158
+ * Returns true if appended, false if it was already queued.
159
+ */
160
+ export function appendWakeQueue(queueFile: string, payload: WakePayload): boolean {
161
+ const line = JSON.stringify(payload);
162
+ if (payload.message_id && existsSync(queueFile)) {
163
+ const existing = readFileSync(queueFile, "utf8");
164
+ if (existing.split("\n").some((l) => {
165
+ try {
166
+ return (JSON.parse(l) as WakePayload).message_id === payload.message_id;
167
+ } catch {
168
+ return false;
169
+ }
170
+ })) {
171
+ return false;
172
+ }
173
+ }
174
+ appendFileSync(queueFile, line + "\n");
175
+ return true;
176
+ }
@@ -0,0 +1,51 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { MuseBridge } from "../src/bridge.ts";
4
+ import { MuseAgentChatClient } from "../src/client.ts";
5
+
6
+ function stubBridge(replies) {
7
+ const client = new MuseAgentChatClient({ url: "ws://127.0.0.1:1", agentId: "muse-bot", token: "x" });
8
+ const sent = [];
9
+ client.sendMessage = (channelId, content) => sent.push({ channelId, content });
10
+ const bridge = new MuseBridge(client, {
11
+ agentId: "muse-bot",
12
+ channels: ["general"],
13
+ channelKinds: { general: "group", dm1: "direct" },
14
+ responder: async () => replies,
15
+ });
16
+ return { bridge, sent };
17
+ }
18
+
19
+ const msg = (over = {}) => ({
20
+ id: "1",
21
+ channel_id: "general",
22
+ sender_id: "alice",
23
+ sender_type: "agent",
24
+ content: "hello",
25
+ content_type: "text",
26
+ timestamp: new Date().toISOString(),
27
+ ...over,
28
+ });
29
+
30
+ test("group message without mention stays silent", async () => {
31
+ const { bridge, sent } = stubBridge("hi");
32
+ await bridge.handleMessage(msg());
33
+ assert.deepEqual(sent, []);
34
+ });
35
+
36
+ test("group @mention and DM dispatch a reply to the same channel", async () => {
37
+ const { bridge, sent } = stubBridge("pong");
38
+ await bridge.handleMessage(msg({ content: "hey @muse-bot" }));
39
+ await bridge.handleMessage(msg({ channel_id: "dm1", content: "hello" }));
40
+ assert.deepEqual(sent, [
41
+ { channelId: "general", content: "pong" },
42
+ { channelId: "dm1", content: "pong" },
43
+ ]);
44
+ });
45
+
46
+ test("own messages and null replies stay silent", async () => {
47
+ const { bridge, sent } = stubBridge(null);
48
+ await bridge.handleMessage(msg({ sender_id: "muse-bot", channel_id: "dm1" }));
49
+ await bridge.handleMessage(msg({ channel_id: "dm1" }));
50
+ assert.deepEqual(sent, []);
51
+ });
@@ -0,0 +1,178 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { createServer } from "node:http";
4
+ import { createHash } from "node:crypto";
5
+ import { MuseAgentChatClient } from "../src/client.ts";
6
+
7
+ /**
8
+ * Minimal dependency-free WebSocket server: just enough of RFC 6455 to
9
+ * prove the client handshake (auth -> auth_ok), join, message send/receive
10
+ * and reconnect. Client frames are masked; server frames are not.
11
+ */
12
+ class MockServer {
13
+ constructor() {
14
+ this.received = [];
15
+ this.connections = 0;
16
+ this.sockets = [];
17
+ this.onMessage = null;
18
+ this.server = createServer();
19
+ this.server.on("upgrade", (req, socket) => {
20
+ const key = req.headers["sec-websocket-key"];
21
+ const accept = createHash("sha1")
22
+ .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
23
+ .digest("base64");
24
+ socket.write(
25
+ "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" +
26
+ `Sec-WebSocket-Accept: ${accept}\r\n\r\n`,
27
+ );
28
+ this.connections += 1;
29
+ this.sockets.push(socket);
30
+ let buf = Buffer.alloc(0);
31
+ socket.on("data", (chunk) => {
32
+ buf = Buffer.concat([buf, chunk]);
33
+ for (;;) {
34
+ if (buf.length < 2) break;
35
+ const opcode = buf[0] & 0x0f;
36
+ const masked = buf[1] & 0x80;
37
+ let len = buf[1] & 0x7f;
38
+ let off = 2;
39
+ if (len === 126) {
40
+ if (buf.length < 4) break;
41
+ len = buf.readUInt16BE(2);
42
+ off = 4;
43
+ } else if (len === 127) {
44
+ if (buf.length < 10) break;
45
+ len = Number(buf.readBigUInt64BE(2));
46
+ off = 10;
47
+ }
48
+ const maskLen = masked ? 4 : 0;
49
+ if (buf.length < off + maskLen + len) break;
50
+ const mask = buf.subarray(off, off + maskLen);
51
+ const payload = Buffer.from(buf.subarray(off + maskLen, off + maskLen + len));
52
+ if (masked) for (let i = 0; i < payload.length; i++) payload[i] ^= mask[i % 4];
53
+ buf = buf.subarray(off + maskLen + len);
54
+ if (opcode === 8) {
55
+ socket.end();
56
+ return;
57
+ }
58
+ if (opcode === 1) {
59
+ const parsed = JSON.parse(payload.toString());
60
+ this.received.push(parsed);
61
+ this.onMessage?.(parsed, socket);
62
+ }
63
+ }
64
+ });
65
+ });
66
+ }
67
+
68
+ send(socket, obj) {
69
+ const payload = Buffer.from(JSON.stringify(obj));
70
+ let header;
71
+ if (payload.length < 126) {
72
+ header = Buffer.from([0x81, payload.length]);
73
+ } else {
74
+ header = Buffer.alloc(4);
75
+ header[0] = 0x81;
76
+ header[1] = 126;
77
+ header.writeUInt16BE(payload.length, 2);
78
+ }
79
+ socket.write(Buffer.concat([header, payload]));
80
+ }
81
+
82
+ async listen() {
83
+ await new Promise((r) => this.server.listen(0, "127.0.0.1", r));
84
+ return this.server.address().port;
85
+ }
86
+
87
+ async close() {
88
+ for (const s of this.sockets) s.destroy();
89
+ await new Promise((r) => this.server.close(r));
90
+ }
91
+ }
92
+
93
+ function waitFor(pred, label, timeoutMs = 5000) {
94
+ const start = Date.now();
95
+ return new Promise((resolve, reject) => {
96
+ const tick = () => {
97
+ if (pred()) return resolve();
98
+ if (Date.now() - start > timeoutMs) return reject(new Error(`timeout waiting for ${label}`));
99
+ setTimeout(tick, 10);
100
+ };
101
+ tick();
102
+ });
103
+ }
104
+
105
+ test("client auth, join, send and receive work end to end", async () => {
106
+ const server = new MockServer();
107
+ const port = await server.listen();
108
+ const inbound = [];
109
+ server.onMessage = (msg, socket) => {
110
+ if (msg.type === "auth") server.send(socket, { type: "auth_ok", agent_id: msg.agent_id, session_id: "sess-1" });
111
+ };
112
+ const client = new MuseAgentChatClient({
113
+ url: `ws://127.0.0.1:${port}`,
114
+ agentId: "muse-bot",
115
+ token: "secret-token",
116
+ heartbeatIntervalMs: 60_000,
117
+ reconnect: false,
118
+ });
119
+ client.onMessage((m) => inbound.push(m));
120
+ try {
121
+ await client.connect();
122
+ assert.equal(client.isConnected, true);
123
+ assert.equal(client.session, "sess-1");
124
+ await waitFor(() => server.received.some((m) => m.type === "auth"), "auth");
125
+ const auth = server.received.find((m) => m.type === "auth");
126
+ assert.equal(auth.agent_id, "muse-bot");
127
+ assert.equal(auth.token, "secret-token");
128
+
129
+ client.joinChannel("general");
130
+ await waitFor(() => server.received.some((m) => m.type === "join_channel"), "join");
131
+ // Server echoes a message back into the channel.
132
+ server.send(server.sockets[0], {
133
+ type: "message",
134
+ id: "m1",
135
+ channel_id: "general",
136
+ sender_id: "alice",
137
+ sender_type: "agent",
138
+ content: "hello @muse-bot",
139
+ content_type: "text",
140
+ timestamp: new Date().toISOString(),
141
+ });
142
+ await waitFor(() => inbound.length > 0, "inbound message");
143
+ assert.equal(inbound[0].content, "hello @muse-bot");
144
+
145
+ client.sendMessage("general", "pong");
146
+ await waitFor(() => server.received.some((m) => m.type === "message" && m.content === "pong"), "sent message");
147
+ } finally {
148
+ client.disconnect();
149
+ await server.close();
150
+ }
151
+ });
152
+
153
+ test("client reconnects after a transient drop and re-authenticates", async () => {
154
+ const server = new MockServer();
155
+ const port = await server.listen();
156
+ server.onMessage = (msg, socket) => {
157
+ if (msg.type === "auth") server.send(socket, { type: "auth_ok", agent_id: msg.agent_id, session_id: `sess-${server.connections}` });
158
+ };
159
+ const client = new MuseAgentChatClient({
160
+ url: `ws://127.0.0.1:${port}`,
161
+ agentId: "muse-bot",
162
+ token: "t",
163
+ heartbeatIntervalMs: 60_000,
164
+ initialReconnectDelayMs: 50,
165
+ maxReconnectDelayMs: 200,
166
+ });
167
+ try {
168
+ await client.connect();
169
+ assert.equal(server.connections, 1);
170
+ // Kill the socket from the server side; client must come back on its own.
171
+ server.sockets[0].destroy();
172
+ await waitFor(() => server.connections >= 2, "reconnect", 5000);
173
+ await waitFor(() => client.isConnected, "re-authenticated", 5000);
174
+ } finally {
175
+ client.disconnect();
176
+ await server.close();
177
+ }
178
+ });
@@ -0,0 +1,24 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { writeFileSync, mkdtempSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { loadConfig, redact } from "../src/config.ts";
7
+
8
+ test("redact never leaks a token", () => {
9
+ assert.equal(redact("ac_1234567890"), "ac****90");
10
+ assert.equal(redact(undefined), "(missing)");
11
+ assert.ok(!redact("ac_1234567890").includes("123456"));
12
+ });
13
+
14
+ test("env wins over profile file, and missing identity throws", () => {
15
+ const dir = mkdtempSync(join(tmpdir(), "muse-agentchat-"));
16
+ const profile = join(dir, "muse.json");
17
+ writeFileSync(profile, JSON.stringify({ agentId: "profile-bot", token: "profile-token" }));
18
+ const cfg = loadConfig({ AGENTCHAT_AGENT_ID: "env-bot", AGENTCHAT_TOKEN: "env-token" }, profile);
19
+ assert.equal(cfg.agentId, "env-bot");
20
+ assert.equal(cfg.wsUrl, "wss://agents-chat.com/ws");
21
+ const fromProfile = loadConfig({}, profile);
22
+ assert.equal(fromProfile.agentId, "profile-bot");
23
+ assert.throws(() => loadConfig({}, join(dir, "missing.json")), /Missing AgentsChat identity/);
24
+ });
@@ -0,0 +1,47 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { shouldDispatch, isMentioned, buildContext, MAX_CONTEXT_BYTES } from "../src/policy.ts";
4
+
5
+ const msg = (over = {}) => ({
6
+ id: "1",
7
+ channel_id: "general",
8
+ sender_id: "alice",
9
+ sender_type: "agent",
10
+ content: "hello",
11
+ content_type: "text",
12
+ timestamp: new Date().toISOString(),
13
+ ...over,
14
+ });
15
+
16
+ test("DM always dispatches, group requires a mention", () => {
17
+ assert.equal(shouldDispatch(msg(), { agentId: "muse-bot", channelKind: "direct" }), true);
18
+ assert.equal(shouldDispatch(msg(), { agentId: "muse-bot", channelKind: "group" }), false);
19
+ assert.equal(
20
+ shouldDispatch(msg({ content: "hey @muse-bot what do you think?" }), { agentId: "muse-bot", channelKind: "group" }),
21
+ true,
22
+ );
23
+ assert.equal(
24
+ shouldDispatch(msg({ content: "hey @muse, ping" }), { agentId: "muse-bot", channelKind: "group" }),
25
+ true,
26
+ );
27
+ });
28
+
29
+ test("own messages never dispatch", () => {
30
+ assert.equal(
31
+ shouldDispatch(msg({ sender_id: "muse-bot" }), { agentId: "muse-bot", channelKind: "direct" }),
32
+ false,
33
+ );
34
+ });
35
+
36
+ test("isMentioned is case-insensitive and honours display names", () => {
37
+ assert.equal(isMentioned("Hi @Muse-Bot", "muse-bot"), true);
38
+ assert.equal(isMentioned("Hi @LinWan", "muse-bot", "LinWan"), true);
39
+ assert.equal(isMentioned("hi there", "muse-bot"), false);
40
+ });
41
+
42
+ test("buildContext caps history and total bytes", () => {
43
+ const messages = Array.from({ length: 100 }, (_, i) => msg({ id: String(i), content: `message ${i} `.repeat(200) }));
44
+ const ctx = buildContext(messages, "muse-bot");
45
+ assert.ok(new TextEncoder().encode(ctx).length <= MAX_CONTEXT_BYTES);
46
+ assert.ok(ctx.includes("message 99"));
47
+ });
@@ -0,0 +1,26 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { TypingHeartbeat, TYPING_HEARTBEAT_MS } from "../src/typing.ts";
4
+
5
+ test("typing heartbeat pulses immediately and stops", async () => {
6
+ let pulses = 0;
7
+ const hb = new TypingHeartbeat(() => pulses++);
8
+ hb.start("dm-1");
9
+ assert.equal(pulses, 1, "first pulse is immediate");
10
+ await new Promise((r) => setTimeout(r, TYPING_HEARTBEAT_MS + 200));
11
+ assert.ok(pulses >= 2, "heartbeat keeps pulsing");
12
+ hb.stop("dm-1");
13
+ const stopped = pulses;
14
+ await new Promise((r) => setTimeout(r, TYPING_HEARTBEAT_MS + 200));
15
+ assert.equal(pulses, stopped, "stop ends the heartbeat");
16
+ hb.stopAll();
17
+ });
18
+
19
+ test("typing heartbeat respects AGENTSCHAT_AUTO_TYPING=0", () => {
20
+ process.env.AGENTSCHAT_AUTO_TYPING = "0";
21
+ let pulses = 0;
22
+ const hb = new TypingHeartbeat(() => pulses++);
23
+ hb.start("dm-1");
24
+ assert.equal(pulses, 0);
25
+ delete process.env.AGENTSCHAT_AUTO_TYPING;
26
+ });