@milliways-ai/agm 0.0.0-stage → 0.9.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.
@@ -0,0 +1,576 @@
1
+ // Native harness integrations for zero-latency, conflict-free waking across Claude Code, Codex, and Antigravity App.
2
+ // All helpers use only Node.js built-ins and gracefully degrade when a harness interface is absent.
3
+ import crypto from "node:crypto";
4
+ import { spawn, spawnSync } from "node:child_process";
5
+ import fs from "node:fs";
6
+ import net from "node:net";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ import { call } from "./api.js";
10
+ import { load } from "./state.js";
11
+
12
+ function alive(pid) {
13
+ if (!Number.isInteger(pid) || pid <= 0) return false;
14
+ try {
15
+ process.kill(pid, 0);
16
+ return true;
17
+ } catch (err) {
18
+ return err.code === "EPERM";
19
+ }
20
+ }
21
+
22
+ function readJsonLimited(filePath, maxBytes = 256 * 1024) {
23
+ try {
24
+ const st = fs.statSync(filePath);
25
+ if (!st.isFile() || st.size > maxBytes) return null;
26
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
27
+ } catch {
28
+ return null;
29
+ }
30
+ }
31
+
32
+ // ============================================================================
33
+ // 1. Claude Code live Unix socket inbox (~/.claude/sessions/<pid>.json)
34
+ // ============================================================================
35
+
36
+ export function claudeHome() {
37
+ return process.env.AGM_CLAUDE_HOME || process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), ".claude");
38
+ }
39
+
40
+ export function claudeSettingsFile() {
41
+ return path.join(claudeHome(), "settings.json");
42
+ }
43
+
44
+ export function claudeCrossSessionAccepted() {
45
+ const settings = readJsonLimited(claudeSettingsFile(), 512 * 1024);
46
+ return settings?.crossSessionInbound === "accept";
47
+ }
48
+
49
+ export function claudeSetCrossSessionInbound(accept) {
50
+ const file = claudeSettingsFile();
51
+ fs.mkdirSync(path.dirname(file), { recursive: true });
52
+ let settings = {};
53
+ if (fs.existsSync(file)) {
54
+ const raw = fs.readFileSync(file, "utf8").trim();
55
+ if (raw) {
56
+ settings = JSON.parse(raw);
57
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) {
58
+ throw new Error(`${file} does not contain a JSON object.`);
59
+ }
60
+ }
61
+ }
62
+ if (accept) settings.crossSessionInbound = "accept";
63
+ else delete settings.crossSessionInbound;
64
+ const tmp = `${file}.${process.pid}.tmp`;
65
+ fs.writeFileSync(tmp, JSON.stringify(settings, null, 2) + "\n", { mode: 0o600 });
66
+ fs.renameSync(tmp, file);
67
+ return file;
68
+ }
69
+
70
+ function claudeProjectSlug(cwd) {
71
+ return String(cwd || "").replace(/[^A-Za-z0-9]/g, "-");
72
+ }
73
+
74
+ function findClaudeTranscript(sessionId, cwd) {
75
+ const projects = path.join(claudeHome(), "projects");
76
+ if (cwd) {
77
+ const direct = path.join(projects, claudeProjectSlug(cwd), `${sessionId}.jsonl`);
78
+ if (fs.existsSync(direct)) return direct;
79
+ }
80
+ let entries = [];
81
+ try {
82
+ entries = fs.readdirSync(projects);
83
+ } catch {
84
+ return null;
85
+ }
86
+ let best = null;
87
+ for (const dirName of entries) {
88
+ const p = path.join(projects, dirName, `${sessionId}.jsonl`);
89
+ try {
90
+ const st = fs.statSync(p);
91
+ if (st.isFile() && (!best || st.mtimeMs > best.mtimeMs)) best = { path: p, mtimeMs: st.mtimeMs };
92
+ } catch {}
93
+ }
94
+ return best?.path || null;
95
+ }
96
+
97
+ // Checks whether the session's most recent permissionMode in its transcript is bypassPermissions.
98
+ // Claude Code holds cross-session socket frames when bypassPermissions is active unless crossSessionInbound is "accept".
99
+ export function claudeSessionBypassPermissions(sessionId, cwd) {
100
+ const file = findClaudeTranscript(sessionId, cwd);
101
+ if (!file) return false;
102
+ let fd;
103
+ try {
104
+ fd = fs.openSync(file, "r");
105
+ const size = fs.fstatSync(fd).size;
106
+ const len = Math.min(size, 128 * 1024);
107
+ const buf = Buffer.alloc(len);
108
+ fs.readSync(fd, buf, 0, len, size - len);
109
+ const text = buf.toString("utf8");
110
+ const matches = [...text.matchAll(/"permissionMode"\s*:\s*"([^"]+)"/g)];
111
+ if (!matches.length) return false;
112
+ return matches.at(-1)[1] === "bypassPermissions";
113
+ } catch {
114
+ return false;
115
+ } finally {
116
+ if (fd !== undefined) {
117
+ try { fs.closeSync(fd); } catch {}
118
+ }
119
+ }
120
+ }
121
+
122
+ function readClaudePeerToken(sessionsDir, pid, socketPath) {
123
+ const hash = crypto.createHash("sha256").update(socketPath).digest("hex");
124
+ const keyFile = readJsonLimited(path.join(sessionsDir, `${pid}.${hash}.key`), 64 * 1024);
125
+ const token = keyFile?.peerToken;
126
+ if (typeof token === "string" && token.length >= 16 && token.length <= 128 && /^[0-9a-f]+$/i.test(token)) {
127
+ return token;
128
+ }
129
+ return null;
130
+ }
131
+
132
+ // Returns live Claude Code Unix socket inbox metadata for `sessionId` (or newest live session if sessionId omitted).
133
+ export function claudeLiveInbox(sessionId) {
134
+ if (process.platform === "win32") return null;
135
+ const sessionsDir = path.join(claudeHome(), "sessions");
136
+ let files = [];
137
+ try {
138
+ files = fs.readdirSync(sessionsDir);
139
+ } catch {
140
+ return null;
141
+ }
142
+ const want = sessionId ? String(sessionId).toLowerCase() : null;
143
+ let best = null;
144
+ for (const file of files) {
145
+ if (!file.endsWith(".json")) continue;
146
+ const pid = Number(file.slice(0, -5));
147
+ if (!Number.isInteger(pid) || pid <= 0 || !alive(pid)) continue;
148
+ const rec = readJsonLimited(path.join(sessionsDir, file));
149
+ if (!rec || rec.pid !== pid || typeof rec.sessionId !== "string") continue;
150
+ const sid = rec.sessionId.toLowerCase();
151
+ if (want && sid !== want) continue;
152
+ const socketPath = rec.messagingSocketPath;
153
+ if (typeof socketPath !== "string" || !path.isAbsolute(socketPath)) continue;
154
+ try {
155
+ if (!fs.lstatSync(socketPath).isSocket()) continue;
156
+ } catch {
157
+ continue;
158
+ }
159
+ const updatedAt = Number(rec.updatedAt) || 0;
160
+ if (!best || updatedAt >= best.updatedAt) {
161
+ const cwd = typeof rec.cwd === "string" ? rec.cwd : null;
162
+ const held = claudeSessionBypassPermissions(sid, cwd) && !claudeCrossSessionAccepted();
163
+ best = {
164
+ sessionId: sid,
165
+ pid,
166
+ socket: socketPath,
167
+ token: readClaudePeerToken(sessionsDir, pid, socketPath),
168
+ cwd,
169
+ updatedAt,
170
+ held,
171
+ };
172
+ }
173
+ }
174
+ return best;
175
+ }
176
+
177
+ export function claudeSocketSend(inbox, text, msgId = crypto.randomUUID(), timeoutMs = 3000) {
178
+ return new Promise((resolve) => {
179
+ if (!inbox?.socket) return resolve({ ok: false, error: "No Claude inbox socket." });
180
+ let done = false;
181
+ const finish = (result) => {
182
+ if (done) return;
183
+ done = true;
184
+ clearTimeout(timer);
185
+ try { sock.destroy(); } catch {}
186
+ resolve(result);
187
+ };
188
+ const sock = net.createConnection(inbox.socket);
189
+ const timer = setTimeout(() => finish({ ok: false, error: "Claude socket send timed out." }), timeoutMs);
190
+ timer.unref?.();
191
+ sock.on("error", (err) => finish({ ok: false, error: err.message }));
192
+ sock.on("connect", () => {
193
+ let frames = "";
194
+ if (inbox.token) frames += JSON.stringify({ type: "auth", token: inbox.token }) + "\n";
195
+ frames += JSON.stringify({
196
+ type: "user",
197
+ session_id: inbox.sessionId,
198
+ uuid: msgId,
199
+ msg_id: msgId,
200
+ from: "Agent DM",
201
+ priority: "next",
202
+ message: { role: "user", content: text },
203
+ }) + "\n";
204
+ sock.end(frames, "utf8", () => {
205
+ // Give the peer a moment to accept before closing; resolve cleanly on close or short settle.
206
+ setTimeout(() => finish({ ok: true }), 100).unref?.();
207
+ });
208
+ });
209
+ sock.on("close", () => finish({ ok: true }));
210
+ });
211
+ }
212
+
213
+ // ============================================================================
214
+ // 2. Codex thread writer-lock probe + thread/queue/add JSON-RPC
215
+ // ============================================================================
216
+
217
+ export function codexHome() {
218
+ return process.env.CODEX_HOME || path.join(os.homedir(), ".codex");
219
+ }
220
+
221
+ // Non-blocking probe of ~/.codex/thread-writer-locks/<id>.lock.
222
+ // Returns true if another Codex process currently holds the thread open, false if free, null if unknown.
223
+ export function codexThreadOpen(threadId) {
224
+ if (process.platform === "win32") return null;
225
+ if (typeof threadId !== "string" || !/^[A-Za-z0-9-]{8,80}$/.test(threadId)) return null;
226
+ const lockDir = path.join(codexHome(), "thread-writer-locks");
227
+ const coordPath = path.join(lockDir, ".coordination.lock");
228
+ const threadPath = path.join(lockDir, `${threadId.toLowerCase()}.lock`);
229
+ if (!fs.existsSync(coordPath) || !fs.existsSync(threadPath)) return false;
230
+
231
+ // Use python3 fcntl.flock when available (standard on macOS & Linux) to acquire .coordination.lock
232
+ // briefly and test threadPath with LOCK_EX | LOCK_NB without creating any new files.
233
+ const py = spawnSync(
234
+ process.env.AGM_PYTHON_BIN || "python3",
235
+ [
236
+ "-c",
237
+ [
238
+ "import fcntl, sys, time",
239
+ "coord = open(sys.argv[1], 'r+b')",
240
+ "deadline = time.monotonic() + 1.5",
241
+ "while True:",
242
+ " try:",
243
+ " fcntl.flock(coord, fcntl.LOCK_EX | fcntl.LOCK_NB)",
244
+ " break",
245
+ " except BlockingIOError:",
246
+ " if time.monotonic() >= deadline: sys.exit(2)",
247
+ " time.sleep(0.02)",
248
+ "try:",
249
+ " f = open(sys.argv[2], 'r+b')",
250
+ " try:",
251
+ " fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)",
252
+ " print('free')",
253
+ " except BlockingIOError:",
254
+ " print('open')",
255
+ " finally:",
256
+ " f.close()",
257
+ "except FileNotFoundError:",
258
+ " print('free')",
259
+ "finally:",
260
+ " coord.close()",
261
+ ].join("\n"),
262
+ coordPath,
263
+ threadPath,
264
+ ],
265
+ { encoding: "utf8", timeout: 3000 },
266
+ );
267
+ if (py.status === 0) {
268
+ const out = py.stdout.trim();
269
+ if (out === "open") return true;
270
+ if (out === "free") return false;
271
+ }
272
+ // Fallback to util-linux `flock -n` on Linux if python3 is unavailable.
273
+ const fl = spawnSync("flock", ["-n", threadPath, "true"], { encoding: "utf8", timeout: 2000 });
274
+ if (fl.status === 0) return false;
275
+ if (fl.status === 1) return true;
276
+ return null;
277
+ }
278
+
279
+ // Enqueue a message into any Codex thread (even if not currently loaded on the shared daemon)
280
+ // using `codex app-server` JSON-RPC `thread/queue/add`.
281
+ export function codexQueueAdd(threadId, text, clientId = crypto.randomUUID(), { codexBin = process.env.AGM_CODEX_BIN || "codex", timeoutMs = 15000 } = {}) {
282
+ return new Promise((resolve) => {
283
+ let settled = false;
284
+ let child;
285
+ const finish = (result) => {
286
+ if (settled) return;
287
+ settled = true;
288
+ clearTimeout(timer);
289
+ try { child?.kill("SIGTERM"); } catch {}
290
+ resolve(result);
291
+ };
292
+ const timer = setTimeout(() => finish({ ok: false, error: "codex app-server thread/queue/add timed out." }), timeoutMs);
293
+ timer.unref?.();
294
+ try {
295
+ child = spawn(codexBin, ["app-server"], {
296
+ stdio: ["pipe", "pipe", "pipe"],
297
+ windowsHide: true,
298
+ shell: process.platform === "win32",
299
+ });
300
+ } catch (err) {
301
+ return finish({ ok: false, error: err.message });
302
+ }
303
+ let buf = "";
304
+ let stderr = "";
305
+ let sentQueue = false;
306
+ child.on("error", (err) => finish({ ok: false, error: err.message }));
307
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-400); });
308
+ child.on("exit", (code) => {
309
+ if (!settled) finish({ ok: false, error: stderr.trim() || `codex app-server exited (${code})` });
310
+ });
311
+ child.stdout.on("data", (chunk) => {
312
+ buf += chunk.toString("utf8");
313
+ let nl;
314
+ while ((nl = buf.indexOf("\n")) !== -1) {
315
+ const line = buf.slice(0, nl).trim();
316
+ buf = buf.slice(nl + 1);
317
+ if (!line) continue;
318
+ let msg;
319
+ try {
320
+ msg = JSON.parse(line);
321
+ } catch {
322
+ continue;
323
+ }
324
+ if (msg.id === 1 && !sentQueue) {
325
+ if (msg.error) return finish({ ok: false, error: msg.error.message || JSON.stringify(msg.error) });
326
+ sentQueue = true;
327
+ try {
328
+ child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized", params: {} }) + "\n");
329
+ child.stdin.write(
330
+ JSON.stringify({
331
+ jsonrpc: "2.0",
332
+ id: 2,
333
+ method: "thread/queue/add",
334
+ params: {
335
+ threadId,
336
+ clientUserMessageId: clientId,
337
+ input: [{ type: "text", text, text_elements: [] }],
338
+ },
339
+ }) + "\n",
340
+ );
341
+ } catch (err) {
342
+ return finish({ ok: false, error: err.message });
343
+ }
344
+ } else if (msg.id === 2) {
345
+ if (msg.error) return finish({ ok: false, error: msg.error.message || JSON.stringify(msg.error) });
346
+ const q = msg.result?.queuedSubmission;
347
+ if (q?.clientUserMessageId === clientId && q?.id) {
348
+ return finish({ ok: true, queueId: String(q.id) });
349
+ }
350
+ return finish({ ok: false, error: "Unexpected thread/queue/add receipt from Codex." });
351
+ }
352
+ }
353
+ });
354
+ try {
355
+ child.stdin.write(
356
+ JSON.stringify({
357
+ jsonrpc: "2.0",
358
+ id: 1,
359
+ method: "initialize",
360
+ params: { clientInfo: { name: "agm", version: "0.9.20" } },
361
+ }) + "\n",
362
+ );
363
+ } catch (err) {
364
+ finish({ ok: false, error: err.message });
365
+ }
366
+ });
367
+ }
368
+
369
+ // ============================================================================
370
+ // 3. Antigravity App native waking (~/.gemini/antigravity/bin/agentapi)
371
+ // ============================================================================
372
+
373
+ export function antigravityHome() {
374
+ if (process.env.AGM_ANTIGRAVITY_HOME) return process.env.AGM_ANTIGRAVITY_HOME;
375
+ if (process.env.ANTIGRAVITY_APP_DATA_DIR) return process.env.ANTIGRAVITY_APP_DATA_DIR;
376
+ return path.join(os.homedir(), ".gemini", "antigravity");
377
+ }
378
+
379
+ export function antigravityAgentApi() {
380
+ if (process.env.AGM_ANTIGRAVITY_AGENTAPI && fs.existsSync(process.env.AGM_ANTIGRAVITY_AGENTAPI)) {
381
+ return process.env.AGM_ANTIGRAVITY_AGENTAPI;
382
+ }
383
+ const names = process.platform === "win32" ? ["agentapi.exe", "agentapi.cmd", "agentapi"] : ["agentapi"];
384
+ for (const name of names) {
385
+ const candidate = path.join(antigravityHome(), "bin", name);
386
+ try {
387
+ fs.accessSync(candidate, fs.constants.X_OK);
388
+ return candidate;
389
+ } catch {}
390
+ }
391
+ return null;
392
+ }
393
+
394
+ function tcpReachable(port, timeoutMs = 300) {
395
+ return new Promise((resolve) => {
396
+ const sock = net.createConnection({ host: "127.0.0.1", port });
397
+ const done = (ok) => {
398
+ clearTimeout(t);
399
+ try { sock.destroy(); } catch {}
400
+ resolve(ok);
401
+ };
402
+ const t = setTimeout(() => done(false), timeoutMs);
403
+ t.unref?.();
404
+ sock.on("connect", () => done(true));
405
+ sock.on("error", () => done(false));
406
+ });
407
+ }
408
+
409
+ export async function antigravityHub() {
410
+ const daemonDir = path.join(antigravityHome(), "daemon");
411
+ let entries = [];
412
+ try {
413
+ entries = fs.readdirSync(daemonDir)
414
+ .filter((n) => n.startsWith("hub_") && n.endsWith(".json"))
415
+ .map((n) => {
416
+ const full = path.join(daemonDir, n);
417
+ try {
418
+ return { path: full, mtimeMs: fs.statSync(full).mtimeMs };
419
+ } catch {
420
+ return null;
421
+ }
422
+ })
423
+ .filter(Boolean)
424
+ .sort((a, b) => b.mtimeMs - a.mtimeMs);
425
+ } catch {
426
+ return null;
427
+ }
428
+ for (const entry of entries) {
429
+ const data = readJsonLimited(entry.path, 64 * 1024);
430
+ const port = Number(data?.httpPort);
431
+ const token = typeof data?.csrfToken === "string" && data.csrfToken ? data.csrfToken : null;
432
+ if (!Number.isInteger(port) || port < 1 || port > 65535 || !token) continue;
433
+ if (await tcpReachable(port)) {
434
+ return { address: `127.0.0.1:${port}`, token };
435
+ }
436
+ }
437
+ return null;
438
+ }
439
+
440
+ export async function antigravitySend(conversationId, text, { timeoutMs = 20000 } = {}) {
441
+ if (typeof conversationId !== "string" || !/^[A-Za-z0-9-]{8,80}$/.test(conversationId)) {
442
+ return { ok: false, error: "Invalid Antigravity conversation id." };
443
+ }
444
+ const hub = await antigravityHub();
445
+ if (!hub) return { ok: false, error: "Antigravity App hub is not running." };
446
+ const exe = antigravityAgentApi();
447
+ if (!exe) return { ok: false, error: "Antigravity agentapi binary not found." };
448
+ return new Promise((resolve) => {
449
+ let settled = false;
450
+ const finish = (result) => {
451
+ if (settled) return;
452
+ settled = true;
453
+ clearTimeout(timer);
454
+ resolve(result);
455
+ };
456
+ const child = spawn(exe, ["send-message", "--title=AgentDM", conversationId, text], {
457
+ stdio: ["ignore", "pipe", "pipe"],
458
+ windowsHide: true,
459
+ env: { ...process.env, ANTIGRAVITY_LS_ADDRESS: hub.address, ANTIGRAVITY_CSRF_TOKEN: hub.token },
460
+ });
461
+ let stderr = "";
462
+ child.stderr.on("data", (chunk) => { stderr = (stderr + chunk.toString()).slice(-400); });
463
+ const timer = setTimeout(() => {
464
+ try { child.kill("SIGTERM"); } catch {}
465
+ finish({ ok: false, error: "agentapi send-message timed out." });
466
+ }, timeoutMs);
467
+ timer.unref?.();
468
+ child.on("error", (err) => finish({ ok: false, error: err.message }));
469
+ child.on("exit", (code) => {
470
+ if (code === 0) finish({ ok: true });
471
+ else finish({ ok: false, error: stderr.trim() || `agentapi exited (${code})` });
472
+ });
473
+ });
474
+ }
475
+
476
+ // ============================================================================
477
+ // 4. Delivery verification & anti-silent-drop closed loop
478
+ // ============================================================================
479
+
480
+ const sleepMs = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
481
+
482
+ // Waits up to timeoutMs (default 45s) for the woken agent to actually read every target room
483
+ // (either local cursor >= targetSeq or server readSeq >= targetSeq). Extends the window while
484
+ // the server reports the member is actively working. Pass timeoutMs = 0 for a single instant check.
485
+ export async function verifyDelivery(name, targets, options = {}) {
486
+ const list = (targets || []).filter((t) => t?.room?.id && Number.isInteger(t.targetSeq));
487
+ if (!list.length) return { verified: true, unconfirmed: [] };
488
+
489
+ const timeoutMs = options.timeoutMs !== undefined
490
+ ? Number(options.timeoutMs)
491
+ : (Number(process.env.AGM_DELIVERY_TIMEOUT_MS) || 45_000);
492
+ const pollMs = Math.max(50, options.pollMs !== undefined
493
+ ? Number(options.pollMs)
494
+ : (Number(process.env.AGM_DELIVERY_POLL_MS) || 3_000));
495
+ const workingExtendMs = Math.max(0, options.workingExtendMs !== undefined
496
+ ? Number(options.workingExtendMs)
497
+ : (Number(process.env.AGM_DELIVERY_WORKING_EXTEND_MS) || 60_000));
498
+ const signal = options.signal;
499
+
500
+ const remaining = new Map(list.map((t) => [t.room.id, t]));
501
+ const checkOnce = async (checkServer) => {
502
+ let anyWorking = false;
503
+ let state;
504
+ try {
505
+ state = load();
506
+ } catch {
507
+ state = { profiles: {} };
508
+ }
509
+ for (const [roomId, { room, targetSeq }] of [...remaining]) {
510
+ const localRoom = state.profiles?.[name]?.rooms?.[roomId];
511
+ if (!localRoom || (localRoom.cursor || 0) >= targetSeq) {
512
+ remaining.delete(roomId);
513
+ continue;
514
+ }
515
+ if (!checkServer) continue;
516
+ try {
517
+ const data = await call(room.api, "GET", "/members", { credential: room.token, timeoutSeconds: 6, signal });
518
+ const self = data.members?.find((m) => m.name === room.name);
519
+ if (!self || self.leftAt || (self.readSeq || 0) >= targetSeq) {
520
+ remaining.delete(roomId);
521
+ continue;
522
+ }
523
+ if (self.working) anyWorking = true;
524
+ } catch {
525
+ // Transient network hiccup must not falsely mark a room as confirmed or crash verification.
526
+ }
527
+ }
528
+ return anyWorking;
529
+ };
530
+
531
+ if (timeoutMs <= 0) {
532
+ await checkOnce(true);
533
+ } else {
534
+ const started = Date.now();
535
+ let deadline = started + timeoutMs;
536
+ const hardCap = started + timeoutMs + workingExtendMs;
537
+ let tick = 0;
538
+ while (remaining.size > 0 && !signal?.aborted) {
539
+ const now = Date.now();
540
+ const isFinal = now >= deadline;
541
+ const anyWorking = await checkOnce(isFinal || tick % 2 === 0);
542
+ tick++;
543
+ if (remaining.size === 0) break;
544
+ if (anyWorking && Date.now() < hardCap) {
545
+ deadline = Math.min(hardCap, Math.max(deadline, Date.now() + Math.max(pollMs * 2, 10_000)));
546
+ }
547
+ if (Date.now() >= deadline || signal?.aborted) {
548
+ if (!isFinal && !signal?.aborted) await checkOnce(true);
549
+ break;
550
+ }
551
+ const wait = Math.min(pollMs, Math.max(50, deadline - Date.now()));
552
+ await sleepMs(wait);
553
+ }
554
+ }
555
+
556
+ return {
557
+ verified: remaining.size === 0,
558
+ unconfirmed: [...remaining.values()].map(({ room, targetSeq }) => ({
559
+ roomId: room.id,
560
+ title: room.title || room.id,
561
+ targetSeq,
562
+ })),
563
+ };
564
+ }
565
+
566
+ // Filters a recorded unverifiedWake down to rooms whose local cursor is still behind targetSeq.
567
+ // Returns null once the agent has caught up on all rooms.
568
+ export function unresolvedWake(unverifiedWake, state, name) {
569
+ if (!unverifiedWake || !Array.isArray(unverifiedWake.rooms) || !unverifiedWake.rooms.length) return null;
570
+ const profileRooms = state?.profiles?.[name]?.rooms || {};
571
+ const pending = unverifiedWake.rooms.filter((r) => {
572
+ const local = profileRooms[r.roomId];
573
+ return local && (local.cursor || 0) < r.targetSeq;
574
+ });
575
+ return pending.length ? { ...unverifiedWake, rooms: pending } : null;
576
+ }