@alexsun-top/opencode-chat-room 0.8.5 → 0.8.6
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 -2
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/cli.ts +19 -0
- package/dist/cli.js +3747 -1443
- package/package.json +6 -1
- package/packages/chat-room-channeld/README.md +13 -8
- package/packages/chat-room-channeld/src/delivery.ts +0 -4
- package/packages/chat-room-channeld/src/host.ts +48 -37
- package/packages/chat-room-channeld/src/pg/database.ts +141 -49
- package/packages/chat-room-channeld/src/pg/worker.mjs +46 -5
- package/packages/chat-room-channeld/src/pg/worker.mts +41 -6
- package/packages/chat-room-channeld/src/state-rows.ts +132 -0
- package/packages/chat-room-channeld/src/state.ts +129 -157
- package/plugin.ts +20 -4
- package/server/app.ts +9 -0
- package/server/assets/base.css +22 -2
- package/server/assets/chat/admin.js +13 -0
- package/server/assets/chat/announcements.js +76 -34
- package/server/assets/chat/confirm-dialog.js +3 -0
- package/server/assets/chat/create-room-dialog.js +7 -0
- package/server/assets/chat/diagram-viewer.js +4 -8
- package/server/assets/chat/doc-preview.js +70 -30
- package/server/assets/chat/editor.js +38 -3
- package/server/assets/chat/events.js +6 -1
- package/server/assets/chat/files.js +28 -26
- package/server/assets/chat/history-loader.js +31 -15
- package/server/assets/chat/integration-editor.js +25 -1
- package/server/assets/chat/integrations.js +107 -15
- package/server/assets/chat/join-requests.js +39 -1
- package/server/assets/chat/locales/de.js +5 -3
- package/server/assets/chat/locales/es.js +5 -3
- package/server/assets/chat/locales/fr.js +5 -3
- package/server/assets/chat/locales/it.js +5 -3
- package/server/assets/chat/locales/ja.js +5 -3
- package/server/assets/chat/locales/ko.js +5 -3
- package/server/assets/chat/markdown-footnotes.js +19 -8
- package/server/assets/chat/markdown.js +0 -7
- package/server/assets/chat/members.js +31 -19
- package/server/assets/chat/message-cache.js +8 -2
- package/server/assets/chat/message-polling.js +8 -2
- package/server/assets/chat/message-window.js +57 -0
- package/server/assets/chat/messages.js +79 -40
- package/server/assets/chat/operator.js +624 -0
- package/server/assets/chat/palette.js +2 -7
- package/server/assets/chat/panels.js +31 -8
- package/server/assets/chat/questions.js +72 -56
- package/server/assets/chat/recall.js +14 -5
- package/server/assets/chat/receipts.js +63 -7
- package/server/assets/chat/refresh-timing.js +6 -0
- package/server/assets/chat/reminders.js +44 -13
- package/server/assets/chat/replies.js +33 -22
- package/server/assets/chat/resource-format.js +4 -1
- package/server/assets/chat/room-list.js +202 -3
- package/server/assets/chat/room-watcher.js +3 -1
- package/server/assets/chat/rooms.js +22 -3
- package/server/assets/chat/settings.js +33 -3
- package/server/assets/chat/state.js +21 -7
- package/server/assets/chat/tasks.js +33 -11
- package/server/assets/chat/window-controls.js +25 -16
- package/server/assets/code-highlight.css +0 -13
- package/server/assets/conversation.css +31 -3
- package/server/assets/doc-preview.css +3 -0
- package/server/assets/files.css +4 -0
- package/server/assets/monaco/integration-rules.js +1 -1
- package/server/assets/responsive.css +12 -2
- package/server/assets/settings.css +3 -1
- package/server/assets/tasks.css +6 -1
- package/server/assets/window-controls.css +3 -1
- package/server/channels.ts +3 -2
- package/server/chat.html +7 -2
- package/server/inbox.ts +3 -1
- package/server/join-requests.ts +8 -1
- package/server/member-routes.ts +16 -2
- package/server/newrooms.ts +2 -13
- package/server/operator-auth.ts +21 -0
- package/server/operator-routes.ts +150 -0
- package/server/operator-state.ts +64 -0
- package/server/operator.css +139 -0
- package/server/room-owner.ts +17 -0
- package/server/routes/inbox.ts +15 -5
- package/server/routes/pages.ts +12 -2
- package/server/routes/room-actions.ts +4 -3
- package/server/system.html +109 -0
- package/server/wake.ts +1 -1
- package/skills/chatroom/SKILL.md +3 -3
- package/src/acp/client.ts +254 -0
- package/src/acp/protocol.ts +300 -0
- package/src/acp/watch.ts +498 -0
- package/src/agent/agent-receipts.ts +87 -5
- package/src/center/center-client.ts +5 -0
- package/src/center/center-inbox.ts +54 -7
- package/src/center/center-wake.ts +57 -3
- package/src/center/forward-client.ts +48 -0
- package/src/center/mentions.ts +16 -3
- package/src/center/notification-delay.ts +139 -0
- package/src/center/queue.ts +3 -0
- package/src/config/file-config.ts +25 -0
- package/src/mcp/server.ts +389 -0
- package/src/protocol/config.ts +7 -0
- package/src/runtime/plugin-notifications.ts +43 -9
- package/src/runtime/v2-plugin.ts +14 -3
- package/src/runtime/v2-receiver.ts +10 -2
- package/src/runtime/watch.ts +5 -1
- package/src/state/pg-database.ts +133 -49
- package/src/state/pg-worker.mjs +46 -5
- package/src/state/pg-worker.mts +41 -6
- package/src/state/receiver-state.ts +47 -0
- package/src/state/sqlite-database.ts +6 -2
- package/src/state/sqlite-members.ts +48 -4
- package/src/state/sqlite-messages.ts +25 -12
- package/src/state/sqlite-schema.ts +4 -1
- package/src/state/sqlite-state.ts +1 -1
- package/src/state/store.ts +10 -4
- package/src/tui/app.mjs +57 -10
- package/src/tui/app.mts +54 -11
- package/src/tui/room-settings-app.mjs +27 -9
- package/src/tui/room-settings-app.mts +26 -9
- package/src/web/integration-rules-editor.ts +25 -2
|
@@ -13,9 +13,10 @@ import { explicitlyAddresses } from "./mentions.ts";
|
|
|
13
13
|
import { withMessageIds } from "./message-ids.ts";
|
|
14
14
|
import { notificationPrefix } from "./notification-budget.ts";
|
|
15
15
|
import { claimBackgroundAttempt } from "../state/receiver-state.ts";
|
|
16
|
-
import { prepareReceiptCandidate, receiptDestination } from "../agent/agent-receipts.ts";
|
|
16
|
+
import { markReceiptDelivered, prepareReceiptCandidate, receiptDestination } from "../agent/agent-receipts.ts";
|
|
17
17
|
import { serializeSessionPush } from "./session-delivery.ts";
|
|
18
18
|
export { serializeSessionPush } from "./session-delivery.ts";
|
|
19
|
+
import { forgetNotificationWait, markNotificationAttempt, notificationMergeable, notificationPacing, scheduleNotificationRetry } from "./notification-delay.ts";
|
|
19
20
|
import {
|
|
20
21
|
sendAsyncNotification,
|
|
21
22
|
sendQueue,
|
|
@@ -28,9 +29,22 @@ import {
|
|
|
28
29
|
|
|
29
30
|
export type InboxItem = QueueItem & { roomId: string; roomName: string; roomKind?: "group" | "direct" };
|
|
30
31
|
const inboxChecks = new Set<string>();
|
|
32
|
+
// A timer that fired during an in-flight check: run once after that check ends.
|
|
33
|
+
const inboxRetries = new Set<string>();
|
|
31
34
|
const restoreScans = new Map<string, { beforeSeq?: number; untilTs?: number }>();
|
|
35
|
+
// Mention gating exists for backlog a restarted process finds unread. A message
|
|
36
|
+
// that arrives while this process runs must reach the session without an @.
|
|
37
|
+
const processStartedAt = Date.now();
|
|
32
38
|
const restoreKey = (sessionID: string, roomID: string) => JSON.stringify([sessionID, roomID]);
|
|
33
39
|
|
|
40
|
+
function scheduleInboxRetry(opts: CenterOpts, sessionID: string, transport: QueueTransport): void {
|
|
41
|
+
if (!inboxRetries.has(sessionID)) return;
|
|
42
|
+
scheduleNotificationRetry(`center-inbox:${sessionID}`, Date.now(), async () => {
|
|
43
|
+
if (!inboxRetries.delete(sessionID)) return;
|
|
44
|
+
await checkCenterInbox(opts, sessionID, transport);
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
34
48
|
function render(roomName: string, roomId: string, roomKind: "group" | "direct", name: string, items: QueueItem[]) {
|
|
35
49
|
const { lines, capped } = formatNotificationLines(items);
|
|
36
50
|
const context = roomKind === "direct" ? `Direct conversation with ${name} in room ${roomName} (${roomId})` : `New messages in room ${roomName} (${roomId})`;
|
|
@@ -42,7 +56,10 @@ export async function checkCenterInbox(
|
|
|
42
56
|
sessionID: string,
|
|
43
57
|
transport: QueueTransport,
|
|
44
58
|
): Promise<void> {
|
|
45
|
-
if (inboxChecks.has(sessionID))
|
|
59
|
+
if (inboxChecks.has(sessionID)) {
|
|
60
|
+
inboxRetries.add(sessionID);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
46
63
|
inboxChecks.add(sessionID);
|
|
47
64
|
try {
|
|
48
65
|
await serializeSessionPush(sessionID, async () => {
|
|
@@ -75,6 +92,7 @@ export async function checkCenterInbox(
|
|
|
75
92
|
// The next inbox poll retries failed delivery.
|
|
76
93
|
} finally {
|
|
77
94
|
inboxChecks.delete(sessionID);
|
|
95
|
+
scheduleInboxRetry(opts, sessionID, transport);
|
|
78
96
|
}
|
|
79
97
|
}
|
|
80
98
|
|
|
@@ -151,12 +169,18 @@ export async function pushItemsToSession(
|
|
|
151
169
|
}
|
|
152
170
|
let worst: PushResult = "delivered";
|
|
153
171
|
for (const [roomId, batch] of rooms) {
|
|
154
|
-
|
|
172
|
+
let roomMentionOnly = mentionOnly && !qualifiedRooms.has(roomId);
|
|
173
|
+
// A message that arrived after this process started is not backlog: deliver
|
|
174
|
+
// it now instead of waiting for an @ that may come minutes later.
|
|
175
|
+
if (roomMentionOnly && batch.some((item) => item.createdAt >= processStartedAt)) roomMentionOnly = false;
|
|
155
176
|
type Recipient = { name?: string; protocol?: "v1" | "v2"; receiverOwnerID?: string; membershipID?: string; lastReadTs?: number; lastQueuedTs?: number; roomKind?: "group" | "direct"; host?: string; directory?: string };
|
|
156
177
|
let recipient: Recipient | undefined;
|
|
157
178
|
try {
|
|
158
179
|
const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, Recipient>;
|
|
159
180
|
recipient = registry[sessionID];
|
|
181
|
+
// A room with one agent is bot-manned: mention-gating it leaves the only
|
|
182
|
+
// agent asleep until someone @-mentions it.
|
|
183
|
+
if (roomMentionOnly && Object.values(registry).filter((member) => member.protocol !== undefined).length === 1) roomMentionOnly = false;
|
|
160
184
|
} catch { continue; }
|
|
161
185
|
if (!recipient || (recipient.protocol ?? "v1") !== (transport.protocol ?? "v1")) continue;
|
|
162
186
|
if (transport.protocol === "v2" && transport.receiverOwnerID && recipient.receiverOwnerID !== transport.receiverOwnerID) continue;
|
|
@@ -206,7 +230,10 @@ export async function pushItemsToSession(
|
|
|
206
230
|
const deltaTs = deliverable.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
207
231
|
const displayDelta = withMessageIds(deliverable);
|
|
208
232
|
const { prompt, capped } = render(batch[0]!.roomName, roomId, roomKind, recipient.name ?? "you", displayDelta);
|
|
209
|
-
const
|
|
233
|
+
const pending = existing?.state === "pending" ? pendingAdmission(sessionID, roomId) : undefined;
|
|
234
|
+
const merge = pending !== undefined && notificationMergeable(pending, deliverable, recipient.name, sessionID);
|
|
235
|
+
const admission = getOrCreatePendingAdmission(sessionID, roomId, displayDelta, prompt, deltaTs, capped, merge);
|
|
236
|
+
if (merge && pending && admission.id !== pending.id) forgetNotificationWait(pending.id);
|
|
210
237
|
const addressedTs = recipient.name
|
|
211
238
|
? admission.items.filter((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind))
|
|
212
239
|
.reduce((max, item) => Math.max(max, item.createdAt), 0)
|
|
@@ -222,6 +249,7 @@ export async function pushItemsToSession(
|
|
|
222
249
|
(current.roomKind ?? "group") !== roomKind) {
|
|
223
250
|
rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
224
251
|
clearPendingAdmission(sessionID, roomId, Number.MAX_SAFE_INTEGER);
|
|
252
|
+
forgetNotificationWait(admission.id);
|
|
225
253
|
continue;
|
|
226
254
|
}
|
|
227
255
|
const currentCutoff = Math.max(current.lastReadTs ?? 0, current.lastQueuedTs ?? 0, queuedTs[roomId] ?? 0);
|
|
@@ -230,26 +258,45 @@ export async function pushItemsToSession(
|
|
|
230
258
|
if (!currentAdmission || currentAdmission.id !== admission.id) {
|
|
231
259
|
continue;
|
|
232
260
|
}
|
|
233
|
-
|
|
261
|
+
const deferred = notificationPacing(currentAdmission, delta, current.name ?? recipient.name, sessionID);
|
|
262
|
+
if (deferred && "deferAt" in deferred) {
|
|
263
|
+
// A busy check coalesces this timer into its after-sweep drain; otherwise
|
|
264
|
+
// this timer runs the check itself with the same sampled deadline.
|
|
265
|
+
scheduleNotificationRetry(`center-inbox:${sessionID}`, deferred.deferAt,
|
|
266
|
+
() => checkCenterInbox(opts, sessionID, transport));
|
|
267
|
+
continue;
|
|
268
|
+
}
|
|
269
|
+
const flush = deferred?.flush === true;
|
|
270
|
+
markNotificationAttempt(admission.id);
|
|
271
|
+
const candidate = transport.protocol === "v2" && current.protocol === "v2" ? prepareReceiptCandidate({
|
|
234
272
|
admissionID: admission.id, sessionID, roomID: roomId, membershipID: current.membershipID,
|
|
235
273
|
receiverOwnerID: current.receiverOwnerID, destination: receiptDestination(opts.center),
|
|
236
274
|
items: admission.items, prompt: admission.prompt, capped: admission.capped,
|
|
237
|
-
});
|
|
275
|
+
}) : undefined;
|
|
238
276
|
const result = transport.protocol === "v1"
|
|
239
277
|
? await sendAsyncNotification(target, sessionID, admission.prompt)
|
|
240
278
|
: await sendQueue(target, sessionID, admission.prompt, admission.id, "steer");
|
|
241
279
|
if (result !== "delivered") {
|
|
242
280
|
// Keep one line per failure: an idle host that never receives is otherwise invisible.
|
|
243
281
|
console.warn(`[chat-room] delivery ${result} room=${roomId} session=${sessionID} protocol=${transport.protocol}`);
|
|
244
|
-
if (result === "rejected")
|
|
282
|
+
if (result === "rejected") {
|
|
283
|
+
rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
284
|
+
forgetNotificationWait(admission.id);
|
|
285
|
+
}
|
|
245
286
|
if (result === "rejected" || worst === "delivered") worst = result;
|
|
246
287
|
continue;
|
|
247
288
|
}
|
|
289
|
+
markReceiptDelivered(candidate);
|
|
248
290
|
markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
|
|
291
|
+
forgetNotificationWait(admission.id);
|
|
249
292
|
void request(opts, "/active", "POST", { sessionID }).catch(() => {});
|
|
250
293
|
if (admission.maxTs > 0 && await markQueued(opts, roomId, sessionID, admission.maxTs)) {
|
|
251
294
|
clearPendingAdmission(sessionID, roomId, admission.maxTs);
|
|
252
295
|
}
|
|
296
|
+
if (flush) {
|
|
297
|
+
scheduleNotificationRetry(`center-inbox:${sessionID}`, Date.now(),
|
|
298
|
+
() => checkCenterInbox(opts, sessionID, transport));
|
|
299
|
+
}
|
|
253
300
|
if (transport.protocol === "v2" && transport.backgroundSession && addressedTs > 0 &&
|
|
254
301
|
claimBackgroundAttempt(sessionID, roomId, backgroundServiceKey(target, opts.center), addressedTs)) {
|
|
255
302
|
let attempt: BackgroundResult;
|
|
@@ -14,12 +14,47 @@ import {
|
|
|
14
14
|
prunePendingAdmission,
|
|
15
15
|
rejectPendingAdmission,
|
|
16
16
|
type PendingAdmission,
|
|
17
|
+
type QueueItem,
|
|
17
18
|
} from "./queue.ts";
|
|
18
19
|
import { markQueued, request, type CenterOpts } from "./center-client.ts";
|
|
19
20
|
import { pushItemsToSession, serializeSessionPush, type InboxItem } from "./center-inbox.ts";
|
|
21
|
+
import { forgetNotificationWait, markNotificationAttempt, notificationPacing, scheduleNotificationRetry } from "./notification-delay.ts";
|
|
20
22
|
import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport.ts";
|
|
21
23
|
|
|
22
24
|
const checking = new WeakSet<QueueTransport>();
|
|
25
|
+
// One-session wake retries that arrived while a sweep was in flight. Each keeps
|
|
26
|
+
// its own eligible set, so a retry for one recipient never widens another's.
|
|
27
|
+
const wakeRetries = new WeakMap<QueueTransport, Set<string>>();
|
|
28
|
+
const wakeRetryKeys = new WeakMap<QueueTransport, string>();
|
|
29
|
+
let wakeRetryKeySeq = 0;
|
|
30
|
+
|
|
31
|
+
function wakeRetryKey(transport: QueueTransport): string {
|
|
32
|
+
const key = wakeRetryKeys.get(transport) ?? `center-wake:${wakeRetryKeySeq++}`;
|
|
33
|
+
wakeRetryKeys.set(transport, key);
|
|
34
|
+
return key;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function wakeSessionRetry(
|
|
38
|
+
opts: CenterOpts, transport: QueueTransport, serveUrl: string, sessionID: string,
|
|
39
|
+
): Promise<void> {
|
|
40
|
+
if (checking.has(transport)) {
|
|
41
|
+
const ids = wakeRetries.get(transport) ?? new Set<string>();
|
|
42
|
+
ids.add(sessionID);
|
|
43
|
+
wakeRetries.set(transport, ids);
|
|
44
|
+
return Promise.resolve();
|
|
45
|
+
}
|
|
46
|
+
return wakeSessions(opts, transport, serveUrl, new Set([sessionID]));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function scheduleWakeDrain(opts: CenterOpts, transport: QueueTransport, serveUrl: string): void {
|
|
50
|
+
if (!wakeRetries.get(transport)?.size) return;
|
|
51
|
+
scheduleNotificationRetry(wakeRetryKey(transport), Date.now(), async () => {
|
|
52
|
+
const ids = wakeRetries.get(transport);
|
|
53
|
+
wakeRetries.delete(transport);
|
|
54
|
+
if (!ids) return;
|
|
55
|
+
for (const sessionID of ids) await wakeSessionRetry(opts, transport, serveUrl, sessionID);
|
|
56
|
+
});
|
|
57
|
+
}
|
|
23
58
|
|
|
24
59
|
async function wakeViaServe(
|
|
25
60
|
serveUrl: string,
|
|
@@ -28,6 +63,7 @@ async function wakeViaServe(
|
|
|
28
63
|
opts: CenterOpts,
|
|
29
64
|
transport: QueueTransport,
|
|
30
65
|
admission: PendingAdmission,
|
|
66
|
+
delta: readonly QueueItem[],
|
|
31
67
|
roomName: string,
|
|
32
68
|
expectedHost: string | undefined,
|
|
33
69
|
expectedDirectory: string | undefined,
|
|
@@ -51,7 +87,7 @@ async function wakeViaServe(
|
|
|
51
87
|
}>;
|
|
52
88
|
const current = registry[sessionID];
|
|
53
89
|
const cutoff = Math.max(current?.lastReadTs ?? 0, current?.lastQueuedTs ?? 0);
|
|
54
|
-
const
|
|
90
|
+
const freshAdmission = prunePendingAdmission(sessionID, roomId, cutoff, (items) => {
|
|
55
91
|
const { lines, capped } = formatNotificationLines(items);
|
|
56
92
|
return { prompt: formatServeWakePrompt(roomName, roomId, lines), capped };
|
|
57
93
|
});
|
|
@@ -59,11 +95,22 @@ async function wakeViaServe(
|
|
|
59
95
|
(transport.protocol === "v2" && current.receiverOwnerID !== transport.receiverOwnerID) ||
|
|
60
96
|
current.host !== expectedHost || current.directory !== expectedDirectory ||
|
|
61
97
|
(current.roomKind ?? "group") !== expectedRoomKind ||
|
|
62
|
-
!
|
|
98
|
+
!freshAdmission || freshAdmission.id !== admission.id || admission.maxTs <= cutoff) {
|
|
63
99
|
rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
64
100
|
clearPendingAdmission(sessionID, roomId, Number.MAX_SAFE_INTEGER);
|
|
101
|
+
forgetNotificationWait(admission.id);
|
|
65
102
|
return false;
|
|
66
103
|
}
|
|
104
|
+
const deferred = notificationPacing(freshAdmission, delta, current.name, sessionID);
|
|
105
|
+
if (deferred && "deferAt" in deferred) {
|
|
106
|
+
// A busy wake sweep records this one-session retry and drains it after the
|
|
107
|
+
// sweep, so the pending admission keeps its deadline and eligible target.
|
|
108
|
+
scheduleNotificationRetry(`center-wake:${JSON.stringify([sessionID, roomId])}`, deferred.deferAt,
|
|
109
|
+
() => wakeSessionRetry(opts, transport, serveUrl, sessionID));
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
const flush = deferred?.flush === true;
|
|
113
|
+
markNotificationAttempt(admission.id);
|
|
67
114
|
const target: QueueTransport = { serverUrl: serveUrl, directory: transport.directory, protocol: transport.protocol };
|
|
68
115
|
const result = transport.protocol === "v1"
|
|
69
116
|
? await sendAsyncNotification(target, sessionID, admission.prompt)
|
|
@@ -71,11 +118,17 @@ async function wakeViaServe(
|
|
|
71
118
|
if (result === "delivered") {
|
|
72
119
|
void request(opts, "/active", "POST", { sessionID }).catch(() => {});
|
|
73
120
|
markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
|
|
121
|
+
forgetNotificationWait(admission.id);
|
|
74
122
|
if (admission.maxTs > 0 && await markQueued(opts, roomId, sessionID, admission.maxTs)) {
|
|
75
123
|
clearPendingAdmission(sessionID, roomId, admission.maxTs);
|
|
76
124
|
}
|
|
125
|
+
if (flush) {
|
|
126
|
+
scheduleNotificationRetry(`center-wake:${JSON.stringify([sessionID, roomId])}`, Date.now(),
|
|
127
|
+
() => wakeSessionRetry(opts, transport, serveUrl, sessionID));
|
|
128
|
+
}
|
|
77
129
|
} else if (result === "rejected") {
|
|
78
130
|
rejectPendingAdmission(sessionID, roomId, admission.id);
|
|
131
|
+
forgetNotificationWait(admission.id);
|
|
79
132
|
}
|
|
80
133
|
return result === "delivered";
|
|
81
134
|
}
|
|
@@ -149,7 +202,7 @@ export async function wakeSessions(
|
|
|
149
202
|
const prompt = formatServeWakePrompt(items[0]!.roomName, roomId, lines);
|
|
150
203
|
const maxTs = deliverable.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
151
204
|
const admission = getOrCreatePendingAdmission(sessionID, roomId, displayDelta, prompt, maxTs, capped);
|
|
152
|
-
await wakeViaServe(serveUrl, sessionID, roomId, opts, target, admission,
|
|
205
|
+
await wakeViaServe(serveUrl, sessionID, roomId, opts, target, admission, delta,
|
|
153
206
|
items[0]!.roomName, entry.host, entry.directory, roomKind);
|
|
154
207
|
});
|
|
155
208
|
}
|
|
@@ -161,5 +214,6 @@ export async function wakeSessions(
|
|
|
161
214
|
// The next wake sweep retries center failures.
|
|
162
215
|
} finally {
|
|
163
216
|
checking.delete(transport);
|
|
217
|
+
scheduleWakeDrain(opts, transport, serveUrl);
|
|
164
218
|
}
|
|
165
219
|
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// Manual Channel D forward calls over the center's existing routes. The
|
|
2
|
+
// caller's actual session is the only identity; this never selects a target
|
|
3
|
+
// itself or claims a queued event was delivered.
|
|
4
|
+
import { request, type CenterOpts } from "./center-client.ts";
|
|
5
|
+
|
|
6
|
+
export type ForwardTarget = { platform: string; account: string; room: string };
|
|
7
|
+
|
|
8
|
+
// Matches the center's endpoint identifier rule.
|
|
9
|
+
const TARGET_IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
|
|
10
|
+
|
|
11
|
+
export function isForwardTarget(value: unknown): value is ForwardTarget {
|
|
12
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
13
|
+
const raw = value as Record<string, unknown>;
|
|
14
|
+
return typeof raw.platform === "string" && TARGET_IDENTIFIER.test(raw.platform)
|
|
15
|
+
&& typeof raw.account === "string" && TARGET_IDENTIFIER.test(raw.account)
|
|
16
|
+
&& typeof raw.room === "string" && TARGET_IDENTIFIER.test(raw.room);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export async function runForwardAction(
|
|
20
|
+
opts: CenterOpts,
|
|
21
|
+
args: { action: string; roomId?: string; messageId?: string; target?: unknown },
|
|
22
|
+
sessionID: string,
|
|
23
|
+
): Promise<string> {
|
|
24
|
+
if (!args.roomId) {
|
|
25
|
+
return "error: roomId is required; use a room UUID from the room list, not the room name";
|
|
26
|
+
}
|
|
27
|
+
const root = `/rooms/${encodeURIComponent(args.roomId)}`;
|
|
28
|
+
if (args.action === "forward_targets") {
|
|
29
|
+
const result = await request(opts, `${root}/forward-targets?sessionID=${encodeURIComponent(sessionID)}`, "GET");
|
|
30
|
+
return JSON.stringify({ targets: Array.isArray(result.targets) ? result.targets : [] });
|
|
31
|
+
}
|
|
32
|
+
if (!args.messageId) {
|
|
33
|
+
return "error: messageId is required; use the full message ID returned by send or poll";
|
|
34
|
+
}
|
|
35
|
+
if (!isForwardTarget(args.target)) {
|
|
36
|
+
return "error: target must contain platform, account, and room identifiers";
|
|
37
|
+
}
|
|
38
|
+
const result = await request(opts, `${root}/forward`, "POST", {
|
|
39
|
+
sessionID,
|
|
40
|
+
messageId: args.messageId,
|
|
41
|
+
target: args.target,
|
|
42
|
+
});
|
|
43
|
+
// 2xx means queued only; a missing eventId is not a confirmed queue.
|
|
44
|
+
if (typeof result.eventId !== "string" || !result.eventId) {
|
|
45
|
+
return "error: forward request was not queued";
|
|
46
|
+
}
|
|
47
|
+
return JSON.stringify({ status: "queued", eventId: result.eventId });
|
|
48
|
+
}
|
package/src/center/mentions.ts
CHANGED
|
@@ -1,14 +1,27 @@
|
|
|
1
1
|
import type { QueueItem } from "./queue.ts";
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
function namesRecipient(item: QueueItem, recipient: string, sessionID?: string): boolean {
|
|
4
4
|
if (!recipient.trim() || (item.senderId === "system" && !item.id?.startsWith("reminder:")) || (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;
|
|
7
5
|
const escaped = recipient.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
8
6
|
const match = new RegExp(`(?<![\\p{L}\\p{N}_.@])(?:<at>)?@${escaped}(?:</at>)?(?![\\p{L}\\p{N}_])`, "u").exec(item.text);
|
|
9
7
|
return match !== null && match.index + match[0].length <= 300;
|
|
10
8
|
}
|
|
11
9
|
|
|
10
|
+
/** A named @ of this recipient; @all and every broadcast tag do not count. */
|
|
11
|
+
export function directlyMentions(item: QueueItem, recipient: string, sessionID?: string): boolean {
|
|
12
|
+
const name = recipient.trim();
|
|
13
|
+
// A member displayed as "all"/"所有人" cannot be told apart from a broadcast.
|
|
14
|
+
if (name === "all" || name === "所有人") return false;
|
|
15
|
+
return namesRecipient(item, recipient, sessionID);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function explicitlyMentions(item: QueueItem, recipient: string, sessionID?: string): boolean {
|
|
19
|
+
if (!recipient.trim() || (item.senderId === "system" && !item.id?.startsWith("reminder:")) || (sessionID !== undefined && item.senderSessionID === sessionID)) return false;
|
|
20
|
+
const broadcast = /(?<![\p{L}\p{N}_.@])(?:<at>)?@(?:all|所有人)(?:<\/at>)?(?![\p{L}\p{N}_])/u.exec(item.text);
|
|
21
|
+
if (broadcast && broadcast.index + broadcast[0].length <= 300) return true;
|
|
22
|
+
return namesRecipient(item, recipient, sessionID);
|
|
23
|
+
}
|
|
24
|
+
|
|
12
25
|
export function explicitlyAddresses(item: QueueItem, recipient: string, sessionID?: string, roomKind?: "group" | "direct"): boolean {
|
|
13
26
|
if (roomKind !== "direct") return explicitlyMentions(item, recipient, sessionID);
|
|
14
27
|
if (item.senderId === "system") return item.id?.startsWith("reminder:") ? explicitlyMentions(item, recipient, sessionID) : false;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { directlyMentions } from "./mentions.ts";
|
|
2
|
+
import type { QueueItem } from "./queue.ts";
|
|
3
|
+
import { NOTIFICATION_DELAY_MAX_MS, type ClientSettings } from "../protocol/config.ts";
|
|
4
|
+
|
|
5
|
+
// Notification pacing for the plugin side: an Agent that was not directly named
|
|
6
|
+
// keeps its notification pending for a fixed wait plus a random spread, so one
|
|
7
|
+
// send does not start every member's LLM request at the same instant.
|
|
8
|
+
export type NotificationDelaySettings = Pick<ClientSettings, "notificationDelayMs" | "notificationJitterMs">;
|
|
9
|
+
|
|
10
|
+
let configured: NotificationDelaySettings | undefined;
|
|
11
|
+
|
|
12
|
+
/** Config-file values resolved by the plugin; an env var still wins per field. */
|
|
13
|
+
export function configureNotificationDelay(settings: NotificationDelaySettings): void {
|
|
14
|
+
configured = settings;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function envMs(env: NodeJS.ProcessEnv, key: string): number | undefined {
|
|
18
|
+
const raw = env[key]?.trim();
|
|
19
|
+
if (!raw) return undefined;
|
|
20
|
+
const value = Number(raw);
|
|
21
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value > NOTIFICATION_DELAY_MAX_MS) {
|
|
22
|
+
throw new Error(`${key} must be an integer from 0 to ${NOTIFICATION_DELAY_MAX_MS}`);
|
|
23
|
+
}
|
|
24
|
+
return value;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function notificationDelaySettings(env: NodeJS.ProcessEnv = process.env): NotificationDelaySettings {
|
|
28
|
+
return {
|
|
29
|
+
notificationDelayMs: envMs(env, "CHAT_ROOM_NOTIFICATION_DELAY_MS") ?? configured?.notificationDelayMs ?? 0,
|
|
30
|
+
notificationJitterMs: envMs(env, "CHAT_ROOM_NOTIFICATION_JITTER_MS") ?? configured?.notificationJitterMs ?? 2000,
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Inclusive wait in [delay, delay + jitter]; a zero jitter means exactly the fixed wait. */
|
|
35
|
+
export function sampleNotificationWait(settings: NotificationDelaySettings, random = Math.random): number {
|
|
36
|
+
const offset = settings.notificationJitterMs === 0
|
|
37
|
+
? 0
|
|
38
|
+
: Math.min(settings.notificationJitterMs, Math.floor(random() * (settings.notificationJitterMs + 1)));
|
|
39
|
+
return settings.notificationDelayMs + offset;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// One sampled deadline per pending admission: retries and sweeps reuse it.
|
|
43
|
+
const waitUntil = new Map<string, number>();
|
|
44
|
+
// Admissions whose prompt already reached a dispatch attempt. An attempt is
|
|
45
|
+
// ambiguous, so a later named @ must retry the original prompt, not merge into it.
|
|
46
|
+
const attempted = new Set<string>();
|
|
47
|
+
|
|
48
|
+
export function markNotificationAttempt(admissionID: string): void {
|
|
49
|
+
attempted.add(admissionID);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* True only for a pending admission that sampled a wait here and never reached
|
|
54
|
+
* a dispatch attempt: its merged in-order batch can replace it safely. A pending
|
|
55
|
+
* admission from before a restart has no sampled wait, so it is not mergeable.
|
|
56
|
+
*/
|
|
57
|
+
export function notificationMergeable(
|
|
58
|
+
pending: { id: string; items: readonly QueueItem[] },
|
|
59
|
+
fit: readonly QueueItem[],
|
|
60
|
+
recipient: string | undefined,
|
|
61
|
+
sessionID: string,
|
|
62
|
+
): boolean {
|
|
63
|
+
if (recipient === undefined || !waitUntil.has(pending.id) || attempted.has(pending.id)) return false;
|
|
64
|
+
const fitIDs = new Set(fit.map((item) => item.id).filter((id): id is string => Boolean(id)));
|
|
65
|
+
// A merged batch that would drop a held item belongs to the flush path instead.
|
|
66
|
+
if (!pending.items.every((item) => item.id === undefined || fitIDs.has(item.id))) return false;
|
|
67
|
+
const held = new Set(pending.items.map((item) => item.id).filter((id): id is string => Boolean(id)));
|
|
68
|
+
return fit.some((item) => item.id !== undefined && !held.has(item.id) &&
|
|
69
|
+
directlyMentions(item, recipient, sessionID));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function sampledWait(admissionID: string, now: number): { at: number; sampled: boolean } {
|
|
73
|
+
const existing = waitUntil.get(admissionID);
|
|
74
|
+
if (existing !== undefined) return { at: existing, sampled: false };
|
|
75
|
+
const at = now + sampleNotificationWait(notificationDelaySettings());
|
|
76
|
+
if (waitUntil.size >= 1000) {
|
|
77
|
+
const oldest = waitUntil.keys().next().value;
|
|
78
|
+
if (oldest !== undefined) waitUntil.delete(oldest);
|
|
79
|
+
}
|
|
80
|
+
waitUntil.set(admissionID, at);
|
|
81
|
+
return { at, sampled: true };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* undefined sends now. deferAt holds the delivery back. flush means send now
|
|
86
|
+
* and then retry at once: a named @ arrived after the held prefix, so the old
|
|
87
|
+
* prefix flushes in order and the mention must not wait for another trigger.
|
|
88
|
+
*/
|
|
89
|
+
export type NotificationPacing =
|
|
90
|
+
| { deferAt: number; sampled: boolean }
|
|
91
|
+
| { flush: true }
|
|
92
|
+
| undefined;
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* A named @ in the pending prefix or the fresh delta cancels the wait, so the
|
|
96
|
+
* older queued prefix flushes in order instead of waiting out its sampled time.
|
|
97
|
+
*/
|
|
98
|
+
export function notificationPacing(
|
|
99
|
+
admission: { id: string; items: readonly QueueItem[] },
|
|
100
|
+
fresh: readonly QueueItem[],
|
|
101
|
+
recipient: string | undefined,
|
|
102
|
+
sessionID: string,
|
|
103
|
+
now = Date.now(),
|
|
104
|
+
): NotificationPacing {
|
|
105
|
+
if (recipient === undefined) return undefined;
|
|
106
|
+
const named = (item: QueueItem) => directlyMentions(item, recipient, sessionID);
|
|
107
|
+
const held = new Set(admission.items.map((item) => item.id).filter((id): id is string => Boolean(id)));
|
|
108
|
+
const uncovered = fresh.filter((item) => item.id !== undefined && !held.has(item.id));
|
|
109
|
+
if (uncovered.some(named)) return { flush: true };
|
|
110
|
+
if (admission.items.some(named)) return undefined;
|
|
111
|
+
const wait = sampledWait(admission.id, now);
|
|
112
|
+
return wait.at > now ? { deferAt: wait.at, sampled: wait.sampled } : undefined;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function forgetNotificationWait(admissionID: string): void {
|
|
116
|
+
waitUntil.delete(admissionID);
|
|
117
|
+
attempted.delete(admissionID);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const retries = new Map<string, { at: number; timer: ReturnType<typeof setTimeout> }>();
|
|
121
|
+
|
|
122
|
+
/** A detached retry outside session locks and sweeps; never blocks a named mention. */
|
|
123
|
+
export function scheduleNotificationRetry(key: string, at: number, run: () => Promise<unknown>): void {
|
|
124
|
+
const existing = retries.get(key);
|
|
125
|
+
if (existing && existing.at <= at) return;
|
|
126
|
+
if (existing) clearTimeout(existing.timer);
|
|
127
|
+
const timer = setTimeout(() => {
|
|
128
|
+
if (retries.get(key)?.at !== at) return;
|
|
129
|
+
retries.delete(key);
|
|
130
|
+
void run().catch(() => {});
|
|
131
|
+
}, Math.max(0, at - Date.now()));
|
|
132
|
+
timer.unref?.();
|
|
133
|
+
retries.set(key, { at, timer });
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function stopNotificationRetries(): void {
|
|
137
|
+
for (const { timer } of retries.values()) clearTimeout(timer);
|
|
138
|
+
retries.clear();
|
|
139
|
+
}
|
package/src/center/queue.ts
CHANGED
|
@@ -80,6 +80,8 @@ export function getOrCreatePendingAdmission(
|
|
|
80
80
|
prompt: string,
|
|
81
81
|
maxTs: number,
|
|
82
82
|
capped: boolean,
|
|
83
|
+
// Replace an unattempted pending admission with the merged batch named @ needs.
|
|
84
|
+
replace = false,
|
|
83
85
|
): PendingAdmission {
|
|
84
86
|
const now = Date.now();
|
|
85
87
|
const existing = readPendingAdmission<PendingAdmission>(sessionID, roomId, now);
|
|
@@ -91,6 +93,7 @@ export function getOrCreatePendingAdmission(
|
|
|
91
93
|
const covered = existing?.state === "admitted" &&
|
|
92
94
|
items.every((item) => !item.id || existing.items.some((delivered) => delivered.id === item.id));
|
|
93
95
|
if (
|
|
96
|
+
!replace &&
|
|
94
97
|
existing &&
|
|
95
98
|
(existing.state === "admitted" ? maxTs <= existing.maxTs && covered : existing.id === id || retriesOriginal)
|
|
96
99
|
) {
|
|
@@ -9,6 +9,7 @@ import type {
|
|
|
9
9
|
RoomFileConfig,
|
|
10
10
|
ServerSettings,
|
|
11
11
|
} from "../protocol/config.ts";
|
|
12
|
+
import { NOTIFICATION_DELAY_MAX_MS } from "../protocol/config.ts";
|
|
12
13
|
|
|
13
14
|
export type { ChannelDSettings, ClientSettings, RoomFileConfig, ServerSettings };
|
|
14
15
|
|
|
@@ -86,6 +87,8 @@ function parseClient(value: unknown): RoomFileConfig["client"] {
|
|
|
86
87
|
if (requestTimeoutMs !== undefined && requestTimeoutMs < 1000) {
|
|
87
88
|
throw new Error("chatroom config: client.requestTimeoutMs must be at least 1000");
|
|
88
89
|
}
|
|
90
|
+
const notificationDelayMs = delayMs(raw.notificationDelayMs, "client.notificationDelayMs");
|
|
91
|
+
const notificationJitterMs = delayMs(raw.notificationJitterMs, "client.notificationJitterMs");
|
|
89
92
|
return {
|
|
90
93
|
url: optionalString(raw.url, "client.url"),
|
|
91
94
|
token: optionalString(raw.token, "client.token"),
|
|
@@ -94,10 +97,20 @@ function parseClient(value: unknown): RoomFileConfig["client"] {
|
|
|
94
97
|
delivery: optionalBoolean(raw.delivery, "client.delivery"),
|
|
95
98
|
deliveryIntervalMs,
|
|
96
99
|
requestTimeoutMs,
|
|
100
|
+
notificationDelayMs,
|
|
101
|
+
notificationJitterMs,
|
|
97
102
|
codexBin: optionalString(raw.codexBin, "client.codexBin"),
|
|
98
103
|
};
|
|
99
104
|
}
|
|
100
105
|
|
|
106
|
+
function delayMs(value: unknown, where: string): number | undefined {
|
|
107
|
+
const ms = optionalNumber(value, where);
|
|
108
|
+
if (ms !== undefined && (!Number.isInteger(ms) || ms < 0 || ms > NOTIFICATION_DELAY_MAX_MS)) {
|
|
109
|
+
throw new Error(`chatroom config: ${where} must be an integer from 0 to ${NOTIFICATION_DELAY_MAX_MS}`);
|
|
110
|
+
}
|
|
111
|
+
return ms;
|
|
112
|
+
}
|
|
113
|
+
|
|
101
114
|
function parsePeers(value: unknown): RoomFileConfig["p2p"] {
|
|
102
115
|
const raw = asRecord(value, "p2p");
|
|
103
116
|
if (!raw) return undefined;
|
|
@@ -271,11 +284,23 @@ export function resolveServerSettings(file: RoomFileConfig | null, env: NodeJS.P
|
|
|
271
284
|
};
|
|
272
285
|
}
|
|
273
286
|
|
|
287
|
+
function notificationMsEnv(env: NodeJS.ProcessEnv, key: string): number | undefined {
|
|
288
|
+
const raw = envValue(env, key)?.trim();
|
|
289
|
+
if (!raw) return undefined;
|
|
290
|
+
const value = Number(raw);
|
|
291
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value > NOTIFICATION_DELAY_MAX_MS) {
|
|
292
|
+
throw new Error(`${key} must be an integer from 0 to ${NOTIFICATION_DELAY_MAX_MS}`);
|
|
293
|
+
}
|
|
294
|
+
return value;
|
|
295
|
+
}
|
|
296
|
+
|
|
274
297
|
/** Environment overrides the file; client.url/token fall back to top-level. */
|
|
275
298
|
export function resolveClientSettings(file: RoomFileConfig | null, env: NodeJS.ProcessEnv = process.env): ClientSettings {
|
|
276
299
|
return {
|
|
277
300
|
url: envValue(env, "CHAT_ROOM_SERVER_URL") ?? file?.client?.url ?? file?.url ?? "",
|
|
278
301
|
token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.client?.token ?? file?.token ?? "",
|
|
279
302
|
wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.client?.wakeServeUrl ?? file?.server?.wakeServeUrl ?? "",
|
|
303
|
+
notificationDelayMs: notificationMsEnv(env, "CHAT_ROOM_NOTIFICATION_DELAY_MS") ?? file?.client?.notificationDelayMs ?? 0,
|
|
304
|
+
notificationJitterMs: notificationMsEnv(env, "CHAT_ROOM_NOTIFICATION_JITTER_MS") ?? file?.client?.notificationJitterMs ?? 2000,
|
|
280
305
|
};
|
|
281
306
|
}
|