@alexsun-top/opencode-chat-room 0.1.0 → 0.1.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.
@@ -4,18 +4,48 @@
4
4
  import { promises as fs } from "node:fs";
5
5
  import path from "node:path";
6
6
  import os from "node:os";
7
- import RoomService, { RoomError, type Room } from "../src/room-service";
7
+ import RoomService, {
8
+ RoomError,
9
+ type Message,
10
+ type Room,
11
+ } from "../src/room-service";
8
12
  import {
13
+ authHeader,
9
14
  enqueue,
15
+ formatServeWakePrompt,
16
+ formatNotificationLines,
10
17
  loadRegistry,
11
18
  loadRooms,
12
19
  saveRegistry,
13
20
  saveRooms,
14
- SERVE_WAKE_PROMPT,
15
21
  type RegistryEntry,
16
22
  } from "../src/store";
23
+ import {
24
+ admissionMatches,
25
+ clearPendingAdmission,
26
+ getOrCreatePendingAdmission,
27
+ markPendingAdmissionAdmitted,
28
+ rejectPendingAdmission,
29
+ type QueueBody,
30
+ type QueueItem,
31
+ } from "../src/queue";
32
+
33
+ function parsePort(value: string): number {
34
+ const port = Number(value);
35
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
36
+ throw new Error(
37
+ `Invalid server port "${value}": expected an integer from 1 to 65535`,
38
+ );
39
+ }
40
+ return port;
41
+ }
17
42
 
18
- const port = Number(process.env.CHAT_ROOM_SERVER_PORT ?? 4399);
43
+ const hostname =
44
+ process.env.CHAT_ROOM_SERVER_HOST ?? process.env.HOST ?? "0.0.0.0";
45
+ const displayHostname = hostname.includes(":") ? `[${hostname}]` : hostname;
46
+ const port = parsePort(
47
+ process.env.CHAT_ROOM_SERVER_PORT ?? process.env.PORT ?? "4399",
48
+ );
19
49
  const token = process.env.CHAT_ROOM_SERVER_TOKEN;
20
50
 
21
51
  // ponytail: 部署者显式配置的 serve 地址——消息到达时立即唤起被 @ 的已退出
@@ -60,10 +90,9 @@ function touchActive(sessionID: string): void {
60
90
  async function wakeMentionedSessions(
61
91
  roomId: string,
62
92
  roomName: string,
63
- senderName: string,
64
93
  text: string,
65
94
  senderSessionID: string,
66
- messageTs: number,
95
+ triggeringMessage: Message,
67
96
  ): Promise<void> {
68
97
  if (!serveWakeUrl) {
69
98
  return;
@@ -106,38 +135,91 @@ async function wakeMentionedSessions(
106
135
  // maxTs;否则更早未读被标记已读但从未投递(插件 sweep 也会因
107
136
  // 水位已推进而跳过——永久丢失)
108
137
  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
- },
138
+ const triggerItem: InboxItem = {
139
+ id: triggeringMessage.id,
140
+ roomId,
141
+ roomName,
142
+ senderId: triggeringMessage.senderId,
143
+ text: triggeringMessage.text,
144
+ createdAt: triggeringMessage.createdAt,
145
+ };
146
+ const items = inbox.items.some((item) => item.id === triggerItem.id)
147
+ ? inbox.items
148
+ : [...inbox.items, triggerItem].sort(
149
+ (a, b) => a.createdAt - b.createdAt,
150
+ );
151
+ const { lines, capped } = formatNotificationLines(items);
152
+ const prompt = formatServeWakePrompt(roomName, lines);
153
+ const maxTs = items.reduce(
154
+ (mx, it) => Math.max(mx, it.createdAt),
155
+ 0,
126
156
  );
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 () => {
157
+ const admissionItems: QueueItem[] = items;
158
+ const admission = getOrCreatePendingAdmission(
159
+ sid,
160
+ roomId,
161
+ admissionItems,
162
+ prompt,
163
+ maxTs,
164
+ capped,
165
+ );
166
+ const body: QueueBody = {
167
+ id: admission.id,
168
+ prompt: { text: admission.prompt },
169
+ delivery: "queue",
170
+ resume: true,
171
+ };
172
+ const confirmRead = async (): Promise<boolean> =>
173
+ enqueue(async () => {
134
174
  const r = await loadRegistry();
135
175
  const e = r[roomId]?.[sid];
136
- if (e) {
137
- e.lastReadTs = Math.max(e.lastReadTs ?? 0, maxTs);
138
- await saveRegistry(r);
176
+ if (!e) {
177
+ return false;
139
178
  }
179
+ e.lastReadTs = Math.max(e.lastReadTs ?? 0, admission.maxTs);
180
+ await saveRegistry(r);
181
+ return true;
140
182
  });
183
+ if (admission.state === "admitted") {
184
+ if (admission.capped) {
185
+ if (maxTs <= admission.maxTs) {
186
+ return;
187
+ }
188
+ } else {
189
+ if (admission.maxTs > 0 && (await confirmRead())) {
190
+ clearPendingAdmission(sid, roomId, admission.maxTs);
191
+ }
192
+ return;
193
+ }
194
+ }
195
+ const directory =
196
+ (entry as RegistryEntry & { directory?: string }).directory ??
197
+ process.env.OPENCODE_DIRECTORY;
198
+ const auth = authHeader();
199
+ const res = await fetch(
200
+ `${serveWakeUrl.replace(/\/+$/, "")}/api/session/${encodeURIComponent(sid)}/prompt`,
201
+ {
202
+ method: "POST",
203
+ headers: {
204
+ "Content-Type": "application/json",
205
+ ...(auth ? { Authorization: auth } : {}),
206
+ ...(directory
207
+ ? { "x-opencode-directory": encodeURIComponent(directory) }
208
+ : {}),
209
+ },
210
+ body: JSON.stringify(body),
211
+ signal: AbortSignal.timeout(10_000),
212
+ },
213
+ );
214
+ const data = await res.json().catch(() => undefined);
215
+ if (res.status >= 200 && res.status < 300 && admissionMatches(data, body, sid)) {
216
+ markPendingAdmissionAdmitted(sid, roomId, admission.id);
217
+ touchActive(sid);
218
+ if (!admission.capped && admission.maxTs > 0 && (await confirmRead())) {
219
+ clearPendingAdmission(sid, roomId, admission.maxTs);
220
+ }
221
+ } else if (res.status !== 404) {
222
+ rejectPendingAdmission(sid, roomId, admission.id);
141
223
  }
142
224
  } catch {
143
225
  // serve 不可达——静默,插件 10s 定时器兜底
@@ -158,7 +240,7 @@ const serializeRoom = (r: Room) => ({
158
240
  ownerId: r.ownerId,
159
241
  createdAt: r.createdAt,
160
242
  participants: [...r.participants.values()],
161
- messages: r.messages,
243
+ messages: r.messages.map(({ senderSessionID: _senderSessionID, ...message }) => message),
162
244
  });
163
245
 
164
246
  async function mutate<T>(
@@ -216,9 +298,13 @@ async function readInbox(
216
298
  member = true;
217
299
  const lastRead = entry.lastReadTs ?? 0;
218
300
  for (const m of room.messages) {
301
+ const isSelf =
302
+ m.senderSessionID !== undefined
303
+ ? m.senderSessionID === sessionID
304
+ : m.senderId === entry.name;
219
305
  if (
220
306
  m.createdAt > lastRead &&
221
- (!excludeSelf || m.senderId !== entry.name)
307
+ (!excludeSelf || !isSelf)
222
308
  ) {
223
309
  out.push({
224
310
  id: m.id,
@@ -238,6 +324,9 @@ async function readInbox(
238
324
  async function handle(req: Request): Promise<Response> {
239
325
  const url = new URL(req.url);
240
326
  const p = url.pathname;
327
+ if (req.method === "GET" && p === "/") {
328
+ return Response.redirect(new URL("/chat", url).toString(), 302);
329
+ }
241
330
  if (req.method === "GET" && p === "/chat") {
242
331
  // ponytail: the human-facing chat page; APIs stay token-gated, the page
243
332
  // itself is a static shell
@@ -308,9 +397,13 @@ async function handle(req: Request): Promise<Response> {
308
397
  serverUrl: "",
309
398
  apiPrefix: "/api",
310
399
  name: owner,
400
+ directory: body.directory || undefined,
311
401
  // ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
312
402
  host: body.host ?? "",
313
- lastReadTs: Date.now(),
403
+ lastReadTs: Math.max(
404
+ Date.now(),
405
+ created.messages.at(-1)?.createdAt ?? 0,
406
+ ),
314
407
  };
315
408
  await saveRegistry(reg);
316
409
  }
@@ -347,14 +440,17 @@ async function handle(req: Request): Promise<Response> {
347
440
  // accepted as a limitation until real session auth exists
348
441
  const body = (await req.json()) as Record<string, unknown>;
349
442
  const ts = Number(body.ts ?? 0);
350
- touchActive(String(body.sessionID ?? "")); // poll 推进 = 活跃
443
+ const roomId = String(body.roomId ?? "");
444
+ const sessionID = String(body.sessionID ?? "");
445
+ touchActive(sessionID); // poll 推进 = 活跃
351
446
  await enqueue(async () => {
352
447
  const reg = await loadRegistry();
353
- const entry = reg[String(body.roomId)]?.[String(body.sessionID)];
448
+ const entry = reg[roomId]?.[sessionID];
354
449
  // ponytail: NaN would poison the watermark (all comparisons false)
355
450
  if (entry && Number.isFinite(ts)) {
356
451
  entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
357
452
  await saveRegistry(reg);
453
+ clearPendingAdmission(sessionID, roomId, ts);
358
454
  }
359
455
  });
360
456
  return json({ ok: true });
@@ -425,6 +521,8 @@ async function handle(req: Request): Promise<Response> {
425
521
  if (!already) {
426
522
  svc.addEvent(roomId, `${name} joined the room`);
427
523
  }
524
+ const latestMessageTs =
525
+ svc.getMessages(roomId).at(-1)?.createdAt ?? 0;
428
526
  regRoom[sessionID] = {
429
527
  // ponytail: central mode self-pulls the inbox; no cross-host URL.
430
528
  // Re-join must not rewind the read watermark (unread messages
@@ -432,9 +530,12 @@ async function handle(req: Request): Promise<Response> {
432
530
  serverUrl: "",
433
531
  apiPrefix: "/api",
434
532
  name,
533
+ directory: body.directory || undefined,
435
534
  // ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
436
535
  host: body.host ?? "",
437
- lastReadTs: regRoom[sessionID]?.lastReadTs ?? Date.now(),
536
+ lastReadTs:
537
+ regRoom[sessionID]?.lastReadTs ??
538
+ Math.max(Date.now(), latestMessageTs),
438
539
  };
439
540
  await saveRegistry(reg);
440
541
  return svc.getRoom(roomId);
@@ -477,7 +578,7 @@ async function handle(req: Request): Promise<Response> {
477
578
  const room = await mutate(async (svc) => {
478
579
  const reg = await loadRegistry();
479
580
  const sender = reg[roomId]?.[sessionID]?.name ?? sessionID;
480
- svc.sendMessage(roomId, sender, text);
581
+ svc.sendMessage(roomId, sender, text, sessionID);
481
582
  return svc.getRoom(roomId);
482
583
  });
483
584
  touchActive(sessionID); // 发送者活跃
@@ -487,10 +588,9 @@ async function handle(req: Request): Promise<Response> {
487
588
  void wakeMentionedSessions(
488
589
  roomId,
489
590
  room.name,
490
- sent.senderId,
491
591
  text,
492
592
  sessionID,
493
- sent.createdAt,
593
+ sent,
494
594
  );
495
595
  }
496
596
  return json(serializeRoom(room), 201);
@@ -515,7 +615,12 @@ async function handle(req: Request): Promise<Response> {
515
615
  return Object.fromEntries(
516
616
  Object.entries(entries).map(([sid, e]) => [
517
617
  sid,
518
- { name: e.name, lastReadTs: e.lastReadTs ?? 0, host: e.host ?? "" },
618
+ {
619
+ name: e.name,
620
+ lastReadTs: e.lastReadTs ?? 0,
621
+ host: e.host ?? "",
622
+ directory: e.directory,
623
+ },
519
624
  ]),
520
625
  );
521
626
  });
@@ -534,6 +639,7 @@ async function handle(req: Request): Promise<Response> {
534
639
  }
535
640
 
536
641
  export default {
642
+ hostname,
537
643
  port,
538
644
  fetch: handle,
539
645
  // ponytail: bun's default idleTimeout (10s) would close our long-poll
@@ -543,7 +649,7 @@ export default {
543
649
  };
544
650
 
545
651
  console.log(
546
- `chat-room center listening on http://localhost:${port}${token ? " (token auth on)" : ""}`,
652
+ `chat-room center listening on http://${displayHostname}:${port}${token ? " (token auth on)" : ""}`,
547
653
  );
548
654
  if (!token) {
549
655
  // ponytail: default is open — anyone who can reach the port can read/write