@alexsun-top/opencode-chat-room 0.2.1 → 0.2.3
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/CHANGELOG.md +20 -1
- package/README.md +29 -20
- package/README.zh-CN.md +27 -21
- package/cli.ts +26 -1
- package/package.json +4 -1
- package/plugin.ts +111 -135
- package/server/chat-server.ts +48 -328
- package/server/history-route.ts +25 -0
- package/server/inbox.ts +9 -0
- package/server/wake.ts +91 -0
- package/src/background.ts +67 -8
- package/src/center-client.ts +8 -2
- package/src/center-inbox.ts +99 -21
- package/src/center-wake.ts +2 -2
- package/src/plugin-notifications.ts +13 -6
- package/src/queue-transport.ts +7 -1
- package/src/queue.ts +17 -55
- package/src/receiver-owner.ts +37 -0
- package/src/receiver-state.ts +92 -0
- package/src/room-service.ts +2 -4
- package/src/session-delivery.ts +51 -0
- package/src/sqlite-state.ts +265 -0
- package/src/store.ts +29 -141
- package/src/v2-plugin.ts +17 -32
- package/src/v2-receiver.ts +109 -0
- package/src/watch.ts +355 -0
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, roomId, 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: "steer", 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
|
+
}
|
package/src/background.ts
CHANGED
|
@@ -1,18 +1,77 @@
|
|
|
1
|
+
import { receiverOwnerID } from "./receiver-owner";
|
|
2
|
+
import { assertDeliveryLease } from "./session-delivery";
|
|
3
|
+
|
|
1
4
|
export async function backgroundOwnSession(sessionID: string, version: string): Promise<boolean> {
|
|
2
5
|
try {
|
|
3
|
-
const
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
headers: Service.headers,
|
|
9
|
-
createClient: (baseUrl, headers) => OpenCode.make({ baseUrl, headers }),
|
|
10
|
-
});
|
|
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
11
|
} catch {
|
|
12
12
|
return false;
|
|
13
13
|
}
|
|
14
14
|
}
|
|
15
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
|
+
|
|
16
75
|
type BackgroundApi = {
|
|
17
76
|
discover(): Promise<{ url: string; auth?: { type: "basic"; username: string; password: string } } | undefined>;
|
|
18
77
|
headers(endpoint: { url: string; auth?: { type: "basic"; username: string; password: string } }): Record<string, string> | undefined;
|
package/src/center-client.ts
CHANGED
|
@@ -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";
|
package/src/center-inbox.ts
CHANGED
|
@@ -10,6 +10,8 @@ import {
|
|
|
10
10
|
} from "./queue";
|
|
11
11
|
import { request, markQueued, type CenterOpts } from "./center-client";
|
|
12
12
|
import { explicitlyMentions } from "./mentions";
|
|
13
|
+
import { serializeSessionPush } from "./session-delivery";
|
|
14
|
+
export { serializeSessionPush } from "./session-delivery";
|
|
13
15
|
import {
|
|
14
16
|
sendAsyncNotification,
|
|
15
17
|
sendQueue,
|
|
@@ -19,18 +21,8 @@ import {
|
|
|
19
21
|
|
|
20
22
|
export type InboxItem = QueueItem & { roomId: string; roomName: string };
|
|
21
23
|
const inboxChecks = new Set<string>();
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
export function serializeSessionPush<T>(sessionID: string, task: () => Promise<T>): Promise<T> {
|
|
25
|
-
const previous = sessionPushes.get(sessionID) ?? Promise.resolve();
|
|
26
|
-
const run = previous.catch(() => {}).then(task);
|
|
27
|
-
let current: Promise<T>;
|
|
28
|
-
current = run.finally(() => {
|
|
29
|
-
if (sessionPushes.get(sessionID) === current) sessionPushes.delete(sessionID);
|
|
30
|
-
});
|
|
31
|
-
sessionPushes.set(sessionID, current);
|
|
32
|
-
return current;
|
|
33
|
-
}
|
|
24
|
+
const restoreScans = new Map<string, { beforeSeq?: number; untilTs?: number }>();
|
|
25
|
+
const restoreKey = (sessionID: string, roomID: string) => JSON.stringify([sessionID, roomID]);
|
|
34
26
|
|
|
35
27
|
export async function checkCenterInbox(
|
|
36
28
|
opts: CenterOpts,
|
|
@@ -44,12 +36,27 @@ export async function checkCenterInbox(
|
|
|
44
36
|
const result = await request(opts, `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1`, "GET") as {
|
|
45
37
|
items?: InboxItem[];
|
|
46
38
|
queuedTs?: Record<string, number>;
|
|
39
|
+
hasMore?: boolean;
|
|
47
40
|
};
|
|
48
41
|
const queued = result.queuedTs ?? {};
|
|
49
|
-
|
|
42
|
+
let items = (Array.isArray(result.items) ? result.items : []).filter(
|
|
50
43
|
(item) => item.createdAt > (queued[item.roomId] ?? 0),
|
|
51
44
|
);
|
|
52
|
-
|
|
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);
|
|
53
60
|
});
|
|
54
61
|
} catch {
|
|
55
62
|
// The next inbox poll retries failed delivery.
|
|
@@ -58,27 +65,98 @@ export async function checkCenterInbox(
|
|
|
58
65
|
}
|
|
59
66
|
}
|
|
60
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
|
+
|
|
61
121
|
export async function pushItemsToSession(
|
|
62
122
|
opts: CenterOpts,
|
|
63
123
|
sessionID: string,
|
|
64
124
|
items: InboxItem[],
|
|
65
125
|
transport: QueueTransport,
|
|
66
126
|
queuedTs: Readonly<Record<string, number>> = {},
|
|
127
|
+
qualifiedRooms: ReadonlySet<string> = new Set(),
|
|
67
128
|
): Promise<PushResult> {
|
|
68
129
|
const rooms = new Map<string, InboxItem[]>();
|
|
130
|
+
const mentionOnly = transport.mentionOnlySessions?.has(sessionID) ?? false;
|
|
69
131
|
for (const item of items) {
|
|
70
132
|
if (item.createdAt <= (queuedTs[item.roomId] ?? 0)) continue;
|
|
71
133
|
const group = rooms.get(item.roomId) ?? [];
|
|
72
|
-
group.push(item);
|
|
134
|
+
if (group.length < 20) group.push(item);
|
|
73
135
|
rooms.set(item.roomId, group);
|
|
74
136
|
}
|
|
75
137
|
let worst: PushResult = "delivered";
|
|
76
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
|
+
}
|
|
77
151
|
const maxTs = batch.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
78
152
|
const existing = pendingAdmission(sessionID, roomId);
|
|
79
153
|
const delta = existing?.state === "admitted" && maxTs > existing.maxTs
|
|
80
154
|
? batch.filter((item) => item.createdAt > existing.maxTs)
|
|
81
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;
|
|
82
160
|
if (existing?.state === "admitted" && (maxTs <= existing.maxTs || !delta.length)) {
|
|
83
161
|
if (existing.maxTs > 0 && await markQueued(opts, roomId, sessionID, existing.maxTs)) {
|
|
84
162
|
clearPendingAdmission(sessionID, roomId, existing.maxTs);
|
|
@@ -87,21 +165,21 @@ export async function pushItemsToSession(
|
|
|
87
165
|
}
|
|
88
166
|
const deltaTs = delta.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
89
167
|
const { lines, capped } = formatNotificationLines(delta);
|
|
90
|
-
const prompt = `<notification>\nNew messages in room ${delta[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
168
|
+
const prompt = `<notification>\nNew messages in room ${delta[0]!.roomName} (${roomId}):\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
91
169
|
const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, deltaTs, capped);
|
|
92
|
-
let delivery: "queue" | "steer" = "queue";
|
|
93
170
|
if (transport.protocol === "v2" && transport.backgroundSession) {
|
|
94
171
|
let name = "";
|
|
95
172
|
try {
|
|
96
173
|
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, { name?: string }>;
|
|
97
174
|
name = registry[sessionID]?.name ?? "";
|
|
98
|
-
} catch { /* Backgrounding is optional; preserve
|
|
99
|
-
if (name && admission.items.some((item) => explicitlyMentions(item, name, sessionID))
|
|
100
|
-
await transport.backgroundSession(sessionID)
|
|
175
|
+
} catch { /* Backgrounding is optional; preserve steer delivery. */ }
|
|
176
|
+
if (name && admission.items.some((item) => explicitlyMentions(item, name, sessionID))) {
|
|
177
|
+
try { await transport.backgroundSession(sessionID); } catch { /* Steering does not depend on backgrounding. */ }
|
|
178
|
+
}
|
|
101
179
|
}
|
|
102
180
|
const result = transport.protocol === "v1"
|
|
103
181
|
? await sendAsyncNotification(transport, sessionID, admission.prompt)
|
|
104
|
-
: await sendQueue(transport, sessionID, admission.prompt, admission.id,
|
|
182
|
+
: await sendQueue(transport, sessionID, admission.prompt, admission.id, "steer");
|
|
105
183
|
if (result !== "delivered") {
|
|
106
184
|
if (result === "rejected") rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
107
185
|
if (result === "rejected" || worst === "delivered") worst = result;
|
package/src/center-wake.ts
CHANGED
|
@@ -40,7 +40,7 @@ async function wakeViaServe(
|
|
|
40
40
|
const target: QueueTransport = { serverUrl: serveUrl, directory: transport.directory, protocol: transport.protocol };
|
|
41
41
|
const result = transport.protocol === "v1"
|
|
42
42
|
? await sendAsyncNotification(target, sessionID, admission.prompt)
|
|
43
|
-
: await sendQueue(target, sessionID, admission.prompt, admission.id);
|
|
43
|
+
: await sendQueue(target, sessionID, admission.prompt, admission.id, "steer");
|
|
44
44
|
if (result === "delivered") {
|
|
45
45
|
void request(opts, "/active", "POST", { sessionID }).catch(() => {});
|
|
46
46
|
markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
|
|
@@ -100,7 +100,7 @@ export async function wakeSessions(
|
|
|
100
100
|
? items.filter((item) => item.createdAt > existing.maxTs) : items;
|
|
101
101
|
if (existing?.state === "admitted" && (currentMax <= existing.maxTs || !delta.length)) return;
|
|
102
102
|
const { lines, capped } = formatNotificationLines(delta);
|
|
103
|
-
const prompt = formatServeWakePrompt(delta[0]!.roomName, lines);
|
|
103
|
+
const prompt = formatServeWakePrompt(delta[0]!.roomName, roomId, lines);
|
|
104
104
|
const maxTs = delta.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
105
105
|
const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, maxTs, capped);
|
|
106
106
|
await wakeViaServe(serveUrl, sessionID, roomId, opts, target, admission);
|
|
@@ -5,7 +5,6 @@ import {
|
|
|
5
5
|
formatNotificationLines,
|
|
6
6
|
loadRegistry,
|
|
7
7
|
NOTIFY_INSTRUCTION,
|
|
8
|
-
saveRegistry,
|
|
9
8
|
statePath,
|
|
10
9
|
timeOf,
|
|
11
10
|
} from "./store";
|
|
@@ -57,16 +56,23 @@ export function createNotifier(deps: {
|
|
|
57
56
|
): Promise<NotifyAttempt | undefined> {
|
|
58
57
|
const entry = (await loadRegistry())[batch.roomId]?.[sessionID];
|
|
59
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;
|
|
60
63
|
const unread = batch.messages.filter((m) =>
|
|
61
64
|
m.createdAt > Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0) &&
|
|
62
65
|
(m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== entry.name),
|
|
63
|
-
);
|
|
66
|
+
).slice(0, 20);
|
|
64
67
|
if (!unread.length) return undefined;
|
|
65
68
|
const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
|
|
66
69
|
const existing = pendingAdmission(sessionID, batch.roomId);
|
|
67
70
|
const delta = existing?.state === "admitted" && maxTs > existing.maxTs
|
|
68
71
|
? unread.filter((m) => m.createdAt > existing.maxTs)
|
|
69
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;
|
|
70
76
|
const base = entry.serverUrl ? new URL(entry.serverUrl) : undefined;
|
|
71
77
|
const prefix = entry.protocol === "v2" ? (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "") : "";
|
|
72
78
|
const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
|
|
@@ -77,7 +83,7 @@ export function createNotifier(deps: {
|
|
|
77
83
|
return { url, status: entry.protocol === "v2" ? 200 : 204 };
|
|
78
84
|
}
|
|
79
85
|
const { lines, capped } = formatNotificationLines(delta);
|
|
80
|
-
const prompt = `<notification>\nNew messages in room ${batch.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
86
|
+
const prompt = `<notification>\nNew messages in room ${batch.roomName} (${batch.roomId}):\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
81
87
|
const deltaTs = delta.reduce((max, m) => Math.max(max, m.createdAt), 0);
|
|
82
88
|
const admission = getOrCreatePendingAdmission(
|
|
83
89
|
sessionID, batch.roomId, delta, prompt, deltaTs, capped,
|
|
@@ -92,10 +98,11 @@ export function createNotifier(deps: {
|
|
|
92
98
|
directory: entry.directory ?? transport.directory,
|
|
93
99
|
};
|
|
94
100
|
const mentioned = entry.protocol === "v2" && admission.items.some((message) => explicitlyMentions(message, entry.name, sessionID));
|
|
95
|
-
|
|
96
|
-
await targetTransport.backgroundSession(sessionID)
|
|
101
|
+
if (mentioned && targetTransport.backgroundSession) {
|
|
102
|
+
try { await targetTransport.backgroundSession(sessionID); } catch { /* Steering does not depend on backgrounding. */ }
|
|
103
|
+
}
|
|
97
104
|
const result = entry.protocol === "v2"
|
|
98
|
-
? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id,
|
|
105
|
+
? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id, "steer")
|
|
99
106
|
: await sendAsyncNotification(targetTransport, sessionID, admission.prompt);
|
|
100
107
|
if (result !== "delivered") {
|
|
101
108
|
if (result === "rejected") rejectPendingAdmission(sessionID, batch.roomId, admission.id);
|
package/src/queue-transport.ts
CHANGED
|
@@ -1,10 +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
7
|
promptQueue?: (sessionID: string, id: string, text: string, delivery: "queue" | "steer") => Promise<unknown>;
|
|
7
8
|
backgroundSession?: (sessionID: string) => Promise<boolean>;
|
|
9
|
+
receiverOwnerID?: string;
|
|
10
|
+
verifySession?: (sessionID: string) => Promise<string | undefined>;
|
|
11
|
+
mentionOnlySessions?: ReadonlySet<string>;
|
|
8
12
|
serverUrl?: string;
|
|
9
13
|
directory?: string;
|
|
10
14
|
protocol?: "v1" | "v2";
|
|
@@ -115,7 +119,7 @@ export async function sendQueue(
|
|
|
115
119
|
sessionID: string,
|
|
116
120
|
text: string,
|
|
117
121
|
admissionID: string,
|
|
118
|
-
delivery: "queue" | "steer" = "
|
|
122
|
+
delivery: "queue" | "steer" = "steer",
|
|
119
123
|
): Promise<PushResult> {
|
|
120
124
|
const body: QueueBody = {
|
|
121
125
|
id: admissionID,
|
|
@@ -123,9 +127,11 @@ export async function sendQueue(
|
|
|
123
127
|
delivery,
|
|
124
128
|
resume: true,
|
|
125
129
|
};
|
|
130
|
+
assertDeliveryLease();
|
|
126
131
|
if (transport.promptQueue) {
|
|
127
132
|
const result = await sendQueueInProcess(transport, sessionID, body);
|
|
128
133
|
if (result !== "unreachable") return result;
|
|
134
|
+
assertDeliveryLease();
|
|
129
135
|
}
|
|
130
136
|
return sendQueueHttp(transport, sessionID, body);
|
|
131
137
|
}
|
package/src/queue.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
+
import { deletePendingAdmission, readPendingAdmission, savePendingAdmission } from "./receiver-state";
|
|
3
|
+
import { assertDeliveryLease } from "./session-delivery";
|
|
2
4
|
|
|
3
5
|
export type QueueItem = {
|
|
4
6
|
id?: string;
|
|
@@ -25,51 +27,9 @@ export type PendingAdmission = {
|
|
|
25
27
|
items: QueueItem[];
|
|
26
28
|
};
|
|
27
29
|
|
|
28
|
-
type PendingEntry = {
|
|
29
|
-
admission: PendingAdmission;
|
|
30
|
-
expiresAt: number;
|
|
31
|
-
};
|
|
32
|
-
|
|
33
|
-
// ponytail: lazy expiry avoids one timer per admission; the hard cap keeps the
|
|
34
|
-
// module-level map bounded even when no later queue activity triggers pruning.
|
|
35
30
|
const PENDING_TTL_MS = 5 * 60_000;
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
function keyFor(sessionID: string, roomId: string): string {
|
|
40
|
-
return `${sessionID}|${roomId}`;
|
|
41
|
-
}
|
|
42
|
-
|
|
43
|
-
function pruneExpired(now: number): void {
|
|
44
|
-
for (const [key, entry] of pending) {
|
|
45
|
-
if (entry.expiresAt <= now) {
|
|
46
|
-
pending.delete(key);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function pendingEntry(key: string, now: number): PendingEntry | undefined {
|
|
52
|
-
pruneExpired(now);
|
|
53
|
-
return pending.get(key);
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function rememberPending(
|
|
57
|
-
key: string,
|
|
58
|
-
admission: PendingAdmission,
|
|
59
|
-
now: number,
|
|
60
|
-
): void {
|
|
61
|
-
pending.delete(key);
|
|
62
|
-
pending.set(key, {
|
|
63
|
-
admission,
|
|
64
|
-
expiresAt: now + PENDING_TTL_MS,
|
|
65
|
-
});
|
|
66
|
-
while (pending.size > MAX_PENDING_ADMISSIONS) {
|
|
67
|
-
const oldest = pending.keys().next();
|
|
68
|
-
if (oldest.done) {
|
|
69
|
-
break;
|
|
70
|
-
}
|
|
71
|
-
pending.delete(oldest.value);
|
|
72
|
-
}
|
|
31
|
+
function save(sessionID: string, roomID: string, admission: PendingAdmission, now: number): void {
|
|
32
|
+
savePendingAdmission(sessionID, roomID, admission, now + PENDING_TTL_MS, now);
|
|
73
33
|
}
|
|
74
34
|
|
|
75
35
|
export function queueAdmissionId(
|
|
@@ -96,7 +56,7 @@ export function pendingAdmission(
|
|
|
96
56
|
sessionID: string,
|
|
97
57
|
roomId: string,
|
|
98
58
|
): PendingAdmission | undefined {
|
|
99
|
-
return
|
|
59
|
+
return readPendingAdmission<PendingAdmission>(sessionID, roomId, Date.now());
|
|
100
60
|
}
|
|
101
61
|
|
|
102
62
|
export function getOrCreatePendingAdmission(
|
|
@@ -107,9 +67,8 @@ export function getOrCreatePendingAdmission(
|
|
|
107
67
|
maxTs: number,
|
|
108
68
|
capped: boolean,
|
|
109
69
|
): PendingAdmission {
|
|
110
|
-
const key = keyFor(sessionID, roomId);
|
|
111
70
|
const now = Date.now();
|
|
112
|
-
const existing =
|
|
71
|
+
const existing = readPendingAdmission<PendingAdmission>(sessionID, roomId, now);
|
|
113
72
|
if (
|
|
114
73
|
existing &&
|
|
115
74
|
(existing.state !== "admitted" || maxTs <= existing.maxTs)
|
|
@@ -126,7 +85,7 @@ export function getOrCreatePendingAdmission(
|
|
|
126
85
|
items: items.slice(-20).map((item) => ({ ...item })),
|
|
127
86
|
};
|
|
128
87
|
if (maxTs > 0) {
|
|
129
|
-
|
|
88
|
+
save(sessionID, roomId, admission, now);
|
|
130
89
|
}
|
|
131
90
|
return admission;
|
|
132
91
|
}
|
|
@@ -136,10 +95,10 @@ export function rejectPendingAdmission(
|
|
|
136
95
|
roomId: string,
|
|
137
96
|
admissionID: string,
|
|
138
97
|
): void {
|
|
139
|
-
|
|
140
|
-
const admission =
|
|
98
|
+
assertDeliveryLease();
|
|
99
|
+
const admission = pendingAdmission(sessionID, roomId);
|
|
141
100
|
if (admission?.state === "pending" && admission.id === admissionID) {
|
|
142
|
-
|
|
101
|
+
deletePendingAdmission(sessionID, roomId);
|
|
143
102
|
}
|
|
144
103
|
}
|
|
145
104
|
|
|
@@ -148,9 +107,12 @@ export function markPendingAdmissionAdmitted(
|
|
|
148
107
|
roomId: string,
|
|
149
108
|
admissionID?: string,
|
|
150
109
|
): PendingAdmission | undefined {
|
|
151
|
-
|
|
110
|
+
assertDeliveryLease();
|
|
111
|
+
const now = Date.now();
|
|
112
|
+
const admission = pendingAdmission(sessionID, roomId);
|
|
152
113
|
if (admission && (admissionID === undefined || admission.id === admissionID)) {
|
|
153
114
|
admission.state = "admitted";
|
|
115
|
+
save(sessionID, roomId, admission, now);
|
|
154
116
|
}
|
|
155
117
|
return admission;
|
|
156
118
|
}
|
|
@@ -160,12 +122,12 @@ export function clearPendingAdmission(
|
|
|
160
122
|
roomId: string,
|
|
161
123
|
confirmedTs: number,
|
|
162
124
|
): void {
|
|
163
|
-
|
|
164
|
-
const admission =
|
|
125
|
+
assertDeliveryLease();
|
|
126
|
+
const admission = pendingAdmission(sessionID, roomId);
|
|
165
127
|
if (!admission || confirmedTs < admission.maxTs) {
|
|
166
128
|
return;
|
|
167
129
|
}
|
|
168
|
-
|
|
130
|
+
deletePendingAdmission(sessionID, roomId);
|
|
169
131
|
}
|
|
170
132
|
|
|
171
133
|
export function admissionMatches(
|