agentschat-mcp 0.36.25 → 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 (82) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/codex/README.md +1 -1
  3. package/codex/app-server.ts +79 -22
  4. package/codex/bots-config.ts +31 -11
  5. package/codex/bridge.ts +123 -25
  6. package/codex/config.ts +128 -21
  7. package/codex/gui-channel.ts +66 -9
  8. package/codex/inbox-sync.ts +65 -12
  9. package/codex/loop-grants.ts +41 -11
  10. package/codex/manager.ts +101 -25
  11. package/codex/owner.ts +81 -9
  12. package/codex/processes.ts +51 -7
  13. package/codex/run.ts +70 -17
  14. package/codex/runtime-home.ts +41 -11
  15. package/codex/thread-history.ts +77 -30
  16. package/codex/transport.ts +122 -19
  17. package/connector/auth.ts +57 -5
  18. package/connector/backfill.ts +92 -10
  19. package/connector/descriptor.ts +27 -1
  20. package/connector/identities.ts +82 -14
  21. package/connector/ingest.ts +11 -2
  22. package/connector/normalize.ts +32 -12
  23. package/connector/run.ts +314 -67
  24. package/connector/server.ts +95 -26
  25. package/dist/codex-bots.js +410 -73
  26. package/dist/codex-bridge.js +1996 -576
  27. package/dist/connector.js +1286 -493
  28. package/dist/dsh.js +1776 -299
  29. package/dist/muse.js +967 -221
  30. package/dist/server.js +4277 -929
  31. package/dsh/client.js +7 -5
  32. package/dsh/identity-ui/client.js +7 -5
  33. package/dsh/identity-ui/index.js +43 -8
  34. package/dsh/inbound-bridge/index.js +595 -146
  35. package/dsh/src/cli.ts +430 -91
  36. package/dsh/src/patch.ts +295 -15
  37. package/dsh/tests/dsh-hardening-127.test.ts +207 -0
  38. package/dsh/tests/dsh.test.ts +990 -3
  39. package/muse/scripts/ensure-muse-wakes.mjs +5 -3
  40. package/muse/scripts/muse-wake-receiver.mjs +4 -1
  41. package/muse/src/bridge.ts +54 -13
  42. package/muse/src/cli.ts +226 -41
  43. package/muse/src/client.ts +249 -34
  44. package/muse/src/config.ts +128 -12
  45. package/muse/src/policy.ts +28 -8
  46. package/muse/src/types.ts +1 -0
  47. package/muse/src/typing.ts +18 -1
  48. package/muse/src/wake.ts +237 -35
  49. package/muse/tests/bridge.test.mjs +131 -0
  50. package/muse/tests/client.test.mjs +327 -0
  51. package/muse/tests/config.test.mjs +78 -1
  52. package/muse/tests/hardening.test.mjs +199 -0
  53. package/muse/tests/hardening126.test.mjs +292 -0
  54. package/muse/tests/policy.test.mjs +83 -1
  55. package/muse/tests/wake.test.mjs +134 -6
  56. package/package.json +1 -1
  57. package/scripts/ensure-grok-wakes.mjs +93 -8
  58. package/scripts/example-url-wake-receiver.mjs +254 -61
  59. package/scripts/grok-bind-register.sh +38 -8
  60. package/skills/onboarding.md +9 -9
  61. package/src/argcheck.ts +113 -33
  62. package/src/cli.mjs +98 -14
  63. package/src/dedup.ts +57 -8
  64. package/src/grok-bind.ts +160 -33
  65. package/src/heartbeat.ts +39 -11
  66. package/src/identity-guard.ts +93 -20
  67. package/src/identity.ts +67 -11
  68. package/src/mentions.ts +26 -5
  69. package/src/onboarding-status.ts +134 -11
  70. package/src/profile-selection.ts +269 -18
  71. package/src/profile-store.ts +222 -28
  72. package/src/read-cursor.ts +256 -9
  73. package/src/reconnect.ts +98 -2
  74. package/src/redact.ts +34 -15
  75. package/src/rest-cli.ts +713 -159
  76. package/src/server.ts +285 -93
  77. package/src/session-bind.ts +731 -132
  78. package/src/session-route.ts +183 -12
  79. package/src/team-lead-skill.ts +3 -0
  80. package/src/timestamps.ts +56 -23
  81. package/src/tool-annotations.ts +10 -1
  82. package/src/wake.ts +510 -91
package/src/rest-cli.ts CHANGED
@@ -16,11 +16,12 @@
16
16
  * any message arriving at/after `__init_ts__` is delivered immediately without
17
17
  * being swallowed by cold-start seeding.
18
18
  */
19
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
20
- import { dirname, join } from "node:path";
19
+ import { randomBytes } from "node:crypto";
20
+ import { lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, unlinkSync, writeFileSync, type Stats } from "node:fs";
21
+ import { dirname, isAbsolute, join, parse, resolve } from "node:path";
21
22
  import { matchesMention } from "./mentions.ts";
22
23
  import { safeWriteProfile } from "./profile-store.ts";
23
- import { loadCursor, persistCursor, type Warn } from "./read-cursor.ts";
24
+ import { cursorFileForAgent, loadCursor, persistCursor, safeAgentCursorSlug, type Warn } from "./read-cursor.ts";
24
25
  import { redactParticipantPii, redactSecrets } from "./redact.ts";
25
26
  import { normalizeTimestampForCursor } from "./timestamps.ts";
26
27
  import { buildWakePrompt, formatWakeAttachments } from "./wake.ts";
@@ -28,7 +29,7 @@ import { buildWakePrompt, formatWakeAttachments } from "./wake.ts";
28
29
  export const CURSOR_INIT_KEY = "__init_ts__";
29
30
  export const CURSOR_LAST_ACTIVE_KEY = "__last_active_ts__";
30
31
  export const CURSOR_MAX_IDLE_KEY = "__max_idle_ms__";
31
- export const DEFAULT_MAX_IDLE_MS = 60 * 60 * 1000; // 1 hour
32
+ export const DEFAULT_MAX_IDLE_MS = 0; // never auto-hibernate unless --max-idle is explicitly configured
32
33
 
33
34
  /**
34
35
  * Parse `--max-idle` value into milliseconds.
@@ -38,7 +39,9 @@ export const DEFAULT_MAX_IDLE_MS = 60 * 60 * 1000; // 1 hour
38
39
  export function parseMaxIdleMs(raw: string | number | undefined): number | undefined {
39
40
  if (raw === undefined || raw === null) return undefined;
40
41
  if (typeof raw === "number") {
41
- return Number.isFinite(raw) && raw >= 0 ? Math.round(raw * 1000) : undefined;
42
+ if (!Number.isFinite(raw) || raw < 0) return undefined;
43
+ const ms = Math.round(raw * 1000);
44
+ return Number.isFinite(ms) && ms <= Number.MAX_SAFE_INTEGER ? ms : undefined;
42
45
  }
43
46
  const s = String(raw).trim().toLowerCase();
44
47
  if (!s) return undefined;
@@ -50,17 +53,342 @@ export function parseMaxIdleMs(raw: string | number | undefined): number | undef
50
53
  const val = Number(m[1]);
51
54
  if (!Number.isFinite(val) || val < 0) return undefined;
52
55
  const unit = m[2] || "s";
53
- if (unit === "ms") return Math.round(val);
54
- if (unit === "s" || unit === "sec" || unit === "secs") return Math.round(val * 1000);
55
- if (unit === "m" || unit === "min" || unit === "mins") return Math.round(val * 60_000);
56
- if (unit === "h" || unit === "hr" || unit === "hrs" || unit === "hour" || unit === "hours") {
57
- return Math.round(val * 3_600_000);
58
- }
59
- if (unit === "d" || unit === "day" || unit === "days") return Math.round(val * 86_400_000);
60
- return undefined;
56
+ let ms: number;
57
+ if (unit === "ms") ms = Math.round(val);
58
+ else if (unit === "s" || unit === "sec" || unit === "secs") ms = Math.round(val * 1000);
59
+ else if (unit === "m" || unit === "min" || unit === "mins") ms = Math.round(val * 60_000);
60
+ else if (unit === "h" || unit === "hr" || unit === "hrs" || unit === "hour" || unit === "hours") {
61
+ ms = Math.round(val * 3_600_000);
62
+ } else if (unit === "d" || unit === "day" || unit === "days") {
63
+ ms = Math.round(val * 86_400_000);
64
+ } else {
65
+ return undefined;
66
+ }
67
+ return Number.isFinite(ms) && ms <= Number.MAX_SAFE_INTEGER ? ms : undefined;
61
68
  }
62
69
  const MAX_SSE_STREAMS = 3;
70
+ const MAX_SSE_LINE_CHARS = 512 * 1024;
63
71
  const MAX_SEEN_IDS = 200;
72
+ const DEFAULT_HTTP_TIMEOUT_MS = 15_000;
73
+ export const MAX_TIMER_MS = 2_147_483_647;
74
+ const MAX_STATE_FILE_BYTES = 1_048_576;
75
+ const MAX_HTTP_JSON_BYTES = 4 * 1024 * 1024;
76
+ const MAX_PID_FILE_BYTES = 64 * 1024;
77
+ const DIRECT_CHANNEL_RE = /^dm[-:]/i;
78
+ const CANONICAL_CURSOR_TS_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{9}Z$/;
79
+ const PROTOTYPE_KEYS = new Set([
80
+ "prototype",
81
+ ...Object.getOwnPropertyNames(Object.prototype).map((k) => k.toLowerCase()),
82
+ ]);
83
+ const CLI_CHANNEL_CREDENTIAL_PREFIX_RE =
84
+ /^(?:ac_|mcp_(?:at|rt|code)_|agent_key_|whsec_|mr_|sk-|sk_|rk_(?:live|test)_|gh[pousr]_|github_pat_|glpat-|xox[baprs]-|hf_|npm_|AIza|AKIA|ASIA)/i;
85
+ const CLI_ENCODED_TRAVERSAL_RE = /(?:%2f|%5c|%00|%2e%2e)/i;
86
+
87
+ export function canonicalRestCursorTimestamp(
88
+ raw: unknown,
89
+ mode: "before" | "after" = "after",
90
+ ): string | undefined {
91
+ if (typeof raw !== "string" || !raw) return undefined;
92
+ const norm = normalizeTimestampForCursor(raw, mode);
93
+ return norm && CANONICAL_CURSOR_TS_RE.test(norm) ? norm : undefined;
94
+ }
95
+
96
+ function isLoopbackHost(hostname: string): boolean {
97
+ const h = hostname.toLowerCase();
98
+ return h === "127.0.0.1" || h === "localhost" || h === "[::1]" || h === "::1";
99
+ }
100
+
101
+ function isUnsafeMetadataOrLinkLocalHost(hostname: string): boolean {
102
+ const lower = hostname.toLowerCase().replace(/^\[|\]$/g, "").replace(/\.$/, "");
103
+ if (
104
+ !lower ||
105
+ lower === "0" ||
106
+ lower === "0.0.0.0" ||
107
+ /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(lower) ||
108
+ lower === "::" ||
109
+ lower === "100.100.100.200" ||
110
+ lower === "fd00:ec2::254" ||
111
+ lower === "metadata.google.internal" ||
112
+ lower.endsWith(".metadata.google.internal") ||
113
+ lower === "metadata" ||
114
+ lower === "metadata.goog" ||
115
+ lower.endsWith(".metadata.goog") ||
116
+ lower === "instance-data"
117
+ ) {
118
+ return true;
119
+ }
120
+ if (/^169\.254\.\d{1,3}\.\d{1,3}$/.test(lower)) return true;
121
+ if (/^fe[89ab][0-9a-f]:/.test(lower)) return true;
122
+ if (lower.startsWith("::ffff:")) {
123
+ const tail = lower.slice("::ffff:".length);
124
+ const tailParts = /^0:(?:[0-9a-f]{1,4}:|\d{1,3}\.)/.test(tail) ? tail.slice(2) : tail;
125
+ if (
126
+ /^169\.254\.\d{1,3}\.\d{1,3}$/.test(tailParts) ||
127
+ /^0\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(tailParts) ||
128
+ tailParts === "100.100.100.200" ||
129
+ tailParts === "0.0.0.0"
130
+ ) {
131
+ return true;
132
+ }
133
+ const hexMatch = tailParts.match(/^([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);
134
+ if (hexMatch) {
135
+ const hi = parseInt(hexMatch[1]!, 16);
136
+ const lo = parseInt(hexMatch[2]!, 16);
137
+ if (
138
+ (((hi >> 8) & 0xff) === 169 && (hi & 0xff) === 254) ||
139
+ (hi === 0x6464 && lo === 0x64c8) ||
140
+ ((hi >> 8) & 0xff) === 0
141
+ ) {
142
+ return true;
143
+ }
144
+ }
145
+ }
146
+ return false;
147
+ }
148
+
149
+ function isAllowedDarwinSystemLink(dirPath: string): boolean {
150
+ if (process.platform !== "darwin") return false;
151
+ if (dirPath !== "/var" && dirPath !== "/tmp" && dirPath !== "/etc") return false;
152
+ try {
153
+ const privStat = lstatSync("/private");
154
+ if (privStat.isSymbolicLink() || !privStat.isDirectory()) return false;
155
+ const targetStat = lstatSync(`/private${dirPath}`);
156
+ if (targetStat.isSymbolicLink() || !targetStat.isDirectory()) return false;
157
+ return readlinkSync(dirPath) === `private${dirPath}`;
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+
163
+ export function hasSafeDirChain(dirPath: string): boolean {
164
+ if (typeof dirPath !== "string" || !dirPath.trim() || /[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(dirPath)) {
165
+ return false;
166
+ }
167
+ // Guard against `symlink_dir/..` lexical collapse before `resolve(dirPath)`.
168
+ if (/(?:^|[\\/])\.\.(?:[\\/]|$)/.test(dirPath)) {
169
+ const rawBase = isAbsolute(dirPath) ? parse(dirPath).root : resolve(".");
170
+ const rawRel = isAbsolute(dirPath) ? dirPath.slice(rawBase.length) : dirPath;
171
+ let rawCur = rawBase.replace(/[\\/]+$/, "") || "/";
172
+ for (const seg of rawRel.split(/[\\/]+/).filter(Boolean)) {
173
+ if (seg === ".") continue;
174
+ if (seg === "..") {
175
+ rawCur = dirname(rawCur);
176
+ continue;
177
+ }
178
+ rawCur = rawCur === "/" ? `/${seg}` : `${rawCur}/${seg}`;
179
+ try {
180
+ const st = lstatSync(rawCur);
181
+ if (st.isSymbolicLink() && !isAllowedDarwinSystemLink(rawCur)) return false;
182
+ if (!st.isSymbolicLink() && !st.isDirectory()) return false;
183
+ } catch (err: any) {
184
+ if (err && err.code === "ENOENT") break;
185
+ return false;
186
+ }
187
+ }
188
+ }
189
+ const abs = resolve(dirPath);
190
+ const root = parse(abs).root;
191
+ const rel = abs.slice(root.length);
192
+ const segments = rel.split(/[\\/]+/).filter(Boolean);
193
+ let cur = root;
194
+ for (let i = 0; i < segments.length; i++) {
195
+ cur = join(cur, segments[i]!);
196
+ let st: Stats;
197
+ try {
198
+ st = lstatSync(cur);
199
+ } catch (err: any) {
200
+ if (err && err.code === "ENOENT") return true;
201
+ return false;
202
+ }
203
+ if (st.isSymbolicLink()) {
204
+ if (isAllowedDarwinSystemLink(cur)) continue;
205
+ return false;
206
+ }
207
+ if (!st.isDirectory()) return false;
208
+ }
209
+ return true;
210
+ }
211
+
212
+ export function validateSafeRestBaseUrl(rawUrl: string): string {
213
+ if (typeof rawUrl !== "string") throw new Error("Invalid AgentsChat REST URL");
214
+ const trimmed = rawUrl.trim().replace(/\/+$/, "");
215
+ if (!trimmed || trimmed.length > 2048 || /[\x00-\x20\x7f-\x9f\u2028\u2029"<>\\]/.test(trimmed) || /:0(?:\/|$)/.test(trimmed)) {
216
+ throw new Error("Invalid AgentsChat REST URL");
217
+ }
218
+ let parsed: URL;
219
+ try {
220
+ parsed = new URL(trimmed);
221
+ } catch {
222
+ throw new Error("Invalid AgentsChat REST URL");
223
+ }
224
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) {
225
+ throw new Error("Invalid AgentsChat REST URL");
226
+ }
227
+ if (isUnsafeMetadataOrLinkLocalHost(parsed.hostname)) {
228
+ throw new Error("Refusing cloud-metadata, link-local, or unspecified AgentsChat REST URL");
229
+ }
230
+ if (parsed.protocol === "https:") return trimmed;
231
+ if (
232
+ parsed.protocol === "http:" &&
233
+ (isLoopbackHost(parsed.hostname) || process.env.AGENTSCHAT_ALLOW_INSECURE_HTTP === "1")
234
+ ) {
235
+ return trimmed;
236
+ }
237
+ throw new Error("Refusing insecure non-loopback HTTP AgentsChat REST URL");
238
+ }
239
+
240
+ export function isSafeCliChannelId(channelId: unknown): channelId is string {
241
+ if (typeof channelId !== "string") return false;
242
+ if (
243
+ channelId.length < 1 ||
244
+ channelId.length > 128 ||
245
+ channelId.trim() !== channelId ||
246
+ /[\x00-\x1f\x7f-\x9f\u2028\u2029/\\\s]/.test(channelId) ||
247
+ channelId === "." ||
248
+ channelId.includes("..") ||
249
+ CLI_ENCODED_TRAVERSAL_RE.test(channelId) ||
250
+ CLI_CHANNEL_CREDENTIAL_PREFIX_RE.test(channelId) ||
251
+ PROTOTYPE_KEYS.has(channelId.toLowerCase())
252
+ ) {
253
+ return false;
254
+ }
255
+ return true;
256
+ }
257
+
258
+ function validateSafeBearerToken(token: unknown): string {
259
+ if (typeof token !== "string") throw new Error("Invalid authentication token");
260
+ const trimmed = token.trim();
261
+ if (!trimmed || trimmed.length > 4096 || /[\x00-\x20\x7f-\x9f\u2028\u2029]/.test(trimmed)) {
262
+ throw new Error("Invalid authentication token");
263
+ }
264
+ return trimmed;
265
+ }
266
+
267
+ function ensureRealDirectory(dir: string): void {
268
+ if (!hasSafeDirChain(dir)) {
269
+ throw new Error("Refusing symlink or non-directory state root");
270
+ }
271
+ const pre = lstatSync(dir, { throwIfNoEntry: false });
272
+ if (pre && (pre.isSymbolicLink() || !pre.isDirectory())) {
273
+ throw new Error("Refusing symlink or non-directory state root");
274
+ }
275
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
276
+ const post = lstatSync(dir);
277
+ if (post.isSymbolicLink() || !post.isDirectory() || !hasSafeDirChain(dir)) {
278
+ throw new Error("Refusing symlink or non-directory state root");
279
+ }
280
+ }
281
+
282
+ function parseSafeResponseJsonText(text: string): any {
283
+ const parsed = JSON.parse(text);
284
+ if (
285
+ parsed &&
286
+ typeof parsed === "object" &&
287
+ !Array.isArray(parsed) &&
288
+ Object.prototype.hasOwnProperty.call(parsed, "__proto__")
289
+ ) {
290
+ throw new Error("Refusing prototype-polluting HTTP JSON response");
291
+ }
292
+ return parsed;
293
+ }
294
+
295
+ export async function readBoundedResponseJson(res: Response, maxBytes = MAX_HTTP_JSON_BYTES): Promise<any> {
296
+ const cl = Number(res.headers?.get("content-length") ?? "");
297
+ if (Number.isFinite(cl) && cl > maxBytes) {
298
+ await res.body?.cancel().catch(() => {});
299
+ throw new Error("HTTP JSON response exceeds byte limit");
300
+ }
301
+ if (!res.body) {
302
+ const text = await res.text();
303
+ if (Buffer.byteLength(text, "utf8") > maxBytes) {
304
+ throw new Error("HTTP JSON response exceeds byte limit");
305
+ }
306
+ return parseSafeResponseJsonText(text);
307
+ }
308
+ const reader = res.body.getReader();
309
+ const chunks: Uint8Array[] = [];
310
+ let total = 0;
311
+ try {
312
+ while (true) {
313
+ const { done, value } = await reader.read();
314
+ if (done) break;
315
+ if (value) {
316
+ total += value.byteLength;
317
+ if (total > maxBytes) {
318
+ await reader.cancel().catch(() => {});
319
+ throw new Error("HTTP JSON response exceeds byte limit");
320
+ }
321
+ chunks.push(value);
322
+ }
323
+ }
324
+ } finally {
325
+ try {
326
+ reader.releaseLock();
327
+ } catch {}
328
+ }
329
+ return parseSafeResponseJsonText(Buffer.concat(chunks, total).toString("utf8"));
330
+ }
331
+
332
+ export function clampTimerMs(raw: unknown, fallback: number, minMs = 0): number {
333
+ if (typeof raw !== "number" || !Number.isFinite(raw)) return fallback;
334
+ const floored = Math.floor(raw);
335
+ if (floored < minMs) return fallback;
336
+ return Math.min(MAX_TIMER_MS, floored);
337
+ }
338
+
339
+ async function fetchWithDeadline(
340
+ f: typeof fetch,
341
+ url: string,
342
+ init: RequestInit,
343
+ timeoutMs: number,
344
+ parentSignal?: AbortSignal,
345
+ ): Promise<Response> {
346
+ if (parentSignal?.aborted) {
347
+ const err = new Error("Aborted");
348
+ err.name = "AbortError";
349
+ throw err;
350
+ }
351
+ const ctrl = new AbortController();
352
+ const onParentAbort = () => ctrl.abort(parentSignal?.reason);
353
+ if (parentSignal) {
354
+ parentSignal.addEventListener("abort", onParentAbort, { once: true });
355
+ }
356
+ const safeTimeoutMs =
357
+ typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
358
+ ? Math.min(MAX_TIMER_MS, Math.floor(timeoutMs))
359
+ : 0;
360
+ const timer =
361
+ safeTimeoutMs > 0
362
+ ? setTimeout(() => {
363
+ const err = new Error(`HTTP request timed out after ${safeTimeoutMs}ms`);
364
+ err.name = "TimeoutError";
365
+ ctrl.abort(err);
366
+ }, safeTimeoutMs)
367
+ : null;
368
+ timer?.unref?.();
369
+ try {
370
+ return await f(url, { redirect: "error", ...init, signal: ctrl.signal });
371
+ } finally {
372
+ if (timer) clearTimeout(timer);
373
+ if (parentSignal) parentSignal.removeEventListener("abort", onParentAbort);
374
+ }
375
+ }
376
+
377
+ function sleepAbortable(ms: number, signal: AbortSignal): Promise<void> {
378
+ if (signal.aborted) return Promise.resolve();
379
+ return new Promise((resolve) => {
380
+ const onAbort = () => {
381
+ clearTimeout(t);
382
+ resolve();
383
+ };
384
+ const t = setTimeout(() => {
385
+ signal.removeEventListener("abort", onAbort);
386
+ resolve();
387
+ }, ms);
388
+ t.unref?.();
389
+ signal.addEventListener("abort", onAbort, { once: true });
390
+ });
391
+ }
64
392
 
65
393
  export interface JoinChannelResult {
66
394
  ok: boolean;
@@ -75,6 +403,7 @@ export interface SendMessageResult {
75
403
  ok: boolean;
76
404
  status: number;
77
405
  id?: string;
406
+ timestamp?: string;
78
407
  agent_id: string;
79
408
  channel_id: string;
80
409
  in_reply_to?: string;
@@ -105,9 +434,11 @@ export interface WakeOnceEvent {
105
434
  should_rearm?: boolean;
106
435
  }
107
436
 
108
- function loadSeenIds(file: string): string[] {
109
- if (!existsSync(file)) return [];
437
+ export function loadSeenIds(file: string): string[] {
110
438
  try {
439
+ if (!hasSafeDirChain(dirname(file))) return [];
440
+ const stat = lstatSync(file);
441
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_STATE_FILE_BYTES) return [];
111
442
  const parsed = JSON.parse(readFileSync(file, "utf8"));
112
443
  return Array.isArray(parsed) ? parsed.filter((x) => typeof x === "string") : [];
113
444
  } catch {
@@ -117,26 +448,102 @@ function loadSeenIds(file: string): string[] {
117
448
 
118
449
  function saveSeenIds(file: string, ids: Iterable<string>): void {
119
450
  try {
120
- mkdirSync(dirname(file), { recursive: true });
451
+ ensureRealDirectory(dirname(file));
121
452
  const list = [...ids].slice(-MAX_SEEN_IDS);
122
453
  safeWriteProfile(file, list);
123
454
  } catch {}
124
455
  }
125
456
 
126
- function loadJsonMap(file: string): Record<string, string> {
127
- if (!existsSync(file)) return {};
457
+ export function loadJsonMap(file: string): Record<string, string> {
458
+ const out: Record<string, string> = Object.create(null);
128
459
  try {
460
+ if (!hasSafeDirChain(dirname(file))) return out;
461
+ const stat = lstatSync(file);
462
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_STATE_FILE_BYTES) return out;
129
463
  const raw = JSON.parse(readFileSync(file, "utf8"));
130
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
131
- return raw as Record<string, string>;
464
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
465
+ for (const [k, v] of Object.entries(raw)) {
466
+ if (!k || PROTOTYPE_KEYS.has(k.toLowerCase()) || typeof v !== "string") continue;
467
+ out[k] = v;
468
+ }
469
+ return out;
470
+ } catch {
471
+ return out;
472
+ }
473
+ }
474
+
475
+ export function acquireWakePidFile(
476
+ wakePidFile: string,
477
+ pid = process.pid,
478
+ killFn: (targetPid: number, sig: NodeJS.Signals) => unknown = process.kill,
479
+ ): boolean {
480
+ let tmp = "";
481
+ let created = false;
482
+ try {
483
+ const dir = dirname(wakePidFile);
484
+ if (!hasSafeDirChain(dir)) return false;
485
+ const dirStat = lstatSync(dir);
486
+ if (dirStat.isSymbolicLink() || !dirStat.isDirectory()) return false;
487
+ try {
488
+ const existing = lstatSync(wakePidFile);
489
+ if (existing.isSymbolicLink() || !existing.isFile()) return false;
490
+ if (existing.size <= MAX_PID_FILE_BYTES) {
491
+ const raw = readFileSync(wakePidFile, "utf8").trim();
492
+ if (/^\d+$/.test(raw)) {
493
+ const oldPid = Number(raw);
494
+ if (Number.isSafeInteger(oldPid) && oldPid > 1 && oldPid !== pid) {
495
+ try {
496
+ killFn(oldPid, "SIGTERM");
497
+ } catch {}
498
+ }
499
+ }
500
+ }
501
+ } catch (e: any) {
502
+ if (e?.code !== "ENOENT") return false;
503
+ }
504
+ tmp = `${wakePidFile}.${pid}.${randomBytes(4).toString("hex")}.tmp`;
505
+ writeFileSync(tmp, `${pid}\n`, { mode: 0o600, flag: "wx" });
506
+ created = true;
507
+ const recheckDir = lstatSync(dir, { throwIfNoEntry: false });
508
+ const recheckTarget = lstatSync(wakePidFile, { throwIfNoEntry: false });
509
+ if (
510
+ !hasSafeDirChain(dir) ||
511
+ !recheckDir ||
512
+ recheckDir.isSymbolicLink() ||
513
+ !recheckDir.isDirectory() ||
514
+ (recheckTarget && (recheckTarget.isSymbolicLink() || !recheckTarget.isFile()))
515
+ ) {
516
+ unlinkSync(tmp);
517
+ created = false;
518
+ return false;
519
+ }
520
+ renameSync(tmp, wakePidFile);
521
+ created = false;
522
+ return true;
132
523
  } catch {
133
- return {};
524
+ if (created && tmp) {
525
+ try {
526
+ unlinkSync(tmp);
527
+ } catch {}
528
+ }
529
+ return false;
134
530
  }
135
531
  }
136
532
 
533
+ export function releaseWakePidFile(wakePidFile: string, pid = process.pid): void {
534
+ try {
535
+ if (!hasSafeDirChain(dirname(wakePidFile))) return;
536
+ const stat = lstatSync(wakePidFile);
537
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_PID_FILE_BYTES) return;
538
+ if (readFileSync(wakePidFile, "utf8").trim() === String(pid)) {
539
+ unlinkSync(wakePidFile);
540
+ }
541
+ } catch {}
542
+ }
543
+
137
544
  function saveJsonMap(file: string, data: Record<string, string>): void {
138
545
  try {
139
- mkdirSync(dirname(file), { recursive: true });
546
+ ensureRealDirectory(dirname(file));
140
547
  safeWriteProfile(file, data);
141
548
  } catch {}
142
549
  }
@@ -151,20 +558,20 @@ export function advanceChannelReadCursor(opts: {
151
558
  warn?: Warn;
152
559
  }): void {
153
560
  const { configDir, agentId, channelId, timestamp } = opts;
154
- if (!agentId || !channelId || !timestamp) return;
561
+ const nextNorm = canonicalRestCursorTimestamp(timestamp, "after");
562
+ if (!agentId || !isSafeCliChannelId(channelId) || !nextNorm) return;
155
563
  const warn = opts.warn ?? ((m: string) => process.stderr.write(m));
156
- mkdirSync(configDir, { recursive: true });
564
+ ensureRealDirectory(configDir);
157
565
 
158
- const lastSeenFile = join(configDir, `last-seen-msg-ts-${agentId}.json`);
566
+ const lastSeenFile = cursorFileForAgent(configDir, agentId);
159
567
  const cursor = loadCursor(lastSeenFile, warn);
160
568
  const prev = cursor.get(channelId) || "";
161
- const nextNorm = normalizeTimestampForCursor(timestamp, "after") || timestamp;
162
- const prevNorm = normalizeTimestampForCursor(prev, "after") || prev;
569
+ const prevNorm = canonicalRestCursorTimestamp(prev, "after");
163
570
  cursor.set(CURSOR_LAST_ACTIVE_KEY, timestamp);
164
571
  if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
165
572
  cursor.set(CURSOR_MAX_IDLE_KEY, String(Math.round(opts.maxIdleMs)));
166
573
  }
167
- if (!prev || nextNorm > prevNorm) {
574
+ if (!prevNorm || nextNorm > prevNorm) {
168
575
  cursor.set(channelId, timestamp);
169
576
  }
170
577
  persistCursor(lastSeenFile, cursor, warn);
@@ -173,8 +580,8 @@ export function advanceChannelReadCursor(opts: {
173
580
  const readCursors = loadJsonMap(readCursorsFile);
174
581
  const scopedKey = `${agentId}:${channelId}`;
175
582
  const prevRead = readCursors[scopedKey] || readCursors[channelId] || "";
176
- const prevReadNorm = normalizeTimestampForCursor(prevRead, "after") || prevRead;
177
- if (!prevRead || nextNorm > prevReadNorm) {
583
+ const prevReadNorm = canonicalRestCursorTimestamp(prevRead, "after");
584
+ if (!prevReadNorm || nextNorm > prevReadNorm) {
178
585
  readCursors[scopedKey] = timestamp;
179
586
  readCursors[channelId] = timestamp;
180
587
  saveJsonMap(readCursorsFile, readCursors);
@@ -187,21 +594,31 @@ export async function joinChannelRest(opts: {
187
594
  agentId: string;
188
595
  token: string;
189
596
  channelId: string;
597
+ timeoutMs?: number;
190
598
  fetchImpl?: typeof fetch;
191
599
  }): Promise<JoinChannelResult> {
192
600
  const f = opts.fetchImpl ?? fetch;
193
- const baseUrl = opts.restUrl.replace(/\/$/, "");
194
- const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/join`;
195
601
  try {
196
- const res = await f(url, {
197
- method: "POST",
198
- headers: {
199
- Authorization: `Bearer ${opts.token}`,
200
- "Content-Type": "application/json",
602
+ const baseUrl = validateSafeRestBaseUrl(opts.restUrl);
603
+ const safeToken = validateSafeBearerToken(opts.token);
604
+ if (!isSafeCliChannelId(opts.channelId)) {
605
+ throw new Error("Invalid channel_id");
606
+ }
607
+ const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/join`;
608
+ const res = await fetchWithDeadline(
609
+ f,
610
+ url,
611
+ {
612
+ method: "POST",
613
+ headers: {
614
+ Authorization: `Bearer ${safeToken}`,
615
+ "Content-Type": "application/json",
616
+ },
617
+ body: JSON.stringify({ sender_id: opts.agentId }),
201
618
  },
202
- body: JSON.stringify({ sender_id: opts.agentId }),
203
- });
204
- const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
619
+ opts.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
620
+ );
621
+ const data = (await readBoundedResponseJson(res).catch(() => ({}))) as Record<string, unknown>;
205
622
  if (res.ok) {
206
623
  return {
207
624
  ok: true,
@@ -216,7 +633,7 @@ export async function joinChannelRest(opts: {
216
633
  status: res.status,
217
634
  agent_id: opts.agentId,
218
635
  channel_id: opts.channelId,
219
- error: String(data.error ?? data.message ?? `HTTP ${res.status}`),
636
+ error: redactSecrets(String(data.error ?? data.message ?? `HTTP ${res.status}`)),
220
637
  };
221
638
  } catch (e: any) {
222
639
  return {
@@ -224,7 +641,7 @@ export async function joinChannelRest(opts: {
224
641
  status: 0,
225
642
  agent_id: opts.agentId,
226
643
  channel_id: opts.channelId,
227
- error: String(e?.message || e),
644
+ error: redactSecrets(String(e?.message || e)),
228
645
  };
229
646
  }
230
647
  }
@@ -239,35 +656,62 @@ export async function sendRestMessage(opts: {
239
656
  text: string;
240
657
  replyTo?: string;
241
658
  maxIdleMs?: number;
659
+ timeoutMs?: number;
242
660
  fetchImpl?: typeof fetch;
243
661
  warn?: Warn;
244
662
  }): Promise<SendMessageResult> {
245
663
  const f = opts.fetchImpl ?? fetch;
246
- const baseUrl = opts.restUrl.replace(/\/$/, "");
247
664
  const cleanText = redactSecrets(opts.text);
248
- const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/messages`;
249
665
  try {
250
- const res = await f(url, {
251
- method: "POST",
252
- headers: {
253
- Authorization: `Bearer ${opts.token}`,
254
- "Content-Type": "application/json",
666
+ const baseUrl = validateSafeRestBaseUrl(opts.restUrl);
667
+ const safeToken = validateSafeBearerToken(opts.token);
668
+ if (!isSafeCliChannelId(opts.channelId)) {
669
+ throw new Error("Invalid channel_id");
670
+ }
671
+ let safeReplyTo: string | undefined;
672
+ if (opts.replyTo !== undefined && opts.replyTo !== "") {
673
+ if (
674
+ typeof opts.replyTo !== "string" ||
675
+ opts.replyTo.length > 256 ||
676
+ /[\x00-\x1f\x7f-\x9f\u2028\u2029\s]/.test(opts.replyTo) ||
677
+ PROTOTYPE_KEYS.has(opts.replyTo.toLowerCase())
678
+ ) {
679
+ throw new Error("Invalid in_reply_to message_id");
680
+ }
681
+ safeReplyTo = opts.replyTo;
682
+ }
683
+ const url = `${baseUrl}/api/channels/${encodeURIComponent(opts.channelId)}/messages`;
684
+ const res = await fetchWithDeadline(
685
+ f,
686
+ url,
687
+ {
688
+ method: "POST",
689
+ headers: {
690
+ Authorization: `Bearer ${safeToken}`,
691
+ "Content-Type": "application/json",
692
+ },
693
+ body: JSON.stringify({
694
+ sender_id: opts.agentId,
695
+ sender_type: "agent",
696
+ content_type: "text",
697
+ content: cleanText,
698
+ ...(safeReplyTo ? { in_reply_to: safeReplyTo } : {}),
699
+ }),
255
700
  },
256
- body: JSON.stringify({
257
- sender_id: opts.agentId,
258
- sender_type: "agent",
259
- content_type: "text",
260
- content: cleanText,
261
- ...(opts.replyTo ? { in_reply_to: opts.replyTo } : {}),
262
- }),
263
- });
264
- const data = (await res.json().catch(() => ({}))) as Record<string, unknown>;
701
+ opts.timeoutMs ?? DEFAULT_HTTP_TIMEOUT_MS,
702
+ );
703
+ const data = (await readBoundedResponseJson(res).catch(() => ({}))) as Record<string, unknown>;
265
704
  if (res.ok) {
705
+ const serverTs =
706
+ typeof data.timestamp === "string" && canonicalRestCursorTimestamp(data.timestamp.trim(), "after")
707
+ ? data.timestamp.trim()
708
+ : undefined;
709
+ const cursorTs = serverTs ?? new Date().toISOString();
266
710
  advanceChannelReadCursor({
267
711
  configDir: opts.configDir,
268
712
  agentId: opts.agentId,
269
713
  channelId: opts.channelId,
270
- timestamp: new Date().toISOString(),
714
+ timestamp: cursorTs,
271
715
  maxIdleMs: opts.maxIdleMs,
272
716
  warn: opts.warn,
273
717
  });
@@ -275,6 +719,7 @@ export async function sendRestMessage(opts: {
275
719
  ok: true,
276
720
  status: res.status,
277
721
  id: typeof data.id === "string" ? data.id : undefined,
722
+ ...(serverTs ? { timestamp: serverTs } : {}),
278
723
  agent_id: opts.agentId,
279
724
  channel_id: opts.channelId,
280
725
  ...(opts.replyTo ? { in_reply_to: opts.replyTo } : {}),
@@ -285,7 +730,7 @@ export async function sendRestMessage(opts: {
285
730
  status: res.status,
286
731
  agent_id: opts.agentId,
287
732
  channel_id: opts.channelId,
288
- error: String(data.error ?? data.message ?? `HTTP ${res.status}`),
733
+ error: redactSecrets(String(data.error ?? data.message ?? `HTTP ${res.status}`)),
289
734
  };
290
735
  } catch (e: any) {
291
736
  return {
@@ -293,7 +738,7 @@ export async function sendRestMessage(opts: {
293
738
  status: 0,
294
739
  agent_id: opts.agentId,
295
740
  channel_id: opts.channelId,
296
- error: String(e?.message || e),
741
+ error: redactSecrets(String(e?.message || e)),
297
742
  };
298
743
  }
299
744
  }
@@ -314,7 +759,7 @@ export function isMessageAddressedToAgent(
314
759
  if (isOwnLoopTick) return true;
315
760
 
316
761
  const channelId = String(msg.channel_id || "");
317
- if (channelId.startsWith("dm-")) return true;
762
+ if (DIRECT_CHANNEL_RE.test(channelId)) return true;
318
763
  if (Array.isArray(msg.mentioned_ids) && msg.mentioned_ids.includes(agentId)) return true;
319
764
  const content = String(msg.content || "");
320
765
  if (matchesMention(content, agentId)) return true;
@@ -335,6 +780,7 @@ export async function wakeOnce(opts: {
335
780
  token: string;
336
781
  channels?: string[];
337
782
  timeoutMs?: number;
783
+ requestTimeoutMs?: number;
338
784
  maxIdleMs?: number;
339
785
  pollIntervalMs?: number;
340
786
  enableSse?: boolean;
@@ -345,41 +791,44 @@ export async function wakeOnce(opts: {
345
791
  const f = opts.fetchImpl ?? fetch;
346
792
  const warn = opts.warn ?? ((m: string) => process.stderr.write(m));
347
793
  const nowIso = opts.nowIso ?? (() => new Date().toISOString());
348
- const baseUrl = opts.restUrl.replace(/\/$/, "");
349
- const { configDir, agentId, displayName, token } = opts;
350
- const timeoutMs = opts.timeoutMs ?? 240_000;
351
- const pollIntervalMs = opts.pollIntervalMs ?? 15_000;
794
+ const baseUrl = validateSafeRestBaseUrl(opts.restUrl);
795
+ const token = validateSafeBearerToken(opts.token);
796
+ const { configDir, agentId, displayName } = opts;
797
+ const timeoutMs =
798
+ opts.timeoutMs !== undefined && Number.isFinite(opts.timeoutMs)
799
+ ? opts.timeoutMs > 0
800
+ ? Math.min(MAX_TIMER_MS, Math.floor(opts.timeoutMs))
801
+ : 0
802
+ : 240_000;
803
+ const requestTimeoutMs = clampTimerMs(opts.requestTimeoutMs, DEFAULT_HTTP_TIMEOUT_MS, 0);
804
+ const pollIntervalMs = clampTimerMs(opts.pollIntervalMs, 15_000, 10);
352
805
  const enableSse = opts.enableSse ?? true;
353
806
 
354
- mkdirSync(configDir, { recursive: true });
355
- const lastSeenFile = join(configDir, `last-seen-msg-ts-${agentId}.json`);
356
- const seenIdsFile = join(configDir, `wake-seen-ids-${agentId}.json`);
807
+ ensureRealDirectory(configDir);
808
+ const safeSlug = safeAgentCursorSlug(agentId);
809
+ const lastSeenFile = cursorFileForAgent(configDir, agentId);
810
+ const seenIdsFile = join(configDir, `wake-seen-ids-${safeSlug}.json`);
357
811
  const mentionTsFile = join(configDir, "mention-timestamps.json");
358
- const wakePidFile = join(configDir, `wake-once-${agentId}.pid`);
812
+ const wakePidFile = join(configDir, `wake-once-${safeSlug}.pid`);
813
+ let wrotePidFile = false;
359
814
 
360
815
  // When running against live network (not unit test mock fetch), ensure at most one wake-once listener per agent
361
816
  if (!opts.fetchImpl) {
362
- try {
363
- if (existsSync(wakePidFile)) {
364
- const oldPid = parseInt(readFileSync(wakePidFile, "utf-8").trim(), 10);
365
- if (Number.isFinite(oldPid) && oldPid > 1 && oldPid !== process.pid) {
366
- try {
367
- process.kill(oldPid, "SIGTERM");
368
- } catch {}
369
- }
370
- }
371
- writeFileSync(wakePidFile, `${process.pid}\n`, { mode: 0o600 });
372
- } catch {}
817
+ wrotePidFile = acquireWakePidFile(wakePidFile);
373
818
  }
374
819
 
375
820
  const cursor = loadCursor(lastSeenFile, warn);
821
+ const fallbackNowIso = () => {
822
+ const candidate = nowIso();
823
+ return canonicalRestCursorTimestamp(candidate, "after") ? candidate : new Date().toISOString();
824
+ };
376
825
  let cursorDirty = false;
377
- if (!cursor.get(CURSOR_INIT_KEY)) {
378
- cursor.set(CURSOR_INIT_KEY, nowIso());
826
+ if (!canonicalRestCursorTimestamp(cursor.get(CURSOR_INIT_KEY), "after")) {
827
+ cursor.set(CURSOR_INIT_KEY, fallbackNowIso());
379
828
  cursorDirty = true;
380
829
  }
381
- if (!cursor.get(CURSOR_LAST_ACTIVE_KEY)) {
382
- cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
830
+ if (!canonicalRestCursorTimestamp(cursor.get(CURSOR_LAST_ACTIVE_KEY), "after")) {
831
+ cursor.set(CURSOR_LAST_ACTIVE_KEY, fallbackNowIso());
383
832
  cursorDirty = true;
384
833
  }
385
834
  if (opts.maxIdleMs !== undefined && Number.isFinite(opts.maxIdleMs) && opts.maxIdleMs >= 0) {
@@ -401,7 +850,9 @@ export async function wakeOnce(opts: {
401
850
  ? savedMaxIdleMs
402
851
  : DEFAULT_MAX_IDLE_MS;
403
852
  const initTs = cursor.get(CURSOR_INIT_KEY)!;
404
- const initTsNorm = normalizeTimestampForCursor(initTs, "after") || initTs;
853
+ const initTsNorm =
854
+ canonicalRestCursorTimestamp(initTs, "after") ??
855
+ normalizeTimestampForCursor(new Date().toISOString(), "after")!;
405
856
 
406
857
  const seenSet = new Set<string>(loadSeenIds(seenIdsFile));
407
858
  const headers = {
@@ -416,6 +867,7 @@ export async function wakeOnce(opts: {
416
867
  agentId,
417
868
  token,
418
869
  channelId: ch.trim(),
870
+ timeoutMs: requestTimeoutMs,
419
871
  fetchImpl: f,
420
872
  });
421
873
  }
@@ -425,57 +877,82 @@ export async function wakeOnce(opts: {
425
877
  const abortCtrl = new AbortController();
426
878
 
427
879
  async function buildGroupContextPrefix(channelId: string, triggerMsgId: string, triggerTs: string): Promise<string> {
428
- if (channelId.startsWith("dm-")) return "";
880
+ if (DIRECT_CHANNEL_RE.test(channelId)) return "";
429
881
  const mentionMap = loadJsonMap(mentionTsFile);
430
882
  const mentionKey = `${agentId}:${channelId}`;
431
- const lastTs = mentionMap[mentionKey] || mentionMap[channelId] || "";
883
+ const rawLastTs = mentionMap[mentionKey] || mentionMap[channelId] || "";
884
+ const lastTs = canonicalRestCursorTimestamp(rawLastTs, "after") ? rawLastTs : "";
432
885
  const params = `limit=50${lastTs ? "&after=" + encodeURIComponent(lastTs) : ""}`;
433
886
  let prefix = "";
434
887
  try {
435
- const res = await f(`${baseUrl}/api/channels/${encodeURIComponent(channelId)}/messages?${params}`, {
436
- headers,
437
- signal: abortCtrl.signal,
438
- });
888
+ const res = await fetchWithDeadline(
889
+ f,
890
+ `${baseUrl}/api/channels/${encodeURIComponent(channelId)}/messages?${params}`,
891
+ { headers },
892
+ requestTimeoutMs,
893
+ abortCtrl.signal,
894
+ );
439
895
  if (res.ok) {
440
- const data = (await res.json()) as { messages?: any[] };
896
+ const data = (await readBoundedResponseJson(res)) as { messages?: any[] };
441
897
  const msgs = (data.messages || []).filter(
442
898
  (m: any) => m && m.id !== triggerMsgId && m.content !== "__typing__",
443
899
  );
444
900
  const trimmed = msgs.slice(-20);
445
901
  if (trimmed.length > 0) {
446
902
  const context = trimmed
447
- .map((m: any) => `${redactParticipantPii(m.sender_id || "?")}: ${String(m.content || "").slice(0, 500)}${formatWakeAttachments(m.attachments)}`)
903
+ .map(
904
+ (m: any) =>
905
+ `${redactParticipantPii(m.sender_id || "?")}: ${redactSecrets(String(m.content || "").slice(0, 500))}${formatWakeAttachments(m.attachments)}`,
906
+ )
448
907
  .join("\n");
449
908
  prefix = `[频道上下文 - 最近 ${trimmed.length} 条消息]\n${context}\n\n[你被 @mention 了,请回复]\n`;
450
909
  }
910
+ } else {
911
+ await res.body?.cancel().catch(() => {});
451
912
  }
452
913
  } catch {}
453
- if (triggerTs) {
454
- mentionMap[mentionKey] = triggerTs;
455
- mentionMap[channelId] = triggerTs;
456
- saveJsonMap(mentionTsFile, mentionMap);
914
+ const triggerNorm = canonicalRestCursorTimestamp(triggerTs, "after");
915
+ if (triggerNorm) {
916
+ const prevNorm = canonicalRestCursorTimestamp(rawLastTs, "after");
917
+ if (!prevNorm || triggerNorm > prevNorm) {
918
+ mentionMap[mentionKey] = triggerTs;
919
+ mentionMap[channelId] = triggerTs;
920
+ saveJsonMap(mentionTsFile, mentionMap);
921
+ }
457
922
  }
458
923
  return prefix;
459
924
  }
460
925
 
461
926
  async function finalizeWake(channelId: string, batch: any[]): Promise<WakeOnceEvent> {
462
927
  const lastMsg = batch[batch.length - 1]!;
928
+ let maxValidBatchTs = "";
929
+ let maxValidBatchNorm = "";
463
930
  for (const m of batch) {
464
931
  if (typeof m.id === "string") seenSet.add(m.id);
932
+ const mNorm = canonicalRestCursorTimestamp(m.timestamp, "after");
933
+ if (mNorm && mNorm > maxValidBatchNorm) {
934
+ maxValidBatchNorm = mNorm;
935
+ maxValidBatchTs = String(m.timestamp);
936
+ }
465
937
  }
466
938
  saveSeenIds(seenIdsFile, seenSet);
467
939
 
468
- if (typeof lastMsg.timestamp === "string" && lastMsg.timestamp) {
469
- cursor.set(channelId, lastMsg.timestamp);
470
- cursor.set(CURSOR_LAST_ACTIVE_KEY, nowIso());
940
+ cursor.set(CURSOR_LAST_ACTIVE_KEY, fallbackNowIso());
941
+ if (maxValidBatchNorm) {
942
+ const prevNorm = canonicalRestCursorTimestamp(cursor.get(channelId), "after");
943
+ if (!prevNorm || maxValidBatchNorm > prevNorm) {
944
+ cursor.set(channelId, maxValidBatchTs);
945
+ }
471
946
  persistCursor(lastSeenFile, cursor, warn);
472
947
  advanceChannelReadCursor({
473
948
  configDir,
474
949
  agentId,
475
950
  channelId,
476
- timestamp: lastMsg.timestamp,
951
+ timestamp: maxValidBatchTs,
477
952
  warn,
478
953
  });
954
+ } else {
955
+ persistCursor(lastSeenFile, cursor, warn);
479
956
  }
480
957
 
481
958
  const contextPrefix = await buildGroupContextPrefix(
@@ -483,15 +960,19 @@ export async function wakeOnce(opts: {
483
960
  String(lastMsg.id || ""),
484
961
  String(lastMsg.timestamp || ""),
485
962
  );
486
- const combinedContent =
963
+ const allSameOwnerDirect = batch.every((m) => m?.same_owner_direct === true);
964
+ const combinedRedactOpts = allSameOwnerDirect ? { preserveAcKeys: true } : undefined;
965
+ const rawCombinedContent =
487
966
  batch.length === 1
488
967
  ? String(lastMsg.content || "")
489
968
  : batch.map((m) => String(m.content || "")).join("\n");
969
+ const safeCombinedContent = redactSecrets(rawCombinedContent, combinedRedactOpts);
490
970
  const prompt = buildWakePrompt(
491
971
  {
492
972
  ...lastMsg,
973
+ same_owner_direct: allSameOwnerDirect,
493
974
  channel_id: channelId,
494
- content: combinedContent,
975
+ content: rawCombinedContent,
495
976
  },
496
977
  contextPrefix,
497
978
  );
@@ -502,14 +983,17 @@ export async function wakeOnce(opts: {
502
983
  channel_id: channelId,
503
984
  message_id: String(lastMsg.id || ""),
504
985
  sender_id: String(lastMsg.sender_id || ""),
505
- content: combinedContent,
986
+ content: safeCombinedContent,
506
987
  timestamp: String(lastMsg.timestamp || ""),
507
988
  ...(batch.length > 1
508
989
  ? {
509
990
  messages: batch.map((m) => ({
510
991
  id: String(m.id || ""),
511
992
  sender_id: String(m.sender_id || ""),
512
- content: String(m.content || ""),
993
+ content: redactSecrets(
994
+ String(m.content || ""),
995
+ m?.same_owner_direct === true ? { preserveAcKeys: true } : undefined,
996
+ ),
513
997
  timestamp: String(m.timestamp || ""),
514
998
  })),
515
999
  }
@@ -524,32 +1008,38 @@ export async function wakeOnce(opts: {
524
1008
  ? rawMessages.filter((m) => m && typeof m === "object" && m.content !== "__typing__")
525
1009
  : [];
526
1010
  list.sort((a, b) => {
527
- const ta = normalizeTimestampForCursor(a.timestamp, "after") || String(a.timestamp || "");
528
- const tb = normalizeTimestampForCursor(b.timestamp, "after") || String(b.timestamp || "");
1011
+ const ta = canonicalRestCursorTimestamp(a.timestamp, "after") ?? "";
1012
+ const tb = canonicalRestCursorTimestamp(b.timestamp, "after") ?? "";
529
1013
  return ta.localeCompare(tb);
530
1014
  });
531
1015
 
532
1016
  const existingAfter = cursor.get(channelId);
533
- if (!existingAfter) {
534
- // First time seeing this channel:
1017
+ const afterNorm = canonicalRestCursorTimestamp(existingAfter, "after");
1018
+ if (!afterNorm) {
1019
+ // First time seeing this channel (or self-healing a corrupted cursor on disk):
535
1020
  // Any message strictly older than `__init_ts__` is pre-existing history and only seeds the cursor.
536
1021
  // Any addressed message at/after `__init_ts__` (e.g. first DM after claiming!) is live and must fire.
537
1022
  const liveBatch: any[] = [];
538
1023
  let newestPreExisting = "";
1024
+ let newestPreExistingNorm = "";
539
1025
  for (const m of list) {
540
1026
  const msgId = String(m.id || "");
541
1027
  if (msgId && seenSet.has(msgId)) continue;
542
1028
  const msgTs = String(m.timestamp || "");
543
- const msgTsNorm = normalizeTimestampForCursor(msgTs, "after") || msgTs;
1029
+ const msgTsNorm = canonicalRestCursorTimestamp(msgTs, "after");
544
1030
  if (msgTsNorm && msgTsNorm < initTsNorm) {
545
1031
  if (msgId) seenSet.add(msgId);
546
- if (msgTs > newestPreExisting) newestPreExisting = msgTs;
1032
+ if (msgTsNorm > newestPreExistingNorm) {
1033
+ newestPreExisting = msgTs;
1034
+ newestPreExistingNorm = msgTsNorm;
1035
+ }
547
1036
  continue;
548
1037
  }
549
1038
  if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
550
1039
  liveBatch.push({ ...m, channel_id: channelId });
551
- } else if (msgTs > newestPreExisting) {
1040
+ } else if (msgTsNorm && msgTsNorm > newestPreExistingNorm) {
552
1041
  newestPreExisting = msgTs;
1042
+ newestPreExistingNorm = msgTsNorm;
553
1043
  }
554
1044
  }
555
1045
  if (liveBatch.length > 0) {
@@ -562,21 +1052,22 @@ export async function wakeOnce(opts: {
562
1052
  return null;
563
1053
  }
564
1054
 
565
- const afterNorm = normalizeTimestampForCursor(existingAfter, "after") || existingAfter;
566
1055
  const addressedBatch: any[] = [];
567
1056
  let latestUnaddressedTs = "";
1057
+ let latestUnaddressedNorm = "";
568
1058
 
569
1059
  for (const m of list) {
570
1060
  const msgId = String(m.id || "");
571
1061
  if (msgId && seenSet.has(msgId)) continue;
572
1062
  const msgTs = String(m.timestamp || "");
573
- const msgTsNorm = normalizeTimestampForCursor(msgTs, "after") || msgTs;
1063
+ const msgTsNorm = canonicalRestCursorTimestamp(msgTs, "after");
574
1064
  if (msgTsNorm && msgTsNorm <= afterNorm) continue;
575
1065
 
576
1066
  if (isMessageAddressedToAgent({ ...m, channel_id: channelId }, agentId, displayName)) {
577
1067
  addressedBatch.push({ ...m, channel_id: channelId });
578
- } else if ( addressedBatch.length === 0 && msgTs ) {
1068
+ } else if (addressedBatch.length === 0 && msgTsNorm && msgTsNorm > latestUnaddressedNorm) {
579
1069
  latestUnaddressedTs = msgTs;
1070
+ latestUnaddressedNorm = msgTsNorm;
580
1071
  }
581
1072
  }
582
1073
 
@@ -603,6 +1094,9 @@ export async function wakeOnce(opts: {
603
1094
  resolved = true;
604
1095
  if (pollTimer) clearInterval(pollTimer);
605
1096
  if (timeoutTimer) clearTimeout(timeoutTimer);
1097
+ if (wrotePidFile) {
1098
+ releaseWakePidFile(wakePidFile);
1099
+ }
606
1100
  try {
607
1101
  abortCtrl.abort();
608
1102
  } catch {}
@@ -610,7 +1104,7 @@ export async function wakeOnce(opts: {
610
1104
  };
611
1105
 
612
1106
  function maybeStartSse(channelId: string) {
613
- if (!enableSse || resolved) return;
1107
+ if (!enableSse || resolved || !isSafeCliChannelId(channelId)) return;
614
1108
  if (activeSseChannels.has(channelId) || activeSseChannels.size >= MAX_SSE_STREAMS) return;
615
1109
  activeSseChannels.add(channelId);
616
1110
  void (async () => {
@@ -619,39 +1113,87 @@ export async function wakeOnce(opts: {
619
1113
  const res = await f(
620
1114
  `${baseUrl}/api/channels/${encodeURIComponent(channelId)}/stream`,
621
1115
  {
1116
+ redirect: "error",
622
1117
  headers: { Authorization: `Bearer ${token}` },
623
1118
  signal: abortCtrl.signal,
624
1119
  },
625
1120
  );
626
- if (!res.ok || !res.body) break;
1121
+ if (!res.ok || !res.body) {
1122
+ try {
1123
+ await res.body?.cancel();
1124
+ } catch {}
1125
+ if (res.status === 429 || res.status >= 500) {
1126
+ sseConnectedChannels.delete(channelId);
1127
+ if (resolved) return;
1128
+ await sleepAbortable(2000, abortCtrl.signal);
1129
+ continue;
1130
+ }
1131
+ break;
1132
+ }
627
1133
  sseConnectedChannels.add(channelId);
628
1134
  const reader = res.body.getReader();
629
- const decoder = new TextDecoder();
630
- let buf = "";
631
- while (!resolved) {
632
- const { value, done } = await reader.read();
633
- if (done) break;
634
- buf += decoder.decode(value, { stream: true });
635
- const lines = buf.split(/\r?\n/);
636
- buf = lines.pop() || "";
637
- for (const line of lines) {
638
- if (!line.startsWith("data:")) continue;
639
- const raw = line.slice(5).trim();
640
- if (!raw) continue;
641
- try {
642
- const parsed = JSON.parse(raw);
643
- const wakeEv = await inspectChannelMessages(channelId, [parsed]);
644
- if (wakeEv) {
645
- finish(wakeEv);
646
- return;
647
- }
648
- } catch {}
1135
+ const onAbortCancel = () => {
1136
+ void reader.cancel().catch(() => {});
1137
+ };
1138
+ if (abortCtrl.signal.aborted) {
1139
+ onAbortCancel();
1140
+ } else {
1141
+ abortCtrl.signal.addEventListener("abort", onAbortCancel, { once: true });
1142
+ }
1143
+ try {
1144
+ const decoder = new TextDecoder();
1145
+ let buf = "";
1146
+ let firstChunk = true;
1147
+ while (!resolved) {
1148
+ const { value, done } = await reader.read();
1149
+ if (done) break;
1150
+ let chunk = decoder.decode(value, { stream: true });
1151
+ if (firstChunk) {
1152
+ firstChunk = false;
1153
+ if (chunk.startsWith("\uFEFF")) chunk = chunk.slice(1);
1154
+ }
1155
+ buf += chunk;
1156
+ if (buf.length > MAX_SSE_LINE_CHARS && !buf.includes("\n")) {
1157
+ buf = "";
1158
+ continue;
1159
+ }
1160
+ const lines = buf.split(/\r?\n/);
1161
+ buf = lines.pop() || "";
1162
+ for (const line of lines) {
1163
+ if (!line.startsWith("data:")) continue;
1164
+ const raw = line.slice(5).trim();
1165
+ if (!raw) continue;
1166
+ try {
1167
+ const parsed = JSON.parse(raw);
1168
+ if (
1169
+ !parsed ||
1170
+ typeof parsed !== "object" ||
1171
+ Array.isArray(parsed) ||
1172
+ Object.prototype.hasOwnProperty.call(parsed, "__proto__")
1173
+ ) {
1174
+ continue;
1175
+ }
1176
+ const wakeEv = await inspectChannelMessages(channelId, [parsed]);
1177
+ if (wakeEv) {
1178
+ finish(wakeEv);
1179
+ return;
1180
+ }
1181
+ } catch {}
1182
+ }
649
1183
  }
1184
+ } finally {
1185
+ abortCtrl.signal.removeEventListener("abort", onAbortCancel);
1186
+ try {
1187
+ await reader.cancel();
1188
+ } catch {}
1189
+ try {
1190
+ reader.releaseLock();
1191
+ } catch {}
650
1192
  }
651
1193
  } catch {
652
1194
  sseConnectedChannels.delete(channelId);
653
1195
  if (resolved) return;
654
- await new Promise((r) => setTimeout(r, 2000));
1196
+ await sleepAbortable(2000, abortCtrl.signal);
655
1197
  }
656
1198
  }
657
1199
  sseConnectedChannels.delete(channelId);
@@ -664,32 +1206,38 @@ export async function wakeOnce(opts: {
664
1206
  if (resolved || polling) return;
665
1207
  polling = true;
666
1208
  try {
667
- const mineRes = await f(`${baseUrl}/api/channels/mine`, {
668
- headers,
669
- signal: abortCtrl.signal,
670
- });
1209
+ const mineRes = await fetchWithDeadline(
1210
+ f,
1211
+ `${baseUrl}/api/channels/mine`,
1212
+ { headers },
1213
+ requestTimeoutMs,
1214
+ abortCtrl.signal,
1215
+ );
671
1216
  const channelList: Array<{ id: string; last_message_at?: string }> = [];
672
1217
  const seenCh = new Set<string>();
673
1218
  if (mineRes.ok) {
674
- const mineData = (await mineRes.json()) as { channels?: any[] };
1219
+ const mineData = (await readBoundedResponseJson(mineRes)) as { channels?: any[] };
675
1220
  for (const ch of mineData.channels || []) {
676
- if (ch && typeof ch.id === "string" && !seenCh.has(ch.id)) {
1221
+ if (ch && isSafeCliChannelId(ch.id) && !seenCh.has(ch.id)) {
677
1222
  seenCh.add(ch.id);
678
1223
  channelList.push({ id: ch.id, last_message_at: ch.last_message_at });
679
1224
  }
680
1225
  }
1226
+ } else {
1227
+ await mineRes.body?.cancel().catch(() => {});
681
1228
  }
682
1229
  for (const extra of opts.channels ?? []) {
683
- if (extra && !seenCh.has(extra)) {
684
- seenCh.add(extra);
685
- channelList.push({ id: extra });
1230
+ const trimmedExtra = typeof extra === "string" ? extra.trim() : "";
1231
+ if (isSafeCliChannelId(trimmedExtra) && !seenCh.has(trimmedExtra)) {
1232
+ seenCh.add(trimmedExtra);
1233
+ channelList.push({ id: trimmedExtra });
686
1234
  }
687
1235
  }
688
1236
 
689
1237
  // Prioritize DMs first for SSE slots, then explicit channels
690
1238
  const sortedForSse = [...channelList].sort((a, b) => {
691
- const aDm = a.id.startsWith("dm-") ? 0 : 1;
692
- const bDm = b.id.startsWith("dm-") ? 0 : 1;
1239
+ const aDm = DIRECT_CHANNEL_RE.test(a.id) ? 0 : 1;
1240
+ const bDm = DIRECT_CHANNEL_RE.test(b.id) ? 0 : 1;
693
1241
  return aDm - bDm;
694
1242
  });
695
1243
  for (const ch of sortedForSse) {
@@ -704,21 +1252,27 @@ export async function wakeOnce(opts: {
704
1252
  continue;
705
1253
  }
706
1254
  const existingAfter = cursor.get(ch.id);
707
- if (existingAfter && ch.last_message_at && initialSyncedChannels.has(ch.id)) {
708
- const lastAtNorm = normalizeTimestampForCursor(ch.last_message_at, "after") || ch.last_message_at;
709
- const afterNorm = normalizeTimestampForCursor(existingAfter, "after") || existingAfter;
710
- if (lastAtNorm <= afterNorm) continue;
1255
+ const existingAfterNorm = canonicalRestCursorTimestamp(existingAfter, "after");
1256
+ if (existingAfterNorm && ch.last_message_at && initialSyncedChannels.has(ch.id)) {
1257
+ const lastAtNorm = canonicalRestCursorTimestamp(ch.last_message_at, "after");
1258
+ if (lastAtNorm && lastAtNorm <= existingAfterNorm) continue;
711
1259
  }
712
- const qs = existingAfter
1260
+ const qs = existingAfterNorm && existingAfter
713
1261
  ? `?after=${encodeURIComponent(existingAfter)}&limit=50`
714
1262
  : `?limit=20`;
715
- const msgRes = await f(
1263
+ const msgRes = await fetchWithDeadline(
1264
+ f,
716
1265
  `${baseUrl}/api/channels/${encodeURIComponent(ch.id)}/messages${qs}`,
717
- { headers, signal: abortCtrl.signal },
1266
+ { headers },
1267
+ requestTimeoutMs,
1268
+ abortCtrl.signal,
718
1269
  );
719
- if (!msgRes.ok) continue;
1270
+ if (!msgRes.ok) {
1271
+ await msgRes.body?.cancel().catch(() => {});
1272
+ continue;
1273
+ }
720
1274
  initialSyncedChannels.add(ch.id);
721
- const msgData = (await msgRes.json()) as { messages?: any[] };
1275
+ const msgData = (await readBoundedResponseJson(msgRes)) as { messages?: any[] };
722
1276
  const wakeEv = await inspectChannelMessages(ch.id, msgData.messages || []);
723
1277
  if (wakeEv) {
724
1278
  finish(wakeEv);