@alexsun-top/opencode-chat-room 0.1.1 → 0.1.3

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,16 +4,32 @@
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
+ pendingAdmission,
29
+ rejectPendingAdmission,
30
+ type QueueBody,
31
+ type QueueItem,
32
+ } from "../src/queue";
17
33
 
18
34
  function parsePort(value: string): number {
19
35
  const port = Number(value);
@@ -75,10 +91,9 @@ function touchActive(sessionID: string): void {
75
91
  async function wakeMentionedSessions(
76
92
  roomId: string,
77
93
  roomName: string,
78
- senderName: string,
79
94
  text: string,
80
95
  senderSessionID: string,
81
- messageTs: number,
96
+ triggeringMessage: Message,
82
97
  ): Promise<void> {
83
98
  if (!serveWakeUrl) {
84
99
  return;
@@ -108,7 +123,9 @@ async function wakeMentionedSessions(
108
123
  sid === senderSessionID ||
109
124
  !mentions.has(entry.name) || // 只唤起被 @ 点名的人
110
125
  entry.host !== os.hostname() || // 只唤起本机 session(serve 只能恢复本机)
111
- (activeSessions.get(sid) ?? 0) > now - WAKE_INACTIVE_MS // 活跃中——插件推送处理
126
+ (activeSessions.get(sid) ?? 0) > now - WAKE_INACTIVE_MS || // 活跃中——插件推送处理
127
+ triggeringMessage.createdAt <= (entry.lastReadTs ?? 0) ||
128
+ triggeringMessage.createdAt <= (entry.lastQueuedTs ?? 0)
112
129
  ) {
113
130
  continue;
114
131
  }
@@ -117,42 +134,126 @@ async function wakeMentionedSessions(
117
134
  }
118
135
  void (async () => {
119
136
  try {
120
- // orc-3 #2——带该 session 的全部未读(含更早的),水位推进到
121
- // maxTs;否则更早未读被标记已读但从未投递(插件 sweep 也会因
122
- // 水位已推进而跳过——永久丢失)
137
+ // orc-3 #2——带该 session 的全部待通知消息(含更早的),队列游标
138
+ // 推进到 maxTs;lastReadTs 保留给 poll,避免未读消息被跳过
123
139
  const inbox = await readInbox(sid, roomId, true);
124
- const older = inbox.items.filter((it) => it.createdAt < messageTs);
125
- // prompt 附带触发消息内容——agent 无需 poll 也能精确回复
126
- const prompt =
127
- `${SERVE_WAKE_PROMPT}\n\n` +
128
- `New message in room ${roomName} from ${senderName}: ${text}` +
129
- (older.length
130
- ? `\n\n更早的未读消息:\n${older
131
- .map((it) => `[${it.senderId}]: ${it.text}`)
132
- .join("\n")}`
133
- : "");
134
- const res = await fetch(
135
- `${serveWakeUrl.replace(/\/+$/, "")}/session/${sid}/message`,
136
- {
137
- method: "POST",
138
- headers: { "Content-Type": "application/json" },
139
- body: JSON.stringify({ parts: [{ type: "text", text: prompt }] }),
140
- },
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,
141
150
  );
142
- if (res.ok) {
143
- // 唤起成功(serve 同步处理完)后推进水位——防循环唤起
144
- const maxTs = Math.max(
145
- messageTs,
146
- ...inbox.items.map((it) => it.createdAt),
147
- );
148
- await enqueue(async () => {
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 () => {
149
184
  const r = await loadRegistry();
150
185
  const e = r[roomId]?.[sid];
151
- if (e) {
152
- e.lastReadTs = Math.max(e.lastReadTs ?? 0, maxTs);
153
- await saveRegistry(r);
186
+ if (!e) {
187
+ return false;
154
188
  }
189
+ e.lastQueuedTs = Math.max(e.lastQueuedTs ?? 0, ts);
190
+ await saveRegistry(r);
191
+ return true;
155
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);
156
257
  }
157
258
  } catch {
158
259
  // serve 不可达——静默,插件 10s 定时器兜底
@@ -173,7 +274,7 @@ const serializeRoom = (r: Room) => ({
173
274
  ownerId: r.ownerId,
174
275
  createdAt: r.createdAt,
175
276
  participants: [...r.participants.values()],
176
- messages: r.messages,
277
+ messages: r.messages.map(({ senderSessionID: _senderSessionID, ...message }) => message),
177
278
  });
178
279
 
179
280
  async function mutate<T>(
@@ -204,7 +305,11 @@ type InboxItem = {
204
305
  text: string;
205
306
  createdAt: number;
206
307
  };
207
- type InboxResult = { member: boolean; items: InboxItem[] };
308
+ type InboxResult = {
309
+ member: boolean;
310
+ items: InboxItem[];
311
+ queuedTs: Record<string, number>;
312
+ };
208
313
 
209
314
  const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
210
315
 
@@ -219,6 +324,7 @@ async function readInbox(
219
324
  return read(async (svc) => {
220
325
  const reg = await loadRegistry();
221
326
  const out: InboxItem[] = [];
327
+ const queuedTs: Record<string, number> = Object.create(null);
222
328
  let member = false;
223
329
  for (const room of svc.listRooms()) {
224
330
  if (roomFilter && room.id !== roomFilter) {
@@ -229,11 +335,16 @@ async function readInbox(
229
335
  continue;
230
336
  }
231
337
  member = true;
338
+ queuedTs[room.id] = entry.lastQueuedTs ?? 0;
232
339
  const lastRead = entry.lastReadTs ?? 0;
233
340
  for (const m of room.messages) {
341
+ const isSelf =
342
+ m.senderSessionID !== undefined
343
+ ? m.senderSessionID === sessionID
344
+ : m.senderId === entry.name;
234
345
  if (
235
346
  m.createdAt > lastRead &&
236
- (!excludeSelf || m.senderId !== entry.name)
347
+ (!excludeSelf || !isSelf)
237
348
  ) {
238
349
  out.push({
239
350
  id: m.id,
@@ -246,13 +357,16 @@ async function readInbox(
246
357
  }
247
358
  }
248
359
  }
249
- return { member, items: out };
360
+ return { member, items: out, queuedTs };
250
361
  });
251
362
  }
252
363
 
253
364
  async function handle(req: Request): Promise<Response> {
254
365
  const url = new URL(req.url);
255
366
  const p = url.pathname;
367
+ if (req.method === "GET" && p === "/") {
368
+ return Response.redirect(new URL("/chat", url).toString(), 302);
369
+ }
256
370
  if (req.method === "GET" && p === "/chat") {
257
371
  // ponytail: the human-facing chat page; APIs stay token-gated, the page
258
372
  // itself is a static shell
@@ -323,9 +437,14 @@ async function handle(req: Request): Promise<Response> {
323
437
  serverUrl: "",
324
438
  apiPrefix: "/api",
325
439
  name: owner,
440
+ directory: body.directory || undefined,
326
441
  // ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
327
442
  host: body.host ?? "",
328
- lastReadTs: Date.now(),
443
+ lastReadTs: Math.max(
444
+ Date.now(),
445
+ created.messages.at(-1)?.createdAt ?? 0,
446
+ ),
447
+ lastQueuedTs: 0,
329
448
  };
330
449
  await saveRegistry(reg);
331
450
  }
@@ -361,17 +480,64 @@ async function handle(req: Request): Promise<Response> {
361
480
  // watermark (sessionIDs are unguessable UUIDs and never exposed);
362
481
  // accepted as a limitation until real session auth exists
363
482
  const body = (await req.json()) as Record<string, unknown>;
364
- const ts = Number(body.ts ?? 0);
365
- touchActive(String(body.sessionID ?? "")); // poll 推进 = 活跃
366
- await enqueue(async () => {
483
+ const ts = Number(body.ts);
484
+ const roomId = String(body.roomId ?? "");
485
+ const sessionID = String(body.sessionID ?? "");
486
+ if (
487
+ body.ts === undefined ||
488
+ body.ts === null ||
489
+ !roomId ||
490
+ !sessionID ||
491
+ !Number.isFinite(ts)
492
+ ) {
493
+ return json({ error: "roomId/sessionID/finite ts are required" }, 400);
494
+ }
495
+ const updated = await enqueue(async () => {
367
496
  const reg = await loadRegistry();
368
- const entry = reg[String(body.roomId)]?.[String(body.sessionID)];
369
- // ponytail: NaN would poison the watermark (all comparisons false)
370
- if (entry && Number.isFinite(ts)) {
371
- entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
372
- await saveRegistry(reg);
497
+ const entry = reg[roomId]?.[sessionID];
498
+ if (!entry) {
499
+ return false;
373
500
  }
501
+ entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
502
+ await saveRegistry(reg);
503
+ clearPendingAdmission(sessionID, roomId, ts);
504
+ return true;
374
505
  });
506
+ if (!updated) {
507
+ return json({ error: "registry entry not found" }, 404);
508
+ }
509
+ touchActive(sessionID); // poll 推进 = 活跃
510
+ return json({ ok: true });
511
+ }
512
+ if (req.method === "POST" && p === "/queued") {
513
+ const body = (await req.json()) as Record<string, unknown>;
514
+ const ts = Number(body.ts);
515
+ const roomId = String(body.roomId ?? "");
516
+ const sessionID = String(body.sessionID ?? "");
517
+ if (
518
+ body.ts === undefined ||
519
+ body.ts === null ||
520
+ !roomId ||
521
+ !sessionID ||
522
+ !Number.isFinite(ts)
523
+ ) {
524
+ return json({ error: "roomId/sessionID/finite ts are required" }, 400);
525
+ }
526
+ const updated = await enqueue(async () => {
527
+ const reg = await loadRegistry();
528
+ const entry = reg[roomId]?.[sessionID];
529
+ if (!entry) {
530
+ return false;
531
+ }
532
+ entry.lastQueuedTs = Math.max(entry.lastQueuedTs ?? 0, ts);
533
+ await saveRegistry(reg);
534
+ clearPendingAdmission(sessionID, roomId, ts);
535
+ return true;
536
+ });
537
+ if (!updated) {
538
+ return json({ error: "registry entry not found" }, 404);
539
+ }
540
+ touchActive(sessionID);
375
541
  return json({ ok: true });
376
542
  }
377
543
  if (req.method === "POST" && p === "/active") {
@@ -440,6 +606,8 @@ async function handle(req: Request): Promise<Response> {
440
606
  if (!already) {
441
607
  svc.addEvent(roomId, `${name} joined the room`);
442
608
  }
609
+ const latestMessageTs =
610
+ svc.getMessages(roomId).at(-1)?.createdAt ?? 0;
443
611
  regRoom[sessionID] = {
444
612
  // ponytail: central mode self-pulls the inbox; no cross-host URL.
445
613
  // Re-join must not rewind the read watermark (unread messages
@@ -447,9 +615,13 @@ async function handle(req: Request): Promise<Response> {
447
615
  serverUrl: "",
448
616
  apiPrefix: "/api",
449
617
  name,
618
+ directory: body.directory || undefined,
450
619
  // ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
451
620
  host: body.host ?? "",
452
- lastReadTs: regRoom[sessionID]?.lastReadTs ?? Date.now(),
621
+ lastQueuedTs: regRoom[sessionID]?.lastQueuedTs,
622
+ lastReadTs:
623
+ regRoom[sessionID]?.lastReadTs ??
624
+ Math.max(Date.now(), latestMessageTs),
453
625
  };
454
626
  await saveRegistry(reg);
455
627
  return svc.getRoom(roomId);
@@ -492,7 +664,7 @@ async function handle(req: Request): Promise<Response> {
492
664
  const room = await mutate(async (svc) => {
493
665
  const reg = await loadRegistry();
494
666
  const sender = reg[roomId]?.[sessionID]?.name ?? sessionID;
495
- svc.sendMessage(roomId, sender, text);
667
+ svc.sendMessage(roomId, sender, text, sessionID);
496
668
  return svc.getRoom(roomId);
497
669
  });
498
670
  touchActive(sessionID); // 发送者活跃
@@ -502,10 +674,9 @@ async function handle(req: Request): Promise<Response> {
502
674
  void wakeMentionedSessions(
503
675
  roomId,
504
676
  room.name,
505
- sent.senderId,
506
677
  text,
507
678
  sessionID,
508
- sent.createdAt,
679
+ sent,
509
680
  );
510
681
  }
511
682
  return json(serializeRoom(room), 201);
@@ -530,7 +701,13 @@ async function handle(req: Request): Promise<Response> {
530
701
  return Object.fromEntries(
531
702
  Object.entries(entries).map(([sid, e]) => [
532
703
  sid,
533
- { name: e.name, lastReadTs: e.lastReadTs ?? 0, host: e.host ?? "" },
704
+ {
705
+ name: e.name,
706
+ lastReadTs: e.lastReadTs ?? 0,
707
+ lastQueuedTs: e.lastQueuedTs ?? 0,
708
+ host: e.host ?? "",
709
+ directory: e.directory,
710
+ },
534
711
  ]),
535
712
  );
536
713
  });