@alexsun-top/opencode-chat-room 0.2.0 → 0.2.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ - On V2, messages that explicitly mention a registered room name can attempt to background that session's blocking shell or subagent work before routing the notification into the running session.
6
+ - Backgrounding is best-effort: it only targets the current OS user's registered service after PID and version checks. It does not start services or probe ports; if unavailable, normal queue delivery remains. Backgrounded tasks are not cancelled.
7
+ - Polling runs every five seconds. Retry and cross-instance serialization keep background attempts aligned with pending notifications.
8
+ - Fixed token storage fallback when browser storage rejects writes. Entering a token still requires clicking Save.
9
+
10
+ ### Verification
11
+
12
+ The production-only package loaded on OpenCode V1 `1.18.29` and V2 `2.0.29`. Real V2 host tests verified that mentioned foreground shell and subagent tasks moved to the background, messages were handled before their test gates opened, and the original work subsequently completed. Non-mentions, truncated name-prefix lookalikes, late mentions outside the displayed text, and a different registered-service PID did not trigger backgrounding. Tests used an isolated local mock model, not paid providers. Unit tests cover retry identity, background retries, concurrent delivery, and host identity checks.
13
+
3
14
  ## 0.2.0
4
15
 
5
16
  - Added V1 and V2 plugin entrypoints so the package works with both OpenCode plugin APIs.
@@ -10,6 +21,6 @@
10
21
 
11
22
  ### Verification
12
23
 
13
- Local host checks covered OpenCode V1 `1.18.29` and V2 `2.0.29`, using a deterministic mock provider without paid model requests. Both hosts exercised all seven room actions, `/room`, standalone and central notifications, failure recovery, and production-only package installation; the packed runtime files match the current source. See the E2E report supplied with the release verification artifacts. V1 `prompt_async` reports acceptance, not durable queue admission.
24
+ Local host checks for 0.2.0 covered OpenCode V1 `1.18.29` and V2 `2.0.29`, using a deterministic mock provider without paid model requests. Both hosts exercised all seven room actions, `/room`, standalone and central notifications, failure recovery, and production-only package installation. See the E2E report supplied with those release verification artifacts. V1 `prompt_async` reports acceptance, not durable queue admission.
14
25
 
15
26
  Existing limits remain: local shared-state writes are last-writer-wins across processes, and room history retains at most 500 messages.
package/README.md CHANGED
@@ -53,6 +53,8 @@ Typical usage in a session:
53
53
 
54
54
  Push notifications use the host's supported transport. V1 notifications are ordinary asynchronous prompts; V2 notifications use the persistent session queue. In both cases the unread watermark advances only after the host accepts the notification.
55
55
 
56
+ On V2, an incoming message that explicitly mentions the registered room name (for example, `@alice`) first attempts to move that session's blocking shell or subagent work into the background, then steers the notification into the still-running session. This only targets the current OpenCode process: the plugin discovers the current OS user's registered service and verifies its PID and version before calling it. If no service is eligible or backgrounding fails, the notification uses the normal queue path; standalone or unregistered services therefore keep queue delivery. A session must still be a room member to receive notifications. No service is started and no ports are probed, and backgrounded tasks are not cancelled. Polling is every five seconds, so this is not instant push.
57
+
56
58
  ## Central mode (multi-host)
57
59
 
58
60
  For several machines: run one central server, point every client at it. This is the only per-client configuration.
@@ -61,17 +63,17 @@ On the server machine, install Bun first. `npx`, `pnpx`, and `bunx` only execute
61
63
 
62
64
  ```bash
63
65
  # Show CLI options:
64
- npx --yes --package=@alexsun-top/opencode-chat-room@0.2.0 -- opencode-chat-room --help
66
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.2.1 -- opencode-chat-room --help
65
67
 
66
68
  # Start the local central server (choose any one runner):
67
- npx --yes --package=@alexsun-top/opencode-chat-room@0.2.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
68
- pnpx --package=@alexsun-top/opencode-chat-room@0.2.0 opencode-chat-room --host 0.0.0.0 --port 4399
69
- bunx @alexsun-top/opencode-chat-room@0.2.0 --host 0.0.0.0 --port 4399 --token secret
69
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.2.1 -- opencode-chat-room --host 0.0.0.0 --port 4399
70
+ pnpx --package=@alexsun-top/opencode-chat-room@0.2.1 opencode-chat-room --host 0.0.0.0 --port 4399
71
+ bunx @alexsun-top/opencode-chat-room@0.2.1 --host 0.0.0.0 --port 4399 --token secret
70
72
 
71
73
  # Environment variables also work; CLI options take precedence:
72
74
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
73
75
  CHAT_ROOM_SERVER_TOKEN=secret \
74
- bunx @alexsun-top/opencode-chat-room@0.2.0
76
+ bunx @alexsun-top/opencode-chat-room@0.2.1
75
77
 
76
78
  # Local checkout:
77
79
  bun install
package/README.zh-CN.md CHANGED
@@ -53,6 +53,8 @@
53
53
 
54
54
  推送通知使用宿主支持的传输方式。V1 通知是普通异步 prompt;V2 通知进入持久会话队列。两者都只有在宿主接受通知后才推进未读水位。
55
55
 
56
+ V2 收到明确提及房间注册名称的消息(例如 `@alice`)时,会先尝试将该会话中正在阻塞的 shell 或子 agent 工作移至后台,再将通知导向仍在运行的会话。此操作只针对当前 OpenCode 进程:插件发现当前操作系统用户注册的服务,并在调用前验证进程 PID 和版本。没有符合条件的服务或后台操作失败时,通知仍走普通队列;独立运行或未注册的服务会保留队列投递。会话仍需加入房间才能收到通知。插件不会启动服务或扫描端口,移至后台的任务也不会被取消。消息每五秒轮询一次,并非即时推送。
57
+
56
58
  ## 中心模式(多主机)
57
59
 
58
60
  多台机器时:跑一个中心服务器,所有客户端指向它。**每个客户端只需要这一个环境变量**。
@@ -61,17 +63,17 @@
61
63
 
62
64
  ```bash
63
65
  # 查看 CLI 选项:
64
- npx --yes --package=@alexsun-top/opencode-chat-room@0.2.0 -- opencode-chat-room --help
66
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.2.1 -- opencode-chat-room --help
65
67
 
66
68
  # 启动本地中心服务器(三选一):
67
- npx --yes --package=@alexsun-top/opencode-chat-room@0.2.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
68
- pnpx --package=@alexsun-top/opencode-chat-room@0.2.0 opencode-chat-room --host 0.0.0.0 --port 4399
69
- bunx @alexsun-top/opencode-chat-room@0.2.0 --host 0.0.0.0 --port 4399 --token secret
69
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.2.1 -- opencode-chat-room --host 0.0.0.0 --port 4399
70
+ pnpx --package=@alexsun-top/opencode-chat-room@0.2.1 opencode-chat-room --host 0.0.0.0 --port 4399
71
+ bunx @alexsun-top/opencode-chat-room@0.2.1 --host 0.0.0.0 --port 4399 --token secret
70
72
 
71
73
  # 也可以使用环境变量;CLI 参数优先:
72
74
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
73
75
  CHAT_ROOM_SERVER_TOKEN=secret \
74
- bunx @alexsun-top/opencode-chat-room@0.2.0
76
+ bunx @alexsun-top/opencode-chat-room@0.2.1
75
77
 
76
78
  # 本地 checkout:
77
79
  bun install
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -48,6 +48,7 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "@opencode-ai/plugin": "^1.18.29",
51
+ "@opencode/client": "2.0.32",
51
52
  "zod": "4.1.8"
52
53
  }
53
54
  }
package/server/chat.html CHANGED
@@ -722,14 +722,19 @@
722
722
  const $ = (s) => document.querySelector(s);
723
723
 
724
724
  /* ---------- 本地存储(隐私模式下 localStorage 可能抛错,回退到内存) ---------- */
725
- const memStore = {};
725
+ const memStore = Object.create(null);
726
726
  function lsGet(k) {
727
+ if (Object.prototype.hasOwnProperty.call(memStore, k)) return memStore[k];
727
728
  try { return localStorage.getItem(k); }
728
- catch { return k in memStore ? memStore[k] : null; }
729
+ catch { return null; }
729
730
  }
730
731
  function lsSet(k, v) {
731
- try { if (v == null) localStorage.removeItem(k); else localStorage.setItem(k, v); }
732
- catch { if (v == null) delete memStore[k]; else memStore[k] = v; }
732
+ const value = v == null ? null : String(v);
733
+ try {
734
+ if (value == null) localStorage.removeItem(k);
735
+ else localStorage.setItem(k, value);
736
+ delete memStore[k];
737
+ } catch { memStore[k] = value; }
733
738
  }
734
739
  function newSessionID() {
735
740
  const webCrypto = globalThis.crypto;
@@ -766,6 +771,10 @@
766
771
  get locale() { return lsGet("chat.locale") || "en"; },
767
772
  set locale(v) { lsSet("chat.locale", v || null); },
768
773
  };
774
+ function saveToken(value) {
775
+ LS.token = String(value ?? "").trim();
776
+ return LS.token;
777
+ }
769
778
 
770
779
  const I18N = {
771
780
  en: {
@@ -2049,8 +2058,7 @@
2049
2058
  const save = e.target.closest("[data-token-save]");
2050
2059
  if (save) {
2051
2060
  const input = document.getElementById(save.dataset.tokenSave);
2052
- LS.token = input.value.trim();
2053
- input.value = LS.token;
2061
+ input.value = saveToken(input.value);
2054
2062
  $("#inToken").value = LS.token;
2055
2063
  $("#inTokenChat").value = LS.token;
2056
2064
  flash(save, "saved");
@@ -0,0 +1,49 @@
1
+ export async function backgroundOwnSession(sessionID: string, version: string): Promise<boolean> {
2
+ try {
3
+ const [{ OpenCode }, { Service }] = await Promise.all([
4
+ import("@opencode/client"), import("@opencode/client/service"),
5
+ ]);
6
+ return backgroundAtRegisteredService(sessionID, version, {
7
+ discover: () => Service.discover({ version }),
8
+ headers: Service.headers,
9
+ createClient: (baseUrl, headers) => OpenCode.make({ baseUrl, headers }),
10
+ });
11
+ } catch {
12
+ return false;
13
+ }
14
+ }
15
+
16
+ type BackgroundApi = {
17
+ discover(): Promise<{ url: string; auth?: { type: "basic"; username: string; password: string } } | undefined>;
18
+ headers(endpoint: { url: string; auth?: { type: "basic"; username: string; password: string } }): Record<string, string> | undefined;
19
+ createClient(baseUrl: string, headers?: Record<string, string>): {
20
+ server: { info(options: { signal: AbortSignal }): Promise<{ pid: number; version: string }> };
21
+ session: { background(input: { sessionID: string }, options: { signal: AbortSignal }): Promise<void> };
22
+ };
23
+ };
24
+
25
+ export async function backgroundAtRegisteredService(
26
+ sessionID: string,
27
+ version: string,
28
+ api: BackgroundApi,
29
+ pid = process.pid,
30
+ ): Promise<boolean> {
31
+ try {
32
+ let timer: ReturnType<typeof setTimeout>;
33
+ const endpoint = await Promise.race([
34
+ api.discover(),
35
+ new Promise<undefined>((resolve) => { timer = setTimeout(() => resolve(undefined), 2000); }),
36
+ ]).finally(() => clearTimeout(timer!));
37
+ if (!endpoint) return false;
38
+ const url = new URL(endpoint.url);
39
+ if (!["127.0.0.1", "localhost", "::1", "[::1]"].includes(url.hostname)) return false;
40
+ const headers = api.headers(endpoint);
41
+ const client = api.createClient(url.origin, headers);
42
+ const info = await client.server.info({ signal: AbortSignal.timeout(1500) });
43
+ if (info.pid !== pid || info.version !== version) return false;
44
+ await client.session.background({ sessionID }, { signal: AbortSignal.timeout(1500) });
45
+ return true;
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
@@ -9,6 +9,7 @@ import {
9
9
  type QueueItem,
10
10
  } from "./queue";
11
11
  import { request, markQueued, type CenterOpts } from "./center-client";
12
+ import { explicitlyMentions } from "./mentions";
12
13
  import {
13
14
  sendAsyncNotification,
14
15
  sendQueue,
@@ -18,12 +19,12 @@ import {
18
19
 
19
20
  export type InboxItem = QueueItem & { roomId: string; roomName: string };
20
21
  const inboxChecks = new Set<string>();
21
- const sessionPushes = new Map<string, Promise<void>>();
22
+ const sessionPushes = new Map<string, Promise<unknown>>();
22
23
 
23
- export function serializeSessionPush(sessionID: string, task: () => Promise<void>): Promise<void> {
24
+ export function serializeSessionPush<T>(sessionID: string, task: () => Promise<T>): Promise<T> {
24
25
  const previous = sessionPushes.get(sessionID) ?? Promise.resolve();
25
26
  const run = previous.catch(() => {}).then(task);
26
- let current: Promise<void>;
27
+ let current: Promise<T>;
27
28
  current = run.finally(() => {
28
29
  if (sessionPushes.get(sessionID) === current) sessionPushes.delete(sessionID);
29
30
  });
@@ -88,9 +89,19 @@ export async function pushItemsToSession(
88
89
  const { lines, capped } = formatNotificationLines(delta);
89
90
  const prompt = `<notification>\nNew messages in room ${delta[0]!.roomName}:\n${lines.join("\n")}\n${NOTIFY_INSTRUCTION}\n</notification>`;
90
91
  const admission = getOrCreatePendingAdmission(sessionID, roomId, delta, prompt, deltaTs, capped);
92
+ let delivery: "queue" | "steer" = "queue";
93
+ if (transport.protocol === "v2" && transport.backgroundSession) {
94
+ let name = "";
95
+ try {
96
+ const registry = await request(opts, `/rooms/${encodeURIComponent(roomId)}/registry`, "GET") as Record<string, { name?: string }>;
97
+ name = registry[sessionID]?.name ?? "";
98
+ } catch { /* Backgrounding is optional; preserve queued delivery. */ }
99
+ if (name && admission.items.some((item) => explicitlyMentions(item, name, sessionID)) &&
100
+ await transport.backgroundSession(sessionID)) delivery = "steer";
101
+ }
91
102
  const result = transport.protocol === "v1"
92
103
  ? await sendAsyncNotification(transport, sessionID, admission.prompt)
93
- : await sendQueue(transport, sessionID, admission.prompt, admission.id);
104
+ : await sendQueue(transport, sessionID, admission.prompt, admission.id, delivery);
94
105
  if (result !== "delivered") {
95
106
  if (result === "rejected") rejectPendingAdmission(sessionID, roomId, admission.id);
96
107
  if (result === "rejected" || worst === "delivered") worst = result;
@@ -0,0 +1,8 @@
1
+ import type { QueueItem } from "./queue";
2
+
3
+ export function explicitlyMentions(item: QueueItem, recipient: string, sessionID?: string): boolean {
4
+ if (!recipient.trim() || item.senderId === "system" || (sessionID !== undefined && item.senderSessionID === sessionID)) return false;
5
+ const escaped = recipient.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6
+ const match = new RegExp(`(?<![\\p{L}\\p{N}_.@])(?:<at>)?@${escaped}(?:</at>)?(?![\\p{L}\\p{N}_])`, "u").exec(item.text);
7
+ return match !== null && match.index + match[0].length <= 300;
8
+ }
@@ -10,6 +10,8 @@ import {
10
10
  timeOf,
11
11
  } from "./store";
12
12
  import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
13
+ import { explicitlyMentions } from "./mentions";
14
+ import { serializeSessionPush } from "./center-inbox";
13
15
  import {
14
16
  getOrCreatePendingAdmission,
15
17
  markPendingAdmissionAdmitted,
@@ -43,6 +45,15 @@ export function createNotifier(deps: {
43
45
  sessionID: string,
44
46
  batch: NotifyBatch,
45
47
  transport: QueueTransport = deps.transport(),
48
+ ): Promise<NotifyAttempt | undefined> {
49
+ if (transport.protocol !== "v2") return notifyTargetUnlocked(sessionID, batch, transport);
50
+ return serializeSessionPush(sessionID, () => notifyTargetUnlocked(sessionID, batch, transport));
51
+ }
52
+
53
+ async function notifyTargetUnlocked(
54
+ sessionID: string,
55
+ batch: NotifyBatch,
56
+ transport: QueueTransport,
46
57
  ): Promise<NotifyAttempt | undefined> {
47
58
  const entry = (await loadRegistry())[batch.roomId]?.[sessionID];
48
59
  if (!entry || (entry.protocol !== "v2" && !entry.serverUrl)) return undefined;
@@ -80,8 +91,11 @@ export function createNotifier(deps: {
80
91
  serverUrl: entry.serverUrl,
81
92
  directory: entry.directory ?? transport.directory,
82
93
  };
94
+ const mentioned = entry.protocol === "v2" && admission.items.some((message) => explicitlyMentions(message, entry.name, sessionID));
95
+ const delivery = mentioned && targetTransport.backgroundSession &&
96
+ await targetTransport.backgroundSession(sessionID) ? "steer" : "queue";
83
97
  const result = entry.protocol === "v2"
84
- ? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id)
98
+ ? await sendQueue(targetTransport, sessionID, admission.prompt, admission.id, delivery)
85
99
  : await sendAsyncNotification(targetTransport, sessionID, admission.prompt);
86
100
  if (result !== "delivered") {
87
101
  if (result === "rejected") rejectPendingAdmission(sessionID, batch.roomId, admission.id);
@@ -3,7 +3,8 @@ import { admissionMatches, type QueueBody } from "./queue";
3
3
 
4
4
  export type PushResult = "delivered" | "unreachable" | "rejected";
5
5
  export type QueueTransport = {
6
- promptQueue?: (sessionID: string, id: string, text: string) => Promise<unknown>;
6
+ promptQueue?: (sessionID: string, id: string, text: string, delivery: "queue" | "steer") => Promise<unknown>;
7
+ backgroundSession?: (sessionID: string) => Promise<boolean>;
7
8
  serverUrl?: string;
8
9
  directory?: string;
9
10
  protocol?: "v1" | "v2";
@@ -42,7 +43,7 @@ async function sendQueueInProcess(
42
43
  ): Promise<PushResult> {
43
44
  let result: unknown;
44
45
  try {
45
- result = await transport.promptQueue!(sessionID, body.id, body.prompt.text);
46
+ result = await transport.promptQueue!(sessionID, body.id, body.prompt.text, body.delivery);
46
47
  } catch (error) {
47
48
  const status = statusOf(error);
48
49
  return status === undefined || status === 404 ? "unreachable" : "rejected";
@@ -114,11 +115,12 @@ export async function sendQueue(
114
115
  sessionID: string,
115
116
  text: string,
116
117
  admissionID: string,
118
+ delivery: "queue" | "steer" = "queue",
117
119
  ): Promise<PushResult> {
118
120
  const body: QueueBody = {
119
121
  id: admissionID,
120
122
  prompt: { text },
121
- delivery: "queue",
123
+ delivery,
122
124
  resume: true,
123
125
  };
124
126
  if (transport.promptQueue) {
package/src/queue.ts CHANGED
@@ -3,6 +3,7 @@ import { createHash } from "node:crypto";
3
3
  export type QueueItem = {
4
4
  id?: string;
5
5
  senderId: string;
6
+ senderSessionID?: string;
6
7
  text: string;
7
8
  createdAt: number;
8
9
  };
@@ -10,7 +11,7 @@ export type QueueItem = {
10
11
  export type QueueBody = {
11
12
  id: string;
12
13
  prompt: { text: string };
13
- delivery: "queue";
14
+ delivery: "queue" | "steer";
14
15
  resume: true;
15
16
  };
16
17
 
@@ -21,6 +22,7 @@ export type PendingAdmission = {
21
22
  maxTs: number;
22
23
  capped: boolean;
23
24
  state: "pending" | "admitted";
25
+ items: QueueItem[];
24
26
  };
25
27
 
26
28
  type PendingEntry = {
@@ -121,6 +123,7 @@ export function getOrCreatePendingAdmission(
121
123
  maxTs,
122
124
  capped,
123
125
  state: "pending",
126
+ items: items.slice(-20).map((item) => ({ ...item })),
124
127
  };
125
128
  if (maxTs > 0) {
126
129
  rememberPending(key, admission, now);
@@ -177,7 +180,7 @@ export function admissionMatches(
177
180
  if (
178
181
  record.id === body.id &&
179
182
  record.sessionID === sessionID &&
180
- record.delivery === "queue"
183
+ (record.delivery === "queue" || record.delivery === "steer")
181
184
  ) {
182
185
  return true;
183
186
  }
package/src/v2-plugin.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Plugin } from "@opencode/plugin";
2
2
  import { z } from "zod";
3
3
  import type { QueueTransport } from "./center-client";
4
+ import { backgroundOwnSession } from "./background";
4
5
 
5
6
  type CenterOptions = { center: string; token: string; directory: string };
6
7
  export type V2Runtime = {
@@ -26,8 +27,9 @@ export function createV2Setup(deps: {
26
27
  const transport: QueueTransport = {
27
28
  directory,
28
29
  protocol: "v2",
29
- promptQueue: (sessionID, id, text) => context.session.prompt({
30
- sessionID, id, text, delivery: "queue", resume: true,
30
+ backgroundSession: (sessionID) => backgroundOwnSession(sessionID, context.app?.version ?? ""),
31
+ promptQueue: (sessionID, id, text, delivery) => context.session.prompt({
32
+ sessionID, id, text, delivery, resume: true,
31
33
  }),
32
34
  };
33
35
  const runtime = deps.runtime(directory, transport);