agentschat-mcp 0.36.17 → 0.36.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/codex/README.md +2 -2
- package/cordis.patch.yml +23 -0
- package/dist/codex-bridge.js +10 -9
- package/dist/connector.js +3 -2
- package/dist/dsh.js +932 -0
- package/dist/muse.js +612 -0
- package/dist/server.js +1215 -436
- package/dsh/README.md +83 -0
- package/dsh/identity-ui/README.md +76 -0
- package/dsh/identity-ui/client.js +260 -0
- package/dsh/identity-ui/cordis.patch.yml +11 -0
- package/dsh/identity-ui/index.js +21 -0
- package/dsh/identity-ui/package.json +29 -0
- package/dsh/inbound-bridge/README.md +84 -0
- package/dsh/inbound-bridge/index.js +716 -0
- package/dsh/inbound-bridge/package.json +14 -0
- package/dsh/src/cli.ts +374 -0
- package/dsh/src/patch.ts +117 -0
- package/dsh/tests/dsh.test.ts +113 -0
- package/muse/README.md +179 -0
- package/muse/scripts/ensure-muse-wakes.mjs +108 -0
- package/muse/scripts/keepalive-hook.sh +45 -0
- package/muse/scripts/muse-wake-receiver.mjs +51 -0
- package/muse/scripts/setup-muse-keepalive.sh +68 -0
- package/muse/scripts/smoke.mjs +17 -0
- package/muse/skills/muse-keepalive.md +95 -0
- package/muse/skills/onboarding.md +137 -0
- package/muse/src/bridge.ts +83 -0
- package/muse/src/cli.ts +155 -0
- package/muse/src/client.ts +241 -0
- package/muse/src/config.ts +79 -0
- package/muse/src/index.ts +10 -0
- package/muse/src/policy.ts +68 -0
- package/muse/src/types.ts +38 -0
- package/muse/src/typing.ts +51 -0
- package/muse/src/wake.ts +176 -0
- package/muse/tests/bridge.test.mjs +51 -0
- package/muse/tests/client.test.mjs +178 -0
- package/muse/tests/config.test.mjs +24 -0
- package/muse/tests/policy.test.mjs +47 -0
- package/muse/tests/typing.test.mjs +26 -0
- package/muse/tests/wake.test.mjs +81 -0
- package/package.json +17 -3
- package/skills/grok-wake-keepalive.md +1 -1
- package/skills/onboarding.md +40 -34
- package/src/cli.mjs +17 -7
- package/src/redact.ts +10 -4
- package/src/server.ts +852 -430
- package/src/session-bind.ts +348 -12
- package/src/session-route.ts +87 -0
- package/src/tool-annotations.ts +1 -0
- package/src/wake.ts +75 -8
package/dist/muse.js
ADDED
|
@@ -0,0 +1,612 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// muse/src/cli.ts
|
|
4
|
+
import { writeFileSync, mkdirSync } from "node:fs";
|
|
5
|
+
import { dirname } from "node:path";
|
|
6
|
+
import { homedir as homedir2 } from "node:os";
|
|
7
|
+
import { join as join2 } from "node:path";
|
|
8
|
+
|
|
9
|
+
// muse/src/policy.ts
|
|
10
|
+
var MAX_HISTORY_MESSAGES = 50;
|
|
11
|
+
var MAX_CONTEXT_BYTES = 15000;
|
|
12
|
+
var MAX_MESSAGE_BYTES = 2000;
|
|
13
|
+
function isMentioned(content, agentId, displayName) {
|
|
14
|
+
const haystack = content.toLowerCase();
|
|
15
|
+
const names = [`@${agentId.toLowerCase()}`];
|
|
16
|
+
if (displayName)
|
|
17
|
+
names.push(`@${displayName.toLowerCase()}`);
|
|
18
|
+
names.push("@muse");
|
|
19
|
+
return names.some((name) => haystack.includes(name));
|
|
20
|
+
}
|
|
21
|
+
function shouldDispatch(message, opts) {
|
|
22
|
+
if (message.sender_id === opts.agentId)
|
|
23
|
+
return false;
|
|
24
|
+
if (opts.channelKind === "direct")
|
|
25
|
+
return true;
|
|
26
|
+
if (!opts.channelKind)
|
|
27
|
+
return isMentioned(message.content, opts.agentId, opts.displayName);
|
|
28
|
+
return isMentioned(message.content, opts.agentId, opts.displayName);
|
|
29
|
+
}
|
|
30
|
+
function truncateToBytes(text, maxBytes) {
|
|
31
|
+
const encoder = new TextEncoder;
|
|
32
|
+
if (encoder.encode(text).length <= maxBytes)
|
|
33
|
+
return text;
|
|
34
|
+
let low = 0;
|
|
35
|
+
let high = text.length;
|
|
36
|
+
while (low < high) {
|
|
37
|
+
const mid = Math.floor((low + high + 1) / 2);
|
|
38
|
+
if (encoder.encode(text.slice(0, mid)).length <= maxBytes)
|
|
39
|
+
low = mid;
|
|
40
|
+
else
|
|
41
|
+
high = mid - 1;
|
|
42
|
+
}
|
|
43
|
+
return text.slice(0, low);
|
|
44
|
+
}
|
|
45
|
+
function buildContext(messages, agentId) {
|
|
46
|
+
const recent = messages.slice(-MAX_HISTORY_MESSAGES);
|
|
47
|
+
const lines = [];
|
|
48
|
+
let bytes = 0;
|
|
49
|
+
for (const m of [...recent].reverse()) {
|
|
50
|
+
const line = `${m.sender_id}: ${truncateToBytes(m.content, MAX_MESSAGE_BYTES)}
|
|
51
|
+
`;
|
|
52
|
+
const lineBytes = new TextEncoder().encode(line).length;
|
|
53
|
+
if (bytes + lineBytes > MAX_CONTEXT_BYTES)
|
|
54
|
+
break;
|
|
55
|
+
bytes += lineBytes;
|
|
56
|
+
lines.unshift(line);
|
|
57
|
+
}
|
|
58
|
+
return lines.join("");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// muse/src/typing.ts
|
|
62
|
+
var TYPING_HEARTBEAT_MS = 2000;
|
|
63
|
+
var TYPING_HEARTBEAT_MAX_MS = 120000;
|
|
64
|
+
|
|
65
|
+
class TypingHeartbeat {
|
|
66
|
+
timers = new Map;
|
|
67
|
+
send;
|
|
68
|
+
constructor(send) {
|
|
69
|
+
this.send = send;
|
|
70
|
+
}
|
|
71
|
+
pulse(channelId) {
|
|
72
|
+
try {
|
|
73
|
+
this.send(channelId);
|
|
74
|
+
} catch {}
|
|
75
|
+
}
|
|
76
|
+
start(channelId) {
|
|
77
|
+
if (!channelId || process.env.AGENTSCHAT_AUTO_TYPING === "0")
|
|
78
|
+
return;
|
|
79
|
+
this.stop(channelId);
|
|
80
|
+
this.pulse(channelId);
|
|
81
|
+
const interval = setInterval(() => this.pulse(channelId), TYPING_HEARTBEAT_MS);
|
|
82
|
+
const cap = setTimeout(() => this.stop(channelId), TYPING_HEARTBEAT_MAX_MS);
|
|
83
|
+
this.timers.set(channelId, { interval, cap });
|
|
84
|
+
}
|
|
85
|
+
stop(channelId) {
|
|
86
|
+
const h = this.timers.get(channelId);
|
|
87
|
+
if (!h)
|
|
88
|
+
return;
|
|
89
|
+
clearInterval(h.interval);
|
|
90
|
+
clearTimeout(h.cap);
|
|
91
|
+
this.timers.delete(channelId);
|
|
92
|
+
}
|
|
93
|
+
stopAll() {
|
|
94
|
+
for (const channelId of [...this.timers.keys()])
|
|
95
|
+
this.stop(channelId);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// muse/src/bridge.ts
|
|
100
|
+
class MuseBridge {
|
|
101
|
+
client;
|
|
102
|
+
history = new Map;
|
|
103
|
+
opts;
|
|
104
|
+
typing = new TypingHeartbeat((channelId) => this.client.sendTyping(channelId));
|
|
105
|
+
constructor(client, opts) {
|
|
106
|
+
this.client = client;
|
|
107
|
+
this.opts = opts;
|
|
108
|
+
this.client.onMessage((m) => void this.handleMessage(m));
|
|
109
|
+
}
|
|
110
|
+
async start() {
|
|
111
|
+
await this.client.connect();
|
|
112
|
+
for (const channelId of this.opts.channels)
|
|
113
|
+
this.client.joinChannel(channelId);
|
|
114
|
+
}
|
|
115
|
+
rejoin() {
|
|
116
|
+
for (const channelId of this.opts.channels)
|
|
117
|
+
this.client.joinChannel(channelId);
|
|
118
|
+
}
|
|
119
|
+
stop() {
|
|
120
|
+
this.client.disconnect();
|
|
121
|
+
}
|
|
122
|
+
get isConnected() {
|
|
123
|
+
return this.client.isConnected;
|
|
124
|
+
}
|
|
125
|
+
async handleMessage(message) {
|
|
126
|
+
const list = this.history.get(message.channel_id) ?? [];
|
|
127
|
+
list.push(message);
|
|
128
|
+
this.history.set(message.channel_id, list.slice(-50));
|
|
129
|
+
const kind = this.opts.channelKinds?.[message.channel_id];
|
|
130
|
+
if (!shouldDispatch(message, { agentId: this.opts.agentId, displayName: this.opts.displayName, channelKind: kind })) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
this.typing.start(message.channel_id);
|
|
134
|
+
const ctx = {
|
|
135
|
+
message,
|
|
136
|
+
channelKind: kind,
|
|
137
|
+
history: [...this.history.get(message.channel_id) ?? []],
|
|
138
|
+
context: buildContext(this.history.get(message.channel_id) ?? [], this.opts.agentId)
|
|
139
|
+
};
|
|
140
|
+
const reply = await this.opts.responder(ctx);
|
|
141
|
+
if (reply)
|
|
142
|
+
this.client.sendMessage(message.channel_id, reply);
|
|
143
|
+
this.typing.stop(message.channel_id);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// muse/src/client.ts
|
|
148
|
+
class MuseAgentChatClient {
|
|
149
|
+
ws = null;
|
|
150
|
+
sessionId = null;
|
|
151
|
+
heartbeatTimer = null;
|
|
152
|
+
reconnectTimer = null;
|
|
153
|
+
messageHandlers = [];
|
|
154
|
+
errorHandlers = [];
|
|
155
|
+
connectResolve = null;
|
|
156
|
+
connectReject = null;
|
|
157
|
+
lifecycleResolve = null;
|
|
158
|
+
explicitlyDisconnected = false;
|
|
159
|
+
reconnectAttempt = 0;
|
|
160
|
+
isReconnecting = false;
|
|
161
|
+
connectSettled = false;
|
|
162
|
+
url;
|
|
163
|
+
agentId;
|
|
164
|
+
token;
|
|
165
|
+
capabilities;
|
|
166
|
+
heartbeatIntervalMs;
|
|
167
|
+
reconnect;
|
|
168
|
+
initialReconnectDelayMs;
|
|
169
|
+
maxReconnectDelayMs;
|
|
170
|
+
onDebug;
|
|
171
|
+
onReconnect;
|
|
172
|
+
constructor(options) {
|
|
173
|
+
this.url = options.url;
|
|
174
|
+
this.agentId = options.agentId;
|
|
175
|
+
this.token = options.token;
|
|
176
|
+
this.capabilities = options.capabilities ?? ["chat"];
|
|
177
|
+
this.heartbeatIntervalMs = options.heartbeatIntervalMs ?? 30000;
|
|
178
|
+
this.reconnect = options.reconnect ?? true;
|
|
179
|
+
this.initialReconnectDelayMs = options.initialReconnectDelayMs ?? 1000;
|
|
180
|
+
this.maxReconnectDelayMs = options.maxReconnectDelayMs ?? 60000;
|
|
181
|
+
this.onDebug = options.onDebug;
|
|
182
|
+
this.onReconnect = options.onReconnect;
|
|
183
|
+
}
|
|
184
|
+
connect() {
|
|
185
|
+
return new Promise((resolve, reject) => {
|
|
186
|
+
this.connectSettled = false;
|
|
187
|
+
this.explicitlyDisconnected = false;
|
|
188
|
+
this.reconnectAttempt = 0;
|
|
189
|
+
this.isReconnecting = false;
|
|
190
|
+
this.connectResolve = resolve;
|
|
191
|
+
this.connectReject = reject;
|
|
192
|
+
this.openSocket();
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
waitUntilClosed() {
|
|
196
|
+
if (!this.lifecycleResolve) {
|
|
197
|
+
return new Promise((resolve) => {
|
|
198
|
+
this.lifecycleResolve = resolve;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
return new Promise((resolve) => {
|
|
202
|
+
const prev = this.lifecycleResolve;
|
|
203
|
+
this.lifecycleResolve = () => {
|
|
204
|
+
prev?.();
|
|
205
|
+
resolve();
|
|
206
|
+
};
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
disconnect() {
|
|
210
|
+
this.explicitlyDisconnected = true;
|
|
211
|
+
if (this.reconnectTimer)
|
|
212
|
+
clearTimeout(this.reconnectTimer);
|
|
213
|
+
if (this.heartbeatTimer)
|
|
214
|
+
clearInterval(this.heartbeatTimer);
|
|
215
|
+
this.reconnectTimer = null;
|
|
216
|
+
this.heartbeatTimer = null;
|
|
217
|
+
this.ws?.close();
|
|
218
|
+
this.ws = null;
|
|
219
|
+
this.sessionId = null;
|
|
220
|
+
this.lifecycleResolve?.();
|
|
221
|
+
}
|
|
222
|
+
get isConnected() {
|
|
223
|
+
return this.ws?.readyState === WebSocket.OPEN && this.sessionId !== null;
|
|
224
|
+
}
|
|
225
|
+
get session() {
|
|
226
|
+
return this.sessionId;
|
|
227
|
+
}
|
|
228
|
+
onMessage(handler) {
|
|
229
|
+
this.messageHandlers.push(handler);
|
|
230
|
+
}
|
|
231
|
+
onError(handler) {
|
|
232
|
+
this.errorHandlers.push(handler);
|
|
233
|
+
}
|
|
234
|
+
joinChannel(channelId) {
|
|
235
|
+
this.send({ type: "join_channel", channel_id: channelId, agent_id: this.agentId });
|
|
236
|
+
}
|
|
237
|
+
leaveChannel(channelId) {
|
|
238
|
+
this.send({ type: "leave_channel", channel_id: channelId, agent_id: this.agentId });
|
|
239
|
+
}
|
|
240
|
+
sendMessage(channelId, content, contentType = "text") {
|
|
241
|
+
this.send({
|
|
242
|
+
type: "message",
|
|
243
|
+
id: crypto.randomUUID(),
|
|
244
|
+
channel_id: channelId,
|
|
245
|
+
sender_id: this.agentId,
|
|
246
|
+
sender_type: "agent",
|
|
247
|
+
content,
|
|
248
|
+
content_type: contentType,
|
|
249
|
+
timestamp: new Date().toISOString()
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
sendTyping(channelId) {
|
|
253
|
+
this.send({ type: "typing", channel_id: channelId, sender_id: this.agentId, cross_pod: true });
|
|
254
|
+
}
|
|
255
|
+
debug(event, meta) {
|
|
256
|
+
this.onDebug?.(event, meta);
|
|
257
|
+
}
|
|
258
|
+
openSocket() {
|
|
259
|
+
this.debug("connect:start", { url: this.url, agentId: this.agentId });
|
|
260
|
+
const ws = new WebSocket(this.url);
|
|
261
|
+
this.ws = ws;
|
|
262
|
+
ws.onopen = () => {
|
|
263
|
+
this.send({
|
|
264
|
+
type: "auth",
|
|
265
|
+
agent_id: this.agentId,
|
|
266
|
+
token: this.token,
|
|
267
|
+
capabilities: this.capabilities
|
|
268
|
+
});
|
|
269
|
+
if (this.heartbeatTimer)
|
|
270
|
+
clearInterval(this.heartbeatTimer);
|
|
271
|
+
this.heartbeatTimer = setInterval(() => {
|
|
272
|
+
this.send({ type: "ping", timestamp: new Date().toISOString() });
|
|
273
|
+
}, this.heartbeatIntervalMs);
|
|
274
|
+
};
|
|
275
|
+
ws.onmessage = (event) => this.handleMessage(String(event.data));
|
|
276
|
+
ws.onerror = () => {
|
|
277
|
+
const err = new Error("WebSocket error");
|
|
278
|
+
if (!this.connectSettled) {
|
|
279
|
+
this.connectSettled = true;
|
|
280
|
+
this.connectReject?.(err);
|
|
281
|
+
}
|
|
282
|
+
this.errorHandlers.forEach((h) => h(err));
|
|
283
|
+
};
|
|
284
|
+
ws.onclose = () => {
|
|
285
|
+
if (this.heartbeatTimer)
|
|
286
|
+
clearInterval(this.heartbeatTimer);
|
|
287
|
+
this.heartbeatTimer = null;
|
|
288
|
+
this.sessionId = null;
|
|
289
|
+
if (this.explicitlyDisconnected) {
|
|
290
|
+
this.lifecycleResolve?.();
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
if (!this.reconnect) {
|
|
294
|
+
this.lifecycleResolve?.();
|
|
295
|
+
return;
|
|
296
|
+
}
|
|
297
|
+
const delay = Math.min(this.initialReconnectDelayMs * 2 ** this.reconnectAttempt, this.maxReconnectDelayMs);
|
|
298
|
+
this.reconnectAttempt += 1;
|
|
299
|
+
this.isReconnecting = true;
|
|
300
|
+
this.debug("reconnect:scheduled", { delayMs: delay, attempt: this.reconnectAttempt });
|
|
301
|
+
this.reconnectTimer = setTimeout(() => this.openSocket(), delay);
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
send(payload) {
|
|
305
|
+
if (this.ws?.readyState !== WebSocket.OPEN) {
|
|
306
|
+
throw new Error("AgentsChat socket is not open");
|
|
307
|
+
}
|
|
308
|
+
this.ws.send(JSON.stringify(payload));
|
|
309
|
+
}
|
|
310
|
+
handleMessage(raw) {
|
|
311
|
+
let msg;
|
|
312
|
+
try {
|
|
313
|
+
msg = JSON.parse(raw);
|
|
314
|
+
} catch {
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
if (msg.type === "auth_ok") {
|
|
318
|
+
this.sessionId = typeof msg.session_id === "string" ? msg.session_id : null;
|
|
319
|
+
this.reconnectAttempt = 0;
|
|
320
|
+
const wasReconnect = this.isReconnecting;
|
|
321
|
+
this.isReconnecting = false;
|
|
322
|
+
if (!this.connectSettled) {
|
|
323
|
+
this.connectSettled = true;
|
|
324
|
+
this.connectResolve?.();
|
|
325
|
+
} else if (wasReconnect) {
|
|
326
|
+
this.onReconnect?.();
|
|
327
|
+
}
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
if (msg.type === "error") {
|
|
331
|
+
const err = new Error(typeof msg.message === "string" ? msg.message : "AgentsChat error");
|
|
332
|
+
if (!this.connectSettled) {
|
|
333
|
+
this.connectSettled = true;
|
|
334
|
+
this.connectReject?.(err);
|
|
335
|
+
}
|
|
336
|
+
this.errorHandlers.forEach((h) => h(err));
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (msg.type === "pong")
|
|
340
|
+
return;
|
|
341
|
+
if (msg.type === "channel_created" && typeof msg.channel_id === "string" && msg.channel_id) {
|
|
342
|
+
this.joinChannel(msg.channel_id);
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
if (msg.type === "message") {
|
|
346
|
+
const chat = {
|
|
347
|
+
id: String(msg.id ?? ""),
|
|
348
|
+
channel_id: String(msg.channel_id ?? ""),
|
|
349
|
+
sender_id: String(msg.sender_id ?? ""),
|
|
350
|
+
sender_type: msg.sender_type ?? "agent",
|
|
351
|
+
content: String(msg.content ?? ""),
|
|
352
|
+
content_type: msg.content_type ?? "text",
|
|
353
|
+
timestamp: String(msg.timestamp ?? new Date().toISOString()),
|
|
354
|
+
channel_type: msg.channel_type,
|
|
355
|
+
thread_id: typeof msg.thread_id === "string" ? msg.thread_id : undefined
|
|
356
|
+
};
|
|
357
|
+
for (const h of this.messageHandlers)
|
|
358
|
+
h(chat);
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// muse/src/config.ts
|
|
364
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
365
|
+
import { homedir } from "node:os";
|
|
366
|
+
import { join } from "node:path";
|
|
367
|
+
var DEFAULT_WS_URL = "wss://agents-chat.com/ws";
|
|
368
|
+
var DEFAULT_REST_URL = "https://agents-chat.com";
|
|
369
|
+
var PROFILE_PATH = join(homedir(), ".agentschat", "muse.json");
|
|
370
|
+
function redact(value) {
|
|
371
|
+
if (!value)
|
|
372
|
+
return "(missing)";
|
|
373
|
+
if (value.length <= 4)
|
|
374
|
+
return "****";
|
|
375
|
+
return `${value.slice(0, 2)}****${value.slice(-2)}`;
|
|
376
|
+
}
|
|
377
|
+
function safeConfig(config) {
|
|
378
|
+
return {
|
|
379
|
+
agentId: config.agentId,
|
|
380
|
+
wsUrl: config.wsUrl,
|
|
381
|
+
restUrl: config.restUrl,
|
|
382
|
+
displayName: config.displayName,
|
|
383
|
+
defaultChannelId: config.defaultChannelId,
|
|
384
|
+
token: redact(config.token)
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
function readProfile(path = PROFILE_PATH) {
|
|
388
|
+
try {
|
|
389
|
+
if (!existsSync(path))
|
|
390
|
+
return {};
|
|
391
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
392
|
+
} catch {
|
|
393
|
+
return {};
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
function loadConfig(env = process.env, profilePath) {
|
|
397
|
+
const profile = readProfile(profilePath);
|
|
398
|
+
const agentId = env.AGENTCHAT_AGENT_ID ?? profile.agentId;
|
|
399
|
+
const token = env.AGENTCHAT_TOKEN ?? profile.token;
|
|
400
|
+
if (!agentId || !token) {
|
|
401
|
+
throw new Error("Missing AgentsChat identity: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " + `or create ${profilePath ?? PROFILE_PATH} via 'muse-agentchat --register-only --name <name>'. ` + "Tokens are never printed; see README for registration.");
|
|
402
|
+
}
|
|
403
|
+
return {
|
|
404
|
+
agentId,
|
|
405
|
+
token,
|
|
406
|
+
wsUrl: env.AGENTCHAT_WS_URL ?? profile.wsUrl ?? DEFAULT_WS_URL,
|
|
407
|
+
restUrl: env.AGENTCHAT_REST_URL ?? profile.restUrl ?? DEFAULT_REST_URL,
|
|
408
|
+
displayName: env.AGENTCHAT_DISPLAY_NAME ?? profile.displayName,
|
|
409
|
+
defaultChannelId: env.AGENTCHAT_CHANNEL_ID ?? profile.defaultChannelId
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// muse/src/wake.ts
|
|
414
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
415
|
+
import { appendFileSync, existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
|
|
416
|
+
var WAKE_SIG_HEADER = "x-agentschat-signature";
|
|
417
|
+
var WAKE_CONTENT_MAX = 500;
|
|
418
|
+
function redactSecrets(text) {
|
|
419
|
+
return text.replace(/ac_[A-Za-z0-9_-]+/g, "[redacted]").replace(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[redacted]");
|
|
420
|
+
}
|
|
421
|
+
function buildWakePayload(msg, opts = {}) {
|
|
422
|
+
const content = typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX)) : undefined;
|
|
423
|
+
const targetSessionId = typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
|
|
424
|
+
return {
|
|
425
|
+
type: typeof msg.type === "string" ? msg.type : "message",
|
|
426
|
+
channel_id: msg.channel_id,
|
|
427
|
+
message_id: msg.id,
|
|
428
|
+
sender_id: msg.sender_id,
|
|
429
|
+
content,
|
|
430
|
+
mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string") : undefined,
|
|
431
|
+
timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined,
|
|
432
|
+
...targetSessionId ? { target_session_id: targetSessionId } : {}
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
function signWakeBody(body, secret) {
|
|
436
|
+
return createHmac("sha256", secret).update(body, "utf8").digest("hex");
|
|
437
|
+
}
|
|
438
|
+
async function fireWake(msg, cfg) {
|
|
439
|
+
const log = cfg.logger ?? (() => {});
|
|
440
|
+
const url = (cfg.url ?? "").trim();
|
|
441
|
+
if (!url)
|
|
442
|
+
return;
|
|
443
|
+
const body = JSON.stringify(buildWakePayload(msg, { targetSessionId: cfg.targetSessionId }));
|
|
444
|
+
const headers = { "Content-Type": "application/json" };
|
|
445
|
+
if (cfg.secret)
|
|
446
|
+
headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
|
|
447
|
+
const doPost = async () => {
|
|
448
|
+
const f = cfg.fetchImpl ?? fetch;
|
|
449
|
+
const ctrl = new AbortController;
|
|
450
|
+
const t = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 5000);
|
|
451
|
+
try {
|
|
452
|
+
const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
|
|
453
|
+
if (!res.ok)
|
|
454
|
+
log(`[muse-agentchat] wake POST ${url} → HTTP ${res.status}`);
|
|
455
|
+
} finally {
|
|
456
|
+
clearTimeout(t);
|
|
457
|
+
}
|
|
458
|
+
};
|
|
459
|
+
try {
|
|
460
|
+
await doPost();
|
|
461
|
+
} catch (e) {
|
|
462
|
+
try {
|
|
463
|
+
await doPost();
|
|
464
|
+
} catch (e2) {
|
|
465
|
+
log(`[muse-agentchat] wake POST ${url} failed: ${e2}`);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
function appendWakeQueue(queueFile, payload) {
|
|
470
|
+
const line = JSON.stringify(payload);
|
|
471
|
+
if (payload.message_id && existsSync2(queueFile)) {
|
|
472
|
+
const existing = readFileSync2(queueFile, "utf8");
|
|
473
|
+
if (existing.split(`
|
|
474
|
+
`).some((l) => {
|
|
475
|
+
try {
|
|
476
|
+
return JSON.parse(l).message_id === payload.message_id;
|
|
477
|
+
} catch {
|
|
478
|
+
return false;
|
|
479
|
+
}
|
|
480
|
+
})) {
|
|
481
|
+
return false;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
appendFileSync(queueFile, line + `
|
|
485
|
+
`);
|
|
486
|
+
return true;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// muse/src/cli.ts
|
|
490
|
+
function arg(name, argv) {
|
|
491
|
+
const i = argv.indexOf(name);
|
|
492
|
+
return i >= 0 ? argv[i + 1] : undefined;
|
|
493
|
+
}
|
|
494
|
+
function has(name, argv) {
|
|
495
|
+
return argv.includes(name);
|
|
496
|
+
}
|
|
497
|
+
async function registerOnly(name, restUrl) {
|
|
498
|
+
console.log("Terms notice: https://agents-chat.com/terms (notice only, no acceptance prompt)");
|
|
499
|
+
const res = await fetch(`${restUrl.replace(/\/$/, "")}/api/account/register`, {
|
|
500
|
+
method: "POST",
|
|
501
|
+
headers: { "content-type": "application/json" },
|
|
502
|
+
body: JSON.stringify({ name, type: "agent", capabilities: ["chat"] })
|
|
503
|
+
});
|
|
504
|
+
if (!res.ok)
|
|
505
|
+
throw new Error(`Registration failed: ${res.status} ${await res.text()}`);
|
|
506
|
+
const data = await res.json();
|
|
507
|
+
const agentId = data.agentId ?? data.agent_id ?? data.id;
|
|
508
|
+
const token = data.agentKey ?? data.token ?? data.key;
|
|
509
|
+
if (!agentId || !token)
|
|
510
|
+
throw new Error("Registration response did not include an agent id/token");
|
|
511
|
+
mkdirSync(dirname(PROFILE_PATH), { recursive: true });
|
|
512
|
+
writeFileSync(PROFILE_PATH, JSON.stringify({ agentId, token }, null, 2), { mode: 384 });
|
|
513
|
+
console.log(`Registered agent '${name}' as ${agentId}. Identity saved to ${PROFILE_PATH} (token not printed).`);
|
|
514
|
+
}
|
|
515
|
+
async function main() {
|
|
516
|
+
const argv = process.argv.slice(2);
|
|
517
|
+
if (has("--help", argv) || has("-h", argv)) {
|
|
518
|
+
console.log("Usage: agentschat-mcp --muse --register-only --name <name> | --wake [--channel <id>...] | --listen [--channel <id>...] [--auto-reply <text>] | --send <channel-id> --text <text>");
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
if (has("--register-only", argv)) {
|
|
522
|
+
const name = arg("--name", argv);
|
|
523
|
+
if (!name)
|
|
524
|
+
throw new Error("--register-only requires --name <name>");
|
|
525
|
+
const restUrl = process.env.AGENTCHAT_REST_URL ?? "https://agents-chat.com";
|
|
526
|
+
await registerOnly(name, restUrl);
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
const config = loadConfig();
|
|
530
|
+
console.log("Muse AgentsChat:", JSON.stringify(safeConfig(config)));
|
|
531
|
+
const client = new MuseAgentChatClient({
|
|
532
|
+
url: config.wsUrl,
|
|
533
|
+
agentId: config.agentId,
|
|
534
|
+
token: config.token,
|
|
535
|
+
capabilities: ["chat"]
|
|
536
|
+
});
|
|
537
|
+
if (has("--wake", argv)) {
|
|
538
|
+
const wakeChannels = [];
|
|
539
|
+
for (let i = 0;i < argv.length; i++) {
|
|
540
|
+
if (argv[i] === "--channel" && argv[i + 1])
|
|
541
|
+
wakeChannels.push(argv[i + 1]);
|
|
542
|
+
}
|
|
543
|
+
if (config.defaultChannelId)
|
|
544
|
+
wakeChannels.push(config.defaultChannelId);
|
|
545
|
+
const queueFile = process.env.MUSE_WAKE_QUEUE ?? join2(homedir2(), ".agentschat", "muse-wake-queue.jsonl");
|
|
546
|
+
const wakeUrl = process.env.MUSE_WAKE_URL ?? process.env.AGENTCHAT_WAKE_URL;
|
|
547
|
+
const wakeSecret = process.env.MUSE_WAKE_SECRET ?? process.env.AGENTCHAT_WAKE_SECRET;
|
|
548
|
+
const typing = new TypingHeartbeat((channelId) => client.sendTyping(channelId));
|
|
549
|
+
process.on("SIGINT", () => typing.stopAll());
|
|
550
|
+
client.onMessage((m) => {
|
|
551
|
+
if (m.sender_id === config.agentId) {
|
|
552
|
+
typing.stop(m.channel_id);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
const kind = m.channel_id.startsWith("dm-") ? "direct" : "group";
|
|
556
|
+
if (!shouldDispatch(m, { agentId: config.agentId, displayName: config.displayName, channelKind: kind }))
|
|
557
|
+
return;
|
|
558
|
+
typing.start(m.channel_id);
|
|
559
|
+
const payload = buildWakePayload({ ...m, type: "message" });
|
|
560
|
+
const queued = appendWakeQueue(queueFile, payload);
|
|
561
|
+
fireWake({ ...m, type: "message" }, { url: wakeUrl, secret: wakeSecret, logger: console.error });
|
|
562
|
+
console.log(`[wake] ${m.channel_id} ${m.sender_id} ${m.id} queued=${queued}`);
|
|
563
|
+
});
|
|
564
|
+
client.onReconnect = () => {
|
|
565
|
+
for (const c of wakeChannels)
|
|
566
|
+
client.joinChannel(c);
|
|
567
|
+
};
|
|
568
|
+
await client.connect();
|
|
569
|
+
for (const c of wakeChannels)
|
|
570
|
+
client.joinChannel(c);
|
|
571
|
+
console.log(`Wake daemon listening on ${wakeChannels.join(", ") || "(no channels — pass --channel <id>)"}, queue=${queueFile}. Press Ctrl+C to stop.`);
|
|
572
|
+
await client.waitUntilClosed();
|
|
573
|
+
return;
|
|
574
|
+
}
|
|
575
|
+
if (has("--send", argv)) {
|
|
576
|
+
const channelId = arg("--send", argv);
|
|
577
|
+
const text = arg("--text", argv);
|
|
578
|
+
if (!channelId || !text)
|
|
579
|
+
throw new Error("--send requires a channel id and --text <text>");
|
|
580
|
+
await client.connect();
|
|
581
|
+
client.joinChannel(channelId);
|
|
582
|
+
client.sendMessage(channelId, text);
|
|
583
|
+
console.log(`Sent to ${channelId}`);
|
|
584
|
+
client.disconnect();
|
|
585
|
+
return;
|
|
586
|
+
}
|
|
587
|
+
const channels = [];
|
|
588
|
+
for (let i = 0;i < argv.length; i++) {
|
|
589
|
+
if (argv[i] === "--channel" && argv[i + 1])
|
|
590
|
+
channels.push(argv[i + 1]);
|
|
591
|
+
}
|
|
592
|
+
if (config.defaultChannelId)
|
|
593
|
+
channels.push(config.defaultChannelId);
|
|
594
|
+
const autoReply = arg("--auto-reply", argv);
|
|
595
|
+
const bridge = new MuseBridge(client, {
|
|
596
|
+
agentId: config.agentId,
|
|
597
|
+
displayName: config.displayName,
|
|
598
|
+
channels,
|
|
599
|
+
responder: async (ctx) => {
|
|
600
|
+
console.log(`[${ctx.message.channel_id}] ${ctx.message.sender_id}: ${ctx.message.content}`);
|
|
601
|
+
return autoReply ?? null;
|
|
602
|
+
}
|
|
603
|
+
});
|
|
604
|
+
client.onReconnect = () => bridge.rejoin();
|
|
605
|
+
await bridge.start();
|
|
606
|
+
console.log(`Listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"}. Press Ctrl+C to stop.`);
|
|
607
|
+
await client.waitUntilClosed();
|
|
608
|
+
}
|
|
609
|
+
main().catch((err) => {
|
|
610
|
+
console.error(err instanceof Error ? err.message : String(err));
|
|
611
|
+
process.exit(1);
|
|
612
|
+
});
|