@alexsun-top/opencode-chat-room 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server/wake.ts ADDED
@@ -0,0 +1,91 @@
1
+ import os from "node:os";
2
+ import type { Message } from "../src/room-service";
3
+ import { authHeader, formatNotificationLines, formatServeWakePrompt, readState, writeState, type RegistryEntry } from "../src/store";
4
+ import { admissionMatches, clearPendingAdmission, getOrCreatePendingAdmission, markPendingAdmissionAdmitted, pendingAdmission, rejectPendingAdmission, type QueueBody, type QueueItem } from "../src/queue";
5
+ import { readInbox, type InboxItem } from "./inbox";
6
+
7
+ const wakeClaims = new Map<string, number>();
8
+ const activeSessions = new Map<string, number>();
9
+ const WAKE_CLAIM_MS = 30_000;
10
+ const WAKE_INACTIVE_MS = 2 * 60_000;
11
+
12
+ export function claimWake(id: string): boolean {
13
+ if (Date.now() - (wakeClaims.get(id) ?? 0) < WAKE_CLAIM_MS) return false;
14
+ wakeClaims.set(id, Date.now());
15
+ return true;
16
+ }
17
+ export function touchActive(id: string): void { if (id) activeSessions.set(id, Date.now()); }
18
+
19
+ export async function wakeMentionedSessions(
20
+ serveWakeUrl: string, roomId: string, roomName: string, text: string,
21
+ senderSessionID: string, triggeringMessage: Message,
22
+ ): Promise<void> {
23
+ if (!serveWakeUrl) return;
24
+ const mentions = new Set<string>();
25
+ for (const match of text.matchAll(/<at>@([^<]+)<\/at>/g)) mentions.add(match[1]!);
26
+ for (const match of text.matchAll(/@([\p{L}\p{N}_]+)/gu)) {
27
+ const at = match.index ?? 0;
28
+ if (at === 0 || !/[A-Za-z0-9_]/.test(text[at - 1] ?? "")) mentions.add(match[1]!);
29
+ }
30
+ if (!mentions.size) return;
31
+ const reg = await readState((_svc, registry) => registry[roomId] ?? {});
32
+ for (const [sid, entry] of Object.entries(reg)) {
33
+ if (sid === senderSessionID || entry.protocol === "v2" || !mentions.has(entry.name) || entry.host !== os.hostname() ||
34
+ (activeSessions.get(sid) ?? 0) > Date.now() - WAKE_INACTIVE_MS ||
35
+ triggeringMessage.createdAt <= (entry.lastReadTs ?? 0) ||
36
+ triggeringMessage.createdAt <= (entry.lastQueuedTs ?? 0) || !claimWake(sid)) continue;
37
+ void deliverWake(serveWakeUrl, sid, roomId, roomName, entry, triggeringMessage).catch(() => {});
38
+ }
39
+ }
40
+
41
+ async function deliverWake(
42
+ serveWakeUrl: string, sid: string, roomId: string, roomName: string,
43
+ entry: RegistryEntry, triggering: Message,
44
+ ): Promise<void> {
45
+ const inbox = await readInbox(sid, roomId, true);
46
+ const current = await readState((_svc, registry) => registry[roomId]?.[sid]);
47
+ if (!current || !inbox.member) return;
48
+ const queued = Math.max(current.lastQueuedTs ?? 0, inbox.queuedTs[roomId] ?? 0);
49
+ if (triggering.createdAt <= (current.lastReadTs ?? 0) || triggering.createdAt <= queued) return;
50
+ const queuedItems = inbox.items.filter((item) => item.createdAt > queued);
51
+ const trigger: InboxItem = { id: triggering.id, roomId, roomName, senderId: triggering.senderId, text: triggering.text, createdAt: triggering.createdAt };
52
+ const items = queuedItems.some((item) => item.id === trigger.id) ? queuedItems : [...queuedItems, trigger].sort((a, b) => a.createdAt - b.createdAt);
53
+ const maxTs = items.reduce((max, item) => Math.max(max, item.createdAt), 0);
54
+ const existing = pendingAdmission(sid, roomId);
55
+ const delta = existing?.state === "admitted" && maxTs > existing.maxTs ? items.filter((item) => item.createdAt > existing.maxTs) : items;
56
+ const confirmQueued = async (ts: number) => {
57
+ const result = await writeState((_svc, registry) => {
58
+ const target = registry[roomId]?.[sid];
59
+ if (!target) return false;
60
+ target.lastQueuedTs = Math.max(target.lastQueuedTs ?? 0, ts);
61
+ return true;
62
+ });
63
+ if (result) clearPendingAdmission(sid, roomId, ts);
64
+ return result;
65
+ };
66
+ if (existing?.state === "admitted" && (maxTs <= existing.maxTs || !delta.length)) {
67
+ await confirmQueued(existing.maxTs);
68
+ return;
69
+ }
70
+ const { lines, capped } = formatNotificationLines(delta);
71
+ const prompt = formatServeWakePrompt(roomName, lines);
72
+ const admission = getOrCreatePendingAdmission(sid, roomId, delta as QueueItem[], prompt,
73
+ delta.reduce((max, item) => Math.max(max, item.createdAt), 0), capped);
74
+ const body: QueueBody = { id: admission.id, prompt: { text: admission.prompt }, delivery: "queue", resume: true };
75
+ const directory = entry.directory ?? process.env.OPENCODE_DIRECTORY;
76
+ const auth = authHeader();
77
+ try {
78
+ const response = await fetch(`${serveWakeUrl.replace(/\/+$/, "")}/api/session/${encodeURIComponent(sid)}/prompt`, {
79
+ method: "POST",
80
+ headers: { "Content-Type": "application/json", ...(auth ? { Authorization: auth } : {}),
81
+ ...(directory ? { "x-opencode-directory": encodeURIComponent(directory) } : {}) },
82
+ body: JSON.stringify(body), signal: AbortSignal.timeout(10_000),
83
+ });
84
+ const data = await response.json().catch(() => undefined);
85
+ if (response.ok && admissionMatches(data, body, sid)) {
86
+ markPendingAdmissionAdmitted(sid, roomId, admission.id);
87
+ touchActive(sid);
88
+ await confirmQueued(admission.maxTs);
89
+ } else if (response.status !== 404) rejectPendingAdmission(sid, roomId, admission.id);
90
+ } catch { /* The periodic inbox poll retries delivery. */ }
91
+ }
@@ -0,0 +1,108 @@
1
+ import { receiverOwnerID } from "./receiver-owner";
2
+ import { assertDeliveryLease } from "./session-delivery";
3
+
4
+ export async function backgroundOwnSession(sessionID: string, version: string): Promise<boolean> {
5
+ try {
6
+ const host = await discoverVerifiedHost(version);
7
+ if (!host) return false;
8
+ assertDeliveryLease();
9
+ await host.client.session.background({ sessionID }, { signal: AbortSignal.timeout(1500) });
10
+ return true;
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ export async function discoverVerifiedHost(version: string) {
17
+ const [{ OpenCode }, { Service }] = await Promise.all([
18
+ import("@opencode/client"), import("@opencode/client/service"),
19
+ ]);
20
+ let timer: ReturnType<typeof setTimeout>;
21
+ const endpoint = await Promise.race([
22
+ Service.discover({ version }),
23
+ new Promise<undefined>((resolve) => { timer = setTimeout(() => resolve(undefined), 2000); }),
24
+ ]).finally(() => clearTimeout(timer!));
25
+ if (!endpoint) return undefined;
26
+ const url = new URL(endpoint.url);
27
+ if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)) return undefined;
28
+ const client = OpenCode.make({ baseUrl: url.origin, headers: Service.headers(endpoint) });
29
+ const info = await client.server.info({ signal: AbortSignal.timeout(1500) });
30
+ if (info.pid !== process.pid || info.version !== version) return undefined;
31
+ return { origin: url.origin, client };
32
+ }
33
+
34
+ export async function discoverCompatibleRegisteredHost() {
35
+ const [{ OpenCode }, { Service }] = await Promise.all([
36
+ import("@opencode/client"), import("@opencode/client/service"),
37
+ ]);
38
+ const endpoint = await Service.discover({ version: (value) => /^2\./.test(value) });
39
+ if (!endpoint) return undefined;
40
+ const url = new URL(endpoint.url);
41
+ if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)) return undefined;
42
+ const client = OpenCode.make({ baseUrl: url.origin, headers: Service.headers(endpoint) });
43
+ const info = await client.server.info({ signal: AbortSignal.timeout(1500) });
44
+ if (!Number.isInteger(info.pid) || !/^2\./.test(info.version)) return undefined;
45
+ const current = await Service.discover({ version: (value) => /^2\./.test(value) });
46
+ if (!current || new URL(current.url).origin !== url.origin) return undefined;
47
+ const currentClient = OpenCode.make({ baseUrl: url.origin, headers: Service.headers(current) });
48
+ const verified = await currentClient.server.info({ signal: AbortSignal.timeout(1500) });
49
+ if (verified.pid !== info.pid || verified.version !== info.version) return undefined;
50
+ return { origin: url.origin, pid: verified.pid, version: verified.version, client: currentClient };
51
+ }
52
+
53
+ export async function backgroundAtCompatibleRegisteredHost(
54
+ sessionID: string,
55
+ expected: { origin: string; pid: number; version: string },
56
+ ): Promise<boolean> {
57
+ try {
58
+ const host = await discoverCompatibleRegisteredHost();
59
+ if (!host || host.origin !== expected.origin || host.pid !== expected.pid || host.version !== expected.version) return false;
60
+ assertDeliveryLease();
61
+ await host.client.session.background({ sessionID }, { signal: AbortSignal.timeout(1500) });
62
+ return true;
63
+ } catch { return false; }
64
+ }
65
+
66
+ export async function verifyHostSession(sessionID: string, version: string): Promise<string | undefined> {
67
+ try {
68
+ const host = await discoverVerifiedHost(version);
69
+ if (!host) return undefined;
70
+ await host.client.session.get({ sessionID }, { signal: AbortSignal.timeout(1500) });
71
+ return receiverOwnerID(host.origin);
72
+ } catch { return undefined; }
73
+ }
74
+
75
+ type BackgroundApi = {
76
+ discover(): Promise<{ url: string; auth?: { type: "basic"; username: string; password: string } } | undefined>;
77
+ headers(endpoint: { url: string; auth?: { type: "basic"; username: string; password: string } }): Record<string, string> | undefined;
78
+ createClient(baseUrl: string, headers?: Record<string, string>): {
79
+ server: { info(options: { signal: AbortSignal }): Promise<{ pid: number; version: string }> };
80
+ session: { background(input: { sessionID: string }, options: { signal: AbortSignal }): Promise<void> };
81
+ };
82
+ };
83
+
84
+ export async function backgroundAtRegisteredService(
85
+ sessionID: string,
86
+ version: string,
87
+ api: BackgroundApi,
88
+ pid = process.pid,
89
+ ): Promise<boolean> {
90
+ try {
91
+ let timer: ReturnType<typeof setTimeout>;
92
+ const endpoint = await Promise.race([
93
+ api.discover(),
94
+ new Promise<undefined>((resolve) => { timer = setTimeout(() => resolve(undefined), 2000); }),
95
+ ]).finally(() => clearTimeout(timer!));
96
+ if (!endpoint) return false;
97
+ const url = new URL(endpoint.url);
98
+ if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)) return false;
99
+ const headers = api.headers(endpoint);
100
+ const client = api.createClient(url.origin, headers);
101
+ const info = await client.server.info({ signal: AbortSignal.timeout(1500) });
102
+ if (info.pid !== pid || info.version !== version) return false;
103
+ await client.session.background({ sessionID }, { signal: AbortSignal.timeout(1500) });
104
+ return true;
105
+ } catch {
106
+ return false;
107
+ }
108
+ }
@@ -15,6 +15,7 @@ import {
15
15
  clearPendingAdmission,
16
16
  } from "./queue";
17
17
  import type { InboxItem } from "./center-inbox";
18
+ import { assertDeliveryLease } from "./session-delivery";
18
19
  export { queueAdmissionId } from "./queue";
19
20
  export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport";
20
21
  export type { QueueTransport, PushResult } from "./queue-transport";
@@ -81,6 +82,7 @@ export async function markQueued(
81
82
  sessionID: string,
82
83
  ts: number,
83
84
  ): Promise<boolean> {
85
+ assertDeliveryLease();
84
86
  return request(opts, "/queued", "POST", { roomId, sessionID, ts })
85
87
  .then(() => true)
86
88
  .catch(() => false);
@@ -93,6 +95,8 @@ export async function centerAction(
93
95
  name?: string;
94
96
  roomId?: string;
95
97
  text?: string;
98
+ receiverOwnerID?: string;
99
+ protocol?: "v1" | "v2";
96
100
  },
97
101
  sessionID: string,
98
102
  ): Promise<string> {
@@ -123,6 +127,7 @@ export async function centerAction(
123
127
  // Record the owning host so only that host wakes this session.
124
128
  host: os.hostname(),
125
129
  directory: opts.directory,
130
+ ...(args.protocol === "v2" ? { protocol: "v2", receiverOwnerID: args.receiverOwnerID } : {}),
126
131
  });
127
132
  return formatRoom(svcOf(room), toRoom(room));
128
133
  }
@@ -142,6 +147,7 @@ export async function centerAction(
142
147
  // Record the owning host so only that host wakes this session.
143
148
  host: os.hostname(),
144
149
  directory: opts.directory,
150
+ ...(args.protocol === "v2" ? { protocol: "v2", receiverOwnerID: args.receiverOwnerID } : {}),
145
151
  },
146
152
  );
147
153
  return formatRoom(svcOf(room), toRoom(room));
@@ -197,7 +203,7 @@ export async function centerAction(
197
203
  opts,
198
204
  `/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(args.roomId)}&excludeSelf=0`,
199
205
  "GET",
200
- )) as unknown as { member: boolean; items: InboxItem[] };
206
+ )) as unknown as { member: boolean; items: InboxItem[]; hasMore?: boolean };
201
207
  // ponytail: F6 — same gate as standalone: only members can read
202
208
  if (!result.member) {
203
209
  return "error: not joined";
@@ -220,7 +226,7 @@ export async function centerAction(
220
226
  })
221
227
  .then(() => clearPendingAdmission(sessionID, args.roomId!, maxTs))
222
228
  .catch(() => {});
223
- return lines.join("\n");
229
+ return lines.join("\n") + (result.hasMore ? "\nMore unread messages remain; poll again." : "");
224
230
  }
225
231
  default:
226
232
  return "error: unknown action";
@@ -9,6 +9,9 @@ import {
9
9
  type QueueItem,
10
10
  } from "./queue";
11
11
  import { request, markQueued, type CenterOpts } from "./center-client";
12
+ import { explicitlyMentions } from "./mentions";
13
+ import { serializeSessionPush } from "./session-delivery";
14
+ export { serializeSessionPush } from "./session-delivery";
12
15
  import {
13
16
  sendAsyncNotification,
14
17
  sendQueue,
@@ -18,18 +21,8 @@ import {
18
21
 
19
22
  export type InboxItem = QueueItem & { roomId: string; roomName: string };
20
23
  const inboxChecks = new Set<string>();
21
- const sessionPushes = new Map<string, Promise<void>>();
22
-
23
- export function serializeSessionPush(sessionID: string, task: () => Promise<void>): Promise<void> {
24
- const previous = sessionPushes.get(sessionID) ?? Promise.resolve();
25
- const run = previous.catch(() => {}).then(task);
26
- let current: Promise<void>;
27
- current = run.finally(() => {
28
- if (sessionPushes.get(sessionID) === current) sessionPushes.delete(sessionID);
29
- });
30
- sessionPushes.set(sessionID, current);
31
- return current;
32
- }
24
+ const restoreScans = new Map<string, { beforeSeq?: number; untilTs?: number }>();
25
+ const restoreKey = (sessionID: string, roomID: string) => JSON.stringify([sessionID, roomID]);
33
26
 
34
27
  export async function checkCenterInbox(
35
28
  opts: CenterOpts,
@@ -43,12 +36,27 @@ export async function checkCenterInbox(
43
36
  const result = await request(opts, `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1`, "GET") as {
44
37
  items?: InboxItem[];
45
38
  queuedTs?: Record<string, number>;
39
+ hasMore?: boolean;
46
40
  };
47
41
  const queued = result.queuedTs ?? {};
48
- const items = (Array.isArray(result.items) ? result.items : []).filter(
42
+ let items = (Array.isArray(result.items) ? result.items : []).filter(
49
43
  (item) => item.createdAt > (queued[item.roomId] ?? 0),
50
44
  );
51
- if (items.length) await pushItemsToSession(opts, sessionID, items, transport, queued);
45
+ const qualified = transport.mentionOnlySessions?.has(sessionID)
46
+ ? await scanRestoredRooms(opts, sessionID, transport.receiverOwnerID ?? "", items, queued, result.hasMore ?? false)
47
+ : new Set<string>();
48
+ if (qualified.size) {
49
+ const merged = new Map(items.map((item) => [item.id, item]));
50
+ for (const roomId of qualified) {
51
+ const page = await request(opts, `/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(roomId)}&excludeSelf=1&timeout=0`, "GET") as {
52
+ items?: InboxItem[]; queuedTs?: Record<string, number>;
53
+ };
54
+ Object.assign(queued, page.queuedTs ?? {});
55
+ for (const item of page.items ?? []) if (item.createdAt > (queued[roomId] ?? 0)) merged.set(item.id, item);
56
+ }
57
+ items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
58
+ }
59
+ if (items.length) await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
52
60
  });
53
61
  } catch {
54
62
  // The next inbox poll retries failed delivery.
@@ -57,27 +65,98 @@ export async function checkCenterInbox(
57
65
  }
58
66
  }
59
67
 
68
+ async function scanRestoredRooms(
69
+ opts: CenterOpts, sessionID: string, ownerID: string, items: InboxItem[],
70
+ queued: Readonly<Record<string, number>>, hasMore: boolean,
71
+ ): Promise<Set<string>> {
72
+ const rooms = new Set(items.map((item) => item.roomId));
73
+ if (hasMore) {
74
+ try {
75
+ const summary = await request(opts, "/rooms/summary", "GET") as unknown as Array<{ id?: string }>;
76
+ for (const room of summary) if (room.id) rooms.add(room.id);
77
+ } catch { /* Keep scanning rooms already present in the bounded inbox page. */ }
78
+ }
79
+ const qualified = new Set<string>();
80
+ for (const roomId of rooms) {
81
+ try {
82
+ const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, { name?: string; protocol?: string; receiverOwnerID?: string; lastReadTs?: number; lastQueuedTs?: number }>;
83
+ const member = registry[sessionID];
84
+ if (!member || member.protocol !== "v2" || member.receiverOwnerID !== ownerID) continue;
85
+ const key = JSON.stringify([sessionID, roomId]);
86
+ const cursor = Math.max(member.lastReadTs ?? 0, member.lastQueuedTs ?? queued[roomId] ?? 0);
87
+ const state = restoreScans.get(key) ?? {};
88
+ if (state.untilTs !== undefined && cursor < state.untilTs) { qualified.add(roomId); continue; }
89
+ state.untilTs = undefined;
90
+ const visible = items.filter((item) => item.roomId === roomId && item.createdAt > cursor).slice(-20);
91
+ if (member.name && visible.some((item) => explicitlyMentions(item, member.name!, sessionID))) {
92
+ state.untilTs = visible.at(-1)!.createdAt;
93
+ restoreScans.set(key, state);
94
+ qualified.add(roomId);
95
+ continue;
96
+ }
97
+ const latest = await request(opts, `/rooms/${encodeURIComponent(roomId)}/history?limit=20&excludeSessionID=${encodeURIComponent(sessionID)}`, "GET") as { messages?: InboxItem[]; nextBeforeSeq?: number | null; hasMore?: boolean };
98
+ const latestUnread = (latest.messages ?? []).filter((item) => item.createdAt > cursor);
99
+ if (member.name && latestUnread.some((item) => explicitlyMentions(item, member.name!, sessionID))) {
100
+ state.untilTs = latestUnread.at(-1)!.createdAt;
101
+ restoreScans.set(key, state);
102
+ qualified.add(roomId);
103
+ continue;
104
+ }
105
+ if (state.beforeSeq === undefined) state.beforeSeq = latest.nextBeforeSeq ?? undefined;
106
+ else {
107
+ const older = await request(opts, `/rooms/${encodeURIComponent(roomId)}/history?beforeSeq=${state.beforeSeq}&limit=20&excludeSessionID=${encodeURIComponent(sessionID)}`, "GET") as { messages?: InboxItem[]; nextBeforeSeq?: number | null; hasMore?: boolean };
108
+ const candidates = (older.messages ?? []).filter((item) => item.createdAt > cursor);
109
+ if (member.name && candidates.some((item) => explicitlyMentions(item, member.name!, sessionID))) {
110
+ state.untilTs = candidates.at(-1)!.createdAt;
111
+ qualified.add(roomId);
112
+ }
113
+ state.beforeSeq = older.hasMore ? older.nextBeforeSeq ?? undefined : undefined;
114
+ }
115
+ restoreScans.set(key, state);
116
+ } catch { /* A room's missing page is retried on the next receiver sweep. */ }
117
+ }
118
+ return qualified;
119
+ }
120
+
60
121
  export async function pushItemsToSession(
61
122
  opts: CenterOpts,
62
123
  sessionID: string,
63
124
  items: InboxItem[],
64
125
  transport: QueueTransport,
65
126
  queuedTs: Readonly<Record<string, number>> = {},
127
+ qualifiedRooms: ReadonlySet<string> = new Set(),
66
128
  ): Promise<PushResult> {
67
129
  const rooms = new Map<string, InboxItem[]>();
130
+ const mentionOnly = transport.mentionOnlySessions?.has(sessionID) ?? false;
68
131
  for (const item of items) {
69
132
  if (item.createdAt <= (queuedTs[item.roomId] ?? 0)) continue;
70
133
  const group = rooms.get(item.roomId) ?? [];
71
- group.push(item);
134
+ if (group.length < 20) group.push(item);
72
135
  rooms.set(item.roomId, group);
73
136
  }
74
137
  let worst: PushResult = "delivered";
75
138
  for (const [roomId, batch] of rooms) {
139
+ const roomMentionOnly = mentionOnly && !qualifiedRooms.has(roomId);
140
+ let recipient: { name?: string; protocol?: string; receiverOwnerID?: string } | undefined;
141
+ if (transport.receiverOwnerID || mentionOnly) {
142
+ try {
143
+ const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, typeof recipient>;
144
+ recipient = registry[sessionID];
145
+ } catch { continue; }
146
+ if (!recipient) continue;
147
+ if (transport.protocol === "v2" && recipient.receiverOwnerID &&
148
+ (recipient.protocol !== "v2" || recipient.receiverOwnerID !== transport.receiverOwnerID)) continue;
149
+ if (roomMentionOnly && (recipient.protocol !== "v2" || recipient.receiverOwnerID !== transport.receiverOwnerID)) continue;
150
+ }
76
151
  const maxTs = batch.reduce((max, item) => Math.max(max, item.createdAt), 0);
77
152
  const existing = pendingAdmission(sessionID, roomId);
78
153
  const delta = existing?.state === "admitted" && maxTs > existing.maxTs
79
154
  ? batch.filter((item) => item.createdAt > existing.maxTs)
80
155
  : batch;
156
+ const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
157
+ if (roomMentionOnly && (!recipient?.name ||
158
+ !eligibleItems.some((item) => explicitlyMentions(item, recipient.name!, sessionID)) &&
159
+ !delta.slice(-20).some((item) => explicitlyMentions(item, recipient.name!, sessionID)))) continue;
81
160
  if (existing?.state === "admitted" && (maxTs <= existing.maxTs || !delta.length)) {
82
161
  if (existing.maxTs > 0 && await markQueued(opts, roomId, sessionID, existing.maxTs)) {
83
162
  clearPendingAdmission(sessionID, roomId, existing.maxTs);
@@ -88,9 +167,19 @@ export async function pushItemsToSession(
88
167
  const { lines, capped } = formatNotificationLines(delta);
89
168
  const prompt = `<notification>\nNew messages in room ${delta[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
90
169
  const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, deltaTs, capped);
170
+ let delivery: "queue" | "steer" = "queue";
171
+ if (transport.protocol === "v2" && transport.backgroundSession) {
172
+ let name = "";
173
+ try {
174
+ const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, { name?: string }>;
175
+ name = registry[sessionID]?.name ?? "";
176
+ } catch { /* Backgrounding is optional; preserve queued delivery. */ }
177
+ if (name && admission.items.some((item) => explicitlyMentions(item, name, sessionID)) &&
178
+ await transport.backgroundSession(sessionID)) delivery = "steer";
179
+ }
91
180
  const result = transport.protocol === "v1"
92
181
  ? await sendAsyncNotification(transport, sessionID, admission.prompt)
93
- : await sendQueue(transport, sessionID, admission.prompt, admission.id);
182
+ : await sendQueue(transport, sessionID, admission.prompt, admission.id, delivery);
94
183
  if (result !== "delivered") {
95
184
  if (result === "rejected") rejectPendingAdmission(sessionID, roomId, admission.id);
96
185
  if (result === "rejected" || worst === "delivered") worst = result;
@@ -0,0 +1,8 @@
1
+ import type { QueueItem } from "./queue";
2
+
3
+ export function explicitlyMentions(item: QueueItem, recipient: string, sessionID?: string): boolean {
4
+ if (!recipient.trim() || item.senderId === "system" || (sessionID !== undefined && item.senderSessionID === sessionID)) return false;
5
+ const escaped = recipient.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6
+ const match = new RegExp(`(?<![\\p{L}\\p{N}_.@])(?:<at>)?@${escaped}(?:</at>)?(?![\\p{L}\\p{N}_])`, "u").exec(item.text);
7
+ return match !== null && match.index + match[0].length <= 300;
8
+ }
@@ -5,11 +5,12 @@ import {
5
5
  formatNotificationLines,
6
6
  loadRegistry,
7
7
  NOTIFY_INSTRUCTION,
8
- saveRegistry,
9
8
  statePath,
10
9
  timeOf,
11
10
  } from "./store";
12
11
  import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
12
+ import { explicitlyMentions } from "./mentions";
13
+ import { serializeSessionPush } from "./center-inbox";
13
14
  import {
14
15
  getOrCreatePendingAdmission,
15
16
  markPendingAdmissionAdmitted,
@@ -43,19 +44,35 @@ export function createNotifier(deps: {
43
44
  sessionID: string,
44
45
  batch: NotifyBatch,
45
46
  transport: QueueTransport = deps.transport(),
47
+ ): Promise<NotifyAttempt | undefined> {
48
+ if (transport.protocol !== "v2") return notifyTargetUnlocked(sessionID, batch, transport);
49
+ return serializeSessionPush(sessionID, () => notifyTargetUnlocked(sessionID, batch, transport));
50
+ }
51
+
52
+ async function notifyTargetUnlocked(
53
+ sessionID: string,
54
+ batch: NotifyBatch,
55
+ transport: QueueTransport,
46
56
  ): Promise<NotifyAttempt | undefined> {
47
57
  const entry = (await loadRegistry())[batch.roomId]?.[sessionID];
48
58
  if (!entry || (entry.protocol !== "v2" && !entry.serverUrl)) return undefined;
59
+ const mentionOnly = transport.mentionOnlySessions?.has(sessionID) ?? false;
60
+ if (transport.protocol === "v2" && entry.receiverOwnerID &&
61
+ (entry.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
62
+ if (mentionOnly && (entry.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
49
63
  const unread = batch.messages.filter((m) =>
50
64
  m.createdAt > Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0) &&
51
65
  (m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== entry.name),
52
- );
66
+ ).slice(0, 20);
53
67
  if (!unread.length) return undefined;
54
68
  const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
55
69
  const existing = pendingAdmission(sessionID, batch.roomId);
56
70
  const delta = existing?.state === "admitted" && maxTs > existing.maxTs
57
71
  ? unread.filter((m) => m.createdAt > existing.maxTs)
58
72
  : unread;
73
+ const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
74
+ if (mentionOnly && !eligibleItems.some((message) => explicitlyMentions(message, entry.name, sessionID)) &&
75
+ !delta.slice(-20).some((message) => explicitlyMentions(message, entry.name, sessionID))) return undefined;
59
76
  const base = entry.serverUrl ? new URL(entry.serverUrl) : undefined;
60
77
  const prefix = entry.protocol === "v2" ? (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "") : "";
61
78
  const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
@@ -80,8 +97,11 @@ export function createNotifier(deps: {
80
97
  serverUrl: entry.serverUrl,
81
98
  directory: entry.directory ?? transport.directory,
82
99
  };
100
+ const mentioned = entry.protocol === "v2" && admission.items.some((message) => explicitlyMentions(message, entry.name, sessionID));
101
+ const delivery = mentioned && targetTransport.backgroundSession &&
102
+ await targetTransport.backgroundSession(sessionID) ? "steer" : "queue";
83
103
  const result = entry.protocol === "v2"
84
- ? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id)
104
+ ? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id, delivery)
85
105
  : await sendAsyncNotification(targetTransport, sessionID, admission.prompt);
86
106
  if (result !== "delivered") {
87
107
  if (result === "rejected") rejectPendingAdmission(sessionID, batch.roomId, admission.id);
@@ -1,9 +1,14 @@
1
1
  import { authHeader } from "./store";
2
2
  import { admissionMatches, type QueueBody } from "./queue";
3
+ import { assertDeliveryLease } from "./session-delivery";
3
4
 
4
5
  export type PushResult = "delivered" | "unreachable" | "rejected";
5
6
  export type QueueTransport = {
6
- promptQueue?: (sessionID: string, id: string, text: string) => Promise<unknown>;
7
+ promptQueue?: (sessionID: string, id: string, text: string, delivery: "queue" | "steer") => Promise<unknown>;
8
+ backgroundSession?: (sessionID: string) => Promise<boolean>;
9
+ receiverOwnerID?: string;
10
+ verifySession?: (sessionID: string) => Promise<string | undefined>;
11
+ mentionOnlySessions?: ReadonlySet<string>;
7
12
  serverUrl?: string;
8
13
  directory?: string;
9
14
  protocol?: "v1" | "v2";
@@ -42,7 +47,7 @@ async function sendQueueInProcess(
42
47
  ): Promise<PushResult> {
43
48
  let result: unknown;
44
49
  try {
45
- result = await transport.promptQueue!(sessionID, body.id, body.prompt.text);
50
+ result = await transport.promptQueue!(sessionID, body.id, body.prompt.text, body.delivery);
46
51
  } catch (error) {
47
52
  const status = statusOf(error);
48
53
  return status === undefined || status === 404 ? "unreachable" : "rejected";
@@ -114,16 +119,19 @@ export async function sendQueue(
114
119
  sessionID: string,
115
120
  text: string,
116
121
  admissionID: string,
122
+ delivery: "queue" | "steer" = "queue",
117
123
  ): Promise<PushResult> {
118
124
  const body: QueueBody = {
119
125
  id: admissionID,
120
126
  prompt: { text },
121
- delivery: "queue",
127
+ delivery,
122
128
  resume: true,
123
129
  };
130
+ assertDeliveryLease();
124
131
  if (transport.promptQueue) {
125
132
  const result = await sendQueueInProcess(transport, sessionID, body);
126
133
  if (result !== "unreachable") return result;
134
+ assertDeliveryLease();
127
135
  }
128
136
  return sendQueueHttp(transport, sessionID, body);
129
137
  }