@alexsun-top/opencode-chat-room 0.2.0 → 0.2.2
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 +23 -2
- package/README.md +22 -13
- package/README.zh-CN.md +20 -13
- package/cli.ts +26 -1
- package/package.json +5 -1
- package/plugin.ts +111 -135
- package/server/chat-server.ts +48 -328
- package/server/chat.html +14 -6
- package/server/history-route.ts +25 -0
- package/server/inbox.ts +9 -0
- package/server/wake.ts +91 -0
- package/src/background.ts +108 -0
- package/src/center-client.ts +8 -2
- package/src/center-inbox.ts +105 -16
- package/src/mentions.ts +8 -0
- package/src/plugin-notifications.ts +23 -3
- package/src/queue-transport.ts +11 -3
- package/src/queue.ts +22 -57
- package/src/receiver-owner.ts +37 -0
- package/src/receiver-state.ts +92 -0
- package/src/room-service.ts +2 -4
- package/src/session-delivery.ts +51 -0
- package/src/sqlite-state.ts +265 -0
- package/src/store.ts +25 -138
- package/src/v2-plugin.ts +19 -32
- package/src/v2-receiver.ts +109 -0
- package/src/watch.ts +355 -0
package/server/chat-server.ts
CHANGED
|
@@ -1,35 +1,22 @@
|
|
|
1
1
|
// ponytail: central chat-room server. Single HTTP service holding the
|
|
2
|
-
// authoritative
|
|
2
|
+
// authoritative SQLite room database; plugins (central mode) talk to it
|
|
3
3
|
// via CHAT_ROOM_SERVER_URL. Optional bearer token (CHAT_ROOM_SERVER_TOKEN).
|
|
4
4
|
import { promises as fs } from "node:fs";
|
|
5
5
|
import path from "node:path";
|
|
6
|
-
import os from "node:os";
|
|
7
6
|
import RoomService, {
|
|
8
7
|
RoomError,
|
|
9
8
|
type Message,
|
|
10
9
|
type Room,
|
|
11
10
|
} from "../src/room-service";
|
|
12
|
-
import {
|
|
13
|
-
authHeader,
|
|
14
|
-
enqueue,
|
|
15
|
-
formatServeWakePrompt,
|
|
16
|
-
formatNotificationLines,
|
|
17
|
-
loadRegistry,
|
|
18
|
-
loadRooms,
|
|
19
|
-
saveRegistry,
|
|
20
|
-
saveRooms,
|
|
21
|
-
type RegistryEntry,
|
|
22
|
-
} from "../src/store";
|
|
11
|
+
import { readState, writeState, type Registry, type RegistryEntry } from "../src/store";
|
|
23
12
|
import {
|
|
24
13
|
admissionMatches,
|
|
25
14
|
clearPendingAdmission,
|
|
26
|
-
getOrCreatePendingAdmission,
|
|
27
|
-
markPendingAdmissionAdmitted,
|
|
28
|
-
pendingAdmission,
|
|
29
|
-
rejectPendingAdmission,
|
|
30
|
-
type QueueBody,
|
|
31
|
-
type QueueItem,
|
|
32
15
|
} from "../src/queue";
|
|
16
|
+
import { readInbox } from "./inbox";
|
|
17
|
+
import { isReceiverOwnerID } from "../src/receiver-owner";
|
|
18
|
+
import { claimWake, touchActive, wakeMentionedSessions } from "./wake";
|
|
19
|
+
import { historyRoute } from "./history-route";
|
|
33
20
|
|
|
34
21
|
function parsePort(value: string): number {
|
|
35
22
|
const port = Number(value);
|
|
@@ -54,214 +41,6 @@ const token = process.env.CHAT_ROOM_SERVER_TOKEN;
|
|
|
54
41
|
// 不是对 opencode 存在的假设
|
|
55
42
|
const serveWakeUrl = process.env.CHAT_ROOM_WAKE_SERVE_URL ?? "";
|
|
56
43
|
|
|
57
|
-
// ponytail: cross-process wake dedupe — multiple opencode windows all run the
|
|
58
|
-
// 10s wake sweep, and their per-process spawn windows don't see each other;
|
|
59
|
-
// the server claims the wake atomically so only one window spawns per session
|
|
60
|
-
// (generic coordination, no opencode assumption)
|
|
61
|
-
const wakeClaims = new Map<string, number>();
|
|
62
|
-
const WAKE_CLAIM_MS = 30 * 1000;
|
|
63
|
-
|
|
64
|
-
function claimWake(sessionID: string): boolean {
|
|
65
|
-
const now = Date.now();
|
|
66
|
-
const last = wakeClaims.get(sessionID) ?? 0;
|
|
67
|
-
if (now - last < WAKE_CLAIM_MS) {
|
|
68
|
-
return false;
|
|
69
|
-
}
|
|
70
|
-
wakeClaims.set(sessionID, now);
|
|
71
|
-
return true;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
// ponytail: 活跃心跳(内存)——任何活跃操作(inbox/read/send/join)都会刷
|
|
75
|
-
// 新;近 2 分钟活跃的会话由插件 queue 推送处理,服务器绝不 serve 双唤起。
|
|
76
|
-
// 内存态:服务器重启后短暂视为未活跃(可接受——重启场景罕见)
|
|
77
|
-
const activeSessions = new Map<string, number>();
|
|
78
|
-
const WAKE_INACTIVE_MS = 2 * 60 * 1000;
|
|
79
|
-
|
|
80
|
-
function touchActive(sessionID: string): void {
|
|
81
|
-
if (sessionID) {
|
|
82
|
-
activeSessions.set(sessionID, Date.now());
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
// ponytail: 服务器消息触发唤起——只有 @ 点名了成员的消息才会唤起(用户
|
|
87
|
-
// 核心需求)。仅唤起本机(host === 服务器主机名)的已退出 opencode 成员:
|
|
88
|
-
// 服务器的 serve 只能恢复本机 session,异机 session 由该机插件定时器兜底。
|
|
89
|
-
// 水位在唤起成功后推进(prompt 已带消息内容——agent 无需 poll 到它,
|
|
90
|
-
// 也不会因先推进而在唤起失败时丢消息)。
|
|
91
|
-
async function wakeMentionedSessions(
|
|
92
|
-
roomId: string,
|
|
93
|
-
roomName: string,
|
|
94
|
-
text: string,
|
|
95
|
-
senderSessionID: string,
|
|
96
|
-
triggeringMessage: Message,
|
|
97
|
-
): Promise<void> {
|
|
98
|
-
if (!serveWakeUrl) {
|
|
99
|
-
return;
|
|
100
|
-
}
|
|
101
|
-
const mentions = new Set<string>();
|
|
102
|
-
for (const m of text.matchAll(/<at>@([^<]+)<\/at>/g)) {
|
|
103
|
-
mentions.add(m[1]!);
|
|
104
|
-
}
|
|
105
|
-
for (const m of text.matchAll(/@([\p{L}\p{N}_]+)/gu)) {
|
|
106
|
-
// ponytail: mid-word 守卫(orc-1)——email/URL 里的 @token 不算提及。
|
|
107
|
-
// 用 ASCII 词字符(与客户端 picker 的 ASCII_WORD 一致,orc-2 #5):
|
|
108
|
-
// 中文前缀(你好@小明)正常触发,dev@bob 不触发
|
|
109
|
-
const at = m.index ?? 0;
|
|
110
|
-
if (at > 0 && /[A-Za-z0-9_]/.test(text[at - 1] ?? "")) continue;
|
|
111
|
-
mentions.add(m[1]!);
|
|
112
|
-
}
|
|
113
|
-
if (mentions.size === 0) {
|
|
114
|
-
return; // 未 @ 任何人——不唤起(核心需求)
|
|
115
|
-
}
|
|
116
|
-
const reg = await enqueue(async () => {
|
|
117
|
-
const r = await loadRegistry();
|
|
118
|
-
return r[roomId] ?? {};
|
|
119
|
-
});
|
|
120
|
-
const now = Date.now();
|
|
121
|
-
for (const [sid, entry] of Object.entries(reg)) {
|
|
122
|
-
if (
|
|
123
|
-
sid === senderSessionID ||
|
|
124
|
-
!mentions.has(entry.name) || // 只唤起被 @ 点名的人
|
|
125
|
-
entry.host !== os.hostname() || // 只唤起本机 session(serve 只能恢复本机)
|
|
126
|
-
(activeSessions.get(sid) ?? 0) > now - WAKE_INACTIVE_MS || // 活跃中——插件推送处理
|
|
127
|
-
triggeringMessage.createdAt <= (entry.lastReadTs ?? 0) ||
|
|
128
|
-
triggeringMessage.createdAt <= (entry.lastQueuedTs ?? 0)
|
|
129
|
-
) {
|
|
130
|
-
continue;
|
|
131
|
-
}
|
|
132
|
-
if (!claimWake(sid)) {
|
|
133
|
-
continue; // 30s 窗口内已唤起过
|
|
134
|
-
}
|
|
135
|
-
void (async () => {
|
|
136
|
-
try {
|
|
137
|
-
// orc-3 #2——带该 session 的全部待通知消息(含更早的),队列游标
|
|
138
|
-
// 推进到 maxTs;lastReadTs 保留给 poll,避免未读消息被跳过
|
|
139
|
-
const inbox = await readInbox(sid, roomId, true);
|
|
140
|
-
const currentEntry = await enqueue(async () => {
|
|
141
|
-
const r = await loadRegistry();
|
|
142
|
-
return r[roomId]?.[sid];
|
|
143
|
-
});
|
|
144
|
-
if (!currentEntry || !inbox.member) {
|
|
145
|
-
return;
|
|
146
|
-
}
|
|
147
|
-
const queuedTs = Math.max(
|
|
148
|
-
currentEntry.lastQueuedTs ?? 0,
|
|
149
|
-
inbox.queuedTs[roomId] ?? 0,
|
|
150
|
-
);
|
|
151
|
-
if (
|
|
152
|
-
triggeringMessage.createdAt <= (currentEntry.lastReadTs ?? 0) ||
|
|
153
|
-
triggeringMessage.createdAt <= queuedTs
|
|
154
|
-
) {
|
|
155
|
-
return;
|
|
156
|
-
}
|
|
157
|
-
const queuedItems = inbox.items.filter(
|
|
158
|
-
(item) => item.createdAt > queuedTs,
|
|
159
|
-
);
|
|
160
|
-
const triggerItem: InboxItem = {
|
|
161
|
-
id: triggeringMessage.id,
|
|
162
|
-
roomId,
|
|
163
|
-
roomName,
|
|
164
|
-
senderId: triggeringMessage.senderId,
|
|
165
|
-
text: triggeringMessage.text,
|
|
166
|
-
createdAt: triggeringMessage.createdAt,
|
|
167
|
-
};
|
|
168
|
-
const items = queuedItems.some((item) => item.id === triggerItem.id)
|
|
169
|
-
? queuedItems
|
|
170
|
-
: [...queuedItems, triggerItem].sort(
|
|
171
|
-
(a, b) => a.createdAt - b.createdAt,
|
|
172
|
-
);
|
|
173
|
-
const currentMaxTs = items.reduce(
|
|
174
|
-
(mx, it) => Math.max(mx, it.createdAt),
|
|
175
|
-
0,
|
|
176
|
-
);
|
|
177
|
-
const existing = pendingAdmission(sid, roomId);
|
|
178
|
-
const deltaItems =
|
|
179
|
-
existing?.state === "admitted" && currentMaxTs > existing.maxTs
|
|
180
|
-
? items.filter((item) => item.createdAt > existing.maxTs)
|
|
181
|
-
: items;
|
|
182
|
-
const confirmQueued = async (ts: number): Promise<boolean> =>
|
|
183
|
-
enqueue(async () => {
|
|
184
|
-
const r = await loadRegistry();
|
|
185
|
-
const e = r[roomId]?.[sid];
|
|
186
|
-
if (!e) {
|
|
187
|
-
return false;
|
|
188
|
-
}
|
|
189
|
-
e.lastQueuedTs = Math.max(e.lastQueuedTs ?? 0, ts);
|
|
190
|
-
await saveRegistry(r);
|
|
191
|
-
return true;
|
|
192
|
-
});
|
|
193
|
-
if (
|
|
194
|
-
existing?.state === "admitted" &&
|
|
195
|
-
(currentMaxTs <= existing.maxTs || deltaItems.length === 0)
|
|
196
|
-
) {
|
|
197
|
-
if (existing.maxTs > 0 && (await confirmQueued(existing.maxTs))) {
|
|
198
|
-
clearPendingAdmission(sid, roomId, existing.maxTs);
|
|
199
|
-
}
|
|
200
|
-
return;
|
|
201
|
-
}
|
|
202
|
-
const { lines, capped } = formatNotificationLines(deltaItems);
|
|
203
|
-
const prompt = formatServeWakePrompt(roomName, lines);
|
|
204
|
-
const maxTs = deltaItems.reduce(
|
|
205
|
-
(mx, it) => Math.max(mx, it.createdAt),
|
|
206
|
-
0,
|
|
207
|
-
);
|
|
208
|
-
const admissionItems: QueueItem[] = deltaItems;
|
|
209
|
-
const admission = getOrCreatePendingAdmission(
|
|
210
|
-
sid,
|
|
211
|
-
roomId,
|
|
212
|
-
admissionItems,
|
|
213
|
-
prompt,
|
|
214
|
-
maxTs,
|
|
215
|
-
capped,
|
|
216
|
-
);
|
|
217
|
-
const body: QueueBody = {
|
|
218
|
-
id: admission.id,
|
|
219
|
-
prompt: { text: admission.prompt },
|
|
220
|
-
delivery: "queue",
|
|
221
|
-
resume: true,
|
|
222
|
-
};
|
|
223
|
-
if (admission.state === "admitted" && maxTs <= admission.maxTs) {
|
|
224
|
-
if (admission.maxTs > 0 && (await confirmQueued(admission.maxTs))) {
|
|
225
|
-
clearPendingAdmission(sid, roomId, admission.maxTs);
|
|
226
|
-
}
|
|
227
|
-
return;
|
|
228
|
-
}
|
|
229
|
-
const directory =
|
|
230
|
-
(entry as RegistryEntry & { directory?: string }).directory ??
|
|
231
|
-
process.env.OPENCODE_DIRECTORY;
|
|
232
|
-
const auth = authHeader();
|
|
233
|
-
const res = await fetch(
|
|
234
|
-
`${serveWakeUrl.replace(/\/+$/, "")}/api/session/${encodeURIComponent(sid)}/prompt`,
|
|
235
|
-
{
|
|
236
|
-
method: "POST",
|
|
237
|
-
headers: {
|
|
238
|
-
"Content-Type": "application/json",
|
|
239
|
-
...(auth ? { Authorization: auth } : {}),
|
|
240
|
-
...(directory
|
|
241
|
-
? { "x-opencode-directory": encodeURIComponent(directory) }
|
|
242
|
-
: {}),
|
|
243
|
-
},
|
|
244
|
-
body: JSON.stringify(body),
|
|
245
|
-
signal: AbortSignal.timeout(10_000),
|
|
246
|
-
},
|
|
247
|
-
);
|
|
248
|
-
const data = await res.json().catch(() => undefined);
|
|
249
|
-
if (res.status >= 200 && res.status < 300 && admissionMatches(data, body, sid)) {
|
|
250
|
-
markPendingAdmissionAdmitted(sid, roomId, admission.id);
|
|
251
|
-
touchActive(sid);
|
|
252
|
-
if (admission.maxTs > 0 && (await confirmQueued(admission.maxTs))) {
|
|
253
|
-
clearPendingAdmission(sid, roomId, admission.maxTs);
|
|
254
|
-
}
|
|
255
|
-
} else if (res.status !== 404) {
|
|
256
|
-
rejectPendingAdmission(sid, roomId, admission.id);
|
|
257
|
-
}
|
|
258
|
-
} catch {
|
|
259
|
-
// serve 不可达——静默,插件 10s 定时器兜底
|
|
260
|
-
}
|
|
261
|
-
})();
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
44
|
const json = (body: unknown, status = 200) =>
|
|
266
45
|
new Response(JSON.stringify(body), {
|
|
267
46
|
status,
|
|
@@ -277,90 +56,17 @@ const serializeRoom = (r: Room) => ({
|
|
|
277
56
|
messages: r.messages.map(({ senderSessionID: _senderSessionID, ...message }) => message),
|
|
278
57
|
});
|
|
279
58
|
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
): Promise<T> {
|
|
283
|
-
return enqueue(async () => {
|
|
284
|
-
const svc = new RoomService();
|
|
285
|
-
svc.hydrate(await loadRooms());
|
|
286
|
-
const result = await fn(svc);
|
|
287
|
-
await saveRooms(svc);
|
|
288
|
-
return result;
|
|
289
|
-
});
|
|
59
|
+
function mutate<T>(fn: (svc: RoomService, registry: Registry) => T): Promise<T> {
|
|
60
|
+
return writeState(fn);
|
|
290
61
|
}
|
|
291
62
|
|
|
292
|
-
|
|
293
|
-
return
|
|
294
|
-
const svc = new RoomService();
|
|
295
|
-
svc.hydrate(await loadRooms());
|
|
296
|
-
return fn(svc);
|
|
297
|
-
});
|
|
63
|
+
function read<T>(fn: (svc: RoomService) => T): Promise<T> {
|
|
64
|
+
return readState(fn);
|
|
298
65
|
}
|
|
299
66
|
|
|
300
|
-
type InboxItem = {
|
|
301
|
-
id: string;
|
|
302
|
-
roomId: string;
|
|
303
|
-
roomName: string;
|
|
304
|
-
senderId: string;
|
|
305
|
-
text: string;
|
|
306
|
-
createdAt: number;
|
|
307
|
-
};
|
|
308
|
-
type InboxResult = {
|
|
309
|
-
member: boolean;
|
|
310
|
-
items: InboxItem[];
|
|
311
|
-
queuedTs: Record<string, number>;
|
|
312
|
-
};
|
|
313
|
-
|
|
314
67
|
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
315
68
|
|
|
316
|
-
//
|
|
317
|
-
async function readInbox(
|
|
318
|
-
sessionID: string,
|
|
319
|
-
roomFilter: string | null,
|
|
320
|
-
excludeSelf: boolean,
|
|
321
|
-
): Promise<InboxResult> {
|
|
322
|
-
// 注意:这里绝不 touchActive——插件 10s 扫描也会调 inbox(把已退出
|
|
323
|
-
// session 误标活跃会让消息触发唤起失效)
|
|
324
|
-
return read(async (svc) => {
|
|
325
|
-
const reg = await loadRegistry();
|
|
326
|
-
const out: InboxItem[] = [];
|
|
327
|
-
const queuedTs: Record<string, number> = Object.create(null);
|
|
328
|
-
let member = false;
|
|
329
|
-
for (const room of svc.listRooms()) {
|
|
330
|
-
if (roomFilter && room.id !== roomFilter) {
|
|
331
|
-
continue;
|
|
332
|
-
}
|
|
333
|
-
const entry = reg[room.id]?.[sessionID];
|
|
334
|
-
if (!entry) {
|
|
335
|
-
continue;
|
|
336
|
-
}
|
|
337
|
-
member = true;
|
|
338
|
-
queuedTs[room.id] = entry.lastQueuedTs ?? 0;
|
|
339
|
-
const lastRead = entry.lastReadTs ?? 0;
|
|
340
|
-
for (const m of room.messages) {
|
|
341
|
-
const isSelf =
|
|
342
|
-
m.senderSessionID !== undefined
|
|
343
|
-
? m.senderSessionID === sessionID
|
|
344
|
-
: m.senderId === entry.name;
|
|
345
|
-
if (
|
|
346
|
-
m.createdAt > lastRead &&
|
|
347
|
-
(!excludeSelf || !isSelf)
|
|
348
|
-
) {
|
|
349
|
-
out.push({
|
|
350
|
-
id: m.id,
|
|
351
|
-
roomId: room.id,
|
|
352
|
-
roomName: room.name,
|
|
353
|
-
senderId: m.senderId,
|
|
354
|
-
text: m.text,
|
|
355
|
-
createdAt: m.createdAt,
|
|
356
|
-
});
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
return { member, items: out, queuedTs };
|
|
361
|
-
});
|
|
362
|
-
}
|
|
363
|
-
|
|
69
|
+
// Database callbacks finish synchronously before any HTTP or long-poll wait.
|
|
364
70
|
async function handle(req: Request): Promise<Response> {
|
|
365
71
|
const url = new URL(req.url);
|
|
366
72
|
const p = url.pathname;
|
|
@@ -397,6 +103,8 @@ async function handle(req: Request): Promise<Response> {
|
|
|
397
103
|
return json({ error: "unauthorized" }, 401);
|
|
398
104
|
}
|
|
399
105
|
try {
|
|
106
|
+
const history = await historyRoute(url);
|
|
107
|
+
if (history) return history;
|
|
400
108
|
if (req.method === "GET" && p === "/rooms/summary") {
|
|
401
109
|
// ponytail: 轻量房间摘要(不含消息)——wakeSessions 每 10s 用它计算
|
|
402
110
|
// latest,避免下载全部房间历史(orc-1 #5)
|
|
@@ -409,12 +117,25 @@ async function handle(req: Request): Promise<Response> {
|
|
|
409
117
|
);
|
|
410
118
|
return json(rooms);
|
|
411
119
|
}
|
|
120
|
+
if (req.method === "GET" && p === "/receiver/memberships") {
|
|
121
|
+
const ownerID = url.searchParams.get("ownerID");
|
|
122
|
+
if (!isReceiverOwnerID(ownerID)) return json({ error: "invalid ownerID" }, 400);
|
|
123
|
+
const sessionIDs = await readState((_svc, registry) => {
|
|
124
|
+
return [...new Set(Object.values(registry).flatMap((entries) =>
|
|
125
|
+
Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id),
|
|
126
|
+
))];
|
|
127
|
+
});
|
|
128
|
+
return json({ sessionIDs });
|
|
129
|
+
}
|
|
412
130
|
if (req.method === "GET" && p === "/rooms") {
|
|
413
131
|
const rooms = await read((svc) => svc.listRooms());
|
|
414
132
|
return json(rooms.map(serializeRoom));
|
|
415
133
|
}
|
|
416
134
|
if (req.method === "POST" && p === "/rooms") {
|
|
417
135
|
const body = (await req.json()) as Record<string, string>;
|
|
136
|
+
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
137
|
+
return json({ error: "invalid receiver ownership" }, 400);
|
|
138
|
+
}
|
|
418
139
|
const name = body.name?.trim();
|
|
419
140
|
if (!name) {
|
|
420
141
|
return json({ error: "name is required" }, 400);
|
|
@@ -426,16 +147,17 @@ async function handle(req: Request): Promise<Response> {
|
|
|
426
147
|
if (owner.length > 64) {
|
|
427
148
|
return json({ error: "ownerId too long (max 64)" }, 400);
|
|
428
149
|
}
|
|
429
|
-
const room = await mutate(
|
|
150
|
+
const room = await mutate((svc, reg) => {
|
|
430
151
|
const created = svc.createRoom(name, owner);
|
|
431
152
|
if (body.sessionID) {
|
|
432
|
-
const reg = await loadRegistry();
|
|
433
153
|
const regRoom = (reg[created.id] =
|
|
434
154
|
reg[created.id] ?? Object.create(null) as Record<string, RegistryEntry>);
|
|
435
155
|
regRoom[body.sessionID] = {
|
|
436
156
|
// ponytail: central mode self-pulls the inbox; no cross-host URL
|
|
437
157
|
serverUrl: "",
|
|
438
158
|
apiPrefix: "/api",
|
|
159
|
+
...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
|
|
160
|
+
...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
|
|
439
161
|
name: owner,
|
|
440
162
|
directory: body.directory || undefined,
|
|
441
163
|
// ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
|
|
@@ -446,7 +168,6 @@ async function handle(req: Request): Promise<Response> {
|
|
|
446
168
|
),
|
|
447
169
|
lastQueuedTs: 0,
|
|
448
170
|
};
|
|
449
|
-
await saveRegistry(reg);
|
|
450
171
|
}
|
|
451
172
|
return created;
|
|
452
173
|
});
|
|
@@ -492,20 +213,18 @@ async function handle(req: Request): Promise<Response> {
|
|
|
492
213
|
) {
|
|
493
214
|
return json({ error: "roomId/sessionID/finite ts are required" }, 400);
|
|
494
215
|
}
|
|
495
|
-
const updated = await
|
|
496
|
-
const reg = await loadRegistry();
|
|
216
|
+
const updated = await writeState((_svc, reg) => {
|
|
497
217
|
const entry = reg[roomId]?.[sessionID];
|
|
498
218
|
if (!entry) {
|
|
499
219
|
return false;
|
|
500
220
|
}
|
|
501
221
|
entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
|
|
502
|
-
await saveRegistry(reg);
|
|
503
|
-
clearPendingAdmission(sessionID, roomId, ts);
|
|
504
222
|
return true;
|
|
505
223
|
});
|
|
506
224
|
if (!updated) {
|
|
507
225
|
return json({ error: "registry entry not found" }, 404);
|
|
508
226
|
}
|
|
227
|
+
clearPendingAdmission(sessionID, roomId, ts);
|
|
509
228
|
touchActive(sessionID); // poll 推进 = 活跃
|
|
510
229
|
return json({ ok: true });
|
|
511
230
|
}
|
|
@@ -523,20 +242,18 @@ async function handle(req: Request): Promise<Response> {
|
|
|
523
242
|
) {
|
|
524
243
|
return json({ error: "roomId/sessionID/finite ts are required" }, 400);
|
|
525
244
|
}
|
|
526
|
-
const updated = await
|
|
527
|
-
const reg = await loadRegistry();
|
|
245
|
+
const updated = await writeState((_svc, reg) => {
|
|
528
246
|
const entry = reg[roomId]?.[sessionID];
|
|
529
247
|
if (!entry) {
|
|
530
248
|
return false;
|
|
531
249
|
}
|
|
532
250
|
entry.lastQueuedTs = Math.max(entry.lastQueuedTs ?? 0, ts);
|
|
533
|
-
await saveRegistry(reg);
|
|
534
|
-
clearPendingAdmission(sessionID, roomId, ts);
|
|
535
251
|
return true;
|
|
536
252
|
});
|
|
537
253
|
if (!updated) {
|
|
538
254
|
return json({ error: "registry entry not found" }, 404);
|
|
539
255
|
}
|
|
256
|
+
clearPendingAdmission(sessionID, roomId, ts);
|
|
540
257
|
touchActive(sessionID);
|
|
541
258
|
return json({ ok: true });
|
|
542
259
|
}
|
|
@@ -552,7 +269,7 @@ async function handle(req: Request): Promise<Response> {
|
|
|
552
269
|
// server only arbitrates, it never spawns anything itself
|
|
553
270
|
const body = (await req.json()) as Record<string, unknown>;
|
|
554
271
|
const sessionID = String(body.sessionID ?? "");
|
|
555
|
-
const ok =
|
|
272
|
+
const ok = claimWake(sessionID);
|
|
556
273
|
return json({ ok });
|
|
557
274
|
}
|
|
558
275
|
const m = p.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
|
|
@@ -561,6 +278,9 @@ async function handle(req: Request): Promise<Response> {
|
|
|
561
278
|
const body = (await req.json()) as Record<string, string>;
|
|
562
279
|
const sessionID = body.sessionID ?? "";
|
|
563
280
|
if (req.method === "POST" && m[2] === "join") {
|
|
281
|
+
if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
|
|
282
|
+
return json({ error: "invalid receiver ownership" }, 400);
|
|
283
|
+
}
|
|
564
284
|
// ponytail: F4/F5 — names must be non-empty, and re-joining under a
|
|
565
285
|
// new name must retire the old participant (no ghost members)
|
|
566
286
|
const id = (body.participantId ?? "").trim();
|
|
@@ -574,8 +294,7 @@ async function handle(req: Request): Promise<Response> {
|
|
|
574
294
|
if (id.length > 64 || name.length > 64) {
|
|
575
295
|
return json({ error: "name too long (max 64)" }, 400);
|
|
576
296
|
}
|
|
577
|
-
const room = await mutate(
|
|
578
|
-
const reg = await loadRegistry();
|
|
297
|
+
const room = await mutate((svc, reg) => {
|
|
579
298
|
const regRoom = (reg[roomId] =
|
|
580
299
|
reg[roomId] ?? Object.create(null) as Record<string, RegistryEntry>);
|
|
581
300
|
// retire the participant this session previously held, if renamed
|
|
@@ -602,7 +321,6 @@ async function handle(req: Request): Promise<Response> {
|
|
|
602
321
|
}
|
|
603
322
|
}
|
|
604
323
|
svc.joinRoom(roomId, { id, name });
|
|
605
|
-
touchActive(sessionID); // join = 活跃
|
|
606
324
|
if (!already) {
|
|
607
325
|
svc.addEvent(roomId, `${name} joined the room`);
|
|
608
326
|
}
|
|
@@ -614,6 +332,9 @@ async function handle(req: Request): Promise<Response> {
|
|
|
614
332
|
// would be silently dropped); a first join starts at join time.
|
|
615
333
|
serverUrl: "",
|
|
616
334
|
apiPrefix: "/api",
|
|
335
|
+
...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
|
|
336
|
+
...(prevEntry?.receiverOwnerID ? { receiverOwnerID: prevEntry.receiverOwnerID } : {}),
|
|
337
|
+
...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
|
|
617
338
|
name,
|
|
618
339
|
directory: body.directory || undefined,
|
|
619
340
|
// ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
|
|
@@ -623,14 +344,13 @@ async function handle(req: Request): Promise<Response> {
|
|
|
623
344
|
regRoom[sessionID]?.lastReadTs ??
|
|
624
345
|
Math.max(Date.now(), latestMessageTs),
|
|
625
346
|
};
|
|
626
|
-
await saveRegistry(reg);
|
|
627
347
|
return svc.getRoom(roomId);
|
|
628
348
|
});
|
|
349
|
+
touchActive(sessionID); // join = active
|
|
629
350
|
return json(serializeRoom(room), 201);
|
|
630
351
|
}
|
|
631
352
|
if (req.method === "POST" && m[2] === "leave") {
|
|
632
|
-
await mutate(
|
|
633
|
-
const reg = await loadRegistry();
|
|
353
|
+
await mutate((svc, reg) => {
|
|
634
354
|
const entry = reg[roomId]?.[sessionID];
|
|
635
355
|
const participantId = entry?.name ?? sessionID;
|
|
636
356
|
// ponytail: orc-2 #2——共享名守卫:还有别的 session 持有同名时,
|
|
@@ -648,7 +368,6 @@ async function handle(req: Request): Promise<Response> {
|
|
|
648
368
|
delete reg[roomId];
|
|
649
369
|
}
|
|
650
370
|
}
|
|
651
|
-
await saveRegistry(reg);
|
|
652
371
|
});
|
|
653
372
|
return json({ ok: true });
|
|
654
373
|
}
|
|
@@ -661,8 +380,7 @@ async function handle(req: Request): Promise<Response> {
|
|
|
661
380
|
if (text.length > 2000) {
|
|
662
381
|
return json({ error: "text too long (max 2000)" }, 400);
|
|
663
382
|
}
|
|
664
|
-
const room = await mutate(
|
|
665
|
-
const reg = await loadRegistry();
|
|
383
|
+
const room = await mutate((svc, reg) => {
|
|
666
384
|
const sender = reg[roomId]?.[sessionID]?.name ?? sessionID;
|
|
667
385
|
svc.sendMessage(roomId, sender, text, sessionID);
|
|
668
386
|
return svc.getRoom(roomId);
|
|
@@ -672,6 +390,7 @@ async function handle(req: Request): Promise<Response> {
|
|
|
672
390
|
const sent = room.messages.at(-1);
|
|
673
391
|
if (sent) {
|
|
674
392
|
void wakeMentionedSessions(
|
|
393
|
+
serveWakeUrl,
|
|
675
394
|
roomId,
|
|
676
395
|
room.name,
|
|
677
396
|
text,
|
|
@@ -695,14 +414,15 @@ async function handle(req: Request): Promise<Response> {
|
|
|
695
414
|
// plugin find which sessions have unread messages without polling every
|
|
696
415
|
// session's inbox; host is included for the @-wake ownership gate
|
|
697
416
|
const roomId = decodeURIComponent(r[1]!);
|
|
698
|
-
const reg = await
|
|
699
|
-
const registry = await loadRegistry();
|
|
417
|
+
const reg = await readState((_svc, registry) => {
|
|
700
418
|
const entries = registry[roomId] ?? {};
|
|
701
419
|
return Object.fromEntries(
|
|
702
420
|
Object.entries(entries).map(([sid, e]) => [
|
|
703
421
|
sid,
|
|
704
422
|
{
|
|
705
423
|
name: e.name,
|
|
424
|
+
protocol: e.protocol,
|
|
425
|
+
receiverOwnerID: e.receiverOwnerID,
|
|
706
426
|
lastReadTs: e.lastReadTs ?? 0,
|
|
707
427
|
lastQueuedTs: e.lastQueuedTs ?? 0,
|
|
708
428
|
host: e.host ?? "",
|
package/server/chat.html
CHANGED
|
@@ -722,14 +722,19 @@
|
|
|
722
722
|
const $ = (s) => document.querySelector(s);
|
|
723
723
|
|
|
724
724
|
/* ---------- 本地存储(隐私模式下 localStorage 可能抛错,回退到内存) ---------- */
|
|
725
|
-
const memStore =
|
|
725
|
+
const memStore = Object.create(null);
|
|
726
726
|
function lsGet(k) {
|
|
727
|
+
if (Object.prototype.hasOwnProperty.call(memStore, k)) return memStore[k];
|
|
727
728
|
try { return localStorage.getItem(k); }
|
|
728
|
-
catch { return
|
|
729
|
+
catch { return null; }
|
|
729
730
|
}
|
|
730
731
|
function lsSet(k, v) {
|
|
731
|
-
|
|
732
|
-
|
|
732
|
+
const value = v == null ? null : String(v);
|
|
733
|
+
try {
|
|
734
|
+
if (value == null) localStorage.removeItem(k);
|
|
735
|
+
else localStorage.setItem(k, value);
|
|
736
|
+
delete memStore[k];
|
|
737
|
+
} catch { memStore[k] = value; }
|
|
733
738
|
}
|
|
734
739
|
function newSessionID() {
|
|
735
740
|
const webCrypto = globalThis.crypto;
|
|
@@ -766,6 +771,10 @@
|
|
|
766
771
|
get locale() { return lsGet("chat.locale") || "en"; },
|
|
767
772
|
set locale(v) { lsSet("chat.locale", v || null); },
|
|
768
773
|
};
|
|
774
|
+
function saveToken(value) {
|
|
775
|
+
LS.token = String(value ?? "").trim();
|
|
776
|
+
return LS.token;
|
|
777
|
+
}
|
|
769
778
|
|
|
770
779
|
const I18N = {
|
|
771
780
|
en: {
|
|
@@ -2049,8 +2058,7 @@
|
|
|
2049
2058
|
const save = e.target.closest("[data-token-save]");
|
|
2050
2059
|
if (save) {
|
|
2051
2060
|
const input = document.getElementById(save.dataset.tokenSave);
|
|
2052
|
-
|
|
2053
|
-
input.value = LS.token;
|
|
2061
|
+
input.value = saveToken(input.value);
|
|
2054
2062
|
$("#inToken").value = LS.token;
|
|
2055
2063
|
$("#inTokenChat").value = LS.token;
|
|
2056
2064
|
flash(save, "saved");
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { readHistory, readState } from "../src/store";
|
|
2
|
+
|
|
3
|
+
export async function historyRoute(url: URL): Promise<Response | undefined> {
|
|
4
|
+
const match = url.pathname.match(/^\/rooms\/([^/]+)\/history$/);
|
|
5
|
+
if (!match) return undefined;
|
|
6
|
+
const roomID = decodeURIComponent(match[1]!);
|
|
7
|
+
const beforeText = url.searchParams.get("beforeSeq");
|
|
8
|
+
const before = beforeText === null ? undefined : Number(beforeText);
|
|
9
|
+
const excludeSessionID = url.searchParams.get("excludeSessionID");
|
|
10
|
+
const limitText = url.searchParams.get("limit");
|
|
11
|
+
const limit = limitText === null ? 100 : Number(limitText);
|
|
12
|
+
if (before !== undefined && (!Number.isSafeInteger(before) || before < 1) ||
|
|
13
|
+
!Number.isInteger(limit) || limit < 1 || limit > 200 ||
|
|
14
|
+
excludeSessionID !== null && (!excludeSessionID || excludeSessionID.length > 128)) {
|
|
15
|
+
return Response.json({ error: "invalid history cursor or limit" }, { status: 400 });
|
|
16
|
+
}
|
|
17
|
+
const access = await readState((service, registry) => ({
|
|
18
|
+
exists: service.listRooms().some((room) => room.id === roomID),
|
|
19
|
+
member: excludeSessionID ? registry[roomID]?.[excludeSessionID] : undefined,
|
|
20
|
+
}));
|
|
21
|
+
if (!access.exists || excludeSessionID && !access.member) return Response.json({ error: "room not found" }, { status: 404 });
|
|
22
|
+
const page = await readHistory(roomID, before, limit, access.member && excludeSessionID
|
|
23
|
+
? { sessionID: excludeSessionID, name: access.member.name } : undefined);
|
|
24
|
+
return Response.json({ ...page, messages: page.messages.map(({ senderSessionID: _sid, ...message }) => message) });
|
|
25
|
+
}
|
package/server/inbox.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { readInboxMessages } from "../src/store";
|
|
2
|
+
import type { Message } from "../src/room-service";
|
|
3
|
+
|
|
4
|
+
export type InboxItem = Pick<Message, "id" | "roomId" | "senderId" | "text" | "createdAt"> & { roomName: string };
|
|
5
|
+
export type InboxResult = { member: boolean; items: InboxItem[]; queuedTs: Record<string, number>; hasMore: boolean };
|
|
6
|
+
|
|
7
|
+
export async function readInbox(sessionID: string, roomFilter: string | null, excludeSelf: boolean): Promise<InboxResult> {
|
|
8
|
+
return readInboxMessages(sessionID, roomFilter, excludeSelf, excludeSelf ? 20 : 100);
|
|
9
|
+
}
|