@alexsun-top/opencode-chat-room 0.1.3 → 0.2.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.
@@ -1,7 +1,5 @@
1
- // ponytail: central-server mode client. All room state lives on the central
2
- // server (CHAT_ROOM_SERVER_URL); this machine pushes queue notifications to
3
- // sessions owned by this OpenCode process before using an HTTP fallback.
4
- import { OpencodeClient } from "@opencode-ai/sdk/v2";
1
+ // Central mode room API client. Recipient runtimes poll the server and deliver
2
+ // inbox items through their host's supported notification transport.
5
3
  import RoomService, {
6
4
  type Message,
7
5
  type Participant,
@@ -9,73 +7,20 @@ import RoomService, {
9
7
  } from "./room-service";
10
8
  import os from "node:os";
11
9
  import {
12
- authHeader,
13
- formatServeWakePrompt,
14
- formatNotificationLines,
15
10
  formatRoom,
16
11
  identity,
17
- NOTIFY_INSTRUCTION,
18
12
  timeOf,
19
13
  } from "./store";
20
14
  import {
21
- admissionMatches,
22
15
  clearPendingAdmission,
23
- getOrCreatePendingAdmission,
24
- markPendingAdmissionAdmitted,
25
- pendingAdmission,
26
- rejectPendingAdmission,
27
- type QueueBody,
28
- type QueueItem,
29
- type PendingAdmission,
30
16
  } from "./queue";
17
+ import type { InboxItem } from "./center-inbox";
31
18
  export { queueAdmissionId } from "./queue";
19
+ export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport";
20
+ export type { QueueTransport, PushResult } from "./queue-transport";
32
21
 
33
22
  type Json = Record<string, unknown>;
34
23
 
35
- const LOCAL_SERVER_URL = "http://localhost:4096";
36
-
37
- export type PushResult = "delivered" | "unreachable" | "rejected";
38
-
39
- export type QueueTransport = {
40
- client?: OpencodeClient;
41
- serverUrl?: string;
42
- directory?: string;
43
- };
44
-
45
- type QueueTransportInput = {
46
- client?: unknown;
47
- directory?: string;
48
- serverUrl?: URL | string;
49
- };
50
-
51
- // Compatibility bridge for OpenCode 1.18.16. The plugin exposes the embedded
52
- // transport through a private field; HTTP remains the compatibility fallback.
53
- export function createQueueTransport(
54
- input: QueueTransportInput = {},
55
- ): QueueTransport {
56
- const raw =
57
- input.client && typeof input.client === "object"
58
- ? (input.client as { _client?: unknown })._client
59
- : undefined;
60
- let client: OpencodeClient | undefined;
61
- if (raw !== undefined && raw !== null) {
62
- try {
63
- type ClientArgs = NonNullable<ConstructorParameters<typeof OpencodeClient>[0]>;
64
- client = new OpencodeClient({
65
- client: raw as NonNullable<ClientArgs["client"]>,
66
- });
67
- } catch {
68
- client = undefined;
69
- }
70
- }
71
- const serverUrl = String(input.serverUrl ?? "").trim();
72
- return {
73
- client,
74
- serverUrl: serverUrl || LOCAL_SERVER_URL,
75
- directory: input.directory,
76
- };
77
- }
78
-
79
24
  function toRoom(r: Json): Room {
80
25
  const participants = new Map<string, Participant>();
81
26
  if (Array.isArray(r.participants)) {
@@ -101,9 +46,9 @@ function svcOf(room: Json): RoomService {
101
46
  return svc;
102
47
  }
103
48
 
104
- type CenterOpts = { center: string; token: string; directory?: string };
49
+ export type CenterOpts = { center: string; token: string; directory?: string };
105
50
 
106
- async function request(
51
+ export async function request(
107
52
  opts: CenterOpts,
108
53
  path: string,
109
54
  method: string,
@@ -130,7 +75,7 @@ async function request(
130
75
  return data;
131
76
  }
132
77
 
133
- async function markQueued(
78
+ export async function markQueued(
134
79
  opts: CenterOpts,
135
80
  roomId: string,
136
81
  sessionID: string,
@@ -175,7 +120,7 @@ export async function centerAction(
175
120
  name: args.name.trim(),
176
121
  ownerId: identity(),
177
122
  sessionID,
178
- // ponytail: ora-1 #2 — 记录归属主机,跨机 @-wake 只由所属机器唤醒
123
+ // Record the owning host so only that host wakes this session.
179
124
  host: os.hostname(),
180
125
  directory: opts.directory,
181
126
  });
@@ -194,7 +139,7 @@ export async function centerAction(
194
139
  sessionID,
195
140
  participantId: me,
196
141
  participantName: me,
197
- // ponytail: ora-1 #2 — 记录归属主机,跨机 @-wake 只由所属机器唤醒
142
+ // Record the owning host so only that host wakes this session.
198
143
  host: os.hostname(),
199
144
  directory: opts.directory,
200
145
  },
@@ -281,510 +226,3 @@ export async function centerAction(
281
226
  return "error: unknown action";
282
227
  }
283
228
  }
284
-
285
- type InboxItem = QueueItem & {
286
- roomId: string;
287
- roomName: string;
288
- };
289
-
290
- function isRecord(value: unknown): value is Json {
291
- return typeof value === "object" && value !== null;
292
- }
293
-
294
- function queueBody(admissionID: string, text: string): QueueBody {
295
- return {
296
- id: admissionID,
297
- prompt: { text },
298
- delivery: "queue",
299
- resume: true,
300
- };
301
- }
302
-
303
- function statusOf(value: unknown): number | undefined {
304
- if (!isRecord(value)) {
305
- return undefined;
306
- }
307
- if (typeof value.status === "number") {
308
- return value.status;
309
- }
310
- if (isRecord(value.response) && typeof value.response.status === "number") {
311
- return value.response.status;
312
- }
313
- if (isRecord(value.cause) && typeof value.cause.status === "number") {
314
- return value.cause.status;
315
- }
316
- return undefined;
317
- }
318
-
319
- function httpHeaders(transport: QueueTransport): Record<string, string> {
320
- const auth = authHeader();
321
- return {
322
- "Content-Type": "application/json",
323
- ...(auth ? { Authorization: auth } : {}),
324
- ...(transport.directory
325
- ? { "x-opencode-directory": encodeURIComponent(transport.directory) }
326
- : {}),
327
- };
328
- }
329
-
330
- async function sendQueueInProcess(
331
- client: OpencodeClient,
332
- sessionID: string,
333
- body: QueueBody,
334
- ): Promise<PushResult> {
335
- let result: unknown;
336
- try {
337
- result = await client.v2.session.prompt(
338
- { sessionID, ...body },
339
- { responseStyle: "fields", signal: AbortSignal.timeout(10_000) },
340
- );
341
- } catch (error) {
342
- const status = statusOf(error);
343
- return status === undefined || status === 404
344
- ? "unreachable"
345
- : "rejected";
346
- }
347
- if (!isRecord(result)) {
348
- return "unreachable";
349
- }
350
- if (!isRecord(result.response)) {
351
- if (admissionMatches(result, body, sessionID)) {
352
- return "delivered";
353
- }
354
- return "unreachable";
355
- }
356
- const status = result.response.status;
357
- if (typeof status !== "number") {
358
- return "unreachable";
359
- }
360
- if (status === 404) {
361
- return "unreachable";
362
- }
363
- if (status < 200 || status >= 300) {
364
- return "rejected";
365
- }
366
- return admissionMatches(result.data, body, sessionID)
367
- ? "delivered"
368
- : "rejected";
369
- }
370
-
371
- async function sendQueueHttp(
372
- transport: QueueTransport,
373
- sessionID: string,
374
- body: QueueBody,
375
- ): Promise<PushResult> {
376
- const base = (transport.serverUrl || LOCAL_SERVER_URL).replace(/\/+$/, "");
377
- let response: Response;
378
- try {
379
- response = await fetch(
380
- `${base}/api/session/${encodeURIComponent(sessionID)}/prompt`,
381
- {
382
- method: "POST",
383
- headers: httpHeaders(transport),
384
- body: JSON.stringify(body),
385
- signal: AbortSignal.timeout(10_000),
386
- },
387
- );
388
- } catch {
389
- return "unreachable";
390
- }
391
- const data = await response.json().catch(() => undefined);
392
- if (response.status === 404) {
393
- return "unreachable";
394
- }
395
- if (!response.ok) {
396
- return "rejected";
397
- }
398
- return admissionMatches(data, body, sessionID) ? "delivered" : "rejected";
399
- }
400
-
401
- export async function sendQueue(
402
- transport: QueueTransport,
403
- sessionID: string,
404
- text: string,
405
- admissionID: string,
406
- ): Promise<PushResult> {
407
- const body = queueBody(admissionID, text);
408
- if (transport.client) {
409
- const result = await sendQueueInProcess(transport.client, sessionID, body);
410
- if (result !== "unreachable") {
411
- return result;
412
- }
413
- }
414
- return sendQueueHttp(transport, sessionID, body);
415
- }
416
-
417
- // Overlapping hook and tool triggers must not double-deliver; keep the lock
418
- // per session so a slow check cannot starve another session.
419
- const inboxChecks = new Set<string>();
420
- const sessionPushes = new Map<string, Promise<void>>();
421
-
422
- function serializeSessionPush(
423
- sessionID: string,
424
- task: () => Promise<void>,
425
- ): Promise<void> {
426
- const previous = sessionPushes.get(sessionID) ?? Promise.resolve();
427
- const run = previous.catch(() => {}).then(task);
428
- let current: Promise<void>;
429
- current = run.finally(() => {
430
- if (sessionPushes.get(sessionID) === current) {
431
- sessionPushes.delete(sessionID);
432
- }
433
- });
434
- sessionPushes.set(sessionID, current);
435
- return current;
436
- }
437
-
438
- export async function checkCenterInbox(
439
- opts: CenterOpts,
440
- sessionID: string,
441
- transport: QueueTransport,
442
- ): Promise<void> {
443
- if (inboxChecks.has(sessionID)) {
444
- return;
445
- }
446
- inboxChecks.add(sessionID);
447
- try {
448
- await serializeSessionPush(sessionID, async () => {
449
- const result = (await request(
450
- opts,
451
- `/inbox?sessionID=${encodeURIComponent(sessionID)}&excludeSelf=1`,
452
- "GET",
453
- )) as unknown as {
454
- member: boolean;
455
- items: InboxItem[];
456
- queuedTs?: Record<string, number>;
457
- };
458
- const queuedTs = result.queuedTs ?? {};
459
- const items = (Array.isArray(result.items) ? result.items : []).filter(
460
- (item) => item.createdAt > (queuedTs[item.roomId] ?? 0),
461
- );
462
- if (items.length > 0) {
463
- await pushItemsToSession(opts, sessionID, items, transport, queuedTs);
464
- }
465
- });
466
- } catch {
467
- // best-effort: next check retries
468
- } finally {
469
- inboxChecks.delete(sessionID);
470
- }
471
- }
472
-
473
- // Items are grouped by room. Queue admission advances only the durable queued
474
- // cursor; poll remains the only path that advances the read cursor.
475
-
476
- export async function pushItemsToSession(
477
- opts: CenterOpts,
478
- sessionID: string,
479
- items: InboxItem[],
480
- transport: QueueTransport,
481
- queuedTs: Readonly<Record<string, number>> = {},
482
- ): Promise<PushResult> {
483
- if (items.length === 0) {
484
- return "delivered";
485
- }
486
- const byRoom = new Map<string, InboxItem[]>();
487
- for (const it of items) {
488
- if (it.createdAt <= (queuedTs[it.roomId] ?? 0)) {
489
- continue;
490
- }
491
- const list = byRoom.get(it.roomId) ?? [];
492
- list.push(it);
493
- byRoom.set(it.roomId, list);
494
- }
495
- let worst: PushResult = "delivered";
496
- for (const [roomId, roomItems] of byRoom) {
497
- const maxTs = roomItems.reduce(
498
- (mx, it) => Math.max(mx, it.createdAt),
499
- 0,
500
- );
501
- const existing = pendingAdmission(sessionID, roomId);
502
- const deltaItems =
503
- existing?.state === "admitted" && maxTs > existing.maxTs
504
- ? roomItems.filter((item) => item.createdAt > existing.maxTs)
505
- : roomItems;
506
- if (
507
- existing?.state === "admitted" &&
508
- (maxTs <= existing.maxTs || deltaItems.length === 0)
509
- ) {
510
- if (existing.maxTs > 0) {
511
- const queued = await markQueued(
512
- opts,
513
- roomId,
514
- sessionID,
515
- existing.maxTs,
516
- );
517
- if (queued) {
518
- clearPendingAdmission(sessionID, roomId, existing.maxTs);
519
- }
520
- }
521
- continue;
522
- }
523
- const deltaMaxTs = deltaItems.reduce(
524
- (mx, it) => Math.max(mx, it.createdAt),
525
- 0,
526
- );
527
- const { lines, capped } = formatNotificationLines(deltaItems);
528
- const prompt = `<notification>\nNew messages in room ${deltaItems[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
529
- const admission = getOrCreatePendingAdmission(
530
- sessionID,
531
- roomId,
532
- deltaItems,
533
- prompt,
534
- deltaMaxTs,
535
- capped,
536
- );
537
- const result = await sendQueue(
538
- transport,
539
- sessionID,
540
- admission.prompt,
541
- admission.id,
542
- );
543
- if (result !== "delivered") {
544
- if (result === "rejected") {
545
- rejectPendingAdmission(sessionID, roomId, admission.id);
546
- }
547
- if (result === "rejected" || worst === "delivered") {
548
- worst = result;
549
- }
550
- continue;
551
- }
552
- markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
553
- void request(opts, "/active", "POST", { sessionID }).catch(() => {});
554
- if (admission.maxTs > 0) {
555
- const queued = await markQueued(opts, roomId, sessionID, admission.maxTs);
556
- if (queued) {
557
- clearPendingAdmission(sessionID, roomId, admission.maxTs);
558
- }
559
- }
560
- }
561
- return worst;
562
- }
563
-
564
- // ponytail: in-plugin wake watcher — sweep all rooms on the central server,
565
- // find sessions with unread messages, and self-push queue notifications to
566
- // them (opencode wakes the session in-process; dead sessions just fail
567
- // silently). Runs on a timer; the central server itself has no opencode
568
- // knowledge, this is purely client-side.
569
- let wakeChecking = false;
570
-
571
- // No process is spawned here. A configured opencode serve is only a fallback
572
- // for mentioned sessions that cannot be admitted by the current process.
573
- async function wakeViaServe(
574
- serveUrl: string,
575
- sessionID: string,
576
- roomId: string,
577
- opts: CenterOpts,
578
- transport: QueueTransport,
579
- admission: PendingAdmission,
580
- ): Promise<boolean> {
581
- // ponytail: 与多窗口插件共用服务器原子去重,避免重复唤起同一 session
582
- try {
583
- const claim = (await fetch(`${opts.center}/wake-claim`, {
584
- method: "POST",
585
- headers: {
586
- "Content-Type": "application/json",
587
- ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}),
588
- },
589
- body: JSON.stringify({ sessionID }),
590
- signal: AbortSignal.timeout(10_000),
591
- }).then((r) => r.json().catch(() => ({})))) as { ok?: boolean };
592
- if (!claim.ok) {
593
- return false;
594
- }
595
- } catch {
596
- return false;
597
- }
598
- const result = await sendQueue(
599
- { ...transport, client: undefined, serverUrl: serveUrl },
600
- sessionID,
601
- admission.prompt,
602
- admission.id,
603
- );
604
- if (result === "delivered") {
605
- void request(opts, "/active", "POST", { sessionID }).catch(() => {});
606
- markPendingAdmissionAdmitted(sessionID, roomId, admission.id);
607
- if (admission.maxTs > 0) {
608
- const queued = await markQueued(opts, roomId, sessionID, admission.maxTs);
609
- if (queued) {
610
- clearPendingAdmission(sessionID, roomId, admission.maxTs);
611
- }
612
- }
613
- } else if (result === "rejected") {
614
- rejectPendingAdmission(sessionID, roomId, admission.id);
615
- }
616
- return result === "delivered";
617
- }
618
-
619
- export async function wakeSessions(
620
- opts: CenterOpts,
621
- transport: QueueTransport,
622
- serveUrl = "",
623
- ): Promise<void> {
624
- if (wakeChecking) {
625
- return;
626
- }
627
- wakeChecking = true;
628
- try {
629
- // ponytail: 轻量摘要(orc-1 #5)——不下载全部房间历史
630
- const rooms = (await request(
631
- opts,
632
- "/rooms/summary",
633
- "GET",
634
- )) as unknown as Array<{ id: string; name: string; latestMsgTs: number }>;
635
- if (!Array.isArray(rooms)) {
636
- return;
637
- }
638
- for (const room of rooms) {
639
- try {
640
- const roomId = String(room.id ?? "");
641
- const latest = Number(room.latestMsgTs ?? 0);
642
- if (!roomId || latest === 0) {
643
- continue;
644
- }
645
- const reg = (await request(
646
- opts,
647
- `/rooms/${encodeURIComponent(roomId)}/registry`,
648
- "GET",
649
- )) as unknown as Record<
650
- string,
651
- {
652
- name: string;
653
- lastReadTs?: number;
654
- lastQueuedTs?: number;
655
- host?: string;
656
- directory?: string;
657
- }
658
- >;
659
- if (!reg || typeof reg !== "object") {
660
- continue;
661
- }
662
- for (const [sessionID, entry] of Object.entries(reg)) {
663
- // ponytail: 网页/模拟条目(host 空)不是 opencode 会话——不扫描
664
- // 不推送(否则死条目每 10s 一次 404 推送,永远 churn,orc-1 #7)
665
- if (!entry.host) {
666
- continue;
667
- }
668
- // ponytail: orc-2 #6——跨 host 条目由各自机器上的插件负责,本机
669
- // 扫描+推送只会 404;队列游标由中心服务器持久化
670
- if (entry.host !== os.hostname()) {
671
- continue;
672
- }
673
- // quick skip: nothing newer than this session's watermark
674
- if (
675
- latest <=
676
- Math.max(entry.lastReadTs ?? 0, entry.lastQueuedTs ?? 0)
677
- ) {
678
- continue;
679
- }
680
- await serializeSessionPush(sessionID, async () => {
681
- const result = (await request(
682
- opts,
683
- `/inbox?sessionID=${encodeURIComponent(sessionID)}&roomId=${encodeURIComponent(roomId)}&excludeSelf=1&timeout=0`,
684
- "GET",
685
- )) as unknown as {
686
- member: boolean;
687
- items: InboxItem[];
688
- queuedTs?: Record<string, number>;
689
- };
690
- const queuedTs = Math.max(
691
- entry.lastQueuedTs ?? 0,
692
- result.queuedTs?.[roomId] ?? 0,
693
- );
694
- const items = Array.isArray(result.items)
695
- ? result.items.filter(
696
- (item) =>
697
- item.roomId === roomId && item.createdAt > queuedTs,
698
- )
699
- : [];
700
- if (items.length === 0) {
701
- return;
702
- }
703
- const targetTransport = {
704
- ...transport,
705
- directory: entry.directory ?? transport.directory,
706
- };
707
- // ponytail: ora-1 #2 — @-wake 只由 session 归属主机执行;web 条目
708
- // (host 为空)与异机条目绝不 spawn(否则错机 spawn 一个不存在
709
- // 的 session,且 5 分钟 claim 窗口会挡住真正正确的那台机器)
710
- const pushed = await pushItemsToSession(
711
- opts,
712
- sessionID,
713
- items,
714
- targetTransport,
715
- result.queuedTs,
716
- );
717
- // 被 @ 的已退出 session:serve 配置了才唤起(进程内,零 spawn)。
718
- // 唤起成功即推进队列游标——消息已进入该 session 的对话(不丢),
719
- // 避免同一未读反复唤起导致循环回复。
720
- // 仅唤起本机 opencode session(host === 本机主机名)——web 条目
721
- // 与 curl 模拟成员(host 空)没有可恢复的 opencode 会话
722
- if (
723
- pushed === "unreachable" &&
724
- serveUrl &&
725
- entry.host === os.hostname()
726
- ) {
727
- const mentioned = items.some((it) => {
728
- if (it.text.includes(`<at>@${entry.name}</at>`)) return true;
729
- const esc = entry.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
730
- return new RegExp(`@${esc}(?![\\p{L}\\p{N}_])`, "u").test(
731
- it.text,
732
- );
733
- });
734
- if (mentioned) {
735
- const currentMaxTs = items.reduce(
736
- (mx, it) => Math.max(mx, it.createdAt),
737
- 0,
738
- );
739
- const existing = pendingAdmission(sessionID, roomId);
740
- const deltaItems =
741
- existing?.state === "admitted" &&
742
- currentMaxTs > existing.maxTs
743
- ? items.filter((item) => item.createdAt > existing.maxTs)
744
- : items;
745
- if (
746
- existing?.state === "admitted" &&
747
- (currentMaxTs <= existing.maxTs || deltaItems.length === 0)
748
- ) {
749
- return;
750
- }
751
- const { lines, capped } = formatNotificationLines(deltaItems);
752
- const prompt = formatServeWakePrompt(
753
- deltaItems[0]!.roomName,
754
- lines,
755
- );
756
- const maxTs = deltaItems.reduce(
757
- (mx, it) => Math.max(mx, it.createdAt),
758
- 0,
759
- );
760
- const admission = getOrCreatePendingAdmission(
761
- sessionID,
762
- roomId,
763
- deltaItems,
764
- prompt,
765
- maxTs,
766
- capped,
767
- );
768
- await wakeViaServe(
769
- serveUrl,
770
- sessionID,
771
- roomId,
772
- opts,
773
- targetTransport,
774
- admission,
775
- );
776
- }
777
- }
778
- });
779
- }
780
- } catch {
781
- // ponytail: orc-3 #4——单房间错误(registry/inbox 请求失败)只跳过
782
- // 该房间,不中止整个 sweep
783
- }
784
- }
785
- } catch {
786
- // best-effort: next sweep retries
787
- } finally {
788
- wakeChecking = false;
789
- }
790
- }