agentschat-mcp 0.36.18 → 0.36.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -14
- package/codex/README.md +2 -2
- package/cordis.patch.yml +23 -0
- package/dist/codex-bridge.js +10 -9
- package/dist/connector.js +3 -2
- package/dist/dsh.js +932 -0
- package/dist/muse.js +612 -0
- package/dist/server.js +1173 -435
- package/dsh/README.md +83 -0
- package/dsh/identity-ui/README.md +76 -0
- package/dsh/identity-ui/client.js +260 -0
- package/dsh/identity-ui/cordis.patch.yml +11 -0
- package/dsh/identity-ui/index.js +21 -0
- package/dsh/identity-ui/package.json +29 -0
- package/dsh/inbound-bridge/README.md +84 -0
- package/dsh/inbound-bridge/index.js +716 -0
- package/dsh/inbound-bridge/package.json +14 -0
- package/dsh/src/cli.ts +374 -0
- package/dsh/src/patch.ts +117 -0
- package/dsh/tests/dsh.test.ts +113 -0
- package/muse/README.md +179 -0
- package/muse/scripts/ensure-muse-wakes.mjs +108 -0
- package/muse/scripts/keepalive-hook.sh +45 -0
- package/muse/scripts/muse-wake-receiver.mjs +51 -0
- package/muse/scripts/setup-muse-keepalive.sh +68 -0
- package/muse/scripts/smoke.mjs +17 -0
- package/muse/skills/muse-keepalive.md +95 -0
- package/muse/skills/onboarding.md +137 -0
- package/muse/src/bridge.ts +83 -0
- package/muse/src/cli.ts +155 -0
- package/muse/src/client.ts +241 -0
- package/muse/src/config.ts +79 -0
- package/muse/src/index.ts +10 -0
- package/muse/src/policy.ts +68 -0
- package/muse/src/types.ts +38 -0
- package/muse/src/typing.ts +51 -0
- package/muse/src/wake.ts +176 -0
- package/muse/tests/bridge.test.mjs +51 -0
- package/muse/tests/client.test.mjs +178 -0
- package/muse/tests/config.test.mjs +24 -0
- package/muse/tests/policy.test.mjs +47 -0
- package/muse/tests/typing.test.mjs +26 -0
- package/muse/tests/wake.test.mjs +81 -0
- package/package.json +17 -3
- package/skills/grok-wake-keepalive.md +1 -1
- package/skills/onboarding.md +40 -34
- package/src/cli.mjs +17 -7
- package/src/redact.ts +10 -4
- package/src/server.ts +817 -431
- package/src/session-bind.ts +325 -12
- package/src/session-route.ts +87 -0
- package/src/tool-annotations.ts +1 -0
- package/src/wake.ts +75 -8
package/dist/dsh.js
ADDED
|
@@ -0,0 +1,932 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// dsh/src/cli.ts
|
|
4
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync3, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "node:fs";
|
|
5
|
+
import { spawn } from "node:child_process";
|
|
6
|
+
import { dirname as dirname2, join as join5 } from "node:path";
|
|
7
|
+
import { homedir as homedir4 } from "node:os";
|
|
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 { homedir } from "node:os";
|
|
365
|
+
import { join } from "node:path";
|
|
366
|
+
var PROFILE_PATH = join(homedir(), ".agentschat", "muse.json");
|
|
367
|
+
function redact(value) {
|
|
368
|
+
if (!value)
|
|
369
|
+
return "(missing)";
|
|
370
|
+
if (value.length <= 4)
|
|
371
|
+
return "****";
|
|
372
|
+
return `${value.slice(0, 2)}****${value.slice(-2)}`;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// muse/src/wake.ts
|
|
376
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
377
|
+
import { appendFileSync, existsSync, readFileSync } from "node:fs";
|
|
378
|
+
var WAKE_SIG_HEADER = "x-agentschat-signature";
|
|
379
|
+
var WAKE_CONTENT_MAX = 500;
|
|
380
|
+
function redactSecrets(text) {
|
|
381
|
+
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]");
|
|
382
|
+
}
|
|
383
|
+
function buildWakePayload(msg, opts = {}) {
|
|
384
|
+
const content = typeof msg.content === "string" ? redactSecrets(msg.content.slice(0, WAKE_CONTENT_MAX)) : undefined;
|
|
385
|
+
const targetSessionId = typeof opts.targetSessionId === "string" && opts.targetSessionId.length > 0 ? opts.targetSessionId : undefined;
|
|
386
|
+
return {
|
|
387
|
+
type: typeof msg.type === "string" ? msg.type : "message",
|
|
388
|
+
channel_id: msg.channel_id,
|
|
389
|
+
message_id: msg.id,
|
|
390
|
+
sender_id: msg.sender_id,
|
|
391
|
+
content,
|
|
392
|
+
mentioned_ids: Array.isArray(msg.mentioned_ids) ? msg.mentioned_ids.filter((x) => typeof x === "string") : undefined,
|
|
393
|
+
timestamp: typeof msg.timestamp === "string" ? msg.timestamp : undefined,
|
|
394
|
+
...targetSessionId ? { target_session_id: targetSessionId } : {}
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
function signWakeBody(body, secret) {
|
|
398
|
+
return createHmac("sha256", secret).update(body, "utf8").digest("hex");
|
|
399
|
+
}
|
|
400
|
+
async function fireWake(msg, cfg) {
|
|
401
|
+
const log = cfg.logger ?? (() => {});
|
|
402
|
+
const url = (cfg.url ?? "").trim();
|
|
403
|
+
if (!url)
|
|
404
|
+
return;
|
|
405
|
+
const body = JSON.stringify(buildWakePayload(msg, { targetSessionId: cfg.targetSessionId }));
|
|
406
|
+
const headers = { "Content-Type": "application/json" };
|
|
407
|
+
if (cfg.secret)
|
|
408
|
+
headers[WAKE_SIG_HEADER] = signWakeBody(body, cfg.secret);
|
|
409
|
+
const doPost = async () => {
|
|
410
|
+
const f = cfg.fetchImpl ?? fetch;
|
|
411
|
+
const ctrl = new AbortController;
|
|
412
|
+
const t = setTimeout(() => ctrl.abort(), cfg.timeoutMs ?? 5000);
|
|
413
|
+
try {
|
|
414
|
+
const res = await f(url, { method: "POST", headers, body, signal: ctrl.signal });
|
|
415
|
+
if (!res.ok)
|
|
416
|
+
log(`[muse-agentchat] wake POST ${url} → HTTP ${res.status}`);
|
|
417
|
+
} finally {
|
|
418
|
+
clearTimeout(t);
|
|
419
|
+
}
|
|
420
|
+
};
|
|
421
|
+
try {
|
|
422
|
+
await doPost();
|
|
423
|
+
} catch (e) {
|
|
424
|
+
try {
|
|
425
|
+
await doPost();
|
|
426
|
+
} catch (e2) {
|
|
427
|
+
log(`[muse-agentchat] wake POST ${url} failed: ${e2}`);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
function appendWakeQueue(queueFile, payload) {
|
|
432
|
+
const line = JSON.stringify(payload);
|
|
433
|
+
if (payload.message_id && existsSync(queueFile)) {
|
|
434
|
+
const existing = readFileSync(queueFile, "utf8");
|
|
435
|
+
if (existing.split(`
|
|
436
|
+
`).some((l) => {
|
|
437
|
+
try {
|
|
438
|
+
return JSON.parse(l).message_id === payload.message_id;
|
|
439
|
+
} catch {
|
|
440
|
+
return false;
|
|
441
|
+
}
|
|
442
|
+
})) {
|
|
443
|
+
return false;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
appendFileSync(queueFile, line + `
|
|
447
|
+
`);
|
|
448
|
+
return true;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// src/session-route.ts
|
|
452
|
+
import { existsSync as existsSync3, readFileSync as readFileSync3 } from "node:fs";
|
|
453
|
+
import { homedir as homedir2 } from "node:os";
|
|
454
|
+
import { join as join3 } from "node:path";
|
|
455
|
+
|
|
456
|
+
// src/session-bind.ts
|
|
457
|
+
import { closeSync, existsSync as existsSync2, mkdirSync, openSync, readFileSync as readFileSync2, readSync, readdirSync, statSync, unlinkSync } from "node:fs";
|
|
458
|
+
import { join as join2 } from "node:path";
|
|
459
|
+
var DEFAULT_SESSION_BINDS_FILENAME = "session-binds.json";
|
|
460
|
+
var LEGACY_AGY_BINDS_FILENAME = "agy-binds.json";
|
|
461
|
+
function parseSessionBinds(raw) {
|
|
462
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw))
|
|
463
|
+
return {};
|
|
464
|
+
const out = {};
|
|
465
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
466
|
+
const key = k.trim();
|
|
467
|
+
if (!key)
|
|
468
|
+
continue;
|
|
469
|
+
if (typeof v === "string" && v.trim()) {
|
|
470
|
+
out[key] = v.trim();
|
|
471
|
+
} else if (v && typeof v === "object" && typeof v.profile === "string" && v.profile.trim()) {
|
|
472
|
+
out[key] = v.profile.trim();
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
return out;
|
|
476
|
+
}
|
|
477
|
+
function loadSessionBinds(configDir) {
|
|
478
|
+
const merged = {};
|
|
479
|
+
for (const filename of [LEGACY_AGY_BINDS_FILENAME, DEFAULT_SESSION_BINDS_FILENAME]) {
|
|
480
|
+
const path = join2(configDir, filename);
|
|
481
|
+
if (!existsSync2(path))
|
|
482
|
+
continue;
|
|
483
|
+
try {
|
|
484
|
+
Object.assign(merged, parseSessionBinds(JSON.parse(readFileSync2(path, "utf8"))));
|
|
485
|
+
} catch {}
|
|
486
|
+
}
|
|
487
|
+
return merged;
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// src/session-route.ts
|
|
491
|
+
function agentschatConfigDir(env = process.env) {
|
|
492
|
+
return env.AGENTSCHAT_CONFIG_DIR ?? join3(homedir2(), ".agentschat");
|
|
493
|
+
}
|
|
494
|
+
function profilePathForName(configDir, name) {
|
|
495
|
+
if (!name || name.includes("/") || name.includes("\\"))
|
|
496
|
+
return;
|
|
497
|
+
const base = name.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
498
|
+
const nested = join3(configDir, "profiles", `${base}.json`);
|
|
499
|
+
if (existsSync3(nested))
|
|
500
|
+
return nested;
|
|
501
|
+
const flat = join3(configDir, `${base}.json`);
|
|
502
|
+
return existsSync3(flat) ? flat : undefined;
|
|
503
|
+
}
|
|
504
|
+
function readAgentId(path) {
|
|
505
|
+
try {
|
|
506
|
+
const parsed = JSON.parse(readFileSync3(path, "utf8"));
|
|
507
|
+
return typeof parsed.agent_id === "string" && parsed.agent_id ? parsed.agent_id : undefined;
|
|
508
|
+
} catch {
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
function resolveSessionForAgent(agentId, opts = {}) {
|
|
513
|
+
if (typeof agentId !== "string" || agentId.length === 0)
|
|
514
|
+
return;
|
|
515
|
+
const configDir = opts.configDir ?? agentschatConfigDir(opts.env);
|
|
516
|
+
let binds;
|
|
517
|
+
try {
|
|
518
|
+
binds = loadSessionBinds(configDir);
|
|
519
|
+
} catch {
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
for (const [sessionId, profileName] of Object.entries(binds).reverse()) {
|
|
523
|
+
const path = profilePathForName(configDir, profileName);
|
|
524
|
+
if (path === undefined)
|
|
525
|
+
continue;
|
|
526
|
+
if (readAgentId(path) !== agentId)
|
|
527
|
+
continue;
|
|
528
|
+
return { sessionId, profileName, agentId };
|
|
529
|
+
}
|
|
530
|
+
return;
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// dsh/src/patch.ts
|
|
534
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync4, writeFileSync } from "node:fs";
|
|
535
|
+
import { dirname, join as join4 } from "node:path";
|
|
536
|
+
import { homedir as homedir3 } from "node:os";
|
|
537
|
+
function resolveDshPatchPath(opts = {}) {
|
|
538
|
+
const home = opts.dshHome ?? process.env.DSH_HOME ?? join4(homedir3(), ".dsh");
|
|
539
|
+
if (opts.dshProfile) {
|
|
540
|
+
return join4(home, "profiles", opts.dshProfile, "cordis.patch.yml");
|
|
541
|
+
}
|
|
542
|
+
return join4(home, "cordis.patch.yml");
|
|
543
|
+
}
|
|
544
|
+
function buildMcpAgentsChatArgs(opts = {}) {
|
|
545
|
+
const pkg = opts.packageSpec ?? "agentschat-mcp@latest";
|
|
546
|
+
const args = ["-y", pkg];
|
|
547
|
+
if (opts.agentsChatProfile) {
|
|
548
|
+
args.push("--profile", opts.agentsChatProfile);
|
|
549
|
+
}
|
|
550
|
+
if (opts.apiUrl) {
|
|
551
|
+
args.push("--url", opts.apiUrl);
|
|
552
|
+
}
|
|
553
|
+
return args;
|
|
554
|
+
}
|
|
555
|
+
function yamlQuote(val) {
|
|
556
|
+
if (/^[A-Za-z0-9._/@:-]+$/.test(val))
|
|
557
|
+
return `'${val}'`;
|
|
558
|
+
return JSON.stringify(val);
|
|
559
|
+
}
|
|
560
|
+
function renderMcpAgentsChatEntry(indent, opts = {}) {
|
|
561
|
+
const args = buildMcpAgentsChatArgs(opts);
|
|
562
|
+
const lines = [
|
|
563
|
+
`${indent}- id: mcp-agentschat`,
|
|
564
|
+
`${indent} name: '@deepseek-ai/dsh-mcp-client'`,
|
|
565
|
+
`${indent} config:`,
|
|
566
|
+
`${indent} serverName: agentschat`,
|
|
567
|
+
`${indent} transport: stdio`,
|
|
568
|
+
`${indent} command: npx`,
|
|
569
|
+
`${indent} args:`,
|
|
570
|
+
...args.map((a) => `${indent} - ${yamlQuote(a)}`)
|
|
571
|
+
];
|
|
572
|
+
return lines.join(`
|
|
573
|
+
`);
|
|
574
|
+
}
|
|
575
|
+
function mergeDshCordisPatch(existingContent, opts = {}) {
|
|
576
|
+
if (/(?:^|\n)\s*-\s*id:\s*['"]?mcp-agentschat['"]?(?:\s|$)/m.test(existingContent)) {
|
|
577
|
+
return { content: existingContent, changed: false };
|
|
578
|
+
}
|
|
579
|
+
const trimmed = existingContent.trim();
|
|
580
|
+
const withoutComments = existingContent.split(`
|
|
581
|
+
`).filter((line) => !/^\s*#/.test(line)).join(`
|
|
582
|
+
`).trim();
|
|
583
|
+
if (!trimmed || withoutComments === "" || withoutComments === "[]") {
|
|
584
|
+
const commentLines = existingContent.split(`
|
|
585
|
+
`).filter((line) => /^\s*#/.test(line));
|
|
586
|
+
const prefix = commentLines.length > 0 ? `${commentLines.join(`
|
|
587
|
+
`)}
|
|
588
|
+
` : "";
|
|
589
|
+
const block2 = `- insert:
|
|
590
|
+
${renderMcpAgentsChatEntry(" ", opts)}
|
|
591
|
+
`;
|
|
592
|
+
return { content: `${prefix}${block2}`, changed: true };
|
|
593
|
+
}
|
|
594
|
+
if (/^-\s*insert:\s*$/m.test(existingContent)) {
|
|
595
|
+
const normalized2 = existingContent.endsWith(`
|
|
596
|
+
`) ? existingContent : `${existingContent}
|
|
597
|
+
`;
|
|
598
|
+
return {
|
|
599
|
+
content: `${normalized2}${renderMcpAgentsChatEntry(" ", opts)}
|
|
600
|
+
`,
|
|
601
|
+
changed: true
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
const normalized = existingContent.endsWith(`
|
|
605
|
+
`) ? existingContent : `${existingContent}
|
|
606
|
+
`;
|
|
607
|
+
const block = `- insert:
|
|
608
|
+
${renderMcpAgentsChatEntry(" ", opts)}
|
|
609
|
+
`;
|
|
610
|
+
return {
|
|
611
|
+
content: `${normalized}${block}`,
|
|
612
|
+
changed: true
|
|
613
|
+
};
|
|
614
|
+
}
|
|
615
|
+
function applyDshCordisPatchFile(opts = {}) {
|
|
616
|
+
const patchPath = resolveDshPatchPath(opts);
|
|
617
|
+
const existing = existsSync4(patchPath) ? readFileSync4(patchPath, "utf8") : "";
|
|
618
|
+
const { content, changed } = mergeDshCordisPatch(existing, opts);
|
|
619
|
+
if (changed) {
|
|
620
|
+
mkdirSync2(dirname(patchPath), { recursive: true });
|
|
621
|
+
writeFileSync(patchPath, content, "utf8");
|
|
622
|
+
}
|
|
623
|
+
return { patchPath, changed };
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
// dsh/src/cli.ts
|
|
627
|
+
var DSH_PROFILE_PATH = join5(homedir4(), ".agentschat", "dsh.json");
|
|
628
|
+
var DEFAULT_WS_URL = "wss://agents-chat.com/ws";
|
|
629
|
+
var DEFAULT_REST_URL = "https://agents-chat.com";
|
|
630
|
+
function arg(name, argv) {
|
|
631
|
+
const i = argv.indexOf(name);
|
|
632
|
+
return i >= 0 ? argv[i + 1] : undefined;
|
|
633
|
+
}
|
|
634
|
+
function has(name, argv) {
|
|
635
|
+
return argv.includes(name);
|
|
636
|
+
}
|
|
637
|
+
function loadDshConfig(env = process.env, profilePath = DSH_PROFILE_PATH) {
|
|
638
|
+
let profile = {};
|
|
639
|
+
try {
|
|
640
|
+
if (existsSync5(profilePath)) {
|
|
641
|
+
profile = JSON.parse(readFileSync5(profilePath, "utf8"));
|
|
642
|
+
}
|
|
643
|
+
} catch {
|
|
644
|
+
profile = {};
|
|
645
|
+
}
|
|
646
|
+
const agentId = env.AGENTCHAT_AGENT_ID ?? profile.agentId;
|
|
647
|
+
const token = env.AGENTCHAT_TOKEN ?? profile.token;
|
|
648
|
+
if (!agentId || !token) {
|
|
649
|
+
throw new Error("Missing AgentsChat identity for DSH: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " + `or create ${profilePath} via 'agentschat-mcp --dsh --register-only --name <name>'.`);
|
|
650
|
+
}
|
|
651
|
+
return {
|
|
652
|
+
agentId,
|
|
653
|
+
token,
|
|
654
|
+
wsUrl: env.AGENTCHAT_WS_URL ?? profile.wsUrl ?? DEFAULT_WS_URL,
|
|
655
|
+
restUrl: env.AGENTCHAT_REST_URL ?? profile.restUrl ?? DEFAULT_REST_URL,
|
|
656
|
+
displayName: env.AGENTCHAT_DISPLAY_NAME ?? profile.displayName,
|
|
657
|
+
defaultChannelId: env.AGENTCHAT_CHANNEL_ID ?? profile.defaultChannelId
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
function safeDshConfig(config) {
|
|
661
|
+
return {
|
|
662
|
+
agentId: config.agentId,
|
|
663
|
+
wsUrl: config.wsUrl,
|
|
664
|
+
restUrl: config.restUrl,
|
|
665
|
+
displayName: config.displayName,
|
|
666
|
+
defaultChannelId: config.defaultChannelId,
|
|
667
|
+
token: redact(config.token)
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
async function registerOnly(name, restUrl, profilePath = DSH_PROFILE_PATH) {
|
|
671
|
+
console.log("Terms notice: https://agents-chat.com/terms (notice only, no acceptance prompt)");
|
|
672
|
+
const res = await fetch(`${restUrl.replace(/\/$/, "")}/api/account/register`, {
|
|
673
|
+
method: "POST",
|
|
674
|
+
headers: { "content-type": "application/json" },
|
|
675
|
+
body: JSON.stringify({ name, type: "agent", capabilities: ["chat"] })
|
|
676
|
+
});
|
|
677
|
+
if (!res.ok)
|
|
678
|
+
throw new Error(`Registration failed: ${res.status} ${await res.text()}`);
|
|
679
|
+
const data = await res.json();
|
|
680
|
+
const agentId = data.agentId ?? data.agent_id ?? data.id;
|
|
681
|
+
const token = data.agentKey ?? data.token ?? data.key;
|
|
682
|
+
if (!agentId || !token)
|
|
683
|
+
throw new Error("Registration response did not include an agent id/token");
|
|
684
|
+
mkdirSync3(dirname2(profilePath), { recursive: true });
|
|
685
|
+
writeFileSync2(profilePath, JSON.stringify({ agentId, token }, null, 2), { mode: 384 });
|
|
686
|
+
console.log(`Registered DSH agent '${name}' as ${agentId}. Identity saved to ${profilePath} (token not printed).`);
|
|
687
|
+
}
|
|
688
|
+
async function runDshHeadlessResponder(prompt, opts = {}) {
|
|
689
|
+
const dshBin = opts.dshBin ?? process.env.DSH_BIN ?? "dsh";
|
|
690
|
+
const dshProfile = opts.dshProfile ?? process.env.DSH_PROFILE ?? "headless";
|
|
691
|
+
const timeoutMs = opts.timeoutMs ?? 120000;
|
|
692
|
+
return new Promise((resolve) => {
|
|
693
|
+
const child = spawn(dshBin, ["--profile", dshProfile, prompt], {
|
|
694
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
695
|
+
env: process.env
|
|
696
|
+
});
|
|
697
|
+
let stdout = "";
|
|
698
|
+
let stderr = "";
|
|
699
|
+
const timer = setTimeout(() => {
|
|
700
|
+
try {
|
|
701
|
+
child.kill("SIGTERM");
|
|
702
|
+
} catch {}
|
|
703
|
+
}, timeoutMs);
|
|
704
|
+
child.stdout.on("data", (chunk) => {
|
|
705
|
+
stdout += chunk.toString("utf8");
|
|
706
|
+
});
|
|
707
|
+
child.stderr.on("data", (chunk) => {
|
|
708
|
+
stderr += chunk.toString("utf8");
|
|
709
|
+
});
|
|
710
|
+
child.on("error", (err) => {
|
|
711
|
+
clearTimeout(timer);
|
|
712
|
+
console.error(`[dsh] failed to spawn ${dshBin}: ${err.message}`);
|
|
713
|
+
resolve(null);
|
|
714
|
+
});
|
|
715
|
+
child.on("close", (code) => {
|
|
716
|
+
clearTimeout(timer);
|
|
717
|
+
if (code !== 0) {
|
|
718
|
+
console.error(`[dsh] exited with code ${code}: ${stderr.trim().slice(0, 300)}`);
|
|
719
|
+
resolve(null);
|
|
720
|
+
return;
|
|
721
|
+
}
|
|
722
|
+
const trimmed = stdout.trim();
|
|
723
|
+
resolve(trimmed.length > 0 ? trimmed : null);
|
|
724
|
+
});
|
|
725
|
+
});
|
|
726
|
+
}
|
|
727
|
+
async function main(argv = process.argv.slice(2)) {
|
|
728
|
+
if (has("--help", argv) || has("-h", argv)) {
|
|
729
|
+
console.log(`Usage: agentschat-mcp --dsh [options]
|
|
730
|
+
|
|
731
|
+
DeepSeek Harness (dsh) integration for AgentsChat:
|
|
732
|
+
1. Bundle install (recommended for dsh web / desktop):
|
|
733
|
+
dsh plugin --profile web add agentschat-mcp
|
|
734
|
+
2. Patch setup (injects @deepseek-ai/dsh-mcp-client into cordis.patch.yml):
|
|
735
|
+
npx -y agentschat-mcp@latest --dsh --setup [--dsh-profile <name>] [--profile <agentschat-profile>]
|
|
736
|
+
3. Register a dedicated DSH bot identity (~/.agentschat/dsh.json):
|
|
737
|
+
npx -y agentschat-mcp@latest --dsh --register-only --name <bot-name>
|
|
738
|
+
4. Real-time WebSocket wake daemon or headless auto-responder:
|
|
739
|
+
npx -y agentschat-mcp@latest --dsh --wake --channel welcome
|
|
740
|
+
npx -y agentschat-mcp@latest --dsh --listen --channel welcome [--dsh-profile headless] [--auto-reply <text>]
|
|
741
|
+
5. Send a one-off message:
|
|
742
|
+
npx -y agentschat-mcp@latest --dsh --send <channel-id> --text <text>`);
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (has("--setup", argv)) {
|
|
746
|
+
const dshHome = arg("--dsh-home", argv);
|
|
747
|
+
const dshProfile = arg("--dsh-profile", argv);
|
|
748
|
+
const agentsChatProfile = arg("--profile", argv);
|
|
749
|
+
const apiUrl = arg("--url", argv);
|
|
750
|
+
const { patchPath, changed } = applyDshCordisPatchFile({
|
|
751
|
+
dshHome,
|
|
752
|
+
dshProfile,
|
|
753
|
+
agentsChatProfile,
|
|
754
|
+
apiUrl
|
|
755
|
+
});
|
|
756
|
+
console.log(changed ? `[dsh] Configured mcp-agentschat (@deepseek-ai/dsh-mcp-client) in ${patchPath}` : `[dsh] mcp-agentschat is already configured in ${patchPath}`);
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
if (has("--register-only", argv)) {
|
|
760
|
+
const name = arg("--name", argv);
|
|
761
|
+
if (!name)
|
|
762
|
+
throw new Error("--register-only requires --name <name>");
|
|
763
|
+
const restUrl = process.env.AGENTCHAT_REST_URL ?? DEFAULT_REST_URL;
|
|
764
|
+
await registerOnly(name, restUrl);
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
const config = loadDshConfig();
|
|
768
|
+
console.log("DSH AgentsChat:", JSON.stringify(safeDshConfig(config)));
|
|
769
|
+
const client = new MuseAgentChatClient({
|
|
770
|
+
url: config.wsUrl,
|
|
771
|
+
agentId: config.agentId,
|
|
772
|
+
token: config.token,
|
|
773
|
+
capabilities: ["chat"]
|
|
774
|
+
});
|
|
775
|
+
if (has("--wake", argv)) {
|
|
776
|
+
const wakeChannels = [];
|
|
777
|
+
for (let i = 0;i < argv.length; i++) {
|
|
778
|
+
if (argv[i] === "--channel" && argv[i + 1])
|
|
779
|
+
wakeChannels.push(argv[i + 1]);
|
|
780
|
+
}
|
|
781
|
+
if (config.defaultChannelId)
|
|
782
|
+
wakeChannels.push(config.defaultChannelId);
|
|
783
|
+
const queueFile = process.env.DSH_WAKE_QUEUE ?? join5(homedir4(), ".agentschat", "dsh-wake-queue.jsonl");
|
|
784
|
+
const wakeUrl = process.env.DSH_WAKE_URL ?? process.env.AGENTCHAT_WAKE_URL;
|
|
785
|
+
const wakeSecret = process.env.DSH_WAKE_SECRET ?? process.env.AGENTCHAT_WAKE_SECRET;
|
|
786
|
+
const connectedAgentIds = new Set;
|
|
787
|
+
const activeTyping = [];
|
|
788
|
+
process.on("SIGINT", () => {
|
|
789
|
+
for (const t of activeTyping)
|
|
790
|
+
t.stopAll();
|
|
791
|
+
});
|
|
792
|
+
const attachWakeForClient = (botClient, botIdentity) => {
|
|
793
|
+
const typing = new TypingHeartbeat((channelId) => botClient.sendTyping(channelId));
|
|
794
|
+
activeTyping.push(typing);
|
|
795
|
+
botClient.onMessage((m) => {
|
|
796
|
+
if (m.sender_id === botIdentity.agentId) {
|
|
797
|
+
typing.stop(m.channel_id);
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
const kind = m.channel_id.startsWith("dm-") ? "direct" : "group";
|
|
801
|
+
if (!shouldDispatch(m, { agentId: botIdentity.agentId, displayName: botIdentity.displayName, channelKind: kind }))
|
|
802
|
+
return;
|
|
803
|
+
typing.start(m.channel_id);
|
|
804
|
+
const route = resolveSessionForAgent(botIdentity.agentId);
|
|
805
|
+
const payload = buildWakePayload({ ...m, type: "message" }, { targetSessionId: route?.sessionId });
|
|
806
|
+
const queued = appendWakeQueue(queueFile, payload);
|
|
807
|
+
fireWake({ ...m, type: "message" }, { url: wakeUrl, secret: wakeSecret, logger: console.error, targetSessionId: route?.sessionId });
|
|
808
|
+
console.log(`[dsh-wake] ${m.channel_id} ${m.sender_id} ${m.id} agent=${botIdentity.agentId} queued=${queued} target=${route?.sessionId ?? "unbound"}`);
|
|
809
|
+
});
|
|
810
|
+
botClient.onReconnect = () => {
|
|
811
|
+
for (const c of wakeChannels)
|
|
812
|
+
botClient.joinChannel(c);
|
|
813
|
+
};
|
|
814
|
+
};
|
|
815
|
+
connectedAgentIds.add(config.agentId);
|
|
816
|
+
attachWakeForClient(client, { agentId: config.agentId, displayName: config.displayName });
|
|
817
|
+
await client.connect();
|
|
818
|
+
for (const c of wakeChannels)
|
|
819
|
+
client.joinChannel(c);
|
|
820
|
+
const syncBoundDshClients = async () => {
|
|
821
|
+
try {
|
|
822
|
+
const cfgDir = agentschatConfigDir();
|
|
823
|
+
const binds = loadSessionBinds(cfgDir);
|
|
824
|
+
for (const [sid, profName] of Object.entries(binds)) {
|
|
825
|
+
if (!sid.startsWith("session-") || !profName)
|
|
826
|
+
continue;
|
|
827
|
+
const base = profName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
828
|
+
const candidates = [join5(cfgDir, "profiles", `${base}.json`), join5(cfgDir, `${base}.json`)];
|
|
829
|
+
const profPath = candidates.find((p) => existsSync5(p));
|
|
830
|
+
if (!profPath)
|
|
831
|
+
continue;
|
|
832
|
+
const raw = JSON.parse(readFileSync5(profPath, "utf8"));
|
|
833
|
+
const botAgentId = typeof raw.agent_id === "string" ? raw.agent_id : typeof raw.agentId === "string" ? raw.agentId : "";
|
|
834
|
+
const botToken = typeof raw.token === "string" ? raw.token : "";
|
|
835
|
+
if (!botAgentId || !botToken || botToken === "dev-token" || connectedAgentIds.has(botAgentId))
|
|
836
|
+
continue;
|
|
837
|
+
connectedAgentIds.add(botAgentId);
|
|
838
|
+
const extraClient = new MuseAgentChatClient({
|
|
839
|
+
url: config.wsUrl,
|
|
840
|
+
agentId: botAgentId,
|
|
841
|
+
token: botToken,
|
|
842
|
+
capabilities: ["chat"]
|
|
843
|
+
});
|
|
844
|
+
attachWakeForClient(extraClient, {
|
|
845
|
+
agentId: botAgentId,
|
|
846
|
+
displayName: typeof raw.display_name === "string" ? raw.display_name : undefined
|
|
847
|
+
});
|
|
848
|
+
await extraClient.connect();
|
|
849
|
+
for (const c of wakeChannels)
|
|
850
|
+
extraClient.joinChannel(c);
|
|
851
|
+
console.log(`[dsh-wake] Connected bound session ${sid} -> ${profName} (${botAgentId})`);
|
|
852
|
+
}
|
|
853
|
+
} catch {}
|
|
854
|
+
};
|
|
855
|
+
await syncBoundDshClients();
|
|
856
|
+
const bindTimer = setInterval(() => void syncBoundDshClients(), 5000);
|
|
857
|
+
bindTimer.unref?.();
|
|
858
|
+
console.log(`DSH wake daemon listening on ${wakeChannels.join(", ") || "(no channels — pass --channel <id>)"}, queue=${queueFile}.`);
|
|
859
|
+
await client.waitUntilClosed();
|
|
860
|
+
clearInterval(bindTimer);
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
if (has("--send", argv)) {
|
|
864
|
+
const channelId = arg("--send", argv);
|
|
865
|
+
const text = arg("--text", argv);
|
|
866
|
+
if (!channelId || !text)
|
|
867
|
+
throw new Error("--send requires a channel id and --text <text>");
|
|
868
|
+
await client.connect();
|
|
869
|
+
client.joinChannel(channelId);
|
|
870
|
+
client.sendMessage(channelId, text);
|
|
871
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
872
|
+
client.disconnect();
|
|
873
|
+
console.log(`Sent message to ${channelId} as ${config.agentId}.`);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
if (has("--listen", argv)) {
|
|
877
|
+
const channels = [];
|
|
878
|
+
for (let i = 0;i < argv.length; i++) {
|
|
879
|
+
if (argv[i] === "--channel" && argv[i + 1])
|
|
880
|
+
channels.push(argv[i + 1]);
|
|
881
|
+
}
|
|
882
|
+
if (config.defaultChannelId)
|
|
883
|
+
channels.push(config.defaultChannelId);
|
|
884
|
+
const autoReply = arg("--auto-reply", argv);
|
|
885
|
+
const dshProfile = arg("--dsh-profile", argv) ?? "headless";
|
|
886
|
+
const channelKinds = {};
|
|
887
|
+
for (const c of channels) {
|
|
888
|
+
channelKinds[c] = c.startsWith("dm-") ? "direct" : "group";
|
|
889
|
+
}
|
|
890
|
+
const bridge = new MuseBridge(client, {
|
|
891
|
+
agentId: config.agentId,
|
|
892
|
+
displayName: config.displayName,
|
|
893
|
+
channels,
|
|
894
|
+
channelKinds,
|
|
895
|
+
responder: async (ctx) => {
|
|
896
|
+
console.log(`[inbound] ${ctx.message.channel_id} ${ctx.message.sender_id}: ${ctx.message.content}`);
|
|
897
|
+
if (autoReply)
|
|
898
|
+
return autoReply;
|
|
899
|
+
const prompt = [
|
|
900
|
+
`You are DeepSeek Harness agent ${config.agentId} on AgentsChat.`,
|
|
901
|
+
`Reply concisely to the latest message in channel ${ctx.message.channel_id}.`,
|
|
902
|
+
`Recent conversation context:
|
|
903
|
+
${ctx.context}`,
|
|
904
|
+
`Latest message from ${ctx.message.sender_id}: ${ctx.message.content}`
|
|
905
|
+
].join(`
|
|
906
|
+
|
|
907
|
+
`);
|
|
908
|
+
return runDshHeadlessResponder(prompt, { dshProfile });
|
|
909
|
+
}
|
|
910
|
+
});
|
|
911
|
+
client.onReconnect = () => bridge.rejoin();
|
|
912
|
+
await bridge.start();
|
|
913
|
+
console.log(`DSH bridge listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"} (profile=${dshProfile}).`);
|
|
914
|
+
await client.waitUntilClosed();
|
|
915
|
+
return;
|
|
916
|
+
}
|
|
917
|
+
throw new Error("Specify --setup, --register-only, --wake, --listen, or --send (see --dsh --help)");
|
|
918
|
+
}
|
|
919
|
+
var invokedDirectly = process.argv[1]?.endsWith("dsh/src/cli.ts") || process.argv[1]?.endsWith("dist/dsh.js") || process.argv.includes("--dsh");
|
|
920
|
+
if (invokedDirectly) {
|
|
921
|
+
main().catch((err) => {
|
|
922
|
+
console.error("DSH AgentsChat error:", err instanceof Error ? err.message : String(err));
|
|
923
|
+
process.exit(1);
|
|
924
|
+
});
|
|
925
|
+
}
|
|
926
|
+
export {
|
|
927
|
+
safeDshConfig,
|
|
928
|
+
runDshHeadlessResponder,
|
|
929
|
+
main,
|
|
930
|
+
loadDshConfig,
|
|
931
|
+
DSH_PROFILE_PATH
|
|
932
|
+
};
|