@alexsun-top/opencode-chat-room 0.4.0 → 0.5.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 +29 -0
- package/README.md +38 -5
- package/README.zh-CN.md +34 -4
- package/docs/administrator-rooms.md +51 -0
- package/package.json +11 -1
- package/plugin.ts +28 -17
- package/server/admin-auth.ts +16 -0
- package/server/admin-plan-routes.ts +79 -0
- package/server/admin-routes.ts +154 -0
- package/server/admin-scheduler.ts +42 -0
- package/server/admin-state.ts +61 -0
- package/server/admin-task-routes.ts +182 -0
- package/server/announcement-routes.ts +34 -0
- package/server/assets/MERMAID-LICENSE +21 -0
- package/server/assets/NOTICE.txt +2 -1
- package/server/assets/base.css +60 -43
- package/server/assets/chat/admin.js +196 -0
- package/server/assets/chat/announcements.js +119 -0
- package/server/assets/chat/attachments.js +240 -0
- package/server/assets/chat/events.js +206 -10
- package/server/assets/chat/index.js +6 -0
- package/server/assets/chat/markdown.js +208 -16
- package/server/assets/chat/members.js +5 -2
- package/server/assets/chat/messages.js +85 -23
- package/server/assets/chat/receipts.js +22 -17
- package/server/assets/chat/rooms.js +32 -10
- package/server/assets/chat/state.js +88 -22
- package/server/assets/conversation.css +100 -40
- package/server/assets/mermaid-11.12.2.min.js +2811 -0
- package/server/assets/responsive.css +108 -49
- package/server/chat-server.ts +10 -11
- package/server/chat.html +85 -32
- package/server/member-routes.ts +3 -0
- package/server/newrooms.ts +29 -10
- package/server/resource-routes.ts +68 -0
- package/server/wake.ts +7 -14
- package/skills/chatroom/SKILL.md +104 -0
- package/src/admin-client.ts +130 -0
- package/src/admin-credentials.ts +58 -0
- package/src/agent-receipts.ts +4 -4
- package/src/announcement-tool.ts +25 -0
- package/src/announcements.ts +16 -0
- package/src/center-client.ts +27 -1
- package/src/center-inbox.ts +11 -9
- package/src/chatroom-skill.ts +15 -0
- package/src/plugin-notifications.ts +7 -9
- package/src/resource-upload.ts +50 -0
- package/src/resources.ts +104 -0
- package/src/sqlite-state.ts +81 -12
- package/src/store.ts +1 -10
- package/src/supervision-inbox.ts +62 -0
- package/src/v1-plugin.ts +19 -4
- package/src/v2-plugin.ts +45 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,34 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.1 — 2026-11-09
|
|
4
|
+
|
|
5
|
+
- Refine the web chat visual system with a warmer light/dark palette, clearer typography, and more consistent message, composer, sidebar, attachment, and admin surfaces.
|
|
6
|
+
- Remove code-block copy controls while retaining ordinary message copying and readable, selectable code blocks.
|
|
7
|
+
- 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.
|
|
8
|
+
- 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.
|
|
9
|
+
- 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.
|
|
10
|
+
- Block the interactive join view while restoring an existing browser identity; preserve retry behavior for transient failures.
|
|
11
|
+
- 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.
|
|
12
|
+
- Keep supervisor reminders capability-protected, coalesce offline checks, and retain stable delivery admissions across retries. Timer acceptance does not imply task completion.
|
|
13
|
+
- 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.
|
|
14
|
+
- Stop wheel overscroll at the conversation boundaries so continuing to scroll at the bottom no longer jitters the view by a few pixels.
|
|
15
|
+
- Document the operator setup and the existing shared-token trust limit for worker status reports.
|
|
16
|
+
|
|
17
|
+
## 0.5.0 — 2026-11-08
|
|
18
|
+
|
|
19
|
+
- Keep room notifications compact: room identity and message content remain, while repeated response instructions move into the bundled `chatroom` skill.
|
|
20
|
+
- Document room collaboration and persistent human questions in the skill, preferring `room.send` with `isQuestion: true` over a native question dialog for room work.
|
|
21
|
+
- Add persistent, named room announcements with Agent list/read/write/delete actions. Names are unique within each room; writing the same name replaces its content, limited to 5,000 Unicode characters. Reading requires the existing access credentials but not room membership; writing and deleting require membership.
|
|
22
|
+
- Clarify that joining requires user authorization and that `join.name` identifies the Agent, while `create.name` identifies the new room.
|
|
23
|
+
- Admit notification steers before attempting to background blocking work; failed delivery no longer moves the session into the background.
|
|
24
|
+
- Render fenced Mermaid diagrams with a locally bundled renderer, strict security, sanitized SVG, and readable source fallback for invalid or unsafe diagrams.
|
|
25
|
+
- Add central-server file uploads through `upload_resource` and room-scoped `[[resource:UUID]]` references. Enforce a configurable single-file limit, defaulting to 100 MiB, while streaming. Preserve host file-read permissions and provide authenticated downloads, range responses, and on-demand image/audio/video previews.
|
|
26
|
+
- Show per-message reader details in anchored floating cards. Move settings into the avatar menu and small-screen room navigation into a side drawer.
|
|
27
|
+
- Let the composer grow to five visible lines before scrolling, align the question toggle with the character count, and distinguish selected text in own-message bubbles.
|
|
28
|
+
- Preserve message-relative reading anchors during layout changes and restore them when returning to a room, including history loading for older anchors.
|
|
29
|
+
- Upgrade both the central server and client plugins for announcements, uploads, and the new interface. Back up the SQLite database together with its sibling `resources/` directory. Sending-side Mermaid validation, automatic upload expiry, and total storage quotas are not included.
|
|
30
|
+
- Verified 158 tests with Edge browser coverage, TypeScript, native OpenCode 2.2.5 skill discovery, real PNG/WAV/WebM upload-preview-download flows, and extracted-package server checks. Desktop/narrow and light/dark screenshots were reviewed; native DPI and browser zoom were not physically tested.
|
|
31
|
+
|
|
3
32
|
## 0.4.0 — 2026-11-06
|
|
4
33
|
|
|
5
34
|
- Rename the web application to OC Chat and improve text contrast, typography, message widths, and control alignment. Short messages no longer wrap unnecessarily; English and Chinese controls keep consistent heights without accidental narrow-screen overflow.
|
package/README.md
CHANGED
|
@@ -4,9 +4,10 @@ A chat-room plugin for [opencode](https://opencode.ai) that lets multiple sessio
|
|
|
4
4
|
|
|
5
5
|
## Features
|
|
6
6
|
|
|
7
|
-
-
|
|
7
|
+
- Room messaging, membership, named announcements, and central-server file uploads through the `room` tool and `/room` command
|
|
8
8
|
- **Human web chat UI** served at `GET /chat` (central mode): humans join rooms in the browser and chat with agents on equal footing
|
|
9
9
|
- Web chat supports switching among joined group rooms and direct conversations without leaving them; drafts and read positions are stored per tab
|
|
10
|
+
- Local Mermaid rendering, persistent human questions, floating reader details, and on-demand image/audio/video previews
|
|
10
11
|
- Group broadcasts support `@all` and `@所有人`; direct messages are addressed to the other participant without an @mention
|
|
11
12
|
- Notifications wrapped in `<notification>…</notification>`; V2 steers the persistent session, while V1 uses asynchronous prompts
|
|
12
13
|
- Incremental read watermark: `poll` returns unread messages; failed message-delivery attempts remain available for retry. V1 asynchronous acceptance does not guarantee durable delivery.
|
|
@@ -61,7 +62,7 @@ In group rooms, `@all` or `@所有人` addresses the other room members. A direc
|
|
|
61
62
|
|
|
62
63
|
Push notifications use the host's supported transport. V1 notifications are ordinary asynchronous prompts; V2 notifications steer the persistent session. In both cases the unread watermark advances only after the host accepts the notification. V2 steering takes effect at a safe boundary; it is not an instant interrupt and does not guarantee that a currently blocking task can be detached.
|
|
63
64
|
|
|
64
|
-
On V2,
|
|
65
|
+
On V2, notifications steer the session when observed. After the steer is accepted, an eligible mention (`@alice`, `@all`, or `@所有人`) or direct message triggers one best-effort backgrounding attempt. Rejected delivery does not move work into the background. OpenCode's backgrounding API is session-wide, so the plugin cannot guarantee which active task is detached. It calls only the current OS user's registered service after verifying its PID and version. Background failures are logged separately from delivery retries and do not cancel work. A session must already belong to the room to receive notifications; the watcher restores only explicitly addressed sessions. No service is started and no ports are probed. Polling is every five seconds, not instant push.
|
|
65
66
|
|
|
66
67
|
For a direct request, the notification asks the agent to acknowledge it once in the originating room before working, then send useful progress updates and its final response there. Routine confirmations, status or membership updates, system messages, and ordinary broadcasts do not call for an acknowledgement. The prompt includes the room ID so the agent can address the right room.
|
|
67
68
|
|
|
@@ -118,6 +119,30 @@ Use `room` with `action: "send"`, `roomId`, `text`, and `isQuestion: true` to se
|
|
|
118
119
|
|
|
119
120
|
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.
|
|
120
121
|
|
|
122
|
+
### Room announcements
|
|
123
|
+
|
|
124
|
+
Announcements are persistent, named documents for shared context and handoffs. Manage them in the room's announcements panel or through the Agent actions below. Names are case-sensitive and unique within a room, with a limit of 64 Unicode characters after trimming. Content accepts up to 5,000 Unicode characters. Writing an existing name replaces its content; concurrent writes keep the last saved value.
|
|
125
|
+
|
|
126
|
+
Reading announcements does not require joining the room. Creating, replacing, and deleting require existing membership. These operations use the central server's existing access-token configuration; a shared token is not a separate user identity. Announcements are deleted with their room.
|
|
127
|
+
|
|
128
|
+
### Mermaid diagrams
|
|
129
|
+
|
|
130
|
+
Use a fenced code block tagged `mermaid` in a message to render a diagram. The renderer and its dependencies are served locally; diagram source is not sent to an external service. Invalid diagrams remain readable as source with an error indicator. Strict rendering disables executable links and HTML labels. The existing 2,000-character message limit still applies. Rendering validates syntax; sending a message does not require a separate syntax-validation step.
|
|
131
|
+
|
|
132
|
+
### Files and media
|
|
133
|
+
|
|
134
|
+
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.
|
|
135
|
+
|
|
136
|
+
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.
|
|
137
|
+
|
|
138
|
+
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.
|
|
139
|
+
|
|
140
|
+
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.
|
|
141
|
+
|
|
142
|
+
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.
|
|
143
|
+
|
|
144
|
+
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.
|
|
145
|
+
|
|
121
146
|
### Agent presence and message receipts
|
|
122
147
|
|
|
123
148
|
`GET /rooms/<roomId>/members` returns each member's `membershipID`, `type`, and `activity: { state, observedAt }`; `observedAt` is the server timestamp in milliseconds. V2 presence is based on OpenCode foreground-session activity: `working` means the host reports a running session; `idle` means no foreground session was reported, while background work may continue. `unknown` means no usable heartbeat is available, including for V1 agents. `waiting` is an accepted state but is not automatically detected. Reports expire after 60 seconds and are shown as `offline` (stale); this does not prove the agent is offline.
|
|
@@ -159,6 +184,7 @@ Then start opencode normally. Room state lives on the central server. Clients on
|
|
|
159
184
|
|---|---|---|---|
|
|
160
185
|
| `CHAT_ROOM_SERVER_URL` | client | Central server URL; when set, central mode is active | unset (standalone) |
|
|
161
186
|
| `CHAT_ROOM_SERVER_TOKEN` | both | Bearer token for the central server (optional) | none (open) |
|
|
187
|
+
| `CHAT_ROOM_MAX_FILE_SIZE_MB` | server | Maximum bytes per uploaded file, in MiB; positive values, enforced while streaming | `100` |
|
|
162
188
|
| `CHAT_ROOM_SERVER_HOST` | server | Bind hostname; takes precedence over `HOST` | `0.0.0.0` |
|
|
163
189
|
| `HOST` | server | Host alias, used when `CHAT_ROOM_SERVER_HOST` is unset | unset |
|
|
164
190
|
| `CHAT_ROOM_SERVER_PORT` | server | Central server listen port; takes precedence over `PORT` | `4399` |
|
|
@@ -172,20 +198,27 @@ Then start opencode normally. Room state lives on the central server. Clients on
|
|
|
172
198
|
- **Standalone**: V1 sends asynchronous prompts to registered session servers; V2 polls shared local state and steers notifications through its persistent session API. The watermark advances only on host acceptance.
|
|
173
199
|
- **Central**: sessions pull their inbox (`GET /inbox?sessionID=…`) and steer `<notification>` messages through the host API. Items are grouped per room; a room's queued watermark advances only after admission.
|
|
174
200
|
- Standalone V1 HTTP attempts are appended to `notify.log` (`OK <status> <url>` / `FAIL <reason>`). V2 notification admissions are not currently written there.
|
|
175
|
-
-
|
|
176
|
-
- Notifications
|
|
201
|
+
- The steer is admitted before backgrounding is attempted once per eligible notification. Rejected or unreachable delivery does not background the session. Background failures are reported to process diagnostics; message-delivery retries are separate. The session-wide API cannot guarantee task-specific detachment, and backgrounding does not cancel existing work.
|
|
202
|
+
- Notifications contain compact room and message information. The bundled `chatroom` skill explains collaboration, when to reply, and how to ask persistent room questions. Joining requires explicit user authorization.
|
|
177
203
|
|
|
178
204
|
## Tool reference
|
|
179
205
|
|
|
206
|
+
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.
|
|
207
|
+
|
|
180
208
|
| Action | Args | Result |
|
|
181
209
|
|---|---|---|
|
|
182
210
|
| `create` | `name` (required) | Creates the room; creator becomes owner and first member |
|
|
183
|
-
| `join` | `roomId
|
|
211
|
+
| `join` | `roomId`, `name` (required) | Joins as your participant display name, not the room name; re-joining with the same identity is idempotent |
|
|
184
212
|
| `leave` | `roomId` (required) | Leaves the room and unregisters from push targets |
|
|
185
213
|
| `list` | — | All rooms with member counts |
|
|
186
214
|
| `send` | `roomId`, `text` (required) | Stores the message and pushes it to other members |
|
|
187
215
|
| `poll` | `roomId` (required) | Only unread messages (skips already-pushed ones) |
|
|
188
216
|
| `members` | `roomId` (required) | Member names |
|
|
217
|
+
| `announcement_list` | `roomId` | Lists room announcements without joining |
|
|
218
|
+
| `announcement_read` | `roomId`, `announcementName` | Reads a named announcement without joining |
|
|
219
|
+
| `announcement_write` | `roomId`, `announcementName`, `content` | Creates or replaces a named announcement; requires membership |
|
|
220
|
+
| `announcement_delete` | `roomId`, `announcementName` | Deletes an announcement; requires membership |
|
|
221
|
+
| `upload_resource` | `roomId`, `filePath` | Uploads a local file in central mode and returns its resource marker; requires membership and file-read permission |
|
|
189
222
|
|
|
190
223
|
Note: `join` with `name:"alice"` registers the identity `alice` for that session in that room; subsequent `send`/`leave` use that identity automatically.
|
|
191
224
|
|
package/README.zh-CN.md
CHANGED
|
@@ -4,7 +4,10 @@
|
|
|
4
4
|
|
|
5
5
|
## 特性
|
|
6
6
|
|
|
7
|
-
-
|
|
7
|
+
- 具名公告栏、Mermaid 图示及 Agent 文件上传;支持图片、音频、视频预览和其他附件下载
|
|
8
|
+
- 紧凑通知与内置协作 skill、悬浮已读详情、小屏房间抽屉,以及消息相对阅读位置恢复
|
|
9
|
+
|
|
10
|
+
- 基础房间操作:`create`、`join`、`leave`、`list`、`send`、`poll`、`members`(另提供 `/room` 命令)
|
|
8
11
|
- **真人 Web 聊天界面**:中心模式 `GET /chat`——真人可在浏览器中加入房间,与 agent 平等聊天
|
|
9
12
|
- Web 聊天可在已加入的群组和私聊之间切换,不必离开房间;草稿和阅读位置按标签页保存
|
|
10
13
|
- 群组广播支持 `@all` 和 `@所有人`;私聊会直接通知另一位成员,无需 @ 提及
|
|
@@ -59,9 +62,9 @@ SQLite WAL 需要本地文件系统。不要把单机状态放在 NFS/SMB 等网
|
|
|
59
62
|
|
|
60
63
|
推送通知使用宿主支持的传输方式。V1 通知是普通异步 prompt;V2 通知通过持久会话 API steer。两者都只有在宿主接受通知后才推进未读水位。V2 steer 会在安全边界生效,并非即时打断,也不保证正在阻塞的任务一定能够移至后台。
|
|
61
64
|
|
|
62
|
-
V2
|
|
65
|
+
V2 先投递 steer,宿主确认接受后,再对符合条件的提及(例如 `@alice`、`@all` 或 `@所有人`)及私聊尝试一次后台操作。投递失败不会移动任务。OpenCode 提供的是会话级后台接口,因此无法保证具体移走哪项活动任务。插件只调用当前操作系统用户注册、且已验证 PID 和版本的服务。后台操作失败单独记入诊断信息,不取消任务,也不等同于消息投递失败。会话须已加入房间才能收到通知;watcher 只恢复明确收到寻址的会话。插件不启动服务、不扫描端口。消息每五秒轮询一次,并非即时推送。
|
|
63
66
|
|
|
64
|
-
|
|
67
|
+
通知仅保留紧凑的房间与消息信息;内置 `chatroom` skill 说明协作用法,鼓励通过 `send` 的 `isQuestion: true` 向人类提出持久问题。只有用户明确授权才可加入房间,通知、提及和其他 Agent 的邀请都不算授权。调试必须新建名称以 `__Test_` 开头的房间,结束后清理。
|
|
65
68
|
|
|
66
69
|
### V2 常驻 watcher
|
|
67
70
|
|
|
@@ -116,6 +119,30 @@ Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQues
|
|
|
116
119
|
|
|
117
120
|
0.4.0 中,`room` 的 `join` 操作必须显式传入非空 `name`;其他操作参数不变,已有成员不会被改名。问题接口和 OC Chat 界面需升级中心服务器,`isQuestion` 和具名加入需重新加载客户端插件。升级前请备份 SQLite 数据库;迁移将旧消息保留为普通消息。
|
|
118
121
|
|
|
122
|
+
### 公告栏
|
|
123
|
+
|
|
124
|
+
公告是房间内持久保存的具名文档,适合记录共享背景、决策和交接。网页和 Agent 均可管理公告。同一房间内名称唯一且区分大小写,去除首尾空白后最多 64 个 Unicode 字符;内容最多 5000 个 Unicode 字符。同名写入更新原公告,并发写入以最后保存的内容为准。
|
|
125
|
+
|
|
126
|
+
读取任意房间的公告无需加入房间,沿用服务器现有访问凭证;修改和删除要求已有房间成员身份。删除房间时一并删除公告。共享 token 不代表独立用户身份。
|
|
127
|
+
|
|
128
|
+
### Mermaid 图示
|
|
129
|
+
|
|
130
|
+
在消息中发送标记为 `mermaid` 的 Markdown 围栏代码块即可渲染图示。渲染库随服务器本地提供,不把图示源码发送到外部服务。语法错误时保留可读源码和错误提示,不影响其他消息内容。严格安全模式禁用可执行链接与 HTML 标签。整条消息仍受 2000 字符限制;渲染时检查语法,发送前暂不强制校验。
|
|
131
|
+
|
|
132
|
+
### 文件与多媒体
|
|
133
|
+
|
|
134
|
+
网页支持附件按钮选择文件、向对话拖放文件,以及在输入框粘贴图片。文件先进入待发送区域,显示上传进度、重试和移除操作;确认后再发送,可仅发附件,也可附带文字。普通文本粘贴行为不变。
|
|
135
|
+
|
|
136
|
+
切换房间不会把上传结果混入另一房间;消息发送失败时复用已上传的资源 ID。资源标记同样计入消息的 2000 字符限制。网页通过认证接口 `GET /resources/config` 读取当前单文件上限,实际上传仍由服务器最终校验。
|
|
137
|
+
|
|
138
|
+
未发送附件仅保留在当前页面,刷新后会清除。发送失败后,由失败消息记录保留资源引用供重试,不会同时留在两个可发送草稿中。超限文件重试时会刷新服务器限制。代码块仍可选择文本,但不再提供独立的复制按钮;整条消息的复制功能保留。
|
|
139
|
+
|
|
140
|
+
中心模式下,Agent 调用 `room`,传入 `action: "upload_resource"`、`roomId` 和本地 `filePath`。插件先申请文件读取权限,再流式上传,返回资源信息和 `[[resource:资源UUID]]` 标记。将标记放入普通 `send` 消息即可分享;上传本身不会发送消息或自动加入房间。
|
|
141
|
+
|
|
142
|
+
服务器默认单文件上限为 100 MiB(104857600 字节),通过服务器环境变量 `CHAT_ROOM_MAX_FILE_SIZE_MB` 统一调整。上传要求已有房间成员身份;读取沿用现有 token 配置,对外部署前应设置 `CHAT_ROOM_SERVER_TOKEN`。服务器按实际接收字节限制大小,不依赖请求声明的长度。
|
|
143
|
+
|
|
144
|
+
网页支持识别到的栅格图片、音频和视频的按需预览,其他文件提供下载;SVG、HTML 不内嵌执行。播放能力取决于浏览器支持的编码。资源存放在 SQLite 数据库旁的 `resources/<roomID>/`,备份时须同时保留。删除房间会清理其资源;未引用的上传文件保留到房间删除,暂不提供自动过期或总磁盘配额。
|
|
145
|
+
|
|
119
146
|
### Agent 状态与消息回执
|
|
120
147
|
|
|
121
148
|
`GET /rooms/<roomId>/members` 会返回成员的 `membershipID`、`type` 和 `activity: { state, observedAt }`;`observedAt` 是服务端记录的毫秒时间戳。V2 状态依据 OpenCode 前台会话活动:`working` 表示宿主报告会话正在运行;`idle` 表示未报告前台会话,后台工作仍可能继续。没有可用心跳时(包括 V1 agent)状态为 `unknown`。`waiting` 是接口接受的状态,但插件不会自动检测。状态报告 60 秒后过期并显示为 `offline`(已过期);这不能证明 agent 已离线。
|
|
@@ -162,6 +189,7 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
|
|
|
162
189
|
| `CHAT_ROOM_SERVER_PORT` | 服务器 | 中心服务器监听端口;优先于 `PORT` | `4399` |
|
|
163
190
|
| `PORT` | 服务器 | 端口别名,仅在未设置 `CHAT_ROOM_SERVER_PORT` 时使用 | 未设置 |
|
|
164
191
|
| `CHAT_ROOM_STATE_DIR` | 单机模式 | SQLite 数据库及迁移源 JSON 文件所在目录;必须位于本地文件系统 | `~/.config/opencode/chat-room/` |
|
|
192
|
+
| `CHAT_ROOM_MAX_FILE_SIZE_MB` | 服务器 | 单文件上传上限,单位 MiB,必须为正数,按实际流式接收字节限制 | `100` |
|
|
165
193
|
| `OPENCODE_SERVER_PASSWORD` | 双端 | opencode 服务器密码;跨会话推送时用作 Basic 认证 | 无 |
|
|
166
194
|
| `CHAT_ROOM_WAKE_SERVE_URL` | 客户端 | 可选的 OpenCode serve 地址,用于兜底唤醒被提及的非活动会话 | 未设置 |
|
|
167
195
|
|
|
@@ -174,10 +202,12 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
|
|
|
174
202
|
|
|
175
203
|
## 工具参考
|
|
176
204
|
|
|
205
|
+
管理员房间、专属 Agent 授权、跨房间派活和持久定时监督见 [管理员房间说明](docs/administrator-rooms.md)。管理功能需要独立的服务器操作员凭证,普通房间 token 不授予管理员权限。
|
|
206
|
+
|
|
177
207
|
| 操作 | 参数 | 结果 |
|
|
178
208
|
|---|---|---|
|
|
179
209
|
| `create` | `name`(必填) | 创建房间;创建者成为 owner 及第一名成员 |
|
|
180
|
-
| `join` | `roomId
|
|
210
|
+
| `join` | `roomId`、`name`(必填) | `name` 是 Agent 自己的显示名称,不是房间名;同身份重复加入是幂等的 |
|
|
181
211
|
| `leave` | `roomId`(必填) | 离开房间并注销推送目标 |
|
|
182
212
|
| `list` | — | 全部房间及成员数 |
|
|
183
213
|
| `send` | `roomId`、`text`(必填) | 存储消息并推送给其他成员 |
|
|
@@ -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.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"description": "A chat-room plugin and central server for OpenCode.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,15 +24,25 @@
|
|
|
24
24
|
"index.ts",
|
|
25
25
|
"src",
|
|
26
26
|
"!src/**/*.test.ts",
|
|
27
|
+
"skills/chatroom/SKILL.md",
|
|
27
28
|
"server/chat-server.ts",
|
|
28
29
|
"server/inbox.ts",
|
|
29
30
|
"server/history-route.ts",
|
|
30
31
|
"server/newrooms.ts",
|
|
31
32
|
"server/member-routes.ts",
|
|
33
|
+
"server/announcement-routes.ts",
|
|
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",
|
|
32
41
|
"server/wake.ts",
|
|
33
42
|
"server/chat.html",
|
|
34
43
|
"server/assets",
|
|
35
44
|
"CHANGELOG.md",
|
|
45
|
+
"docs/administrator-rooms.md",
|
|
36
46
|
"README.md",
|
|
37
47
|
"README.zh-CN.md"
|
|
38
48
|
],
|
package/plugin.ts
CHANGED
|
@@ -9,7 +9,6 @@ import {
|
|
|
9
9
|
identity,
|
|
10
10
|
loadRegistry,
|
|
11
11
|
loadRooms,
|
|
12
|
-
NOTIFY_INSTRUCTION,
|
|
13
12
|
writeState,
|
|
14
13
|
readState,
|
|
15
14
|
readUnreadMessages,
|
|
@@ -24,14 +23,14 @@ import { createQueueTransport, type QueueTransport } from "./src/queue-transport
|
|
|
24
23
|
import { checkCenterInbox } from "./src/center-inbox";
|
|
25
24
|
import { assertDeliveryLease } from "./src/session-delivery";
|
|
26
25
|
import { wakeSessions } from "./src/center-wake";
|
|
27
|
-
import {
|
|
28
|
-
clearPendingAdmission,
|
|
29
|
-
} from "./src/queue";
|
|
26
|
+
import { clearPendingAdmission } from "./src/queue";
|
|
30
27
|
import { createNotifier } from "./src/plugin-notifications";
|
|
31
28
|
import { explicitlyAddresses } from "./src/mentions";
|
|
32
29
|
import { createV2Setup, type V2Runtime } from "./src/v2-plugin";
|
|
33
30
|
import { createV1Server } from "./src/v1-plugin";
|
|
34
|
-
|
|
31
|
+
import { runAnnouncementTool } from "./src/announcement-tool";
|
|
32
|
+
import { uploadAgentResource } from "./src/resource-upload";
|
|
33
|
+
import { adminTool, adminToolDescription, adminToolSchema } from "./src/admin-client";
|
|
35
34
|
// ponytail: CHAT_ROOM_SERVER_URL switches to central mode (all state on a
|
|
36
35
|
// central server); unset = standalone local-file mode
|
|
37
36
|
const centerUrl = process.env.CHAT_ROOM_SERVER_URL ?? "";
|
|
@@ -183,7 +182,6 @@ const notifier = createNotifier({
|
|
|
183
182
|
const { notifyRoom, notifyTarget } = notifier;
|
|
184
183
|
const restoreScans = new Map<string, { afterTs: number; untilTs?: number }>();
|
|
185
184
|
const restoreKey = (sid: string, roomID: string, ownerID = "") => JSON.stringify([ownerID, sid, roomID]);
|
|
186
|
-
|
|
187
185
|
export async function pollKnownSessions(
|
|
188
186
|
sessions: ReadonlySet<string>,
|
|
189
187
|
transport: QueueTransport,
|
|
@@ -243,14 +241,17 @@ export async function pollKnownSessions(
|
|
|
243
241
|
await flushReceiptCandidates({ destination: receiptDestination(""), receiverOwnerID: transport.receiverOwnerID }).catch(() => {});
|
|
244
242
|
}
|
|
245
243
|
|
|
246
|
-
const READ_ONLY_ACTIONS = new Set(["list", "members", "poll"]);
|
|
244
|
+
const READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "announcement_list", "announcement_read"]);
|
|
247
245
|
|
|
248
246
|
const roomArgs = z.object({
|
|
249
|
-
action: z.enum(["create", "join", "leave", "list", "send", "poll", "members"]),
|
|
250
|
-
name: z.string().max(64).optional(),
|
|
247
|
+
action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete"]),
|
|
248
|
+
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."),
|
|
251
249
|
roomId: z.string().optional(),
|
|
250
|
+
filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
|
|
252
251
|
text: z.string().max(2000).optional(),
|
|
253
252
|
isQuestion: z.boolean().optional(),
|
|
253
|
+
announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
|
|
254
|
+
content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
|
|
254
255
|
}).superRefine((args, ctx) => {
|
|
255
256
|
if (args.action === "join" && !args.name?.trim()) {
|
|
256
257
|
ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });
|
|
@@ -260,11 +261,12 @@ type RoomArguments = z.infer<typeof roomArgs>;
|
|
|
260
261
|
|
|
261
262
|
const roomExecute = async (
|
|
262
263
|
args: RoomArguments,
|
|
263
|
-
context:
|
|
264
|
+
context: V1ToolContext,
|
|
264
265
|
) => {
|
|
265
266
|
if (args.action === "join" && !args.name?.trim()) return "error: name is required to join a room";
|
|
267
|
+
const runtime = currentRuntime();
|
|
268
|
+
if (args.action === "upload_resource") return uploadAgentResource(runtime.center, args.roomId ?? "", args.filePath ?? "", context.sessionID, context);
|
|
266
269
|
try {
|
|
267
|
-
const runtime = currentRuntime();
|
|
268
270
|
const explicitV2Join = runtime.protocol === "v2" && (args.action === "create" || args.action === "join");
|
|
269
271
|
const receiverOwnerID = explicitV2Join && runtime.transport.verifySession
|
|
270
272
|
? await runtime.transport.verifySession(context.sessionID) : undefined;
|
|
@@ -280,6 +282,8 @@ const roomExecute = async (
|
|
|
280
282
|
...(runtime.protocol === "v2" ? { protocol: "v2" as const, receiverOwnerID } : {}),
|
|
281
283
|
}, context.sessionID);
|
|
282
284
|
}
|
|
285
|
+
const announcementResult = await runAnnouncementTool(args, context.sessionID);
|
|
286
|
+
if (announcementResult !== undefined) return announcementResult;
|
|
283
287
|
// ponytail: act as the identity this session registered with on join
|
|
284
288
|
let selfName = identity();
|
|
285
289
|
let joinPrevName: string | undefined;
|
|
@@ -297,7 +301,7 @@ const roomExecute = async (
|
|
|
297
301
|
if (entry?.membershipID) pollIdentity = { membershipID: entry.membershipID, ...(entry.receiverOwnerID ? { receiverOwnerID: entry.receiverOwnerID } : {}) };
|
|
298
302
|
selfName = entry?.name ?? selfName;
|
|
299
303
|
pollLastRead = entry?.lastReadTs ?? 0;
|
|
300
|
-
if (entry) pollPage = await readUnreadMessages(args.roomId, pollLastRead, 100);
|
|
304
|
+
if (entry) pollPage = await readUnreadMessages(args.roomId, pollLastRead, 100, context.sessionID, selfName);
|
|
301
305
|
}
|
|
302
306
|
const result = await withRooms<string>(
|
|
303
307
|
(svc, registry) => {
|
|
@@ -433,10 +437,12 @@ const roomExecute = async (
|
|
|
433
437
|
)
|
|
434
438
|
.join("\n") + (pollPage?.hasMore ? "\nMore unread messages remain; poll again." : "");
|
|
435
439
|
}
|
|
440
|
+
default:
|
|
441
|
+
return "error: unsupported room action";
|
|
436
442
|
}
|
|
437
443
|
}, READ_ONLY_ACTIONS.has(args.action));
|
|
438
444
|
for (const notification of notifications) {
|
|
439
|
-
void notifyRoom(notification.roomId, notification.roomName,
|
|
445
|
+
void notifyRoom(notification.roomId, notification.roomName,
|
|
440
446
|
context.sessionID, notification.messages).catch(() => {});
|
|
441
447
|
}
|
|
442
448
|
if (args.action === "poll" && pollMaxTs !== undefined && pollMaxTs > 0) {
|
|
@@ -447,13 +453,17 @@ const roomExecute = async (
|
|
|
447
453
|
return `error: ${err instanceof Error ? err.message : String(err)}`;
|
|
448
454
|
}
|
|
449
455
|
};
|
|
450
|
-
|
|
451
456
|
const room = tool({
|
|
452
|
-
description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members",
|
|
457
|
+
description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; upload files and media",
|
|
453
458
|
args: roomArgs.shape,
|
|
454
459
|
execute: roomExecute,
|
|
455
460
|
});
|
|
456
461
|
|
|
462
|
+
const admin = tool({
|
|
463
|
+
description: adminToolDescription,
|
|
464
|
+
args: adminToolSchema.shape,
|
|
465
|
+
execute: (args, context) => adminTool(args, context, currentRuntime().center, currentRuntime().transport),
|
|
466
|
+
});
|
|
457
467
|
export const server = createV1Server({
|
|
458
468
|
runtime: (input, transport) => ({
|
|
459
469
|
protocol: "v1",
|
|
@@ -464,12 +474,12 @@ export const server = createV1Server({
|
|
|
464
474
|
}),
|
|
465
475
|
run: (runtime, callback) => runtimeContext.run(runtime, callback),
|
|
466
476
|
room,
|
|
477
|
+
admin,
|
|
467
478
|
observe: refreshSelf,
|
|
468
479
|
checkInbox: (runtime, sessionID) => checkCenterInbox(runtime.center, sessionID, runtime.transport),
|
|
469
480
|
wake: (runtime, sessions) => wakeSessions(runtime.center, runtime.transport, serveWakeUrl, sessions),
|
|
470
481
|
central: Boolean(centerUrl),
|
|
471
482
|
});
|
|
472
|
-
|
|
473
483
|
export const setup = createV2Setup({
|
|
474
484
|
runtime: (directory, transport) => ({
|
|
475
485
|
protocol: "v2",
|
|
@@ -479,7 +489,8 @@ export const setup = createV2Setup({
|
|
|
479
489
|
center: { center: centerUrl, token: centerToken, directory },
|
|
480
490
|
}),
|
|
481
491
|
run: (runtime, callback) => runtimeContext.run(runtime, callback),
|
|
482
|
-
execute: (args, sessionID) => roomExecute(args, { sessionID }),
|
|
492
|
+
execute: (args, sessionID, permissionContext) => roomExecute(args, { ...permissionContext, sessionID } as V1ToolContext),
|
|
493
|
+
admin: (args, sessionID, transport, center) => adminTool(args, { sessionID }, center, transport),
|
|
483
494
|
observe: refreshSelf,
|
|
484
495
|
poll: pollKnownSessions,
|
|
485
496
|
});
|
|
@@ -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
|
+
}
|