@alexsun-top/opencode-chat-room 0.2.3 → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +44 -7
  3. package/README.zh-CN.md +44 -7
  4. package/package.json +6 -2
  5. package/plugin.ts +21 -6
  6. package/server/assets/DOMPURIFY-LICENSE +202 -0
  7. package/server/assets/MARKED-LICENSE +44 -0
  8. package/server/assets/NOTICE.txt +6 -0
  9. package/server/assets/base.css +225 -0
  10. package/server/assets/chat/events.js +148 -0
  11. package/server/assets/chat/index.js +12 -0
  12. package/server/assets/chat/markdown.js +65 -0
  13. package/server/assets/chat/members.js +201 -0
  14. package/server/assets/chat/mentions.js +131 -0
  15. package/server/assets/chat/messages.js +489 -0
  16. package/server/assets/chat/rooms.js +443 -0
  17. package/server/assets/chat/state.js +327 -0
  18. package/server/assets/conversation.css +364 -0
  19. package/server/assets/dompurify-3.4.7.js +3 -0
  20. package/server/assets/marked-18.0.4.js +79 -0
  21. package/server/assets/responsive.css +119 -0
  22. package/server/chat-server.ts +39 -43
  23. package/server/chat.html +27 -1984
  24. package/server/history-route.ts +2 -1
  25. package/server/inbox.ts +1 -1
  26. package/server/member-routes.ts +117 -0
  27. package/server/newrooms.ts +86 -0
  28. package/server/wake.ts +13 -14
  29. package/src/agent-presence.ts +60 -0
  30. package/src/agent-receipts.ts +107 -0
  31. package/src/background.ts +70 -25
  32. package/src/center-client.ts +25 -6
  33. package/src/center-inbox.ts +77 -37
  34. package/src/center-wake.ts +43 -9
  35. package/src/member-state.ts +25 -0
  36. package/src/mentions.ts +7 -0
  37. package/src/plugin-notifications.ts +75 -23
  38. package/src/queue-transport.ts +17 -1
  39. package/src/queue.ts +36 -2
  40. package/src/receiver-state.ts +108 -6
  41. package/src/room-service.ts +19 -1
  42. package/src/sqlite-state.ts +123 -16
  43. package/src/store.ts +28 -1
  44. package/src/v2-plugin.ts +10 -2
  45. package/src/v2-receiver.ts +67 -45
  46. package/src/watch.ts +17 -3
@@ -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
  };
@@ -71,7 +73,7 @@ export async function request(
71
73
  });
72
74
  const data = (await res.json().catch(() => ({}))) as Json;
73
75
  if (!res.ok) {
74
- 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 });
75
77
  }
76
78
  return data;
77
79
  }
@@ -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, "/rooms", "GET")) as unknown as Json[];
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
  }
@@ -199,6 +201,13 @@ export async function centerAction(
199
201
  if (!args.roomId) {
200
202
  return "error: roomId is required";
201
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; }
202
211
  const result = (await request(
203
212
  opts,
204
213
  `/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(args.roomId)}&excludeSelf=0`,
@@ -219,13 +228,23 @@ export async function centerAction(
219
228
  // following action cannot race the read watermark update. A failure only
220
229
  // repeats the messages, never loses them.
221
230
  const maxTs = items.reduce((mx, it) => Math.max(mx, it.createdAt), 0);
222
- await request(opts, "/read", "POST", {
231
+ const exactIDs = items.map((item) => item.id);
232
+ const body = {
223
233
  roomId: args.roomId,
224
234
  sessionID,
225
235
  ts: maxTs,
226
- })
227
- .then(() => clearPendingAdmission(sessionID, args.roomId!, maxTs))
228
- .catch(() => {});
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
+ }
229
248
  return lines.join("\n") + (result.hasMore ? "\nMore unread messages remain; poll again." : "");
230
249
  }
231
250
  default:
@@ -1,29 +1,40 @@
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 { explicitlyMentions } from "./mentions";
12
+ import { explicitlyAddresses } from "./mentions";
13
+ import { claimBackgroundAttempt } from "./receiver-state";
14
+ import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
13
15
  import { serializeSessionPush } from "./session-delivery";
14
16
  export { serializeSessionPush } from "./session-delivery";
15
17
  import {
16
18
  sendAsyncNotification,
17
19
  sendQueue,
20
+ backgroundResult,
21
+ backgroundServiceKey,
22
+ type BackgroundResult,
18
23
  type PushResult,
19
24
  type QueueTransport,
20
25
  } from "./queue-transport";
21
26
 
22
- export type InboxItem = QueueItem & { roomId: string; roomName: string };
27
+ export type InboxItem = QueueItem & { roomId: string; roomName: string; roomKind?: "group" | "direct" };
23
28
  const inboxChecks = new Set<string>();
24
29
  const restoreScans = new Map<string, { beforeSeq?: number; untilTs?: number }>();
25
30
  const restoreKey = (sessionID: string, roomID: string) => JSON.stringify([sessionID, roomID]);
26
31
 
32
+ function render(roomName: string, roomId: string, roomKind: "group" | "direct", name: string, items: QueueItem[]) {
33
+ const { lines, capped } = formatNotificationLines(items);
34
+ const context = roomKind === "direct" ? `Direct conversation with ${name} in room ${roomName} (${roomId})` : `New messages in room ${roomName} (${roomId})`;
35
+ return { prompt: `<notification>\n${context}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`, capped };
36
+ }
37
+
27
38
  export async function checkCenterInbox(
28
39
  opts: CenterOpts,
29
40
  sessionID: string,
@@ -56,7 +67,7 @@ export async function checkCenterInbox(
56
67
  }
57
68
  items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
58
69
  }
59
- if (items.length) await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
70
+ await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
60
71
  });
61
72
  } catch {
62
73
  // The next inbox poll retries failed delivery.
@@ -79,7 +90,7 @@ async function scanRestoredRooms(
79
90
  const qualified = new Set<string>();
80
91
  for (const roomId of rooms) {
81
92
  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 }>;
93
+ 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
94
  const member = registry[sessionID];
84
95
  if (!member || member.protocol !== "v2" || member.receiverOwnerID !== ownerID) continue;
85
96
  const key = JSON.stringify([sessionID, roomId]);
@@ -88,7 +99,7 @@ async function scanRestoredRooms(
88
99
  if (state.untilTs !== undefined && cursor < state.untilTs) { qualified.add(roomId); continue; }
89
100
  state.untilTs = undefined;
90
101
  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))) {
102
+ if (member.name && visible.some((item) => explicitlyAddresses(item, member.name!, sessionID, member.roomKind))) {
92
103
  state.untilTs = visible.at(-1)!.createdAt;
93
104
  restoreScans.set(key, state);
94
105
  qualified.add(roomId);
@@ -96,7 +107,7 @@ async function scanRestoredRooms(
96
107
  }
97
108
  const latest = await request(opts, `/rooms/${encodeURIComponent(roomId)}/history?limit=20&excludeSessionID=${encodeURIComponent(sessionID)}`, "GET") as { messages?: InboxItem[]; nextBeforeSeq?: number | null; hasMore?: boolean };
98
109
  const latestUnread = (latest.messages ?? []).filter((item) => item.createdAt > cursor);
99
- if (member.name && latestUnread.some((item) => explicitlyMentions(item, member.name!, sessionID))) {
110
+ if (member.name && latestUnread.some((item) => explicitlyAddresses(item, member.name!, sessionID, member.roomKind))) {
100
111
  state.untilTs = latestUnread.at(-1)!.createdAt;
101
112
  restoreScans.set(key, state);
102
113
  qualified.add(roomId);
@@ -106,7 +117,7 @@ async function scanRestoredRooms(
106
117
  else {
107
118
  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
119
  const candidates = (older.messages ?? []).filter((item) => item.createdAt > cursor);
109
- if (member.name && candidates.some((item) => explicitlyMentions(item, member.name!, sessionID))) {
120
+ if (member.name && candidates.some((item) => explicitlyAddresses(item, member.name!, sessionID, member.roomKind))) {
110
121
  state.untilTs = candidates.at(-1)!.createdAt;
111
122
  qualified.add(roomId);
112
123
  }
@@ -137,26 +148,31 @@ export async function pushItemsToSession(
137
148
  let worst: PushResult = "delivered";
138
149
  for (const [roomId, batch] of rooms) {
139
150
  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
- }
151
- const maxTs = batch.reduce((max, item) => Math.max(max, item.createdAt), 0);
151
+ type Recipient = { name?: string; protocol?: "v1" | "v2"; receiverOwnerID?: string; membershipID?: string; lastReadTs?: number; lastQueuedTs?: number; roomKind?: "group" | "direct"; host?: string; directory?: string };
152
+ let recipient: Recipient | undefined;
153
+ try {
154
+ const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, Recipient>;
155
+ recipient = registry[sessionID];
156
+ } catch { continue; }
157
+ if (!recipient || (recipient.protocol ?? "v1") !== (transport.protocol ?? "v1")) continue;
158
+ if (transport.protocol === "v2" && transport.receiverOwnerID && recipient.receiverOwnerID !== transport.receiverOwnerID) continue;
159
+ if (roomMentionOnly && (recipient.protocol !== "v2" || recipient.receiverOwnerID !== transport.receiverOwnerID)) continue;
160
+ const target = { ...transport, directory: recipient.directory ?? transport.directory };
161
+ const roomKind = recipient.roomKind ?? batch.find((item) => item.roomKind)?.roomKind ?? "group";
162
+ const cutoff = Math.max(queuedTs[roomId] ?? 0, recipient.lastReadTs ?? 0, recipient.lastQueuedTs ?? 0);
163
+ const unread = batch.filter((item) => item.createdAt > cutoff);
164
+ prunePendingAdmission(sessionID, roomId, cutoff,
165
+ (pending) => render(batch[0]!.roomName, roomId, roomKind, recipient!.name ?? "you", pending));
152
166
  const existing = pendingAdmission(sessionID, roomId);
167
+ if (!unread.length && existing?.state !== "pending") continue;
168
+ const maxTs = unread.reduce((max, item) => Math.max(max, item.createdAt), 0);
153
169
  const delta = existing?.state === "admitted" && maxTs > existing.maxTs
154
- ? batch.filter((item) => item.createdAt > existing.maxTs)
155
- : batch;
170
+ ? unread.filter((item) => item.createdAt > existing.maxTs)
171
+ : unread;
156
172
  const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
157
173
  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;
174
+ !eligibleItems.some((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind)) &&
175
+ !delta.slice(-20).some((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind)))) continue;
160
176
  if (existing?.state === "admitted" && (maxTs <= existing.maxTs || !delta.length)) {
161
177
  if (existing.maxTs > 0 && await markQueued(opts, roomId, sessionID, existing.maxTs)) {
162
178
  clearPendingAdmission(sessionID, roomId, existing.maxTs);
@@ -164,22 +180,46 @@ export async function pushItemsToSession(
164
180
  continue;
165
181
  }
166
182
  const deltaTs = delta.reduce((max, item) => Math.max(max, item.createdAt), 0);
167
- const { lines, capped } = formatNotificationLines(delta);
168
- const prompt = `<notification>\nNew messages in room ${delta[0]!.roomName} (${roomId}):\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
183
+ const { prompt, capped } = render(batch[0]!.roomName, roomId, roomKind, recipient.name ?? "you", delta);
169
184
  const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, deltaTs, capped);
170
- if (transport.protocol === "v2" && transport.backgroundSession) {
171
- let name = "";
172
- try {
173
- const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, { name?: string }>;
174
- name = registry[sessionID]?.name ?? "";
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
- }
185
+ const addressedTs = recipient.name
186
+ ? admission.items.filter((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind))
187
+ .reduce((max, item) => Math.max(max, item.createdAt), 0)
188
+ : 0;
189
+ if (transport.protocol === "v2" && transport.backgroundSession && addressedTs > 0 &&
190
+ claimBackgroundAttempt(sessionID, roomId, backgroundServiceKey(target, opts.center), addressedTs)) {
191
+ let attempt: BackgroundResult;
192
+ try { attempt = backgroundResult(await target.backgroundSession!(sessionID)); }
193
+ catch { attempt = { status: "failed", reason: "request-threw" }; }
194
+ if (attempt.status !== "done") console.warn(`[chat-room] background ${attempt.status} room=${roomId} reason=${attempt.reason ?? "unknown"}`);
179
195
  }
196
+ let current: Recipient | undefined;
197
+ try {
198
+ const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, Recipient>;
199
+ current = registry[sessionID];
200
+ } catch { current = undefined; }
201
+ if (!current || (current.protocol ?? "v1") !== (recipient.protocol ?? "v1") ||
202
+ (transport.protocol === "v2" && transport.receiverOwnerID && current.receiverOwnerID !== transport.receiverOwnerID) ||
203
+ current.host !== recipient.host || current.directory !== recipient.directory ||
204
+ (current.roomKind ?? "group") !== roomKind) {
205
+ rejectPendingAdmission(sessionID, roomId, admission.id);
206
+ clearPendingAdmission(sessionID, roomId, Number.MAX_SAFE_INTEGER);
207
+ continue;
208
+ }
209
+ const currentCutoff = Math.max(current.lastReadTs ?? 0, current.lastQueuedTs ?? 0, queuedTs[roomId] ?? 0);
210
+ const currentAdmission = prunePendingAdmission(sessionID, roomId, currentCutoff,
211
+ (pending) => render(batch[0]!.roomName, roomId, roomKind, current!.name ?? "you", pending));
212
+ if (!currentAdmission || currentAdmission.id !== admission.id) {
213
+ continue;
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
+ });
180
220
  const result = transport.protocol === "v1"
181
- ? await sendAsyncNotification(transport, sessionID, admission.prompt)
182
- : await sendQueue(transport, sessionID, admission.prompt, admission.id, "steer");
221
+ ? await sendAsyncNotification(target, sessionID, admission.prompt)
222
+ : await sendQueue(target, sessionID, admission.prompt, admission.id, "steer");
183
223
  if (result !== "delivered") {
184
224
  if (result === "rejected") rejectPendingAdmission(sessionID, roomId, admission.id);
185
225
  if (result === "rejected" || worst === "delivered") worst = result;
@@ -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; lastReadTs?: number; lastQueuedTs?: number; host?: string; directory?: 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 mentioned = items.some((item) => {
92
- if (item.text.includes(`<at>@${entry.name}</at>`)) return true;
93
- const escaped = entry.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
94
- return new RegExp(`@${escaped}(?![\\p{L}\\p{N}_])`, "u").test(item.text);
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 = items.reduce((max, item) => Math.max(max, item.createdAt), 0);
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
- ? items.filter((item) => item.createdAt > existing.maxTs) : items;
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 {
@@ -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
+ }
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
+ }
@@ -4,21 +4,27 @@ import type { Message } from "./room-service";
4
4
  import {
5
5
  formatNotificationLines,
6
6
  loadRegistry,
7
+ loadRooms,
7
8
  NOTIFY_INSTRUCTION,
8
9
  statePath,
9
10
  timeOf,
10
11
  } from "./store";
11
- import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
12
- import { explicitlyMentions } from "./mentions";
12
+ import { backgroundResult, backgroundServiceKey, sendAsyncNotification, sendQueue, type BackgroundResult, type QueueTransport } from "./queue-transport";
13
+ import { explicitlyAddresses } from "./mentions";
14
+ import { claimBackgroundAttempt } from "./receiver-state";
13
15
  import { serializeSessionPush } from "./center-inbox";
16
+ import { prepareReceiptCandidate, receiptDestination } from "./agent-receipts";
14
17
  import {
15
18
  getOrCreatePendingAdmission,
19
+ clearPendingAdmission,
16
20
  markPendingAdmissionAdmitted,
17
21
  pendingAdmission,
18
22
  rejectPendingAdmission,
23
+ prunePendingAdmission,
24
+ type QueueItem,
19
25
  } from "./queue";
20
26
 
21
- type NotifyBatch = { roomId: string; roomName: string; messages: Message[] };
27
+ type NotifyBatch = { roomId: string; roomName: string; roomKind?: "group" | "direct"; messages: Message[] };
22
28
  type NotifyAttempt = { url: string; status: number };
23
29
  type TargetQueue = { latest?: NotifyBatch; latestTs: number; running: Promise<NotifyAttempt[]> };
24
30
 
@@ -40,6 +46,21 @@ export function createNotifier(deps: {
40
46
  await fs.appendFile(notifyPath(), lines.join("\n") + "\n", "utf8").catch(() => {});
41
47
  }
42
48
 
49
+ function render(batch: NotifyBatch, name: string, roomKind: "group" | "direct", items: QueueItem[]) {
50
+ const { lines, capped } = formatNotificationLines(items);
51
+ const context = roomKind === "direct" ? `Direct conversation with ${name} in room ${batch.roomName} (${batch.roomId})` : `New messages in room ${batch.roomName} (${batch.roomId})`;
52
+ return { prompt: `<notification>\n${context}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`, capped };
53
+ }
54
+
55
+ async function tryBackground(transport: QueueTransport, sessionID: string) {
56
+ try { return backgroundResult(await transport.backgroundSession!(sessionID)); }
57
+ catch { return { status: "failed" as const, reason: "request-threw" }; }
58
+ }
59
+
60
+ function logBackgroundResult(roomId: string, status: string, reason?: string) {
61
+ if (status !== "done") console.warn(`[chat-room] background ${status} room=${roomId} reason=${reason ?? "unknown"}`);
62
+ }
63
+
43
64
  async function notifyTarget(
44
65
  sessionID: string,
45
66
  batch: NotifyBatch,
@@ -54,25 +75,37 @@ export function createNotifier(deps: {
54
75
  batch: NotifyBatch,
55
76
  transport: QueueTransport,
56
77
  ): Promise<NotifyAttempt | undefined> {
57
- const entry = (await loadRegistry())[batch.roomId]?.[sessionID];
78
+ const [registry, rooms] = await Promise.all([loadRegistry(), loadRooms()]);
79
+ const entry = registry[batch.roomId]?.[sessionID];
80
+ const roomKind = batch.roomKind ?? rooms.find((room) => room.id === batch.roomId)?.kind ?? "group";
58
81
  if (!entry || (entry.protocol !== "v2" && !entry.serverUrl)) return undefined;
82
+ const protocol = entry.protocol ?? "v1";
83
+ if (protocol !== (transport.protocol ?? "v1") && !(transport.protocol === "v2" && protocol === "v1")) return undefined;
59
84
  const mentionOnly = transport.mentionOnlySessions?.has(sessionID) ?? false;
60
- if (transport.protocol === "v2" && entry.receiverOwnerID &&
61
- (entry.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
85
+ if (protocol === "v2" && (transport.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
62
86
  if (mentionOnly && (entry.protocol !== "v2" || entry.receiverOwnerID !== transport.receiverOwnerID)) return undefined;
87
+ const targetTransport = {
88
+ ...transport,
89
+ protocol,
90
+ serverUrl: entry.serverUrl,
91
+ directory: entry.directory ?? transport.directory,
92
+ };
93
+ const service = backgroundServiceKey(targetTransport);
94
+ const cutoff = Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0);
95
+ prunePendingAdmission(sessionID, batch.roomId, cutoff, (items) => render(batch, entry.name, roomKind, items));
63
96
  const unread = batch.messages.filter((m) =>
64
- m.createdAt > Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0) &&
65
- (m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== entry.name),
66
- ).slice(0, 20);
67
- if (!unread.length) return undefined;
68
- const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
97
+ m.createdAt > cutoff &&
98
+ (m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== (roomKind === "direct" ? sessionID : entry.name)),
99
+ ).slice(0, 20).map((item) => ({ ...item, roomKind }));
69
100
  const existing = pendingAdmission(sessionID, batch.roomId);
101
+ if (!unread.length && existing?.state !== "pending") return undefined;
102
+ const maxTs = unread.reduce((max, m) => Math.max(max, m.createdAt), 0);
70
103
  const delta = existing?.state === "admitted" && maxTs > existing.maxTs
71
104
  ? unread.filter((m) => m.createdAt > existing.maxTs)
72
105
  : unread;
73
106
  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;
107
+ if (mentionOnly && !eligibleItems.some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind)) &&
108
+ !delta.slice(-20).some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind))) return undefined;
76
109
  const base = entry.serverUrl ? new URL(entry.serverUrl) : undefined;
77
110
  const prefix = entry.protocol === "v2" ? (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "") : "";
78
111
  const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
@@ -82,8 +115,7 @@ export function createNotifier(deps: {
82
115
  if (existing.maxTs > 0) await deps.bumpQueued(batch.roomId, sessionID, existing.maxTs);
83
116
  return { url, status: entry.protocol === "v2" ? 200 : 204 };
84
117
  }
85
- const { lines, capped } = formatNotificationLines(delta);
86
- const prompt = `<notification>\nNew messages in room ${batch.roomName} (${batch.roomId}):\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
118
+ const { prompt, capped } = render(batch, entry.name, roomKind, delta);
87
119
  const deltaTs = delta.reduce((max, m) => Math.max(max, m.createdAt), 0);
88
120
  const admission = getOrCreatePendingAdmission(
89
121
  sessionID, batch.roomId, delta, prompt, deltaTs, capped,
@@ -92,15 +124,35 @@ export function createNotifier(deps: {
92
124
  await deps.bumpQueued(batch.roomId, sessionID, admission.maxTs);
93
125
  return { url, status: entry.protocol === "v2" ? 200 : 204 };
94
126
  }
95
- const targetTransport = {
96
- ...transport,
97
- serverUrl: entry.serverUrl,
98
- directory: entry.directory ?? transport.directory,
99
- };
100
- const mentioned = entry.protocol === "v2" && admission.items.some((message) => explicitlyMentions(message, entry.name, sessionID));
101
- if (mentioned && targetTransport.backgroundSession) {
102
- try { await targetTransport.backgroundSession(sessionID); } catch { /* Steering does not depend on backgrounding. */ }
127
+ const addressedTs = admission.items.filter((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind))
128
+ .reduce((max, message) => Math.max(max, message.createdAt), 0);
129
+ if (entry.protocol === "v2" && addressedTs > 0 && targetTransport.backgroundSession && claimBackgroundAttempt(
130
+ sessionID, batch.roomId, service, addressedTs,
131
+ )) {
132
+ const attempt = await tryBackground(targetTransport, sessionID);
133
+ logBackgroundResult(batch.roomId, attempt.status, attempt.reason);
134
+ }
135
+ const [currentRegistry, currentRooms] = await Promise.all([loadRegistry(), loadRooms()]);
136
+ const currentEntry = currentRegistry[batch.roomId]?.[sessionID];
137
+ const currentKind = currentRooms.find((room) => room.id === batch.roomId)?.kind ?? "group";
138
+ if (!currentEntry || (currentEntry.protocol ?? "v1") !== protocol || currentEntry.serverUrl !== entry.serverUrl ||
139
+ currentEntry.directory !== entry.directory ||
140
+ (protocol === "v2" && currentEntry.receiverOwnerID !== transport.receiverOwnerID) || currentKind !== roomKind) {
141
+ rejectPendingAdmission(sessionID, batch.roomId, admission.id);
142
+ clearPendingAdmission(sessionID, batch.roomId, Number.MAX_SAFE_INTEGER);
143
+ return undefined;
103
144
  }
145
+ const currentCutoff = Math.max(currentEntry.lastReadTs ?? 0, currentEntry.lastQueuedTs ?? 0);
146
+ const currentAdmission = prunePendingAdmission(sessionID, batch.roomId, currentCutoff,
147
+ (items) => render(batch, entry.name, roomKind, items));
148
+ if (!currentAdmission || currentAdmission.id !== admission.id) {
149
+ return notifyTargetUnlocked(sessionID, batch, transport);
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
+ });
104
156
  const result = entry.protocol === "v2"
105
157
  ? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id, "steer")
106
158
  : await sendAsyncNotification(targetTransport, sessionID, admission.prompt);
@@ -3,9 +3,10 @@ import { admissionMatches, type QueueBody } from "./queue";
3
3
  import { assertDeliveryLease } from "./session-delivery";
4
4
 
5
5
  export type PushResult = "delivered" | "unreachable" | "rejected";
6
+ export type BackgroundResult = { status: "done" | "failed" | "skip"; reason?: string };
6
7
  export type QueueTransport = {
7
8
  promptQueue?: (sessionID: string, id: string, text: string, delivery: "queue" | "steer") => Promise<unknown>;
8
- backgroundSession?: (sessionID: string) => Promise<boolean>;
9
+ backgroundSession?: (sessionID: string) => Promise<boolean | BackgroundResult>;
9
10
  receiverOwnerID?: string;
10
11
  verifySession?: (sessionID: string) => Promise<string | undefined>;
11
12
  mentionOnlySessions?: ReadonlySet<string>;
@@ -14,6 +15,21 @@ export type QueueTransport = {
14
15
  protocol?: "v1" | "v2";
15
16
  };
16
17
 
18
+ export function backgroundResult(value: boolean | BackgroundResult): BackgroundResult {
19
+ return typeof value === "boolean" ? value ? { status: "done" } : { status: "failed", reason: "unclassified-failure" } : value;
20
+ }
21
+
22
+ export function backgroundServiceKey(transport: QueueTransport, serviceURL = transport.serverUrl ?? ""): string {
23
+ let origin = serviceURL;
24
+ try {
25
+ if (serviceURL) {
26
+ const url = new URL(serviceURL);
27
+ origin = `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
28
+ }
29
+ } catch { /* Keep non-URL identifiers distinct. */ }
30
+ return JSON.stringify([transport.receiverOwnerID ?? "", origin]);
31
+ }
32
+
17
33
  export function createQueueTransport(input: { directory?: string; serverUrl?: URL | string } = {}): QueueTransport {
18
34
  const serverUrl = String(input.serverUrl ?? "").trim();
19
35
  return { serverUrl: serverUrl || undefined, protocol: "v1", directory: input.directory };