@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.
@@ -0,0 +1,530 @@
1
+ // ponytail: central-server mode client. All room state lives on the central
2
+ // server (CHAT_ROOM_SERVER_URL); this machine self-pushes queue notifications
3
+ // to its own embedded server (localhost is always reachable from the same
4
+ // process, so no cross-host serverUrl or firewall setup is needed).
5
+ import RoomService, {
6
+ type Message,
7
+ type Participant,
8
+ type Room,
9
+ } from "./room-service";
10
+ import os from "node:os";
11
+ import {
12
+ authHeader,
13
+ formatNotificationLines,
14
+ formatRoom,
15
+ identity,
16
+ NOTIFY_INSTRUCTION,
17
+ SERVE_WAKE_PROMPT,
18
+ timeOf,
19
+ } from "./store";
20
+
21
+ type Json = Record<string, unknown>;
22
+
23
+ function toRoom(r: Json): Room {
24
+ const participants = new Map<string, Participant>();
25
+ if (Array.isArray(r.participants)) {
26
+ for (const p of r.participants as Participant[]) {
27
+ if (p && typeof p.id === "string" && typeof p.name === "string") {
28
+ participants.set(p.id, p);
29
+ }
30
+ }
31
+ }
32
+ return {
33
+ id: String(r.id ?? ""),
34
+ name: String(r.name ?? ""),
35
+ ownerId: String(r.ownerId ?? ""),
36
+ createdAt: Number(r.createdAt ?? 0),
37
+ participants,
38
+ messages: Array.isArray(r.messages) ? (r.messages as Message[]) : [],
39
+ };
40
+ }
41
+
42
+ function svcOf(room: Json): RoomService {
43
+ const svc = new RoomService();
44
+ svc.hydrate([toRoom(room)]);
45
+ return svc;
46
+ }
47
+
48
+ type CenterOpts = { center: string; token: string };
49
+
50
+ async function request(
51
+ opts: CenterOpts,
52
+ path: string,
53
+ method: string,
54
+ body?: unknown,
55
+ ): Promise<Json> {
56
+ const headers: Record<string, string> = {};
57
+ if (opts.token) {
58
+ headers["Authorization"] = `Bearer ${opts.token}`;
59
+ }
60
+ if (body !== undefined) {
61
+ headers["Content-Type"] = "application/json";
62
+ }
63
+ const res = await fetch(`${opts.center}${path}`, {
64
+ method,
65
+ headers,
66
+ body: body === undefined ? undefined : JSON.stringify(body),
67
+ // ponytail: don't hang the tool call on a dead center
68
+ signal: AbortSignal.timeout(10_000),
69
+ });
70
+ const data = (await res.json().catch(() => ({}))) as Json;
71
+ if (!res.ok) {
72
+ throw new Error(String(data.error ?? `center error ${res.status}`));
73
+ }
74
+ return data;
75
+ }
76
+
77
+ export async function centerAction(
78
+ opts: CenterOpts,
79
+ args: {
80
+ action: string;
81
+ name?: string;
82
+ roomId?: string;
83
+ text?: string;
84
+ },
85
+ sessionID: string,
86
+ ): Promise<string> {
87
+ const { center, token } = opts;
88
+ switch (args.action) {
89
+ case "list": {
90
+ const rooms = (await request(opts, "/rooms", "GET")) as unknown as Json[];
91
+ if (!Array.isArray(rooms) || rooms.length === 0) {
92
+ return "no rooms yet";
93
+ }
94
+ return rooms
95
+ .map(
96
+ (r) =>
97
+ `${r.id} (${r.name}): ${
98
+ Array.isArray(r.participants) ? r.participants.length : 0
99
+ } members`,
100
+ )
101
+ .join("\n");
102
+ }
103
+ case "create": {
104
+ if (!args.name?.trim()) {
105
+ return "error: name is required";
106
+ }
107
+ const room = await request(opts, "/rooms", "POST", {
108
+ name: args.name.trim(),
109
+ ownerId: identity(),
110
+ sessionID,
111
+ // ponytail: ora-1 #2 — 记录归属主机,跨机 @-wake 只由所属机器唤醒
112
+ host: os.hostname(),
113
+ });
114
+ return formatRoom(svcOf(room), toRoom(room));
115
+ }
116
+ case "join": {
117
+ if (!args.roomId) {
118
+ return "error: roomId is required";
119
+ }
120
+ const me = identity(args.name?.trim());
121
+ const room = await request(
122
+ opts,
123
+ `/rooms/${encodeURIComponent(args.roomId)}/join`,
124
+ "POST",
125
+ {
126
+ sessionID,
127
+ participantId: me,
128
+ participantName: me,
129
+ // ponytail: ora-1 #2 — 记录归属主机,跨机 @-wake 只由所属机器唤醒
130
+ host: os.hostname(),
131
+ },
132
+ );
133
+ return formatRoom(svcOf(room), toRoom(room));
134
+ }
135
+ case "leave": {
136
+ if (!args.roomId) {
137
+ return "error: roomId is required";
138
+ }
139
+ await request(
140
+ opts,
141
+ `/rooms/${encodeURIComponent(args.roomId)}/leave`,
142
+ "POST",
143
+ { sessionID },
144
+ );
145
+ return `left room ${args.roomId}`;
146
+ }
147
+ case "members": {
148
+ if (!args.roomId) {
149
+ return "error: roomId is required";
150
+ }
151
+ const room = await request(
152
+ opts,
153
+ `/rooms/${encodeURIComponent(args.roomId)}`,
154
+ "GET",
155
+ );
156
+ const svc = svcOf(room);
157
+ const members = svc.getParticipants(toRoom(room).id);
158
+ return members.length > 0
159
+ ? members.map((m) => m.name).join("\n")
160
+ : "no members";
161
+ }
162
+ case "send": {
163
+ if (!args.roomId) {
164
+ return "error: roomId is required";
165
+ }
166
+ if (!args.text?.trim()) {
167
+ return "error: text is required";
168
+ }
169
+ const room = await request(
170
+ opts,
171
+ `/rooms/${encodeURIComponent(args.roomId)}/messages`,
172
+ "POST",
173
+ { sessionID, text: args.text.trim() },
174
+ );
175
+ const svc = svcOf(room);
176
+ return `sent: ${args.text.trim()}\n${formatRoom(svc, toRoom(room))}`;
177
+ }
178
+ case "poll": {
179
+ if (!args.roomId) {
180
+ return "error: roomId is required";
181
+ }
182
+ const result = (await request(
183
+ opts,
184
+ `/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(args.roomId)}&excludeSelf=0`,
185
+ "GET",
186
+ )) as unknown as { member: boolean; items: InboxItem[] };
187
+ // ponytail: F6 — same gate as standalone: only members can read
188
+ if (!result.member) {
189
+ return "error: not joined";
190
+ }
191
+ const items = Array.isArray(result.items) ? result.items : [];
192
+ if (items.length === 0) {
193
+ return "no new messages";
194
+ }
195
+ const lines = items.map(
196
+ (it) => `[${timeOf(it.createdAt)}] ${it.senderId}: ${it.text}`,
197
+ );
198
+ // ponytail: F7 — advance the watermark after the result is delivered
199
+ // (fire-and-forget); a failure only repeats the messages, never loses
200
+ const maxTs = items.reduce((mx, it) => Math.max(mx, it.createdAt), 0);
201
+ void request(opts, "/read", "POST", {
202
+ roomId: args.roomId,
203
+ sessionID,
204
+ ts: maxTs,
205
+ }).catch(() => {});
206
+ return lines.join("\n");
207
+ }
208
+ default:
209
+ return "error: unknown action";
210
+ }
211
+ }
212
+
213
+ type InboxItem = {
214
+ roomId: string;
215
+ roomName: string;
216
+ senderId: string;
217
+ text: string;
218
+ createdAt: number;
219
+ };
220
+
221
+ // ponytail: overlapping hook+tool triggers must not double-deliver;
222
+ // per-session so a slow check for one session can't starve another
223
+ const inboxChecks = new Set<string>();
224
+
225
+ // ponytail: central mode has no cross-host push; each session pulls its inbox
226
+ // on every hook/tool call and self-pushes queue notifications (localhost).
227
+ // Items are grouped by room: a room's watermark advances only when every item
228
+ // in that room was pushed successfully, so a failed push is retried next time.
229
+ export async function checkCenterInbox(
230
+ opts: CenterOpts,
231
+ sessionID: string,
232
+ selfServerUrl: string,
233
+ ): Promise<void> {
234
+ if (inboxChecks.has(sessionID)) {
235
+ return;
236
+ }
237
+ inboxChecks.add(sessionID);
238
+ try {
239
+ const result = (await request(
240
+ opts,
241
+ `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1`,
242
+ "GET",
243
+ )) as unknown as { member: boolean; items: InboxItem[] };
244
+ const items = Array.isArray(result.items) ? result.items : [];
245
+ if (items.length > 0) {
246
+ await pushItemsToSession(opts, sessionID, items, selfServerUrl);
247
+ }
248
+ } catch {
249
+ // best-effort: next check retries
250
+ } finally {
251
+ inboxChecks.delete(sessionID);
252
+ }
253
+ }
254
+ // ponytail: push a batch of inbox items to one session (grouped per room —
255
+ // a room's watermark advances only when every item in it was pushed
256
+ // successfully, so a failed push is retried next time).
257
+ // Result: "delivered" = all 2xx; "unreachable" = connection refused or 404
258
+ // (the session's process is very likely gone — the only case worth spawning
259
+ // a replacement process for); "rejected" = server alive but refused (401/5xx
260
+ // — do NOT spawn, the session may live in another window).
261
+ export type PushResult = "delivered" | "unreachable" | "rejected";
262
+
263
+ // ponytail: in-process push dedupe — the 30s wake sweep and the per-hook
264
+ // inbox check must not deliver the same items twice; capped pushes (which
265
+ // deliberately don't advance the watermark) would otherwise re-notify every
266
+ // sweep forever (orc-1 #4)
267
+ const lastPushed = new Map<string, number>();
268
+
269
+ export async function pushItemsToSession(
270
+ opts: CenterOpts,
271
+ sessionID: string,
272
+ items: InboxItem[],
273
+ selfServerUrl: string,
274
+ ): Promise<PushResult> {
275
+ if (items.length === 0) {
276
+ return "delivered";
277
+ }
278
+ const byRoom = new Map<string, InboxItem[]>();
279
+ for (const it of items) {
280
+ const list = byRoom.get(it.roomId) ?? [];
281
+ list.push(it);
282
+ byRoom.set(it.roomId, list);
283
+ }
284
+ const auth = authHeader();
285
+ const base = selfServerUrl.replace(/\/+$/, "");
286
+ let worst: PushResult = "delivered";
287
+ for (const [roomId, roomItems] of byRoom) {
288
+ const maxTs = roomItems.reduce(
289
+ (mx, it) => Math.max(mx, it.createdAt),
290
+ 0,
291
+ );
292
+ const key = `${sessionID}|${roomId}`;
293
+ if (maxTs <= (lastPushed.get(key) ?? 0)) {
294
+ continue; // already pushed this content
295
+ }
296
+ if (lastPushed.size > 1000) {
297
+ lastPushed.clear(); // ponytail: cap——防长驻进程无限增长
298
+ }
299
+ const { lines, capped } = formatNotificationLines(roomItems);
300
+ const prompt = `<notification>\nNew messages in room ${roomItems[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
301
+ // ponytail: network errors (e.g. connection refused — the session's
302
+ // process has exited) count as push failure, NOT as a crash: a rejected
303
+ // fetch here would abort the whole wake sweep and skip every other
304
+ // session, and the @-wake spawn would never run
305
+ let res: Response;
306
+ try {
307
+ res = await fetch(`${base}/api/session/${sessionID}/prompt`, {
308
+ method: "POST",
309
+ headers: {
310
+ "Content-Type": "application/json",
311
+ ...(auth ? { Authorization: auth } : {}),
312
+ },
313
+ body: JSON.stringify({ prompt, delivery: "queue" }),
314
+ });
315
+ } catch {
316
+ worst = "unreachable";
317
+ continue;
318
+ }
319
+ // ponytail: a capped push must not advance the watermark — the
320
+ // folded-out messages would become permanently unreadable; the
321
+ // uncapped poll/inbox path remains the lossless catch-up
322
+ if (res.ok) {
323
+ if (capped) {
324
+ lastPushed.set(key, maxTs);
325
+ } else {
326
+ // orc-3 #6——/read 失败时不得记 lastPushed:水位未推进,下次 sweep
327
+ // 重推(否则推送成功但水位未动 → 推送路径对该批消息永久静默)
328
+ const advanced = await request(opts, "/read", "POST", {
329
+ roomId,
330
+ sessionID,
331
+ ts: maxTs,
332
+ })
333
+ .then(() => true)
334
+ .catch(() => false);
335
+ if (advanced) lastPushed.set(key, maxTs);
336
+ }
337
+ } else if (res.status === 404 || res.status === 400) {
338
+ // 404 / 400 (Invalid session ID): 本进程/本 server 不持有该 session
339
+ // ——已退出或从未在本机运行 → 视为 unreachable,可由 serve 唤起
340
+ worst = "unreachable";
341
+ } else {
342
+ worst = "rejected";
343
+ }
344
+ }
345
+ return worst;
346
+ }
347
+
348
+ // ponytail: in-plugin wake watcher — sweep all rooms on the central server,
349
+ // find sessions with unread messages, and self-push queue notifications to
350
+ // them (opencode wakes the session in-process; dead sessions just fail
351
+ // silently). Runs on a timer; the central server itself has no opencode
352
+ // knowledge, this is purely client-side.
353
+ let wakeChecking = false;
354
+
355
+ // ponytail: 纯进程内唤醒(去 spawn)——已退出进程的 session 不再拉起新
356
+ // 进程。若部署者配置了 CHAT_ROOM_WAKE_SERVE_URL(常驻 opencode serve),
357
+ // 对被 @ 的已退出 session 通过 serve 的 /session/:id/message 进程内唤起;
358
+ // serve 未配置/不可达 → 不唤醒(未读由水位保留,session 下次运行时 poll
359
+ // 自动拿到)
360
+ async function wakeViaServe(
361
+ serveUrl: string,
362
+ sessionID: string,
363
+ opts: CenterOpts,
364
+ prompt = SERVE_WAKE_PROMPT,
365
+ ): Promise<boolean> {
366
+ // ponytail: 与多窗口插件共用服务器原子去重,避免重复唤起同一 session
367
+ try {
368
+ const claim = (await fetch(`${opts.center}/wake-claim`, {
369
+ method: "POST",
370
+ headers: {
371
+ "Content-Type": "application/json",
372
+ ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}),
373
+ },
374
+ body: JSON.stringify({ sessionID }),
375
+ signal: AbortSignal.timeout(10_000),
376
+ }).then((r) => r.json().catch(() => ({})))) as { ok?: boolean };
377
+ if (!claim.ok) {
378
+ return false;
379
+ }
380
+ } catch {
381
+ return false;
382
+ }
383
+ try {
384
+ const res = await fetch(
385
+ `${serveUrl.replace(/\/+$/, "")}/session/${sessionID}/message`,
386
+ {
387
+ method: "POST",
388
+ headers: { "Content-Type": "application/json" },
389
+ body: JSON.stringify({ parts: [{ type: "text", text: prompt }] }),
390
+ signal: AbortSignal.timeout(10_000),
391
+ },
392
+ );
393
+ return res.ok;
394
+ } catch {
395
+ // serve 未启动/不可达——按用户要求不唤醒(无 spawn、无重试)
396
+ return false;
397
+ }
398
+ }
399
+
400
+ export async function wakeSessions(
401
+ opts: CenterOpts,
402
+ selfServerUrl: string,
403
+ serveUrl = "",
404
+ ): Promise<void> {
405
+ if (wakeChecking) {
406
+ return;
407
+ }
408
+ wakeChecking = true;
409
+ try {
410
+ // ponytail: 轻量摘要(orc-1 #5)——不下载全部房间历史
411
+ const rooms = (await request(
412
+ opts,
413
+ "/rooms/summary",
414
+ "GET",
415
+ )) as unknown as Array<{ id: string; name: string; latestMsgTs: number }>;
416
+ if (!Array.isArray(rooms)) {
417
+ return;
418
+ }
419
+ for (const room of rooms) {
420
+ try {
421
+ const roomId = String(room.id ?? "");
422
+ const latest = Number(room.latestMsgTs ?? 0);
423
+ if (!roomId || latest === 0) {
424
+ continue;
425
+ }
426
+ const reg = (await request(
427
+ opts,
428
+ `/rooms/${encodeURIComponent(roomId)}/registry`,
429
+ "GET",
430
+ )) as unknown as Record<
431
+ string,
432
+ { name: string; lastReadTs?: number; host?: string }
433
+ >;
434
+ if (!reg || typeof reg !== "object") {
435
+ continue;
436
+ }
437
+ for (const [sessionID, entry] of Object.entries(reg)) {
438
+ // ponytail: 网页/模拟条目(host 空)不是 opencode 会话——不扫描
439
+ // 不推送(否则死条目每 10s 一次 404 推送,永远 churn,orc-1 #7)
440
+ if (!entry.host) {
441
+ continue;
442
+ }
443
+ // ponytail: orc-2 #6——跨 host 条目由各自机器上的插件负责,本机
444
+ // 扫描+推送只会 404(lastPushed 只在 res.ok 时设置,永不去重)
445
+ if (entry.host !== os.hostname()) {
446
+ continue;
447
+ }
448
+ // quick skip: nothing newer than this session's watermark
449
+ if (latest <= (entry.lastReadTs ?? 0)) {
450
+ continue;
451
+ }
452
+ const result = (await request(
453
+ opts,
454
+ `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1&timeout=0`,
455
+ "GET",
456
+ )) as unknown as { member: boolean; items: InboxItem[] };
457
+ const items = Array.isArray(result.items) ? result.items : [];
458
+ if (items.length > 0) {
459
+ // ponytail: ora-1 #2 — @-wake 只由 session 归属主机执行;web 条目
460
+ // (host 为空)与异机条目绝不 spawn(否则错机 spawn 一个不存在
461
+ // 的 session,且 5 分钟 claim 窗口会挡住真正正确的那台机器)
462
+ const pushed = await pushItemsToSession(
463
+ opts,
464
+ sessionID,
465
+ items,
466
+ selfServerUrl,
467
+ );
468
+ if (pushed === "delivered") {
469
+ // ponytail: 进程内自推成功 = 该 session 真实活跃——上报服务器,
470
+ // 避免服务器 serve 双唤起
471
+ void request(opts, "/active", "POST", { sessionID }).catch(
472
+ () => {},
473
+ );
474
+ }
475
+ // 被 @ 的已退出 session:serve 配置了才唤起(进程内,零 spawn)。
476
+ // 唤起成功即推进水位——消息已进入该 session 的对话(不丢),
477
+ // 避免同一未读反复唤起导致循环回复。
478
+ // 仅唤起本机 opencode session(host === 本机主机名)——web 条目
479
+ // 与 curl 模拟成员(host 空)没有可恢复的 opencode 会话
480
+ if (
481
+ pushed === "unreachable" &&
482
+ serveUrl &&
483
+ entry.host === os.hostname()
484
+ ) {
485
+ const mentioned = items.some((it) => {
486
+ if (it.text.includes(`<at>@${entry.name}</at>`)) return true;
487
+ const esc = entry.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
488
+ return new RegExp(`@${esc}(?![\\p{L}\\p{N}_])`, "u").test(
489
+ it.text,
490
+ );
491
+ });
492
+ if (mentioned) {
493
+ // ponytail: orc-2 #1——唤起 prompt 必须带未读消息内容(镜像
494
+ // 服务器路径),否则 agent poll 时已无未读(水位已推进),
495
+ // @ 内容永远不达;水位推进到 maxTs 因此是安全的
496
+ const content = items
497
+ .map((it) => `[${it.senderId}]: ${it.text}`)
498
+ .join("\n");
499
+ const woke = await wakeViaServe(
500
+ serveUrl,
501
+ sessionID,
502
+ opts,
503
+ `${SERVE_WAKE_PROMPT}\n\n未读消息:\n${content}`,
504
+ );
505
+ if (woke) {
506
+ const maxTs = items.reduce(
507
+ (mx, it) => Math.max(mx, it.createdAt),
508
+ 0,
509
+ );
510
+ await request(opts, "/read", "POST", {
511
+ roomId,
512
+ sessionID,
513
+ ts: maxTs,
514
+ }).catch(() => {});
515
+ }
516
+ }
517
+ }
518
+ }
519
+ }
520
+ } catch {
521
+ // ponytail: orc-3 #4——单房间错误(registry/inbox 请求失败)只跳过
522
+ // 该房间,不中止整个 sweep
523
+ }
524
+ }
525
+ } catch {
526
+ // best-effort: next sweep retries
527
+ } finally {
528
+ wakeChecking = false;
529
+ }
530
+ }
@@ -0,0 +1,169 @@
1
+ import { randomUUID } from "node:crypto";
2
+
3
+ export type Participant = {
4
+ id: string;
5
+ name: string;
6
+ joinedAt: number;
7
+ };
8
+
9
+ export type Message = {
10
+ id: string;
11
+ roomId: string;
12
+ senderId: string;
13
+ text: string;
14
+ createdAt: number;
15
+ };
16
+
17
+ export type Room = {
18
+ id: string;
19
+ name: string;
20
+ ownerId: string;
21
+ participants: Map<string, Participant>;
22
+ messages: Message[];
23
+ createdAt: number;
24
+ };
25
+
26
+ export type RoomErrorCode =
27
+ | "ROOM_NOT_FOUND"
28
+ | "NOT_JOINED"
29
+ | "EMPTY_MESSAGE";
30
+
31
+ export class RoomError extends Error {
32
+ readonly code: RoomErrorCode;
33
+
34
+ constructor(code: RoomErrorCode, message?: string) {
35
+ super(message ?? code);
36
+ this.name = "RoomError";
37
+ this.code = code;
38
+ }
39
+ }
40
+
41
+ export default class RoomService {
42
+ private rooms: Map<string, Room> = new Map();
43
+
44
+ // ponytail: per-room history ceiling — everything above the watermark is
45
+ // unreachable anyway; this bounds rooms.json and every serialized response
46
+ static readonly MAX_MESSAGES = 500;
47
+
48
+ hydrate(rooms: Room[]): void {
49
+ for (const room of rooms) {
50
+ // ponytail: cap pre-existing rooms.json files on load so an old
51
+ // oversized file doesn't stay heavy until the next event
52
+ this.trimMessages(room);
53
+ this.rooms.set(room.id, room);
54
+ }
55
+ }
56
+
57
+ createRoom(name: string, ownerId: string): Room {
58
+ const room: Room = {
59
+ id: randomUUID(),
60
+ name,
61
+ ownerId,
62
+ participants: new Map(),
63
+ messages: [],
64
+ createdAt: Date.now(),
65
+ };
66
+ room.participants.set(ownerId, {
67
+ id: ownerId,
68
+ name: ownerId,
69
+ joinedAt: Date.now(),
70
+ });
71
+ this.rooms.set(room.id, room);
72
+ return room;
73
+ }
74
+
75
+ getRoom(roomId: string): Room {
76
+ const room = this.rooms.get(roomId);
77
+ if (!room) {
78
+ throw new RoomError("ROOM_NOT_FOUND", `room not found: ${roomId}`);
79
+ }
80
+ return room;
81
+ }
82
+
83
+ listRooms(): Room[] {
84
+ return [...this.rooms.values()];
85
+ }
86
+
87
+ joinRoom(
88
+ roomId: string,
89
+ participant: { id: string; name: string },
90
+ ): Participant {
91
+ const room = this.getRoom(roomId);
92
+ // ponytail: the same identity from another session is the same member —
93
+ // a second window on the same machine must not be locked out
94
+ const existing = room.participants.get(participant.id);
95
+ if (existing) {
96
+ return existing;
97
+ }
98
+ const member: Participant = {
99
+ id: participant.id,
100
+ name: participant.name,
101
+ joinedAt: Date.now(),
102
+ };
103
+ room.participants.set(member.id, member);
104
+ return member;
105
+ }
106
+
107
+ leaveRoom(roomId: string, participantId: string): void {
108
+ const room = this.getRoom(roomId);
109
+ if (!room.participants.delete(participantId)) {
110
+ throw new RoomError("NOT_JOINED", `not joined: ${participantId}`);
111
+ }
112
+ }
113
+
114
+ sendMessage(roomId: string, senderId: string, text: string): Message {
115
+ const room = this.getRoom(roomId);
116
+ if (!room.participants.has(senderId)) {
117
+ throw new RoomError("NOT_JOINED", `not joined: ${senderId}`);
118
+ }
119
+ const trimmed = text.trim();
120
+ if (trimmed.length === 0) {
121
+ throw new RoomError("EMPTY_MESSAGE", "message text is empty");
122
+ }
123
+ const message: Message = {
124
+ id: randomUUID(),
125
+ roomId,
126
+ senderId,
127
+ text: trimmed,
128
+ createdAt: Date.now(),
129
+ };
130
+ room.messages.push(message);
131
+ this.trimMessages(room);
132
+ return message;
133
+ }
134
+
135
+ // ponytail: membership events live in the message stream (senderId
136
+ // "system") so push notifications and the central inbox carry them for free
137
+ addEvent(roomId: string, text: string): Message {
138
+ const message: Message = {
139
+ id: randomUUID(),
140
+ roomId,
141
+ senderId: "system",
142
+ text,
143
+ createdAt: Date.now(),
144
+ };
145
+ const room = this.getRoom(roomId);
146
+ room.messages.push(message);
147
+ this.trimMessages(room);
148
+ return message;
149
+ }
150
+
151
+ private trimMessages(room: Room): void {
152
+ const overflow = room.messages.length - RoomService.MAX_MESSAGES;
153
+ if (overflow > 0) {
154
+ room.messages.splice(0, overflow);
155
+ }
156
+ }
157
+
158
+ getMessages(roomId: string): Message[] {
159
+ return [...this.getRoom(roomId).messages];
160
+ }
161
+
162
+ getParticipants(roomId: string): Participant[] {
163
+ return [...this.getRoom(roomId).participants.values()];
164
+ }
165
+
166
+ containsParticipant(roomId: string, participantId: string): boolean {
167
+ return this.rooms.get(roomId)?.participants.has(participantId) ?? false;
168
+ }
169
+ }