@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/plugin.ts ADDED
@@ -0,0 +1,487 @@
1
+ import { tool } from "@opencode-ai/plugin";
2
+ import { z } from "zod";
3
+ import { promises as fs } from "node:fs";
4
+ import path from "node:path";
5
+ import RoomService, { RoomError, type Message } from "./src/room-service";
6
+ import {
7
+ authHeader,
8
+ enqueue,
9
+ formatNotificationLines,
10
+ formatRoom,
11
+ identity,
12
+ loadRegistry,
13
+ loadRooms,
14
+ NOTIFY_INSTRUCTION,
15
+ saveRegistry,
16
+ saveRooms,
17
+ senderName,
18
+ statePath,
19
+ timeOf,
20
+ type Registry,
21
+ type RegistryEntry,
22
+ } from "./src/store";
23
+ import { centerAction, checkCenterInbox, wakeSessions } from "./src/center-client";
24
+
25
+ // captured once at server start; registry push notifications route to it
26
+ let selfServerUrl = "";
27
+
28
+ // ponytail: central-mode in-process wake timer (see server() below)
29
+ let wakeTimer: ReturnType<typeof setInterval> | null = null;
30
+
31
+ // ponytail: CHAT_ROOM_SERVER_URL switches to central mode (all state on a
32
+ // central server); unset = standalone local-file mode
33
+ const centerUrl = process.env.CHAT_ROOM_SERVER_URL ?? "";
34
+ const centerToken = process.env.CHAT_ROOM_SERVER_TOKEN ?? "";
35
+ const centerOpts = { center: centerUrl, token: centerToken };
36
+ // ponytail: optional常驻 opencode serve 地址——配置了才能对已退出 session
37
+ // 做进程内唤起;未配置则不唤起(用户要求)
38
+ const serveWakeUrl = process.env.CHAT_ROOM_WAKE_SERVE_URL ?? "";
39
+
40
+ async function withRooms<T>(
41
+ fn: (svc: RoomService) => T,
42
+ readOnly = false,
43
+ ): Promise<T> {
44
+ return enqueue(async () => {
45
+ const svc = new RoomService();
46
+ svc.hydrate(await loadRooms());
47
+ try {
48
+ const result = fn(svc);
49
+ if (!readOnly) {
50
+ await saveRooms(svc);
51
+ }
52
+ return result;
53
+ } catch (err) {
54
+ if (err instanceof RoomError) {
55
+ return `error: ${err.message}` as unknown as T;
56
+ }
57
+ throw err;
58
+ }
59
+ });
60
+ }
61
+
62
+ async function registerSelf(
63
+ roomId: string,
64
+ sessionID: string,
65
+ name = identity(),
66
+ ): Promise<void> {
67
+ return enqueue(async () => {
68
+ try {
69
+ const reg = await loadRegistry();
70
+ const regRoom = (reg[roomId] =
71
+ reg[roomId] ?? Object.create(null) as Record<string, RegistryEntry>);
72
+ regRoom[sessionID] = {
73
+ serverUrl: selfServerUrl,
74
+ apiPrefix: "/api",
75
+ name,
76
+ // ponytail: re-join must not rewind the read watermark (unread
77
+ // messages before the re-join would be silently dropped); a first
78
+ // join starts reading at join time
79
+ lastReadTs: regRoom[sessionID]?.lastReadTs ?? Date.now(),
80
+ };
81
+ await saveRegistry(reg);
82
+ } catch {
83
+ // ponytail: registry failure only disables push, never blocks room ops
84
+ }
85
+ });
86
+ }
87
+
88
+ async function unregisterSelf(
89
+ roomId: string,
90
+ sessionID: string,
91
+ ): Promise<void> {
92
+ return enqueue(async () => {
93
+ try {
94
+ const reg = await loadRegistry();
95
+ if (reg[roomId]) {
96
+ delete reg[roomId][sessionID];
97
+ if (Object.keys(reg[roomId]).length === 0) {
98
+ delete reg[roomId];
99
+ }
100
+ await saveRegistry(reg);
101
+ }
102
+ } catch {
103
+ // ponytail: registry failure only disables push, never blocks room ops
104
+ }
105
+ });
106
+ }
107
+
108
+ function notifyPath(): string {
109
+ return path.join(path.dirname(statePath()), "notify.log");
110
+ }
111
+
112
+ async function logNotify(
113
+ roomId: string,
114
+ results: ReadonlyArray<PromiseSettledResult<{ url: string; status: number }>>,
115
+ ): Promise<void> {
116
+ const lines = results.map((r) => {
117
+ const head = `[${timeOf(Date.now())}] room=${roomId}`;
118
+ return r.status === "fulfilled"
119
+ ? `${head} OK ${r.value.status} ${r.value.url}`
120
+ : `${head} FAIL ${r.reason instanceof Error ? r.reason.message : String(r.reason)}`;
121
+ });
122
+ await fs
123
+ .appendFile(notifyPath(), lines.join("\n") + "\n", "utf8")
124
+ .catch(() => {});
125
+ }
126
+
127
+ // ponytail: push is best-effort; poll remains the fallback; log every attempt for debugging
128
+ async function bumpLastRead(
129
+ roomId: string,
130
+ sessionID: string,
131
+ ts: number,
132
+ ): Promise<void> {
133
+ return enqueue(async () => {
134
+ try {
135
+ const reg = await loadRegistry();
136
+ const entry = reg[roomId]?.[sessionID];
137
+ if (entry) {
138
+ // never rewind: an older in-flight push must not lower the watermark
139
+ entry.lastReadTs = Math.max(entry.lastReadTs ?? 0, ts);
140
+ await saveRegistry(reg);
141
+ }
142
+ } catch {
143
+ // best-effort: an unpromoted read position only means poll repeats
144
+ }
145
+ });
146
+ }
147
+
148
+ // ponytail: one push carries EVERY unread message for the target (not just
149
+ // the latest), so advancing the watermark on success never skips a message
150
+ // 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
152
+ async function notifyRoom(
153
+ roomId: string,
154
+ roomName: string,
155
+ body: string,
156
+ selfSessionID: string,
157
+ messages: Message[],
158
+ ): 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);
209
+ }
210
+ }
211
+ await logNotify(roomId, results);
212
+ } catch {
213
+ // registry/io failure: nothing to log, fall back to poll
214
+ }
215
+ }
216
+
217
+ const READ_ONLY_ACTIONS = new Set(["list", "members", "poll"]);
218
+
219
+ const room = tool({
220
+ description:
221
+ "Chat room operations: create, join, leave and list rooms; send and poll messages; list members",
222
+ args: {
223
+ action: z.enum(["create", "join", "leave", "list", "send", "poll", "members"]),
224
+ name: z.string().max(64).optional(),
225
+ roomId: z.string().optional(),
226
+ text: z.string().max(2000).optional(),
227
+ },
228
+ execute: async (args, context) => {
229
+ try {
230
+ if (centerUrl) {
231
+ // ponytail: central mode — self-pull inbox first, then act via HTTP
232
+ // (skipped for poll: poll itself pulls the inbox, so racing the
233
+ // fire-and-forget check would read the position it just advanced)
234
+ if (args.action !== "poll") {
235
+ void checkCenterInbox(centerOpts, context.sessionID, selfServerUrl);
236
+ }
237
+ return await centerAction(centerOpts, args, context.sessionID);
238
+ }
239
+ // ponytail: act as the identity this session registered with on join
240
+ let selfName = identity();
241
+ let joinPrevName: string | undefined;
242
+ let joinPrevShared = false;
243
+ let leaveNameShared = false;
244
+ let pollLastRead = 0;
245
+ let pollEntry = false;
246
+ if (args.roomId) {
247
+ const reg = await loadRegistry().catch(() => ({} as Registry));
248
+ if (args.action === "send" || args.action === "leave") {
249
+ selfName = reg[args.roomId]?.[context.sessionID]?.name ?? selfName;
250
+ }
251
+ if (args.action === "leave") {
252
+ // ora-2 M2: 其他 session 仍持有该名字时,离开只删条目不删参与者
253
+ leaveNameShared = Object.entries(reg[args.roomId] ?? {}).some(
254
+ ([sid, e]) => sid !== context.sessionID && e.name === selfName,
255
+ );
256
+ }
257
+ if (args.action === "join") {
258
+ joinPrevName = reg[args.roomId]?.[context.sessionID]?.name;
259
+ // ponytail: don't retire the old participant if another session
260
+ // still uses it (default same-host identity is shared)
261
+ joinPrevShared =
262
+ joinPrevName !== undefined &&
263
+ Object.entries(reg[args.roomId] ?? {}).some(
264
+ ([sid, e]) => sid !== context.sessionID && e.name === joinPrevName,
265
+ );
266
+ }
267
+ if (args.action === "poll") {
268
+ pollEntry = reg[args.roomId]?.[context.sessionID] !== undefined;
269
+ selfName = reg[args.roomId]?.[context.sessionID]?.name ?? selfName;
270
+ pollLastRead = reg[args.roomId]?.[context.sessionID]?.lastReadTs ?? 0;
271
+ }
272
+ }
273
+ let actedRoomId: string | undefined;
274
+ let newMemberName: string | undefined;
275
+ let leftRoomId: string | undefined;
276
+ let pollMaxTs: number | undefined;
277
+ const result = await withRooms<string>(
278
+ (svc) => {
279
+ switch (args.action) {
280
+ case "create": {
281
+ if (!args.name?.trim()) {
282
+ return "error: name is required";
283
+ }
284
+ const created = svc.createRoom(args.name.trim(), identity());
285
+ actedRoomId = created.id;
286
+ return formatRoom(svc, created);
287
+ }
288
+ case "join": {
289
+ if (!args.roomId) {
290
+ return "error: roomId is required";
291
+ }
292
+ const me = identity(args.name?.trim());
293
+ // ponytail: F5 — re-join under a new name retires the old
294
+ // participant, otherwise every rename leaks a ghost member;
295
+ // skipped when another session still holds the old name
296
+ if (
297
+ joinPrevName !== undefined &&
298
+ joinPrevName !== me &&
299
+ !joinPrevShared &&
300
+ svc.containsParticipant(args.roomId, joinPrevName)
301
+ ) {
302
+ svc.leaveRoom(args.roomId, joinPrevName);
303
+ }
304
+ const already = svc.containsParticipant(args.roomId, me);
305
+ svc.joinRoom(args.roomId, { id: me, name: me });
306
+ const room = svc.getRoom(args.roomId);
307
+ actedRoomId = args.roomId;
308
+ newMemberName = me;
309
+ if (!already) {
310
+ // ponytail: membership events live in the message stream, so
311
+ // the join notification rides the normal unread push
312
+ svc.addEvent(args.roomId, `${me} joined the room`);
313
+ void notifyRoom(
314
+ args.roomId,
315
+ room.name,
316
+ NOTIFY_INSTRUCTION,
317
+ context.sessionID,
318
+ room.messages,
319
+ );
320
+ }
321
+ return formatRoom(svc, room);
322
+ }
323
+ case "leave": {
324
+ if (!args.roomId) {
325
+ return "error: roomId is required";
326
+ }
327
+ // ponytail: ora-2 M2 — mirror the join guard: if another session
328
+ // still holds this name, remove only the registry entry, not the
329
+ // participant (or the sibling window breaks with NOT_JOINED);
330
+ // 也不广播假的 "left" 事件(参与者仍在场)
331
+ if (!leaveNameShared) {
332
+ svc.leaveRoom(args.roomId, selfName);
333
+ const room = svc.getRoom(args.roomId);
334
+ svc.addEvent(args.roomId, `${selfName} left the room`);
335
+ void notifyRoom(
336
+ args.roomId,
337
+ room.name,
338
+ NOTIFY_INSTRUCTION,
339
+ context.sessionID,
340
+ room.messages,
341
+ );
342
+ }
343
+ leftRoomId = args.roomId;
344
+ return `left room ${args.roomId}`;
345
+ }
346
+ case "list": {
347
+ const rooms = svc.listRooms();
348
+ if (rooms.length === 0) {
349
+ return "no rooms yet";
350
+ }
351
+ return rooms
352
+ .map(
353
+ (r) =>
354
+ `${r.id} (${r.name}): ${svc.getParticipants(r.id).length} members`,
355
+ )
356
+ .join("\n");
357
+ }
358
+ case "members": {
359
+ if (!args.roomId) {
360
+ return "error: roomId is required";
361
+ }
362
+ const members = svc.getParticipants(args.roomId);
363
+ return members.length > 0
364
+ ? members.map((m) => m.name).join("\n")
365
+ : "no members";
366
+ }
367
+ case "send": {
368
+ if (!args.roomId) {
369
+ return "error: roomId is required";
370
+ }
371
+ if (!args.text?.trim()) {
372
+ return "error: text is required";
373
+ }
374
+ const msg = svc.sendMessage(args.roomId, selfName, args.text);
375
+ const room = svc.getRoom(args.roomId);
376
+ void notifyRoom(
377
+ args.roomId,
378
+ room.name,
379
+ NOTIFY_INSTRUCTION,
380
+ context.sessionID,
381
+ room.messages,
382
+ );
383
+ return `sent: ${args.text}\n${formatRoom(svc, room)}`;
384
+ }
385
+ case "poll": {
386
+ if (!args.roomId) {
387
+ return "error: roomId is required";
388
+ }
389
+ // ponytail: gate on registry entry (session granularity) — a
390
+ // participant-id check would pass for any session sharing the
391
+ // same host identity
392
+ if (!pollEntry) {
393
+ return "error: not joined";
394
+ }
395
+ if (!svc.containsParticipant(args.roomId, selfName)) {
396
+ return "error: not joined";
397
+ }
398
+ // ponytail: only messages newer than this session's last read (or
399
+ // last successful push) — queue-notified messages don't repeat
400
+ const messages = svc
401
+ .getMessages(args.roomId)
402
+ .filter((m) => m.createdAt > pollLastRead);
403
+ if (messages.length === 0) {
404
+ return "no new messages";
405
+ }
406
+ pollMaxTs = messages.reduce(
407
+ (mx, m) => Math.max(mx, m.createdAt),
408
+ 0,
409
+ );
410
+ return messages
411
+ .map(
412
+ (m) =>
413
+ `[${timeOf(m.createdAt)}] ${senderName(svc, m)}: ${m.text}`,
414
+ )
415
+ .join("\n");
416
+ }
417
+ }
418
+ },
419
+ READ_ONLY_ACTIONS.has(args.action));
420
+ const joinedRoom = actedRoomId;
421
+ if (joinedRoom !== undefined) {
422
+ await registerSelf(joinedRoom, context.sessionID, newMemberName);
423
+ }
424
+ if (leftRoomId !== undefined) {
425
+ await unregisterSelf(leftRoomId, context.sessionID);
426
+ }
427
+ if (args.action === "poll" && pollMaxTs !== undefined && pollMaxTs > 0) {
428
+ await bumpLastRead(args.roomId!, context.sessionID, pollMaxTs);
429
+ }
430
+ return result;
431
+ } catch (err) {
432
+ return `error: ${err instanceof Error ? err.message : String(err)}`;
433
+ }
434
+ },
435
+ });
436
+
437
+ // ponytail: mutation of the passed config is enough for the SDK to pick up the command
438
+ async function config(cfg: any) {
439
+ cfg.command = cfg.command ?? {};
440
+ cfg.command["room"] = {
441
+ description: "Chat room: create/join/leave/list rooms, send and poll messages",
442
+ template:
443
+ "Use the room tool to handle the chat room command. Arguments: $ARGUMENTS",
444
+ };
445
+ }
446
+
447
+ export default {
448
+ id: "chat-room",
449
+ server: async (input: { serverUrl: URL | string }) => {
450
+ selfServerUrl = String(input.serverUrl);
451
+ if (centerUrl) {
452
+ // ponytail: in-process wake watcher — sweep the central server every
453
+ // 10s and self-push queue notifications to any session (including
454
+ // sleeping sub-agents in this process) that has unread messages; the
455
+ // central server itself has no opencode knowledge. 10s balances
456
+ // wake latency vs scan cost (wakeChecking prevents overlap)
457
+ if (wakeTimer) {
458
+ clearInterval(wakeTimer); // HMR/reload must not accumulate timers
459
+ }
460
+ void wakeSessions(centerOpts, selfServerUrl, serveWakeUrl);
461
+ wakeTimer = setInterval(() => {
462
+ void wakeSessions(centerOpts, selfServerUrl, serveWakeUrl);
463
+ }, 10000);
464
+ }
465
+ return {
466
+ tool: { room },
467
+ config,
468
+ // ponytail: central mode has no cross-host push, so each session pulls
469
+ // its inbox on chat messages and self-pushes queue notifications
470
+ // (SDK signature: (input, output) — sessionID is on the first arg)
471
+ ...(centerUrl
472
+ ? {
473
+ "chat.message": async (
474
+ input: { sessionID: string },
475
+ _output: unknown,
476
+ ) => {
477
+ void checkCenterInbox(
478
+ centerOpts,
479
+ input.sessionID,
480
+ selfServerUrl,
481
+ );
482
+ },
483
+ }
484
+ : {}),
485
+ };
486
+ },
487
+ };