agentschat-mcp 0.36.24 → 0.36.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +12 -0
- package/README.md +8 -0
- package/codex/README.md +1 -1
- package/codex/app-server.ts +79 -22
- package/codex/bots-config.ts +31 -11
- package/codex/bridge.ts +123 -25
- package/codex/config.ts +128 -21
- package/codex/gui-channel.ts +66 -9
- package/codex/inbox-sync.ts +65 -12
- package/codex/loop-grants.ts +41 -11
- package/codex/manager.ts +101 -25
- package/codex/owner.ts +81 -9
- package/codex/processes.ts +51 -7
- package/codex/run.ts +70 -17
- package/codex/runtime-home.ts +41 -11
- package/codex/thread-history.ts +77 -30
- package/codex/transport.ts +122 -19
- package/connector/auth.ts +57 -5
- package/connector/backfill.ts +92 -10
- package/connector/descriptor.ts +27 -1
- package/connector/identities.ts +82 -14
- package/connector/ingest.ts +11 -2
- package/connector/normalize.ts +32 -12
- package/connector/run.ts +314 -67
- package/connector/server.ts +95 -26
- package/dist/codex-bots.js +410 -73
- package/dist/codex-bridge.js +1996 -576
- package/dist/connector.js +1286 -493
- package/dist/dsh.js +1776 -299
- package/dist/muse.js +967 -221
- package/dist/server.js +7645 -1172
- package/dsh/client.js +7 -5
- package/dsh/identity-ui/client.js +7 -5
- package/dsh/identity-ui/index.js +43 -8
- package/dsh/inbound-bridge/index.js +595 -146
- package/dsh/src/cli.ts +430 -91
- package/dsh/src/patch.ts +295 -15
- package/dsh/tests/dsh-hardening-127.test.ts +207 -0
- package/dsh/tests/dsh.test.ts +990 -3
- package/muse/scripts/ensure-muse-wakes.mjs +5 -3
- package/muse/scripts/muse-wake-receiver.mjs +4 -1
- package/muse/src/bridge.ts +54 -13
- package/muse/src/cli.ts +226 -41
- package/muse/src/client.ts +249 -34
- package/muse/src/config.ts +128 -12
- package/muse/src/policy.ts +28 -8
- package/muse/src/types.ts +1 -0
- package/muse/src/typing.ts +18 -1
- package/muse/src/wake.ts +237 -35
- package/muse/tests/bridge.test.mjs +131 -0
- package/muse/tests/client.test.mjs +327 -0
- package/muse/tests/config.test.mjs +78 -1
- package/muse/tests/hardening.test.mjs +199 -0
- package/muse/tests/hardening126.test.mjs +292 -0
- package/muse/tests/policy.test.mjs +83 -1
- package/muse/tests/wake.test.mjs +134 -6
- package/package.json +3 -3
- package/scripts/ensure-grok-wakes.mjs +93 -8
- package/scripts/example-url-wake-receiver.mjs +254 -61
- package/scripts/grok-bind-register.sh +38 -8
- package/skills/agentschat-team-lead/SKILL.md +1 -1
- package/skills/onboarding.md +14 -10
- package/src/argcheck.ts +1890 -1
- package/src/cli.mjs +98 -14
- package/src/dedup.ts +57 -8
- package/src/grok-bind.ts +160 -33
- package/src/heartbeat.ts +39 -11
- package/src/identity-guard.ts +93 -20
- package/src/identity.ts +67 -11
- package/src/mentions.ts +26 -5
- package/src/onboarding-status.ts +134 -11
- package/src/profile-selection.ts +269 -18
- package/src/profile-store.ts +222 -28
- package/src/read-cursor.ts +256 -9
- package/src/reconnect.ts +98 -2
- package/src/redact.ts +34 -15
- package/src/rest-cli.ts +713 -159
- package/src/server.ts +2487 -342
- package/src/session-bind.ts +731 -132
- package/src/session-route.ts +183 -12
- package/src/team-lead-skill.ts +3 -0
- package/src/timestamps.ts +56 -23
- package/src/tool-annotations.ts +22 -1
- package/src/wake.ts +524 -90
package/muse/src/client.ts
CHANGED
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import { validateEndpointUrl } from "./config.ts";
|
|
2
|
+
import { sanitizeMuseText } from "./wake.ts";
|
|
3
|
+
import { resolveDrainReconnectDelay } from "../../src/reconnect.ts";
|
|
1
4
|
import type { ChatMessage, MessageHandler, MuseAgentChatOptions, WireMessage } from "./types.ts";
|
|
2
5
|
|
|
3
6
|
/**
|
|
@@ -9,13 +12,46 @@ import type { ChatMessage, MessageHandler, MuseAgentChatOptions, WireMessage } f
|
|
|
9
12
|
* resolves only on an explicit disconnect(), not on transient drops, so a
|
|
10
13
|
* long-lived Muse bot survives network blips without manual restarts.
|
|
11
14
|
*/
|
|
15
|
+
const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
|
|
16
|
+
const MAX_JOINED_CHANNELS = 256;
|
|
17
|
+
const MAX_WS_FRAME_BYTES = 1_048_576;
|
|
18
|
+
|
|
19
|
+
function rawFrameByteLength(data: unknown): number {
|
|
20
|
+
if (typeof data === "string") {
|
|
21
|
+
// Upper bound is data.length * 3 in UTF-8; only call Buffer.byteLength when length > MAX_WS_FRAME_BYTES / 3
|
|
22
|
+
if (data.length > MAX_WS_FRAME_BYTES) return data.length;
|
|
23
|
+
if (data.length * 3 <= MAX_WS_FRAME_BYTES) return data.length;
|
|
24
|
+
return Buffer.byteLength(data, "utf8");
|
|
25
|
+
}
|
|
26
|
+
if (data instanceof ArrayBuffer) return data.byteLength;
|
|
27
|
+
if (ArrayBuffer.isView(data)) return data.byteLength;
|
|
28
|
+
return 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function safeDelayMs(value: number | undefined, fallback: number, min = 0): number {
|
|
32
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < min) return fallback;
|
|
33
|
+
return Math.min(value, MAX_TIMER_DELAY_MS);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function normalizeChannelId(raw: unknown): string | null {
|
|
37
|
+
if (typeof raw !== "string") return null;
|
|
38
|
+
const trimmed = raw.trim();
|
|
39
|
+
if (!trimmed || trimmed.length > 128 || /[\/\\\x00-\x20\x7f-\x9f\u2028\u2029]/.test(trimmed) ||
|
|
40
|
+
[".", "..", "__proto__", "constructor", "prototype"].includes(trimmed.toLowerCase())) return null;
|
|
41
|
+
return trimmed;
|
|
42
|
+
}
|
|
43
|
+
|
|
12
44
|
export class MuseAgentChatClient {
|
|
13
45
|
private ws: WebSocket | null = null;
|
|
14
46
|
private sessionId: string | null = null;
|
|
15
47
|
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
|
|
16
48
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
49
|
+
private connectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
50
|
+
private nextReconnectDelayOverrideMs: number | null = null;
|
|
17
51
|
private readonly messageHandlers: MessageHandler[] = [];
|
|
18
52
|
private readonly errorHandlers: Array<(err: Error) => void> = [];
|
|
53
|
+
private readonly joinedChannels = new Set<string>();
|
|
54
|
+
private readonly sessionJoined = new Set<string>();
|
|
19
55
|
private connectResolve: (() => void) | null = null;
|
|
20
56
|
private connectReject: ((err: Error) => void) | null = null;
|
|
21
57
|
private lifecycleResolve: (() => void) | null = null;
|
|
@@ -29,6 +65,7 @@ export class MuseAgentChatClient {
|
|
|
29
65
|
readonly token: string;
|
|
30
66
|
readonly capabilities: string[];
|
|
31
67
|
readonly heartbeatIntervalMs: number;
|
|
68
|
+
readonly connectTimeoutMs: number;
|
|
32
69
|
readonly reconnect: boolean;
|
|
33
70
|
readonly initialReconnectDelayMs: number;
|
|
34
71
|
readonly maxReconnectDelayMs: number;
|
|
@@ -36,20 +73,54 @@ export class MuseAgentChatClient {
|
|
|
36
73
|
onReconnect?: MuseAgentChatOptions["onReconnect"];
|
|
37
74
|
|
|
38
75
|
constructor(options: MuseAgentChatOptions) {
|
|
39
|
-
this.url = options.url;
|
|
76
|
+
this.url = validateEndpointUrl(options.url, "ws");
|
|
40
77
|
this.agentId = options.agentId;
|
|
41
78
|
this.token = options.token;
|
|
42
79
|
this.capabilities = options.capabilities ?? ["chat"];
|
|
43
|
-
this.heartbeatIntervalMs = options.heartbeatIntervalMs
|
|
80
|
+
this.heartbeatIntervalMs = safeDelayMs(options.heartbeatIntervalMs, 30_000, 100);
|
|
81
|
+
this.connectTimeoutMs = safeDelayMs(options.connectTimeoutMs, 15_000, 0);
|
|
44
82
|
this.reconnect = options.reconnect ?? true;
|
|
45
|
-
this.initialReconnectDelayMs = options.initialReconnectDelayMs
|
|
46
|
-
this.maxReconnectDelayMs = options.maxReconnectDelayMs
|
|
83
|
+
this.initialReconnectDelayMs = safeDelayMs(options.initialReconnectDelayMs, 1_000, 0);
|
|
84
|
+
this.maxReconnectDelayMs = safeDelayMs(options.maxReconnectDelayMs, 60_000, 0);
|
|
47
85
|
this.onDebug = options.onDebug;
|
|
48
86
|
this.onReconnect = options.onReconnect;
|
|
49
87
|
}
|
|
50
88
|
|
|
89
|
+
private clearConnectTimer(): void {
|
|
90
|
+
if (this.connectTimer) {
|
|
91
|
+
clearTimeout(this.connectTimer);
|
|
92
|
+
this.connectTimer = null;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
private emitError(err: Error): void {
|
|
97
|
+
for (const h of this.errorHandlers) {
|
|
98
|
+
try {
|
|
99
|
+
h(err);
|
|
100
|
+
} catch {
|
|
101
|
+
/* isolate error listener faults */
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
51
106
|
connect(): Promise<void> {
|
|
52
107
|
return new Promise((resolve, reject) => {
|
|
108
|
+
this.clearConnectTimer();
|
|
109
|
+
if (this.reconnectTimer) {
|
|
110
|
+
clearTimeout(this.reconnectTimer);
|
|
111
|
+
this.reconnectTimer = null;
|
|
112
|
+
}
|
|
113
|
+
if (this.heartbeatTimer) {
|
|
114
|
+
clearInterval(this.heartbeatTimer);
|
|
115
|
+
this.heartbeatTimer = null;
|
|
116
|
+
}
|
|
117
|
+
const prevWs = this.ws;
|
|
118
|
+
this.ws = null;
|
|
119
|
+
this.sessionId = null;
|
|
120
|
+
this.sessionJoined.clear();
|
|
121
|
+
if (prevWs) {
|
|
122
|
+
try { prevWs.close(); } catch {}
|
|
123
|
+
}
|
|
53
124
|
this.connectSettled = false;
|
|
54
125
|
this.explicitlyDisconnected = false;
|
|
55
126
|
this.reconnectAttempt = 0;
|
|
@@ -77,14 +148,24 @@ export class MuseAgentChatClient {
|
|
|
77
148
|
|
|
78
149
|
disconnect(): void {
|
|
79
150
|
this.explicitlyDisconnected = true;
|
|
151
|
+
this.clearConnectTimer();
|
|
80
152
|
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
81
153
|
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
82
154
|
this.reconnectTimer = null;
|
|
83
155
|
this.heartbeatTimer = null;
|
|
84
|
-
this.
|
|
156
|
+
if (!this.connectSettled) {
|
|
157
|
+
this.connectSettled = true;
|
|
158
|
+
this.connectReject?.(new Error("Disconnected before authentication completed"));
|
|
159
|
+
}
|
|
160
|
+
this.connectResolve = null;
|
|
161
|
+
this.connectReject = null;
|
|
162
|
+
this.lifecycleResolve?.();
|
|
163
|
+
this.lifecycleResolve = null;
|
|
164
|
+
const prev = this.ws;
|
|
85
165
|
this.ws = null;
|
|
86
166
|
this.sessionId = null;
|
|
87
|
-
this.
|
|
167
|
+
this.sessionJoined.clear();
|
|
168
|
+
try { prev?.close(); } catch {}
|
|
88
169
|
}
|
|
89
170
|
|
|
90
171
|
get isConnected(): boolean {
|
|
@@ -104,30 +185,50 @@ export class MuseAgentChatClient {
|
|
|
104
185
|
}
|
|
105
186
|
|
|
106
187
|
joinChannel(channelId: string): void {
|
|
107
|
-
|
|
188
|
+
const clean = normalizeChannelId(channelId);
|
|
189
|
+
if (!clean) return;
|
|
190
|
+
if (!this.joinedChannels.has(clean) && this.joinedChannels.size >= MAX_JOINED_CHANNELS) return;
|
|
191
|
+
this.joinedChannels.add(clean);
|
|
192
|
+
this.sessionJoined.add(clean);
|
|
193
|
+
this.send({ type: "join_channel", channel_id: clean, agent_id: this.agentId });
|
|
108
194
|
}
|
|
109
195
|
|
|
110
196
|
leaveChannel(channelId: string): void {
|
|
111
|
-
|
|
197
|
+
const clean = normalizeChannelId(channelId);
|
|
198
|
+
if (!clean) return;
|
|
199
|
+
this.joinedChannels.delete(clean);
|
|
200
|
+
this.sessionJoined.delete(clean);
|
|
201
|
+
this.send({ type: "leave_channel", channel_id: clean, agent_id: this.agentId });
|
|
112
202
|
}
|
|
113
203
|
|
|
114
|
-
sendMessage(
|
|
204
|
+
sendMessage(
|
|
205
|
+
channelId: string,
|
|
206
|
+
content: string,
|
|
207
|
+
contentType: ChatMessage["content_type"] = "text",
|
|
208
|
+
replyTo?: string,
|
|
209
|
+
): void {
|
|
210
|
+
const clean = normalizeChannelId(channelId);
|
|
211
|
+
if (!clean || (replyTo !== undefined &&
|
|
212
|
+
(typeof replyTo !== "string" || replyTo.length > 256 || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(replyTo)))) return;
|
|
115
213
|
this.send({
|
|
116
214
|
type: "message",
|
|
117
215
|
id: crypto.randomUUID(),
|
|
118
|
-
channel_id:
|
|
216
|
+
channel_id: clean,
|
|
119
217
|
sender_id: this.agentId,
|
|
120
218
|
sender_type: "agent",
|
|
121
219
|
content,
|
|
122
220
|
content_type: contentType,
|
|
123
221
|
timestamp: new Date().toISOString(),
|
|
222
|
+
...(replyTo ? { reply_to: replyTo } : {}),
|
|
124
223
|
});
|
|
125
224
|
}
|
|
126
225
|
|
|
127
226
|
sendTyping(channelId: string): void {
|
|
227
|
+
const clean = normalizeChannelId(channelId);
|
|
228
|
+
if (!clean) return;
|
|
128
229
|
// cross_pod:true → the hub fans the frame out to humans on other pods;
|
|
129
230
|
// typing frames are ephemeral and never persisted.
|
|
130
|
-
this.send({ type: "typing", channel_id:
|
|
231
|
+
this.send({ type: "typing", channel_id: clean, sender_id: this.agentId, cross_pod: true });
|
|
131
232
|
}
|
|
132
233
|
|
|
133
234
|
private debug(event: string, meta?: Record<string, unknown>): void {
|
|
@@ -136,33 +237,89 @@ export class MuseAgentChatClient {
|
|
|
136
237
|
|
|
137
238
|
private openSocket(): void {
|
|
138
239
|
this.debug("connect:start", { url: this.url, agentId: this.agentId });
|
|
240
|
+
this.clearConnectTimer();
|
|
241
|
+
this.sessionJoined.clear();
|
|
139
242
|
const ws = new WebSocket(this.url);
|
|
140
243
|
this.ws = ws;
|
|
244
|
+
if (this.connectTimeoutMs > 0) {
|
|
245
|
+
this.connectTimer = setTimeout(() => {
|
|
246
|
+
this.connectTimer = null;
|
|
247
|
+
if (this.ws !== ws) return;
|
|
248
|
+
const err = new Error(`AgentsChat connect timed out after ${this.connectTimeoutMs}ms`);
|
|
249
|
+
if (!this.connectSettled) {
|
|
250
|
+
this.connectSettled = true;
|
|
251
|
+
this.explicitlyDisconnected = true;
|
|
252
|
+
try { ws.close(); } catch {}
|
|
253
|
+
this.connectReject?.(err);
|
|
254
|
+
this.emitError(err);
|
|
255
|
+
} else if (this.sessionId === null) {
|
|
256
|
+
// Reconnect handshake stalled before auth_ok: close hung socket so onclose schedules next retry!
|
|
257
|
+
this.emitError(err);
|
|
258
|
+
try { ws.close(); } catch {}
|
|
259
|
+
}
|
|
260
|
+
}, this.connectTimeoutMs);
|
|
261
|
+
this.connectTimer.unref?.();
|
|
262
|
+
}
|
|
141
263
|
ws.onopen = () => {
|
|
142
|
-
this.
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
264
|
+
if (this.ws !== ws) return;
|
|
265
|
+
try {
|
|
266
|
+
this.send({
|
|
267
|
+
type: "auth",
|
|
268
|
+
agent_id: this.agentId,
|
|
269
|
+
token: this.token,
|
|
270
|
+
capabilities: this.capabilities,
|
|
271
|
+
});
|
|
272
|
+
} catch (err) {
|
|
273
|
+
this.clearConnectTimer();
|
|
274
|
+
if (!this.connectSettled) {
|
|
275
|
+
this.connectSettled = true;
|
|
276
|
+
this.connectReject?.(err instanceof Error ? err : new Error(String(err)));
|
|
277
|
+
}
|
|
278
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
279
|
+
try { ws.close(); } catch {}
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
148
282
|
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
149
283
|
this.heartbeatTimer = setInterval(() => {
|
|
150
|
-
this.
|
|
284
|
+
if (this.ws !== ws) return;
|
|
285
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
286
|
+
try {
|
|
287
|
+
this.send({ type: "ping", timestamp: new Date().toISOString() });
|
|
288
|
+
} catch (err) {
|
|
289
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
290
|
+
try { ws.close(); } catch {}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
151
293
|
}, this.heartbeatIntervalMs);
|
|
294
|
+
this.heartbeatTimer.unref?.();
|
|
295
|
+
};
|
|
296
|
+
ws.onmessage = (event) => {
|
|
297
|
+
if (this.ws !== ws) return;
|
|
298
|
+
if (rawFrameByteLength(event.data) > MAX_WS_FRAME_BYTES) return;
|
|
299
|
+
this.handleMessage(String(event.data));
|
|
152
300
|
};
|
|
153
|
-
ws.onmessage = (event) => this.handleMessage(String(event.data));
|
|
154
301
|
ws.onerror = () => {
|
|
302
|
+
if (this.ws !== ws) return;
|
|
155
303
|
const err = new Error("WebSocket error");
|
|
156
304
|
if (!this.connectSettled) {
|
|
305
|
+
this.clearConnectTimer();
|
|
157
306
|
this.connectSettled = true;
|
|
158
307
|
this.connectReject?.(err);
|
|
159
308
|
}
|
|
160
|
-
this.
|
|
309
|
+
this.emitError(err);
|
|
161
310
|
};
|
|
162
311
|
ws.onclose = () => {
|
|
312
|
+
if (this.ws !== ws) return;
|
|
313
|
+
this.clearConnectTimer();
|
|
163
314
|
if (this.heartbeatTimer) clearInterval(this.heartbeatTimer);
|
|
164
315
|
this.heartbeatTimer = null;
|
|
165
316
|
this.sessionId = null;
|
|
317
|
+
this.sessionJoined.clear();
|
|
318
|
+
if (!this.connectSettled && !this.reconnect) {
|
|
319
|
+
this.clearConnectTimer();
|
|
320
|
+
this.connectSettled = true;
|
|
321
|
+
this.connectReject?.(new Error("WebSocket closed before authentication"));
|
|
322
|
+
}
|
|
166
323
|
if (this.explicitlyDisconnected) {
|
|
167
324
|
this.lifecycleResolve?.();
|
|
168
325
|
return;
|
|
@@ -171,14 +328,22 @@ export class MuseAgentChatClient {
|
|
|
171
328
|
this.lifecycleResolve?.();
|
|
172
329
|
return;
|
|
173
330
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
this.
|
|
177
|
-
|
|
178
|
-
|
|
331
|
+
let delay: number;
|
|
332
|
+
if (this.nextReconnectDelayOverrideMs !== null) {
|
|
333
|
+
delay = this.nextReconnectDelayOverrideMs;
|
|
334
|
+
this.nextReconnectDelayOverrideMs = null;
|
|
335
|
+
} else {
|
|
336
|
+
const exp = Math.min(Math.max(0, this.reconnectAttempt), 30);
|
|
337
|
+
delay = Math.min(
|
|
338
|
+
this.initialReconnectDelayMs * 2 ** exp,
|
|
339
|
+
this.maxReconnectDelayMs,
|
|
340
|
+
);
|
|
341
|
+
this.reconnectAttempt += 1;
|
|
342
|
+
}
|
|
179
343
|
this.isReconnecting = true;
|
|
180
344
|
this.debug("reconnect:scheduled", { delayMs: delay, attempt: this.reconnectAttempt });
|
|
181
345
|
this.reconnectTimer = setTimeout(() => this.openSocket(), delay);
|
|
346
|
+
this.reconnectTimer.unref?.();
|
|
182
347
|
};
|
|
183
348
|
}
|
|
184
349
|
|
|
@@ -190,13 +355,19 @@ export class MuseAgentChatClient {
|
|
|
190
355
|
}
|
|
191
356
|
|
|
192
357
|
private handleMessage(raw: string): void {
|
|
193
|
-
|
|
358
|
+
if (Buffer.byteLength(raw, "utf8") > 1_048_576) return;
|
|
359
|
+
let parsed: unknown;
|
|
194
360
|
try {
|
|
195
|
-
|
|
361
|
+
parsed = JSON.parse(raw);
|
|
196
362
|
} catch {
|
|
197
363
|
return;
|
|
198
364
|
}
|
|
365
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.hasOwn(parsed, "__proto__")) {
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
const msg = parsed as WireMessage;
|
|
199
369
|
if (msg.type === "auth_ok") {
|
|
370
|
+
this.clearConnectTimer();
|
|
200
371
|
this.sessionId = typeof msg.session_id === "string" ? msg.session_id : null;
|
|
201
372
|
this.reconnectAttempt = 0;
|
|
202
373
|
const wasReconnect = this.isReconnecting;
|
|
@@ -206,24 +377,55 @@ export class MuseAgentChatClient {
|
|
|
206
377
|
this.connectResolve?.();
|
|
207
378
|
} else if (wasReconnect) {
|
|
208
379
|
this.onReconnect?.();
|
|
380
|
+
for (const ch of this.joinedChannels) {
|
|
381
|
+
if (!this.sessionJoined.has(ch) && this.ws?.readyState === WebSocket.OPEN) {
|
|
382
|
+
this.joinChannel(ch);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
209
385
|
}
|
|
210
386
|
return;
|
|
211
387
|
}
|
|
212
|
-
if (msg.type === "error") {
|
|
213
|
-
const
|
|
388
|
+
if (msg.type === "auth_error" || msg.type === "error") {
|
|
389
|
+
const text =
|
|
390
|
+
typeof msg.error === "string"
|
|
391
|
+
? msg.error
|
|
392
|
+
: typeof msg.message === "string"
|
|
393
|
+
? msg.message
|
|
394
|
+
: msg.type === "auth_error"
|
|
395
|
+
? "AgentsChat authentication error"
|
|
396
|
+
: "AgentsChat error";
|
|
397
|
+
const err = new Error(sanitizeMuseText(text).slice(0, 1024));
|
|
398
|
+
if (msg.type === "auth_error") {
|
|
399
|
+
this.explicitlyDisconnected = true;
|
|
400
|
+
try {
|
|
401
|
+
this.ws?.close();
|
|
402
|
+
} catch {}
|
|
403
|
+
}
|
|
214
404
|
if (!this.connectSettled) {
|
|
405
|
+
this.clearConnectTimer();
|
|
215
406
|
this.connectSettled = true;
|
|
216
407
|
this.connectReject?.(err);
|
|
217
408
|
}
|
|
218
|
-
this.
|
|
409
|
+
this.emitError(err);
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (msg.type === "please_reconnect" || msg.type === "shard_moved") {
|
|
413
|
+
this.nextReconnectDelayOverrideMs = resolveDrainReconnectDelay(
|
|
414
|
+
msg as { jitter_ms?: unknown; within_ms?: unknown },
|
|
415
|
+
);
|
|
416
|
+
this.reconnectAttempt = 0;
|
|
417
|
+
try {
|
|
418
|
+
this.ws?.close();
|
|
419
|
+
} catch {}
|
|
219
420
|
return;
|
|
220
421
|
}
|
|
221
422
|
if (msg.type === "pong") return;
|
|
222
423
|
if (msg.type === "channel_created" && typeof msg.channel_id === "string" && msg.channel_id) {
|
|
223
|
-
this.joinChannel(msg.channel_id);
|
|
424
|
+
if (this.ws?.readyState === WebSocket.OPEN) this.joinChannel(msg.channel_id);
|
|
224
425
|
return;
|
|
225
426
|
}
|
|
226
|
-
if (msg.type === "message") {
|
|
427
|
+
if (msg.type === "message" || msg.type === "thread_reply") {
|
|
428
|
+
if (msg.content === "__typing__") return;
|
|
227
429
|
const chat: ChatMessage = {
|
|
228
430
|
id: String(msg.id ?? ""),
|
|
229
431
|
channel_id: String(msg.channel_id ?? ""),
|
|
@@ -233,9 +435,22 @@ export class MuseAgentChatClient {
|
|
|
233
435
|
content_type: (msg.content_type as ChatMessage["content_type"]) ?? "text",
|
|
234
436
|
timestamp: String(msg.timestamp ?? new Date().toISOString()),
|
|
235
437
|
channel_type: msg.channel_type as ChatMessage["channel_type"],
|
|
236
|
-
thread_id:
|
|
438
|
+
thread_id:
|
|
439
|
+
typeof msg.thread_id === "string"
|
|
440
|
+
? msg.thread_id
|
|
441
|
+
: typeof msg.parent_id === "string"
|
|
442
|
+
? msg.parent_id
|
|
443
|
+
: undefined,
|
|
237
444
|
};
|
|
238
|
-
for (const h of this.messageHandlers)
|
|
445
|
+
for (const h of this.messageHandlers) {
|
|
446
|
+
try {
|
|
447
|
+
Promise.resolve(h(chat)).catch((err) => {
|
|
448
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
449
|
+
});
|
|
450
|
+
} catch (err) {
|
|
451
|
+
this.emitError(err instanceof Error ? err : new Error(String(err)));
|
|
452
|
+
}
|
|
453
|
+
}
|
|
239
454
|
}
|
|
240
455
|
}
|
|
241
456
|
}
|
package/muse/src/config.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { existsSync, readFileSync } from "node:fs";
|
|
1
|
+
import { existsSync, lstatSync, readFileSync, realpathSync } from "node:fs";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
|
-
import { join } from "node:path";
|
|
3
|
+
import { dirname, isAbsolute, join, sep } from "node:path";
|
|
4
4
|
|
|
5
5
|
export interface MuseAgentChatConfig {
|
|
6
6
|
agentId: string;
|
|
@@ -14,6 +14,112 @@ export interface MuseAgentChatConfig {
|
|
|
14
14
|
export const DEFAULT_WS_URL = "wss://agents-chat.com/ws";
|
|
15
15
|
export const DEFAULT_REST_URL = "https://agents-chat.com";
|
|
16
16
|
export const PROFILE_PATH = join(homedir(), ".agentschat", "muse.json");
|
|
17
|
+
const MAX_PROFILE_BYTES = 64 * 1024;
|
|
18
|
+
|
|
19
|
+
function isLoopbackHost(hostname: string): boolean {
|
|
20
|
+
const h = hostname.toLowerCase();
|
|
21
|
+
return h === "localhost" || h === "127.0.0.1" || h === "[::1]" || h === "::1";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** URL.hostname is already canonicalized by the WHATWG URL parser. */
|
|
25
|
+
export function isUnsafeEndpointHost(hostname: string): boolean {
|
|
26
|
+
let host = hostname.toLowerCase().replace(/\.+$/, "");
|
|
27
|
+
if (["metadata.google.internal", "metadata.goog", "metadata", "instance-data"].includes(host) ||
|
|
28
|
+
host.endsWith(".metadata.google.internal") || host.endsWith(".metadata.goog")) return true;
|
|
29
|
+
const unsafeV4 = (ip: string) => ip.startsWith("0.") || ip === "100.100.100.200" || ip.startsWith("169.254.");
|
|
30
|
+
if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return unsafeV4(host);
|
|
31
|
+
if (!host.startsWith("[")) return false;
|
|
32
|
+
try {
|
|
33
|
+
host = new URL(`http://${host}`).hostname.toLowerCase();
|
|
34
|
+
} catch {
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
const address = host.slice(1, -1);
|
|
38
|
+
const [left, right = ""] = address.split("::");
|
|
39
|
+
const head = left ? left.split(":") : [];
|
|
40
|
+
const tail = right ? right.split(":") : [];
|
|
41
|
+
const words = (address.includes("::")
|
|
42
|
+
? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail]
|
|
43
|
+
: head).map(x => parseInt(x, 16));
|
|
44
|
+
if (words.length !== 8) return true;
|
|
45
|
+
const mapped = (words.slice(0, 5).every(x => x === 0) && words[5] === 0xffff) ||
|
|
46
|
+
(words.slice(0, 4).every(x => x === 0) && words[4] === 0xffff && words[5] === 0);
|
|
47
|
+
if (mapped) return unsafeV4(`${words[6]! >> 8}.${words[6]! & 255}.${words[7]! >> 8}.${words[7]! & 255}`);
|
|
48
|
+
return words.every(x => x === 0) || (words[0]! & 0xffc0) === 0xfe80 ||
|
|
49
|
+
(words[0] === 0xfd00 && words[1] === 0xec2 && words.slice(2, 7).every(x => x === 0) && words[7] === 0x254);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function isSafeAgentId(value: unknown): value is string {
|
|
53
|
+
return typeof value === "string" && value.length > 0 && value.length <= 128 &&
|
|
54
|
+
![".", "..", "__proto__", "constructor", "prototype"].includes(value.toLowerCase()) &&
|
|
55
|
+
!/[\/\\\s\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Inspect existing ancestors before recursive mkdir can follow a symlink. */
|
|
59
|
+
export function assertSafeParentDirectories(file: string): void {
|
|
60
|
+
if (!file || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(file)) {
|
|
61
|
+
throw new Error("Refusing to write Muse file inside symlinked or non-directory parent");
|
|
62
|
+
}
|
|
63
|
+
// Preserve lexical .. components so a symlink before /../ is still inspected.
|
|
64
|
+
const parent = dirname(isAbsolute(file) ? file : `${process.cwd()}${sep}${file}`);
|
|
65
|
+
// Check from root to leaf, before a later /.. can hide a symlink.
|
|
66
|
+
const parts = parent.split(sep);
|
|
67
|
+
for (let i = 1; i <= parts.length; i++) {
|
|
68
|
+
const dir = parts.slice(0, i).join(sep) || sep;
|
|
69
|
+
try {
|
|
70
|
+
const st = lstatSync(dir);
|
|
71
|
+
const systemLink = process.platform === "darwin" &&
|
|
72
|
+
["/var", "/tmp", "/etc"].includes(dir) && st.isSymbolicLink() &&
|
|
73
|
+
realpathSync(dir) === `/private${dir}` &&
|
|
74
|
+
!lstatSync("/private").isSymbolicLink() && lstatSync("/private").isDirectory() &&
|
|
75
|
+
!lstatSync(`/private${dir}`).isSymbolicLink() &&
|
|
76
|
+
lstatSync(`/private${dir}`).isDirectory();
|
|
77
|
+
if ((!systemLink && st.isSymbolicLink()) || (!st.isDirectory() && !systemLink)) {
|
|
78
|
+
throw new Error("Refusing to write Muse file inside symlinked or non-directory parent");
|
|
79
|
+
}
|
|
80
|
+
} catch (err) {
|
|
81
|
+
if ((err as NodeJS.ErrnoException)?.code !== "ENOENT") throw err;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function validateEndpointUrl(raw: string, kind: "ws" | "rest"): string {
|
|
87
|
+
if (raw !== raw.trim() || /["<>\\\x00-\x20\x7f-\x9f\u2028\u2029]/.test(raw)) {
|
|
88
|
+
throw new Error(`Invalid Muse ${kind} URL`);
|
|
89
|
+
}
|
|
90
|
+
const trimmed = raw;
|
|
91
|
+
let parsed: URL;
|
|
92
|
+
try {
|
|
93
|
+
parsed = new URL(trimmed);
|
|
94
|
+
} catch {
|
|
95
|
+
throw new Error(`Invalid Muse ${kind} URL`);
|
|
96
|
+
}
|
|
97
|
+
if (isUnsafeEndpointHost(parsed.hostname)) {
|
|
98
|
+
throw new Error(`Unsafe Muse ${kind} URL host`);
|
|
99
|
+
}
|
|
100
|
+
if (parsed.port === "0" || parsed.search || parsed.hash || raw.includes("?") || raw.includes("#")) {
|
|
101
|
+
throw new Error(`Invalid Muse ${kind} URL port/query/hash`);
|
|
102
|
+
}
|
|
103
|
+
if (parsed.username || parsed.password) {
|
|
104
|
+
throw new Error(`Embedded credentials are not allowed in Muse ${kind} URL`);
|
|
105
|
+
}
|
|
106
|
+
if (kind === "ws") {
|
|
107
|
+
if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:") {
|
|
108
|
+
throw new Error(`Invalid Muse ws URL protocol: ${parsed.protocol}`);
|
|
109
|
+
}
|
|
110
|
+
if (parsed.protocol === "ws:" && !isLoopbackHost(parsed.hostname)) {
|
|
111
|
+
throw new Error("Remote Muse ws URL must use wss://");
|
|
112
|
+
}
|
|
113
|
+
} else {
|
|
114
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
115
|
+
throw new Error(`Invalid Muse rest URL protocol: ${parsed.protocol}`);
|
|
116
|
+
}
|
|
117
|
+
if (parsed.protocol === "http:" && !isLoopbackHost(parsed.hostname)) {
|
|
118
|
+
throw new Error("Remote Muse rest URL must use https://");
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return trimmed;
|
|
122
|
+
}
|
|
17
123
|
|
|
18
124
|
export function redact(value: string | undefined): string {
|
|
19
125
|
if (!value) return "(missing)";
|
|
@@ -44,8 +150,14 @@ interface ProfileFile {
|
|
|
44
150
|
|
|
45
151
|
function readProfile(path = PROFILE_PATH): ProfileFile {
|
|
46
152
|
try {
|
|
153
|
+
assertSafeParentDirectories(path);
|
|
47
154
|
if (!existsSync(path)) return {};
|
|
48
|
-
|
|
155
|
+
const st = lstatSync(path);
|
|
156
|
+
if (!st.isFile() || st.isSymbolicLink() || st.size > MAX_PROFILE_BYTES) return {};
|
|
157
|
+
const parsed = JSON.parse(readFileSync(path, "utf8"));
|
|
158
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) && !Object.hasOwn(parsed, "__proto__")
|
|
159
|
+
? (parsed as ProfileFile)
|
|
160
|
+
: {};
|
|
49
161
|
} catch {
|
|
50
162
|
return {};
|
|
51
163
|
}
|
|
@@ -59,21 +171,25 @@ function readProfile(path = PROFILE_PATH): ProfileFile {
|
|
|
59
171
|
*/
|
|
60
172
|
export function loadConfig(env: NodeJS.ProcessEnv = process.env, profilePath?: string): MuseAgentChatConfig {
|
|
61
173
|
const profile = readProfile(profilePath);
|
|
62
|
-
const
|
|
63
|
-
const
|
|
64
|
-
if (!
|
|
174
|
+
const rawAgentId = (env.AGENTCHAT_AGENT_ID ?? profile.agentId ?? "").trim();
|
|
175
|
+
const rawToken = (env.AGENTCHAT_TOKEN ?? profile.token ?? "").trim();
|
|
176
|
+
if (!isSafeAgentId(rawAgentId) || !rawToken || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(rawAgentId) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(rawToken)) {
|
|
65
177
|
throw new Error(
|
|
66
178
|
"Missing AgentsChat identity: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " +
|
|
67
179
|
`or create ${profilePath ?? PROFILE_PATH} via 'muse-agentchat --register-only --name <name>'. ` +
|
|
68
180
|
"Tokens are never printed; see README for registration.",
|
|
69
181
|
);
|
|
70
182
|
}
|
|
183
|
+
const wsUrl = validateEndpointUrl(env.AGENTCHAT_WS_URL ?? profile.wsUrl ?? DEFAULT_WS_URL, "ws");
|
|
184
|
+
const restUrl = validateEndpointUrl(env.AGENTCHAT_REST_URL ?? profile.restUrl ?? DEFAULT_REST_URL, "rest");
|
|
185
|
+
const rawDisplay = (env.AGENTCHAT_DISPLAY_NAME ?? profile.displayName)?.trim();
|
|
186
|
+
const rawChannel = (env.AGENTCHAT_CHANNEL_ID ?? profile.defaultChannelId)?.trim();
|
|
71
187
|
return {
|
|
72
|
-
agentId,
|
|
73
|
-
token,
|
|
74
|
-
wsUrl
|
|
75
|
-
restUrl
|
|
76
|
-
displayName:
|
|
77
|
-
defaultChannelId:
|
|
188
|
+
agentId: rawAgentId,
|
|
189
|
+
token: rawToken,
|
|
190
|
+
wsUrl,
|
|
191
|
+
restUrl,
|
|
192
|
+
displayName: rawDisplay || undefined,
|
|
193
|
+
defaultChannelId: rawChannel || undefined,
|
|
78
194
|
};
|
|
79
195
|
}
|
package/muse/src/policy.ts
CHANGED
|
@@ -16,27 +16,41 @@ export const MAX_CONTEXT_BYTES = 15_000;
|
|
|
16
16
|
export const MAX_MESSAGE_BYTES = 2_000;
|
|
17
17
|
|
|
18
18
|
export function isMentioned(content: string, agentId: string, displayName?: string): boolean {
|
|
19
|
+
if (typeof content !== "string") return false;
|
|
19
20
|
const haystack = content.toLowerCase();
|
|
20
|
-
const names = [`@${agentId.toLowerCase()}`];
|
|
21
|
-
if (displayName) names.push(`@${displayName.toLowerCase()}`);
|
|
22
21
|
// "muse" is the public name of this agent; accept a bare @muse mention too.
|
|
23
|
-
names
|
|
24
|
-
|
|
22
|
+
const names = [agentId, displayName, "muse"]
|
|
23
|
+
.filter((name): name is string => typeof name === "string" && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(name) && name.trim().length > 0)
|
|
24
|
+
.map((name) => `@${name.trim().toLowerCase()}`);
|
|
25
|
+
return names.some((name) => {
|
|
26
|
+
let index = haystack.indexOf(name);
|
|
27
|
+
while (index !== -1) {
|
|
28
|
+
const before = haystack[index - 1];
|
|
29
|
+
const afterCodePoint = haystack.codePointAt(index + name.length);
|
|
30
|
+
const after = afterCodePoint === undefined ? "" : String.fromCodePoint(afterCodePoint);
|
|
31
|
+
if ((!before || !/[a-z0-9@]/i.test(before)) &&
|
|
32
|
+
(!after || !/[\p{L}\p{N}\p{M}_-]/u.test(after))) return true;
|
|
33
|
+
index = haystack.indexOf(name, index + 1);
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
36
|
+
});
|
|
25
37
|
}
|
|
26
38
|
|
|
27
39
|
export function shouldDispatch(
|
|
28
40
|
message: ChatMessage,
|
|
29
41
|
opts: { agentId: string; displayName?: string; channelKind?: ChannelKind },
|
|
30
42
|
): boolean {
|
|
43
|
+
if (!message || typeof message !== "object" || typeof message.content !== "string") return false;
|
|
31
44
|
if (message.sender_id === opts.agentId) return false;
|
|
32
45
|
if (opts.channelKind === "direct") return true;
|
|
33
46
|
// Unknown kind: be conservative and require a mention, except when the
|
|
34
47
|
// message looks like a DM (server may omit channel_type on DMs).
|
|
35
|
-
if (!opts.channelKind
|
|
48
|
+
if (!opts.channelKind && typeof message.channel_id === "string" && /^dm[-:]/i.test(message.channel_id)) return true;
|
|
36
49
|
return isMentioned(message.content, opts.agentId, opts.displayName);
|
|
37
50
|
}
|
|
38
51
|
|
|
39
52
|
function truncateToBytes(text: string, maxBytes: number): string {
|
|
53
|
+
if (typeof text !== "string" || maxBytes <= 0) return "";
|
|
40
54
|
const encoder = new TextEncoder();
|
|
41
55
|
if (encoder.encode(text).length <= maxBytes) return text;
|
|
42
56
|
let low = 0;
|
|
@@ -46,6 +60,9 @@ function truncateToBytes(text: string, maxBytes: number): string {
|
|
|
46
60
|
if (encoder.encode(text.slice(0, mid)).length <= maxBytes) low = mid;
|
|
47
61
|
else high = mid - 1;
|
|
48
62
|
}
|
|
63
|
+
if (low > 0 && low < text.length &&
|
|
64
|
+
text.charCodeAt(low - 1) >= 0xd800 && text.charCodeAt(low - 1) <= 0xdbff &&
|
|
65
|
+
text.charCodeAt(low) >= 0xdc00 && text.charCodeAt(low) <= 0xdfff) low -= 1;
|
|
49
66
|
return text.slice(0, low);
|
|
50
67
|
}
|
|
51
68
|
|
|
@@ -57,12 +74,15 @@ export function buildContext(messages: ChatMessage[], agentId: string): string {
|
|
|
57
74
|
const lines: string[] = [];
|
|
58
75
|
let bytes = 0;
|
|
59
76
|
for (const m of [...recent].reverse()) {
|
|
60
|
-
const
|
|
77
|
+
const sender = typeof m.sender_id === "string"
|
|
78
|
+
? m.sender_id.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]+/g, " ").slice(0, 128)
|
|
79
|
+
: "unknown";
|
|
80
|
+
const line = `${sender}: ${truncateToBytes(m.content, MAX_MESSAGE_BYTES)}\n`;
|
|
61
81
|
const lineBytes = new TextEncoder().encode(line).length;
|
|
62
82
|
if (bytes + lineBytes > MAX_CONTEXT_BYTES) break;
|
|
63
83
|
bytes += lineBytes;
|
|
64
|
-
lines.
|
|
84
|
+
lines.push(line);
|
|
65
85
|
}
|
|
66
86
|
void agentId;
|
|
67
|
-
return lines.join("");
|
|
87
|
+
return lines.reverse().join("");
|
|
68
88
|
}
|