@alexsun-top/opencode-chat-room 0.5.0 → 0.5.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +23 -7
  3. package/README.zh-CN.md +23 -7
  4. package/docs/administrator-rooms.md +51 -0
  5. package/package.json +11 -2
  6. package/plugin.ts +29 -12
  7. package/server/admin-auth.ts +16 -0
  8. package/server/admin-plan-routes.ts +79 -0
  9. package/server/admin-routes.ts +154 -0
  10. package/server/admin-scheduler.ts +42 -0
  11. package/server/admin-state.ts +61 -0
  12. package/server/admin-task-routes.ts +182 -0
  13. package/server/assets/base.css +55 -43
  14. package/server/assets/chat/admin.js +223 -0
  15. package/server/assets/chat/attachments.js +240 -0
  16. package/server/assets/chat/editor.js +211 -0
  17. package/server/assets/chat/events.js +34 -10
  18. package/server/assets/chat/index.js +8 -0
  19. package/server/assets/chat/markdown.js +1 -12
  20. package/server/assets/chat/members.js +1 -1
  21. package/server/assets/chat/mentions.js +38 -28
  22. package/server/assets/chat/message-window.js +18 -0
  23. package/server/assets/chat/messages.js +64 -46
  24. package/server/assets/chat/questions.js +113 -41
  25. package/server/assets/chat/receipts.js +0 -1
  26. package/server/assets/chat/reminders.js +101 -0
  27. package/server/assets/chat/replies.js +149 -0
  28. package/server/assets/chat/rooms.js +30 -10
  29. package/server/assets/chat/state.js +68 -18
  30. package/server/assets/conversation.css +111 -45
  31. package/server/assets/responsive.css +83 -28
  32. package/server/chat-server.ts +23 -6
  33. package/server/chat.html +82 -31
  34. package/server/inbox.ts +5 -1
  35. package/server/newrooms.ts +27 -10
  36. package/server/resource-routes.ts +3 -0
  37. package/server/room-reminders.ts +212 -0
  38. package/server/wake.ts +11 -15
  39. package/skills/chatroom/SKILL.md +21 -1
  40. package/src/admin-client.ts +130 -0
  41. package/src/admin-credentials.ts +58 -0
  42. package/src/agent-receipts.ts +13 -18
  43. package/src/center-client.ts +1 -1
  44. package/src/center-inbox.ts +2 -0
  45. package/src/plugin-notifications.ts +4 -0
  46. package/src/queue.ts +7 -2
  47. package/src/reminder-client.ts +50 -0
  48. package/src/resource-read.ts +118 -0
  49. package/src/resources.ts +1 -1
  50. package/src/sqlite-state.ts +89 -21
  51. package/src/store.ts +22 -8
  52. package/src/supervision-inbox.ts +62 -0
  53. package/src/v1-plugin.ts +13 -3
  54. package/src/v2-plugin.ts +24 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.5.2 — 2026-11-10
4
+
5
+ - Add replies with linked message quotes, navigation to the original, and an automatic author mention. Replying to a question answers it using the existing atomic answer operation.
6
+ - Render pending questions as Markdown, enlarge the question panel, and provide a copy action. Hide copy controls for system messages and remove the message excerpt from the reader panel.
7
+ - Show mentions as atomic tokens while editing and preserve the existing message format when sending.
8
+ - Fix own messages being counted as unread by the background room watcher and refresh the jump button after a confirmed read.
9
+ - Include a bounded excerpt of the original question in answer notifications without changing the stored message.
10
+ - Show administrator-room indicators to authorized operators and clarify that a designated administrator manages all rooms.
11
+ - Add the `read_resource` room action to stream attachments into private temporary files for an Agent to inspect using its own tools.
12
+ - Raise the default server upload limit to 500 MiB per file; operators can still configure a different limit.
13
+ - Add persistent room reminders for one-time and CRON schedules, with member management and message templates.
14
+
15
+ ## 0.5.1 — 2026-11-09
16
+
17
+ - Refine the web chat visual system with a warmer light/dark palette, clearer typography, and more consistent message, composer, sidebar, attachment, and admin surfaces.
18
+ - Remove code-block copy controls while retaining ordinary message copying and readable, selectable code blocks.
19
+ - Add browser file selection, drag-and-drop attachments, and pasted images, with upload progress, retries, removal, and review before sending. Attachment markers share the existing message limit and room-scoped resource API.
20
+ - Expose the authenticated server upload limit through `GET /resources/config` so the browser can validate against the configured limit instead of a separate hard-coded default.
21
+ - Restore the avatar and name in a bottom-left user menu, move language controls into settings, and place leave/delete actions in a room options menu.
22
+ - Block the interactive join view while restoring an existing browser identity; preserve retry behavior for transient failures.
23
+ - Add opt-in administrator rooms with one operator-designated Agent, separate enrollment and scoped capabilities, cross-room tasks, worker progress reports, and persistent recurring supervision plans.
24
+ - Keep supervisor reminders capability-protected, coalesce offline checks, and retain stable delivery admissions across retries. Timer acceptance does not imply task completion.
25
+ - Exclude the caller's own messages from unread counts and Agent polls, poll observed V1 sessions periodically for admin delivery, use native `msg_` admission IDs with migration for pending admin deliveries, cancel nonterminal tasks on enrollment rotation, and send optional immediate server wake through the V1 `prompt_async` endpoint.
26
+ - Stop wheel overscroll at the conversation boundaries so continuing to scroll at the bottom no longer jitters the view by a few pixels.
27
+ - Document the operator setup and the existing shared-token trust limit for worker status reports.
28
+
3
29
  ## 0.5.0 — 2026-11-08
4
30
 
5
31
  - Keep room notifications compact: room identity and message content remain, while repeated response instructions move into the bundled `chatroom` skill.
package/README.md CHANGED
@@ -80,17 +80,17 @@ On the server machine, install Bun first. `npx`, `pnpx`, and `bunx` only execute
80
80
 
81
81
  ```bash
82
82
  # Show CLI options:
83
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --help
83
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --help
84
84
 
85
85
  # Start the local central server (choose any one runner):
86
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
- pnpx --package=@alexsun-top/opencode-chat-room@0.4.0 opencode-chat-room --host 0.0.0.0 --port 4399
88
- bunx @alexsun-top/opencode-chat-room@0.4.0 --host 0.0.0.0 --port 4399 --token secret
86
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
+ pnpx --package=@alexsun-top/opencode-chat-room@0.5.2 opencode-chat-room --host 0.0.0.0 --port 4399
88
+ bunx @alexsun-top/opencode-chat-room@0.5.2 --host 0.0.0.0 --port 4399 --token secret
89
89
 
90
90
  # Environment variables also work; CLI options take precedence:
91
91
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
92
92
  CHAT_ROOM_SERVER_TOKEN=secret \
93
- bunx @alexsun-top/opencode-chat-room@0.4.0
93
+ bunx @alexsun-top/opencode-chat-room@0.5.2
94
94
 
95
95
  # Local checkout:
96
96
  bun install
@@ -113,10 +113,16 @@ The central server uses a trusted shared-token model, not per-user authorization
113
113
 
114
114
  ### Question messages (0.4.0)
115
115
 
116
- Use `room` with `action: "send"`, `roomId`, `text`, and `isQuestion: true` to send a question. In web chat, enable **Question** before sending. Open the room's **Questions** panel to answer pending questions one at a time. Ordinary chat replies do not dismiss questions. After an answer is saved, the question leaves the pending list; both messages remain in history.
116
+ Use `room` with `action: "send"`, `roomId`, `text`, and `isQuestion: true` to send a question. In web chat, enable **Question** before sending. Answer from the **Questions** panel or reply directly to the question message. After an answer is saved, the question leaves the pending list; both messages remain in history.
117
117
 
118
118
  `GET /rooms/:roomId/questions` returns `{ questions }`, oldest first, including pending questions outside the visible history window. `POST /rooms/:roomId/questions/:questionID/answers` accepts `{ sessionID, text }` and returns `{ questionID, answer }`. The server requires current room membership and saves the answer and answered state atomically; competing answers receive HTTP 409. Questions have `isQuestion` and, after answering, `answeredByMessageID`; answers have `answerToMessageID`. These routes use the existing shared room token, not separate human authentication.
119
119
 
120
+ ### Room reminders
121
+
122
+ `GET /rooms/:roomId/reminders?sessionID=...`, `POST /rooms/:roomId/reminders`, `PATCH /rooms/:roomId/reminders/:id`, and `DELETE /rooms/:roomId/reminders/:id` require a current room member and the existing shared server token. Create with `{ sessionID, text, schedule }`; schedules are `{ type: "once", at, timezone? }` or `{ type: "cron", expression, timezone? }`. Cron expressions have five fields and recur no more often than once per minute. An omitted timezone uses the server's IANA timezone. Naive one-time timestamps are interpreted in that timezone (or the supplied IANA timezone); timestamps with `Z` or an offset specify the instant, while an optional timezone controls display only. Ambiguous or nonexistent local times during daylight-saving transitions are rejected; include an explicit offset to select an instant. `{time}` is rendered with the effective timezone and offset. The final rendered message must fit within 2,000 characters. Reminders persist if their creator leaves; every current member can manage them, and deleting the room deletes its reminders.
123
+
124
+ Agents use the `room` tool's `reminder_create`, `reminder_list`, `reminder_update`, and `reminder_delete` actions. Web members can manage reminders from the room header. Templates support `{time}`, `{initiator}`, and `{room}`. The server posts a system message when due; missed recurring occurrences coalesce into one message, and an overdue one-time reminder fires once after recovery.
125
+
120
126
  Version 0.4.0 requires an explicit non-empty `name` for `room`'s `join` action. Other actions keep their existing arguments; existing memberships are not renamed. Upgrade the central server for the question APIs and OC Chat interface, and reload client plugins for `isQuestion` and named joins. Back up the SQLite database before upgrading; the migration preserves old messages as ordinary messages.
121
127
 
122
128
  ### Room announcements
@@ -131,9 +137,17 @@ Use a fenced code block tagged `mermaid` in a message to render a diagram. The r
131
137
 
132
138
  ### Files and media
133
139
 
140
+ In web chat, use the attachment button, drop files into the conversation, or paste an image into the composer. Review the staged attachments before sending; uploading does not post a message. You can send attachments alone or with a caption. Progress, retry, and removal controls are shown beside staged files. Ordinary text paste remains unchanged.
141
+
142
+ Uploads stay associated with their original room when switching conversations. Message retries reuse the uploaded resource IDs. Resource markers count toward the 2,000-character message limit. The browser reads the server's current single-file limit from the authenticated `GET /resources/config` endpoint; the upload endpoint remains authoritative if settings change.
143
+
144
+ Unsent attachments are held in the current page and are cleared on reload. If sending fails, the failed-message entry retains its resource references for retry, rather than leaving the same attachments in two sendable drafts. Retrying an oversized file refreshes the server limit. Code blocks remain selectable but no longer have separate copy buttons; whole-message copying is still available.
145
+
134
146
  In central mode, an Agent can call `room` with `action: "upload_resource"`, `roomId`, and `filePath`. The plugin requests file-read permission, streams the local file to the server, and returns resource metadata and a marker such as `[[resource:550e8400-e29b-41d4-a716-446655440000]]`. Include the marker in a normal `send` message to share it; uploading alone does not post a message or join a room.
135
147
 
136
- The server-wide single-file limit defaults to 100 MiB (104,857,600 bytes). Configure `CHAT_ROOM_MAX_FILE_SIZE_MB` on the server to change it. The server counts streamed bytes, including requests without `Content-Length`. Uploads require room membership. Retrieval follows the server's existing token configuration; set `CHAT_ROOM_SERVER_TOKEN` before exposing the server to other networks.
148
+ To retrieve a room attachment, call `room` with `action: "read_resource"`, `roomId`, and the marker UUID as `resourceId`. The tool saves the attachment to a private temporary file and returns its path, without exposing the server token. The Agent can then decide whether to read it. The limit is 512 MiB or the server's configured limit, whichever is lower; if the server limit cannot be fetched, the 512 MiB safety cap applies. Successful files remain until removed or cleaned up by the operating system. Resource access uses the server's existing shared-token permissions.
149
+
150
+ The server-wide single-file limit defaults to 500 MiB (524,288,000 bytes). Configure `CHAT_ROOM_MAX_FILE_SIZE_MB` on the server to change it. The server counts streamed bytes, including requests without `Content-Length`. Uploads require room membership. Retrieval follows the server's existing token configuration; set `CHAT_ROOM_SERVER_TOKEN` before exposing the server to other networks.
137
151
 
138
152
  The browser offers downloads and on-demand previews for recognized raster images, audio, and video. Other formats, including SVG and HTML, are download-only. Playback depends on browser codec support. Resource files live beside the SQLite database in `resources/<roomID>/`; back up both. Room deletion removes its resources. Unreferenced uploads remain until the room is deleted; no automatic expiration or aggregate disk quota is provided.
139
153
 
@@ -197,6 +211,8 @@ Then start opencode normally. Room state lives on the central server. Clients on
197
211
 
198
212
  ## Tool reference
199
213
 
214
+ Administrator-room setup, scoped Agent enrollment, cross-room tasks, and persistent supervision plans are described in [Administrator rooms](docs/administrator-rooms.md). Administration requires a separate server operator credential; the ordinary room token does not grant these privileges.
215
+
200
216
  | Action | Args | Result |
201
217
  |---|---|---|
202
218
  | `create` | `name` (required) | Creates the room; creator becomes owner and first member |
package/README.zh-CN.md CHANGED
@@ -80,17 +80,17 @@ OpenCode 2.2.1 会在默认 60 分钟无活动后卸载闲置项目的服务。W
80
80
 
81
81
  ```bash
82
82
  # 查看 CLI 选项:
83
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --help
83
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --help
84
84
 
85
85
  # 启动本地中心服务器(三选一):
86
- npx --yes --package=@alexsun-top/opencode-chat-room@0.4.0 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
- pnpx --package=@alexsun-top/opencode-chat-room@0.4.0 opencode-chat-room --host 0.0.0.0 --port 4399
88
- bunx @alexsun-top/opencode-chat-room@0.4.0 --host 0.0.0.0 --port 4399 --token secret
86
+ npx --yes --package=@alexsun-top/opencode-chat-room@0.5.2 -- opencode-chat-room --host 0.0.0.0 --port 4399
87
+ pnpx --package=@alexsun-top/opencode-chat-room@0.5.2 opencode-chat-room --host 0.0.0.0 --port 4399
88
+ bunx @alexsun-top/opencode-chat-room@0.5.2 --host 0.0.0.0 --port 4399 --token secret
89
89
 
90
90
  # 也可以使用环境变量;CLI 参数优先:
91
91
  CHAT_ROOM_SERVER_HOST=127.0.0.1 CHAT_ROOM_SERVER_PORT=4399 \
92
92
  CHAT_ROOM_SERVER_TOKEN=secret \
93
- bunx @alexsun-top/opencode-chat-room@0.4.0
93
+ bunx @alexsun-top/opencode-chat-room@0.5.2
94
94
 
95
95
  # 本地 checkout:
96
96
  bun install
@@ -113,10 +113,16 @@ bun run server
113
113
 
114
114
  ### 问题消息(0.4.0)
115
115
 
116
- Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQuestion: true` 发送问题。网页发送前勾选“问题”,在当前房间的“问题”面板逐条回答。普通聊天回复不会自动消除问题;回答保存成功后,问题移出待回答列表,问题和回答仍保留在历史记录中。
116
+ Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQuestion: true` 发送问题。网页发送前勾选“问题”;可以在“问题”面板回答,也可以直接回复问题消息。回答保存成功后,问题移出待回答列表,问题和回答仍保留在历史记录中。
117
117
 
118
118
  `GET /rooms/:roomId/questions` 返回 `{ questions }`,按时间从旧到新排列,包含可视历史窗口以外的未回答问题。`POST /rooms/:roomId/questions/:questionID/answers` 接受 `{ sessionID, text }`,返回 `{ questionID, answer }`。服务端要求当前房间成员身份,并原子保存回答和已回答状态;并发重复回答返回 HTTP 409。问题包含 `isQuestion`,回答后增加 `answeredByMessageID`;回答包含 `answerToMessageID`。接口沿用共享令牌,不提供独立的人类身份认证。
119
119
 
120
+ ### 房间提醒
121
+
122
+ 房间成员可在网页房间头部管理提醒;Agent 可通过 `room` 的 `reminder_create`、`reminder_list`、`reminder_update` 和 `reminder_delete` 操作管理。提醒支持一次性时间或五字段 CRON 表达式,模板可使用 `{time}`、`{initiator}` 和 `{room}`。到期时服务器向房间发送系统消息;错过的周期合并为一条,一次性提醒在服务器恢复后补发一次。创建者离房后提醒继续,删除房间时提醒一并删除。
123
+
124
+ 时区默认使用服务器时区,也可指定 IANA 时区。未带偏移的一次性时间按指定或服务器时区解释;带 `Z` 或偏移的时间表示明确时刻,指定的时区用于显示。夏令时中不存在或有歧义的本地时间会被拒绝,可用明确偏移指定时刻。提醒管理沿用共享令牌及房间成员权限。
125
+
120
126
  0.4.0 中,`room` 的 `join` 操作必须显式传入非空 `name`;其他操作参数不变,已有成员不会被改名。问题接口和 OC Chat 界面需升级中心服务器,`isQuestion` 和具名加入需重新加载客户端插件。升级前请备份 SQLite 数据库;迁移将旧消息保留为普通消息。
121
127
 
122
128
  ### 公告栏
@@ -131,9 +137,17 @@ Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQues
131
137
 
132
138
  ### 文件与多媒体
133
139
 
140
+ 网页支持附件按钮选择文件、向对话拖放文件,以及在输入框粘贴图片。文件先进入待发送区域,显示上传进度、重试和移除操作;确认后再发送,可仅发附件,也可附带文字。普通文本粘贴行为不变。
141
+
142
+ 切换房间不会把上传结果混入另一房间;消息发送失败时复用已上传的资源 ID。资源标记同样计入消息的 2000 字符限制。网页通过认证接口 `GET /resources/config` 读取当前单文件上限,实际上传仍由服务器最终校验。
143
+
144
+ 未发送附件仅保留在当前页面,刷新后会清除。发送失败后,由失败消息记录保留资源引用供重试,不会同时留在两个可发送草稿中。超限文件重试时会刷新服务器限制。代码块仍可选择文本,但不再提供独立的复制按钮;整条消息的复制功能保留。
145
+
134
146
  中心模式下,Agent 调用 `room`,传入 `action: "upload_resource"`、`roomId` 和本地 `filePath`。插件先申请文件读取权限,再流式上传,返回资源信息和 `[[resource:资源UUID]]` 标记。将标记放入普通 `send` 消息即可分享;上传本身不会发送消息或自动加入房间。
135
147
 
136
- 服务器默认单文件上限为 100 MiB(104857600 字节),通过服务器环境变量 `CHAT_ROOM_MAX_FILE_SIZE_MB` 统一调整。上传要求已有房间成员身份;读取沿用现有 token 配置,对外部署前应设置 `CHAT_ROOM_SERVER_TOKEN`。服务器按实际接收字节限制大小,不依赖请求声明的长度。
148
+ 获取房间附件时,调用 `room` 并传入 `action: "read_resource"`、`roomId` 和标记中的 UUID(`resourceId`)。工具将附件保存到私有临时文件并返回路径,不暴露服务器令牌;Agent 可自行决定是否读取该文件。单个附件上限为 512 MiB 和服务器配置上限中的较小值;无法获取服务器上限时使用 512 MiB 安全上限。成功下载的文件会保留到手动删除或操作系统清理临时目录。资源访问仍使用服务器现有的共享令牌权限。
149
+
150
+ 服务器默认单文件上限为 500 MiB(524288000 字节),通过服务器环境变量 `CHAT_ROOM_MAX_FILE_SIZE_MB` 统一调整。上传要求已有房间成员身份;读取沿用现有 token 配置,对外部署前应设置 `CHAT_ROOM_SERVER_TOKEN`。服务器按实际接收字节限制大小,不依赖请求声明的长度。
137
151
 
138
152
  网页支持识别到的栅格图片、音频和视频的按需预览,其他文件提供下载;SVG、HTML 不内嵌执行。播放能力取决于浏览器支持的编码。资源存放在 SQLite 数据库旁的 `resources/<roomID>/`,备份时须同时保留。删除房间会清理其资源;未引用的上传文件保留到房间删除,暂不提供自动过期或总磁盘配额。
139
153
 
@@ -196,6 +210,8 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
196
210
 
197
211
  ## 工具参考
198
212
 
213
+ 管理员房间、专属 Agent 授权、跨房间派活和持久定时监督见 [管理员房间说明](docs/administrator-rooms.md)。管理功能需要独立的服务器操作员凭证,普通房间 token 不授予管理员权限。
214
+
199
215
  | 操作 | 参数 | 结果 |
200
216
  |---|---|---|
201
217
  | `create` | `name`(必填) | 创建房间;创建者成为 owner 及第一名成员 |
@@ -0,0 +1,51 @@
1
+ # Administrator rooms
2
+
3
+ An administrator room is a normal group room with one operator-designated Agent. That Agent can inspect the central server's rooms, dispatch tasks to specific existing Agent sessions, and schedule recurring supervision reminders without joining target rooms.
4
+
5
+ Administration is opt-in. Configure `CHAT_ROOM_ADMIN_TOKEN` on the central server with a secret different from `CHAT_ROOM_SERVER_TOKEN`. Ordinary room access still uses the existing server token. This change does not update an existing deployment or its configuration automatically.
6
+
7
+ Both server tokens must be set to enable administration. The operator credential is also required when deleting an administrator room or the room anchoring its designated Agent, because deletion would remove the associated administration records.
8
+
9
+ ## Enroll the designated Agent
10
+
11
+ 1. Open settings from the bottom-left user menu and enter the separate administration token. The browser retains it only for that tab.
12
+ 2. Use the administration panel to designate an existing Agent membership for an administrator room.
13
+ 3. Copy the one-time enrollment instruction and send it privately to the selected Agent session. Do not post it in a room.
14
+ 4. The Agent calls the `admin` tool with `action: "admin_claim"`, the administrator `roomId`, and the `enrollmentKey`.
15
+
16
+ The plugin binds the claim to its native session and receiver owner. It stores the returned capability privately on the host instead of displaying it in tool output. If enrollment expires, its response is lost, or credential persistence fails, reset enrollment from the operator panel.
17
+
18
+ Reassigning the designation revokes the previous capability. Joining or rejoining a room never grants administrator privileges. Agent capabilities cannot replace the designated Agent or issue new enrollment keys.
19
+
20
+ ## Dispatch and supervise
21
+
22
+ The `admin` tool uses `roomId` for the administrator room; `targetRoomId` and `targetSessionID` identify the worker. Ordinary `room` tool behavior is unchanged.
23
+
24
+ | Action | Additional arguments | Purpose |
25
+ | --- | --- | --- |
26
+ | `admin_overview` | None | Inspect rooms, members, tasks, and plans |
27
+ | `admin_history` | `targetRoomId`, optional `limit` | Inspect bounded target-room history |
28
+ | `admin_dispatch` | `targetRoomId`, `targetSessionID`, `text` | Create a task for an existing Agent |
29
+ | `admin_tasks` | None | List tracked tasks |
30
+ | `admin_task_update` | `taskId`, `status`, optional `progress` | Record task progress and blockers |
31
+ | `admin_plans` | None | Inspect recurring supervision plans |
32
+ | `admin_plan_create` | `name`, `intervalSeconds`, `text` | Schedule checks of work progress |
33
+ | `admin_plan_update` | `planId`, `paused` | Pause or resume a plan |
34
+ | `admin_plan_delete` | `planId` | Remove a plan |
35
+ | `task_progress` | `taskId`, `status`, `progress` | Let the assigned worker report progress without administrator privileges |
36
+
37
+ Task states are `pending`, `working`, `blocked`, `completed`, and `cancelled`. Status is reported information, not proof that the work was reviewed or completed correctly.
38
+
39
+ Workers receive the task ID and reporting instructions with their assignment. The plugin retains a task-scoped reporting token privately, before delivering the assignment to the host. Progress reports use the worker's native session and receiver owner; they do not require the administrator's capability or operator token. The token is not part of the prompt.
40
+
41
+ Worker delivery remains inside the existing shared-server-token trust domain: a client holding that token can impersonate another client's routing IDs and obtain its worker assignment. Worker status is therefore self-reported information, not independent authenticated evidence. Global supervisor reminders require the designated Agent's capability for both retrieval and acknowledgement.
42
+
43
+ Cancelling queued work prevents later delivery and revokes its progress token. Instructions already accepted by a host cannot be recalled; coordinate cancellation with the worker when execution may already have started.
44
+
45
+ The server persists schedules and pending deliveries. Reminders steer the designated supervisor; offline periods are coalesced rather than replayed as a backlog of reminders. The host must be available to execute an Agent. A timer firing, a host accepting a steer, and an Agent completing work are separate events.
46
+
47
+ ## Security and operations
48
+
49
+ Use HTTPS outside loopback. Keep operator credentials, enrollment keys, and capabilities out of room messages, URLs, logs, and shared screenshots. The server authenticates secret possession; caller-supplied session IDs are not credentials. Processes with unrestricted access to the same OS account can read one another's files, so private file modes do not provide sandbox isolation between such Agents.
50
+
51
+ Back up server SQLite state to preserve designations, tasks, and schedules. Host-local capabilities must also remain available to the enrolled plugin after restart. Revocation requires operator enrollment reset rather than copying credentials between sessions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.5.0",
3
+ "version": "0.5.2",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -32,10 +32,18 @@
32
32
  "server/member-routes.ts",
33
33
  "server/announcement-routes.ts",
34
34
  "server/resource-routes.ts",
35
+ "server/admin-routes.ts",
36
+ "server/admin-state.ts",
37
+ "server/admin-auth.ts",
38
+ "server/admin-task-routes.ts",
39
+ "server/admin-plan-routes.ts",
40
+ "server/admin-scheduler.ts",
41
+ "server/room-reminders.ts",
35
42
  "server/wake.ts",
36
43
  "server/chat.html",
37
44
  "server/assets",
38
45
  "CHANGELOG.md",
46
+ "docs/administrator-rooms.md",
39
47
  "README.md",
40
48
  "README.zh-CN.md"
41
49
  ],
@@ -45,7 +53,7 @@
45
53
  },
46
54
  "scripts": {
47
55
  "server": "bun run server/chat-server.ts",
48
- "test": "bun test",
56
+ "test": "for file in src/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done",
49
57
  "typecheck": "tsc --noEmit"
50
58
  },
51
59
  "devDependencies": {
@@ -59,6 +67,7 @@
59
67
  "dependencies": {
60
68
  "@opencode-ai/plugin": "^1.18.29",
61
69
  "@opencode/client": "2.0.32",
70
+ "croner": "11.0.0",
62
71
  "zod": "4.1.8"
63
72
  }
64
73
  }
package/plugin.ts CHANGED
@@ -23,16 +23,16 @@ import { createQueueTransport, type QueueTransport } from "./src/queue-transport
23
23
  import { checkCenterInbox } from "./src/center-inbox";
24
24
  import { assertDeliveryLease } from "./src/session-delivery";
25
25
  import { wakeSessions } from "./src/center-wake";
26
- import {
27
- clearPendingAdmission,
28
- } from "./src/queue";
26
+ import { clearPendingAdmission } from "./src/queue";
29
27
  import { createNotifier } from "./src/plugin-notifications";
30
28
  import { explicitlyAddresses } from "./src/mentions";
31
29
  import { createV2Setup, type V2Runtime } from "./src/v2-plugin";
32
30
  import { createV1Server } from "./src/v1-plugin";
33
31
  import { runAnnouncementTool } from "./src/announcement-tool";
34
32
  import { uploadAgentResource } from "./src/resource-upload";
35
-
33
+ import { readAgentResource, resourceReadFailure } from "./src/resource-read";
34
+ import { adminTool, adminToolDescription, adminToolSchema } from "./src/admin-client";
35
+ import { runReminderTool } from "./src/reminder-client";
36
36
  // ponytail: CHAT_ROOM_SERVER_URL switches to central mode (all state on a
37
37
  // central server); unset = standalone local-file mode
38
38
  const centerUrl = process.env.CHAT_ROOM_SERVER_URL ?? "";
@@ -184,7 +184,6 @@ const notifier = createNotifier({
184
184
  const { notifyRoom, notifyTarget } = notifier;
185
185
  const restoreScans = new Map<string, { afterTs: number; untilTs?: number }>();
186
186
  const restoreKey = (sid: string, roomID: string, ownerID = "") => JSON.stringify([ownerID, sid, roomID]);
187
-
188
187
  export async function pollKnownSessions(
189
188
  sessions: ReadonlySet<string>,
190
189
  transport: QueueTransport,
@@ -246,15 +245,19 @@ export async function pollKnownSessions(
246
245
 
247
246
  const READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "announcement_list", "announcement_read"]);
248
247
 
249
- const roomArgs = z.object({
250
- action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete"]),
248
+ export const roomArgs = z.object({
249
+ action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
251
250
  name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
252
251
  roomId: z.string().optional(),
252
+ resourceId: z.string().optional(),
253
253
  filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
254
254
  text: z.string().max(2000).optional(),
255
255
  isQuestion: z.boolean().optional(),
256
256
  announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
257
257
  content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
258
+ reminderId: z.string().optional(),
259
+ schedule: z.discriminatedUnion("type", [z.object({ type: z.literal("once"), at: z.string(), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() }), z.object({ type: z.literal("cron"), expression: z.string().regex(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() })]).optional(),
260
+ paused: z.boolean().optional(),
258
261
  }).superRefine((args, ctx) => {
259
262
  if (args.action === "join" && !args.name?.trim()) {
260
263
  ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });
@@ -264,11 +267,20 @@ type RoomArguments = z.infer<typeof roomArgs>;
264
267
 
265
268
  const roomExecute = async (
266
269
  args: RoomArguments,
267
- context: V1ToolContext,
270
+ context: V1ToolContext & { signal?: AbortSignal },
268
271
  ) => {
269
272
  if (args.action === "join" && !args.name?.trim()) return "error: name is required to join a room";
270
273
  const runtime = currentRuntime();
274
+ if (args.action === "reminder_list" || args.action === "reminder_create" || args.action === "reminder_update" || args.action === "reminder_delete") {
275
+ return await runReminderTool(runtime.center, args, context.sessionID);
276
+ }
271
277
  if (args.action === "upload_resource") return uploadAgentResource(runtime.center, args.roomId ?? "", args.filePath ?? "", context.sessionID, context);
278
+ if (args.action === "read_resource") {
279
+ try {
280
+ if (!context.ask) return "error: host webfetch permission is unavailable";
281
+ return await readAgentResource(runtime.center, args.roomId ?? "", args.resourceId ?? "", context, context.abort ?? context.signal);
282
+ } catch (error) { return `error: ${resourceReadFailure(error)}`; }
283
+ }
272
284
  try {
273
285
  const explicitV2Join = runtime.protocol === "v2" && (args.action === "create" || args.action === "join");
274
286
  const receiverOwnerID = explicitV2Join && runtime.transport.verifySession
@@ -304,7 +316,7 @@ const roomExecute = async (
304
316
  if (entry?.membershipID) pollIdentity = { membershipID: entry.membershipID, ...(entry.receiverOwnerID ? { receiverOwnerID: entry.receiverOwnerID } : {}) };
305
317
  selfName = entry?.name ?? selfName;
306
318
  pollLastRead = entry?.lastReadTs ?? 0;
307
- if (entry) pollPage = await readUnreadMessages(args.roomId, pollLastRead, 100);
319
+ if (entry) pollPage = await readUnreadMessages(args.roomId, pollLastRead, 100, context.sessionID, selfName);
308
320
  }
309
321
  const result = await withRooms<string>(
310
322
  (svc, registry) => {
@@ -456,13 +468,17 @@ const roomExecute = async (
456
468
  return `error: ${err instanceof Error ? err.message : String(err)}`;
457
469
  }
458
470
  };
459
-
460
471
  const room = tool({
461
- description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; upload files and media",
472
+ description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
462
473
  args: roomArgs.shape,
463
474
  execute: roomExecute,
464
475
  });
465
476
 
477
+ const admin = tool({
478
+ description: adminToolDescription,
479
+ args: adminToolSchema.shape,
480
+ execute: (args, context) => adminTool(args, context, currentRuntime().center, currentRuntime().transport),
481
+ });
466
482
  export const server = createV1Server({
467
483
  runtime: (input, transport) => ({
468
484
  protocol: "v1",
@@ -473,12 +489,12 @@ export const server = createV1Server({
473
489
  }),
474
490
  run: (runtime, callback) => runtimeContext.run(runtime, callback),
475
491
  room,
492
+ admin,
476
493
  observe: refreshSelf,
477
494
  checkInbox: (runtime, sessionID) => checkCenterInbox(runtime.center, sessionID, runtime.transport),
478
495
  wake: (runtime, sessions) => wakeSessions(runtime.center, runtime.transport, serveWakeUrl, sessions),
479
496
  central: Boolean(centerUrl),
480
497
  });
481
-
482
498
  export const setup = createV2Setup({
483
499
  runtime: (directory, transport) => ({
484
500
  protocol: "v2",
@@ -489,6 +505,7 @@ export const setup = createV2Setup({
489
505
  }),
490
506
  run: (runtime, callback) => runtimeContext.run(runtime, callback),
491
507
  execute: (args, sessionID, permissionContext) => roomExecute(args, { ...permissionContext, sessionID } as V1ToolContext),
508
+ admin: (args, sessionID, transport, center) => adminTool(args, { sessionID }, center, transport),
492
509
  observe: refreshSelf,
493
510
  poll: pollKnownSessions,
494
511
  });
@@ -0,0 +1,16 @@
1
+ import { matchesHash, safeEqual, type Binding } from "./admin-state";
2
+
3
+ const operatorSecret = process.env.CHAT_ROOM_ADMIN_TOKEN ?? "";
4
+ const serverSecret = process.env.CHAT_ROOM_SERVER_TOKEN ?? "";
5
+ export const adminEnabled = Boolean(operatorSecret && serverSecret && !safeEqual(operatorSecret, serverSecret));
6
+ export const isOperator = (request: Request) => adminEnabled && safeEqual(request.headers.get("x-chat-admin-token") ?? "", operatorSecret);
7
+
8
+ export function agentHeadersMatch(request: Request, binding: Binding): boolean {
9
+ return request.headers.get("x-chat-agent-session") === binding.session_id &&
10
+ (request.headers.get("x-chat-agent-owner") ?? "") === binding.receiver_owner_id;
11
+ }
12
+
13
+ export function hasAdminCapability(request: Request, binding: Binding): boolean {
14
+ return Boolean(binding.capability_hash && agentHeadersMatch(request, binding) &&
15
+ matchesHash(request.headers.get("x-chat-admin-capability") ?? "", binding.capability_hash));
16
+ }
@@ -0,0 +1,79 @@
1
+ import { hasAdminCapability, isOperator } from "./admin-auth";
2
+ import type { Database } from "bun:sqlite";
3
+ import { binding, exec, many, one, tx, validCurrent } from "./admin-state";
4
+ import type { Binding } from "./admin-state";
5
+
6
+ const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
7
+ const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
8
+ const auth = (request: Request, b: Binding) => isOperator(request) || hasAdminCapability(request, b);
9
+ const planRows = (db: Database, id: string) => many(db,
10
+ "SELECT id,admin_room_id AS adminRoomId,name,interval_seconds AS intervalSeconds,text,paused,next_run_at AS nextRunAt,created_at AS createdAt FROM admin_plans WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", id);
11
+
12
+ export async function adminPlanRoutes(request: Request, url: URL): Promise<Response | undefined> {
13
+ const base = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/plans$/);
14
+ const child = url.pathname.match(/^\/admin\/rooms\/([^/]+)\/plans\/([^/]+)$/);
15
+ if (!base && !child) return undefined;
16
+ const roomID = decodeURIComponent((base ?? child)![1]!);
17
+ if (base && request.method === "GET") return tx(db => {
18
+ const b = binding(db, roomID);
19
+ if (!b) return { error: "admin room not found", status: 404 };
20
+ if (!auth(request, b)) return { error: "unauthorized", status: 401 };
21
+ if (!isOperator(request) && !validCurrent(db, b)) return { error: "binding is no longer active", status: 409 };
22
+ return { plans: planRows(db, roomID) };
23
+ }).then(result => "status" in result ? json({ error: result.error }, result.status) : json(result));
24
+ if (base && request.method === "POST") return createPlan(request, roomID);
25
+ if (child && request.method === "PATCH") return updatePlan(request, roomID, decodeURIComponent(child[2]!));
26
+ if (child && request.method === "DELETE") return deletePlan(request, roomID, decodeURIComponent(child[2]!));
27
+ return json({ error: "method not allowed" }, 405);
28
+ }
29
+
30
+ async function createPlan(request: Request, roomID: string): Promise<Response> {
31
+ const body: unknown = await request.json();
32
+ if (!object(body) || typeof body.name !== "string" || !body.name.trim() || body.name.trim().length > 64 ||
33
+ typeof body.text !== "string" || !body.text.trim() || body.text.trim().length > 2000 ||
34
+ !Number.isInteger(body.intervalSeconds) || (body.intervalSeconds as number) < 60 || (body.intervalSeconds as number) > 2_592_000) return json({ error: "invalid plan" }, 400);
35
+ const name = body.name.trim(), text = body.text.trim(), interval = body.intervalSeconds as number;
36
+ const result = await tx(db => {
37
+ const b = binding(db, roomID);
38
+ if (!b) return { status: 404 as const };
39
+ if (!auth(request, b)) return { status: 401 as const };
40
+ if (!validCurrent(db, b)) return { status: 409 as const };
41
+ const id = crypto.randomUUID(), now = Date.now();
42
+ exec(db, "INSERT INTO admin_plans VALUES(?,?,?,?,?,0,?,?)", id, roomID, name, interval, text, now + interval * 1000, now);
43
+ return { plan: { id, adminRoomId: roomID, name, intervalSeconds: interval, text, paused: false, nextRunAt: now + interval * 1000, createdAt: now } };
44
+ });
45
+ if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "admin room not found" : "binding is no longer active" }, result.status);
46
+ return json(result, 201);
47
+ }
48
+
49
+ async function updatePlan(request: Request, roomID: string, planID: string): Promise<Response> {
50
+ const body: unknown = await request.json();
51
+ if (!object(body) || typeof body.paused !== "boolean") return json({ error: "paused must be boolean" }, 400);
52
+ const result = await tx(db => {
53
+ const b = binding(db, roomID);
54
+ if (!b) return { status: 404 as const };
55
+ if (!auth(request, b)) return { status: 401 as const };
56
+ if (!validCurrent(db, b)) return { status: 409 as const };
57
+ const plan = one<{ id: string; next_run_at: number; interval_seconds: number }>(db,
58
+ "SELECT id,next_run_at,interval_seconds FROM admin_plans WHERE id=? AND admin_room_id=?", planID, roomID);
59
+ if (!plan) return { status: 404 as const };
60
+ const next = body.paused ? plan.next_run_at : Date.now() + plan.interval_seconds * 1000;
61
+ exec(db, "UPDATE admin_plans SET paused=?,next_run_at=? WHERE id=?", body.paused ? 1 : 0, next, planID);
62
+ if (body.paused) exec(db, "DELETE FROM admin_deliveries WHERE admin_room_id=? AND kind='supervision' AND task_id=? AND acknowledged=0", roomID, `plan:${planID}`);
63
+ return { ok: true, nextRunAt: next };
64
+ });
65
+ if ("status" in result) return json({ error: result.status === 401 ? "unauthorized" : result.status === 404 ? "plan not found" : "binding is no longer active" }, result.status);
66
+ return json(result);
67
+ }
68
+
69
+ async function deletePlan(request: Request, roomID: string, planID: string): Promise<Response> {
70
+ const result = await tx(db => {
71
+ const b = binding(db, roomID);
72
+ if (!b) return 404;
73
+ if (!auth(request, b)) return 401;
74
+ if (!validCurrent(db, b)) return 409;
75
+ exec(db, "DELETE FROM admin_deliveries WHERE admin_room_id=? AND kind='supervision' AND task_id=? AND acknowledged=0", roomID, `plan:${planID}`);
76
+ return exec(db, "DELETE FROM admin_plans WHERE id=? AND admin_room_id=?", planID, roomID).changes ? 200 : 404;
77
+ });
78
+ return json(result === 200 ? { ok: true } : { error: result === 401 ? "unauthorized" : result === 409 ? "binding is no longer active" : "plan not found" }, result);
79
+ }