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
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "dsh-agentschat-inbound",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"type": "module",
|
|
6
|
+
"description": "DeepSeek Harness host plugin: signed AgentsChat wakes into a bound session, plus the loopback identity API the GUI chip uses.",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"index.js",
|
|
12
|
+
"README.md"
|
|
13
|
+
]
|
|
14
|
+
}
|
package/dsh/src/cli.ts
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* DeepSeek Harness (dsh) bridge & setup utility for AgentsChat, shipped inside
|
|
4
|
+
* the `agentschat-mcp` package.
|
|
5
|
+
*
|
|
6
|
+
* Usage:
|
|
7
|
+
* npx -y agentschat-mcp@latest --dsh --setup [--dsh-profile <name>] [--profile <agentschat-profile>]
|
|
8
|
+
* npx -y agentschat-mcp@latest --dsh --register-only --name <bot-name>
|
|
9
|
+
* npx -y agentschat-mcp@latest --dsh --wake [--channel <id> ...]
|
|
10
|
+
* npx -y agentschat-mcp@latest --dsh --listen [--channel <id> ...] [--dsh-profile <headless>] [--auto-reply <text>]
|
|
11
|
+
* npx -y agentschat-mcp@latest --dsh --send <channel-id> --text <text>
|
|
12
|
+
*/
|
|
13
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
14
|
+
import { spawn } from "node:child_process";
|
|
15
|
+
import { dirname, join } from "node:path";
|
|
16
|
+
import { homedir } from "node:os";
|
|
17
|
+
import { MuseBridge } from "../../muse/src/bridge.ts";
|
|
18
|
+
import { MuseAgentChatClient } from "../../muse/src/client.ts";
|
|
19
|
+
import { redact } from "../../muse/src/config.ts";
|
|
20
|
+
import { shouldDispatch } from "../../muse/src/policy.ts";
|
|
21
|
+
import { TypingHeartbeat } from "../../muse/src/typing.ts";
|
|
22
|
+
import { appendWakeQueue, buildWakePayload, fireWake } from "../../muse/src/wake.ts";
|
|
23
|
+
import { agentschatConfigDir, resolveSessionForAgent } from "../../src/session-route.ts";
|
|
24
|
+
import { loadSessionBinds } from "../../src/session-bind.ts";
|
|
25
|
+
import { applyDshCordisPatchFile } from "./patch.ts";
|
|
26
|
+
|
|
27
|
+
export const DSH_PROFILE_PATH = join(homedir(), ".agentschat", "dsh.json");
|
|
28
|
+
const DEFAULT_WS_URL = "wss://agents-chat.com/ws";
|
|
29
|
+
const DEFAULT_REST_URL = "https://agents-chat.com";
|
|
30
|
+
|
|
31
|
+
export interface DshBridgeConfig {
|
|
32
|
+
agentId: string;
|
|
33
|
+
token: string;
|
|
34
|
+
wsUrl: string;
|
|
35
|
+
restUrl: string;
|
|
36
|
+
displayName?: string;
|
|
37
|
+
defaultChannelId?: string;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function arg(name: string, argv: string[]): string | undefined {
|
|
41
|
+
const i = argv.indexOf(name);
|
|
42
|
+
return i >= 0 ? argv[i + 1] : undefined;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function has(name: string, argv: string[]): boolean {
|
|
46
|
+
return argv.includes(name);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function loadDshConfig(
|
|
50
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
51
|
+
profilePath: string = DSH_PROFILE_PATH,
|
|
52
|
+
): DshBridgeConfig {
|
|
53
|
+
let profile: Record<string, string | undefined> = {};
|
|
54
|
+
try {
|
|
55
|
+
if (existsSync(profilePath)) {
|
|
56
|
+
profile = JSON.parse(readFileSync(profilePath, "utf8")) as Record<string, string | undefined>;
|
|
57
|
+
}
|
|
58
|
+
} catch {
|
|
59
|
+
profile = {};
|
|
60
|
+
}
|
|
61
|
+
const agentId = env.AGENTCHAT_AGENT_ID ?? profile.agentId;
|
|
62
|
+
const token = env.AGENTCHAT_TOKEN ?? profile.token;
|
|
63
|
+
if (!agentId || !token) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
"Missing AgentsChat identity for DSH: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " +
|
|
66
|
+
`or create ${profilePath} via 'agentschat-mcp --dsh --register-only --name <name>'.`,
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
agentId,
|
|
71
|
+
token,
|
|
72
|
+
wsUrl: env.AGENTCHAT_WS_URL ?? profile.wsUrl ?? DEFAULT_WS_URL,
|
|
73
|
+
restUrl: env.AGENTCHAT_REST_URL ?? profile.restUrl ?? DEFAULT_REST_URL,
|
|
74
|
+
displayName: env.AGENTCHAT_DISPLAY_NAME ?? profile.displayName,
|
|
75
|
+
defaultChannelId: env.AGENTCHAT_CHANNEL_ID ?? profile.defaultChannelId,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function safeDshConfig(config: DshBridgeConfig): Record<string, unknown> {
|
|
80
|
+
return {
|
|
81
|
+
agentId: config.agentId,
|
|
82
|
+
wsUrl: config.wsUrl,
|
|
83
|
+
restUrl: config.restUrl,
|
|
84
|
+
displayName: config.displayName,
|
|
85
|
+
defaultChannelId: config.defaultChannelId,
|
|
86
|
+
token: redact(config.token),
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
async function registerOnly(name: string, restUrl: string, profilePath = DSH_PROFILE_PATH): Promise<void> {
|
|
91
|
+
console.log("Terms notice: https://agents-chat.com/terms (notice only, no acceptance prompt)");
|
|
92
|
+
const res = await fetch(`${restUrl.replace(/\/$/, "")}/api/account/register`, {
|
|
93
|
+
method: "POST",
|
|
94
|
+
headers: { "content-type": "application/json" },
|
|
95
|
+
body: JSON.stringify({ name, type: "agent", capabilities: ["chat"] }),
|
|
96
|
+
});
|
|
97
|
+
if (!res.ok) throw new Error(`Registration failed: ${res.status} ${await res.text()}`);
|
|
98
|
+
const data = (await res.json()) as Record<string, unknown>;
|
|
99
|
+
const agentId = (data.agentId ?? data.agent_id ?? data.id) as string | undefined;
|
|
100
|
+
const token = (data.agentKey ?? data.token ?? data.key) as string | undefined;
|
|
101
|
+
if (!agentId || !token) throw new Error("Registration response did not include an agent id/token");
|
|
102
|
+
mkdirSync(dirname(profilePath), { recursive: true });
|
|
103
|
+
writeFileSync(profilePath, JSON.stringify({ agentId, token }, null, 2), { mode: 0o600 });
|
|
104
|
+
console.log(`Registered DSH agent '${name}' as ${agentId}. Identity saved to ${profilePath} (token not printed).`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Run a one-shot DeepSeek Harness headless turn (`dsh --profile headless "<prompt>"`)
|
|
109
|
+
* with stdin redirected from `/dev/null` so non-interactive spawns never hang.
|
|
110
|
+
*/
|
|
111
|
+
export async function runDshHeadlessResponder(
|
|
112
|
+
prompt: string,
|
|
113
|
+
opts: { dshBin?: string; dshProfile?: string; timeoutMs?: number } = {},
|
|
114
|
+
): Promise<string | null> {
|
|
115
|
+
const dshBin = opts.dshBin ?? process.env.DSH_BIN ?? "dsh";
|
|
116
|
+
const dshProfile = opts.dshProfile ?? process.env.DSH_PROFILE ?? "headless";
|
|
117
|
+
const timeoutMs = opts.timeoutMs ?? 120_000;
|
|
118
|
+
|
|
119
|
+
return new Promise((resolve) => {
|
|
120
|
+
const child = spawn(dshBin, ["--profile", dshProfile, prompt], {
|
|
121
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
122
|
+
env: process.env,
|
|
123
|
+
});
|
|
124
|
+
let stdout = "";
|
|
125
|
+
let stderr = "";
|
|
126
|
+
const timer = setTimeout(() => {
|
|
127
|
+
try {
|
|
128
|
+
child.kill("SIGTERM");
|
|
129
|
+
} catch {
|
|
130
|
+
/* ignore */
|
|
131
|
+
}
|
|
132
|
+
}, timeoutMs);
|
|
133
|
+
|
|
134
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
135
|
+
stdout += chunk.toString("utf8");
|
|
136
|
+
});
|
|
137
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
138
|
+
stderr += chunk.toString("utf8");
|
|
139
|
+
});
|
|
140
|
+
child.on("error", (err) => {
|
|
141
|
+
clearTimeout(timer);
|
|
142
|
+
console.error(`[dsh] failed to spawn ${dshBin}: ${err.message}`);
|
|
143
|
+
resolve(null);
|
|
144
|
+
});
|
|
145
|
+
child.on("close", (code) => {
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
if (code !== 0) {
|
|
148
|
+
console.error(`[dsh] exited with code ${code}: ${stderr.trim().slice(0, 300)}`);
|
|
149
|
+
resolve(null);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
const trimmed = stdout.trim();
|
|
153
|
+
resolve(trimmed.length > 0 ? trimmed : null);
|
|
154
|
+
});
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export async function main(argv: string[] = process.argv.slice(2)): Promise<void> {
|
|
159
|
+
if (has("--help", argv) || has("-h", argv)) {
|
|
160
|
+
console.log(`Usage: agentschat-mcp --dsh [options]
|
|
161
|
+
|
|
162
|
+
DeepSeek Harness (dsh) integration for AgentsChat:
|
|
163
|
+
1. Bundle install (recommended for dsh web / desktop):
|
|
164
|
+
dsh plugin --profile web add agentschat-mcp
|
|
165
|
+
2. Patch setup (injects @deepseek-ai/dsh-mcp-client into cordis.patch.yml):
|
|
166
|
+
npx -y agentschat-mcp@latest --dsh --setup [--dsh-profile <name>] [--profile <agentschat-profile>]
|
|
167
|
+
3. Register a dedicated DSH bot identity (~/.agentschat/dsh.json):
|
|
168
|
+
npx -y agentschat-mcp@latest --dsh --register-only --name <bot-name>
|
|
169
|
+
4. Real-time WebSocket wake daemon or headless auto-responder:
|
|
170
|
+
npx -y agentschat-mcp@latest --dsh --wake --channel welcome
|
|
171
|
+
npx -y agentschat-mcp@latest --dsh --listen --channel welcome [--dsh-profile headless] [--auto-reply <text>]
|
|
172
|
+
5. Send a one-off message:
|
|
173
|
+
npx -y agentschat-mcp@latest --dsh --send <channel-id> --text <text>`);
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (has("--setup", argv)) {
|
|
178
|
+
const dshHome = arg("--dsh-home", argv);
|
|
179
|
+
const dshProfile = arg("--dsh-profile", argv);
|
|
180
|
+
const agentsChatProfile = arg("--profile", argv);
|
|
181
|
+
const apiUrl = arg("--url", argv);
|
|
182
|
+
const { patchPath, changed } = applyDshCordisPatchFile({
|
|
183
|
+
dshHome,
|
|
184
|
+
dshProfile,
|
|
185
|
+
agentsChatProfile,
|
|
186
|
+
apiUrl,
|
|
187
|
+
});
|
|
188
|
+
console.log(
|
|
189
|
+
changed
|
|
190
|
+
? `[dsh] Configured mcp-agentschat (@deepseek-ai/dsh-mcp-client) in ${patchPath}`
|
|
191
|
+
: `[dsh] mcp-agentschat is already configured in ${patchPath}`,
|
|
192
|
+
);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (has("--register-only", argv)) {
|
|
197
|
+
const name = arg("--name", argv);
|
|
198
|
+
if (!name) throw new Error("--register-only requires --name <name>");
|
|
199
|
+
const restUrl = process.env.AGENTCHAT_REST_URL ?? DEFAULT_REST_URL;
|
|
200
|
+
await registerOnly(name, restUrl);
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const config = loadDshConfig();
|
|
205
|
+
console.log("DSH AgentsChat:", JSON.stringify(safeDshConfig(config)));
|
|
206
|
+
const client = new MuseAgentChatClient({
|
|
207
|
+
url: config.wsUrl,
|
|
208
|
+
agentId: config.agentId,
|
|
209
|
+
token: config.token,
|
|
210
|
+
capabilities: ["chat"],
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
if (has("--wake", argv)) {
|
|
214
|
+
const wakeChannels: string[] = [];
|
|
215
|
+
for (let i = 0; i < argv.length; i++) {
|
|
216
|
+
if (argv[i] === "--channel" && argv[i + 1]) wakeChannels.push(argv[i + 1]);
|
|
217
|
+
}
|
|
218
|
+
if (config.defaultChannelId) wakeChannels.push(config.defaultChannelId);
|
|
219
|
+
const queueFile =
|
|
220
|
+
process.env.DSH_WAKE_QUEUE ?? join(homedir(), ".agentschat", "dsh-wake-queue.jsonl");
|
|
221
|
+
const wakeUrl = process.env.DSH_WAKE_URL ?? process.env.AGENTCHAT_WAKE_URL;
|
|
222
|
+
const wakeSecret = process.env.DSH_WAKE_SECRET ?? process.env.AGENTCHAT_WAKE_SECRET;
|
|
223
|
+
|
|
224
|
+
const connectedAgentIds = new Set<string>();
|
|
225
|
+
const activeTyping: TypingHeartbeat[] = [];
|
|
226
|
+
process.on("SIGINT", () => {
|
|
227
|
+
for (const t of activeTyping) t.stopAll();
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
const attachWakeForClient = (
|
|
231
|
+
botClient: MuseAgentChatClient,
|
|
232
|
+
botIdentity: { agentId: string; displayName?: string },
|
|
233
|
+
) => {
|
|
234
|
+
const typing = new TypingHeartbeat((channelId) => botClient.sendTyping(channelId));
|
|
235
|
+
activeTyping.push(typing);
|
|
236
|
+
botClient.onMessage((m) => {
|
|
237
|
+
if (m.sender_id === botIdentity.agentId) {
|
|
238
|
+
typing.stop(m.channel_id);
|
|
239
|
+
return;
|
|
240
|
+
}
|
|
241
|
+
const kind = m.channel_id.startsWith("dm-") ? "direct" : "group";
|
|
242
|
+
if (!shouldDispatch(m, { agentId: botIdentity.agentId, displayName: botIdentity.displayName, channelKind: kind })) return;
|
|
243
|
+
typing.start(m.channel_id);
|
|
244
|
+
// Route the wake to the harness Session this identity is bound to
|
|
245
|
+
// (`session-binds.json`), so the receiver stops guessing "the newest idle
|
|
246
|
+
// Session" — a guess that lands in an unrelated conversation whenever an
|
|
247
|
+
// older Session happens to be idle. No bind → no target, and the receiver
|
|
248
|
+
// keeps its own fallback policy.
|
|
249
|
+
const route = resolveSessionForAgent(botIdentity.agentId);
|
|
250
|
+
const payload = buildWakePayload({ ...m, type: "message" }, { targetSessionId: route?.sessionId });
|
|
251
|
+
const queued = appendWakeQueue(queueFile, payload);
|
|
252
|
+
void fireWake(
|
|
253
|
+
{ ...m, type: "message" },
|
|
254
|
+
{ url: wakeUrl, secret: wakeSecret, logger: console.error, targetSessionId: route?.sessionId },
|
|
255
|
+
);
|
|
256
|
+
console.log(
|
|
257
|
+
`[dsh-wake] ${m.channel_id} ${m.sender_id} ${m.id} agent=${botIdentity.agentId} queued=${queued} target=${route?.sessionId ?? "unbound"}`,
|
|
258
|
+
);
|
|
259
|
+
});
|
|
260
|
+
botClient.onReconnect = () => {
|
|
261
|
+
for (const c of wakeChannels) botClient.joinChannel(c);
|
|
262
|
+
};
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
connectedAgentIds.add(config.agentId);
|
|
266
|
+
attachWakeForClient(client, { agentId: config.agentId, displayName: config.displayName });
|
|
267
|
+
await client.connect();
|
|
268
|
+
for (const c of wakeChannels) client.joinChannel(c);
|
|
269
|
+
|
|
270
|
+
// Also multiplex any additional DSH sessions (`session-*`) bound in `session-binds.json`
|
|
271
|
+
const syncBoundDshClients = async () => {
|
|
272
|
+
try {
|
|
273
|
+
const cfgDir = agentschatConfigDir();
|
|
274
|
+
const binds = loadSessionBinds(cfgDir);
|
|
275
|
+
for (const [sid, profName] of Object.entries(binds)) {
|
|
276
|
+
if (!sid.startsWith("session-") || !profName) continue;
|
|
277
|
+
const base = profName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
|
|
278
|
+
const candidates = [join(cfgDir, "profiles", `${base}.json`), join(cfgDir, `${base}.json`)];
|
|
279
|
+
const profPath = candidates.find((p) => existsSync(p));
|
|
280
|
+
if (!profPath) continue;
|
|
281
|
+
const raw = JSON.parse(readFileSync(profPath, "utf8")) as Record<string, any>;
|
|
282
|
+
const botAgentId = typeof raw.agent_id === "string" ? raw.agent_id : typeof raw.agentId === "string" ? raw.agentId : "";
|
|
283
|
+
const botToken = typeof raw.token === "string" ? raw.token : "";
|
|
284
|
+
if (!botAgentId || !botToken || botToken === "dev-token" || connectedAgentIds.has(botAgentId)) continue;
|
|
285
|
+
connectedAgentIds.add(botAgentId);
|
|
286
|
+
const extraClient = new MuseAgentChatClient({
|
|
287
|
+
url: config.wsUrl,
|
|
288
|
+
agentId: botAgentId,
|
|
289
|
+
token: botToken,
|
|
290
|
+
capabilities: ["chat"],
|
|
291
|
+
});
|
|
292
|
+
attachWakeForClient(extraClient, {
|
|
293
|
+
agentId: botAgentId,
|
|
294
|
+
displayName: typeof raw.display_name === "string" ? raw.display_name : undefined,
|
|
295
|
+
});
|
|
296
|
+
await extraClient.connect();
|
|
297
|
+
for (const c of wakeChannels) extraClient.joinChannel(c);
|
|
298
|
+
console.log(`[dsh-wake] Connected bound session ${sid} -> ${profName} (${botAgentId})`);
|
|
299
|
+
}
|
|
300
|
+
} catch {}
|
|
301
|
+
};
|
|
302
|
+
await syncBoundDshClients();
|
|
303
|
+
const bindTimer = setInterval(() => void syncBoundDshClients(), 5_000);
|
|
304
|
+
(bindTimer as any).unref?.();
|
|
305
|
+
|
|
306
|
+
console.log(`DSH wake daemon listening on ${wakeChannels.join(", ") || "(no channels — pass --channel <id>)"}, queue=${queueFile}.`);
|
|
307
|
+
await client.waitUntilClosed();
|
|
308
|
+
clearInterval(bindTimer);
|
|
309
|
+
return;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (has("--send", argv)) {
|
|
313
|
+
const channelId = arg("--send", argv);
|
|
314
|
+
const text = arg("--text", argv);
|
|
315
|
+
if (!channelId || !text) throw new Error("--send requires a channel id and --text <text>");
|
|
316
|
+
await client.connect();
|
|
317
|
+
client.joinChannel(channelId);
|
|
318
|
+
client.sendMessage(channelId, text);
|
|
319
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
320
|
+
client.disconnect();
|
|
321
|
+
console.log(`Sent message to ${channelId} as ${config.agentId}.`);
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
if (has("--listen", argv)) {
|
|
326
|
+
const channels: string[] = [];
|
|
327
|
+
for (let i = 0; i < argv.length; i++) {
|
|
328
|
+
if (argv[i] === "--channel" && argv[i + 1]) channels.push(argv[i + 1]);
|
|
329
|
+
}
|
|
330
|
+
if (config.defaultChannelId) channels.push(config.defaultChannelId);
|
|
331
|
+
const autoReply = arg("--auto-reply", argv);
|
|
332
|
+
const dshProfile = arg("--dsh-profile", argv) ?? "headless";
|
|
333
|
+
const channelKinds: Record<string, "direct" | "group"> = {};
|
|
334
|
+
for (const c of channels) {
|
|
335
|
+
channelKinds[c] = c.startsWith("dm-") ? "direct" : "group";
|
|
336
|
+
}
|
|
337
|
+
const bridge = new MuseBridge(client, {
|
|
338
|
+
agentId: config.agentId,
|
|
339
|
+
displayName: config.displayName,
|
|
340
|
+
channels,
|
|
341
|
+
channelKinds,
|
|
342
|
+
responder: async (ctx) => {
|
|
343
|
+
console.log(`[inbound] ${ctx.message.channel_id} ${ctx.message.sender_id}: ${ctx.message.content}`);
|
|
344
|
+
if (autoReply) return autoReply;
|
|
345
|
+
const prompt = [
|
|
346
|
+
`You are DeepSeek Harness agent ${config.agentId} on AgentsChat.`,
|
|
347
|
+
`Reply concisely to the latest message in channel ${ctx.message.channel_id}.`,
|
|
348
|
+
`Recent conversation context:\n${ctx.context}`,
|
|
349
|
+
`Latest message from ${ctx.message.sender_id}: ${ctx.message.content}`,
|
|
350
|
+
].join("\n\n");
|
|
351
|
+
return runDshHeadlessResponder(prompt, { dshProfile });
|
|
352
|
+
},
|
|
353
|
+
});
|
|
354
|
+
client.onReconnect = () => bridge.rejoin();
|
|
355
|
+
await bridge.start();
|
|
356
|
+
console.log(`DSH bridge listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"} (profile=${dshProfile}).`);
|
|
357
|
+
await client.waitUntilClosed();
|
|
358
|
+
return;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
throw new Error("Specify --setup, --register-only, --wake, --listen, or --send (see --dsh --help)");
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
const invokedDirectly =
|
|
365
|
+
process.argv[1]?.endsWith("dsh/src/cli.ts") ||
|
|
366
|
+
process.argv[1]?.endsWith("dist/dsh.js") ||
|
|
367
|
+
process.argv.includes("--dsh");
|
|
368
|
+
|
|
369
|
+
if (invokedDirectly) {
|
|
370
|
+
main().catch((err: unknown) => {
|
|
371
|
+
console.error("DSH AgentsChat error:", err instanceof Error ? err.message : String(err));
|
|
372
|
+
process.exit(1);
|
|
373
|
+
});
|
|
374
|
+
}
|
package/dsh/src/patch.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
|
|
5
|
+
export interface DshPatchOptions {
|
|
6
|
+
dshHome?: string;
|
|
7
|
+
dshProfile?: string;
|
|
8
|
+
agentsChatProfile?: string;
|
|
9
|
+
apiUrl?: string;
|
|
10
|
+
packageSpec?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function resolveDshPatchPath(opts: DshPatchOptions = {}): string {
|
|
14
|
+
const home = opts.dshHome ?? process.env.DSH_HOME ?? join(homedir(), ".dsh");
|
|
15
|
+
if (opts.dshProfile) {
|
|
16
|
+
return join(home, "profiles", opts.dshProfile, "cordis.patch.yml");
|
|
17
|
+
}
|
|
18
|
+
return join(home, "cordis.patch.yml");
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function buildMcpAgentsChatArgs(opts: DshPatchOptions = {}): string[] {
|
|
22
|
+
const pkg = opts.packageSpec ?? "agentschat-mcp@latest";
|
|
23
|
+
const args = ["-y", pkg];
|
|
24
|
+
if (opts.agentsChatProfile) {
|
|
25
|
+
args.push("--profile", opts.agentsChatProfile);
|
|
26
|
+
}
|
|
27
|
+
if (opts.apiUrl) {
|
|
28
|
+
args.push("--url", opts.apiUrl);
|
|
29
|
+
}
|
|
30
|
+
return args;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function yamlQuote(val: string): string {
|
|
34
|
+
if (/^[A-Za-z0-9._/@:-]+$/.test(val)) return `'${val}'`;
|
|
35
|
+
return JSON.stringify(val);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Render the YAML lines for an `- id: mcp-agentschat` entry at a given indent.
|
|
40
|
+
*/
|
|
41
|
+
export function renderMcpAgentsChatEntry(indent: string, opts: DshPatchOptions = {}): string {
|
|
42
|
+
const args = buildMcpAgentsChatArgs(opts);
|
|
43
|
+
const lines = [
|
|
44
|
+
`${indent}- id: mcp-agentschat`,
|
|
45
|
+
`${indent} name: '@deepseek-ai/dsh-mcp-client'`,
|
|
46
|
+
`${indent} config:`,
|
|
47
|
+
`${indent} serverName: agentschat`,
|
|
48
|
+
`${indent} transport: stdio`,
|
|
49
|
+
`${indent} command: npx`,
|
|
50
|
+
`${indent} args:`,
|
|
51
|
+
...args.map((a) => `${indent} - ${yamlQuote(a)}`),
|
|
52
|
+
];
|
|
53
|
+
return lines.join("\n");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Idempotently merge the `mcp-agentschat` entry into a DSH `cordis.patch.yml`
|
|
58
|
+
* document string while preserving existing comments and entries (such as
|
|
59
|
+
* machine-local `openai-fetch-proxy` or UI settings overrides).
|
|
60
|
+
*/
|
|
61
|
+
export function mergeDshCordisPatch(existingContent: string, opts: DshPatchOptions = {}): {
|
|
62
|
+
content: string;
|
|
63
|
+
changed: boolean;
|
|
64
|
+
} {
|
|
65
|
+
if (/(?:^|\n)\s*-\s*id:\s*['"]?mcp-agentschat['"]?(?:\s|$)/m.test(existingContent)) {
|
|
66
|
+
return { content: existingContent, changed: false };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const trimmed = existingContent.trim();
|
|
70
|
+
|
|
71
|
+
// Case 1: Empty file or comments-only or empty YAML array `[]`
|
|
72
|
+
const withoutComments = existingContent
|
|
73
|
+
.split("\n")
|
|
74
|
+
.filter((line) => !/^\s*#/.test(line))
|
|
75
|
+
.join("\n")
|
|
76
|
+
.trim();
|
|
77
|
+
|
|
78
|
+
if (!trimmed || withoutComments === "" || withoutComments === "[]") {
|
|
79
|
+
const commentLines = existingContent
|
|
80
|
+
.split("\n")
|
|
81
|
+
.filter((line) => /^\s*#/.test(line));
|
|
82
|
+
const prefix = commentLines.length > 0 ? `${commentLines.join("\n")}\n` : "";
|
|
83
|
+
const block = `- insert:\n${renderMcpAgentsChatEntry(" ", opts)}\n`;
|
|
84
|
+
return { content: `${prefix}${block}`, changed: true };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Case 2: File already has a top-level `- insert:` block (like ~/.dsh/cordis.patch.yml)
|
|
88
|
+
if (/^-\s*insert:\s*$/m.test(existingContent)) {
|
|
89
|
+
const normalized = existingContent.endsWith("\n") ? existingContent : `${existingContent}\n`;
|
|
90
|
+
return {
|
|
91
|
+
content: `${normalized}${renderMcpAgentsChatEntry(" ", opts)}\n`,
|
|
92
|
+
changed: true,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Case 3: File is a top-level YAML array of patch entries (like profiles/desktop/cordis.patch.yml)
|
|
97
|
+
const normalized = existingContent.endsWith("\n") ? existingContent : `${existingContent}\n`;
|
|
98
|
+
const block = `- insert:\n${renderMcpAgentsChatEntry(" ", opts)}\n`;
|
|
99
|
+
return {
|
|
100
|
+
content: `${normalized}${block}`,
|
|
101
|
+
changed: true,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
export function applyDshCordisPatchFile(opts: DshPatchOptions = {}): {
|
|
106
|
+
patchPath: string;
|
|
107
|
+
changed: boolean;
|
|
108
|
+
} {
|
|
109
|
+
const patchPath = resolveDshPatchPath(opts);
|
|
110
|
+
const existing = existsSync(patchPath) ? readFileSync(patchPath, "utf8") : "";
|
|
111
|
+
const { content, changed } = mergeDshCordisPatch(existing, opts);
|
|
112
|
+
if (changed) {
|
|
113
|
+
mkdirSync(dirname(patchPath), { recursive: true });
|
|
114
|
+
writeFileSync(patchPath, content, "utf8");
|
|
115
|
+
}
|
|
116
|
+
return { patchPath, changed };
|
|
117
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { describe, expect, test } from "bun:test";
|
|
2
|
+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import {
|
|
6
|
+
applyDshCordisPatchFile,
|
|
7
|
+
buildMcpAgentsChatArgs,
|
|
8
|
+
mergeDshCordisPatch,
|
|
9
|
+
resolveDshPatchPath,
|
|
10
|
+
} from "../src/patch.ts";
|
|
11
|
+
import { loadDshConfig, safeDshConfig } from "../src/cli.ts";
|
|
12
|
+
|
|
13
|
+
const ROOT = resolve(import.meta.dir, "../..");
|
|
14
|
+
|
|
15
|
+
describe("DeepSeek Harness (dsh) integration", () => {
|
|
16
|
+
test("package.json declares dsh.bundle.patch and ships cordis.patch.yml", () => {
|
|
17
|
+
const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
|
|
18
|
+
expect(pkg.dsh?.bundle?.patch).toBe("./cordis.patch.yml");
|
|
19
|
+
expect(pkg.files).toContain("cordis.patch.yml");
|
|
20
|
+
expect(pkg.files).toContain("dsh/");
|
|
21
|
+
expect(pkg.files).toContain("dist/dsh.js");
|
|
22
|
+
|
|
23
|
+
const bundlePatch = readFileSync(join(ROOT, "cordis.patch.yml"), "utf8");
|
|
24
|
+
expect(bundlePatch).toContain("id: mcp-agentschat");
|
|
25
|
+
expect(bundlePatch).toContain("name: '@deepseek-ai/dsh-mcp-client'");
|
|
26
|
+
expect(bundlePatch).toContain("serverName: agentschat");
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("mergeDshCordisPatch handles empty and [] patch files", () => {
|
|
30
|
+
const emptyRes = mergeDshCordisPatch("");
|
|
31
|
+
expect(emptyRes.changed).toBe(true);
|
|
32
|
+
expect(emptyRes.content).toContain("- insert:");
|
|
33
|
+
expect(emptyRes.content).toContain("- id: mcp-agentschat");
|
|
34
|
+
expect(emptyRes.content).toContain("name: '@deepseek-ai/dsh-mcp-client'");
|
|
35
|
+
|
|
36
|
+
const arrayRes = mergeDshCordisPatch("# comment\n[]\n", {
|
|
37
|
+
agentsChatProfile: "DSH_Bot",
|
|
38
|
+
apiUrl: "https://agents-chat.com",
|
|
39
|
+
});
|
|
40
|
+
expect(arrayRes.changed).toBe(true);
|
|
41
|
+
expect(arrayRes.content).toContain("# comment");
|
|
42
|
+
expect(arrayRes.content).not.toContain("[]");
|
|
43
|
+
expect(arrayRes.content).toContain("- '--profile'");
|
|
44
|
+
expect(arrayRes.content).toContain("- 'DSH_Bot'");
|
|
45
|
+
expect(arrayRes.content).toContain("- '--url'");
|
|
46
|
+
expect(arrayRes.content).toContain("- 'https://agents-chat.com'");
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
test("mergeDshCordisPatch preserves existing - insert: rows and is idempotent", () => {
|
|
50
|
+
const existing = [
|
|
51
|
+
"# Machine-local DSH patch layer",
|
|
52
|
+
"- insert:",
|
|
53
|
+
" - id: openai-fetch-proxy",
|
|
54
|
+
" name: 'file:///Users/test/.dsh/plugins/openai-proxy/index.js'",
|
|
55
|
+
"",
|
|
56
|
+
].join("\n");
|
|
57
|
+
|
|
58
|
+
const first = mergeDshCordisPatch(existing, { agentsChatProfile: "Jack" });
|
|
59
|
+
expect(first.changed).toBe(true);
|
|
60
|
+
expect(first.content).toContain("id: openai-fetch-proxy");
|
|
61
|
+
expect(first.content).toContain("id: mcp-agentschat");
|
|
62
|
+
expect(first.content).toContain("- 'Jack'");
|
|
63
|
+
|
|
64
|
+
const second = mergeDshCordisPatch(first.content, { agentsChatProfile: "Jack" });
|
|
65
|
+
expect(second.changed).toBe(false);
|
|
66
|
+
expect(second.content).toBe(first.content);
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
test("applyDshCordisPatchFile writes to profile or home path", () => {
|
|
70
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-patch-test-"));
|
|
71
|
+
try {
|
|
72
|
+
const homePatch = resolveDshPatchPath({ dshHome: dir });
|
|
73
|
+
expect(homePatch).toBe(join(dir, "cordis.patch.yml"));
|
|
74
|
+
|
|
75
|
+
const res1 = applyDshCordisPatchFile({ dshHome: dir, dshProfile: "desktop", agentsChatProfile: "DshDesktop" });
|
|
76
|
+
expect(res1.changed).toBe(true);
|
|
77
|
+
expect(res1.patchPath).toBe(join(dir, "profiles", "desktop", "cordis.patch.yml"));
|
|
78
|
+
expect(readFileSync(res1.patchPath, "utf8")).toContain("DshDesktop");
|
|
79
|
+
|
|
80
|
+
const res2 = applyDshCordisPatchFile({ dshHome: dir, dshProfile: "desktop", agentsChatProfile: "DshDesktop" });
|
|
81
|
+
expect(res2.changed).toBe(false);
|
|
82
|
+
} finally {
|
|
83
|
+
rmSync(dir, { recursive: true, force: true });
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
|
|
87
|
+
test("loadDshConfig reads profile file and redacts token in safeDshConfig", () => {
|
|
88
|
+
const dir = mkdtempSync(join(tmpdir(), "dsh-cfg-test-"));
|
|
89
|
+
try {
|
|
90
|
+
const profilePath = join(dir, "dsh.json");
|
|
91
|
+
writeFileSync(
|
|
92
|
+
profilePath,
|
|
93
|
+
JSON.stringify({ agentId: "dsh-agent-1", token: "ac_secret_token_123456" }),
|
|
94
|
+
"utf8",
|
|
95
|
+
);
|
|
96
|
+
const cfg = loadDshConfig({}, profilePath);
|
|
97
|
+
expect(cfg.agentId).toBe("dsh-agent-1");
|
|
98
|
+
expect(cfg.token).toBe("ac_secret_token_123456");
|
|
99
|
+
const safe = safeDshConfig(cfg);
|
|
100
|
+
expect(safe.agentId).toBe("dsh-agent-1");
|
|
101
|
+
expect(String(safe.token)).not.toContain("secret_token");
|
|
102
|
+
} finally {
|
|
103
|
+
rmSync(dir, { recursive: true, force: true });
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("buildMcpAgentsChatArgs constructs expected CLI flags", () => {
|
|
108
|
+
expect(buildMcpAgentsChatArgs()).toEqual(["-y", "agentschat-mcp@latest"]);
|
|
109
|
+
expect(
|
|
110
|
+
buildMcpAgentsChatArgs({ agentsChatProfile: "MyDsh", apiUrl: "https://agents-chat.com" }),
|
|
111
|
+
).toEqual(["-y", "agentschat-mcp@latest", "--profile", "MyDsh", "--url", "https://agents-chat.com"]);
|
|
112
|
+
});
|
|
113
|
+
});
|