@alexsun-top/opencode-chat-room 0.3.0 → 0.3.1
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 +9 -0
- package/README.md +26 -5
- package/README.zh-CN.md +26 -5
- package/package.json +2 -1
- package/plugin.ts +15 -1
- package/server/assets/chat/events.js +4 -2
- package/server/assets/chat/members.js +120 -14
- package/server/assets/chat/messages.js +81 -9
- package/server/assets/chat/rooms.js +1 -1
- package/server/assets/chat/state.js +12 -1
- package/server/assets/conversation.css +19 -5
- package/server/assets/responsive.css +3 -3
- package/server/chat-server.ts +5 -33
- package/server/member-routes.ts +117 -0
- package/server/newrooms.ts +6 -10
- package/src/agent-presence.ts +60 -0
- package/src/agent-receipts.ts +107 -0
- package/src/center-client.ts +22 -5
- package/src/center-inbox.ts +7 -1
- package/src/member-state.ts +25 -0
- package/src/plugin-notifications.ts +6 -0
- package/src/receiver-state.ts +51 -6
- package/src/sqlite-state.ts +99 -7
- package/src/store.ts +28 -1
- package/src/v2-plugin.ts +10 -2
- package/src/v2-receiver.ts +67 -45
- package/src/watch.ts +17 -3
|
@@ -59,7 +59,7 @@
|
|
|
59
59
|
#chatView > .msg-scroll { grid-column: 2; grid-row: 3; min-height: 0; }
|
|
60
60
|
#chatView > .composer { grid-column: 2; grid-row: 4; }
|
|
61
61
|
.chat-head-main h1 { font-size: 21px; }
|
|
62
|
-
.thread { padding: 28px
|
|
62
|
+
.thread { padding: 28px 24px 12px; }
|
|
63
63
|
.msg-text { max-width: min(82%, 680px); padding: 10px 14px; }
|
|
64
64
|
.composer { padding: 14px 24px calc(14px + env(safe-area-inset-bottom)); }
|
|
65
65
|
.composer-row { max-width: 940px; width: 100%; margin: 0 auto; }
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
.code-copy:hover { color: var(--accent); border-color: var(--accent); }
|
|
73
73
|
.msg-text table { display: block; max-width: 100%; overflow-x: auto; border-collapse: collapse; }
|
|
74
74
|
.msg-text th, .msg-text td { padding: 5px 9px; border: 1px solid var(--line); text-align: left; }
|
|
75
|
-
.msg-text th { background: color-mix(in srgb, var(--accent) 9%, var(--surface)); }
|
|
75
|
+
.msg-text th { white-space: nowrap; background: color-mix(in srgb, var(--accent) 9%, var(--surface)); }
|
|
76
76
|
.msg-text input[type="checkbox"] { accent-color: var(--accent); }
|
|
77
77
|
.msg-text del { color: var(--ink-3); }
|
|
78
78
|
.msg-text hr { border: 0; border-top: 1px solid var(--line); }
|
|
@@ -114,6 +114,6 @@
|
|
|
114
114
|
#chatView > .chat-head { align-items: center; }
|
|
115
115
|
.chat-head-actions { justify-content: flex-start; }
|
|
116
116
|
.chat-head-actions .chip { width: 34px; height: 34px; padding: 0; font-size: 0; }
|
|
117
|
-
.chat-head-actions .panel { position: fixed; top: calc(env(safe-area-inset-top) +
|
|
117
|
+
.chat-head-actions .panel { position: fixed; top: calc(env(safe-area-inset-top) + 196px); left: 12px; right: 12px; width: auto; max-height: min(55dvh, 420px); overflow: auto; }
|
|
118
118
|
.room-meta { max-width: 100px; overflow: hidden; }
|
|
119
119
|
}
|
package/server/chat-server.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { isReceiverOwnerID } from "../src/receiver-owner";
|
|
|
18
18
|
import { claimWake, touchActive, wakeMentionedSessions } from "./wake";
|
|
19
19
|
import { historyRoute } from "./history-route";
|
|
20
20
|
import { roomManagement } from "./newrooms";
|
|
21
|
+
import { memberRoutes } from "./member-routes";
|
|
21
22
|
|
|
22
23
|
function parsePort(value: string): number {
|
|
23
24
|
const port = Number(value);
|
|
@@ -147,6 +148,8 @@ async function handle(req: Request): Promise<Response> {
|
|
|
147
148
|
const rooms = await read((svc) => svc.listRooms().filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller)));
|
|
148
149
|
return json(rooms.map(serializeRoom));
|
|
149
150
|
}
|
|
151
|
+
const members = await memberRoutes(req, url);
|
|
152
|
+
if (members) return members;
|
|
150
153
|
const management = await roomManagement(req, url);
|
|
151
154
|
if (management) return management;
|
|
152
155
|
if (req.method === "POST" && p === "/rooms") {
|
|
@@ -214,38 +217,6 @@ async function handle(req: Request): Promise<Response> {
|
|
|
214
217
|
}
|
|
215
218
|
return json(result);
|
|
216
219
|
}
|
|
217
|
-
if (req.method === "POST" && p === "/read") {
|
|
218
|
-
// ponytail: trusted-client-only — any caller can advance any session's
|
|
219
|
-
// watermark (sessionIDs are unguessable UUIDs and never exposed);
|
|
220
|
-
// accepted as a limitation until real session auth exists
|
|
221
|
-
const body = (await req.json()) as Record<string, unknown>;
|
|
222
|
-
const ts = Number(body.ts);
|
|
223
|
-
const roomId = String(body.roomId ?? "");
|
|
224
|
-
const sessionID = String(body.sessionID ?? "");
|
|
225
|
-
if (
|
|
226
|
-
body.ts === undefined ||
|
|
227
|
-
body.ts === null ||
|
|
228
|
-
!roomId ||
|
|
229
|
-
!sessionID ||
|
|
230
|
-
!Number.isFinite(ts)
|
|
231
|
-
) {
|
|
232
|
-
return json({ error: "roomId/sessionID/finite ts are required" }, 400);
|
|
233
|
-
}
|
|
234
|
-
const updated = await writeState((_svc, reg) => {
|
|
235
|
-
const entry = reg[roomId]?.[sessionID];
|
|
236
|
-
if (!entry) {
|
|
237
|
-
return false;
|
|
238
|
-
}
|
|
239
|
-
entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
|
|
240
|
-
return true;
|
|
241
|
-
});
|
|
242
|
-
if (!updated) {
|
|
243
|
-
return json({ error: "registry entry not found" }, 404);
|
|
244
|
-
}
|
|
245
|
-
clearPendingAdmission(sessionID, roomId, ts);
|
|
246
|
-
touchActive(sessionID); // poll 推进 = 活跃
|
|
247
|
-
return json({ ok: true });
|
|
248
|
-
}
|
|
249
220
|
if (req.method === "POST" && p === "/queued") {
|
|
250
221
|
const body = (await req.json()) as Record<string, unknown>;
|
|
251
222
|
const ts = Number(body.ts);
|
|
@@ -353,9 +324,9 @@ async function handle(req: Request): Promise<Response> {
|
|
|
353
324
|
serverUrl: "",
|
|
354
325
|
apiPrefix: "/api",
|
|
355
326
|
...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
|
|
356
|
-
...(prevEntry?.receiverOwnerID ? { receiverOwnerID: prevEntry.receiverOwnerID } : {}),
|
|
357
327
|
...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
|
|
358
328
|
name,
|
|
329
|
+
...(prevEntry?.membershipID ? { membershipID: prevEntry.membershipID } : {}),
|
|
359
330
|
directory: body.directory || undefined,
|
|
360
331
|
// ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
|
|
361
332
|
host: body.host ?? "",
|
|
@@ -443,6 +414,7 @@ async function handle(req: Request): Promise<Response> {
|
|
|
443
414
|
sid,
|
|
444
415
|
{
|
|
445
416
|
name: e.name,
|
|
417
|
+
membershipID: e.membershipID,
|
|
446
418
|
protocol: e.protocol,
|
|
447
419
|
receiverOwnerID: e.receiverOwnerID,
|
|
448
420
|
lastReadTs: e.lastReadTs ?? 0,
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { memberActivity, type WorkState } from "../src/member-state";
|
|
2
|
+
import { acknowledgeReadWithReceipts, readReceipts, readState, recordMessageReceipts, reportPresence, writeState, type ReceiptEvidence, type ReceiptIdentity } from "../src/store";
|
|
3
|
+
import { isReceiverOwnerID } from "../src/receiver-owner";
|
|
4
|
+
import { clearPendingAdmission } from "../src/queue";
|
|
5
|
+
import { touchActive } from "./wake";
|
|
6
|
+
|
|
7
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
8
|
+
const states = new Set<WorkState>(["working", "idle", "waiting", "unknown"]);
|
|
9
|
+
type Report = { sessionID: string; receiverOwnerID?: string; state: WorkState };
|
|
10
|
+
|
|
11
|
+
function object(value: unknown): value is Record<string, unknown> {
|
|
12
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function memberRoutes(req: Request, url: URL): Promise<Response | undefined> {
|
|
16
|
+
if (req.method === "POST" && url.pathname === "/read") {
|
|
17
|
+
const body = (await req.json()) as Record<string, unknown>;
|
|
18
|
+
const ts = body.ts;
|
|
19
|
+
const roomId = String(body.roomId ?? "");
|
|
20
|
+
const sessionID = String(body.sessionID ?? "");
|
|
21
|
+
const messageIDs = body.messageIDs;
|
|
22
|
+
const hasReceipts = messageIDs !== undefined;
|
|
23
|
+
if (
|
|
24
|
+
body.ts === undefined ||
|
|
25
|
+
body.ts === null ||
|
|
26
|
+
!roomId ||
|
|
27
|
+
!sessionID ||
|
|
28
|
+
typeof ts !== "number" || !Number.isSafeInteger(ts) || ts <= 0 ||
|
|
29
|
+
(hasReceipts && (!Array.isArray(messageIDs) || !messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => typeof id !== "string" || !id || id.length > 128) ||
|
|
30
|
+
typeof body.membershipID !== "string" || !body.membershipID || body.membershipID.length > 128 ||
|
|
31
|
+
typeof body.evidence !== "string" || !["displayed", "tool", "context"].includes(body.evidence) ||
|
|
32
|
+
(body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID))))
|
|
33
|
+
) {
|
|
34
|
+
return json({ error: "invalid read acknowledgement" }, 400);
|
|
35
|
+
}
|
|
36
|
+
if (hasReceipts) {
|
|
37
|
+
const result = await acknowledgeReadWithReceipts(roomId, sessionID, ts, messageIDs as string[], body.evidence as ReceiptEvidence, {
|
|
38
|
+
membershipID: body.membershipID as string,
|
|
39
|
+
...(typeof body.receiverOwnerID === "string" ? { receiverOwnerID: body.receiverOwnerID } : {}),
|
|
40
|
+
});
|
|
41
|
+
if (result.status === "membership") return json({ error: "membership generation mismatch" }, 409);
|
|
42
|
+
if (result.status === "messageIDs") return json({ error: "message IDs do not belong to this room" }, 400);
|
|
43
|
+
if (result.status !== "ok") return json({ error: "read acknowledgement rejected" }, 400);
|
|
44
|
+
clearPendingAdmission(sessionID, roomId, result.readThroughTs ?? 0);
|
|
45
|
+
touchActive(sessionID);
|
|
46
|
+
return json({ ok: true, acceptedIDs: result.acceptedIDs });
|
|
47
|
+
}
|
|
48
|
+
const updated = await writeState((svc, reg) => {
|
|
49
|
+
const entry = reg[roomId]?.[sessionID];
|
|
50
|
+
if (!entry) return false;
|
|
51
|
+
const actualTs = Math.min(ts, svc.getMessages(roomId).at(-1)?.createdAt ?? 0);
|
|
52
|
+
if (actualTs > 0) entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, actualTs);
|
|
53
|
+
return { actualTs };
|
|
54
|
+
});
|
|
55
|
+
if (!updated) return json({ error: "registry entry not found" }, 404);
|
|
56
|
+
clearPendingAdmission(sessionID, roomId, updated.actualTs);
|
|
57
|
+
touchActive(sessionID);
|
|
58
|
+
return json({ ok: true });
|
|
59
|
+
}
|
|
60
|
+
const receiptRoute = url.pathname.match(/^\/rooms\/([^/]+)\/receipts$/);
|
|
61
|
+
if (req.method === "POST" && receiptRoute) {
|
|
62
|
+
const body: unknown = await req.json();
|
|
63
|
+
if (!object(body)) return json({ error: "JSON object body is required" }, 400);
|
|
64
|
+
const sessionID = body.sessionID, membershipID = body.membershipID, evidence = body.evidence;
|
|
65
|
+
const ids = body.messageIDs;
|
|
66
|
+
const ownerID = body.receiverOwnerID;
|
|
67
|
+
if (typeof sessionID !== "string" || !sessionID || sessionID.length > 128 ||
|
|
68
|
+
typeof membershipID !== "string" || !membershipID || membershipID.length > 128 ||
|
|
69
|
+
!Array.isArray(ids) || !ids.length || ids.length > 500 || ids.some((id) => typeof id !== "string" || !id || id.length > 128) ||
|
|
70
|
+
typeof evidence !== "string" || !["displayed", "tool", "context"].includes(evidence) ||
|
|
71
|
+
(ownerID !== undefined && !isReceiverOwnerID(ownerID))) return json({ error: "invalid message receipt" }, 400);
|
|
72
|
+
const identity: ReceiptIdentity = { membershipID, ...(typeof ownerID === "string" ? { receiverOwnerID: ownerID } : {}) };
|
|
73
|
+
const result = await recordMessageReceipts(decodeURIComponent(receiptRoute[1]!), sessionID, ids as string[], evidence as ReceiptEvidence, identity);
|
|
74
|
+
if (result.status === "membership") return json({ error: "membership generation mismatch" }, 409);
|
|
75
|
+
if (result.status === "messageIDs") return json({ error: "message IDs do not belong to this room" }, 400);
|
|
76
|
+
return json({ acceptedIDs: result.acceptedIDs });
|
|
77
|
+
}
|
|
78
|
+
const match = url.pathname.match(/^\/rooms\/([^/]+)\/(members|receipts)$/);
|
|
79
|
+
if (req.method === "GET" && match) {
|
|
80
|
+
const roomID = decodeURIComponent(match[1]!);
|
|
81
|
+
if (match[2] === "members") return json(await readState((svc, registry) => {
|
|
82
|
+
svc.getRoom(roomID);
|
|
83
|
+
return Object.entries(registry[roomID] ?? {}).map(([sessionID, entry]) => ({
|
|
84
|
+
sessionID, membershipID: entry.membershipID!, name: entry.name, ...(entry.protocol ? { protocol: entry.protocol } : {}),
|
|
85
|
+
...(entry.host ? { host: entry.host } : {}),
|
|
86
|
+
type: entry.protocol === "v1" || entry.protocol === "v2" || Boolean(entry.host) ? "agent" : "human",
|
|
87
|
+
activity: memberActivity(entry),
|
|
88
|
+
}));
|
|
89
|
+
}));
|
|
90
|
+
const registry = await readState((svc, entries) => { svc.getRoom(roomID); return entries[roomID] ?? {}; });
|
|
91
|
+
const filter = url.searchParams.get("messageIDs");
|
|
92
|
+
const ids = filter === null ? undefined : filter.split(",");
|
|
93
|
+
if (ids && (!ids.length || ids.length > 500 || ids.some((id) => !id || id.length > 128))) return json({ error: "invalid message IDs" }, 400);
|
|
94
|
+
const receipts = await readReceipts(roomID, ids);
|
|
95
|
+
if (!receipts) return json({ error: "message IDs do not belong to this room" }, 400);
|
|
96
|
+
return json({ receipts: receipts.map((item) => ({ messageID: item.messageID, readers: item.readers.map((reader) => ({ ...reader, currentMember: Boolean(registry[reader.sessionID]) })) })), semantics: "per-message" });
|
|
97
|
+
}
|
|
98
|
+
if (req.method !== "POST" || url.pathname !== "/presence") return undefined;
|
|
99
|
+
const body: unknown = await req.json();
|
|
100
|
+
if (!object(body) || !Array.isArray(body.sessions) || body.sessions.length > 200) return json({ error: "sessions must be an array of at most 200 reports" }, 400);
|
|
101
|
+
const ownerID = body.ownerID;
|
|
102
|
+
const sequence = body.sequence;
|
|
103
|
+
if ((ownerID !== undefined && !isReceiverOwnerID(ownerID)) ||
|
|
104
|
+
(ownerID === undefined && sequence !== undefined) ||
|
|
105
|
+
(ownerID !== undefined && (typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence <= 0))) return json({ error: "invalid owner sequence" }, 400);
|
|
106
|
+
const reports = new Map<string, Report>();
|
|
107
|
+
for (const item of body.sessions) {
|
|
108
|
+
if (!object(item) || typeof item.sessionID !== "string" || !item.sessionID || item.sessionID.length > 128 ||
|
|
109
|
+
typeof item.state !== "string" || !states.has(item.state as WorkState) ||
|
|
110
|
+
(item.receiverOwnerID !== undefined && (!isReceiverOwnerID(item.receiverOwnerID) || item.receiverOwnerID !== ownerID)) ||
|
|
111
|
+
(ownerID === undefined && item.receiverOwnerID !== undefined)) return json({ error: "invalid presence report" }, 400);
|
|
112
|
+
reports.set(item.sessionID, { sessionID: item.sessionID, state: item.state as WorkState,
|
|
113
|
+
...(typeof ownerID === "string" ? { receiverOwnerID: ownerID } : {}) });
|
|
114
|
+
}
|
|
115
|
+
const result = await reportPresence([...reports.values()], ownerID as string | undefined, sequence as number | undefined);
|
|
116
|
+
return json({ updatedSessionIDs: result.stale ? [] : result.updatedSessionIDs });
|
|
117
|
+
}
|
package/server/newrooms.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import RoomService, { RoomError, type Room } from "../src/room-service";
|
|
2
|
-
import {
|
|
2
|
+
import { writeState } from "../src/store";
|
|
3
3
|
import { clearPendingAdmission } from "../src/queue";
|
|
4
4
|
|
|
5
5
|
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
@@ -29,9 +29,13 @@ export async function roomManagement(req: Request, url: URL): Promise<Response |
|
|
|
29
29
|
const members = (registry[direct.id] ??= Object.create(null));
|
|
30
30
|
const tail = direct.messages.at(-1)?.createdAt ?? 0;
|
|
31
31
|
for (const [sid, entry] of [[sessionID, actor], [targetSessionID, target]] as const) {
|
|
32
|
+
const { membershipID: _sourceMembershipID, lastSeenAt: _sourceSeenAt, workState: _sourceWorkState, ...binding } = entry;
|
|
32
33
|
svc.joinRoom(direct.id, { id: sid, name: entry.name });
|
|
33
34
|
const previous = members[sid];
|
|
34
|
-
members[sid] = { ...
|
|
35
|
+
members[sid] = { ...binding, ...(previous?.membershipID ? { membershipID: previous.membershipID } : {}),
|
|
36
|
+
...(previous?.lastSeenAt !== undefined ? { lastSeenAt: previous.lastSeenAt } : {}),
|
|
37
|
+
...(previous?.workState !== undefined ? { workState: previous.workState } : {}),
|
|
38
|
+
lastReadTs: previous ? previous.lastReadTs ?? 0 : tail, lastQueuedTs: previous?.lastQueuedTs ?? 0 };
|
|
35
39
|
}
|
|
36
40
|
return { room: direct, created: !existing };
|
|
37
41
|
});
|
|
@@ -78,13 +82,5 @@ export async function roomManagement(req: Request, url: URL): Promise<Response |
|
|
|
78
82
|
for (const sid of sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
|
|
79
83
|
return json({ ok: true });
|
|
80
84
|
}
|
|
81
|
-
const members = p.match(/^\/rooms\/([^/]+)\/members$/);
|
|
82
|
-
if (members && req.method === "GET") {
|
|
83
|
-
const roomId = decodeURIComponent(members[1]!);
|
|
84
|
-
return json(await readState((svc, registry) => {
|
|
85
|
-
svc.getRoom(roomId);
|
|
86
|
-
return Object.entries(registry[roomId] ?? {}).map(([sessionID, entry]) => ({ sessionID, name: entry.name, ...(entry.protocol ? { protocol: entry.protocol } : {}), ...(entry.host ? { host: entry.host } : {}) }));
|
|
87
|
-
}));
|
|
88
|
-
}
|
|
89
85
|
return undefined;
|
|
90
86
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { reportPresence, type PresenceReport, type Registry } from "./store";
|
|
3
|
+
import { claimPresenceReport, nextPresenceSequence, acquireDeliveryLease, ownsDeliveryLease, releaseDeliveryLease } from "./receiver-state";
|
|
4
|
+
|
|
5
|
+
const LEASE_MS = 20_000;
|
|
6
|
+
const REPORT_MS = 10_000;
|
|
7
|
+
const TIMEOUT_MS = 3_000;
|
|
8
|
+
type Center = { center: string; token: string };
|
|
9
|
+
type Host = { client: { session: { active(options?: { signal?: AbortSignal }): Promise<unknown> } } };
|
|
10
|
+
|
|
11
|
+
export function locallyOwnedSessions(registry: Registry, ownerID: string): Set<string> {
|
|
12
|
+
return new Set(Object.values(registry).flatMap((entries) => Object.entries(entries)
|
|
13
|
+
.filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id)));
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function reportAgentPresence(input: {
|
|
17
|
+
host: Host;
|
|
18
|
+
ownerID: string;
|
|
19
|
+
center: Center;
|
|
20
|
+
sessionIDs: ReadonlySet<string>;
|
|
21
|
+
current(): Promise<boolean>;
|
|
22
|
+
}): Promise<void> {
|
|
23
|
+
const ids = [...new Set(input.sessionIDs)];
|
|
24
|
+
if (!ids.length) return;
|
|
25
|
+
const target = input.center.center ? new URL(input.center.center).origin : "standalone";
|
|
26
|
+
const key = `presence:${input.ownerID}:${target}`;
|
|
27
|
+
const holder = randomUUID();
|
|
28
|
+
const now = Date.now();
|
|
29
|
+
try {
|
|
30
|
+
if (!acquireDeliveryLease(key, holder, now, now + LEASE_MS)) return;
|
|
31
|
+
try {
|
|
32
|
+
if (!claimPresenceReport(input.ownerID, target, now, REPORT_MS)) return;
|
|
33
|
+
const batches = Array.from({ length: Math.ceil(ids.length / 200) }, (_, i) => ids.slice(i * 200, (i + 1) * 200));
|
|
34
|
+
const sequences = batches.map(() => nextPresenceSequence(input.ownerID));
|
|
35
|
+
let active: Record<string, unknown> | undefined;
|
|
36
|
+
try {
|
|
37
|
+
const value = await input.host.client.session.active({ signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
38
|
+
if (value && typeof value === "object" && !Array.isArray(value) &&
|
|
39
|
+
Object.values(value).every((entry) => entry && typeof entry === "object" && (entry as { type?: unknown }).type === "running")) {
|
|
40
|
+
active = value as Record<string, unknown>;
|
|
41
|
+
}
|
|
42
|
+
} catch { /* Unknown is safer than claiming idle when the host API is unavailable. */ }
|
|
43
|
+
const state = (id: string) => active ? Object.hasOwn(active, id) ? "working" : "idle" : "unknown";
|
|
44
|
+
for (let i = 0; i < batches.length; i++) {
|
|
45
|
+
if (!ownsDeliveryLease(key, holder, Date.now()) || !await input.current()) return;
|
|
46
|
+
const sessions = batches[i]!.map((sessionID) => ({ sessionID, receiverOwnerID: input.ownerID, state: state(sessionID) }));
|
|
47
|
+
if (input.center.center) {
|
|
48
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
49
|
+
if (input.center.token) headers.Authorization = `Bearer ${input.center.token}`;
|
|
50
|
+
await fetch(`${input.center.center}/presence`, {
|
|
51
|
+
method: "POST", headers,
|
|
52
|
+
body: JSON.stringify({ ownerID: input.ownerID, sequence: sequences[i], sessions }), signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
53
|
+
}).then((response) => { if (!response.ok) throw new Error(`presence ${response.status}`); }).catch(() => {});
|
|
54
|
+
} else {
|
|
55
|
+
await reportPresence(sessions as PresenceReport[], input.ownerID, sequences[i]).catch(() => {});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} finally { releaseDeliveryLease(key, holder); }
|
|
59
|
+
} catch { /* Presence must never interrupt message delivery. */ }
|
|
60
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { databasePath, recordMessageReceipts } from "./store";
|
|
4
|
+
import { acquireDeliveryLease, deleteReceiptCandidate, markReceiptCandidateReady, ownsDeliveryLease, receiptCandidates, readyReceiptCandidates, releaseDeliveryLease, saveReceiptCandidate } from "./receiver-state";
|
|
5
|
+
|
|
6
|
+
// shortcut: expire unobserved proofs after seven days; increase if hosts may stay disconnected longer.
|
|
7
|
+
const UNOBSERVED_TTL = 7 * 24 * 60 * 60_000;
|
|
8
|
+
type Item = { id?: string; text: string };
|
|
9
|
+
export type ReceiptCandidate = {
|
|
10
|
+
admissionID: string; sessionID: string; roomID: string; membershipID: string;
|
|
11
|
+
receiverOwnerID: string; destination: string; messageIDs: string[]; textHash: string; createdAt: number;
|
|
12
|
+
};
|
|
13
|
+
const hash = (text: string) => createHash("sha256").update(text).digest("hex");
|
|
14
|
+
|
|
15
|
+
export function receiptDestination(center: string): string {
|
|
16
|
+
if (!center) return path.resolve(databasePath());
|
|
17
|
+
const url = new URL(center);
|
|
18
|
+
url.username = ""; url.password = ""; url.search = ""; url.hash = "";
|
|
19
|
+
return url.href.replace(/\/+$/, "");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function prepareReceiptCandidate(input: {
|
|
23
|
+
admissionID: string; sessionID: string; roomID: string; membershipID?: string;
|
|
24
|
+
receiverOwnerID?: string; destination: string; items: Item[]; prompt: string; capped: boolean;
|
|
25
|
+
}): ReceiptCandidate | undefined {
|
|
26
|
+
if (input.capped || !input.membershipID || input.membershipID.length > 128 || !input.receiverOwnerID ||
|
|
27
|
+
!input.sessionID || input.sessionID.length > 128 || !input.roomID || input.roomID.length > 128 ||
|
|
28
|
+
!input.items.length || input.items.length > 500 || input.items.some((item) => typeof item.id !== "string" || !item.id || item.id.length > 128 || typeof item.text !== "string")) return undefined;
|
|
29
|
+
const candidate: ReceiptCandidate = {
|
|
30
|
+
admissionID: input.admissionID, sessionID: input.sessionID, roomID: input.roomID,
|
|
31
|
+
membershipID: input.membershipID, receiverOwnerID: input.receiverOwnerID,
|
|
32
|
+
destination: input.destination, messageIDs: input.items.map((item) => item.id!),
|
|
33
|
+
textHash: hash(input.prompt), createdAt: Date.now(),
|
|
34
|
+
};
|
|
35
|
+
const key = hash(JSON.stringify([candidate.sessionID, candidate.admissionID, candidate.roomID, candidate.destination, candidate.receiverOwnerID, candidate.membershipID]));
|
|
36
|
+
try { saveReceiptCandidate(key, candidate, candidate.createdAt + UNOBSERVED_TTL); }
|
|
37
|
+
catch { return undefined; }
|
|
38
|
+
return candidate;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function contextText(message: unknown): { id: string; text: string } | undefined {
|
|
42
|
+
if (!message || typeof message !== "object") return;
|
|
43
|
+
const value = message as { id?: unknown; role?: unknown; content?: unknown };
|
|
44
|
+
if (value.role !== "user" || typeof value.id !== "string" || !Array.isArray(value.content)) return;
|
|
45
|
+
if (!value.content.every((part) => part && typeof part === "object" && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string")) return;
|
|
46
|
+
return { id: value.id, text: value.content.map((part) => (part as { text: string }).text).join("") };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function observeReceiptContext(sessionID: string, messages: readonly unknown[], destination: string, ownerID: string): number {
|
|
50
|
+
let observed = 0;
|
|
51
|
+
for (const message of messages) {
|
|
52
|
+
const context = contextText(message);
|
|
53
|
+
if (!context) continue;
|
|
54
|
+
for (const candidate of receiptCandidates<ReceiptCandidate>(sessionID, context.id, destination, ownerID, Date.now())) {
|
|
55
|
+
if (hash(context.text) !== candidate.textHash) continue;
|
|
56
|
+
const key = hash(JSON.stringify([candidate.sessionID, candidate.admissionID, candidate.roomID, candidate.destination, candidate.receiverOwnerID, candidate.membershipID]));
|
|
57
|
+
if (markReceiptCandidateReady(key)) observed++;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return observed;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const receiptFlushes = new Map<string, Promise<void>>();
|
|
64
|
+
export function flushReceiptCandidates(input: {
|
|
65
|
+
destination: string; receiverOwnerID?: string; center?: string; token?: string;
|
|
66
|
+
}): Promise<void> {
|
|
67
|
+
const key = JSON.stringify([input.destination, input.receiverOwnerID ?? ""]);
|
|
68
|
+
const running = receiptFlushes.get(key);
|
|
69
|
+
if (running) return running;
|
|
70
|
+
const task = flushOneReceiptCandidate(input).finally(() => receiptFlushes.delete(key));
|
|
71
|
+
receiptFlushes.set(key, task);
|
|
72
|
+
return task;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function flushOneReceiptCandidate(input: { destination: string; receiverOwnerID?: string; center?: string; token?: string }): Promise<void> {
|
|
76
|
+
const leaseKey = `receipt-flush:${hash(JSON.stringify([input.destination, input.receiverOwnerID ?? ""]))}`;
|
|
77
|
+
const holder = randomUUID(), now = Date.now();
|
|
78
|
+
if (!acquireDeliveryLease(leaseKey, holder, now, now + 5000)) return;
|
|
79
|
+
try {
|
|
80
|
+
let candidates: Array<{ id: string; value: ReceiptCandidate }>;
|
|
81
|
+
try { candidates = readyReceiptCandidates<ReceiptCandidate>(input.destination, input.receiverOwnerID, Date.now(), 1); }
|
|
82
|
+
catch { return; }
|
|
83
|
+
for (const { id, value } of candidates) {
|
|
84
|
+
try {
|
|
85
|
+
if (input.center) {
|
|
86
|
+
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
|
87
|
+
if (input.token) headers.Authorization = `Bearer ${input.token}`;
|
|
88
|
+
const response = await fetch(`${input.center.replace(/\/+$/, "")}/rooms/${encodeURIComponent(value.roomID)}/receipts`, {
|
|
89
|
+
method: "POST", headers, body: JSON.stringify({ sessionID: value.sessionID, membershipID: value.membershipID,
|
|
90
|
+
receiverOwnerID: value.receiverOwnerID, messageIDs: value.messageIDs, evidence: "context" }),
|
|
91
|
+
signal: AbortSignal.timeout(3000),
|
|
92
|
+
});
|
|
93
|
+
if (response.ok) {
|
|
94
|
+
const body = await response.json() as { acceptedIDs?: unknown };
|
|
95
|
+
const accepted = new Set(Array.isArray(body.acceptedIDs) ? body.acceptedIDs.filter((item): item is string => typeof item === "string") : []);
|
|
96
|
+
if (value.messageIDs.every((messageID) => accepted.has(messageID)) && ownsDeliveryLease(leaseKey, holder, Date.now())) deleteReceiptCandidate(id);
|
|
97
|
+
} else if (response.status === 400 || response.status === 404 || response.status === 409) deleteReceiptCandidate(id);
|
|
98
|
+
} else {
|
|
99
|
+
await recordMessageReceipts(value.roomID, value.sessionID, value.messageIDs, "context", {
|
|
100
|
+
membershipID: value.membershipID, receiverOwnerID: value.receiverOwnerID,
|
|
101
|
+
});
|
|
102
|
+
deleteReceiptCandidate(id);
|
|
103
|
+
}
|
|
104
|
+
} catch { /* Transient upload failures keep ready proof for the next receiver sweep. */ }
|
|
105
|
+
}
|
|
106
|
+
} finally { releaseDeliveryLease(leaseKey, holder); }
|
|
107
|
+
}
|
package/src/center-client.ts
CHANGED
|
@@ -73,7 +73,7 @@ export async function request(
|
|
|
73
73
|
});
|
|
74
74
|
const data = (await res.json().catch(() => ({}))) as Json;
|
|
75
75
|
if (!res.ok) {
|
|
76
|
-
throw new Error(String(data.error ?? `center error ${res.status}`));
|
|
76
|
+
throw Object.assign(new Error(String(data.error ?? `center error ${res.status}`)), { status: res.status });
|
|
77
77
|
}
|
|
78
78
|
return data;
|
|
79
79
|
}
|
|
@@ -201,6 +201,13 @@ export async function centerAction(
|
|
|
201
201
|
if (!args.roomId) {
|
|
202
202
|
return "error: roomId is required";
|
|
203
203
|
}
|
|
204
|
+
let member: { membershipID?: string; receiverOwnerID?: string } | undefined;
|
|
205
|
+
let legacyCenter = false;
|
|
206
|
+
try {
|
|
207
|
+
const registry = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/registry`, "GET") as Record<string, { membershipID?: string; receiverOwnerID?: string }>;
|
|
208
|
+
member = registry[sessionID];
|
|
209
|
+
legacyCenter = Boolean(member && !member.membershipID);
|
|
210
|
+
} catch (error) { legacyCenter = (error as { status?: number }).status === 404; }
|
|
204
211
|
const result = (await request(
|
|
205
212
|
opts,
|
|
206
213
|
`/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(args.roomId)}&excludeSelf=0`,
|
|
@@ -221,13 +228,23 @@ export async function centerAction(
|
|
|
221
228
|
// following action cannot race the read watermark update. A failure only
|
|
222
229
|
// repeats the messages, never loses them.
|
|
223
230
|
const maxTs = items.reduce((mx, it) => Math.max(mx, it.createdAt), 0);
|
|
224
|
-
|
|
231
|
+
const exactIDs = items.map((item) => item.id);
|
|
232
|
+
const body = {
|
|
225
233
|
roomId: args.roomId,
|
|
226
234
|
sessionID,
|
|
227
235
|
ts: maxTs,
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
236
|
+
...(member?.membershipID && exactIDs.every((id) => typeof id === "string" && id)
|
|
237
|
+
? { messageIDs: exactIDs, membershipID: member.membershipID, evidence: "tool",
|
|
238
|
+
...(member.receiverOwnerID ? { receiverOwnerID: member.receiverOwnerID } : {}) }
|
|
239
|
+
: {}),
|
|
240
|
+
};
|
|
241
|
+
if (member?.membershipID && !exactIDs.every((id) => typeof id === "string" && id)) {
|
|
242
|
+
// Without stable IDs, do not perform an unguarded watermark update.
|
|
243
|
+
} else if (member?.membershipID || legacyCenter) {
|
|
244
|
+
await request(opts, "/read", "POST", body)
|
|
245
|
+
.then(() => clearPendingAdmission(sessionID, args.roomId!, maxTs))
|
|
246
|
+
.catch(() => {});
|
|
247
|
+
}
|
|
231
248
|
return lines.join("\n") + (result.hasMore ? "\nMore unread messages remain; poll again." : "");
|
|
232
249
|
}
|
|
233
250
|
default:
|
package/src/center-inbox.ts
CHANGED
|
@@ -11,6 +11,7 @@ import {
|
|
|
11
11
|
import { request, markQueued, type CenterOpts } from "./center-client";
|
|
12
12
|
import { explicitlyAddresses } from "./mentions";
|
|
13
13
|
import { claimBackgroundAttempt } from "./receiver-state";
|
|
14
|
+
import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
|
|
14
15
|
import { serializeSessionPush } from "./session-delivery";
|
|
15
16
|
export { serializeSessionPush } from "./session-delivery";
|
|
16
17
|
import {
|
|
@@ -147,7 +148,7 @@ export async function pushItemsToSession(
|
|
|
147
148
|
let worst: PushResult = "delivered";
|
|
148
149
|
for (const [roomId, batch] of rooms) {
|
|
149
150
|
const roomMentionOnly = mentionOnly && !qualifiedRooms.has(roomId);
|
|
150
|
-
type Recipient = { name?: string; protocol?: "v1" | "v2"; receiverOwnerID?: string; lastReadTs?: number; lastQueuedTs?: number; roomKind?: "group" | "direct"; host?: string; directory?: string };
|
|
151
|
+
type Recipient = { name?: string; protocol?: "v1" | "v2"; receiverOwnerID?: string; membershipID?: string; lastReadTs?: number; lastQueuedTs?: number; roomKind?: "group" | "direct"; host?: string; directory?: string };
|
|
151
152
|
let recipient: Recipient | undefined;
|
|
152
153
|
try {
|
|
153
154
|
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, Recipient>;
|
|
@@ -211,6 +212,11 @@ export async function pushItemsToSession(
|
|
|
211
212
|
if (!currentAdmission || currentAdmission.id !== admission.id) {
|
|
212
213
|
continue;
|
|
213
214
|
}
|
|
215
|
+
if (transport.protocol === "v2" && current.protocol === "v2") prepareReceiptCandidate({
|
|
216
|
+
admissionID: admission.id, sessionID, roomID: roomId, membershipID: current.membershipID,
|
|
217
|
+
receiverOwnerID: current.receiverOwnerID, destination: receiptDestination(opts.center),
|
|
218
|
+
items: admission.items, prompt: admission.prompt, capped: admission.capped,
|
|
219
|
+
});
|
|
214
220
|
const result = transport.protocol === "v1"
|
|
215
221
|
? await sendAsyncNotification(target, sessionID, admission.prompt)
|
|
216
222
|
: await sendQueue(target, sessionID, admission.prompt, admission.id, "steer");
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { RegistryEntry, WorkState } from "./store";
|
|
2
|
+
|
|
3
|
+
export type { WorkState } from "./store";
|
|
4
|
+
export type ActivityState = WorkState | "offline";
|
|
5
|
+
export const PRESENCE_TTL_MS = 60_000;
|
|
6
|
+
|
|
7
|
+
export function presenceOwnerMatches(entry: RegistryEntry, ownerID?: string): boolean {
|
|
8
|
+
return entry.protocol === "v2"
|
|
9
|
+
? Boolean(entry.receiverOwnerID && entry.receiverOwnerID === ownerID)
|
|
10
|
+
: (entry.protocol === "v1" || entry.protocol === undefined && Boolean(entry.serverUrl || entry.host)) &&
|
|
11
|
+
!entry.receiverOwnerID && ownerID === undefined;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function receiptOwnerMatches(entry: RegistryEntry, ownerID?: string): boolean {
|
|
15
|
+
return entry.receiverOwnerID === undefined
|
|
16
|
+
? ownerID === undefined
|
|
17
|
+
: entry.protocol === "v2" && entry.receiverOwnerID === ownerID;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function memberActivity(entry: RegistryEntry, now = Date.now()): { state: ActivityState; observedAt: number | null } {
|
|
21
|
+
const observedAt = entry.lastSeenAt;
|
|
22
|
+
if (observedAt === undefined) return { state: "unknown", observedAt: null };
|
|
23
|
+
if (now - observedAt >= PRESENCE_TTL_MS) return { state: "offline", observedAt };
|
|
24
|
+
return { state: entry.workState ?? "unknown", observedAt };
|
|
25
|
+
}
|
|
@@ -13,6 +13,7 @@ import { backgroundResult, backgroundServiceKey, sendAsyncNotification, sendQueu
|
|
|
13
13
|
import { explicitlyAddresses } from "./mentions";
|
|
14
14
|
import { claimBackgroundAttempt } from "./receiver-state";
|
|
15
15
|
import { serializeSessionPush } from "./center-inbox";
|
|
16
|
+
import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
|
|
16
17
|
import {
|
|
17
18
|
getOrCreatePendingAdmission,
|
|
18
19
|
clearPendingAdmission,
|
|
@@ -147,6 +148,11 @@ export function createNotifier(deps: {
|
|
|
147
148
|
if (!currentAdmission || currentAdmission.id !== admission.id) {
|
|
148
149
|
return notifyTargetUnlocked(sessionID, batch, transport);
|
|
149
150
|
}
|
|
151
|
+
if (protocol === "v2") prepareReceiptCandidate({
|
|
152
|
+
admissionID: admission.id, sessionID, roomID: batch.roomId, membershipID: currentEntry.membershipID,
|
|
153
|
+
receiverOwnerID: currentEntry.receiverOwnerID, destination: receiptDestination(""),
|
|
154
|
+
items: admission.items, prompt: admission.prompt, capped: admission.capped,
|
|
155
|
+
});
|
|
150
156
|
const result = entry.protocol === "v2"
|
|
151
157
|
? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id, "steer")
|
|
152
158
|
: await sendAsyncNotification(targetTransport, sessionID, admission.prompt);
|
package/src/receiver-state.ts
CHANGED
|
@@ -8,7 +8,7 @@ const pause = (ms: number) => Atomics.wait(new Int32Array(new SharedArrayBuffer(
|
|
|
8
8
|
function initialize(db: Database): void {
|
|
9
9
|
for (let attempt = 0; ; attempt++) {
|
|
10
10
|
try {
|
|
11
|
-
db.exec("PRAGMA journal_mode=WAL; BEGIN IMMEDIATE; CREATE TABLE IF NOT EXISTS delivery_leases(session_id TEXT PRIMARY KEY,holder TEXT NOT NULL,expires_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS pending_admissions(session_id TEXT NOT NULL,room_id TEXT NOT NULL,admission TEXT NOT NULL,expires_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,PRIMARY KEY(session_id,room_id)); CREATE INDEX IF NOT EXISTS pending_admissions_expiry ON pending_admissions(expires_at); CREATE TABLE IF NOT EXISTS background_attempted_through(session_id TEXT NOT NULL,room_id TEXT NOT NULL,service TEXT NOT NULL,through_ts INTEGER NOT NULL,PRIMARY KEY(session_id,room_id,service)); CREATE TABLE IF NOT EXISTS watcher_claims(identity TEXT PRIMARY KEY,instance_id TEXT NOT NULL,pid INTEGER NOT NULL);");
|
|
11
|
+
db.exec("PRAGMA journal_mode=WAL; BEGIN IMMEDIATE; CREATE TABLE IF NOT EXISTS delivery_leases(session_id TEXT PRIMARY KEY,holder TEXT NOT NULL,expires_at INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS pending_admissions(session_id TEXT NOT NULL,room_id TEXT NOT NULL,admission TEXT NOT NULL,expires_at INTEGER NOT NULL,updated_at INTEGER NOT NULL,PRIMARY KEY(session_id,room_id)); CREATE INDEX IF NOT EXISTS pending_admissions_expiry ON pending_admissions(expires_at); CREATE TABLE IF NOT EXISTS background_attempted_through(session_id TEXT NOT NULL,room_id TEXT NOT NULL,service TEXT NOT NULL,through_ts INTEGER NOT NULL,PRIMARY KEY(session_id,room_id,service)); CREATE TABLE IF NOT EXISTS watcher_claims(identity TEXT PRIMARY KEY,instance_id TEXT NOT NULL,pid INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS presence_sequences(owner_id TEXT PRIMARY KEY,sequence INTEGER NOT NULL); CREATE TABLE IF NOT EXISTS presence_throttle(owner_id TEXT NOT NULL,target TEXT NOT NULL,last_report_at INTEGER NOT NULL,PRIMARY KEY(owner_id,target)); CREATE TABLE IF NOT EXISTS receipt_candidates(candidate_id TEXT PRIMARY KEY,session_id TEXT NOT NULL,admission_id TEXT NOT NULL,destination TEXT NOT NULL,owner_id TEXT NOT NULL,candidate TEXT NOT NULL,ready INTEGER NOT NULL,expires_at INTEGER NOT NULL);");
|
|
12
12
|
migrateLegacyBackgroundAttempts(db);
|
|
13
13
|
db.exec("COMMIT");
|
|
14
14
|
return;
|
|
@@ -86,11 +86,10 @@ function immediate<T>(fn: (db: Database) => T): T {
|
|
|
86
86
|
}
|
|
87
87
|
|
|
88
88
|
export function readPendingAdmission<T>(sessionID: string, roomID: string, now: number): T | undefined {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
});
|
|
89
|
+
// Keep notification reads lock-free; saves reclaim expired rows.
|
|
90
|
+
const row = database().query("SELECT admission FROM pending_admissions WHERE session_id=? AND room_id=? AND expires_at>?")
|
|
91
|
+
.get(sessionID, roomID, now) as { admission: string } | null;
|
|
92
|
+
return row ? JSON.parse(row.admission) as T : undefined;
|
|
94
93
|
}
|
|
95
94
|
export function savePendingAdmission(sessionID: string, roomID: string, value: unknown, expiresAt: number, now: number): void {
|
|
96
95
|
immediate((db) => {
|
|
@@ -104,12 +103,58 @@ export function deletePendingAdmission(sessionID: string, roomID: string): void
|
|
|
104
103
|
immediate((db) => db.query("DELETE FROM pending_admissions WHERE session_id=? AND room_id=?").run(sessionID, roomID));
|
|
105
104
|
}
|
|
106
105
|
|
|
106
|
+
export function saveReceiptCandidate(id: string, value: unknown, expiresAt: number): void {
|
|
107
|
+
immediate((db) => {
|
|
108
|
+
db.query("DELETE FROM receipt_candidates WHERE ready=0 AND expires_at<=?").run(Date.now());
|
|
109
|
+
const item = value as { sessionID: string; admissionID: string; destination: string; receiverOwnerID?: string };
|
|
110
|
+
db.query("INSERT INTO receipt_candidates VALUES(?,?,?,?,?,?,0,?) ON CONFLICT(candidate_id) DO UPDATE SET candidate=excluded.candidate")
|
|
111
|
+
.run(id, item.sessionID, item.admissionID, item.destination, item.receiverOwnerID ?? "", JSON.stringify(value), expiresAt);
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
export function receiptCandidates<T>(sessionID: string, admissionID: string, destination: string, ownerID: string, now: number): T[] {
|
|
115
|
+
return immediate((db) => {
|
|
116
|
+
db.query("DELETE FROM receipt_candidates WHERE ready=0 AND expires_at<=?").run(now);
|
|
117
|
+
return (db.query("SELECT candidate FROM receipt_candidates WHERE session_id=? AND admission_id=? AND destination=? AND owner_id=?").all(sessionID, admissionID, destination, ownerID) as Array<{ candidate: string }>).map((row) => JSON.parse(row.candidate) as T);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
export function markReceiptCandidateReady(id: string): boolean {
|
|
121
|
+
return immediate((db) => db.query("UPDATE receipt_candidates SET ready=1,expires_at=? WHERE candidate_id=? AND ready=0")
|
|
122
|
+
.run(Number.MAX_SAFE_INTEGER, id).changes === 1);
|
|
123
|
+
}
|
|
124
|
+
export function readyReceiptCandidates<T>(destination: string, ownerID: string | undefined, now: number, limit?: number): Array<{ id: string; value: T }> {
|
|
125
|
+
return immediate((db) => {
|
|
126
|
+
db.query("DELETE FROM receipt_candidates WHERE ready=0 AND expires_at<=?").run(now);
|
|
127
|
+
const query = "SELECT candidate_id,candidate FROM receipt_candidates WHERE ready=1 AND destination=? AND owner_id=?" + (limit ? " LIMIT ?" : "");
|
|
128
|
+
const rows = (limit ? db.query(query).all(destination, ownerID ?? "", limit) : db.query(query).all(destination, ownerID ?? "")) as Array<{ candidate_id: string; candidate: string }>;
|
|
129
|
+
return rows.map((row) => ({ id: row.candidate_id, value: JSON.parse(row.candidate) as T }));
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
export function deleteReceiptCandidate(id: string): void {
|
|
133
|
+
immediate((db) => db.query("DELETE FROM receipt_candidates WHERE candidate_id=?").run(id));
|
|
134
|
+
}
|
|
135
|
+
|
|
107
136
|
export function claimBackgroundAttempt(sessionID: string, roomID: string, service: string, throughTs: number): boolean {
|
|
108
137
|
return immediate((db) => Number.isSafeInteger(throughTs) && throughTs > 0 &&
|
|
109
138
|
db.query("INSERT INTO background_attempted_through VALUES(?,?,?,?) ON CONFLICT(session_id,room_id,service) DO UPDATE SET through_ts=excluded.through_ts WHERE excluded.through_ts>background_attempted_through.through_ts")
|
|
110
139
|
.run(sessionID, roomID, service, throughTs).changes === 1);
|
|
111
140
|
}
|
|
112
141
|
|
|
142
|
+
export function nextPresenceSequence(ownerID: string): number {
|
|
143
|
+
return immediate((db) => {
|
|
144
|
+
db.query("INSERT INTO presence_sequences VALUES(?,1) ON CONFLICT(owner_id) DO UPDATE SET sequence=sequence+1").run(ownerID);
|
|
145
|
+
return (db.query("SELECT sequence FROM presence_sequences WHERE owner_id=?").get(ownerID) as { sequence: number }).sequence;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function claimPresenceReport(ownerID: string, target: string, now: number, interval: number): boolean {
|
|
150
|
+
return immediate((db) => {
|
|
151
|
+
const row = db.query("SELECT last_report_at FROM presence_throttle WHERE owner_id=? AND target=?").get(ownerID, target) as { last_report_at: number } | null;
|
|
152
|
+
if (row && now - row.last_report_at < interval) return false;
|
|
153
|
+
db.query("INSERT INTO presence_throttle VALUES(?,?,?) ON CONFLICT(owner_id,target) DO UPDATE SET last_report_at=excluded.last_report_at").run(ownerID, target, now);
|
|
154
|
+
return true;
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
113
158
|
export function acquireDeliveryLease(sessionID: string, holder: string, now: number, expiresAt: number): boolean {
|
|
114
159
|
return immediate((db) => {
|
|
115
160
|
db.query("DELETE FROM delivery_leases WHERE expires_at<=?").run(now);
|