agentschat-mcp 0.36.25 → 0.36.27

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 (86) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +10 -10
  3. package/codex/README.md +4 -4
  4. package/codex/app-server.ts +101 -22
  5. package/codex/bots-config.ts +32 -11
  6. package/codex/bridge.ts +127 -28
  7. package/codex/config.ts +137 -21
  8. package/codex/gui-channel.ts +66 -9
  9. package/codex/inbox-sync.ts +77 -12
  10. package/codex/loop-grants.ts +49 -11
  11. package/codex/manager.ts +108 -27
  12. package/codex/owner.ts +106 -9
  13. package/codex/processes.ts +51 -7
  14. package/codex/run.ts +70 -17
  15. package/codex/runtime-home.ts +51 -11
  16. package/codex/thread-history.ts +87 -30
  17. package/codex/transport.ts +135 -22
  18. package/connector/README.md +1 -1
  19. package/connector/auth.ts +57 -5
  20. package/connector/backfill.ts +92 -10
  21. package/connector/descriptor.ts +27 -1
  22. package/connector/identities.ts +82 -14
  23. package/connector/ingest.ts +11 -2
  24. package/connector/normalize.ts +32 -12
  25. package/connector/run.ts +314 -67
  26. package/connector/server.ts +95 -26
  27. package/cordis.patch.yml +4 -2
  28. package/dist/codex-bots.js +437 -75
  29. package/dist/codex-bridge.js +2111 -582
  30. package/dist/connector.js +1300 -493
  31. package/dist/dsh.js +1789 -299
  32. package/dist/muse.js +967 -221
  33. package/dist/server.js +4410 -919
  34. package/dsh/README.md +1 -1
  35. package/dsh/client.js +7 -5
  36. package/dsh/identity-ui/client.js +7 -5
  37. package/dsh/identity-ui/index.js +43 -8
  38. package/dsh/inbound-bridge/index.js +677 -154
  39. package/dsh/src/cli.ts +430 -91
  40. package/dsh/src/patch.ts +295 -15
  41. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  42. package/dsh/tests/dsh.test.ts +1174 -3
  43. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  44. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  45. package/muse/src/bridge.ts +54 -13
  46. package/muse/src/cli.ts +226 -41
  47. package/muse/src/client.ts +249 -34
  48. package/muse/src/config.ts +128 -12
  49. package/muse/src/policy.ts +28 -8
  50. package/muse/src/types.ts +1 -0
  51. package/muse/src/typing.ts +18 -1
  52. package/muse/src/wake.ts +237 -35
  53. package/muse/tests/bridge.test.mjs +131 -0
  54. package/muse/tests/client.test.mjs +327 -0
  55. package/muse/tests/config.test.mjs +78 -1
  56. package/muse/tests/hardening.test.mjs +199 -0
  57. package/muse/tests/hardening126.test.mjs +292 -0
  58. package/muse/tests/policy.test.mjs +83 -1
  59. package/muse/tests/wake.test.mjs +134 -6
  60. package/package.json +3 -3
  61. package/scripts/ensure-grok-wakes.mjs +93 -8
  62. package/scripts/example-url-wake-receiver.mjs +254 -61
  63. package/scripts/grok-bind-register.sh +38 -8
  64. package/skills/onboarding.md +15 -15
  65. package/src/argcheck.ts +113 -33
  66. package/src/cli.mjs +100 -16
  67. package/src/dedup.ts +57 -8
  68. package/src/grok-bind.ts +182 -33
  69. package/src/heartbeat.ts +39 -11
  70. package/src/identity-guard.ts +93 -20
  71. package/src/identity.ts +67 -11
  72. package/src/mentions.ts +26 -5
  73. package/src/onboarding-status.ts +134 -11
  74. package/src/profile-selection.ts +299 -18
  75. package/src/profile-store.ts +248 -30
  76. package/src/read-cursor.ts +280 -9
  77. package/src/reconnect.ts +98 -2
  78. package/src/redact.ts +34 -15
  79. package/src/rest-cli.ts +713 -159
  80. package/src/server.ts +286 -94
  81. package/src/session-bind.ts +777 -134
  82. package/src/session-route.ts +183 -12
  83. package/src/team-lead-skill.ts +3 -0
  84. package/src/timestamps.ts +56 -23
  85. package/src/tool-annotations.ts +10 -1
  86. package/src/wake.ts +510 -91
@@ -44,16 +44,24 @@
44
44
 
45
45
  import {
46
46
  appendFileSync,
47
+ closeSync,
48
+ constants,
49
+ copyFileSync,
50
+ fstatSync,
51
+ openSync,
47
52
  chmodSync,
48
53
  existsSync,
54
+ lstatSync,
49
55
  mkdirSync,
50
56
  readFileSync,
51
57
  readdirSync,
58
+ realpathSync,
52
59
  renameSync,
53
60
  statSync,
61
+ unlinkSync,
54
62
  writeFileSync,
55
63
  } from 'node:fs';
56
- import { dirname, join } from 'node:path';
64
+ import { dirname, isAbsolute, join, parse, resolve, sep } from 'node:path';
57
65
  import { homedir } from 'node:os';
58
66
  import { fileURLToPath } from 'node:url';
59
67
  import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
@@ -76,7 +84,132 @@ const MAX_SEEN_IDS = 200;
76
84
  * message_id, which bypass dedupe entirely — must not grow the queue forever.
77
85
  */
78
86
  const MAX_PENDING = 100;
87
+ export const MAX_HTTP_BODY_BYTES = 64 * 1024;
79
88
  const WAKE_PATH = '/agentschat/wake';
89
+ const FORBIDDEN_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
90
+ const LOCAL_HTTP_ORIGIN_RE = /^https?:\/\/(?:127\.0\.0\.1|localhost|(?:tauri|dsh|dsh-app)\.localhost|\[::1\])(?::(\d{1,5}))?$/i;
91
+ const LOCAL_SCHEME_ORIGIN_RE = /^(?:app|tauri|dsh|dsh-app):\/\/[a-z0-9._-]+(?::(\d{1,5}))?$/i;
92
+ let inboundTmpSeq = 0;
93
+
94
+ /**
95
+ * Only local DSH UI origins (loopback HTTP/HTTPS or desktop webview schemes)
96
+ * may call this loopback bridge from a browser. External websites and
97
+ * sandboxed `Origin: null` frames are rejected to prevent drive-by CSRF.
98
+ */
99
+ export function isAllowedLocalOrigin(origin) {
100
+ if (typeof origin !== 'string' || origin.length === 0 || origin.length > 128) return false;
101
+ if (origin === 'file://') return true;
102
+ const httpMatch = LOCAL_HTTP_ORIGIN_RE.exec(origin);
103
+ if (httpMatch) {
104
+ if (httpMatch[1] !== undefined) {
105
+ const p = Number(httpMatch[1]);
106
+ if (!Number.isInteger(p) || p < 1 || p > 65535) return false;
107
+ }
108
+ return true;
109
+ }
110
+ const schemeMatch = LOCAL_SCHEME_ORIGIN_RE.exec(origin);
111
+ if (schemeMatch) {
112
+ if (schemeMatch[1] !== undefined) {
113
+ const p = Number(schemeMatch[1]);
114
+ if (!Number.isInteger(p) || p < 1 || p > 65535) return false;
115
+ }
116
+ return true;
117
+ }
118
+ return false;
119
+ }
120
+
121
+ const RESERVED_PROFILE_SIDECARS = new Set([
122
+ 'profile',
123
+ 'session-binds',
124
+ 'session-binds.meta',
125
+ 'session-binds_meta',
126
+ 'session-binds-meta',
127
+ 'agy-binds',
128
+ 'agy-binds.meta',
129
+ 'agy-binds_meta',
130
+ 'agy-binds-meta',
131
+ 'agy-session-binds',
132
+ 'agy-session-binds.meta',
133
+ 'agy-session-binds_meta',
134
+ 'grok-binds',
135
+ 'grok-binds.meta',
136
+ 'grok-binds_meta',
137
+ 'grok-binds-meta',
138
+ 'identity-guard',
139
+ 'cursor',
140
+ 'read-cursors',
141
+ 'mention-timestamps',
142
+ 'wake-pids',
143
+ 'config',
144
+ 'codex-bots',
145
+ 'dsh',
146
+ 'muse',
147
+ ]);
148
+
149
+ function isSafeKey(value) {
150
+ return (
151
+ typeof value === 'string' &&
152
+ value.length > 0 &&
153
+ value.length <= 128 &&
154
+ !FORBIDDEN_KEYS.has(value.toLowerCase()) &&
155
+ value !== '.' && value !== '..' && !/[\/\\]/.test(value) &&
156
+ !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value)
157
+ );
158
+ }
159
+
160
+ export function isBlockedInboundHost(rawHostname) {
161
+ if (typeof rawHostname !== 'string' || !rawHostname) return true;
162
+ let host = rawHostname.toLowerCase().replace(/\.+$/, '');
163
+ if (
164
+ ['metadata.google.internal', 'metadata.goog', 'metadata', 'instance-data'].includes(host) ||
165
+ host.endsWith('.metadata.google.internal') ||
166
+ host.endsWith('.metadata.goog')
167
+ ) {
168
+ return true;
169
+ }
170
+ const unsafeV4 = (ip) => ip.startsWith('0.') || ip === '100.100.100.200' || ip.startsWith('169.254.');
171
+ if (/^\d+\.\d+\.\d+\.\d+$/.test(host)) return unsafeV4(host);
172
+ if (!host.startsWith('[')) return false;
173
+ try {
174
+ host = new URL(`http://${host}`).hostname.toLowerCase();
175
+ } catch {
176
+ return true;
177
+ }
178
+ const address = host.slice(1, -1);
179
+ const [left, right = ''] = address.split('::');
180
+ const head = left ? left.split(':') : [];
181
+ const tail = right ? right.split(':') : [];
182
+ const words = (
183
+ address.includes('::')
184
+ ? [...head, ...Array(Math.max(0, 8 - head.length - tail.length)).fill('0'), ...tail]
185
+ : head
186
+ ).map((x) => parseInt(x, 16));
187
+ if (words.length !== 8 || words.some((x) => !Number.isInteger(x) || x < 0 || x > 0xffff)) return true;
188
+ const mapped =
189
+ (words.slice(0, 5).every((x) => x === 0) && words[5] === 0xffff) ||
190
+ (words.slice(0, 4).every((x) => x === 0) && words[4] === 0xffff && words[5] === 0);
191
+ if (mapped) return unsafeV4(`${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}.${words[7] & 255}`);
192
+ return (
193
+ words.every((x) => x === 0) ||
194
+ (words[0] & 0xffc0) === 0xfe80 ||
195
+ (words[0] === 0xfd00 && words[1] === 0xec2 && words.slice(2, 7).every((x) => x === 0) && words[7] === 0x254)
196
+ );
197
+ }
198
+
199
+ function scrubSecrets(text) {
200
+ if (typeof text !== 'string' || text.length === 0) return '';
201
+ return text
202
+ .replace(/\b(https?:\/\/)([^/\s@]*@)/gi, '$1[REDACTED]@')
203
+ .replace(/\b(?:Bearer|Basic)\s+[^\s"',;]+/gi, 'Bearer [REDACTED]')
204
+ .replace(/\bac_[A-Za-z0-9_-]{8,}/g, 'ac_[REDACTED]')
205
+ .replace(/\bagent_key_[A-Za-z0-9_-]{8,}/g, 'agent_key_[REDACTED]')
206
+ .replace(/\bsk-[A-Za-z0-9_-]{8,}/g, 'sk-[REDACTED]')
207
+ .replace(/\b(?:hf_|npm_|mr_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|AIza)[A-Za-z0-9_-]{8,}/g, '[REDACTED]')
208
+ .replace(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, '[REDACTED]')
209
+ .replace(/mcp_(?:at|rt|code)_[A-Za-z0-9_-]{8,}/g, '[REDACTED]')
210
+ .replace(/whsec_[A-Za-z0-9_-]{8,}/g, '[REDACTED]')
211
+ .replace(/eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, '[REDACTED]');
212
+ }
80
213
  /**
81
214
  * Identifies the code the *running* instance actually has in memory.
82
215
  *
@@ -86,7 +219,7 @@ const WAKE_PATH = '/agentschat/wake';
86
219
  * is no way to tell which version is live from the outside, which is how a
87
220
  * "fixed" build once delivered into a busy Session. `/health` reports it.
88
221
  */
89
- const BUILD = 'inbound/2026-10-29.21-bundled';
222
+ const BUILD = 'inbound/2026-11-16.22-rc3-compat';
90
223
  /** Producer-owned source kind; a bare `plugin` wrapper is refused by session format v4. */
91
224
  const SOURCE_KIND = 'plugin:agentschat-inbound';
92
225
  /** Poll interval while wakes wait for a root agent to finish its turn. */
@@ -109,58 +242,222 @@ function settleWithin(promise, ms) {
109
242
  ]).finally(() => clearTimeout(timer));
110
243
  }
111
244
 
112
- function log(line) {
245
+ function isDarwinCanonicalSystemLink(dirPath) {
246
+ if (process.platform !== 'darwin' || !['/var', '/tmp', '/etc'].includes(dirPath)) return false;
113
247
  try {
248
+ return (
249
+ realpathSync(dirPath) === `/private${dirPath}` &&
250
+ !lstatSync('/private').isSymbolicLink() &&
251
+ lstatSync('/private').isDirectory() &&
252
+ !lstatSync(`/private${dirPath}`).isSymbolicLink() &&
253
+ lstatSync(`/private${dirPath}`).isDirectory()
254
+ );
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+
260
+ export function checkParentDirectory(targetPath) {
261
+ if (typeof targetPath !== 'string' || !targetPath || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(targetPath)) {
262
+ throw new Error('Refusing unsafe parent directory');
263
+ }
264
+ const absRaw = isAbsolute(targetPath) ? targetPath : `${process.cwd()}${sep}${targetPath}`;
265
+ const rawParent = dirname(absRaw);
266
+ const root = parse(rawParent).root;
267
+ const rawSegments = rawParent.slice(root.length).split(/[\\/]+/).filter(Boolean);
268
+ if (rawSegments.includes('..')) {
269
+ let cur = root;
270
+ for (const seg of rawSegments) {
271
+ if (seg === '.') continue;
272
+ if (seg === '..') {
273
+ cur = dirname(cur);
274
+ continue;
275
+ }
276
+ const next = join(cur, seg);
277
+ try {
278
+ const lst = lstatSync(next);
279
+ if (lst.isSymbolicLink() && !isDarwinCanonicalSystemLink(next)) {
280
+ throw new Error('Refusing unsafe parent directory');
281
+ }
282
+ if (!lst.isSymbolicLink() && !lst.isDirectory()) {
283
+ throw new Error('Refusing unsafe parent directory');
284
+ }
285
+ } catch (error) {
286
+ if (error?.code !== 'ENOENT') throw error;
287
+ }
288
+ cur = next;
289
+ }
290
+ }
291
+ let parent = dirname(resolve(targetPath));
292
+ for (;;) {
114
293
  try {
115
- if (statSync(LOG_PATH).size > LOG_MAX_BYTES) writeFileSync(LOG_PATH, '');
116
- } catch {}
117
- appendFileSync(LOG_PATH, `${new Date().toISOString()} ${line}\n`);
118
- } catch {}
294
+ const lst = lstatSync(parent);
295
+ if (lst.isSymbolicLink()) {
296
+ if (!isDarwinCanonicalSystemLink(parent)) throw new Error('Refusing unsafe parent directory');
297
+ } else if (!lst.isDirectory()) {
298
+ throw new Error('Refusing unsafe parent directory');
299
+ }
300
+ } catch (error) {
301
+ if (error?.code !== 'ENOENT') throw error;
302
+ }
303
+ const next = dirname(parent);
304
+ if (next === parent) break;
305
+ parent = next;
306
+ }
307
+ }
308
+
309
+ function checkTarget(path) {
310
+ try {
311
+ const lst = lstatSync(path);
312
+ if (lst.isSymbolicLink() || !lst.isFile()) throw new Error('Refusing non-regular target');
313
+ } catch (error) {
314
+ if (error?.code !== 'ENOENT') throw error;
315
+ }
119
316
  }
120
317
 
121
- /** Read the shared wake secret, creating it (0600) when absent. */
122
- function loadSecret() {
318
+ export function atomicReplaceRegular(tmp, target, fsOps) {
319
+ const renameFn = fsOps?.renameSync ?? renameSync;
320
+ const copyFn = fsOps?.copyFileSync ?? copyFileSync;
321
+ const unlinkFn = fsOps?.unlinkSync ?? unlinkSync;
322
+ checkParentDirectory(target);
323
+ checkTarget(target);
123
324
  try {
124
- if (existsSync(SECRET_PATH)) {
125
- const existing = readFileSync(SECRET_PATH, 'utf8').trim();
325
+ renameFn(tmp, target);
326
+ } catch (err) {
327
+ if (err?.code === 'EPERM' || err?.code === 'EACCES') {
328
+ checkParentDirectory(target);
329
+ checkTarget(target);
330
+ copyFn(tmp, target);
331
+ try {
332
+ unlinkFn(tmp);
333
+ } catch {}
334
+ return;
335
+ }
336
+ throw err;
337
+ }
338
+ }
339
+
340
+ /** Bound actual response bytes, regardless of Content-Length. */
341
+ async function readRegistrationText(res) {
342
+ if (!res.body) throw new Error("Empty registration response");
343
+ const reader = res.body.getReader();
344
+ const decoder = new TextDecoder("utf-8", { fatal: true });
345
+ let bytes = 0;
346
+ let text = "";
347
+ try {
348
+ for (;;) {
349
+ const { done, value } = await reader.read();
350
+ if (done) break;
351
+ bytes += value.byteLength;
352
+ if (bytes > 1024 * 1024) throw new Error("Registration response exceeds 1MiB");
353
+ text += decoder.decode(value, { stream: true });
354
+ }
355
+ return text + decoder.decode();
356
+ } catch (error) {
357
+ void reader.cancel().catch(() => {});
358
+ throw error;
359
+ } finally {
360
+ reader.releaseLock();
361
+ }
362
+ }
363
+
364
+ function isSafeAgentId(value) {
365
+ return typeof value === "string" && value.length > 0 && value.length <= 128 && value !== "." && value !== ".." &&
366
+ !FORBIDDEN_KEYS.has(value.toLowerCase()) && !/[\s\x00-\x1f\x7f-\x9f\u2028\u2029/\\]/.test(value);
367
+ }
368
+
369
+ function writeLog(logPath, line) {
370
+ let fd;
371
+ try {
372
+ checkParentDirectory(logPath);
373
+ mkdirSync(dirname(logPath), { recursive: true });
374
+ checkParentDirectory(logPath);
375
+ checkTarget(logPath);
376
+ fd = openSync(logPath, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), 0o600);
377
+ const lst = fstatSync(fd);
378
+ if (!lst.isFile()) return;
379
+ if (lst.size > LOG_MAX_BYTES) {
380
+ closeSync(fd);
381
+ fd = undefined;
382
+ const tmp = `${logPath}.${process.pid}.${Date.now()}.${++inboundTmpSeq}.tmp`;
383
+ let created = false;
384
+ try {
385
+ writeFileSync(tmp, '', { flag: 'wx', mode: 0o600 });
386
+ created = true;
387
+ atomicReplaceRegular(tmp, logPath);
388
+ } finally {
389
+ if (created) { try { unlinkSync(tmp); } catch {} }
390
+ }
391
+ fd = openSync(logPath, constants.O_WRONLY | constants.O_APPEND | (constants.O_NOFOLLOW ?? 0));
392
+ }
393
+ appendFileSync(fd, `${new Date().toISOString()} ${line}\n`);
394
+ } catch {} finally {
395
+ if (fd !== undefined) closeSync(fd);
396
+ }
397
+ }
398
+
399
+ /** Read the shared wake secret, creating it (0600) atomically when absent. */
400
+ function loadSecret(secretPath, logFn) {
401
+ try {
402
+ checkParentDirectory(secretPath);
403
+ try {
404
+ const lst = lstatSync(secretPath);
405
+ if (lst.isSymbolicLink() || !lst.isFile()) {
406
+ logFn(`refusing non-regular wake secret path: ${secretPath}`);
407
+ return undefined;
408
+ }
409
+ const existing = readFileSync(secretPath, 'utf8').trim();
126
410
  if (existing) return existing;
411
+ } catch (err) {
412
+ if (err?.code !== 'ENOENT') throw err;
127
413
  }
128
- mkdirSync(dirname(SECRET_PATH), { recursive: true });
414
+ mkdirSync(dirname(secretPath), { recursive: true, mode: 0o700 });
415
+ checkParentDirectory(secretPath);
129
416
  const secret = randomBytes(32).toString('hex');
130
- writeFileSync(SECRET_PATH, `${secret}\n`, { mode: 0o600 });
417
+ const tmp = `${secretPath}.${process.pid}.${Date.now()}.${++inboundTmpSeq}.tmp`;
418
+ let created = false;
131
419
  try {
132
- chmodSync(SECRET_PATH, 0o600);
133
- } catch (error) {
134
- log(`WARNING: could not chmod ${SECRET_PATH}: ${error?.message ?? error}`);
420
+ writeFileSync(tmp, `${secret}\n`, { flag: 'wx', mode: 0o600 });
421
+ created = true;
422
+ atomicReplaceRegular(tmp, secretPath);
423
+ try {
424
+ chmodSync(secretPath, 0o600);
425
+ } catch (error) {
426
+ logFn(`WARNING: could not chmod ${secretPath}: ${error?.message ?? error}`);
427
+ }
428
+ } catch (err) {
429
+ try {
430
+ if (created) unlinkSync(tmp);
431
+ } catch {}
432
+ throw err;
135
433
  }
136
434
  return secret;
137
435
  } catch (error) {
138
- log(`cannot load wake secret: ${error?.message ?? error}`);
436
+ logFn(`cannot load wake secret: ${error?.message ?? error}`);
139
437
  return undefined;
140
438
  }
141
439
  }
142
440
 
143
- function verifySignature(body, sigHex, secret) {
441
+ export function verifySignature(body, sigHex, secret) {
442
+ if (typeof body !== 'string' || typeof secret !== 'string' || secret.length === 0) return false;
144
443
  if (typeof sigHex !== 'string' || sigHex.length === 0) return false;
145
- let received;
146
- try {
147
- received = Buffer.from(sigHex, 'hex');
148
- } catch {
149
- return false;
150
- }
444
+ const normalized = sigHex.startsWith('sha256=') ? sigHex.slice(7) : sigHex;
445
+ if (!/^[0-9a-f]{64}$/i.test(normalized)) return false;
446
+ const received = Buffer.from(normalized, 'hex');
151
447
  const expected = createHmac('sha256', secret).update(body, 'utf8').digest();
152
448
  return received.length === expected.length && timingSafeEqual(received, expected);
153
449
  }
154
450
 
155
451
  /** Render the inbound message as a normal user turn for the agent. */
156
452
  function renderInbound(payload) {
157
- const channel = payload.channel_id ?? '(unknown)';
158
- const kind = channel.startsWith('dm-') ? 'direct message' : 'channel message';
453
+ const header = (value) => String(value ?? '(unknown)').replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, ' ').slice(0, 128);
454
+ const channel = header(payload.channel_id);
455
+ const kind = /^dm[-:]/i.test(channel) ? 'direct message' : 'channel message';
159
456
  return [
160
457
  '[AgentsChat inbound message]',
161
458
  `channel_id: ${channel}`,
162
- payload.message_id ? `message_id: ${payload.message_id}` : undefined,
163
- `from: ${payload.sender_id ?? '(unknown)'}`,
459
+ payload.message_id ? `message_id: ${header(payload.message_id)}` : undefined,
460
+ `from: ${header(payload.sender_id)}`,
164
461
  `kind: ${kind}`,
165
462
  'content:',
166
463
  payload.content ?? '(empty)',
@@ -172,40 +469,45 @@ function renderInbound(payload) {
172
469
  .join('\n');
173
470
  }
174
471
 
175
- const seen = [];
176
- const seenSet = new Set();
177
-
178
- /** Deduplicate wake retries by message_id; bounded memory. */
179
- function firstDelivery(payload) {
180
- const id = typeof payload.message_id === 'string' ? payload.message_id : undefined;
181
- if (!id) return true;
182
- if (seenSet.has(id)) return false;
183
- seenSet.add(id);
184
- seen.push(id);
185
- if (seen.length > MAX_SEEN_IDS) {
186
- const evicted = seen.shift();
187
- if (evicted !== undefined) seenSet.delete(evicted);
188
- }
189
- return true;
190
- }
472
+ export function apply(ctx, config = {}) {
473
+ const rawPort = Number(config.port ?? 8799);
474
+ const requestedPort = Number.isInteger(rawPort) && rawPort >= 0 && rawPort <= 65535 ? rawPort : 8799;
475
+ let boundPort = requestedPort;
476
+ const agentschatDir = config.agentschatDir ?? AGENTSCHAT_DIR;
477
+ const profilesDir = join(agentschatDir, 'profiles');
478
+ const bindsPath = join(agentschatDir, 'session-binds.json');
479
+ const secretPath = config.secretPath ?? (config.agentschatDir ? join(agentschatDir, 'dsh-inbound.secret') : SECRET_PATH);
480
+ const queuePath = config.queuePath ?? (config.agentschatDir ? join(agentschatDir, 'dsh-wake-queue.jsonl') : QUEUE_PATH);
481
+ const logPath = config.logPath ?? LOG_PATH;
482
+ const log = (line) => writeLog(logPath, line);
191
483
 
192
- /**
193
- * Release a claim taken by firstDelivery() after a delivery that never landed.
194
- *
195
- * The claim happens *before* the attempt (so a retry storm cannot double-queue),
196
- * which means a wake that fails to splice has to be un-claimed here — otherwise
197
- * the daemon's next attempt is swallowed as a duplicate and the message is lost
198
- * for good.
199
- */
200
- function forgetDelivery(payload) {
201
- const id = typeof payload.message_id === 'string' ? payload.message_id : undefined;
202
- if (!id || !seenSet.delete(id)) return;
203
- const index = seen.indexOf(id);
204
- if (index >= 0) seen.splice(index, 1);
205
- }
484
+ const seen = [];
485
+ const seenSet = new Set();
486
+
487
+ /** Deduplicate wake retries by message_id; bounded memory per plugin instance. */
488
+ function firstDelivery(payload) {
489
+ const id = typeof payload.message_id === 'string' ? payload.message_id : undefined;
490
+ if (!id) return true;
491
+ if (seenSet.has(id)) return false;
492
+ seenSet.add(id);
493
+ seen.push(id);
494
+ if (seen.length > MAX_SEEN_IDS) {
495
+ const evicted = seen.shift();
496
+ if (evicted !== undefined) seenSet.delete(evicted);
497
+ }
498
+ return true;
499
+ }
500
+
501
+ /**
502
+ * Release a claim taken by firstDelivery() after a delivery that never landed.
503
+ */
504
+ function forgetDelivery(payload) {
505
+ const id = typeof payload.message_id === 'string' ? payload.message_id : undefined;
506
+ if (!id || !seenSet.delete(id)) return;
507
+ const index = seen.indexOf(id);
508
+ if (index >= 0) seen.splice(index, 1);
509
+ }
206
510
 
207
- export function apply(ctx, config = {}) {
208
- const port = Number(config.port ?? 8799);
209
511
  // When installed as the published `agentschat-mcp` DSH bundle, `../../dist/dsh.js`
210
512
  // sits right inside the package so the wake daemon starts zero-config. Machine-local
211
513
  // copies (`~/.dsh/plugins/...`) lack `../../dist/dsh.js` and fall back to config/env.
@@ -218,12 +520,18 @@ export function apply(ctx, config = {}) {
218
520
  }
219
521
  })();
220
522
  const mcpBin = config.mcpBin ?? process.env.AGENTSCHAT_DSH_BRIDGE_BIN ?? defaultBundledMcpBin;
221
- const nodeBin = config.nodeBin ?? process.env.DSH_NODE_BIN ?? 'node';
523
+ const nodeBin =
524
+ config.nodeBin ??
525
+ process.env.DSH_NODE_BIN ??
526
+ process.env.DSH_NODE ??
527
+ (process.versions?.electron ? process.execPath : 'node');
222
528
  const channels = Array.isArray(config.channels) && config.channels.length > 0 ? config.channels : ['welcome'];
223
- const retryMs = Number(config.retryMs ?? DEFAULT_RETRY_MS);
224
- const flushTimeoutMs = Number(config.flushTimeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS);
529
+ const rawRetryMs = Number(config.retryMs ?? DEFAULT_RETRY_MS);
530
+ const retryMs = Number.isFinite(rawRetryMs) && rawRetryMs >= 10 ? Math.min(Math.floor(rawRetryMs), 300_000) : DEFAULT_RETRY_MS;
531
+ const rawFlushTimeoutMs = Number(config.flushTimeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS);
532
+ const flushTimeoutMs = Number.isFinite(rawFlushTimeoutMs) && rawFlushTimeoutMs >= 10 ? Math.min(Math.floor(rawFlushTimeoutMs), 300_000) : DEFAULT_FLUSH_TIMEOUT_MS;
225
533
 
226
- const secret = loadSecret();
534
+ const secret = loadSecret(secretPath, log);
227
535
  if (secret === undefined) {
228
536
  log('not starting: no wake secret');
229
537
  return;
@@ -234,6 +542,30 @@ export function apply(ctx, config = {}) {
234
542
  let restartTimer;
235
543
  let consecutiveFailures = 0;
236
544
 
545
+ /**
546
+ * DSH >= 0.2.1-rc.3 removed `AgentRegistry.roots()` in favor of `list()` and
547
+ * marks delegated child sessions via `session.header.origin === 'subagent'`
548
+ * or `delegationDepth > 0`.
549
+ */
550
+ function isOrdinaryRootAgent(agent) {
551
+ if (!agent || typeof agent !== 'object') return false;
552
+ const header = agent.session?.header;
553
+ if (header && typeof header === 'object') {
554
+ if (header.origin === 'subagent') return false;
555
+ if (typeof header.delegationDepth === 'number' && header.delegationDepth > 0) return false;
556
+ }
557
+ return true;
558
+ }
559
+
560
+ function isArchivedSession(sessionId) {
561
+ try {
562
+ const archived = ctx.get('workspaceRegistry')?.archivedSessionIds;
563
+ return Array.isArray(archived) && archived.includes(sessionId);
564
+ } catch {
565
+ return false;
566
+ }
567
+ }
568
+
237
569
  /** Live root agents, oldest first, with the status the gate reads. */
238
570
  function rootStatuses() {
239
571
  return liveRoots().map((agent) => {
@@ -247,7 +579,7 @@ export function apply(ctx, config = {}) {
247
579
  });
248
580
  }
249
581
 
250
- /** Live root agents, oldest first. */
582
+ /** Live root agents, oldest first (compatible with both DSH 0.1.x `roots()` and 0.2.1-rc.3+ `list()`). */
251
583
  function liveRoots() {
252
584
  let agents;
253
585
  try {
@@ -258,13 +590,51 @@ export function apply(ctx, config = {}) {
258
590
  }
259
591
  if (agents === undefined || agents === null) return [];
260
592
  try {
261
- return agents.roots();
593
+ if (typeof agents.roots === 'function') {
594
+ return agents.roots();
595
+ }
596
+ if (typeof agents.list === 'function') {
597
+ return agents.list().filter(isOrdinaryRootAgent);
598
+ }
599
+ log('cannot list root agents: neither agents.roots() nor agents.list() is available');
600
+ return [];
262
601
  } catch (error) {
263
602
  log(`cannot list root agents: ${error?.message ?? error}`);
264
603
  return [];
265
604
  }
266
605
  }
267
606
 
607
+ /**
608
+ * Resolve a bound session to its live Agent, activating a cold persisted
609
+ * session through `sessionController.resolveAgent()` on DSH >= 0.2.1-rc.3
610
+ * (same activation seam `@deepseek-ai/dsh-schedule` uses).
611
+ */
612
+ async function resolveBoundTargetAgent(wanted) {
613
+ const live = liveRoots().find((agent) => agent.id === wanted);
614
+ if (live !== undefined) return live;
615
+ if (isArchivedSession(wanted)) return undefined;
616
+ let sessionController;
617
+ try {
618
+ sessionController = ctx.get('sessionController');
619
+ } catch {
620
+ return undefined;
621
+ }
622
+ if (sessionController && typeof sessionController.resolveAgent === 'function') {
623
+ const outcome = await settleWithin(
624
+ Promise.resolve().then(() => sessionController.resolveAgent(wanted)),
625
+ 10_000,
626
+ );
627
+ if (outcome.timedOut === true) {
628
+ log(`WARNING: session activation for ${wanted} timed out after 10000ms`);
629
+ return undefined;
630
+ }
631
+ if (outcome.ok === true && outcome.value && typeof outcome.value === 'object' && !('error' in outcome.value) && outcome.value.agent) {
632
+ return isOrdinaryRootAgent(outcome.value.agent) ? outcome.value.agent : undefined;
633
+ }
634
+ }
635
+ return undefined;
636
+ }
637
+
268
638
  /** Wake deliveries waiting for their bound session to go idle, oldest first. */
269
639
  const pending = [];
270
640
  let retryTimer;
@@ -293,7 +663,7 @@ export function apply(ctx, config = {}) {
293
663
  log(`wake ${id} dropped: identity is unbound (bind a session in the identity chip to receive it here)`);
294
664
  return 'dropped';
295
665
  }
296
- const target = liveRoots().find((agent) => agent.id === wanted);
666
+ const target = await resolveBoundTargetAgent(wanted);
297
667
  if (target === undefined) {
298
668
  log(`wake ${id} dropped: bound session ${wanted} is not live (bind the identity to an open session)`);
299
669
  return 'dropped';
@@ -416,42 +786,61 @@ export function apply(ctx, config = {}) {
416
786
  */
417
787
  function listProfiles() {
418
788
  const out = [];
419
- const seen = new Set();
789
+ const seenNames = new Set();
420
790
  const scan = (dir) => {
791
+ try {
792
+ const dirStat = lstatSync(dir);
793
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return;
794
+ } catch {
795
+ return;
796
+ }
421
797
  let files;
422
798
  try {
423
- files = readdirSync(dir).filter((file) => file.endsWith('.json'));
799
+ files = readdirSync(dir).filter((file) => /\.json$/i.test(file));
424
800
  } catch {
425
801
  return;
426
802
  }
427
803
  for (const file of files) {
428
- const name = file.replace(/\.json$/, '');
429
- if (seen.has(name)) continue;
804
+ const name = file.replace(/\.json$/i, '');
805
+ if (!isSafeKey(name) || RESERVED_PROFILE_SIDECARS.has(name.toLowerCase()) || seenNames.has(name)) continue;
430
806
  const path = join(dir, file);
431
807
  try {
808
+ const lst = lstatSync(path);
809
+ if (lst.isSymbolicLink() || !lst.isFile() || lst.size > 256 * 1024) continue;
432
810
  const parsed = JSON.parse(readFileSync(path, 'utf8'));
433
- const agentId = typeof parsed.agent_id === 'string' ? parsed.agent_id : '';
434
- if (!agentId) continue;
435
- seen.add(name);
811
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed) || Object.prototype.hasOwnProperty.call(parsed, '__proto__')) continue;
812
+ const agentId = typeof parsed.agent_id === 'string' ? parsed.agent_id.trim() : '';
813
+ if (!isSafeAgentId(agentId)) continue;
814
+ seenNames.add(name);
436
815
  out.push({
437
816
  name,
438
817
  agentId,
439
818
  displayName: typeof parsed.display_name === 'string' ? parsed.display_name : undefined,
440
- mtime: statSync(path).mtimeMs,
819
+ mtime: lst.mtimeMs,
441
820
  });
442
821
  } catch {}
443
822
  }
444
823
  };
445
- scan(PROFILES_DIR);
446
- scan(AGENTSCHAT_DIR);
824
+ scan(profilesDir);
825
+ scan(agentschatDir);
447
826
  out.sort((a, b) => b.mtime - a.mtime);
448
827
  return out;
449
828
  }
450
829
 
451
830
  function readBinds() {
452
831
  try {
453
- const parsed = JSON.parse(readFileSync(BINDS_PATH, 'utf8'));
454
- return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
832
+ const lst = lstatSync(bindsPath);
833
+ if (lst.isSymbolicLink() || !lst.isFile() || lst.size > 256 * 1024) return {};
834
+ const parsed = JSON.parse(readFileSync(bindsPath, 'utf8'));
835
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed) || Object.prototype.hasOwnProperty.call(parsed, '__proto__')) return {};
836
+ const clean = {};
837
+ for (const [k, v] of Object.entries(parsed)) {
838
+ if (!isSafeKey(k) || typeof v !== 'string') continue;
839
+ const trimmed = v.trim();
840
+ if (!isSafeKey(trimmed)) continue;
841
+ clean[k] = trimmed;
842
+ }
843
+ return clean;
455
844
  } catch {
456
845
  return {};
457
846
  }
@@ -459,40 +848,89 @@ export function apply(ctx, config = {}) {
459
848
 
460
849
  /** Same shape the MCP server reads: `{ [sessionId]: profileName }`. */
461
850
  function writeBinds(binds) {
462
- mkdirSync(AGENTSCHAT_DIR, { recursive: true });
463
- const tmp = `${BINDS_PATH}.${process.pid}.tmp`;
464
- writeFileSync(tmp, JSON.stringify(binds, null, 2));
465
- renameSync(tmp, BINDS_PATH);
851
+ checkParentDirectory(bindsPath);
852
+ try {
853
+ const lst = lstatSync(bindsPath);
854
+ if (lst.isSymbolicLink() || !lst.isFile()) {
855
+ throw new Error(`Refusing to overwrite non-regular session-binds path: ${bindsPath}`);
856
+ }
857
+ } catch (err) {
858
+ if (err?.code !== 'ENOENT') throw err;
859
+ }
860
+ mkdirSync(agentschatDir, { recursive: true, mode: 0o700 });
861
+ checkParentDirectory(bindsPath);
862
+ const tmp = `${bindsPath}.${process.pid}.${Date.now()}.${++inboundTmpSeq}.tmp`;
863
+ let created = false;
864
+ try {
865
+ writeFileSync(tmp, `${JSON.stringify(binds, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
866
+ created = true;
867
+ atomicReplaceRegular(tmp, bindsPath);
868
+ try {
869
+ chmodSync(bindsPath, 0o600);
870
+ } catch {}
871
+ } catch (err) {
872
+ try {
873
+ if (created) unlinkSync(tmp);
874
+ } catch {}
875
+ throw err;
876
+ }
466
877
  }
467
878
 
468
- function sendJson(res, status, value) {
469
- res.writeHead(status, {
470
- 'content-type': 'application/json',
471
- 'access-control-allow-origin': '*',
879
+ function buildCorsHeaders(origin) {
880
+ if (typeof origin !== 'string' || !isAllowedLocalOrigin(origin)) return {};
881
+ return {
882
+ 'access-control-allow-origin': origin,
472
883
  'access-control-allow-methods': 'GET, POST, OPTIONS',
473
884
  'access-control-allow-headers': 'content-type',
885
+ vary: 'Origin',
886
+ };
887
+ }
888
+
889
+ function sendJson(res, status, value, corsHeaders = {}) {
890
+ res.writeHead(status, {
891
+ 'content-type': 'application/json',
892
+ ...corsHeaders,
474
893
  });
475
894
  res.end(JSON.stringify(value));
476
895
  }
477
896
 
478
- /** Read a bounded JSON body; the endpoint is loopback-only and unauthenticated. */
479
- function readJsonBody(req, res, onBody) {
897
+ /** Read a bounded UTF-8 request body; rejects payloads above `MAX_HTTP_BODY_BYTES` with 413. */
898
+ function readBoundedBody(req, res, corsHeaders, onText) {
480
899
  const chunks = [];
481
900
  let size = 0;
901
+ let settled = false;
482
902
  req.on('data', (chunk) => {
903
+ if (settled) return;
483
904
  size += chunk.length;
484
- if (size > 64 * 1024) {
905
+ if (size > MAX_HTTP_BODY_BYTES) {
906
+ settled = true;
907
+ if (!res.headersSent) {
908
+ res.writeHead(413, { 'content-type': 'application/json', ...corsHeaders });
909
+ res.end(JSON.stringify({ ok: false, error: 'payload too large' }));
910
+ }
485
911
  req.destroy();
486
912
  return;
487
913
  }
488
914
  chunks.push(chunk);
489
915
  });
916
+ req.on('error', () => {
917
+ settled = true;
918
+ });
490
919
  req.on('end', () => {
920
+ if (settled) return;
921
+ settled = true;
922
+ onText(Buffer.concat(chunks).toString('utf8'));
923
+ });
924
+ }
925
+
926
+ /** Read a bounded JSON body; the endpoint is loopback-only and unauthenticated. */
927
+ function readJsonBody(req, res, corsHeaders, onBody) {
928
+ readBoundedBody(req, res, corsHeaders, (rawText) => {
491
929
  let parsed;
492
930
  try {
493
- parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
931
+ parsed = JSON.parse(rawText);
494
932
  } catch {
495
- sendJson(res, 400, { ok: false, error: 'invalid JSON' });
933
+ sendJson(res, 400, { ok: false, error: 'invalid JSON' }, corsHeaders);
496
934
  return;
497
935
  }
498
936
  onBody(parsed);
@@ -500,12 +938,21 @@ export function apply(ctx, config = {}) {
500
938
  }
501
939
 
502
940
  const server = createServer((req, res) => {
941
+ const originHeader = req.headers.origin;
942
+ if (originHeader !== undefined && (typeof originHeader !== 'string' || !isAllowedLocalOrigin(originHeader))) {
943
+ log(`rejected cross-origin request from origin=${String(originHeader).slice(0, 120)}`);
944
+ res.writeHead(403, { 'content-type': 'text/plain' });
945
+ res.end('forbidden');
946
+ return;
947
+ }
948
+ const corsHeaders = buildCorsHeaders(originHeader);
949
+
503
950
  if (req.method === 'OPTIONS') {
504
- res.writeHead(204, {
505
- 'access-control-allow-origin': '*',
506
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
507
- 'access-control-allow-headers': 'content-type',
508
- });
951
+ const preflightHeaders = { ...corsHeaders };
952
+ if (req.headers['access-control-request-private-network'] === 'true' && typeof originHeader === 'string') {
953
+ preflightHeaders['access-control-allow-private-network'] = 'true';
954
+ }
955
+ res.writeHead(204, preflightHeaders);
509
956
  res.end();
510
957
  return;
511
958
  }
@@ -515,15 +962,15 @@ export function apply(ctx, config = {}) {
515
962
  // no separate storage — and the next tool call from this session picks the
516
963
  // identity up without a restart.
517
964
  if (req.method === 'GET' && req.url === '/identity') {
518
- sendJson(res, 200, { ok: true, build: BUILD, profiles: listProfiles(), binds: readBinds() });
965
+ sendJson(res, 200, { ok: true, build: BUILD, profiles: listProfiles(), binds: readBinds() }, corsHeaders);
519
966
  return;
520
967
  }
521
968
  if (req.method === 'POST' && req.url === '/identity/bind') {
522
- readJsonBody(req, res, (body) => {
969
+ readJsonBody(req, res, corsHeaders, (body) => {
523
970
  const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
524
971
  const profileName = typeof body?.profileName === 'string' ? body.profileName.trim() : '';
525
- if (!sessionId || !listProfiles().some((entry) => entry.name === profileName)) {
526
- sendJson(res, 400, { ok: false, error: 'sessionId and a known profileName are required' });
972
+ if (!isSafeKey(sessionId) || !isSafeKey(profileName) || !listProfiles().some((entry) => entry.name === profileName)) {
973
+ sendJson(res, 400, { ok: false, error: 'sessionId and a known profileName are required' }, corsHeaders);
527
974
  return;
528
975
  }
529
976
  const binds = readBinds();
@@ -531,11 +978,11 @@ export function apply(ctx, config = {}) {
531
978
  try {
532
979
  writeBinds(binds);
533
980
  } catch (error) {
534
- sendJson(res, 500, { ok: false, error: String(error?.message ?? error) });
981
+ sendJson(res, 500, { ok: false, error: scrubSecrets(String(error?.message ?? error)) }, corsHeaders);
535
982
  return;
536
983
  }
537
984
  log(`identity bound: ${sessionId} -> ${profileName}`);
538
- sendJson(res, 200, { ok: true, binds });
985
+ sendJson(res, 200, { ok: true, binds }, corsHeaders);
539
986
  });
540
987
  return;
541
988
  }
@@ -543,31 +990,64 @@ export function apply(ctx, config = {}) {
543
990
  // carries whatever failed. Without it a blank UI is indistinguishable from a
544
991
  // module that never loaded.
545
992
  if (req.method === 'POST' && req.url === '/identity/alive') {
546
- readJsonBody(req, res, (body) => {
547
- log(`client-alive ${JSON.stringify(body)}`);
548
- sendJson(res, 200, { ok: true, build: BUILD });
993
+ readJsonBody(req, res, corsHeaders, (body) => {
994
+ log(`client-alive ${scrubSecrets(JSON.stringify(body).slice(0, 512))}`);
995
+ sendJson(res, 200, { ok: true, build: BUILD }, corsHeaders);
549
996
  });
550
997
  return;
551
998
  }
552
999
  if (req.method === 'POST' && req.url === '/identity/create') {
553
- readJsonBody(req, res, async (body) => {
554
- const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
1000
+ readJsonBody(req, res, corsHeaders, async (body) => {
1001
+ const rawSessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
1002
+ if (rawSessionId && !isSafeKey(rawSessionId)) {
1003
+ sendJson(res, 400, { ok: false, error: 'invalid sessionId' }, corsHeaders);
1004
+ return;
1005
+ }
1006
+ const sessionId = rawSessionId;
555
1007
  const rawName = typeof body?.name === 'string' && body.name.trim()
556
- ? body.name.trim().slice(0, 48)
1008
+ ? body.name.trim().replace(/[\x00-\x1f\x7f-\x9f\u2028\u2029]/g, '').slice(0, 48)
557
1009
  : `DSH_${sessionId ? sessionId.replace(/^session-/, '').slice(0, 6) : randomBytes(3).toString('hex')}`;
558
- const baseName = rawName.replace(/[^a-zA-Z0-9_-]/g, '_').replace(/^_+|_+$/g, '') || `DSH_${randomBytes(3).toString('hex')}`;
1010
+ const sanitizedBase = rawName.replace(/[^a-zA-Z0-9_-]/g, '_').replace(/^_+|_+$/g, '');
1011
+ const baseName =
1012
+ isSafeKey(sanitizedBase) && !RESERVED_PROFILE_SIDECARS.has(sanitizedBase.toLowerCase())
1013
+ ? sanitizedBase
1014
+ : `DSH_${randomBytes(3).toString('hex')}`;
559
1015
  let profileName = baseName;
560
1016
  let suffix = 2;
561
- mkdirSync(PROFILES_DIR, { recursive: true });
562
- while (existsSync(join(PROFILES_DIR, `${profileName}.json`)) || existsSync(join(AGENTSCHAT_DIR, `${profileName}.json`))) {
1017
+ try {
1018
+ checkParentDirectory(join(profilesDir, 'placeholder'));
1019
+ } catch {
1020
+ sendJson(res, 500, { ok: false, error: 'refusing unsafe profiles directory' }, corsHeaders);
1021
+ return;
1022
+ }
1023
+ mkdirSync(profilesDir, { recursive: true, mode: 0o700 });
1024
+ while (existsSync(join(profilesDir, `${profileName}.json`)) || existsSync(join(agentschatDir, `${profileName}.json`))) {
563
1025
  profileName = `${baseName}_${suffix++}`;
564
1026
  }
565
- const restBase = (
1027
+ const restBase = String(
566
1028
  config.apiUrl ??
567
1029
  process.env.AGENTCHAT_REST_URL ??
568
1030
  process.env.AGENTSCHAT_API_URL ??
569
- 'https://agents-chat.com'
570
- ).replace(/\/+$/, '');
1031
+ 'https://agents-chat.com',
1032
+ )
1033
+ .trim()
1034
+ .replace(/\/+$/, '');
1035
+ let parsedRest;
1036
+ try {
1037
+ parsedRest = new URL(restBase);
1038
+ } catch {
1039
+ sendJson(res, 400, { ok: false, error: 'invalid API URL' }, corsHeaders);
1040
+ return;
1041
+ }
1042
+ const host = parsedRest.hostname.toLowerCase().replace(/\.+$/, '');
1043
+ const loopback = ['localhost', '127.0.0.1', '::1', '[::1]'].includes(host);
1044
+ if ((parsedRest.protocol !== 'https:' && !(parsedRest.protocol === 'http:' && loopback)) ||
1045
+ isBlockedInboundHost(parsedRest.hostname) ||
1046
+ parsedRest.username || parsedRest.password || parsedRest.port === '0' || parsedRest.search || parsedRest.hash ||
1047
+ /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(restBase)) {
1048
+ sendJson(res, 400, { ok: false, error: 'unsupported API URL protocol' }, corsHeaders);
1049
+ return;
1050
+ }
571
1051
  const wsUrl =
572
1052
  process.env.AGENTCHAT_WS_URL ??
573
1053
  `${restBase.replace(/^https:\/\//i, 'wss://').replace(/^http:\/\//i, 'ws://')}/ws`;
@@ -580,20 +1060,33 @@ export function apply(ctx, config = {}) {
580
1060
  type: 'agent',
581
1061
  capabilities: ['dsh', 'coding', 'chat'],
582
1062
  }),
1063
+ redirect: 'error',
1064
+ signal: AbortSignal.timeout(15_000),
583
1065
  });
584
1066
  if (!regRes.ok) {
585
- const errText = (await regRes.text()).slice(0, 200);
586
- sendJson(res, 502, { ok: false, error: `register HTTP ${regRes.status}: ${errText}` });
1067
+ const errText = scrubSecrets(await readRegistrationText(regRes)).slice(0, 200);
1068
+ sendJson(res, 502, { ok: false, error: `register HTTP ${regRes.status}: ${errText}` }, corsHeaders);
587
1069
  return;
588
1070
  }
589
- const data = await regRes.json();
590
- const agentId = data.agentId ?? data.agent_id ?? data.id;
591
- const token = data.agentKey ?? data.token ?? data.key;
592
- if (typeof agentId !== 'string' || !agentId || typeof token !== 'string' || !token) {
593
- sendJson(res, 502, { ok: false, error: 'register response missing agent_id/token' });
1071
+ const data = JSON.parse(await readRegistrationText(regRes));
1072
+ const rawAgentId = data?.agentId ?? data?.agent_id ?? data?.id;
1073
+ const rawToken = data?.agentKey ?? data?.token ?? data?.key;
1074
+ const agentId = typeof rawAgentId === 'string' ? rawAgentId.trim() : '';
1075
+ const token = typeof rawToken === 'string' ? rawToken.trim() : '';
1076
+ if (!isSafeAgentId(rawAgentId) || !token || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(agentId) || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(token)) {
1077
+ sendJson(res, 502, { ok: false, error: 'register response missing agent_id/token' }, corsHeaders);
594
1078
  return;
595
1079
  }
596
- const profilePath = join(PROFILES_DIR, `${profileName}.json`);
1080
+ const profilePath = join(profilesDir, `${profileName}.json`);
1081
+ try {
1082
+ const lst = lstatSync(profilePath);
1083
+ if (lst.isSymbolicLink() || !lst.isFile()) {
1084
+ sendJson(res, 500, { ok: false, error: 'refusing non-regular profile path' }, corsHeaders);
1085
+ return;
1086
+ }
1087
+ } catch (err) {
1088
+ if (err?.code !== 'ENOENT') throw err;
1089
+ }
597
1090
  const record = {
598
1091
  name: profileName,
599
1092
  display_name: rawName,
@@ -603,33 +1096,49 @@ export function apply(ctx, config = {}) {
603
1096
  api_url: restBase,
604
1097
  created_at: new Date().toISOString(),
605
1098
  };
606
- writeFileSync(profilePath, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
1099
+ const tmp = `${profilePath}.${process.pid}.${Date.now()}.${++inboundTmpSeq}.tmp`;
1100
+ let created = false;
607
1101
  try {
608
- chmodSync(profilePath, 0o600);
609
- } catch {}
1102
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { flag: 'wx', mode: 0o600 });
1103
+ created = true;
1104
+ atomicReplaceRegular(tmp, profilePath);
1105
+ try {
1106
+ chmodSync(profilePath, 0o600);
1107
+ } catch {}
1108
+ } catch (err) {
1109
+ try {
1110
+ if (created) unlinkSync(tmp);
1111
+ } catch {}
1112
+ throw err;
1113
+ }
610
1114
  const binds = readBinds();
611
1115
  if (sessionId) {
612
1116
  binds[sessionId] = profileName;
613
1117
  writeBinds(binds);
614
1118
  }
615
1119
  log(`identity created: ${profileName} (${agentId})${sessionId ? ` bound to ${sessionId}` : ''}`);
616
- sendJson(res, 200, {
617
- ok: true,
618
- profile: { name: profileName, agentId, displayName: rawName },
619
- profiles: listProfiles(),
620
- binds,
621
- });
1120
+ sendJson(
1121
+ res,
1122
+ 200,
1123
+ {
1124
+ ok: true,
1125
+ profile: { name: profileName, agentId, displayName: rawName },
1126
+ profiles: listProfiles(),
1127
+ binds,
1128
+ },
1129
+ corsHeaders,
1130
+ );
622
1131
  } catch (error) {
623
- sendJson(res, 500, { ok: false, error: String(error?.message ?? error) });
1132
+ sendJson(res, 500, { ok: false, error: scrubSecrets(String(error?.message ?? error)) }, corsHeaders);
624
1133
  }
625
1134
  });
626
1135
  return;
627
1136
  }
628
1137
  if (req.method === 'POST' && req.url === '/identity/unbind') {
629
- readJsonBody(req, res, (body) => {
1138
+ readJsonBody(req, res, corsHeaders, (body) => {
630
1139
  const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
631
- if (!sessionId) {
632
- sendJson(res, 400, { ok: false, error: 'sessionId required' });
1140
+ if (!isSafeKey(sessionId)) {
1141
+ sendJson(res, 400, { ok: false, error: 'sessionId required' }, corsHeaders);
633
1142
  return;
634
1143
  }
635
1144
  const binds = readBinds();
@@ -637,17 +1146,17 @@ export function apply(ctx, config = {}) {
637
1146
  try {
638
1147
  writeBinds(binds);
639
1148
  } catch (error) {
640
- sendJson(res, 500, { ok: false, error: String(error?.message ?? error) });
1149
+ sendJson(res, 500, { ok: false, error: scrubSecrets(String(error?.message ?? error)) }, corsHeaders);
641
1150
  return;
642
1151
  }
643
1152
  log(`identity unbound: ${sessionId}`);
644
- sendJson(res, 200, { ok: true, binds });
1153
+ sendJson(res, 200, { ok: true, binds }, corsHeaders);
645
1154
  });
646
1155
  return;
647
1156
  }
648
1157
  if (req.method === 'GET' && (req.url === '/health' || req.url === '/selftest')) {
649
1158
  const roots = rootStatuses();
650
- res.writeHead(200, { 'content-type': 'application/json' });
1159
+ res.writeHead(200, { 'content-type': 'application/json', ...corsHeaders });
651
1160
  if (req.url === '/health') {
652
1161
  // `build` is the only way to tell which file:// version is actually in
653
1162
  // memory; `agents` is kept for scripts that predate `roots`.
@@ -656,7 +1165,7 @@ export function apply(ctx, config = {}) {
656
1165
  ok: true,
657
1166
  plugin: name,
658
1167
  build: BUILD,
659
- port,
1168
+ port: boundPort,
660
1169
  agents: roots.map((root) => root.id),
661
1170
  roots,
662
1171
  daemon: daemon !== undefined,
@@ -670,15 +1179,22 @@ export function apply(ctx, config = {}) {
670
1179
  // Delivery is bound-only, so the useful answer is per binding, not "the
671
1180
  // newest idle root".
672
1181
  const byId = new Map(liveRoots().map((agent) => [agent.id, agent]));
1182
+ let hasActivator = false;
1183
+ try {
1184
+ hasActivator = typeof ctx.get('sessionController')?.resolveAgent === 'function';
1185
+ } catch {}
673
1186
  const bound = Object.entries(readBinds()).map(([sessionId, profileName]) => {
674
1187
  const agent = byId.get(sessionId);
1188
+ const canActivate = agent === undefined && hasActivator && !isArchivedSession(sessionId);
675
1189
  return {
676
1190
  sessionId,
677
1191
  profile: profileName,
678
- status: agent === undefined ? 'missing' : agent.status,
1192
+ status: agent === undefined ? (canActivate ? 'cold' : 'missing') : agent.status,
679
1193
  decision:
680
1194
  agent === undefined
681
- ? 'drop'
1195
+ ? canActivate
1196
+ ? 'activate'
1197
+ : 'drop'
682
1198
  : agent.status === 'idle'
683
1199
  ? 'deliver'
684
1200
  : typeof agent.steer === 'function'
@@ -701,18 +1217,15 @@ export function apply(ctx, config = {}) {
701
1217
  return;
702
1218
  }
703
1219
  if (req.method !== 'POST' || req.url !== WAKE_PATH) {
704
- res.writeHead(404, { 'content-type': 'text/plain' });
1220
+ res.writeHead(404, { 'content-type': 'text/plain', ...corsHeaders });
705
1221
  res.end('not found');
706
1222
  return;
707
1223
  }
708
- const chunks = [];
709
- req.on('data', (chunk) => chunks.push(chunk));
710
- req.on('end', () => {
711
- const body = Buffer.concat(chunks).toString('utf8');
1224
+ readBoundedBody(req, res, corsHeaders, (body) => {
712
1225
  const signature = req.headers['x-agentschat-signature'];
713
1226
  if (!verifySignature(body, typeof signature === 'string' ? signature : '', secret)) {
714
1227
  log('rejected wake: bad or missing signature');
715
- res.writeHead(403, { 'content-type': 'text/plain' });
1228
+ res.writeHead(403, { 'content-type': 'text/plain', ...corsHeaders });
716
1229
  res.end('forbidden');
717
1230
  return;
718
1231
  }
@@ -721,11 +1234,11 @@ export function apply(ctx, config = {}) {
721
1234
  payload = JSON.parse(body);
722
1235
  } catch (error) {
723
1236
  log(`rejected wake: invalid JSON (${error?.message ?? error})`);
724
- res.writeHead(400, { 'content-type': 'text/plain' });
1237
+ res.writeHead(400, { 'content-type': 'text/plain', ...corsHeaders });
725
1238
  res.end('bad request');
726
1239
  return;
727
1240
  }
728
- res.writeHead(200, { 'content-type': 'application/json' });
1241
+ res.writeHead(200, { 'content-type': 'application/json', ...corsHeaders });
729
1242
  res.end('{"ok":true}');
730
1243
  inject(payload).catch((error) => log(`inject failed: ${error?.message ?? error}`));
731
1244
  });
@@ -736,8 +1249,17 @@ export function apply(ctx, config = {}) {
736
1249
  // to whatever else happens to own the port.
737
1250
  log('not starting the wake daemon: the endpoint is not ours');
738
1251
  });
739
- server.listen(port, '127.0.0.1', () => {
740
- log(`listening on http://127.0.0.1:${port}${WAKE_PATH} (health: /health, selftest: /selftest, build: ${BUILD})`);
1252
+ server.listen(requestedPort, '127.0.0.1', () => {
1253
+ const addr = server.address();
1254
+ if (addr && typeof addr === 'object' && typeof addr.port === 'number') {
1255
+ boundPort = addr.port;
1256
+ }
1257
+ log(`listening on http://127.0.0.1:${boundPort}${WAKE_PATH} (health: /health, selftest: /selftest, build: ${BUILD})`);
1258
+ if (typeof config.onListening === 'function') {
1259
+ try {
1260
+ config.onListening({ port: boundPort });
1261
+ } catch {}
1262
+ }
741
1263
  startDaemon();
742
1264
  });
743
1265
 
@@ -751,9 +1273,10 @@ export function apply(ctx, config = {}) {
751
1273
  for (const channel of channels) args.push('--channel', channel);
752
1274
  const env = {
753
1275
  ...process.env,
754
- DSH_WAKE_URL: `http://127.0.0.1:${port}${WAKE_PATH}`,
1276
+ ...(process.versions?.electron && nodeBin === process.execPath ? { ELECTRON_RUN_AS_NODE: '1' } : {}),
1277
+ DSH_WAKE_URL: `http://127.0.0.1:${boundPort}${WAKE_PATH}`,
755
1278
  DSH_WAKE_SECRET: secret,
756
- DSH_WAKE_QUEUE: QUEUE_PATH,
1279
+ DSH_WAKE_QUEUE: queuePath,
757
1280
  };
758
1281
  log(`starting wake daemon: ${nodeBin} ${args.join(' ')}`);
759
1282
  daemon = spawn(nodeBin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });