@alexsun-top/opencode-chat-room 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -0
- package/README.zh-CN.md +121 -0
- package/cli.ts +5 -0
- package/index.ts +9 -0
- package/package.json +47 -0
- package/plugin.ts +487 -0
- package/server/chat-server.ts +554 -0
- package/server/chat.html +1856 -0
- package/src/center-client.ts +530 -0
- package/src/room-service.ts +169 -0
- package/src/store.ts +237 -0
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
// ponytail: central chat-room server. Single HTTP service holding the
|
|
2
|
+
// authoritative rooms.json/registry.json; plugins (central mode) talk to it
|
|
3
|
+
// via CHAT_ROOM_SERVER_URL. Optional bearer token (CHAT_ROOM_SERVER_TOKEN).
|
|
4
|
+
import { promises as fs } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import RoomService, { RoomError, type Room } from "../src/room-service";
|
|
8
|
+
import {
|
|
9
|
+
enqueue,
|
|
10
|
+
loadRegistry,
|
|
11
|
+
loadRooms,
|
|
12
|
+
saveRegistry,
|
|
13
|
+
saveRooms,
|
|
14
|
+
SERVE_WAKE_PROMPT,
|
|
15
|
+
type RegistryEntry,
|
|
16
|
+
} from "../src/store";
|
|
17
|
+
|
|
18
|
+
const port = Number(process.env.CHAT_ROOM_SERVER_PORT ?? 4399);
|
|
19
|
+
const token = process.env.CHAT_ROOM_SERVER_TOKEN;
|
|
20
|
+
|
|
21
|
+
// ponytail: 部署者显式配置的 serve 地址——消息到达时立即唤起被 @ 的已退出
|
|
22
|
+
// session(零轮询延迟);未配置则跳过(插件定时器兜底)。这是显式配置,
|
|
23
|
+
// 不是对 opencode 存在的假设
|
|
24
|
+
const serveWakeUrl = process.env.CHAT_ROOM_WAKE_SERVE_URL ?? "";
|
|
25
|
+
|
|
26
|
+
// ponytail: cross-process wake dedupe — multiple opencode windows all run the
|
|
27
|
+
// 10s wake sweep, and their per-process spawn windows don't see each other;
|
|
28
|
+
// the server claims the wake atomically so only one window spawns per session
|
|
29
|
+
// (generic coordination, no opencode assumption)
|
|
30
|
+
const wakeClaims = new Map<string, number>();
|
|
31
|
+
const WAKE_CLAIM_MS = 30 * 1000;
|
|
32
|
+
|
|
33
|
+
function claimWake(sessionID: string): boolean {
|
|
34
|
+
const now = Date.now();
|
|
35
|
+
const last = wakeClaims.get(sessionID) ?? 0;
|
|
36
|
+
if (now - last < WAKE_CLAIM_MS) {
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
wakeClaims.set(sessionID, now);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// ponytail: 活跃心跳(内存)——任何活跃操作(inbox/read/send/join)都会刷
|
|
44
|
+
// 新;近 2 分钟活跃的会话由插件 queue 推送处理,服务器绝不 serve 双唤起。
|
|
45
|
+
// 内存态:服务器重启后短暂视为未活跃(可接受——重启场景罕见)
|
|
46
|
+
const activeSessions = new Map<string, number>();
|
|
47
|
+
const WAKE_INACTIVE_MS = 2 * 60 * 1000;
|
|
48
|
+
|
|
49
|
+
function touchActive(sessionID: string): void {
|
|
50
|
+
if (sessionID) {
|
|
51
|
+
activeSessions.set(sessionID, Date.now());
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ponytail: 服务器消息触发唤起——只有 @ 点名了成员的消息才会唤起(用户
|
|
56
|
+
// 核心需求)。仅唤起本机(host === 服务器主机名)的已退出 opencode 成员:
|
|
57
|
+
// 服务器的 serve 只能恢复本机 session,异机 session 由该机插件定时器兜底。
|
|
58
|
+
// 水位在唤起成功后推进(prompt 已带消息内容——agent 无需 poll 到它,
|
|
59
|
+
// 也不会因先推进而在唤起失败时丢消息)。
|
|
60
|
+
async function wakeMentionedSessions(
|
|
61
|
+
roomId: string,
|
|
62
|
+
roomName: string,
|
|
63
|
+
senderName: string,
|
|
64
|
+
text: string,
|
|
65
|
+
senderSessionID: string,
|
|
66
|
+
messageTs: number,
|
|
67
|
+
): Promise<void> {
|
|
68
|
+
if (!serveWakeUrl) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
const mentions = new Set<string>();
|
|
72
|
+
for (const m of text.matchAll(/<at>@([^<]+)<\/at>/g)) {
|
|
73
|
+
mentions.add(m[1]!);
|
|
74
|
+
}
|
|
75
|
+
for (const m of text.matchAll(/@([\p{L}\p{N}_]+)/gu)) {
|
|
76
|
+
// ponytail: mid-word 守卫(orc-1)——email/URL 里的 @token 不算提及。
|
|
77
|
+
// 用 ASCII 词字符(与客户端 picker 的 ASCII_WORD 一致,orc-2 #5):
|
|
78
|
+
// 中文前缀(你好@小明)正常触发,dev@bob 不触发
|
|
79
|
+
const at = m.index ?? 0;
|
|
80
|
+
if (at > 0 && /[A-Za-z0-9_]/.test(text[at - 1] ?? "")) continue;
|
|
81
|
+
mentions.add(m[1]!);
|
|
82
|
+
}
|
|
83
|
+
if (mentions.size === 0) {
|
|
84
|
+
return; // 未 @ 任何人——不唤起(核心需求)
|
|
85
|
+
}
|
|
86
|
+
const reg = await enqueue(async () => {
|
|
87
|
+
const r = await loadRegistry();
|
|
88
|
+
return r[roomId] ?? {};
|
|
89
|
+
});
|
|
90
|
+
const now = Date.now();
|
|
91
|
+
for (const [sid, entry] of Object.entries(reg)) {
|
|
92
|
+
if (
|
|
93
|
+
sid === senderSessionID ||
|
|
94
|
+
!mentions.has(entry.name) || // 只唤起被 @ 点名的人
|
|
95
|
+
entry.host !== os.hostname() || // 只唤起本机 session(serve 只能恢复本机)
|
|
96
|
+
(activeSessions.get(sid) ?? 0) > now - WAKE_INACTIVE_MS // 活跃中——插件推送处理
|
|
97
|
+
) {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
if (!claimWake(sid)) {
|
|
101
|
+
continue; // 30s 窗口内已唤起过
|
|
102
|
+
}
|
|
103
|
+
void (async () => {
|
|
104
|
+
try {
|
|
105
|
+
// orc-3 #2——带该 session 的全部未读(含更早的),水位推进到
|
|
106
|
+
// maxTs;否则更早未读被标记已读但从未投递(插件 sweep 也会因
|
|
107
|
+
// 水位已推进而跳过——永久丢失)
|
|
108
|
+
const inbox = await readInbox(sid, roomId, true);
|
|
109
|
+
const older = inbox.items.filter((it) => it.createdAt < messageTs);
|
|
110
|
+
// prompt 附带触发消息内容——agent 无需 poll 也能精确回复
|
|
111
|
+
const prompt =
|
|
112
|
+
`${SERVE_WAKE_PROMPT}\n\n` +
|
|
113
|
+
`New message in room ${roomName} from ${senderName}: ${text}` +
|
|
114
|
+
(older.length
|
|
115
|
+
? `\n\n更早的未读消息:\n${older
|
|
116
|
+
.map((it) => `[${it.senderId}]: ${it.text}`)
|
|
117
|
+
.join("\n")}`
|
|
118
|
+
: "");
|
|
119
|
+
const res = await fetch(
|
|
120
|
+
`${serveWakeUrl.replace(/\/+$/, "")}/session/${sid}/message`,
|
|
121
|
+
{
|
|
122
|
+
method: "POST",
|
|
123
|
+
headers: { "Content-Type": "application/json" },
|
|
124
|
+
body: JSON.stringify({ parts: [{ type: "text", text: prompt }] }),
|
|
125
|
+
},
|
|
126
|
+
);
|
|
127
|
+
if (res.ok) {
|
|
128
|
+
// 唤起成功(serve 同步处理完)后推进水位——防循环唤起
|
|
129
|
+
const maxTs = Math.max(
|
|
130
|
+
messageTs,
|
|
131
|
+
...inbox.items.map((it) => it.createdAt),
|
|
132
|
+
);
|
|
133
|
+
await enqueue(async () => {
|
|
134
|
+
const r = await loadRegistry();
|
|
135
|
+
const e = r[roomId]?.[sid];
|
|
136
|
+
if (e) {
|
|
137
|
+
e.lastReadTs = Math.max(e.lastReadTs ?? 0, maxTs);
|
|
138
|
+
await saveRegistry(r);
|
|
139
|
+
}
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
} catch {
|
|
143
|
+
// serve 不可达——静默,插件 10s 定时器兜底
|
|
144
|
+
}
|
|
145
|
+
})();
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const json = (body: unknown, status = 200) =>
|
|
150
|
+
new Response(JSON.stringify(body), {
|
|
151
|
+
status,
|
|
152
|
+
headers: { "Content-Type": "application/json" },
|
|
153
|
+
});
|
|
154
|
+
|
|
155
|
+
const serializeRoom = (r: Room) => ({
|
|
156
|
+
id: r.id,
|
|
157
|
+
name: r.name,
|
|
158
|
+
ownerId: r.ownerId,
|
|
159
|
+
createdAt: r.createdAt,
|
|
160
|
+
participants: [...r.participants.values()],
|
|
161
|
+
messages: r.messages,
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
async function mutate<T>(
|
|
165
|
+
fn: (svc: RoomService) => T | Promise<T>,
|
|
166
|
+
): Promise<T> {
|
|
167
|
+
return enqueue(async () => {
|
|
168
|
+
const svc = new RoomService();
|
|
169
|
+
svc.hydrate(await loadRooms());
|
|
170
|
+
const result = await fn(svc);
|
|
171
|
+
await saveRooms(svc);
|
|
172
|
+
return result;
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async function read<T>(fn: (svc: RoomService) => T | Promise<T>): Promise<T> {
|
|
177
|
+
return enqueue(async () => {
|
|
178
|
+
const svc = new RoomService();
|
|
179
|
+
svc.hydrate(await loadRooms());
|
|
180
|
+
return fn(svc);
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
type InboxItem = {
|
|
185
|
+
id: string;
|
|
186
|
+
roomId: string;
|
|
187
|
+
roomName: string;
|
|
188
|
+
senderId: string;
|
|
189
|
+
text: string;
|
|
190
|
+
createdAt: number;
|
|
191
|
+
};
|
|
192
|
+
type InboxResult = { member: boolean; items: InboxItem[] };
|
|
193
|
+
|
|
194
|
+
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
195
|
+
|
|
196
|
+
// ponytail: short enqueue per check (writes are never blocked by a long poll)
|
|
197
|
+
async function readInbox(
|
|
198
|
+
sessionID: string,
|
|
199
|
+
roomFilter: string | null,
|
|
200
|
+
excludeSelf: boolean,
|
|
201
|
+
): Promise<InboxResult> {
|
|
202
|
+
// 注意:这里绝不 touchActive——插件 10s 扫描也会调 inbox(把已退出
|
|
203
|
+
// session 误标活跃会让消息触发唤起失效)
|
|
204
|
+
return read(async (svc) => {
|
|
205
|
+
const reg = await loadRegistry();
|
|
206
|
+
const out: InboxItem[] = [];
|
|
207
|
+
let member = false;
|
|
208
|
+
for (const room of svc.listRooms()) {
|
|
209
|
+
if (roomFilter && room.id !== roomFilter) {
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
const entry = reg[room.id]?.[sessionID];
|
|
213
|
+
if (!entry) {
|
|
214
|
+
continue;
|
|
215
|
+
}
|
|
216
|
+
member = true;
|
|
217
|
+
const lastRead = entry.lastReadTs ?? 0;
|
|
218
|
+
for (const m of room.messages) {
|
|
219
|
+
if (
|
|
220
|
+
m.createdAt > lastRead &&
|
|
221
|
+
(!excludeSelf || m.senderId !== entry.name)
|
|
222
|
+
) {
|
|
223
|
+
out.push({
|
|
224
|
+
id: m.id,
|
|
225
|
+
roomId: room.id,
|
|
226
|
+
roomName: room.name,
|
|
227
|
+
senderId: m.senderId,
|
|
228
|
+
text: m.text,
|
|
229
|
+
createdAt: m.createdAt,
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return { member, items: out };
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async function handle(req: Request): Promise<Response> {
|
|
239
|
+
const url = new URL(req.url);
|
|
240
|
+
const p = url.pathname;
|
|
241
|
+
if (req.method === "GET" && p === "/chat") {
|
|
242
|
+
// ponytail: the human-facing chat page; APIs stay token-gated, the page
|
|
243
|
+
// itself is a static shell
|
|
244
|
+
const html = await fs
|
|
245
|
+
.readFile(path.join(import.meta.dir, "chat.html"), "utf8")
|
|
246
|
+
.catch(() => null);
|
|
247
|
+
if (html === null) {
|
|
248
|
+
return json({ error: "chat page not found" }, 404);
|
|
249
|
+
}
|
|
250
|
+
return new Response(html, {
|
|
251
|
+
headers: {
|
|
252
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
253
|
+
// ponytail: never cache the page — the UI is iterated often and the
|
|
254
|
+
// server reads it fresh from disk on every request
|
|
255
|
+
"Cache-Control": "no-store",
|
|
256
|
+
},
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
// ponytail: F1 — reject non-JSON POSTs; a text/plain simple request from a
|
|
260
|
+
// malicious page would otherwise mutate rooms cross-origin (no preflight)
|
|
261
|
+
if (
|
|
262
|
+
req.method === "POST" &&
|
|
263
|
+
!req.headers.get("content-type")?.includes("application/json")
|
|
264
|
+
) {
|
|
265
|
+
return json({ error: "content-type must be application/json" }, 415);
|
|
266
|
+
}
|
|
267
|
+
if (token && req.headers.get("authorization") !== `Bearer ${token}`) {
|
|
268
|
+
return json({ error: "unauthorized" }, 401);
|
|
269
|
+
}
|
|
270
|
+
try {
|
|
271
|
+
if (req.method === "GET" && p === "/rooms/summary") {
|
|
272
|
+
// ponytail: 轻量房间摘要(不含消息)——wakeSessions 每 10s 用它计算
|
|
273
|
+
// latest,避免下载全部房间历史(orc-1 #5)
|
|
274
|
+
const rooms = await read((svc) =>
|
|
275
|
+
svc.listRooms().map((r) => ({
|
|
276
|
+
id: r.id,
|
|
277
|
+
name: r.name,
|
|
278
|
+
latestMsgTs: r.messages.at(-1)?.createdAt ?? 0,
|
|
279
|
+
})),
|
|
280
|
+
);
|
|
281
|
+
return json(rooms);
|
|
282
|
+
}
|
|
283
|
+
if (req.method === "GET" && p === "/rooms") {
|
|
284
|
+
const rooms = await read((svc) => svc.listRooms());
|
|
285
|
+
return json(rooms.map(serializeRoom));
|
|
286
|
+
}
|
|
287
|
+
if (req.method === "POST" && p === "/rooms") {
|
|
288
|
+
const body = (await req.json()) as Record<string, string>;
|
|
289
|
+
const name = body.name?.trim();
|
|
290
|
+
if (!name) {
|
|
291
|
+
return json({ error: "name is required" }, 400);
|
|
292
|
+
}
|
|
293
|
+
if (name.length > 64) {
|
|
294
|
+
return json({ error: "name too long (max 64)" }, 400);
|
|
295
|
+
}
|
|
296
|
+
const owner = (body.ownerId ?? "").trim() || "访客";
|
|
297
|
+
if (owner.length > 64) {
|
|
298
|
+
return json({ error: "ownerId too long (max 64)" }, 400);
|
|
299
|
+
}
|
|
300
|
+
const room = await mutate(async (svc) => {
|
|
301
|
+
const created = svc.createRoom(name, owner);
|
|
302
|
+
if (body.sessionID) {
|
|
303
|
+
const reg = await loadRegistry();
|
|
304
|
+
const regRoom = (reg[created.id] =
|
|
305
|
+
reg[created.id] ?? Object.create(null) as Record<string, RegistryEntry>);
|
|
306
|
+
regRoom[body.sessionID] = {
|
|
307
|
+
// ponytail: central mode self-pulls the inbox; no cross-host URL
|
|
308
|
+
serverUrl: "",
|
|
309
|
+
apiPrefix: "/api",
|
|
310
|
+
name: owner,
|
|
311
|
+
// ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
|
|
312
|
+
host: body.host ?? "",
|
|
313
|
+
lastReadTs: Date.now(),
|
|
314
|
+
};
|
|
315
|
+
await saveRegistry(reg);
|
|
316
|
+
}
|
|
317
|
+
return created;
|
|
318
|
+
});
|
|
319
|
+
return json(serializeRoom(room), 201);
|
|
320
|
+
}
|
|
321
|
+
if (req.method === "GET" && p === "/inbox") {
|
|
322
|
+
const sessionID = url.searchParams.get("sessionID") ?? "";
|
|
323
|
+
const roomFilter = url.searchParams.get("roomId");
|
|
324
|
+
// ponytail: poll includes the caller's own messages (echo), the
|
|
325
|
+
// notification self-pull excludes them — aligned with standalone poll
|
|
326
|
+
const excludeSelf = url.searchParams.get("excludeSelf") === "1";
|
|
327
|
+
// long-poll: wait up to `timeout` ms for the first new message
|
|
328
|
+
// instead of returning empty immediately (web chat + sub-agent
|
|
329
|
+
// watchers); empty responses only happen on timeout
|
|
330
|
+
const timeout = Math.min(
|
|
331
|
+
Math.max(Number(url.searchParams.get("timeout") ?? 0) || 0, 0),
|
|
332
|
+
30000,
|
|
333
|
+
);
|
|
334
|
+
const deadline = Date.now() + timeout;
|
|
335
|
+
let result = await readInbox(sessionID, roomFilter, excludeSelf);
|
|
336
|
+
while (result.items.length === 0 && Date.now() < deadline) {
|
|
337
|
+
// ponytail: 2s between disk scans (orc-1 #7) — 1s × 25 iterations
|
|
338
|
+
// doubles the file reads on shared-mount deployments
|
|
339
|
+
await sleep(2000);
|
|
340
|
+
result = await readInbox(sessionID, roomFilter, excludeSelf);
|
|
341
|
+
}
|
|
342
|
+
return json(result);
|
|
343
|
+
}
|
|
344
|
+
if (req.method === "POST" && p === "/read") {
|
|
345
|
+
// ponytail: trusted-client-only — any caller can advance any session's
|
|
346
|
+
// watermark (sessionIDs are unguessable UUIDs and never exposed);
|
|
347
|
+
// accepted as a limitation until real session auth exists
|
|
348
|
+
const body = (await req.json()) as Record<string, unknown>;
|
|
349
|
+
const ts = Number(body.ts ?? 0);
|
|
350
|
+
touchActive(String(body.sessionID ?? "")); // poll 推进 = 活跃
|
|
351
|
+
await enqueue(async () => {
|
|
352
|
+
const reg = await loadRegistry();
|
|
353
|
+
const entry = reg[String(body.roomId)]?.[String(body.sessionID)];
|
|
354
|
+
// ponytail: NaN would poison the watermark (all comparisons false)
|
|
355
|
+
if (entry && Number.isFinite(ts)) {
|
|
356
|
+
entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
|
|
357
|
+
await saveRegistry(reg);
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
return json({ ok: true });
|
|
361
|
+
}
|
|
362
|
+
if (req.method === "POST" && p === "/active") {
|
|
363
|
+
// ponytail: 活跃上报——插件对"进程内自推成功"的 session 调用(真实
|
|
364
|
+
// 活跃);服务器据此避免 serve 双唤起
|
|
365
|
+
const body = (await req.json()) as Record<string, unknown>;
|
|
366
|
+
touchActive(String(body.sessionID ?? ""));
|
|
367
|
+
return json({ ok: true });
|
|
368
|
+
}
|
|
369
|
+
if (req.method === "POST" && p === "/wake-claim") {
|
|
370
|
+
// ponytail: atomic cross-process wake dedupe (see claimWake) — the
|
|
371
|
+
// server only arbitrates, it never spawns anything itself
|
|
372
|
+
const body = (await req.json()) as Record<string, unknown>;
|
|
373
|
+
const sessionID = String(body.sessionID ?? "");
|
|
374
|
+
const ok = await enqueue(async () => claimWake(sessionID));
|
|
375
|
+
return json({ ok });
|
|
376
|
+
}
|
|
377
|
+
const m = p.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
|
|
378
|
+
if (m) {
|
|
379
|
+
const roomId = decodeURIComponent(m[1]!);
|
|
380
|
+
const body = (await req.json()) as Record<string, string>;
|
|
381
|
+
const sessionID = body.sessionID ?? "";
|
|
382
|
+
if (req.method === "POST" && m[2] === "join") {
|
|
383
|
+
// ponytail: F4/F5 — names must be non-empty, and re-joining under a
|
|
384
|
+
// new name must retire the old participant (no ghost members)
|
|
385
|
+
const id = (body.participantId ?? "").trim();
|
|
386
|
+
const name = (body.participantName ?? "").trim();
|
|
387
|
+
if (!id || !name || !sessionID) {
|
|
388
|
+
return json(
|
|
389
|
+
{ error: "participantId/participantName/sessionID are required" },
|
|
390
|
+
400,
|
|
391
|
+
);
|
|
392
|
+
}
|
|
393
|
+
if (id.length > 64 || name.length > 64) {
|
|
394
|
+
return json({ error: "name too long (max 64)" }, 400);
|
|
395
|
+
}
|
|
396
|
+
const room = await mutate(async (svc) => {
|
|
397
|
+
const reg = await loadRegistry();
|
|
398
|
+
const regRoom = (reg[roomId] =
|
|
399
|
+
reg[roomId] ?? Object.create(null) as Record<string, RegistryEntry>);
|
|
400
|
+
// retire the participant this session previously held, if renamed
|
|
401
|
+
// — skipped when another session still uses the old name
|
|
402
|
+
const prevEntry = regRoom[sessionID];
|
|
403
|
+
if (prevEntry && prevEntry.name !== name) {
|
|
404
|
+
const shared = Object.entries(regRoom).some(
|
|
405
|
+
([sid, e]) => sid !== sessionID && e.name === prevEntry.name,
|
|
406
|
+
);
|
|
407
|
+
if (!shared && svc.containsParticipant(roomId, prevEntry.name)) {
|
|
408
|
+
svc.leaveRoom(roomId, prevEntry.name);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
const already = svc.containsParticipant(roomId, id);
|
|
412
|
+
// ponytail: prune a stale registry entry for the same participant
|
|
413
|
+
// name from another session (closed tab / cleared localStorage) —
|
|
414
|
+
// but only when the identity is NOT already present, otherwise two
|
|
415
|
+
// live sessions sharing a nickname would evict each other forever
|
|
416
|
+
if (!already) {
|
|
417
|
+
for (const [sid, e] of Object.entries(regRoom)) {
|
|
418
|
+
if (sid !== sessionID && e.name === name) {
|
|
419
|
+
delete regRoom[sid];
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
svc.joinRoom(roomId, { id, name });
|
|
424
|
+
touchActive(sessionID); // join = 活跃
|
|
425
|
+
if (!already) {
|
|
426
|
+
svc.addEvent(roomId, `${name} joined the room`);
|
|
427
|
+
}
|
|
428
|
+
regRoom[sessionID] = {
|
|
429
|
+
// ponytail: central mode self-pulls the inbox; no cross-host URL.
|
|
430
|
+
// Re-join must not rewind the read watermark (unread messages
|
|
431
|
+
// would be silently dropped); a first join starts at join time.
|
|
432
|
+
serverUrl: "",
|
|
433
|
+
apiPrefix: "/api",
|
|
434
|
+
name,
|
|
435
|
+
// ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
|
|
436
|
+
host: body.host ?? "",
|
|
437
|
+
lastReadTs: regRoom[sessionID]?.lastReadTs ?? Date.now(),
|
|
438
|
+
};
|
|
439
|
+
await saveRegistry(reg);
|
|
440
|
+
return svc.getRoom(roomId);
|
|
441
|
+
});
|
|
442
|
+
return json(serializeRoom(room), 201);
|
|
443
|
+
}
|
|
444
|
+
if (req.method === "POST" && m[2] === "leave") {
|
|
445
|
+
await mutate(async (svc) => {
|
|
446
|
+
const reg = await loadRegistry();
|
|
447
|
+
const entry = reg[roomId]?.[sessionID];
|
|
448
|
+
const participantId = entry?.name ?? sessionID;
|
|
449
|
+
// ponytail: orc-2 #2——共享名守卫:还有别的 session 持有同名时,
|
|
450
|
+
// 只移除本 entry,不移除参与者(否则兄弟 tab 发送会 NOT_JOINED)
|
|
451
|
+
const shared = Object.entries(reg[roomId] ?? {}).some(
|
|
452
|
+
([sid, e]) => e.name === participantId && sid !== sessionID,
|
|
453
|
+
);
|
|
454
|
+
if (!shared) {
|
|
455
|
+
svc.leaveRoom(roomId, participantId);
|
|
456
|
+
svc.addEvent(roomId, `${participantId} left the room`);
|
|
457
|
+
}
|
|
458
|
+
if (reg[roomId]) {
|
|
459
|
+
delete reg[roomId][sessionID];
|
|
460
|
+
if (Object.keys(reg[roomId]).length === 0) {
|
|
461
|
+
delete reg[roomId];
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
await saveRegistry(reg);
|
|
465
|
+
});
|
|
466
|
+
return json({ ok: true });
|
|
467
|
+
}
|
|
468
|
+
if (req.method === "POST" && m[2] === "messages") {
|
|
469
|
+
// ponytail: F3 — mirror the plugin's zod limit at the HTTP boundary
|
|
470
|
+
const text = (body.text ?? "").trim();
|
|
471
|
+
if (!text) {
|
|
472
|
+
return json({ error: "text is required" }, 400);
|
|
473
|
+
}
|
|
474
|
+
if (text.length > 2000) {
|
|
475
|
+
return json({ error: "text too long (max 2000)" }, 400);
|
|
476
|
+
}
|
|
477
|
+
const room = await mutate(async (svc) => {
|
|
478
|
+
const reg = await loadRegistry();
|
|
479
|
+
const sender = reg[roomId]?.[sessionID]?.name ?? sessionID;
|
|
480
|
+
svc.sendMessage(roomId, sender, text);
|
|
481
|
+
return svc.getRoom(roomId);
|
|
482
|
+
});
|
|
483
|
+
touchActive(sessionID); // 发送者活跃
|
|
484
|
+
// ponytail: 即时唤起——仅 @ 点名成员时(核心需求)
|
|
485
|
+
const sent = room.messages.at(-1);
|
|
486
|
+
if (sent) {
|
|
487
|
+
void wakeMentionedSessions(
|
|
488
|
+
roomId,
|
|
489
|
+
room.name,
|
|
490
|
+
sent.senderId,
|
|
491
|
+
text,
|
|
492
|
+
sessionID,
|
|
493
|
+
sent.createdAt,
|
|
494
|
+
);
|
|
495
|
+
}
|
|
496
|
+
return json(serializeRoom(room), 201);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
const g = p.match(/^\/rooms\/([^/]+)$/);
|
|
500
|
+
if (g && req.method === "GET") {
|
|
501
|
+
const room = await read((svc) =>
|
|
502
|
+
svc.getRoom(decodeURIComponent(g[1]!)),
|
|
503
|
+
);
|
|
504
|
+
return json(serializeRoom(room));
|
|
505
|
+
}
|
|
506
|
+
const r = p.match(/^\/rooms\/([^/]+)\/registry$/);
|
|
507
|
+
if (r && req.method === "GET") {
|
|
508
|
+
// ponytail: session registry for the in-plugin wake watcher — lets the
|
|
509
|
+
// plugin find which sessions have unread messages without polling every
|
|
510
|
+
// session's inbox; host is included for the @-wake ownership gate
|
|
511
|
+
const roomId = decodeURIComponent(r[1]!);
|
|
512
|
+
const reg = await enqueue(async () => {
|
|
513
|
+
const registry = await loadRegistry();
|
|
514
|
+
const entries = registry[roomId] ?? {};
|
|
515
|
+
return Object.fromEntries(
|
|
516
|
+
Object.entries(entries).map(([sid, e]) => [
|
|
517
|
+
sid,
|
|
518
|
+
{ name: e.name, lastReadTs: e.lastReadTs ?? 0, host: e.host ?? "" },
|
|
519
|
+
]),
|
|
520
|
+
);
|
|
521
|
+
});
|
|
522
|
+
return json(reg);
|
|
523
|
+
}
|
|
524
|
+
return json({ error: "not found" }, 404);
|
|
525
|
+
} catch (err) {
|
|
526
|
+
if (err instanceof RoomError) {
|
|
527
|
+
return json(
|
|
528
|
+
{ error: err.message },
|
|
529
|
+
err.code === "ROOM_NOT_FOUND" ? 404 : 409,
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
return json({ error: err instanceof Error ? err.message : String(err) }, 500);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
export default {
|
|
537
|
+
port,
|
|
538
|
+
fetch: handle,
|
|
539
|
+
// ponytail: bun's default idleTimeout (10s) would close our long-poll
|
|
540
|
+
// connections (25s) mid-request -> ERR_EMPTY_RESPONSE on every poll;
|
|
541
|
+
// keep connections alive well past the longest long-poll window
|
|
542
|
+
idleTimeout: 60,
|
|
543
|
+
};
|
|
544
|
+
|
|
545
|
+
console.log(
|
|
546
|
+
`chat-room center listening on http://localhost:${port}${token ? " (token auth on)" : ""}`,
|
|
547
|
+
);
|
|
548
|
+
if (!token) {
|
|
549
|
+
// ponytail: default is open — anyone who can reach the port can read/write
|
|
550
|
+
// rooms; set CHAT_ROOM_SERVER_TOKEN before exposing beyond localhost
|
|
551
|
+
console.warn(
|
|
552
|
+
"chat-room center has NO token auth — set CHAT_ROOM_SERVER_TOKEN if this port is reachable from other hosts",
|
|
553
|
+
);
|
|
554
|
+
}
|