agentschat-mcp 0.36.24 → 0.36.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +8 -0
  3. package/codex/README.md +1 -1
  4. package/codex/app-server.ts +79 -22
  5. package/codex/bots-config.ts +31 -11
  6. package/codex/bridge.ts +123 -25
  7. package/codex/config.ts +128 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +65 -12
  10. package/codex/loop-grants.ts +41 -11
  11. package/codex/manager.ts +101 -25
  12. package/codex/owner.ts +81 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +41 -11
  16. package/codex/thread-history.ts +77 -30
  17. package/codex/transport.ts +122 -19
  18. package/connector/auth.ts +57 -5
  19. package/connector/backfill.ts +92 -10
  20. package/connector/descriptor.ts +27 -1
  21. package/connector/identities.ts +82 -14
  22. package/connector/ingest.ts +11 -2
  23. package/connector/normalize.ts +32 -12
  24. package/connector/run.ts +314 -67
  25. package/connector/server.ts +95 -26
  26. package/dist/codex-bots.js +410 -73
  27. package/dist/codex-bridge.js +1996 -576
  28. package/dist/connector.js +1286 -493
  29. package/dist/dsh.js +1776 -299
  30. package/dist/muse.js +967 -221
  31. package/dist/server.js +7645 -1172
  32. package/dsh/client.js +7 -5
  33. package/dsh/identity-ui/client.js +7 -5
  34. package/dsh/identity-ui/index.js +43 -8
  35. package/dsh/inbound-bridge/index.js +595 -146
  36. package/dsh/src/cli.ts +430 -91
  37. package/dsh/src/patch.ts +295 -15
  38. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  39. package/dsh/tests/dsh.test.ts +990 -3
  40. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  41. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  42. package/muse/src/bridge.ts +54 -13
  43. package/muse/src/cli.ts +226 -41
  44. package/muse/src/client.ts +249 -34
  45. package/muse/src/config.ts +128 -12
  46. package/muse/src/policy.ts +28 -8
  47. package/muse/src/types.ts +1 -0
  48. package/muse/src/typing.ts +18 -1
  49. package/muse/src/wake.ts +237 -35
  50. package/muse/tests/bridge.test.mjs +131 -0
  51. package/muse/tests/client.test.mjs +327 -0
  52. package/muse/tests/config.test.mjs +78 -1
  53. package/muse/tests/hardening.test.mjs +199 -0
  54. package/muse/tests/hardening126.test.mjs +292 -0
  55. package/muse/tests/policy.test.mjs +83 -1
  56. package/muse/tests/wake.test.mjs +134 -6
  57. package/package.json +3 -3
  58. package/scripts/ensure-grok-wakes.mjs +93 -8
  59. package/scripts/example-url-wake-receiver.mjs +254 -61
  60. package/scripts/grok-bind-register.sh +38 -8
  61. package/skills/agentschat-team-lead/SKILL.md +1 -1
  62. package/skills/onboarding.md +14 -10
  63. package/src/argcheck.ts +1890 -1
  64. package/src/cli.mjs +98 -14
  65. package/src/dedup.ts +57 -8
  66. package/src/grok-bind.ts +160 -33
  67. package/src/heartbeat.ts +39 -11
  68. package/src/identity-guard.ts +93 -20
  69. package/src/identity.ts +67 -11
  70. package/src/mentions.ts +26 -5
  71. package/src/onboarding-status.ts +134 -11
  72. package/src/profile-selection.ts +269 -18
  73. package/src/profile-store.ts +222 -28
  74. package/src/read-cursor.ts +256 -9
  75. package/src/reconnect.ts +98 -2
  76. package/src/redact.ts +34 -15
  77. package/src/rest-cli.ts +713 -159
  78. package/src/server.ts +2487 -342
  79. package/src/session-bind.ts +731 -132
  80. package/src/session-route.ts +183 -12
  81. package/src/team-lead-skill.ts +3 -0
  82. package/src/timestamps.ts +56 -23
  83. package/src/tool-annotations.ts +22 -1
  84. package/src/wake.ts +524 -90
package/dsh/src/cli.ts CHANGED
@@ -10,7 +10,8 @@
10
10
  * npx -y agentschat-mcp@latest --dsh --listen [--channel <id> ...] [--dsh-profile <headless>] [--auto-reply <text>]
11
11
  * npx -y agentschat-mcp@latest --dsh --send <channel-id> --text <text>
12
12
  */
13
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
14
+ import { randomBytes } from "node:crypto";
14
15
  import { spawn } from "node:child_process";
15
16
  import { dirname, join } from "node:path";
16
17
  import { homedir } from "node:os";
@@ -22,7 +23,8 @@ import { TypingHeartbeat } from "../../muse/src/typing.ts";
22
23
  import { appendWakeQueue, buildWakePayload, fireWake } from "../../muse/src/wake.ts";
23
24
  import { agentschatConfigDir, resolveSessionForAgent } from "../../src/session-route.ts";
24
25
  import { loadSessionBinds } from "../../src/session-bind.ts";
25
- import { applyDshCordisPatchFile } from "./patch.ts";
26
+ import { resolveWindowsCliSpawn } from "../../src/wake.ts";
27
+ import { applyDshCordisPatchFile, checkParentDirectory, isBlockedDshHost } from "./patch.ts";
26
28
 
27
29
  export const DSH_PROFILE_PATH = join(homedir(), ".agentschat", "dsh.json");
28
30
  const DEFAULT_WS_URL = "wss://agents-chat.com/ws";
@@ -39,40 +41,182 @@ export interface DshBridgeConfig {
39
41
 
40
42
  function arg(name: string, argv: string[]): string | undefined {
41
43
  const i = argv.indexOf(name);
42
- return i >= 0 ? argv[i + 1] : undefined;
44
+ const value = i >= 0 ? argv[i + 1] : undefined;
45
+ return value?.startsWith("--") ? undefined : value;
43
46
  }
44
47
 
45
48
  function has(name: string, argv: string[]): boolean {
46
49
  return argv.includes(name);
47
50
  }
48
51
 
52
+ const FORBIDDEN_KEYS = new Set(["__proto__", "constructor", "prototype"]);
53
+ const DSH_CLI_CTRL_RE = /[\x00-\x1f\x7f-\x9f\u2028\u2029]/;
54
+ const DSH_CLI_PRETRIM_CTRL_RE = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\u2028\u2029]/;
55
+
56
+ export const RESERVED_DSH_PROFILE_BASENAMES = new Set([
57
+ "profile",
58
+ "session-binds",
59
+ "session-binds_meta",
60
+ "session-binds.meta",
61
+ "session-binds-meta",
62
+ "agy-binds",
63
+ "agy-binds_meta",
64
+ "agy-binds.meta",
65
+ "agy-binds-meta",
66
+ "grok-binds",
67
+ "grok-binds_meta",
68
+ "grok-binds.meta",
69
+ "grok-binds-meta",
70
+ "agy-session-binds",
71
+ "agy-session-binds_meta",
72
+ "agy-session-binds.meta",
73
+ "agy-session-binds-meta",
74
+ "identity-guard",
75
+ "cursor",
76
+ "read-cursors",
77
+ "mention-timestamps",
78
+ "wake-pids",
79
+ "config",
80
+ "codex-bots",
81
+ "dsh",
82
+ "muse",
83
+ ]);
84
+
85
+ /** Bound actual response bytes, regardless of Content-Length. */
86
+ async function readRegistrationText(res: Response): Promise<string> {
87
+ if (!res.body) throw new Error("Empty registration response");
88
+ const reader = res.body.getReader();
89
+ const decoder = new TextDecoder("utf-8", { fatal: true });
90
+ let bytes = 0;
91
+ let text = "";
92
+ try {
93
+ for (;;) {
94
+ const { done, value } = await reader.read();
95
+ if (done) break;
96
+ bytes += value.byteLength;
97
+ if (bytes > 1024 * 1024) throw new Error("Registration response exceeds 1MiB");
98
+ text += decoder.decode(value, { stream: true });
99
+ }
100
+ return text + decoder.decode();
101
+ } catch (error) {
102
+ void reader.cancel().catch(() => {});
103
+ throw error;
104
+ } finally {
105
+ reader.releaseLock();
106
+ }
107
+ }
108
+
109
+ function isSafeAgentId(value: unknown): boolean {
110
+ return (
111
+ typeof value === "string" &&
112
+ !!value &&
113
+ value.length <= 128 &&
114
+ value !== "." &&
115
+ value !== ".." &&
116
+ !FORBIDDEN_KEYS.has(value.toLowerCase()) &&
117
+ !/[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(value)
118
+ );
119
+ }
120
+
121
+ function validateChannelId(value: string | undefined): string {
122
+ if (!value || value.startsWith("--") || !isSafeAgentId(value) ||
123
+ Object.getOwnPropertyNames(Object.prototype).some((key) => key.toLowerCase() === value.toLowerCase())) throw new Error("Invalid channel id: --send requires a channel id and --channel requires a value");
124
+ return value;
125
+ }
126
+
127
+ function logText(value: string): string {
128
+ return redact(value.replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, ""));
129
+ }
130
+
131
+ function promptHeader(value: string): string {
132
+ return value.replace(/[\r\n\x00-\x1f\x7f-\x9f\u2028\u2029]/g, "");
133
+ }
134
+
135
+ function isLoopbackHost(hostname: string): boolean {
136
+ const h = hostname.toLowerCase().replace(/\.$/, "");
137
+ return h === "localhost" || h === "127.0.0.1" || h === "[::1]" || h === "::1";
138
+ }
139
+
140
+ function validateHttpOrWsUrl(raw: string, allowedProtocols: string[], label: string): string {
141
+ if (typeof raw !== "string" || DSH_CLI_PRETRIM_CTRL_RE.test(raw)) {
142
+ throw new Error(`Invalid ${label} URL`);
143
+ }
144
+ const trimmed = raw.trim();
145
+ if (!trimmed || raw !== trimmed || /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(raw)) {
146
+ throw new Error(`Invalid ${label} URL`);
147
+ }
148
+ let parsed: URL;
149
+ try {
150
+ parsed = new URL(trimmed);
151
+ } catch {
152
+ throw new Error(`Invalid ${label} URL`);
153
+ }
154
+ if (
155
+ isBlockedDshHost(parsed.hostname) ||
156
+ parsed.username ||
157
+ parsed.password ||
158
+ parsed.port === "0" ||
159
+ parsed.search ||
160
+ parsed.hash
161
+ ) {
162
+ throw new Error(`Invalid ${label} URL`);
163
+ }
164
+ if (!allowedProtocols.includes(parsed.protocol)) {
165
+ throw new Error(`Unsupported ${label} protocol: ${parsed.protocol}`);
166
+ }
167
+ if ((parsed.protocol === "ws:" || parsed.protocol === "http:") && !isLoopbackHost(parsed.hostname)) {
168
+ throw new Error(`Remote ${label} URL must use TLS (${parsed.protocol === "ws:" ? "wss://" : "https://"})`);
169
+ }
170
+ return trimmed;
171
+ }
172
+
49
173
  export function loadDshConfig(
50
174
  env: NodeJS.ProcessEnv = process.env,
51
175
  profilePath: string = DSH_PROFILE_PATH,
52
176
  ): DshBridgeConfig {
53
- let profile: Record<string, string | undefined> = {};
177
+ let profile: Record<string, unknown> = {};
54
178
  try {
55
- if (existsSync(profilePath)) {
56
- profile = JSON.parse(readFileSync(profilePath, "utf8")) as Record<string, string | undefined>;
179
+ checkParentDirectory(profilePath);
180
+ const lst = lstatSync(profilePath);
181
+ if (!lst.isSymbolicLink() && lst.isFile() && lst.size <= 256 * 1024) {
182
+ const parsed = JSON.parse(readFileSync(profilePath, "utf8"));
183
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) && !Object.prototype.hasOwnProperty.call(parsed, "__proto__")) {
184
+ profile = parsed as Record<string, unknown>;
185
+ }
57
186
  }
58
187
  } catch {
59
188
  profile = {};
60
189
  }
61
- const agentId = env.AGENTCHAT_AGENT_ID ?? profile.agentId;
62
- const token = env.AGENTCHAT_TOKEN ?? profile.token;
63
- if (!agentId || !token) {
190
+ const rawAgentId = env.AGENTCHAT_AGENT_ID ?? (typeof profile.agentId === "string" ? profile.agentId : undefined);
191
+ const rawToken = env.AGENTCHAT_TOKEN ?? (typeof profile.token === "string" ? profile.token : undefined);
192
+ const agentId = typeof rawAgentId === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawAgentId) ? rawAgentId.trim() : "";
193
+ const token = typeof rawToken === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawToken) ? rawToken.trim() : "";
194
+ if (!isSafeAgentId(agentId) || !token || DSH_CLI_CTRL_RE.test(agentId) || DSH_CLI_CTRL_RE.test(token)) {
64
195
  throw new Error(
65
196
  "Missing AgentsChat identity for DSH: set AGENTCHAT_AGENT_ID and AGENTCHAT_TOKEN, " +
66
197
  `or create ${profilePath} via 'agentschat-mcp --dsh --register-only --name <name>'.`,
67
198
  );
68
199
  }
200
+ const wsUrl = validateHttpOrWsUrl(
201
+ env.AGENTCHAT_WS_URL ?? (typeof profile.wsUrl === "string" ? profile.wsUrl : DEFAULT_WS_URL),
202
+ ["ws:", "wss:"],
203
+ "AgentChat WebSocket",
204
+ );
205
+ const restUrl = validateHttpOrWsUrl(
206
+ env.AGENTCHAT_REST_URL ?? (typeof profile.restUrl === "string" ? profile.restUrl : DEFAULT_REST_URL),
207
+ ["http:", "https:"],
208
+ "AgentChat REST",
209
+ );
210
+ const rawDisplay = env.AGENTCHAT_DISPLAY_NAME ?? (typeof profile.displayName === "string" ? profile.displayName : undefined);
211
+ const rawChan = env.AGENTCHAT_CHANNEL_ID ?? (typeof profile.defaultChannelId === "string" ? profile.defaultChannelId : undefined);
212
+ const cleanDisplay = typeof rawDisplay === "string" ? rawDisplay.replace(DSH_CLI_CTRL_RE, "").trim() : "";
69
213
  return {
70
214
  agentId,
71
215
  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,
216
+ wsUrl,
217
+ restUrl,
218
+ displayName: cleanDisplay || undefined,
219
+ defaultChannelId: rawChan?.trim() || undefined,
76
220
  };
77
221
  }
78
222
 
@@ -87,21 +231,88 @@ export function safeDshConfig(config: DshBridgeConfig): Record<string, unknown>
87
231
  };
88
232
  }
89
233
 
90
- async function registerOnly(name: string, restUrl: string, profilePath = DSH_PROFILE_PATH): Promise<void> {
234
+ export async function registerOnly(name: string, restUrl: string, profilePath = DSH_PROFILE_PATH): Promise<void> {
235
+ if (typeof name !== "string" || DSH_CLI_PRETRIM_CTRL_RE.test(name)) {
236
+ throw new Error("Invalid --name value");
237
+ }
238
+ const cleanName = name.trim();
239
+ if (!cleanName || cleanName.length > 64 || DSH_CLI_CTRL_RE.test(cleanName)) {
240
+ throw new Error("Invalid --name value");
241
+ }
242
+ checkParentDirectory(profilePath);
243
+ const safeRestUrl = validateHttpOrWsUrl(restUrl, ["http:", "https:"], "AgentChat REST");
91
244
  console.log("Terms notice: https://agents-chat.com/terms (notice only, no acceptance prompt)");
92
- const res = await fetch(`${restUrl.replace(/\/$/, "")}/api/account/register`, {
245
+ const res = await fetch(`${safeRestUrl.replace(/\/+$/, "")}/api/account/register`, {
93
246
  method: "POST",
94
247
  headers: { "content-type": "application/json" },
95
- body: JSON.stringify({ name, type: "agent", capabilities: ["chat"] }),
248
+ body: JSON.stringify({ name: cleanName, type: "agent", capabilities: ["chat"] }),
249
+ redirect: "error",
250
+ signal: AbortSignal.timeout(15_000),
96
251
  });
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).`);
252
+ if (!res.ok) {
253
+ const errText = redact((await readRegistrationText(res)).slice(0, 300));
254
+ throw new Error(`Registration failed: ${res.status} ${errText}`);
255
+ }
256
+ const data = JSON.parse(await readRegistrationText(res)) as Record<string, unknown>;
257
+ if (data === null || typeof data !== "object" || Array.isArray(data) ||
258
+ Object.getPrototypeOf(data) !== Object.prototype || Object.prototype.hasOwnProperty.call(data, "__proto__")) {
259
+ throw new Error("Invalid registration response object");
260
+ }
261
+ const rawAgentId = (data.agentId ?? data.agent_id ?? data.id) as string | undefined;
262
+ const rawToken = (data.agentKey ?? data.token ?? data.key) as string | undefined;
263
+ const agentId = typeof rawAgentId === "string" && !DSH_CLI_CTRL_RE.test(rawAgentId) ? rawAgentId.trim() : "";
264
+ const token = typeof rawToken === "string" && !DSH_CLI_CTRL_RE.test(rawToken) ? rawToken.trim() : "";
265
+ if (!isSafeAgentId(rawAgentId) || !token || DSH_CLI_CTRL_RE.test(agentId) || DSH_CLI_CTRL_RE.test(token)) {
266
+ throw new Error("Registration response did not include a valid agent id/token");
267
+ }
268
+ try {
269
+ const lst = lstatSync(profilePath);
270
+ if (lst.isSymbolicLink() || !lst.isFile()) {
271
+ throw new Error(`Refusing to overwrite non-regular file ${profilePath}`);
272
+ }
273
+ } catch (err: any) {
274
+ if (err?.code !== "ENOENT") throw err;
275
+ }
276
+ checkParentDirectory(profilePath);
277
+ mkdirSync(dirname(profilePath), { recursive: true, mode: 0o700 });
278
+ checkParentDirectory(profilePath);
279
+ const tmp = `${profilePath}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
280
+ let created = false;
281
+ try {
282
+ writeFileSync(tmp, JSON.stringify({ agentId, token }, null, 2), { mode: 0o600, flag: "wx" });
283
+ created = true;
284
+ checkParentDirectory(profilePath);
285
+ try {
286
+ const lst = lstatSync(profilePath);
287
+ if (lst.isSymbolicLink() || !lst.isFile()) throw new Error(`Refusing to overwrite non-regular file ${profilePath}`);
288
+ } catch (err: any) {
289
+ if (err?.code !== "ENOENT") throw err;
290
+ }
291
+ try {
292
+ renameSync(tmp, profilePath);
293
+ } catch (renameErr: any) {
294
+ if (renameErr?.code !== "EPERM" && renameErr?.code !== "EACCES") {
295
+ throw renameErr;
296
+ }
297
+ checkParentDirectory(profilePath);
298
+ try {
299
+ const lst = lstatSync(profilePath);
300
+ if (lst.isSymbolicLink() || !lst.isFile()) throw new Error(`Refusing to overwrite non-regular file ${profilePath}`);
301
+ } catch (err: any) {
302
+ if (err?.code !== "ENOENT") throw err;
303
+ }
304
+ copyFileSync(tmp, profilePath);
305
+ try { unlinkSync(tmp); } catch {}
306
+ created = false;
307
+ }
308
+ if (process.platform !== "win32") {
309
+ try { chmodSync(profilePath, 0o600); } catch {}
310
+ }
311
+ } catch (err) {
312
+ if (created) { try { unlinkSync(tmp); } catch {} }
313
+ throw err;
314
+ }
315
+ console.log(`Registered DSH agent '${cleanName}' as ${agentId}. Identity saved to ${profilePath} (token not printed).`);
105
316
  }
106
317
 
107
318
  /**
@@ -112,40 +323,79 @@ export async function runDshHeadlessResponder(
112
323
  prompt: string,
113
324
  opts: { dshBin?: string; dshProfile?: string; timeoutMs?: number } = {},
114
325
  ): 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;
326
+ const rawBin = opts.dshBin ?? process.env.DSH_BIN ?? "dsh";
327
+ const rawProfile = opts.dshProfile ?? process.env.DSH_PROFILE ?? "headless";
328
+ const dshBin = typeof rawBin === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawBin) ? rawBin.trim() : "";
329
+ const dshProfile = typeof rawProfile === "string" && !DSH_CLI_PRETRIM_CTRL_RE.test(rawProfile) ? rawProfile.trim() : "";
330
+ if (!dshBin || DSH_CLI_CTRL_RE.test(dshBin)) {
331
+ console.error("[dsh] invalid dshBin");
332
+ return null;
333
+ }
334
+ if (!dshProfile || dshProfile.startsWith("-") || DSH_CLI_CTRL_RE.test(dshProfile)) {
335
+ console.error("[dsh] invalid dshProfile");
336
+ return null;
337
+ }
338
+ const t = opts.timeoutMs ?? 120_000;
339
+ const timeoutMs = Number.isFinite(t) && t > 0 ? Math.min(Math.floor(t), 2_147_483_647) : 120_000;
118
340
 
119
341
  return new Promise((resolve) => {
120
- const child = spawn(dshBin, ["--profile", dshProfile, prompt], {
342
+ const resolved = resolveWindowsCliSpawn(dshBin, ["--profile", dshProfile, prompt], { env: process.env });
343
+ const child = spawn(resolved.cmd, resolved.args, {
121
344
  stdio: ["ignore", "pipe", "pipe"],
122
345
  env: process.env,
346
+ windowsHide: true,
123
347
  });
124
348
  let stdout = "";
125
349
  let stderr = "";
350
+ let killTimer: ReturnType<typeof setTimeout> | undefined;
351
+ const clearTimers = () => {
352
+ clearTimeout(timer);
353
+ if (killTimer) {
354
+ clearTimeout(killTimer);
355
+ killTimer = undefined;
356
+ }
357
+ };
126
358
  const timer = setTimeout(() => {
127
359
  try {
128
360
  child.kill("SIGTERM");
129
361
  } catch {
130
362
  /* ignore */
131
363
  }
364
+ killTimer = setTimeout(() => {
365
+ killTimer = undefined;
366
+ if (child.exitCode === null) {
367
+ try {
368
+ child.kill("SIGKILL");
369
+ } catch {
370
+ /* ignore */
371
+ }
372
+ }
373
+ }, 3_000);
374
+ killTimer.unref?.();
132
375
  }, timeoutMs);
376
+ timer.unref?.();
133
377
 
134
378
  child.stdout.on("data", (chunk: Buffer) => {
135
- stdout += chunk.toString("utf8");
379
+ if (stdout.length < 2_000_000) {
380
+ const text = chunk.toString("utf8");
381
+ stdout += text.slice(0, 2_000_000 - stdout.length);
382
+ }
136
383
  });
137
384
  child.stderr.on("data", (chunk: Buffer) => {
138
- stderr += chunk.toString("utf8");
385
+ if (stderr.length < 65_536) {
386
+ const text = chunk.toString("utf8");
387
+ stderr += text.slice(0, 65_536 - stderr.length);
388
+ }
139
389
  });
140
390
  child.on("error", (err) => {
141
- clearTimeout(timer);
142
- console.error(`[dsh] failed to spawn ${dshBin}: ${err.message}`);
391
+ clearTimers();
392
+ console.error(`[dsh] failed to spawn ${dshBin}: ${redact(err.message)}`);
143
393
  resolve(null);
144
394
  });
145
395
  child.on("close", (code) => {
146
- clearTimeout(timer);
396
+ clearTimers();
147
397
  if (code !== 0) {
148
- console.error(`[dsh] exited with code ${code}: ${stderr.trim().slice(0, 300)}`);
398
+ console.error(`[dsh] exited with code ${code}: ${redact(stderr.trim().slice(0, 300))}`);
149
399
  resolve(null);
150
400
  return;
151
401
  }
@@ -174,6 +424,10 @@ DeepSeek Harness (dsh) integration for AgentsChat:
174
424
  return;
175
425
  }
176
426
 
427
+ for (let i = 0; i < argv.length; i++) {
428
+ if (argv[i] === "--channel" || argv[i] === "--send") validateChannelId(argv[i + 1]);
429
+ }
430
+
177
431
  if (has("--setup", argv)) {
178
432
  const dshHome = arg("--dsh-home", argv);
179
433
  const dshProfile = arg("--dsh-profile", argv);
@@ -209,13 +463,17 @@ DeepSeek Harness (dsh) integration for AgentsChat:
209
463
  } catch {
210
464
  console.log("[dsh-wake] No global dsh.json identity; watching session-binds.json for bound DSH sessions.");
211
465
  }
212
- const defaultWsUrl = primaryConfig?.wsUrl ?? process.env.AGENTCHAT_WS_URL ?? DEFAULT_WS_URL;
466
+ const defaultWsUrl = validateHttpOrWsUrl(
467
+ primaryConfig?.wsUrl ?? process.env.AGENTCHAT_WS_URL ?? DEFAULT_WS_URL,
468
+ ["ws:", "wss:"], "AgentChat WebSocket",
469
+ );
213
470
 
214
- const wakeChannels: string[] = [];
471
+ const rawWakeChannels: string[] = [];
215
472
  for (let i = 0; i < argv.length; i++) {
216
- if (argv[i] === "--channel" && argv[i + 1]) wakeChannels.push(argv[i + 1]);
473
+ if (argv[i] === "--channel" && argv[i + 1]) rawWakeChannels.push(argv[i + 1]);
217
474
  }
218
- if (primaryConfig?.defaultChannelId) wakeChannels.push(primaryConfig.defaultChannelId);
475
+ if (primaryConfig?.defaultChannelId) rawWakeChannels.push(validateChannelId(primaryConfig.defaultChannelId));
476
+ const wakeChannels = [...new Set(rawWakeChannels)];
219
477
  const queueFile =
220
478
  process.env.DSH_WAKE_QUEUE ?? join(homedir(), ".agentschat", "dsh-wake-queue.jsonl");
221
479
  const wakeUrl = process.env.DSH_WAKE_URL ?? process.env.AGENTCHAT_WAKE_URL;
@@ -237,7 +495,7 @@ DeepSeek Harness (dsh) integration for AgentsChat:
237
495
  typing.stop(m.channel_id);
238
496
  return;
239
497
  }
240
- const kind = m.channel_id.startsWith("dm-") ? "direct" : "group";
498
+ const kind = /^dm[-:]/i.test(m.channel_id) ? "direct" : "group";
241
499
  if (!shouldDispatch(m, { agentId: botIdentity.agentId, displayName: botIdentity.displayName, channelKind: kind })) return;
242
500
  typing.start(m.channel_id);
243
501
  const route = resolveSessionForAgent(botIdentity.agentId);
@@ -248,7 +506,7 @@ DeepSeek Harness (dsh) integration for AgentsChat:
248
506
  { url: wakeUrl, secret: wakeSecret, logger: console.error, targetSessionId: route?.sessionId },
249
507
  );
250
508
  console.log(
251
- `[dsh-wake] ${m.channel_id} ${m.sender_id} ${m.id} agent=${botIdentity.agentId} queued=${queued} target=${route?.sessionId ?? "unbound"}`,
509
+ `[dsh-wake] ${logText(`${m.channel_id} ${m.sender_id} ${m.id} agent=${botIdentity.agentId} queued=${queued} target=${route?.sessionId ?? "unbound"}`)}`,
252
510
  );
253
511
  });
254
512
  botClient.onReconnect = () => {
@@ -274,59 +532,125 @@ DeepSeek Harness (dsh) integration for AgentsChat:
274
532
  }
275
533
 
276
534
  // Multiplex any DSH sessions (`session-*`) bound in `session-binds.json`
535
+ let syncInFlight = false;
277
536
  const syncBoundDshClients = async () => {
537
+ if (syncInFlight) return;
538
+ syncInFlight = true;
278
539
  try {
279
540
  const cfgDir = agentschatConfigDir();
280
541
  const binds = loadSessionBinds(cfgDir);
281
542
  for (const [sid, profName] of Object.entries(binds)) {
282
- if (!sid.startsWith("session-") || !profName) continue;
283
- const base = profName.replace(/\.json$/, "").replace(/[^a-zA-Z0-9_-]/g, "_");
284
- const candidates = [join(cfgDir, "profiles", `${base}.json`), join(cfgDir, `${base}.json`)];
285
- const profPath = candidates.find((p) => existsSync(p));
286
- if (!profPath) continue;
287
- const raw = JSON.parse(readFileSync(profPath, "utf8")) as Record<string, any>;
288
- const botAgentId = typeof raw.agent_id === "string" ? raw.agent_id : typeof raw.agentId === "string" ? raw.agentId : "";
289
- const botToken = typeof raw.token === "string" ? raw.token : "";
290
- const botWsUrl = typeof raw.server === "string" && /^wss?:\/\//i.test(raw.server) ? raw.server : defaultWsUrl;
291
- if (!botAgentId || !botToken || botToken === "dev-token" || connectedAgentIds.has(botAgentId)) continue;
292
- connectedAgentIds.add(botAgentId);
293
- const extraClient = new MuseAgentChatClient({
294
- url: botWsUrl,
295
- agentId: botAgentId,
296
- token: botToken,
297
- capabilities: ["chat"],
298
- });
299
- attachWakeForClient(extraClient, {
300
- agentId: botAgentId,
301
- displayName: typeof raw.display_name === "string" ? raw.display_name : undefined,
302
- });
303
- await extraClient.connect();
304
- for (const c of wakeChannels) extraClient.joinChannel(c);
305
- console.log(`[dsh-wake] Connected bound session ${sid} -> ${profName} (${botAgentId})`);
543
+ if (
544
+ !sid.startsWith("session-") ||
545
+ sid.length > 128 ||
546
+ sid.includes("..") ||
547
+ /[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(sid) ||
548
+ FORBIDDEN_KEYS.has(sid.toLowerCase()) ||
549
+ !profName ||
550
+ typeof profName !== "string"
551
+ ) {
552
+ continue;
553
+ }
554
+ const base = profName.replace(/\.json$/i, "").replace(/[^a-zA-Z0-9_-]/g, "_");
555
+ if (!base || base.length > 64 || FORBIDDEN_KEYS.has(base.toLowerCase()) || RESERVED_DSH_PROFILE_BASENAMES.has(base.toLowerCase())) {
556
+ continue;
557
+ }
558
+ let extraClient: MuseAgentChatClient | null = null;
559
+ try {
560
+ const candidates = [join(cfgDir, "profiles", `${base}.json`), join(cfgDir, `${base}.json`)];
561
+ const profPath = candidates.find((p) => {
562
+ try {
563
+ checkParentDirectory(p);
564
+ const lst = lstatSync(p);
565
+ return !lst.isSymbolicLink() && lst.isFile() && lst.size <= 256 * 1024;
566
+ } catch {
567
+ return false;
568
+ }
569
+ });
570
+ if (!profPath) continue;
571
+ const raw = JSON.parse(readFileSync(profPath, "utf8")) as Record<string, any>;
572
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw) || Object.prototype.hasOwnProperty.call(raw, "__proto__")) continue;
573
+ const rawAgentId = typeof raw.agent_id === "string" ? raw.agent_id : typeof raw.agentId === "string" ? raw.agentId : "";
574
+ const rawToken = typeof raw.token === "string" ? raw.token : "";
575
+ const botAgentId = rawAgentId.trim();
576
+ const botToken = rawToken.trim();
577
+ let botWsUrl = defaultWsUrl;
578
+ if (typeof raw.server === "string" && raw.server.trim()) {
579
+ try {
580
+ botWsUrl = validateHttpOrWsUrl(raw.server.trim(), ["ws:", "wss:"], "AgentChat WebSocket");
581
+ } catch {
582
+ botWsUrl = defaultWsUrl;
583
+ }
584
+ }
585
+ if (
586
+ !isSafeAgentId(rawAgentId) ||
587
+ !botToken ||
588
+ botToken === "dev-token" ||
589
+ DSH_CLI_CTRL_RE.test(rawAgentId) ||
590
+ DSH_CLI_CTRL_RE.test(rawToken) ||
591
+ connectedAgentIds.has(botAgentId)
592
+ ) {
593
+ continue;
594
+ }
595
+ extraClient = new MuseAgentChatClient({
596
+ url: botWsUrl,
597
+ agentId: botAgentId,
598
+ token: botToken,
599
+ capabilities: ["chat"],
600
+ });
601
+ await extraClient.connect();
602
+ connectedAgentIds.add(botAgentId);
603
+ attachWakeForClient(extraClient, {
604
+ agentId: botAgentId,
605
+ displayName: typeof raw.display_name === "string" ? raw.display_name : undefined,
606
+ });
607
+ for (const c of wakeChannels) extraClient.joinChannel(c);
608
+ console.log(`[dsh-wake] ${logText(`Connected bound session ${sid} -> ${profName} (${botAgentId})`)}`);
609
+ } catch (err) {
610
+ try {
611
+ extraClient?.disconnect();
612
+ } catch {}
613
+ const msg = err instanceof Error ? err.message : String(err);
614
+ console.error(`[dsh-wake] ${logText(`Failed to connect bound session ${sid} (${profName}): ${msg}`)}`);
615
+ }
306
616
  }
307
- } catch {}
617
+ } catch {} finally {
618
+ syncInFlight = false;
619
+ }
308
620
  };
309
621
  await syncBoundDshClients();
310
622
  const bindTimer = setInterval(() => void syncBoundDshClients(), 3_000);
623
+ bindTimer.unref?.();
311
624
 
312
625
  console.log(`DSH wake daemon listening on ${wakeChannels.join(", ") || "(no channels — pass --channel <id>)"}, queue=${queueFile}.`);
313
- await new Promise<void>((resolve) => {
314
- const shutdown = () => {
315
- for (const t of activeTyping) t.stopAll();
316
- for (const c of activeClients) {
317
- try {
318
- c.disconnect();
319
- } catch {}
626
+ let shutdownWakeRef: (() => void) | undefined;
627
+ try {
628
+ await new Promise<void>((resolve) => {
629
+ const shutdown = () => {
630
+ for (const t of activeTyping) t.stopAll();
631
+ for (const c of activeClients) {
632
+ try {
633
+ c.disconnect();
634
+ } catch {}
635
+ }
636
+ resolve();
637
+ };
638
+ shutdownWakeRef = shutdown;
639
+ process.once("SIGINT", shutdown);
640
+ process.once("SIGTERM", shutdown);
641
+ if (process.platform !== "win32") process.once("SIGHUP", shutdown);
642
+ if (primaryClient) {
643
+ void primaryClient.waitUntilClosed().then(resolve);
320
644
  }
321
- resolve();
322
- };
323
- process.once("SIGINT", shutdown);
324
- process.once("SIGTERM", shutdown);
325
- if (primaryClient) {
326
- void primaryClient.waitUntilClosed().then(resolve);
645
+ });
646
+ } finally {
647
+ clearInterval(bindTimer);
648
+ if (shutdownWakeRef) {
649
+ process.removeListener("SIGINT", shutdownWakeRef);
650
+ process.removeListener("SIGTERM", shutdownWakeRef);
651
+ if (process.platform !== "win32") process.removeListener("SIGHUP", shutdownWakeRef);
327
652
  }
328
- });
329
- clearInterval(bindTimer);
653
+ }
330
654
  return;
331
655
  }
332
656
 
@@ -353,16 +677,17 @@ DeepSeek Harness (dsh) integration for AgentsChat:
353
677
  }
354
678
 
355
679
  if (has("--listen", argv)) {
356
- const channels: string[] = [];
680
+ const rawChannels: string[] = [];
357
681
  for (let i = 0; i < argv.length; i++) {
358
- if (argv[i] === "--channel" && argv[i + 1]) channels.push(argv[i + 1]);
682
+ if (argv[i] === "--channel" && argv[i + 1]) rawChannels.push(argv[i + 1]);
359
683
  }
360
- if (config.defaultChannelId) channels.push(config.defaultChannelId);
684
+ if (config.defaultChannelId) rawChannels.push(validateChannelId(config.defaultChannelId));
685
+ const channels = [...new Set(rawChannels)];
361
686
  const autoReply = arg("--auto-reply", argv);
362
687
  const dshProfile = arg("--dsh-profile", argv) ?? "headless";
363
688
  const channelKinds: Record<string, "direct" | "group"> = {};
364
689
  for (const c of channels) {
365
- channelKinds[c] = c.startsWith("dm-") ? "direct" : "group";
690
+ channelKinds[c] = /^dm[-:]/i.test(c) ? "direct" : "group";
366
691
  }
367
692
  const bridge = new MuseBridge(client, {
368
693
  agentId: config.agentId,
@@ -370,21 +695,35 @@ DeepSeek Harness (dsh) integration for AgentsChat:
370
695
  channels,
371
696
  channelKinds,
372
697
  responder: async (ctx) => {
373
- console.log(`[inbound] ${ctx.message.channel_id} ${ctx.message.sender_id}: ${ctx.message.content}`);
698
+ console.log(`[inbound] ${logText(`${ctx.message.channel_id} ${ctx.message.sender_id}: ${ctx.message.content}`)}`);
374
699
  if (autoReply) return autoReply;
375
700
  const prompt = [
376
701
  `You are DeepSeek Harness agent ${config.agentId} on AgentsChat.`,
377
- `Reply concisely to the latest message in channel ${ctx.message.channel_id}.`,
702
+ `Reply concisely to the latest message in channel ${promptHeader(ctx.message.channel_id)}.`,
378
703
  `Recent conversation context:\n${ctx.context}`,
379
- `Latest message from ${ctx.message.sender_id}: ${ctx.message.content}`,
704
+ `Latest message from ${promptHeader(ctx.message.sender_id)}: ${ctx.message.content}`,
380
705
  ].join("\n\n");
381
706
  return runDshHeadlessResponder(prompt, { dshProfile });
382
707
  },
383
708
  });
384
709
  client.onReconnect = () => bridge.rejoin();
385
- await bridge.start();
386
- console.log(`DSH bridge listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"} (profile=${dshProfile}).`);
387
- await client.waitUntilClosed();
710
+ const shutdownListen = () => {
711
+ try {
712
+ client.disconnect();
713
+ } catch {}
714
+ };
715
+ process.once("SIGINT", shutdownListen);
716
+ process.once("SIGTERM", shutdownListen);
717
+ if (process.platform !== "win32") process.once("SIGHUP", shutdownListen);
718
+ try {
719
+ await bridge.start();
720
+ console.log(`DSH bridge listening on ${channels.join(", ") || "(no channels — pass --channel <id>)"} (profile=${dshProfile}).`);
721
+ await client.waitUntilClosed();
722
+ } finally {
723
+ process.removeListener("SIGINT", shutdownListen);
724
+ process.removeListener("SIGTERM", shutdownListen);
725
+ if (process.platform !== "win32") process.removeListener("SIGHUP", shutdownListen);
726
+ }
388
727
  return;
389
728
  }
390
729
 
@@ -398,7 +737,7 @@ const invokedDirectly =
398
737
 
399
738
  if (invokedDirectly) {
400
739
  main().catch((err: unknown) => {
401
- console.error("DSH AgentsChat error:", err instanceof Error ? err.message : String(err));
740
+ console.error("DSH AgentsChat error:", logText(err instanceof Error ? err.message : String(err)));
402
741
  process.exit(1);
403
742
  });
404
743
  }