@alexsun-top/opencode-chat-room 0.2.3 → 0.3.0
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 +12 -0
- package/README.md +23 -7
- package/README.zh-CN.md +23 -7
- package/package.json +5 -2
- package/plugin.ts +6 -5
- package/server/assets/DOMPURIFY-LICENSE +202 -0
- package/server/assets/MARKED-LICENSE +44 -0
- package/server/assets/NOTICE.txt +6 -0
- package/server/assets/base.css +225 -0
- package/server/assets/chat/events.js +146 -0
- package/server/assets/chat/index.js +12 -0
- package/server/assets/chat/markdown.js +65 -0
- package/server/assets/chat/members.js +95 -0
- package/server/assets/chat/mentions.js +131 -0
- package/server/assets/chat/messages.js +417 -0
- package/server/assets/chat/rooms.js +443 -0
- package/server/assets/chat/state.js +316 -0
- package/server/assets/conversation.css +350 -0
- package/server/assets/dompurify-3.4.7.js +3 -0
- package/server/assets/marked-18.0.4.js +79 -0
- package/server/assets/responsive.css +119 -0
- package/server/chat-server.ts +34 -10
- package/server/chat.html +27 -1984
- package/server/history-route.ts +2 -1
- package/server/inbox.ts +1 -1
- package/server/newrooms.ts +90 -0
- package/server/wake.ts +13 -14
- package/src/background.ts +70 -25
- package/src/center-client.ts +3 -1
- package/src/center-inbox.ts +71 -37
- package/src/center-wake.ts +43 -9
- package/src/mentions.ts +7 -0
- package/src/plugin-notifications.ts +69 -23
- package/src/queue-transport.ts +17 -1
- package/src/queue.ts +36 -2
- package/src/receiver-state.ts +58 -1
- package/src/room-service.ts +19 -1
- package/src/sqlite-state.ts +24 -9
package/server/history-route.ts
CHANGED
|
@@ -15,11 +15,12 @@ export async function historyRoute(url: URL): Promise<Response | undefined> {
|
|
|
15
15
|
return Response.json({ error: "invalid history cursor or limit" }, { status: 400 });
|
|
16
16
|
}
|
|
17
17
|
const access = await readState((service, registry) => ({
|
|
18
|
+
kind: service.listRooms().find((room) => room.id === roomID)?.kind ?? "group",
|
|
18
19
|
exists: service.listRooms().some((room) => room.id === roomID),
|
|
19
20
|
member: excludeSessionID ? registry[roomID]?.[excludeSessionID] : undefined,
|
|
20
21
|
}));
|
|
21
22
|
if (!access.exists || excludeSessionID && !access.member) return Response.json({ error: "room not found" }, { status: 404 });
|
|
22
23
|
const page = await readHistory(roomID, before, limit, access.member && excludeSessionID
|
|
23
24
|
? { sessionID: excludeSessionID, name: access.member.name } : undefined);
|
|
24
|
-
return Response.json({ ...page,
|
|
25
|
+
return Response.json({ ...page, roomKind: access.kind });
|
|
25
26
|
}
|
package/server/inbox.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { readInboxMessages } from "../src/store";
|
|
2
2
|
import type { Message } from "../src/room-service";
|
|
3
3
|
|
|
4
|
-
export type InboxItem = Pick<Message, "id" | "roomId" | "senderId" | "text" | "createdAt"> & { roomName: string };
|
|
4
|
+
export type InboxItem = Pick<Message, "id" | "roomId" | "senderId" | "senderSessionID" | "text" | "createdAt"> & { roomName: string; roomKind?: "group" | "direct" };
|
|
5
5
|
export type InboxResult = { member: boolean; items: InboxItem[]; queuedTs: Record<string, number>; hasMore: boolean };
|
|
6
6
|
|
|
7
7
|
export async function readInbox(sessionID: string, roomFilter: string | null, excludeSelf: boolean): Promise<InboxResult> {
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import RoomService, { RoomError, type Room } from "../src/room-service";
|
|
2
|
+
import { readState, writeState } from "../src/store";
|
|
3
|
+
import { clearPendingAdmission } from "../src/queue";
|
|
4
|
+
|
|
5
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
6
|
+
const serializeRoom = (room: Room) => ({ ...room, participants: [...room.participants.values()], messages: room.messages, kind: room.kind ?? "group" });
|
|
7
|
+
const mutate = <T>(fn: (service: RoomService, registry: import("../src/store").Registry) => T) => writeState(fn);
|
|
8
|
+
async function objectBody(req: Request): Promise<Record<string, unknown> | undefined> {
|
|
9
|
+
const value: unknown = await req.json();
|
|
10
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function roomManagement(req: Request, url: URL): Promise<Response | undefined> {
|
|
14
|
+
const p = url.pathname;
|
|
15
|
+
if (req.method === "POST" && p === "/direct") {
|
|
16
|
+
const body = await objectBody(req);
|
|
17
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
18
|
+
const roomId = typeof body.roomId === "string" ? body.roomId : "";
|
|
19
|
+
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
20
|
+
const targetSessionID = typeof body.targetSessionID === "string" ? body.targetSessionID : "";
|
|
21
|
+
if (!roomId || !sessionID || !targetSessionID || sessionID === targetSessionID || sessionID.length > 128 || targetSessionID.length > 128) return json({ error: "roomId and distinct sessionIDs are required" }, 400);
|
|
22
|
+
const result = await mutate((svc, registry) => {
|
|
23
|
+
svc.getRoom(roomId);
|
|
24
|
+
const actor = registry[roomId]?.[sessionID], target = registry[roomId]?.[targetSessionID];
|
|
25
|
+
if (!actor || !target) throw new RoomError("NOT_JOINED", "both sessions must belong to the source room");
|
|
26
|
+
const pair = JSON.stringify([sessionID, targetSessionID].sort());
|
|
27
|
+
const existing = svc.listRooms().find((room) => room.directPair === pair);
|
|
28
|
+
const direct = existing ?? svc.createDirectRoom(`${actor.name} ↔ ${target.name}`, actor.name, [sessionID, targetSessionID]);
|
|
29
|
+
const members = (registry[direct.id] ??= Object.create(null));
|
|
30
|
+
const tail = direct.messages.at(-1)?.createdAt ?? 0;
|
|
31
|
+
for (const [sid, entry] of [[sessionID, actor], [targetSessionID, target]] as const) {
|
|
32
|
+
svc.joinRoom(direct.id, { id: sid, name: entry.name });
|
|
33
|
+
const previous = members[sid];
|
|
34
|
+
members[sid] = { ...entry, lastReadTs: previous ? previous.lastReadTs ?? 0 : tail, lastQueuedTs: previous?.lastQueuedTs ?? 0 };
|
|
35
|
+
}
|
|
36
|
+
return { room: direct, created: !existing };
|
|
37
|
+
});
|
|
38
|
+
return json(serializeRoom(result.room), result.created ? 201 : 200);
|
|
39
|
+
}
|
|
40
|
+
const kick = p.match(/^\/rooms\/([^/]+)\/kick$/);
|
|
41
|
+
if (kick && req.method === "POST") {
|
|
42
|
+
const roomId = decodeURIComponent(kick[1]!);
|
|
43
|
+
const body = await objectBody(req);
|
|
44
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
45
|
+
const actor = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
46
|
+
const target = typeof body.targetSessionID === "string" ? body.targetSessionID : "";
|
|
47
|
+
if (!actor || !target || actor === target || actor.length > 128 || target.length > 128) return json({ error: "distinct sessionIDs are required" }, 400);
|
|
48
|
+
const result = await mutate((svc, registry) => {
|
|
49
|
+
const room = svc.getRoom(roomId), members = registry[roomId];
|
|
50
|
+
if (!members?.[actor]) throw new RoomError("NOT_JOINED", "actor is not a room member");
|
|
51
|
+
if (room.kind === "direct") throw new RoomError("DIRECT_ROOM_FULL", "delete the direct conversation instead");
|
|
52
|
+
const removed = members[target];
|
|
53
|
+
if (!removed) throw new RoomError("ROOM_NOT_FOUND", "target session is not a room member");
|
|
54
|
+
delete members[target];
|
|
55
|
+
if (!Object.values(members).some((entry) => entry.name === removed.name)) svc.leaveRoom(roomId, removed.name);
|
|
56
|
+
const message = svc.addEvent(roomId, `${removed.name} was removed from the room`);
|
|
57
|
+
if (!Object.keys(members).length) delete registry[roomId];
|
|
58
|
+
return { message, target };
|
|
59
|
+
});
|
|
60
|
+
clearPendingAdmission(result.target, roomId, Number.MAX_SAFE_INTEGER);
|
|
61
|
+
return json({ ok: true, createdAt: result.message.createdAt });
|
|
62
|
+
}
|
|
63
|
+
const remove = p.match(/^\/rooms\/([^/]+)$/);
|
|
64
|
+
if (remove && req.method === "DELETE") {
|
|
65
|
+
const roomId = decodeURIComponent(remove[1]!);
|
|
66
|
+
const body = await objectBody(req);
|
|
67
|
+
if (!body) return json({ error: "JSON object body is required" }, 400);
|
|
68
|
+
const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
|
|
69
|
+
if (!sessionID || sessionID.length > 128) return json({ error: "sessionID is required" }, 400);
|
|
70
|
+
const sessions = await mutate((svc, registry) => {
|
|
71
|
+
svc.getRoom(roomId);
|
|
72
|
+
if (!registry[roomId]?.[sessionID]) throw new RoomError("NOT_JOINED", "actor is not a room member");
|
|
73
|
+
const removed = Object.keys(registry[roomId]);
|
|
74
|
+
svc.deleteRoom(roomId);
|
|
75
|
+
delete registry[roomId];
|
|
76
|
+
return removed;
|
|
77
|
+
});
|
|
78
|
+
for (const sid of sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
|
|
79
|
+
return json({ ok: true });
|
|
80
|
+
}
|
|
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
|
+
return undefined;
|
|
90
|
+
}
|
package/server/wake.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import os from "node:os";
|
|
2
2
|
import type { Message } from "../src/room-service";
|
|
3
|
-
import { authHeader, formatNotificationLines, formatServeWakePrompt, readState, writeState, type RegistryEntry } from "../src/store";
|
|
3
|
+
import { authHeader, formatNotificationLines, formatServeWakePrompt, NOTIFY_INSTRUCTION, readState, writeState, type RegistryEntry } from "../src/store";
|
|
4
4
|
import { admissionMatches, clearPendingAdmission, getOrCreatePendingAdmission, markPendingAdmissionAdmitted, pendingAdmission, rejectPendingAdmission, type QueueBody, type QueueItem } from "../src/queue";
|
|
5
5
|
import { readInbox, type InboxItem } from "./inbox";
|
|
6
|
+
import { explicitlyAddresses } from "../src/mentions";
|
|
6
7
|
|
|
7
8
|
const wakeClaims = new Map<string, number>();
|
|
8
9
|
const activeSessions = new Map<string, number>();
|
|
@@ -21,25 +22,21 @@ export async function wakeMentionedSessions(
|
|
|
21
22
|
senderSessionID: string, triggeringMessage: Message,
|
|
22
23
|
): Promise<void> {
|
|
23
24
|
if (!serveWakeUrl) return;
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
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] ?? {});
|
|
25
|
+
const { roomKind, reg } = await readState((svc, registry) => ({
|
|
26
|
+
roomKind: svc.getRoom(roomId).kind ?? "group",
|
|
27
|
+
reg: registry[roomId] ?? {},
|
|
28
|
+
}));
|
|
32
29
|
for (const [sid, entry] of Object.entries(reg)) {
|
|
33
|
-
if (
|
|
30
|
+
if (entry.protocol === "v2" || !explicitlyAddresses(triggeringMessage, entry.name, sid, roomKind) || entry.host !== os.hostname() ||
|
|
34
31
|
(activeSessions.get(sid) ?? 0) > Date.now() - WAKE_INACTIVE_MS ||
|
|
35
32
|
triggeringMessage.createdAt <= (entry.lastReadTs ?? 0) ||
|
|
36
33
|
triggeringMessage.createdAt <= (entry.lastQueuedTs ?? 0) || !claimWake(sid)) continue;
|
|
37
|
-
void deliverWake(serveWakeUrl, sid, roomId, roomName, entry, triggeringMessage).catch(() => {});
|
|
34
|
+
void deliverWake(serveWakeUrl, sid, roomId, roomName, roomKind, entry, triggeringMessage).catch(() => {});
|
|
38
35
|
}
|
|
39
36
|
}
|
|
40
37
|
|
|
41
38
|
async function deliverWake(
|
|
42
|
-
serveWakeUrl: string, sid: string, roomId: string, roomName: string,
|
|
39
|
+
serveWakeUrl: string, sid: string, roomId: string, roomName: string, roomKind: "group" | "direct",
|
|
43
40
|
entry: RegistryEntry, triggering: Message,
|
|
44
41
|
): Promise<void> {
|
|
45
42
|
const inbox = await readInbox(sid, roomId, true);
|
|
@@ -48,7 +45,7 @@ async function deliverWake(
|
|
|
48
45
|
const queued = Math.max(current.lastQueuedTs ?? 0, inbox.queuedTs[roomId] ?? 0);
|
|
49
46
|
if (triggering.createdAt <= (current.lastReadTs ?? 0) || triggering.createdAt <= queued) return;
|
|
50
47
|
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 };
|
|
48
|
+
const trigger: InboxItem = { id: triggering.id, roomId, roomName, roomKind, senderId: triggering.senderId, text: triggering.text, createdAt: triggering.createdAt };
|
|
52
49
|
const items = queuedItems.some((item) => item.id === trigger.id) ? queuedItems : [...queuedItems, trigger].sort((a, b) => a.createdAt - b.createdAt);
|
|
53
50
|
const maxTs = items.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
54
51
|
const existing = pendingAdmission(sid, roomId);
|
|
@@ -68,7 +65,9 @@ async function deliverWake(
|
|
|
68
65
|
return;
|
|
69
66
|
}
|
|
70
67
|
const { lines, capped } = formatNotificationLines(delta);
|
|
71
|
-
const prompt =
|
|
68
|
+
const prompt = roomKind === "direct"
|
|
69
|
+
? `You received a direct message. Poll and reply in that direct conversation: ${NOTIFY_INSTRUCTION}\n\nNew messages in direct conversation ${roomName} (${roomId}):\n${lines.join("\n")}`
|
|
70
|
+
: formatServeWakePrompt(roomName, roomId, lines);
|
|
72
71
|
const admission = getOrCreatePendingAdmission(sid, roomId, delta as QueueItem[], prompt,
|
|
73
72
|
delta.reduce((max, item) => Math.max(max, item.createdAt), 0), capped);
|
|
74
73
|
const body: QueueBody = { id: admission.id, prompt: { text: admission.prompt }, delivery: "steer", resume: true };
|
package/src/background.ts
CHANGED
|
@@ -1,16 +1,65 @@
|
|
|
1
1
|
import { receiverOwnerID } from "./receiver-owner";
|
|
2
2
|
import { assertDeliveryLease } from "./session-delivery";
|
|
3
|
+
import type { BackgroundResult } from "./queue-transport";
|
|
3
4
|
|
|
4
|
-
|
|
5
|
+
type BackgroundHost = NonNullable<Awaited<ReturnType<typeof discoverVerifiedHost>>> & { pid: number; version: string };
|
|
6
|
+
type HostLookup = { host?: BackgroundHost; result?: BackgroundResult };
|
|
7
|
+
const failed = (reason: string): BackgroundResult => ({ status: "failed", reason });
|
|
8
|
+
const skip = (reason: string): BackgroundResult => ({ status: "skip", reason });
|
|
9
|
+
|
|
10
|
+
function outcome(error: unknown): BackgroundResult {
|
|
11
|
+
const value = error as { name?: string; code?: string; status?: number; response?: { status?: number }; cause?: { code?: string; status?: number } };
|
|
12
|
+
const status = value?.status ?? value?.response?.status ?? value?.cause?.status;
|
|
13
|
+
const code = value?.code ?? value?.cause?.code;
|
|
14
|
+
if (status === 404) return skip("unsupported-or-session-missing");
|
|
15
|
+
if (status === 400 || status === 401 || status === 403) return skip("request-rejected");
|
|
16
|
+
if (value?.name === "TimeoutError" || code === "ETIMEDOUT" || code === "ABORT_ERR") return failed("timeout");
|
|
17
|
+
if (code === "ECONNREFUSED" || code === "ECONNRESET") return failed("connection-failed");
|
|
18
|
+
if (typeof status === "number" && status >= 500) return failed("server-error");
|
|
19
|
+
return status ? skip("request-rejected") : failed("request-unavailable");
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
async function backgroundHost(version: string, compatible: boolean): Promise<HostLookup> {
|
|
23
|
+
try {
|
|
24
|
+
const [{ OpenCode }, { Service }] = await Promise.all([
|
|
25
|
+
import("@opencode/client"), import("@opencode/client/service"),
|
|
26
|
+
]);
|
|
27
|
+
const discover = () => Service.discover({ version: compatible ? (value: string) => /^2\./.test(value) : version });
|
|
28
|
+
let timer: ReturnType<typeof setTimeout>;
|
|
29
|
+
const endpoint = await Promise.race([
|
|
30
|
+
discover(), new Promise<undefined>((resolve) => { timer = setTimeout(() => resolve(undefined), 2000); }),
|
|
31
|
+
]).finally(() => clearTimeout(timer!));
|
|
32
|
+
if (!endpoint) return { result: failed("service-not-registered") };
|
|
33
|
+
const url = new URL(endpoint.url);
|
|
34
|
+
if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)) return { result: skip("non-loopback-registration") };
|
|
35
|
+
const client = OpenCode.make({ baseUrl: url.origin, headers: Service.headers(endpoint) });
|
|
36
|
+
const info = await client.server.info({ signal: AbortSignal.timeout(3000) });
|
|
37
|
+
if (!Number.isInteger(info.pid) || !/^2\./.test(info.version)) return { result: skip("invalid-host-identity") };
|
|
38
|
+
if (!compatible && info.version !== version) return { result: skip("version-mismatch") };
|
|
39
|
+
if (!compatible && info.pid !== process.pid) return { result: skip("process-mismatch") };
|
|
40
|
+
if (compatible) {
|
|
41
|
+
const current = await discover();
|
|
42
|
+
if (!current || new URL(current.url).origin !== url.origin) return { result: skip("registered-service-changed") };
|
|
43
|
+
const verified = await OpenCode.make({ baseUrl: url.origin, headers: Service.headers(current) })
|
|
44
|
+
.server.info({ signal: AbortSignal.timeout(3000) });
|
|
45
|
+
if (verified.pid !== info.pid || verified.version !== info.version) return { result: skip("registered-service-changed") };
|
|
46
|
+
return { host: { origin: url.origin, pid: verified.pid, version: verified.version, client: OpenCode.make({ baseUrl: url.origin, headers: Service.headers(current) }) } };
|
|
47
|
+
}
|
|
48
|
+
return { host: { origin: url.origin, pid: info.pid, version: info.version, client } };
|
|
49
|
+
} catch (error) { return { result: outcome(error) }; }
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function background(host: BackgroundHost, sessionID: string): Promise<BackgroundResult> {
|
|
5
53
|
try {
|
|
6
|
-
const host = await discoverVerifiedHost(version);
|
|
7
|
-
if (!host) return false;
|
|
8
54
|
assertDeliveryLease();
|
|
9
|
-
await host.client.session.background({ sessionID }, { signal: AbortSignal.timeout(
|
|
10
|
-
return
|
|
11
|
-
} catch {
|
|
12
|
-
|
|
13
|
-
|
|
55
|
+
await host.client.session.background({ sessionID }, { signal: AbortSignal.timeout(8000) });
|
|
56
|
+
return { status: "done" };
|
|
57
|
+
} catch (error) { return outcome(error); }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function backgroundOwnSession(sessionID: string, version: string): Promise<BackgroundResult> {
|
|
61
|
+
const lookup = await backgroundHost(version, false);
|
|
62
|
+
return lookup.host ? background(lookup.host, sessionID) : lookup.result!;
|
|
14
63
|
}
|
|
15
64
|
|
|
16
65
|
export async function discoverVerifiedHost(version: string) {
|
|
@@ -53,14 +102,12 @@ export async function discoverCompatibleRegisteredHost() {
|
|
|
53
102
|
export async function backgroundAtCompatibleRegisteredHost(
|
|
54
103
|
sessionID: string,
|
|
55
104
|
expected: { origin: string; pid: number; version: string },
|
|
56
|
-
): Promise<
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
return true;
|
|
63
|
-
} catch { return false; }
|
|
105
|
+
): Promise<BackgroundResult> {
|
|
106
|
+
const lookup = await backgroundHost("", true);
|
|
107
|
+
if (!lookup.host) return lookup.result!;
|
|
108
|
+
const host = lookup.host;
|
|
109
|
+
if (host.origin !== expected.origin || host.pid !== expected.pid || host.version !== expected.version) return skip("registered-service-changed");
|
|
110
|
+
return background(host, sessionID);
|
|
64
111
|
}
|
|
65
112
|
|
|
66
113
|
export async function verifyHostSession(sessionID: string, version: string): Promise<string | undefined> {
|
|
@@ -86,23 +133,21 @@ export async function backgroundAtRegisteredService(
|
|
|
86
133
|
version: string,
|
|
87
134
|
api: BackgroundApi,
|
|
88
135
|
pid = process.pid,
|
|
89
|
-
): Promise<
|
|
136
|
+
): Promise<BackgroundResult> {
|
|
90
137
|
try {
|
|
91
138
|
let timer: ReturnType<typeof setTimeout>;
|
|
92
139
|
const endpoint = await Promise.race([
|
|
93
140
|
api.discover(),
|
|
94
141
|
new Promise<undefined>((resolve) => { timer = setTimeout(() => resolve(undefined), 2000); }),
|
|
95
142
|
]).finally(() => clearTimeout(timer!));
|
|
96
|
-
if (!endpoint) return
|
|
143
|
+
if (!endpoint) return failed("service-not-registered");
|
|
97
144
|
const url = new URL(endpoint.url);
|
|
98
|
-
if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)) return
|
|
145
|
+
if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)) return skip("non-loopback-registration");
|
|
99
146
|
const headers = api.headers(endpoint);
|
|
100
147
|
const client = api.createClient(url.origin, headers);
|
|
101
148
|
const info = await client.server.info({ signal: AbortSignal.timeout(1500) });
|
|
102
|
-
if (info.pid !== pid || info.version !== version) return
|
|
103
|
-
await client.session.background({ sessionID }, { signal: AbortSignal.timeout(
|
|
104
|
-
return
|
|
105
|
-
} catch {
|
|
106
|
-
return false;
|
|
107
|
-
}
|
|
149
|
+
if (info.pid !== pid || info.version !== version) return skip(info.pid !== pid ? "process-mismatch" : "version-mismatch");
|
|
150
|
+
await client.session.background({ sessionID }, { signal: AbortSignal.timeout(8000) });
|
|
151
|
+
return { status: "done" };
|
|
152
|
+
} catch (error) { return outcome(error); }
|
|
108
153
|
}
|
package/src/center-client.ts
CHANGED
|
@@ -36,6 +36,8 @@ function toRoom(r: Json): Room {
|
|
|
36
36
|
name: String(r.name ?? ""),
|
|
37
37
|
ownerId: String(r.ownerId ?? ""),
|
|
38
38
|
createdAt: Number(r.createdAt ?? 0),
|
|
39
|
+
kind: r.kind === "direct" ? "direct" : "group",
|
|
40
|
+
...(Array.isArray(r.directSessionIDs) ? { directSessionIDs: r.directSessionIDs as string[] } : {}),
|
|
39
41
|
participants,
|
|
40
42
|
messages: Array.isArray(r.messages) ? (r.messages as Message[]) : [],
|
|
41
43
|
};
|
|
@@ -103,7 +105,7 @@ export async function centerAction(
|
|
|
103
105
|
const { center, token } = opts;
|
|
104
106
|
switch (args.action) {
|
|
105
107
|
case "list": {
|
|
106
|
-
const rooms = (await request(opts,
|
|
108
|
+
const rooms = (await request(opts, `/rooms?sessionID=${encodeURIComponent(sessionID)}`, "GET")) as unknown as Json[];
|
|
107
109
|
if (!Array.isArray(rooms) || rooms.length === 0) {
|
|
108
110
|
return "no rooms yet";
|
|
109
111
|
}
|
package/src/center-inbox.ts
CHANGED
|
@@ -1,29 +1,39 @@
|
|
|
1
1
|
import { formatNotificationLines, NOTIFY_INSTRUCTION } from "./store";
|
|
2
2
|
import {
|
|
3
|
-
admissionMatches,
|
|
4
3
|
clearPendingAdmission,
|
|
5
4
|
getOrCreatePendingAdmission,
|
|
6
5
|
markPendingAdmissionAdmitted,
|
|
7
6
|
pendingAdmission,
|
|
7
|
+
prunePendingAdmission,
|
|
8
8
|
rejectPendingAdmission,
|
|
9
9
|
type QueueItem,
|
|
10
10
|
} from "./queue";
|
|
11
11
|
import { request, markQueued, type CenterOpts } from "./center-client";
|
|
12
|
-
import {
|
|
12
|
+
import { explicitlyAddresses } from "./mentions";
|
|
13
|
+
import { claimBackgroundAttempt } from "./receiver-state";
|
|
13
14
|
import { serializeSessionPush } from "./session-delivery";
|
|
14
15
|
export { serializeSessionPush } from "./session-delivery";
|
|
15
16
|
import {
|
|
16
17
|
sendAsyncNotification,
|
|
17
18
|
sendQueue,
|
|
19
|
+
backgroundResult,
|
|
20
|
+
backgroundServiceKey,
|
|
21
|
+
type BackgroundResult,
|
|
18
22
|
type PushResult,
|
|
19
23
|
type QueueTransport,
|
|
20
24
|
} from "./queue-transport";
|
|
21
25
|
|
|
22
|
-
export type InboxItem = QueueItem & { roomId: string; roomName: string };
|
|
26
|
+
export type InboxItem = QueueItem & { roomId: string; roomName: string; roomKind?: "group" | "direct" };
|
|
23
27
|
const inboxChecks = new Set<string>();
|
|
24
28
|
const restoreScans = new Map<string, { beforeSeq?: number; untilTs?: number }>();
|
|
25
29
|
const restoreKey = (sessionID: string, roomID: string) => JSON.stringify([sessionID, roomID]);
|
|
26
30
|
|
|
31
|
+
function render(roomName: string, roomId: string, roomKind: "group" | "direct", name: string, items: QueueItem[]) {
|
|
32
|
+
const { lines, capped } = formatNotificationLines(items);
|
|
33
|
+
const context = roomKind === "direct" ? `Direct conversation with ${name} in room ${roomName} (${roomId})` : `New messages in room ${roomName} (${roomId})`;
|
|
34
|
+
return { prompt: `<notification>\n${context}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`, capped };
|
|
35
|
+
}
|
|
36
|
+
|
|
27
37
|
export async function checkCenterInbox(
|
|
28
38
|
opts: CenterOpts,
|
|
29
39
|
sessionID: string,
|
|
@@ -56,7 +66,7 @@ export async function checkCenterInbox(
|
|
|
56
66
|
}
|
|
57
67
|
items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
58
68
|
}
|
|
59
|
-
|
|
69
|
+
await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
|
|
60
70
|
});
|
|
61
71
|
} catch {
|
|
62
72
|
// The next inbox poll retries failed delivery.
|
|
@@ -79,7 +89,7 @@ async function scanRestoredRooms(
|
|
|
79
89
|
const qualified = new Set<string>();
|
|
80
90
|
for (const roomId of rooms) {
|
|
81
91
|
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 }>;
|
|
92
|
+
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, { name?: string; protocol?: string; receiverOwnerID?: string; lastReadTs?: number; lastQueuedTs?: number; roomKind?: "group" | "direct" }>;
|
|
83
93
|
const member = registry[sessionID];
|
|
84
94
|
if (!member || member.protocol !== "v2" || member.receiverOwnerID !== ownerID) continue;
|
|
85
95
|
const key = JSON.stringify([sessionID, roomId]);
|
|
@@ -88,7 +98,7 @@ async function scanRestoredRooms(
|
|
|
88
98
|
if (state.untilTs !== undefined && cursor < state.untilTs) { qualified.add(roomId); continue; }
|
|
89
99
|
state.untilTs = undefined;
|
|
90
100
|
const visible = items.filter((item) => item.roomId === roomId && item.createdAt > cursor).slice(-20);
|
|
91
|
-
if (member.name && visible.some((item) =>
|
|
101
|
+
if (member.name && visible.some((item) => explicitlyAddresses(item, member.name!, sessionID, member.roomKind))) {
|
|
92
102
|
state.untilTs = visible.at(-1)!.createdAt;
|
|
93
103
|
restoreScans.set(key, state);
|
|
94
104
|
qualified.add(roomId);
|
|
@@ -96,7 +106,7 @@ async function scanRestoredRooms(
|
|
|
96
106
|
}
|
|
97
107
|
const latest = await request(opts, `/rooms/${encodeURIComponent(roomId)}/history?limit=20&excludeSessionID=${encodeURIComponent(sessionID)}`, "GET") as { messages?: InboxItem[]; nextBeforeSeq?: number | null; hasMore?: boolean };
|
|
98
108
|
const latestUnread = (latest.messages ?? []).filter((item) => item.createdAt > cursor);
|
|
99
|
-
if (member.name && latestUnread.some((item) =>
|
|
109
|
+
if (member.name && latestUnread.some((item) => explicitlyAddresses(item, member.name!, sessionID, member.roomKind))) {
|
|
100
110
|
state.untilTs = latestUnread.at(-1)!.createdAt;
|
|
101
111
|
restoreScans.set(key, state);
|
|
102
112
|
qualified.add(roomId);
|
|
@@ -106,7 +116,7 @@ async function scanRestoredRooms(
|
|
|
106
116
|
else {
|
|
107
117
|
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
118
|
const candidates = (older.messages ?? []).filter((item) => item.createdAt > cursor);
|
|
109
|
-
if (member.name && candidates.some((item) =>
|
|
119
|
+
if (member.name && candidates.some((item) => explicitlyAddresses(item, member.name!, sessionID, member.roomKind))) {
|
|
110
120
|
state.untilTs = candidates.at(-1)!.createdAt;
|
|
111
121
|
qualified.add(roomId);
|
|
112
122
|
}
|
|
@@ -137,26 +147,31 @@ export async function pushItemsToSession(
|
|
|
137
147
|
let worst: PushResult = "delivered";
|
|
138
148
|
for (const [roomId, batch] of rooms) {
|
|
139
149
|
const roomMentionOnly = mentionOnly && !qualifiedRooms.has(roomId);
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
const
|
|
150
|
+
type Recipient = { name?: string; protocol?: "v1" | "v2"; receiverOwnerID?: string; lastReadTs?: number; lastQueuedTs?: number; roomKind?: "group" | "direct"; host?: string; directory?: string };
|
|
151
|
+
let recipient: Recipient | undefined;
|
|
152
|
+
try {
|
|
153
|
+
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, Recipient>;
|
|
154
|
+
recipient = registry[sessionID];
|
|
155
|
+
} catch { continue; }
|
|
156
|
+
if (!recipient || (recipient.protocol ?? "v1") !== (transport.protocol ?? "v1")) continue;
|
|
157
|
+
if (transport.protocol === "v2" && transport.receiverOwnerID && recipient.receiverOwnerID !== transport.receiverOwnerID) continue;
|
|
158
|
+
if (roomMentionOnly && (recipient.protocol !== "v2" || recipient.receiverOwnerID !== transport.receiverOwnerID)) continue;
|
|
159
|
+
const target = { ...transport, directory: recipient.directory ?? transport.directory };
|
|
160
|
+
const roomKind = recipient.roomKind ?? batch.find((item) => item.roomKind)?.roomKind ?? "group";
|
|
161
|
+
const cutoff = Math.max(queuedTs[roomId] ?? 0, recipient.lastReadTs ?? 0, recipient.lastQueuedTs ?? 0);
|
|
162
|
+
const unread = batch.filter((item) => item.createdAt > cutoff);
|
|
163
|
+
prunePendingAdmission(sessionID, roomId, cutoff,
|
|
164
|
+
(pending) => render(batch[0]!.roomName, roomId, roomKind, recipient!.name ?? "you", pending));
|
|
152
165
|
const existing = pendingAdmission(sessionID, roomId);
|
|
166
|
+
if (!unread.length && existing?.state !== "pending") continue;
|
|
167
|
+
const maxTs = unread.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
153
168
|
const delta = existing?.state === "admitted" && maxTs > existing.maxTs
|
|
154
|
-
?
|
|
155
|
-
:
|
|
169
|
+
? unread.filter((item) => item.createdAt > existing.maxTs)
|
|
170
|
+
: unread;
|
|
156
171
|
const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
|
|
157
172
|
if (roomMentionOnly && (!recipient?.name ||
|
|
158
|
-
!eligibleItems.some((item) =>
|
|
159
|
-
!delta.slice(-20).some((item) =>
|
|
173
|
+
!eligibleItems.some((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind)) &&
|
|
174
|
+
!delta.slice(-20).some((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind)))) continue;
|
|
160
175
|
if (existing?.state === "admitted" && (maxTs <= existing.maxTs || !delta.length)) {
|
|
161
176
|
if (existing.maxTs > 0 && await markQueued(opts, roomId, sessionID, existing.maxTs)) {
|
|
162
177
|
clearPendingAdmission(sessionID, roomId, existing.maxTs);
|
|
@@ -164,22 +179,41 @@ export async function pushItemsToSession(
|
|
|
164
179
|
continue;
|
|
165
180
|
}
|
|
166
181
|
const deltaTs = delta.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
167
|
-
const {
|
|
168
|
-
const prompt = `<notification>\nNew messages in room ${delta[0]!.roomName} (${roomId}):\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
|
|
182
|
+
const { prompt, capped } = render(batch[0]!.roomName, roomId, roomKind, recipient.name ?? "you", delta);
|
|
169
183
|
const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, deltaTs, capped);
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
}
|
|
184
|
+
const addressedTs = recipient.name
|
|
185
|
+
? admission.items.filter((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind))
|
|
186
|
+
.reduce((max, item) => Math.max(max, item.createdAt), 0)
|
|
187
|
+
: 0;
|
|
188
|
+
if (transport.protocol === "v2" && transport.backgroundSession && addressedTs > 0 &&
|
|
189
|
+
claimBackgroundAttempt(sessionID, roomId, backgroundServiceKey(target, opts.center), addressedTs)) {
|
|
190
|
+
let attempt: BackgroundResult;
|
|
191
|
+
try { attempt = backgroundResult(await target.backgroundSession!(sessionID)); }
|
|
192
|
+
catch { attempt = { status: "failed", reason: "request-threw" }; }
|
|
193
|
+
if (attempt.status !== "done") console.warn(`[chat-room] background ${attempt.status} room=${roomId} reason=${attempt.reason ?? "unknown"}`);
|
|
194
|
+
}
|
|
195
|
+
let current: Recipient | undefined;
|
|
196
|
+
try {
|
|
197
|
+
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, Recipient>;
|
|
198
|
+
current = registry[sessionID];
|
|
199
|
+
} catch { current = undefined; }
|
|
200
|
+
if (!current || (current.protocol ?? "v1") !== (recipient.protocol ?? "v1") ||
|
|
201
|
+
(transport.protocol === "v2" && transport.receiverOwnerID && current.receiverOwnerID !== transport.receiverOwnerID) ||
|
|
202
|
+
current.host !== recipient.host || current.directory !== recipient.directory ||
|
|
203
|
+
(current.roomKind ?? "group") !== roomKind) {
|
|
204
|
+
rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
205
|
+
clearPendingAdmission(sessionID, roomId, Number.MAX_SAFE_INTEGER);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const currentCutoff = Math.max(current.lastReadTs ?? 0, current.lastQueuedTs ?? 0, queuedTs[roomId] ?? 0);
|
|
209
|
+
const currentAdmission = prunePendingAdmission(sessionID, roomId, currentCutoff,
|
|
210
|
+
(pending) => render(batch[0]!.roomName, roomId, roomKind, current!.name ?? "you", pending));
|
|
211
|
+
if (!currentAdmission || currentAdmission.id !== admission.id) {
|
|
212
|
+
continue;
|
|
179
213
|
}
|
|
180
214
|
const result = transport.protocol === "v1"
|
|
181
|
-
? await sendAsyncNotification(
|
|
182
|
-
: await sendQueue(
|
|
215
|
+
? await sendAsyncNotification(target, sessionID, admission.prompt)
|
|
216
|
+
: await sendQueue(target, sessionID, admission.prompt, admission.id, "steer");
|
|
183
217
|
if (result !== "delivered") {
|
|
184
218
|
if (result === "rejected") rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
185
219
|
if (result === "rejected" || worst === "delivered") worst = result;
|
package/src/center-wake.ts
CHANGED
|
@@ -3,11 +3,13 @@ import {
|
|
|
3
3
|
formatNotificationLines,
|
|
4
4
|
formatServeWakePrompt,
|
|
5
5
|
} from "./store";
|
|
6
|
+
import { explicitlyAddresses } from "./mentions";
|
|
6
7
|
import {
|
|
7
8
|
clearPendingAdmission,
|
|
8
9
|
getOrCreatePendingAdmission,
|
|
9
10
|
markPendingAdmissionAdmitted,
|
|
10
11
|
pendingAdmission,
|
|
12
|
+
prunePendingAdmission,
|
|
11
13
|
rejectPendingAdmission,
|
|
12
14
|
type PendingAdmission,
|
|
13
15
|
} from "./queue";
|
|
@@ -24,6 +26,10 @@ async function wakeViaServe(
|
|
|
24
26
|
opts: CenterOpts,
|
|
25
27
|
transport: QueueTransport,
|
|
26
28
|
admission: PendingAdmission,
|
|
29
|
+
roomName: string,
|
|
30
|
+
expectedHost: string | undefined,
|
|
31
|
+
expectedDirectory: string | undefined,
|
|
32
|
+
expectedRoomKind: "group" | "direct",
|
|
27
33
|
): Promise<boolean> {
|
|
28
34
|
try {
|
|
29
35
|
const response = await fetch(`${opts.center}/wake-claim`, {
|
|
@@ -37,6 +43,25 @@ async function wakeViaServe(
|
|
|
37
43
|
} catch {
|
|
38
44
|
return false;
|
|
39
45
|
}
|
|
46
|
+
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, {
|
|
47
|
+
protocol?: "v1" | "v2"; receiverOwnerID?: string; lastReadTs?: number; lastQueuedTs?: number;
|
|
48
|
+
name?: string; roomKind?: "group" | "direct"; host?: string; directory?: string;
|
|
49
|
+
}>;
|
|
50
|
+
const current = registry[sessionID];
|
|
51
|
+
const cutoff = Math.max(current?.lastReadTs ?? 0, current?.lastQueuedTs ?? 0);
|
|
52
|
+
const fresh = prunePendingAdmission(sessionID, roomId, cutoff, (items) => {
|
|
53
|
+
const { lines, capped } = formatNotificationLines(items);
|
|
54
|
+
return { prompt: formatServeWakePrompt(roomName, roomId, lines), capped };
|
|
55
|
+
});
|
|
56
|
+
if (!current || (current.protocol ?? "v1") !== (transport.protocol ?? "v1") ||
|
|
57
|
+
(transport.protocol === "v2" && current.receiverOwnerID !== transport.receiverOwnerID) ||
|
|
58
|
+
current.host !== expectedHost || current.directory !== expectedDirectory ||
|
|
59
|
+
(current.roomKind ?? "group") !== expectedRoomKind ||
|
|
60
|
+
!fresh || fresh.id !== admission.id || admission.maxTs <= cutoff) {
|
|
61
|
+
rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
62
|
+
clearPendingAdmission(sessionID, roomId, Number.MAX_SAFE_INTEGER);
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
40
65
|
const target: QueueTransport = { serverUrl: serveUrl, directory: transport.directory, protocol: transport.protocol };
|
|
41
66
|
const result = transport.protocol === "v1"
|
|
42
67
|
? await sendAsyncNotification(target, sessionID, admission.prompt)
|
|
@@ -70,7 +95,8 @@ export async function wakeSessions(
|
|
|
70
95
|
const latest = Number(room.latestMsgTs ?? 0);
|
|
71
96
|
if (!roomId || latest === 0) continue;
|
|
72
97
|
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, {
|
|
73
|
-
name: string;
|
|
98
|
+
name: string; protocol?: "v1" | "v2"; receiverOwnerID?: string; lastReadTs?: number; lastQueuedTs?: number;
|
|
99
|
+
host?: string; directory?: string; roomKind?: "group" | "direct";
|
|
74
100
|
}>;
|
|
75
101
|
for (const [sessionID, entry] of Object.entries(registry)) {
|
|
76
102
|
if (eligibleSessions && !eligibleSessions.has(sessionID)) continue;
|
|
@@ -88,22 +114,30 @@ export async function wakeSessions(
|
|
|
88
114
|
const target = { ...transport, directory: entry.directory ?? transport.directory };
|
|
89
115
|
const pushed = await pushItemsToSession(opts, sessionID, items, target, inbox.queuedTs);
|
|
90
116
|
if (pushed !== "unreachable" || !serveUrl) return;
|
|
91
|
-
const
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
117
|
+
const currentRegistry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, typeof entry>;
|
|
118
|
+
const current = currentRegistry[sessionID];
|
|
119
|
+
if (!current || (current.protocol ?? "v1") !== (entry.protocol ?? "v1") || current.host !== entry.host ||
|
|
120
|
+
current.directory !== entry.directory || (transport.protocol === "v2" && current.receiverOwnerID !== transport.receiverOwnerID)) return;
|
|
121
|
+
const roomKind = current.roomKind ?? "group";
|
|
122
|
+
const currentCursor = Math.max(current.lastReadTs ?? 0, current.lastQueuedTs ?? 0);
|
|
123
|
+
const unread = items.filter((item) => item.createdAt > currentCursor);
|
|
124
|
+
const mentioned = unread.some((item) => explicitlyAddresses(item, current.name, sessionID, roomKind));
|
|
96
125
|
if (!mentioned) return;
|
|
97
|
-
const currentMax =
|
|
126
|
+
const currentMax = unread.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
127
|
+
prunePendingAdmission(sessionID, roomId, currentCursor, (pending) => {
|
|
128
|
+
const { lines, capped } = formatNotificationLines(pending);
|
|
129
|
+
return { prompt: formatServeWakePrompt(unread[0]!.roomName, roomId, lines), capped };
|
|
130
|
+
});
|
|
98
131
|
const existing = pendingAdmission(sessionID, roomId);
|
|
99
132
|
const delta = existing?.state === "admitted" && currentMax > existing.maxTs
|
|
100
|
-
?
|
|
133
|
+
? unread.filter((item) => item.createdAt > existing.maxTs) : unread;
|
|
101
134
|
if (existing?.state === "admitted" && (currentMax <= existing.maxTs || !delta.length)) return;
|
|
102
135
|
const { lines, capped } = formatNotificationLines(delta);
|
|
103
136
|
const prompt = formatServeWakePrompt(delta[0]!.roomName, roomId, lines);
|
|
104
137
|
const maxTs = delta.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
105
138
|
const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, maxTs, capped);
|
|
106
|
-
await wakeViaServe(serveUrl, sessionID, roomId, opts, target, admission
|
|
139
|
+
await wakeViaServe(serveUrl, sessionID, roomId, opts, target, admission,
|
|
140
|
+
delta[0]!.roomName, entry.host, entry.directory, roomKind);
|
|
107
141
|
});
|
|
108
142
|
}
|
|
109
143
|
} catch {
|
package/src/mentions.ts
CHANGED
|
@@ -2,7 +2,14 @@ import type { QueueItem } from "./queue";
|
|
|
2
2
|
|
|
3
3
|
export function explicitlyMentions(item: QueueItem, recipient: string, sessionID?: string): boolean {
|
|
4
4
|
if (!recipient.trim() || item.senderId === "system" || (sessionID !== undefined && item.senderSessionID === sessionID)) return false;
|
|
5
|
+
const broadcast = /(?<![\p{L}\p{N}_.@])(?:<at>)?@(?:all|所有人)(?:<\/at>)?(?![\p{L}\p{N}_])/u.exec(item.text);
|
|
6
|
+
if (broadcast && broadcast.index + broadcast[0].length <= 300) return true;
|
|
5
7
|
const escaped = recipient.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
6
8
|
const match = new RegExp(`(?<![\\p{L}\\p{N}_.@])(?:<at>)?@${escaped}(?:</at>)?(?![\\p{L}\\p{N}_])`, "u").exec(item.text);
|
|
7
9
|
return match !== null && match.index + match[0].length <= 300;
|
|
8
10
|
}
|
|
11
|
+
|
|
12
|
+
export function explicitlyAddresses(item: QueueItem, recipient: string, sessionID?: string, roomKind?: "group" | "direct"): boolean {
|
|
13
|
+
if (roomKind !== "direct") return explicitlyMentions(item, recipient, sessionID);
|
|
14
|
+
return item.senderId !== "system" && item.senderId !== sessionID && item.senderSessionID !== sessionID;
|
|
15
|
+
}
|