@alexsun-top/opencode-chat-room 0.6.7 → 0.6.9
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 +24 -0
- package/README.md +6 -3
- package/README.zh-CN.md +7 -3
- package/docs/administrator-rooms.md +7 -2
- package/package.json +4 -1
- package/plugin.ts +38 -8
- package/server/assets/base.css +222 -28
- package/server/assets/chat/admin-badge.js +28 -6
- package/server/assets/chat/admin.js +7 -1
- package/server/assets/chat/announcements.js +1 -1
- package/server/assets/chat/attachment-store.js +106 -0
- package/server/assets/chat/attachments.js +201 -21
- package/server/assets/chat/confirm-dialog.js +28 -0
- package/server/assets/chat/events.js +37 -9
- package/server/assets/chat/image-zoom.js +86 -2
- package/server/assets/chat/index.js +10 -0
- package/server/assets/chat/install-prompt.js +82 -0
- package/server/assets/chat/join-requests.js +355 -0
- package/server/assets/chat/markdown.js +55 -7
- package/server/assets/chat/members.js +5 -3
- package/server/assets/chat/message-polling.js +24 -3
- package/server/assets/chat/messages.js +6 -4
- package/server/assets/chat/questions.js +10 -6
- package/server/assets/chat/recall.js +267 -0
- package/server/assets/chat/reminders.js +53 -9
- package/server/assets/chat/replies.js +1 -1
- package/server/assets/chat/room-list.js +14 -5
- package/server/assets/chat/room-watcher.js +5 -1
- package/server/assets/chat/rooms.js +17 -5
- package/server/assets/chat/shortcuts.js +40 -0
- package/server/assets/chat/state.js +69 -16
- package/server/assets/chat/system-messages.js +4 -0
- package/server/assets/conversation.css +2 -2
- package/server/assets/recall.css +29 -0
- package/server/assets/responsive.css +41 -13
- package/server/chat-server.ts +55 -66
- package/server/chat.html +139 -16
- package/server/inbox.ts +1 -1
- package/server/join-requests.ts +106 -0
- package/server/message-recall-routes.ts +37 -0
- package/server/newrooms.ts +9 -0
- package/server/room-join.ts +59 -0
- package/server/room-owner.ts +3 -20
- package/server/room-payload.ts +2 -0
- package/server/sw.js +1 -0
- package/server/wake.ts +45 -16
- package/skills/chatroom/SKILL.md +32 -0
- package/src/README.md +5 -3
- package/src/agent/admin-client.ts +28 -4
- package/src/center/center-client.ts +81 -4
- package/src/center/center-inbox.ts +35 -10
- package/src/center/center-wake.ts +25 -12
- package/src/center/message-ids.ts +7 -0
- package/src/center/notification-budget.ts +16 -0
- package/src/center/queue.ts +14 -4
- package/src/rooms/room-service.ts +10 -1
- package/src/runtime/plugin-notifications.ts +37 -11
- package/src/runtime/v2-plugin.ts +1 -1
- package/src/state/roles.ts +34 -0
- package/src/state/sqlite-state.ts +197 -27
- package/src/state/store.ts +22 -3
- package/src/tests/announcement-board.ts +12 -2
|
@@ -51,6 +51,58 @@ function svcOf(room: Json): RoomService {
|
|
|
51
51
|
|
|
52
52
|
export type CenterOpts = { center: string; token: string; directory?: string };
|
|
53
53
|
|
|
54
|
+
export type JoinRequestStatus = "pending" | "joined" | "none";
|
|
55
|
+
export type JoinRequest = {
|
|
56
|
+
sessionID: string;
|
|
57
|
+
participantId: string;
|
|
58
|
+
name: string;
|
|
59
|
+
isAgent: boolean;
|
|
60
|
+
createdAt: number;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
async function reviewRequest<T>(run: Promise<T>, verb: string): Promise<T> {
|
|
64
|
+
try {
|
|
65
|
+
return await run;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
const status = (error as { status?: number }).status;
|
|
68
|
+
if (status === 403) throw new Error(`not allowed: only a human administrator or the designated management agent can ${verb} join requests`);
|
|
69
|
+
if (status === 404) throw new Error("join request already handled or gone; list the pending requests again");
|
|
70
|
+
if (status === 409) throw new Error("join request is stale: the requester identity or name collides; deny it and ask them to join again");
|
|
71
|
+
throw error;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function joinStatus(opts: CenterOpts, roomId: string, sessionID: string): Promise<JoinRequestStatus> {
|
|
76
|
+
const data = await request(opts, `/rooms/${encodeURIComponent(roomId)}/join-requests/status?sessionID=${encodeURIComponent(sessionID)}`, "GET");
|
|
77
|
+
return data.status === "pending" || data.status === "joined" ? data.status : "none";
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function listJoinRequests(opts: CenterOpts, roomId: string, reviewerSessionID: string,
|
|
81
|
+
extraHeaders?: Record<string, string>): Promise<JoinRequest[]> {
|
|
82
|
+
const data = await reviewRequest(
|
|
83
|
+
request(opts, `/rooms/${encodeURIComponent(roomId)}/join-requests?sessionID=${encodeURIComponent(reviewerSessionID)}`, "GET", undefined, extraHeaders),
|
|
84
|
+
"list",
|
|
85
|
+
);
|
|
86
|
+
const rows = Array.isArray(data) ? data : [];
|
|
87
|
+
return rows
|
|
88
|
+
.filter((row) => row && typeof row.sessionID === "string" && typeof row.name === "string")
|
|
89
|
+
.map((row) => ({
|
|
90
|
+
sessionID: String(row.sessionID),
|
|
91
|
+
participantId: String(row.participantId ?? row.name),
|
|
92
|
+
name: String(row.name),
|
|
93
|
+
isAgent: row.isAgent === true,
|
|
94
|
+
createdAt: Number(row.createdAt ?? 0),
|
|
95
|
+
}));
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function decideJoinRequest(opts: CenterOpts, roomId: string, requestSessionID: string,
|
|
99
|
+
approve: boolean, reviewerSessionID: string, extraHeaders?: Record<string, string>): Promise<void> {
|
|
100
|
+
await reviewRequest(
|
|
101
|
+
request(opts, `/rooms/${encodeURIComponent(roomId)}/join-requests/${encodeURIComponent(requestSessionID)}/${approve ? "approve" : "deny"}`, "POST", { sessionID: reviewerSessionID }, extraHeaders),
|
|
102
|
+
approve ? "approve" : "deny",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
54
106
|
export async function request(
|
|
55
107
|
opts: CenterOpts,
|
|
56
108
|
path: string,
|
|
@@ -109,12 +161,14 @@ export async function centerAction(
|
|
|
109
161
|
action: string;
|
|
110
162
|
name?: string;
|
|
111
163
|
roomId?: string;
|
|
164
|
+
messageId?: string;
|
|
112
165
|
text?: string;
|
|
113
166
|
announcementName?: string;
|
|
114
167
|
content?: string;
|
|
115
168
|
isQuestion?: boolean;
|
|
116
169
|
receiverOwnerID?: string;
|
|
117
170
|
protocol?: "v1" | "v2";
|
|
171
|
+
joinPolicy?: "open" | "approval";
|
|
118
172
|
},
|
|
119
173
|
sessionID: string,
|
|
120
174
|
): Promise<string> {
|
|
@@ -145,6 +199,7 @@ export async function centerAction(
|
|
|
145
199
|
// Record the owning host so only that host wakes this session.
|
|
146
200
|
host: os.hostname(),
|
|
147
201
|
directory: opts.directory,
|
|
202
|
+
...(args.joinPolicy ? { joinPolicy: args.joinPolicy } : {}),
|
|
148
203
|
...(args.protocol === "v2" ? { protocol: "v2", receiverOwnerID: args.receiverOwnerID } : {}),
|
|
149
204
|
});
|
|
150
205
|
return formatRoom(svcOf(room), toRoom(room));
|
|
@@ -171,8 +226,20 @@ export async function centerAction(
|
|
|
171
226
|
...(args.protocol === "v2" ? { protocol: "v2", receiverOwnerID: args.receiverOwnerID } : {}),
|
|
172
227
|
},
|
|
173
228
|
);
|
|
229
|
+
if (room.status === "pending") {
|
|
230
|
+
return `pending: join request sent to room ${args.roomId}; a human administrator must approve it. You are NOT a member yet: do not claim you joined, and do not send or poll until join_status reports joined.`;
|
|
231
|
+
}
|
|
174
232
|
return formatRoom(svcOf(room), toRoom(room));
|
|
175
233
|
}
|
|
234
|
+
case "join_status": {
|
|
235
|
+
if (!args.roomId) return "error: roomId is required";
|
|
236
|
+
const status = await joinStatus(opts, args.roomId, sessionID);
|
|
237
|
+
if (status === "joined") return `joined room ${args.roomId}`;
|
|
238
|
+
if (status === "pending") {
|
|
239
|
+
return `pending: join request for room ${args.roomId} is waiting for a human administrator; you are NOT a member yet`;
|
|
240
|
+
}
|
|
241
|
+
return `none: no join request for room ${args.roomId}; run join with your name to request access`;
|
|
242
|
+
}
|
|
176
243
|
case "leave": {
|
|
177
244
|
if (!args.roomId) {
|
|
178
245
|
return "error: roomId is required";
|
|
@@ -237,8 +304,17 @@ export async function centerAction(
|
|
|
237
304
|
"POST",
|
|
238
305
|
{ sessionID, text: args.text.trim(), ...(args.isQuestion ? { isQuestion: true } : {}) },
|
|
239
306
|
);
|
|
240
|
-
const
|
|
241
|
-
|
|
307
|
+
const parsed = toRoom(room);
|
|
308
|
+
const sentID = [...parsed.messages].reverse()
|
|
309
|
+
.find((message) => message.senderSessionID === sessionID && message.text === args.text!.trim())?.id
|
|
310
|
+
?? parsed.messages.at(-1)?.id;
|
|
311
|
+
return `sent: ${args.text.trim()}\n${sentID ? `message id: ${sentID}\n` : ""}${formatRoom(svcOf(room), parsed)}`;
|
|
312
|
+
}
|
|
313
|
+
case "recall": {
|
|
314
|
+
if (!args.roomId) return "error: roomId is required";
|
|
315
|
+
if (!args.messageId) return "error: messageId is required";
|
|
316
|
+
await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/messages/${encodeURIComponent(args.messageId)}/recall`, "POST", { sessionID });
|
|
317
|
+
return `recalled message ${args.messageId}`;
|
|
242
318
|
}
|
|
243
319
|
case "poll": {
|
|
244
320
|
if (!args.roomId) {
|
|
@@ -260,12 +336,13 @@ export async function centerAction(
|
|
|
260
336
|
if (!result.member) {
|
|
261
337
|
return "error: not joined";
|
|
262
338
|
}
|
|
263
|
-
const items = (Array.isArray(result.items) ? result.items : [])
|
|
339
|
+
const items = (Array.isArray(result.items) ? result.items : [])
|
|
340
|
+
.filter((item) => item.senderSessionID !== sessionID && !item.recalledAt);
|
|
264
341
|
if (items.length === 0) {
|
|
265
342
|
return "no new messages";
|
|
266
343
|
}
|
|
267
344
|
const lines = items.map(
|
|
268
|
-
(it) => `[${timeOf(it.createdAt)}] ${it.senderId}: ${it.text}`,
|
|
345
|
+
(it) => `[${timeOf(it.createdAt)}] ${it.senderId}: ${it.text} (id: ${it.id})`,
|
|
269
346
|
);
|
|
270
347
|
// ponytail: F7 — serialize the acknowledgment before returning so a
|
|
271
348
|
// following action cannot race the read watermark update. A failure only
|
|
@@ -10,6 +10,8 @@ import {
|
|
|
10
10
|
} from "./queue.ts";
|
|
11
11
|
import { request, markQueued, type CenterOpts } from "./center-client.ts";
|
|
12
12
|
import { explicitlyAddresses } from "./mentions.ts";
|
|
13
|
+
import { withMessageIds } from "./message-ids.ts";
|
|
14
|
+
import { notificationPrefix } from "./notification-budget.ts";
|
|
13
15
|
import { claimBackgroundAttempt } from "../state/receiver-state.ts";
|
|
14
16
|
import { prepareReceiptCandidate, receiptDestination } from "../agent/agent-receipts.ts";
|
|
15
17
|
import { serializeSessionPush } from "./session-delivery.ts";
|
|
@@ -67,7 +69,7 @@ export async function checkCenterInbox(
|
|
|
67
69
|
}
|
|
68
70
|
items = [...merged.values()].sort((a, b) => a.createdAt - b.createdAt);
|
|
69
71
|
}
|
|
70
|
-
await pushItemsToSession(opts, sessionID, items, transport, queued, qualified);
|
|
72
|
+
await pushItemsToSession(opts, sessionID, items, transport, queued, qualified, result.hasMore === false);
|
|
71
73
|
});
|
|
72
74
|
} catch {
|
|
73
75
|
// The next inbox poll retries failed delivery.
|
|
@@ -136,6 +138,8 @@ export async function pushItemsToSession(
|
|
|
136
138
|
transport: QueueTransport,
|
|
137
139
|
queuedTs: Readonly<Record<string, number>> = {},
|
|
138
140
|
qualifiedRooms: ReadonlySet<string> = new Set(),
|
|
141
|
+
// A truncated multi-room page cannot prove an absent pending item was recalled.
|
|
142
|
+
pageComplete = true,
|
|
139
143
|
): Promise<PushResult> {
|
|
140
144
|
const rooms = new Map<string, InboxItem[]>();
|
|
141
145
|
const mentionOnly = transport.mentionOnlySessions?.has(sessionID) ?? false;
|
|
@@ -160,28 +164,49 @@ export async function pushItemsToSession(
|
|
|
160
164
|
const target = { ...transport, directory: recipient.directory ?? transport.directory };
|
|
161
165
|
const roomKind = recipient.roomKind ?? batch.find((item) => item.roomKind)?.roomKind ?? "group";
|
|
162
166
|
const cutoff = Math.max(queuedTs[roomId] ?? 0, recipient.lastReadTs ?? 0, recipient.lastQueuedTs ?? 0);
|
|
163
|
-
const unread = batch.filter((item) => item.createdAt > cutoff);
|
|
167
|
+
const unread = batch.filter((item) => item.createdAt > cutoff && !item.recalledAt);
|
|
168
|
+
// Recalled messages disappear from the authoritative inbox; drop them from
|
|
169
|
+
// a pending admission before its prompt is delivered again.
|
|
170
|
+
const live = new Set(batch.map((item) => item.id).filter((id): id is string => typeof id === "string" && !!id));
|
|
171
|
+
// A truncated page cannot mark recalls; the room snapshot can.
|
|
172
|
+
const recalled = new Set<string>();
|
|
173
|
+
if (!pageComplete && pendingAdmission(sessionID, roomId)?.state === "pending") {
|
|
174
|
+
try {
|
|
175
|
+
const room = await request(opts, `/rooms/${encodeURIComponent(roomId)}`, "GET") as { messages?: Array<{ id?: string; recalledAt?: number }> };
|
|
176
|
+
for (const message of room.messages ?? []) if (message.id && message.recalledAt) recalled.add(message.id);
|
|
177
|
+
} catch { /* keep the page view */ }
|
|
178
|
+
}
|
|
164
179
|
prunePendingAdmission(sessionID, roomId, cutoff,
|
|
165
|
-
(pending) => render(batch[0]!.roomName, roomId, roomKind, recipient!.name ?? "you", pending)
|
|
180
|
+
(pending) => render(batch[0]!.roomName, roomId, roomKind, recipient!.name ?? "you", pending),
|
|
181
|
+
(item) => !item.id || (!recalled.has(item.id) && (!pageComplete || live.has(item.id))));
|
|
166
182
|
const existing = pendingAdmission(sessionID, roomId);
|
|
167
183
|
if (!unread.length && existing?.state !== "pending") continue;
|
|
168
|
-
const
|
|
169
|
-
const delta = existing?.state === "admitted"
|
|
170
|
-
? unread.filter((item) => item.createdAt > existing.maxTs)
|
|
184
|
+
const deliveredIDs = new Set(existing?.state === "admitted" ? existing.items.map((item) => item.id) : []);
|
|
185
|
+
const delta = existing?.state === "admitted"
|
|
186
|
+
? unread.filter((item) => item.createdAt > existing.maxTs || !deliveredIDs.has(item.id))
|
|
171
187
|
: unread;
|
|
172
188
|
const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
|
|
173
189
|
if (roomMentionOnly && (!recipient?.name ||
|
|
174
190
|
!eligibleItems.some((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind)) &&
|
|
175
191
|
!delta.slice(-20).some((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind)))) continue;
|
|
176
|
-
if (existing?.state === "admitted" &&
|
|
192
|
+
if (existing?.state === "admitted" && !delta.length) {
|
|
177
193
|
if (existing.maxTs > 0 && await markQueued(opts, roomId, sessionID, existing.maxTs)) {
|
|
178
194
|
clearPendingAdmission(sessionID, roomId, existing.maxTs);
|
|
179
195
|
}
|
|
180
196
|
continue;
|
|
181
197
|
}
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
198
|
+
// A later trigger may carry only newer messages; retain the undelivered
|
|
199
|
+
// admission so retrying it first cannot skip older unread messages.
|
|
200
|
+
const carried = existing?.state === "pending" ? existing.items : [];
|
|
201
|
+
const carriedIDs = new Set(carried.map((item) => item.id));
|
|
202
|
+
const merged = carried.length
|
|
203
|
+
? [...carried, ...delta.filter((item) => !carriedIDs.has(item.id)).slice(0, Math.max(0, 20 - carried.length))]
|
|
204
|
+
: delta;
|
|
205
|
+
const deliverable = notificationPrefix(merged);
|
|
206
|
+
const deltaTs = deliverable.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
207
|
+
const displayDelta = withMessageIds(deliverable);
|
|
208
|
+
const { prompt, capped } = render(batch[0]!.roomName, roomId, roomKind, recipient.name ?? "you", displayDelta);
|
|
209
|
+
const admission = getOrCreatePendingAdmission(sessionID, roomId, displayDelta, prompt, deltaTs, capped);
|
|
185
210
|
const addressedTs = recipient.name
|
|
186
211
|
? admission.items.filter((item) => explicitlyAddresses(item, recipient.name!, sessionID, roomKind))
|
|
187
212
|
.reduce((max, item) => Math.max(max, item.createdAt), 0)
|
|
@@ -4,6 +4,8 @@ import {
|
|
|
4
4
|
formatServeWakePrompt,
|
|
5
5
|
} from "../state/store.ts";
|
|
6
6
|
import { explicitlyAddresses } from "./mentions.ts";
|
|
7
|
+
import { withMessageIds } from "./message-ids.ts";
|
|
8
|
+
import { notificationPrefix } from "./notification-budget.ts";
|
|
7
9
|
import {
|
|
8
10
|
clearPendingAdmission,
|
|
9
11
|
getOrCreatePendingAdmission,
|
|
@@ -105,14 +107,15 @@ export async function wakeSessions(
|
|
|
105
107
|
await serializeSessionPush(sessionID, async () => {
|
|
106
108
|
const inbox = await request(opts,
|
|
107
109
|
`/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(roomId)}&excludeSelf=1&timeout=0`,
|
|
108
|
-
"GET") as { items?: InboxItem[]; queuedTs?: Record<string, number
|
|
110
|
+
"GET") as { items?: InboxItem[]; queuedTs?: Record<string, number>; hasMore?: boolean };
|
|
109
111
|
const queuedTs = Math.max(entry.lastQueuedTs ?? 0, inbox.queuedTs?.[roomId] ?? 0);
|
|
110
112
|
const items = (Array.isArray(inbox.items) ? inbox.items : []).filter(
|
|
111
113
|
(item) => item.roomId === roomId && item.createdAt > queuedTs,
|
|
112
114
|
);
|
|
113
115
|
if (!items.length) return;
|
|
114
116
|
const target = { ...transport, directory: entry.directory ?? transport.directory };
|
|
115
|
-
const pushed = await pushItemsToSession(opts, sessionID, items, target, inbox.queuedTs
|
|
117
|
+
const pushed = await pushItemsToSession(opts, sessionID, items, target, inbox.queuedTs,
|
|
118
|
+
new Set(), !(inbox.hasMore ?? false));
|
|
116
119
|
if (pushed !== "unreachable" || !serveUrl) return;
|
|
117
120
|
const currentRegistry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, typeof entry>;
|
|
118
121
|
const current = currentRegistry[sessionID];
|
|
@@ -123,21 +126,31 @@ export async function wakeSessions(
|
|
|
123
126
|
const unread = items.filter((item) => item.createdAt > currentCursor);
|
|
124
127
|
const mentioned = unread.some((item) => explicitlyAddresses(item, current.name, sessionID, roomKind));
|
|
125
128
|
if (!mentioned) return;
|
|
126
|
-
const
|
|
129
|
+
const live = new Set(items.map((item) => item.id).filter(Boolean));
|
|
127
130
|
prunePendingAdmission(sessionID, roomId, currentCursor, (pending) => {
|
|
128
131
|
const { lines, capped } = formatNotificationLines(pending);
|
|
129
132
|
return { prompt: formatServeWakePrompt(unread[0]!.roomName, roomId, lines), capped };
|
|
130
|
-
});
|
|
133
|
+
}, (item) => !item.id || inbox.hasMore !== false || live.has(item.id));
|
|
131
134
|
const existing = pendingAdmission(sessionID, roomId);
|
|
132
|
-
const
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
const
|
|
135
|
+
const deliveredIDs = new Set(existing?.state === "admitted" ? existing.items.map((item) => item.id) : []);
|
|
136
|
+
const delta = existing?.state === "admitted"
|
|
137
|
+
? unread.filter((item) => item.createdAt > existing.maxTs || !deliveredIDs.has(item.id)) : unread;
|
|
138
|
+
if (existing?.state === "admitted" && !delta.length) return;
|
|
139
|
+
// Merge an undelivered admission with the newer delta instead of
|
|
140
|
+
// replacing it, so retrying the old prompt cannot skip messages.
|
|
141
|
+
const carried = existing?.state === "pending" ? existing.items : [];
|
|
142
|
+
const carriedIDs = new Set(carried.map((item) => item.id));
|
|
143
|
+
const merged = carried.length
|
|
144
|
+
? [...carried, ...delta.filter((item) => !carriedIDs.has(item.id)).slice(0, Math.max(0, 20 - carried.length))]
|
|
145
|
+
: delta;
|
|
146
|
+
const deliverable = notificationPrefix(merged);
|
|
147
|
+
const displayDelta = withMessageIds(deliverable);
|
|
148
|
+
const { lines, capped } = formatNotificationLines(displayDelta);
|
|
149
|
+
const prompt = formatServeWakePrompt(items[0]!.roomName, roomId, lines);
|
|
150
|
+
const maxTs = deliverable.reduce((max, item) => Math.max(max, item.createdAt), 0);
|
|
151
|
+
const admission = getOrCreatePendingAdmission(sessionID, roomId, displayDelta, prompt, maxTs, capped);
|
|
139
152
|
await wakeViaServe(serveUrl, sessionID, roomId, opts, target, admission,
|
|
140
|
-
|
|
153
|
+
items[0]!.roomName, entry.host, entry.directory, roomKind);
|
|
141
154
|
});
|
|
142
155
|
}
|
|
143
156
|
} catch {
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Message IDs ride inside the text prefix so the 300-char line budget never
|
|
2
|
+
// truncates the ID an agent needs for recall.
|
|
3
|
+
export function withMessageIds<T extends { id?: string; text: string }>(items: readonly T[]): T[] {
|
|
4
|
+
return items.map((item) => item.id && !item.text.startsWith(`(id: ${item.id}) `)
|
|
5
|
+
? { ...item, text: `(id: ${item.id}) ${item.text}` }
|
|
6
|
+
: item);
|
|
7
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Mirror of MAX_LINES in formatNotificationLines: format keeps the newest
|
|
2
|
+
// lines, so an admission must instead carry the oldest prefix that fits.
|
|
3
|
+
// Otherwise bumping its maxTs would skip unrendered older messages.
|
|
4
|
+
const MAX_NOTIFICATION_LINES = 20;
|
|
5
|
+
|
|
6
|
+
export function notificationPrefix<T extends { id?: string; senderId: string; text: string; createdAt: number; answerQuestionExcerpt?: string }>(items: readonly T[]): T[] {
|
|
7
|
+
let lines = 0;
|
|
8
|
+
let end = 0;
|
|
9
|
+
for (const item of items) {
|
|
10
|
+
const needed = item.answerQuestionExcerpt ? 2 : 1;
|
|
11
|
+
if (lines + needed > MAX_NOTIFICATION_LINES) break;
|
|
12
|
+
lines += needed;
|
|
13
|
+
end++;
|
|
14
|
+
}
|
|
15
|
+
return items.slice(0, end);
|
|
16
|
+
}
|
package/src/center/queue.ts
CHANGED
|
@@ -10,6 +10,7 @@ export type QueueItem = {
|
|
|
10
10
|
createdAt: number;
|
|
11
11
|
roomKind?: "group" | "direct";
|
|
12
12
|
answerQuestionExcerpt?: string;
|
|
13
|
+
recalledAt?: number;
|
|
13
14
|
};
|
|
14
15
|
|
|
15
16
|
export type QueueBody = {
|
|
@@ -85,23 +86,30 @@ export function getOrCreatePendingAdmission(
|
|
|
85
86
|
const id = queueAdmissionId(sessionID, roomId, items, prompt);
|
|
86
87
|
const retriesOriginal = existing?.state === "pending" && existing.items.length < items.length &&
|
|
87
88
|
queueAdmissionId(sessionID, roomId, existing.items) === queueAdmissionId(sessionID, roomId, items.slice(0, existing.items.length));
|
|
89
|
+
// An admitted prompt only covers the items it carried. Older unread items
|
|
90
|
+
// that surfaced later must get their own admission even below its maxTs.
|
|
91
|
+
const covered = existing?.state === "admitted" &&
|
|
92
|
+
items.every((item) => !item.id || existing.items.some((delivered) => delivered.id === item.id));
|
|
88
93
|
if (
|
|
89
94
|
existing &&
|
|
90
|
-
(existing.state === "admitted" ? maxTs <= existing.maxTs : existing.id === id || retriesOriginal)
|
|
95
|
+
(existing.state === "admitted" ? maxTs <= existing.maxTs && covered : existing.id === id || retriesOriginal)
|
|
91
96
|
) {
|
|
92
97
|
return existing;
|
|
93
98
|
}
|
|
99
|
+
// Keep the watermark monotonic when a retried admission fills a delivery gap
|
|
100
|
+
// below an already-admitted one.
|
|
101
|
+
const admissionMaxTs = existing?.state === "admitted" ? Math.max(maxTs, existing.maxTs) : maxTs;
|
|
94
102
|
const admission: PendingAdmission = {
|
|
95
103
|
id,
|
|
96
104
|
createdAt: now,
|
|
97
105
|
prompt,
|
|
98
106
|
itemCount: items.length,
|
|
99
|
-
maxTs,
|
|
107
|
+
maxTs: admissionMaxTs,
|
|
100
108
|
capped,
|
|
101
109
|
state: "pending",
|
|
102
110
|
items: items.slice(-20).map((item) => ({ ...item })),
|
|
103
111
|
};
|
|
104
|
-
if (
|
|
112
|
+
if (admissionMaxTs > 0) {
|
|
105
113
|
save(sessionID, roomId, admission, now);
|
|
106
114
|
}
|
|
107
115
|
return admission;
|
|
@@ -112,6 +120,8 @@ export function prunePendingAdmission(
|
|
|
112
120
|
roomId: string,
|
|
113
121
|
throughTs: number,
|
|
114
122
|
rebuild: (items: QueueItem[]) => { prompt: string; capped: boolean },
|
|
123
|
+
// Authoritative recheck: drop items the source no longer returns (recalled).
|
|
124
|
+
keep?: (item: QueueItem) => boolean,
|
|
115
125
|
): PendingAdmission | undefined {
|
|
116
126
|
const existing = pendingAdmission(sessionID, roomId);
|
|
117
127
|
if (!existing) return undefined;
|
|
@@ -119,7 +129,7 @@ export function prunePendingAdmission(
|
|
|
119
129
|
if (existing.maxTs <= throughTs) deletePendingAdmission(sessionID, roomId);
|
|
120
130
|
return existing.maxTs <= throughTs ? undefined : existing;
|
|
121
131
|
}
|
|
122
|
-
const items = existing.items.filter((item) => item.createdAt > throughTs);
|
|
132
|
+
const items = existing.items.filter((item) => item.createdAt > throughTs && (!keep || keep(item)));
|
|
123
133
|
if (items.length === existing.items.length) return existing;
|
|
124
134
|
if (!items.length) { deletePendingAdmission(sessionID, roomId); return undefined; }
|
|
125
135
|
const { prompt, capped } = rebuild(items);
|
|
@@ -16,12 +16,20 @@ export type Message = {
|
|
|
16
16
|
isQuestion?: boolean;
|
|
17
17
|
answerToMessageID?: string;
|
|
18
18
|
answeredByMessageID?: string;
|
|
19
|
+
// Soft recall: the original text stays in storage for member reveal, while
|
|
20
|
+
// read paths expose the message as a tombstone.
|
|
21
|
+
recalledAt?: number;
|
|
22
|
+
recalledBy?: string;
|
|
19
23
|
};
|
|
20
24
|
|
|
25
|
+
export type JoinPolicy = "open" | "approval";
|
|
26
|
+
|
|
21
27
|
export type Room = {
|
|
22
28
|
id: string;
|
|
23
29
|
name: string;
|
|
24
30
|
description?: string;
|
|
31
|
+
// Absent means "open" so rooms created before approvals existed stay open.
|
|
32
|
+
joinPolicy?: JoinPolicy;
|
|
25
33
|
ownerId: string;
|
|
26
34
|
// Server-issued membership binding for the owner and the explicitly chosen successor.
|
|
27
35
|
// Display names remain the public identity; the membership IDs guard against name reuse.
|
|
@@ -72,11 +80,12 @@ export default class RoomService {
|
|
|
72
80
|
}
|
|
73
81
|
}
|
|
74
82
|
|
|
75
|
-
createRoom(name: string, ownerId: string): Room {
|
|
83
|
+
createRoom(name: string, ownerId: string, joinPolicy?: JoinPolicy): Room {
|
|
76
84
|
const room: Room = {
|
|
77
85
|
id: randomUUID(),
|
|
78
86
|
name,
|
|
79
87
|
ownerId,
|
|
88
|
+
...(joinPolicy === "approval" ? { joinPolicy } : {}),
|
|
80
89
|
participants: new Map(),
|
|
81
90
|
messages: [],
|
|
82
91
|
createdAt: Date.now(),
|
|
@@ -6,11 +6,14 @@ import {
|
|
|
6
6
|
loadRegistry,
|
|
7
7
|
loadRooms,
|
|
8
8
|
readQuestionExcerpt,
|
|
9
|
+
recalledMessageIDs,
|
|
9
10
|
statePath,
|
|
10
11
|
timeOf,
|
|
11
12
|
} from "../state/store.ts";
|
|
12
13
|
import { backgroundResult, backgroundServiceKey, sendAsyncNotification, sendQueue, type BackgroundResult, type QueueTransport } from "../center/queue-transport.ts";
|
|
13
14
|
import { explicitlyAddresses } from "../center/mentions.ts";
|
|
15
|
+
import { withMessageIds } from "../center/message-ids.ts";
|
|
16
|
+
import { notificationPrefix } from "../center/notification-budget.ts";
|
|
14
17
|
import { claimBackgroundAttempt } from "../state/receiver-state.ts";
|
|
15
18
|
import { serializeSessionPush } from "../center/center-inbox.ts";
|
|
16
19
|
import { prepareReceiptCandidate, receiptDestination } from "../agent/agent-receipts.ts";
|
|
@@ -75,10 +78,13 @@ export function createNotifier(deps: {
|
|
|
75
78
|
batch: NotifyBatch,
|
|
76
79
|
transport: QueueTransport,
|
|
77
80
|
): Promise<NotifyAttempt | undefined> {
|
|
78
|
-
batch = { ...batch, messages: await Promise.all(batch.messages.map(async (message) => message.answerToMessageID
|
|
79
|
-
? { ...message, answerQuestionExcerpt: await readQuestionExcerpt(batch.roomId, message.answerToMessageID) }
|
|
80
|
-
: message)) };
|
|
81
81
|
const [registry, rooms] = await Promise.all([loadRegistry(), loadRooms()]);
|
|
82
|
+
// Recheck against the current room snapshot: a recall may land after the
|
|
83
|
+
// notifier batch was captured but before this delivery attempt.
|
|
84
|
+
const fresh = new Map((rooms.find((room) => room.id === batch.roomId)?.messages ?? []).map((message) => [message.id, message]));
|
|
85
|
+
batch = { ...batch, messages: (await Promise.all(batch.messages.map(async (message) => message.answerToMessageID
|
|
86
|
+
? { ...message, answerQuestionExcerpt: await readQuestionExcerpt(batch.roomId, message.answerToMessageID) }
|
|
87
|
+
: message))).filter((message) => !message.recalledAt && !fresh.get(message.id)?.recalledAt) };
|
|
82
88
|
const entry = registry[batch.roomId]?.[sessionID];
|
|
83
89
|
const roomKind = batch.roomKind ?? rooms.find((room) => room.id === batch.roomId)?.kind ?? "group";
|
|
84
90
|
if (!entry || (entry.protocol !== "v2" && !entry.serverUrl)) return undefined;
|
|
@@ -95,7 +101,14 @@ export function createNotifier(deps: {
|
|
|
95
101
|
};
|
|
96
102
|
const service = backgroundServiceKey(targetTransport);
|
|
97
103
|
const cutoff = Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0);
|
|
98
|
-
|
|
104
|
+
// The room snapshot is the recall authority. A trigger batch may be only a
|
|
105
|
+
// small delta, so an ID missing from it does not mean the message is gone.
|
|
106
|
+
// The snapshot window is bounded, so ask the store for older pending IDs.
|
|
107
|
+
const missingIDs = (pendingAdmission(sessionID, batch.roomId)?.items ?? [])
|
|
108
|
+
.map((item) => item.id).filter((id): id is string => !!id && !fresh.has(id));
|
|
109
|
+
const recalledIDs = missingIDs.length ? await recalledMessageIDs(batch.roomId, missingIDs) : new Set<string>();
|
|
110
|
+
prunePendingAdmission(sessionID, batch.roomId, cutoff, (items) => render(batch, entry.name, roomKind, items),
|
|
111
|
+
(item) => !item.id || (!fresh.get(item.id)?.recalledAt && !recalledIDs.has(item.id)));
|
|
99
112
|
const unreadAll = batch.messages.filter((m) =>
|
|
100
113
|
m.createdAt > cutoff &&
|
|
101
114
|
(m.senderSessionID !== undefined ? m.senderSessionID !== sessionID : m.senderId !== (roomKind === "direct" ? sessionID : entry.name)),
|
|
@@ -103,9 +116,11 @@ export function createNotifier(deps: {
|
|
|
103
116
|
const unread = unreadAll.slice(-20).map((item) => ({ ...item, roomKind }));
|
|
104
117
|
const existing = pendingAdmission(sessionID, batch.roomId);
|
|
105
118
|
if (!unread.length && existing?.state !== "pending") return undefined;
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
119
|
+
// An admitted prompt only covers the items it carried; older unread items
|
|
120
|
+
// that surface later still need delivery, below its watermark or not.
|
|
121
|
+
const deliveredIDs = new Set(existing?.state === "admitted" ? existing.items.map((item) => item.id) : []);
|
|
122
|
+
const delta = existing?.state === "admitted"
|
|
123
|
+
? unread.filter((message) => message.createdAt > existing.maxTs || !deliveredIDs.has(message.id))
|
|
109
124
|
: unread;
|
|
110
125
|
const eligibleItems = existing?.state === "pending" ? existing.items : delta.slice(-20);
|
|
111
126
|
if (mentionOnly && !eligibleItems.some((message) => explicitlyAddresses(message, entry.name, sessionID, roomKind)) &&
|
|
@@ -115,14 +130,25 @@ export function createNotifier(deps: {
|
|
|
115
130
|
const endpoint = entry.protocol === "v2" ? "prompt" : "prompt_async";
|
|
116
131
|
const path = `${prefix ? `/${prefix}` : ""}/session/${encodeURIComponent(sessionID)}/${endpoint}`;
|
|
117
132
|
const url = base ? `${base.origin}${path}` : `opencode://session/${sessionID}/${endpoint}`;
|
|
118
|
-
if (existing?.state === "admitted" &&
|
|
133
|
+
if (existing?.state === "admitted" && !delta.length) {
|
|
119
134
|
if (existing.maxTs > 0) await deps.bumpQueued(batch.roomId, sessionID, existing.maxTs);
|
|
120
135
|
return { url, status: entry.protocol === "v2" ? 200 : 204 };
|
|
121
136
|
}
|
|
122
|
-
|
|
123
|
-
|
|
137
|
+
// Keep an undelivered admission intact when a later trigger carries only
|
|
138
|
+
// newer messages; the retry goes out first and the new delta follows.
|
|
139
|
+
const carried = existing?.state === "pending" ? existing.items : [];
|
|
140
|
+
const carriedIDs = new Set(carried.map((item) => item.id));
|
|
141
|
+
const merged = carried.length
|
|
142
|
+
? [...carried, ...delta.filter((item) => !carriedIDs.has(item.id)).slice(0, Math.max(0, 20 - carried.length))]
|
|
143
|
+
: delta;
|
|
144
|
+
// Only the oldest fitting prefix may move the watermark; anything beyond
|
|
145
|
+
// the line budget stays unread for the next sweep.
|
|
146
|
+
const deliverable = notificationPrefix(merged);
|
|
147
|
+
const displayDelta = withMessageIds(deliverable);
|
|
148
|
+
const { prompt, capped } = render(batch, entry.name, roomKind, displayDelta);
|
|
149
|
+
const deltaTs = deliverable.reduce((max, m) => Math.max(max, m.createdAt), 0);
|
|
124
150
|
const admission = getOrCreatePendingAdmission(
|
|
125
|
-
sessionID, batch.roomId,
|
|
151
|
+
sessionID, batch.roomId, displayDelta, prompt, deltaTs, capped,
|
|
126
152
|
);
|
|
127
153
|
if (admission.state === "admitted" && deltaTs <= admission.maxTs) {
|
|
128
154
|
await deps.bumpQueued(batch.roomId, sessionID, admission.maxTs);
|
package/src/runtime/v2-plugin.ts
CHANGED
|
@@ -174,7 +174,7 @@ export function roomSchema() {
|
|
|
174
174
|
roomId: z.string().optional(),
|
|
175
175
|
resourceId: z.string().optional(),
|
|
176
176
|
filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
|
|
177
|
-
text: z.string().max(
|
|
177
|
+
text: z.string().max(5000).optional(),
|
|
178
178
|
isQuestion: z.boolean().optional(),
|
|
179
179
|
announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
|
|
180
180
|
content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type RoleRoom = {
|
|
2
|
+
ownerId: string;
|
|
3
|
+
ownerMembershipID?: string;
|
|
4
|
+
adminIds?: string[];
|
|
5
|
+
adminMembershipIDs?: string[];
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
export type RoleEntry = {
|
|
9
|
+
name?: string | null;
|
|
10
|
+
protocol?: string | null;
|
|
11
|
+
host?: string | null;
|
|
12
|
+
receiverOwnerID?: string | null;
|
|
13
|
+
membershipID?: string | null;
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// Agents carry a protocol (v1/v2), a host, or a receiver binding; only a person may
|
|
17
|
+
// own a room, so any of those fields marks an entry that must never be promoted.
|
|
18
|
+
export function isUser(entry: RoleEntry | undefined | null): boolean {
|
|
19
|
+
return Boolean(entry?.name) && !entry!.protocol && !entry!.host && !entry!.receiverOwnerID;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// The owner is a person bound to a server-issued membership. The display name is
|
|
23
|
+
// only for presentation: a new session that reuses the name must not inherit the room.
|
|
24
|
+
export function isOwnerEntry(room: RoleRoom, entry: RoleEntry | null | undefined): boolean {
|
|
25
|
+
return isUser(entry) && entry!.name === room.ownerId &&
|
|
26
|
+
(!room.ownerMembershipID || entry!.membershipID === room.ownerMembershipID);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function isRoomAdmin(room: RoleRoom, entry: RoleEntry | null | undefined): boolean {
|
|
30
|
+
if (isOwnerEntry(room, entry)) return true;
|
|
31
|
+
if (!isUser(entry) || !(room.adminIds ?? []).includes(entry!.name!)) return false;
|
|
32
|
+
if (!room.adminMembershipIDs?.length) return true;
|
|
33
|
+
return !entry!.membershipID || room.adminMembershipIDs.includes(entry!.membershipID);
|
|
34
|
+
}
|