@alexsun-top/opencode-chat-room 0.1.1 → 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.
package/README.md CHANGED
@@ -57,17 +57,17 @@ On the server machine, install Bun first. `npx`, `pnpx`, and `bunx` only execute
57
57
 
58
58
  ```bash
59
59
  # Show CLI options:
60
- npx --yes --package=@alexsun-top/opencode-chat-room@0.1.1 -- opencode-chat-room --help
60
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --help
61
61
 
62
62
  # Start the local central server (choose any one runner):
63
- npx --yes --package=@alexsun-top/opencode-chat-room@0.1.1 -- opencode-chat-room --host 0.0.0.0 --port 4399
64
- pnpx --package=@alexsun-top/opencode-chat-room@0.1.1 opencode-chat-room --host 0.0.0.0 --port 4399
65
- bunx @alexsun-top/opencode-chat-room@0.1.1 --host 0.0.0.0 --port 4399 --token secret
63
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
64
+ pnpx --package=@alexsun-top/opencode-chat-room@0.1.2 opencode-chat-room --host 0.0.0.0 --port 4399
65
+ bunx @alexsun-top/opencode-chat-room@0.1.2 --host 0.0.0.0 --port 4399 --token secret
66
66
 
67
67
  # Environment variables also work; CLI options take precedence:
68
68
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
69
69
  CHAT_ROOM_SERVER_TOKEN=secret \
70
- bunx @alexsun-top/opencode-chat-room@0.1.1
70
+ bunx @alexsun-top/opencode-chat-room@0.1.2
71
71
 
72
72
  # Local checkout:
73
73
  bun install
package/README.zh-CN.md CHANGED
@@ -57,17 +57,17 @@
57
57
 
58
58
  ```bash
59
59
  # 查看 CLI 选项:
60
- npx --yes --package=@alexsun-top/opencode-chat-room@0.1.1 -- opencode-chat-room --help
60
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --help
61
61
 
62
62
  # 启动本地中心服务器(三选一):
63
- npx --yes --package=@alexsun-top/opencode-chat-room@0.1.1 -- opencode-chat-room --host 0.0.0.0 --port 4399
64
- pnpx --package=@alexsun-top/opencode-chat-room@0.1.1 opencode-chat-room --host 0.0.0.0 --port 4399
65
- bunx @alexsun-top/opencode-chat-room@0.1.1 --host 0.0.0.0 --port 4399 --token secret
63
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.1.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
64
+ pnpx --package=@alexsun-top/opencode-chat-room@0.1.2 opencode-chat-room --host 0.0.0.0 --port 4399
65
+ bunx @alexsun-top/opencode-chat-room@0.1.2 --host 0.0.0.0 --port 4399 --token secret
66
66
 
67
67
  # 也可以使用环境变量;CLI 参数优先:
68
68
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
69
69
  CHAT_ROOM_SERVER_TOKEN=secret \
70
- bunx @alexsun-top/opencode-chat-room@0.1.1
70
+ bunx @alexsun-top/opencode-chat-room@0.1.2
71
71
 
72
72
  # 本地 checkout:
73
73
  bun install
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -42,6 +42,7 @@
42
42
  },
43
43
  "dependencies": {
44
44
  "@opencode-ai/plugin": "^1.18.16",
45
+ "@opencode-ai/sdk": "1.18.16",
45
46
  "zod": "4.1.8"
46
47
  }
47
48
  }
package/plugin.ts CHANGED
@@ -1,10 +1,9 @@
1
- import { tool } from "@opencode-ai/plugin";
1
+ import { tool, type PluginInput } from "@opencode-ai/plugin";
2
2
  import { z } from "zod";
3
3
  import { promises as fs } from "node:fs";
4
4
  import path from "node:path";
5
5
  import RoomService, { RoomError, type Message } from "./src/room-service";
6
6
  import {
7
- authHeader,
8
7
  enqueue,
9
8
  formatNotificationLines,
10
9
  formatRoom,
@@ -20,10 +19,25 @@ import {
20
19
  type Registry,
21
20
  type RegistryEntry,
22
21
  } from "./src/store";
23
- import { centerAction, checkCenterInbox, wakeSessions } from "./src/center-client";
22
+ import {
23
+ centerAction,
24
+ checkCenterInbox,
25
+ createQueueTransport,
26
+ sendQueue,
27
+ wakeSessions,
28
+ type QueueTransport,
29
+ } from "./src/center-client";
30
+ import {
31
+ clearPendingAdmission,
32
+ getOrCreatePendingAdmission,
33
+ markPendingAdmissionAdmitted,
34
+ rejectPendingAdmission,
35
+ } from "./src/queue";
24
36
 
25
37
  // captured once at server start; registry push notifications route to it
26
38
  let selfServerUrl = "";
39
+ let selfDirectory = "";
40
+ let queueTransport: QueueTransport = createQueueTransport();
27
41
 
28
42
  // ponytail: central-mode in-process wake timer (see server() below)
29
43
  let wakeTimer: ReturnType<typeof setInterval> | null = null;
@@ -32,7 +46,7 @@ let wakeTimer: ReturnType<typeof setInterval> | null = null;
32
46
  // central server); unset = standalone local-file mode
33
47
  const centerUrl = process.env.CHAT_ROOM_SERVER_URL ?? "";
34
48
  const centerToken = process.env.CHAT_ROOM_SERVER_TOKEN ?? "";
35
- const centerOpts = { center: centerUrl, token: centerToken };
49
+ const centerOpts = { center: centerUrl, token: centerToken, directory: "" };
36
50
  // ponytail: optional常驻 opencode serve 地址——配置了才能对已退出 session
37
51
  // 做进程内唤起;未配置则不唤起(用户要求)
38
52
  const serveWakeUrl = process.env.CHAT_ROOM_WAKE_SERVE_URL ?? "";
@@ -67,16 +81,22 @@ async function registerSelf(
67
81
  return enqueue(async () => {
68
82
  try {
69
83
  const reg = await loadRegistry();
84
+ const latestMessageTs =
85
+ (await loadRooms()).find((room) => room.id === roomId)?.messages.at(-1)
86
+ ?.createdAt ?? 0;
70
87
  const regRoom = (reg[roomId] =
71
88
  reg[roomId] ?? Object.create(null) as Record<string, RegistryEntry>);
72
89
  regRoom[sessionID] = {
73
90
  serverUrl: selfServerUrl,
74
91
  apiPrefix: "/api",
75
92
  name,
93
+ directory: selfDirectory || undefined,
76
94
  // ponytail: re-join must not rewind the read watermark (unread
77
95
  // messages before the re-join would be silently dropped); a first
78
96
  // join starts reading at join time
79
- lastReadTs: regRoom[sessionID]?.lastReadTs ?? Date.now(),
97
+ lastReadTs:
98
+ regRoom[sessionID]?.lastReadTs ??
99
+ Math.max(Date.now(), latestMessageTs),
80
100
  };
81
101
  await saveRegistry(reg);
82
102
  } catch {
@@ -115,9 +135,12 @@ async function logNotify(
115
135
  ): Promise<void> {
116
136
  const lines = results.map((r) => {
117
137
  const head = `[${timeOf(Date.now())}] room=${roomId}`;
118
- return r.status === "fulfilled"
138
+ if (r.status === "rejected") {
139
+ return `${head} FAIL ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`;
140
+ }
141
+ return r.value.status >= 200 && r.value.status < 300
119
142
  ? `${head} OK ${r.value.status} ${r.value.url}`
120
- : `${head} FAIL ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`;
143
+ : `${head} FAIL ${r.value.status} ${r.value.url}`;
121
144
  });
122
145
  await fs
123
146
  .appendFile(notifyPath(), lines.join("\n") + "\n", "utf8")
@@ -129,7 +152,7 @@ async function bumpLastRead(
129
152
  roomId: string,
130
153
  sessionID: string,
131
154
  ts: number,
132
- ): Promise<void> {
155
+ ): Promise<boolean> {
133
156
  return enqueue(async () => {
134
157
  try {
135
158
  const reg = await loadRegistry();
@@ -138,9 +161,13 @@ async function bumpLastRead(
138
161
  // never rewind: an older in-flight push must not lower the watermark
139
162
  entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
140
163
  await saveRegistry(reg);
164
+ clearPendingAdmission(sessionID, roomId, ts);
165
+ return true;
141
166
  }
167
+ return false;
142
168
  } catch {
143
169
  // best-effort: an unpromoted read position only means poll repeats
170
+ return false;
144
171
  }
145
172
  });
146
173
  }
@@ -148,69 +175,191 @@ async function bumpLastRead(
148
175
  // ponytail: one push carries EVERY unread message for the target (not just
149
176
  // the latest), so advancing the watermark on success never skips a message
150
177
  // whose earlier push failed. Event-only pushes (empty messages) don't bump.
151
- // ponytail: push is best-effort; poll remains the fallback; log every attempt for debugging
178
+ type NotifyBatch = {
179
+ roomId: string;
180
+ roomName: string;
181
+ messages: Message[];
182
+ };
183
+
184
+ type NotifyAttempt = { url: string; status: number };
185
+
186
+ type NotifyTargetQueue = {
187
+ latest: NotifyBatch | undefined;
188
+ latestTs: number;
189
+ running: Promise<NotifyAttempt[]>;
190
+ };
191
+
192
+ const notifyQueues = new Map<string, NotifyTargetQueue>();
193
+
194
+ function notifyBatchMaxTs(batch: NotifyBatch): number {
195
+ return batch.messages.reduce(
196
+ (maxTs, message) => Math.max(maxTs, message.createdAt),
197
+ 0,
198
+ );
199
+ }
200
+
201
+ async function notifyTarget(
202
+ sessionID: string,
203
+ batch: NotifyBatch,
204
+ ): Promise<NotifyAttempt | undefined> {
205
+ const reg = await loadRegistry();
206
+ const entry = reg[batch.roomId]?.[sessionID];
207
+ if (!entry?.serverUrl) {
208
+ return undefined;
209
+ }
210
+ const unread = batch.messages.filter(
211
+ (m) =>
212
+ m.createdAt > (entry.lastReadTs ?? 0) &&
213
+ (m.senderSessionID !== undefined
214
+ ? m.senderSessionID !== sessionID
215
+ : m.senderId !== entry.name),
216
+ );
217
+ const { lines, capped } = formatNotificationLines(unread);
218
+ const prompt =
219
+ unread.length > 0
220
+ ? `<notification>\nNew messages in room ${batch.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`
221
+ : `<notification>\n${NOTIFY_INSTRUCTION}\n</notification>`;
222
+ const maxTs = unread.reduce(
223
+ (mx, message) => Math.max(mx, message.createdAt),
224
+ 0,
225
+ );
226
+ const admissionItems = unread.length > 0 ? unread : batch.messages.slice(-1);
227
+ const admission = getOrCreatePendingAdmission(
228
+ sessionID,
229
+ batch.roomId,
230
+ admissionItems,
231
+ prompt,
232
+ maxTs,
233
+ capped,
234
+ );
235
+ const base = new URL(entry.serverUrl);
236
+ const prefix = (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "");
237
+ const url = `${base.origin}/${prefix}/session/${sessionID}/prompt`;
238
+ if (admission.state === "admitted") {
239
+ if (admission.capped) {
240
+ if (maxTs <= admission.maxTs) {
241
+ return { url, status: 200 };
242
+ }
243
+ } else {
244
+ if (admission.maxTs <= 0) {
245
+ return { url, status: 200 };
246
+ }
247
+ await bumpLastRead(batch.roomId, sessionID, admission.maxTs);
248
+ return { url, status: 200 };
249
+ }
250
+ }
251
+ const result = await sendQueue(
252
+ {
253
+ ...queueTransport,
254
+ serverUrl: entry.serverUrl,
255
+ directory: entry.directory ?? queueTransport.directory,
256
+ },
257
+ sessionID,
258
+ admission.prompt,
259
+ admission.id,
260
+ );
261
+ if (result !== "delivered") {
262
+ if (result === "rejected") {
263
+ rejectPendingAdmission(sessionID, batch.roomId, admission.id);
264
+ }
265
+ return { url, status: result === "unreachable" ? 0 : 400 };
266
+ }
267
+ markPendingAdmissionAdmitted(sessionID, batch.roomId, admission.id);
268
+ if (admission.maxTs > 0 && !admission.capped) {
269
+ await bumpLastRead(batch.roomId, sessionID, admission.maxTs);
270
+ }
271
+ return { url, status: 200 };
272
+ }
273
+
274
+ function queueNotifyTarget(
275
+ sessionID: string,
276
+ batch: NotifyBatch,
277
+ ): Promise<NotifyAttempt[]> {
278
+ const key = JSON.stringify([batch.roomId, sessionID]);
279
+ const existing = notifyQueues.get(key);
280
+ if (existing) {
281
+ const maxTs = notifyBatchMaxTs(batch);
282
+ if (maxTs > existing.latestTs) {
283
+ existing.latest = batch;
284
+ existing.latestTs = maxTs;
285
+ }
286
+ return existing.running;
287
+ }
288
+
289
+ const state: NotifyTargetQueue = {
290
+ latest: batch,
291
+ latestTs: notifyBatchMaxTs(batch),
292
+ running: Promise.resolve([] as NotifyAttempt[]),
293
+ };
294
+ const running = (async (): Promise<NotifyAttempt[]> => {
295
+ const attempts: NotifyAttempt[] = [];
296
+ let failed = false;
297
+ let firstError: unknown;
298
+ while (state.latest) {
299
+ const current = state.latest;
300
+ state.latest = undefined;
301
+ try {
302
+ const attempt = await notifyTarget(sessionID, current);
303
+ if (attempt) {
304
+ attempts.push(attempt);
305
+ }
306
+ } catch (error) {
307
+ if (!failed) {
308
+ firstError = error;
309
+ failed = true;
310
+ }
311
+ }
312
+ }
313
+ if (failed) {
314
+ throw firstError;
315
+ }
316
+ return attempts;
317
+ })();
318
+ state.running = running;
319
+ notifyQueues.set(key, state);
320
+ const cleanup = () => {
321
+ if (notifyQueues.get(key) === state) {
322
+ notifyQueues.delete(key);
323
+ }
324
+ };
325
+ void running.then(cleanup, cleanup);
326
+ return running;
327
+ }
328
+
152
329
  async function notifyRoom(
153
330
  roomId: string,
154
331
  roomName: string,
155
- body: string,
332
+ _body: string,
156
333
  selfSessionID: string,
157
334
  messages: Message[],
158
335
  ): Promise<void> {
159
- try {
160
- const reg = await loadRegistry();
161
- const targets = Object.entries(reg[roomId] ?? {}).filter(
162
- ([sessionID, entry]) => sessionID !== selfSessionID && entry.serverUrl,
163
- );
164
- const auth = authHeader();
165
- const results = await Promise.allSettled(
166
- targets.map(async ([sessionID, entry]) => {
167
- const unread = messages.filter(
168
- (m) => m.createdAt > (entry.lastReadTs ?? 0) && m.senderId !== entry.name,
169
- );
170
- const { lines, capped } = formatNotificationLines(unread);
171
- const prompt =
172
- unread.length > 0
173
- ? `<notification>\nNew messages in room ${roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`
174
- : `<notification>\n${NOTIFY_INSTRUCTION}\n</notification>`;
175
- const base = new URL(entry.serverUrl);
176
- const prefix = (entry.apiPrefix || "/api").replace(/^\/+|\/+$/g, "");
177
- const url = `${base.origin}/${prefix}/session/${sessionID}/prompt`;
178
- const res = await fetch(url, {
179
- method: "POST",
180
- headers: {
181
- "Content-Type": "application/json",
182
- ...(auth ? { Authorization: auth } : {}),
183
- },
184
- body: JSON.stringify({ prompt, delivery: "queue" }),
185
- });
186
- return {
187
- url,
188
- status: res.status,
189
- sessionID,
190
- // ponytail: a capped push must not advance the watermark — the
191
- // folded-out messages would become permanently unreadable
192
- maxTs:
193
- unread.length > 0 && !capped
194
- ? Math.max(...unread.map((m) => m.createdAt))
195
- : undefined,
196
- };
197
- }),
198
- );
199
- // mark pushed messages as read only on 2xx; a failed push stays unread
200
- // so the receiver's next poll picks it up
201
- for (const r of results) {
202
- if (
203
- r.status === "fulfilled" &&
204
- r.value.status >= 200 &&
205
- r.value.status < 300 &&
206
- r.value.maxTs !== undefined
207
- ) {
208
- void bumpLastRead(roomId, r.value.sessionID, r.value.maxTs);
336
+ const reg = await loadRegistry();
337
+ const targets = Object.entries(reg[roomId] ?? {}).filter(
338
+ ([sessionID, entry]) => sessionID !== selfSessionID && entry.serverUrl,
339
+ );
340
+ const batch: NotifyBatch = { roomId, roomName, messages };
341
+ const results = await Promise.allSettled(
342
+ targets.map(([sessionID]) => queueNotifyTarget(sessionID, batch)),
343
+ );
344
+ const logResults: PromiseSettledResult<NotifyAttempt>[] = [];
345
+ let failed = false;
346
+ let firstError: unknown;
347
+ for (const result of results) {
348
+ if (result.status === "fulfilled") {
349
+ for (const attempt of result.value) {
350
+ logResults.push({ status: "fulfilled", value: attempt });
351
+ }
352
+ } else {
353
+ logResults.push({ status: "rejected", reason: result.reason });
354
+ if (!failed) {
355
+ firstError = result.reason;
356
+ failed = true;
209
357
  }
210
358
  }
211
- await logNotify(roomId, results);
212
- } catch {
213
- // registry/io failure: nothing to log, fall back to poll
359
+ }
360
+ await logNotify(roomId, logResults);
361
+ if (failed) {
362
+ throw firstError;
214
363
  }
215
364
  }
216
365
 
@@ -232,7 +381,7 @@ const room = tool({
232
381
  // (skipped for poll: poll itself pulls the inbox, so racing the
233
382
  // fire-and-forget check would read the position it just advanced)
234
383
  if (args.action !== "poll") {
235
- void checkCenterInbox(centerOpts, context.sessionID, selfServerUrl);
384
+ void checkCenterInbox(centerOpts, context.sessionID, queueTransport);
236
385
  }
237
386
  return await centerAction(centerOpts, args, context.sessionID);
238
387
  }
@@ -316,7 +465,7 @@ const room = tool({
316
465
  NOTIFY_INSTRUCTION,
317
466
  context.sessionID,
318
467
  room.messages,
319
- );
468
+ ).catch(() => {});
320
469
  }
321
470
  return formatRoom(svc, room);
322
471
  }
@@ -338,7 +487,7 @@ const room = tool({
338
487
  NOTIFY_INSTRUCTION,
339
488
  context.sessionID,
340
489
  room.messages,
341
- );
490
+ ).catch(() => {});
342
491
  }
343
492
  leftRoomId = args.roomId;
344
493
  return `left room ${args.roomId}`;
@@ -371,7 +520,12 @@ const room = tool({
371
520
  if (!args.text?.trim()) {
372
521
  return "error: text is required";
373
522
  }
374
- const msg = svc.sendMessage(args.roomId, selfName, args.text);
523
+ const msg = svc.sendMessage(
524
+ args.roomId,
525
+ selfName,
526
+ args.text,
527
+ context.sessionID,
528
+ );
375
529
  const room = svc.getRoom(args.roomId);
376
530
  void notifyRoom(
377
531
  args.roomId,
@@ -379,7 +533,7 @@ const room = tool({
379
533
  NOTIFY_INSTRUCTION,
380
534
  context.sessionID,
381
535
  room.messages,
382
- );
536
+ ).catch(() => {});
383
537
  return `sent: ${args.text}\n${formatRoom(svc, room)}`;
384
538
  }
385
539
  case "poll": {
@@ -446,8 +600,11 @@ async function config(cfg: any) {
446
600
 
447
601
  export default {
448
602
  id: "chat-room",
449
- server: async (input: { serverUrl: URL | string }) => {
450
- selfServerUrl = String(input.serverUrl);
603
+ server: async (input: PluginInput) => {
604
+ queueTransport = createQueueTransport(input);
605
+ selfServerUrl = queueTransport.serverUrl ?? "";
606
+ selfDirectory = input.directory;
607
+ centerOpts.directory = selfDirectory;
451
608
  if (centerUrl) {
452
609
  // ponytail: in-process wake watcher — sweep the central server every
453
610
  // 10s and self-push queue notifications to any session (including
@@ -457,9 +614,9 @@ export default {
457
614
  if (wakeTimer) {
458
615
  clearInterval(wakeTimer); // HMR/reload must not accumulate timers
459
616
  }
460
- void wakeSessions(centerOpts, selfServerUrl, serveWakeUrl);
617
+ void wakeSessions(centerOpts, queueTransport, serveWakeUrl);
461
618
  wakeTimer = setInterval(() => {
462
- void wakeSessions(centerOpts, selfServerUrl, serveWakeUrl);
619
+ void wakeSessions(centerOpts, queueTransport, serveWakeUrl);
463
620
  }, 10000);
464
621
  }
465
622
  return {
@@ -477,7 +634,7 @@ export default {
477
634
  void checkCenterInbox(
478
635
  centerOpts,
479
636
  input.sessionID,
480
- selfServerUrl,
637
+ queueTransport,
481
638
  );
482
639
  },
483
640
  }