@alexsun-top/opencode-chat-room 0.4.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/README.md +30 -5
- package/README.zh-CN.md +26 -4
- package/package.json +4 -1
- package/plugin.ts +18 -9
- 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 +15 -0
- package/server/assets/chat/announcements.js +119 -0
- package/server/assets/chat/events.js +180 -6
- package/server/assets/chat/index.js +2 -0
- package/server/assets/chat/markdown.js +214 -11
- package/server/assets/chat/members.js +4 -1
- package/server/assets/chat/messages.js +54 -18
- package/server/assets/chat/receipts.js +22 -17
- package/server/assets/chat/rooms.js +11 -6
- package/server/assets/chat/state.js +47 -13
- package/server/assets/conversation.css +21 -6
- package/server/assets/mermaid-11.12.2.min.js +2811 -0
- package/server/assets/responsive.css +39 -29
- package/server/chat-server.ts +8 -7
- package/server/chat.html +28 -9
- package/server/member-routes.ts +3 -0
- package/server/newrooms.ts +2 -0
- package/server/resource-routes.ts +65 -0
- package/server/wake.ts +2 -2
- package/skills/chatroom/SKILL.md +92 -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 +26 -0
- package/src/center-inbox.ts +9 -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 +41 -0
- package/src/store.ts +1 -10
- package/src/v1-plugin.ts +6 -1
- package/src/v2-plugin.ts +34 -8
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.5.0 — 2026-11-08
|
|
4
|
+
|
|
5
|
+
- Keep room notifications compact: room identity and message content remain, while repeated response instructions move into the bundled `chatroom` skill.
|
|
6
|
+
- Document room collaboration and persistent human questions in the skill, preferring `room.send` with `isQuestion: true` over a native question dialog for room work.
|
|
7
|
+
- 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.
|
|
8
|
+
- Clarify that joining requires user authorization and that `join.name` identifies the Agent, while `create.name` identifies the new room.
|
|
9
|
+
- Admit notification steers before attempting to background blocking work; failed delivery no longer moves the session into the background.
|
|
10
|
+
- Render fenced Mermaid diagrams with a locally bundled renderer, strict security, sanitized SVG, and readable source fallback for invalid or unsafe diagrams.
|
|
11
|
+
- 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.
|
|
12
|
+
- Show per-message reader details in anchored floating cards. Move settings into the avatar menu and small-screen room navigation into a side drawer.
|
|
13
|
+
- 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.
|
|
14
|
+
- Preserve message-relative reading anchors during layout changes and restore them when returning to a room, including history loading for older anchors.
|
|
15
|
+
- 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.
|
|
16
|
+
- 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.
|
|
17
|
+
|
|
3
18
|
## 0.4.0 — 2026-11-06
|
|
4
19
|
|
|
5
20
|
- 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,24 @@ 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 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
|
+
|
|
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.
|
|
137
|
+
|
|
138
|
+
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
|
+
|
|
121
140
|
### Agent presence and message receipts
|
|
122
141
|
|
|
123
142
|
`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 +178,7 @@ Then start opencode normally. Room state lives on the central server. Clients on
|
|
|
159
178
|
|---|---|---|---|
|
|
160
179
|
| `CHAT_ROOM_SERVER_URL` | client | Central server URL; when set, central mode is active | unset (standalone) |
|
|
161
180
|
| `CHAT_ROOM_SERVER_TOKEN` | both | Bearer token for the central server (optional) | none (open) |
|
|
181
|
+
| `CHAT_ROOM_MAX_FILE_SIZE_MB` | server | Maximum bytes per uploaded file, in MiB; positive values, enforced while streaming | `100` |
|
|
162
182
|
| `CHAT_ROOM_SERVER_HOST` | server | Bind hostname; takes precedence over `HOST` | `0.0.0.0` |
|
|
163
183
|
| `HOST` | server | Host alias, used when `CHAT_ROOM_SERVER_HOST` is unset | unset |
|
|
164
184
|
| `CHAT_ROOM_SERVER_PORT` | server | Central server listen port; takes precedence over `PORT` | `4399` |
|
|
@@ -172,20 +192,25 @@ Then start opencode normally. Room state lives on the central server. Clients on
|
|
|
172
192
|
- **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
193
|
- **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
194
|
- 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
|
|
195
|
+
- 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.
|
|
196
|
+
- 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
197
|
|
|
178
198
|
## Tool reference
|
|
179
199
|
|
|
180
200
|
| Action | Args | Result |
|
|
181
201
|
|---|---|---|
|
|
182
202
|
| `create` | `name` (required) | Creates the room; creator becomes owner and first member |
|
|
183
|
-
| `join` | `roomId
|
|
203
|
+
| `join` | `roomId`, `name` (required) | Joins as your participant display name, not the room name; re-joining with the same identity is idempotent |
|
|
184
204
|
| `leave` | `roomId` (required) | Leaves the room and unregisters from push targets |
|
|
185
205
|
| `list` | — | All rooms with member counts |
|
|
186
206
|
| `send` | `roomId`, `text` (required) | Stores the message and pushes it to other members |
|
|
187
207
|
| `poll` | `roomId` (required) | Only unread messages (skips already-pushed ones) |
|
|
188
208
|
| `members` | `roomId` (required) | Member names |
|
|
209
|
+
| `announcement_list` | `roomId` | Lists room announcements without joining |
|
|
210
|
+
| `announcement_read` | `roomId`, `announcementName` | Reads a named announcement without joining |
|
|
211
|
+
| `announcement_write` | `roomId`, `announcementName`, `content` | Creates or replaces a named announcement; requires membership |
|
|
212
|
+
| `announcement_delete` | `roomId`, `announcementName` | Deletes an announcement; requires membership |
|
|
213
|
+
| `upload_resource` | `roomId`, `filePath` | Uploads a local file in central mode and returns its resource marker; requires membership and file-read permission |
|
|
189
214
|
|
|
190
215
|
Note: `join` with `name:"alice"` registers the identity `alice` for that session in that room; subsequent `send`/`leave` use that identity automatically.
|
|
191
216
|
|
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,24 @@ 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
|
+
中心模式下,Agent 调用 `room`,传入 `action: "upload_resource"`、`roomId` 和本地 `filePath`。插件先申请文件读取权限,再流式上传,返回资源信息和 `[[resource:资源UUID]]` 标记。将标记放入普通 `send` 消息即可分享;上传本身不会发送消息或自动加入房间。
|
|
135
|
+
|
|
136
|
+
服务器默认单文件上限为 100 MiB(104857600 字节),通过服务器环境变量 `CHAT_ROOM_MAX_FILE_SIZE_MB` 统一调整。上传要求已有房间成员身份;读取沿用现有 token 配置,对外部署前应设置 `CHAT_ROOM_SERVER_TOKEN`。服务器按实际接收字节限制大小,不依赖请求声明的长度。
|
|
137
|
+
|
|
138
|
+
网页支持识别到的栅格图片、音频和视频的按需预览,其他文件提供下载;SVG、HTML 不内嵌执行。播放能力取决于浏览器支持的编码。资源存放在 SQLite 数据库旁的 `resources/<roomID>/`,备份时须同时保留。删除房间会清理其资源;未引用的上传文件保留到房间删除,暂不提供自动过期或总磁盘配额。
|
|
139
|
+
|
|
119
140
|
### Agent 状态与消息回执
|
|
120
141
|
|
|
121
142
|
`GET /rooms/<roomId>/members` 会返回成员的 `membershipID`、`type` 和 `activity: { state, observedAt }`;`observedAt` 是服务端记录的毫秒时间戳。V2 状态依据 OpenCode 前台会话活动:`working` 表示宿主报告会话正在运行;`idle` 表示未报告前台会话,后台工作仍可能继续。没有可用心跳时(包括 V1 agent)状态为 `unknown`。`waiting` 是接口接受的状态,但插件不会自动检测。状态报告 60 秒后过期并显示为 `offline`(已过期);这不能证明 agent 已离线。
|
|
@@ -162,6 +183,7 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
|
|
|
162
183
|
| `CHAT_ROOM_SERVER_PORT` | 服务器 | 中心服务器监听端口;优先于 `PORT` | `4399` |
|
|
163
184
|
| `PORT` | 服务器 | 端口别名,仅在未设置 `CHAT_ROOM_SERVER_PORT` 时使用 | 未设置 |
|
|
164
185
|
| `CHAT_ROOM_STATE_DIR` | 单机模式 | SQLite 数据库及迁移源 JSON 文件所在目录;必须位于本地文件系统 | `~/.config/opencode/chat-room/` |
|
|
186
|
+
| `CHAT_ROOM_MAX_FILE_SIZE_MB` | 服务器 | 单文件上传上限,单位 MiB,必须为正数,按实际流式接收字节限制 | `100` |
|
|
165
187
|
| `OPENCODE_SERVER_PASSWORD` | 双端 | opencode 服务器密码;跨会话推送时用作 Basic 认证 | 无 |
|
|
166
188
|
| `CHAT_ROOM_WAKE_SERVE_URL` | 客户端 | 可选的 OpenCode serve 地址,用于兜底唤醒被提及的非活动会话 | 未设置 |
|
|
167
189
|
|
|
@@ -177,7 +199,7 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
|
|
|
177
199
|
| 操作 | 参数 | 结果 |
|
|
178
200
|
|---|---|---|
|
|
179
201
|
| `create` | `name`(必填) | 创建房间;创建者成为 owner 及第一名成员 |
|
|
180
|
-
| `join` | `roomId
|
|
202
|
+
| `join` | `roomId`、`name`(必填) | `name` 是 Agent 自己的显示名称,不是房间名;同身份重复加入是幂等的 |
|
|
181
203
|
| `leave` | `roomId`(必填) | 离开房间并注销推送目标 |
|
|
182
204
|
| `list` | — | 全部房间及成员数 |
|
|
183
205
|
| `send` | `roomId`、`text`(必填) | 存储消息并推送给其他成员 |
|
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.0",
|
|
4
4
|
"description": "A chat-room plugin and central server for OpenCode.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -24,11 +24,14 @@
|
|
|
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",
|
|
32
35
|
"server/wake.ts",
|
|
33
36
|
"server/chat.html",
|
|
34
37
|
"server/assets",
|
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,
|
|
@@ -31,6 +30,8 @@ import { createNotifier } from "./src/plugin-notifications";
|
|
|
31
30
|
import { explicitlyAddresses } from "./src/mentions";
|
|
32
31
|
import { createV2Setup, type V2Runtime } from "./src/v2-plugin";
|
|
33
32
|
import { createV1Server } from "./src/v1-plugin";
|
|
33
|
+
import { runAnnouncementTool } from "./src/announcement-tool";
|
|
34
|
+
import { uploadAgentResource } from "./src/resource-upload";
|
|
34
35
|
|
|
35
36
|
// ponytail: CHAT_ROOM_SERVER_URL switches to central mode (all state on a
|
|
36
37
|
// central server); unset = standalone local-file mode
|
|
@@ -243,14 +244,17 @@ export async function pollKnownSessions(
|
|
|
243
244
|
await flushReceiptCandidates({ destination: receiptDestination(""), receiverOwnerID: transport.receiverOwnerID }).catch(() => {});
|
|
244
245
|
}
|
|
245
246
|
|
|
246
|
-
const READ_ONLY_ACTIONS = new Set(["list", "members", "poll"]);
|
|
247
|
+
const READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "announcement_list", "announcement_read"]);
|
|
247
248
|
|
|
248
249
|
const roomArgs = z.object({
|
|
249
|
-
action: z.enum(["create", "join", "leave", "list", "send", "poll", "members"]),
|
|
250
|
-
name: z.string().max(64).optional(),
|
|
250
|
+
action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete"]),
|
|
251
|
+
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
252
|
roomId: z.string().optional(),
|
|
253
|
+
filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
|
|
252
254
|
text: z.string().max(2000).optional(),
|
|
253
255
|
isQuestion: z.boolean().optional(),
|
|
256
|
+
announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
|
|
257
|
+
content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
|
|
254
258
|
}).superRefine((args, ctx) => {
|
|
255
259
|
if (args.action === "join" && !args.name?.trim()) {
|
|
256
260
|
ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });
|
|
@@ -260,11 +264,12 @@ type RoomArguments = z.infer<typeof roomArgs>;
|
|
|
260
264
|
|
|
261
265
|
const roomExecute = async (
|
|
262
266
|
args: RoomArguments,
|
|
263
|
-
context:
|
|
267
|
+
context: V1ToolContext,
|
|
264
268
|
) => {
|
|
265
269
|
if (args.action === "join" && !args.name?.trim()) return "error: name is required to join a room";
|
|
270
|
+
const runtime = currentRuntime();
|
|
271
|
+
if (args.action === "upload_resource") return uploadAgentResource(runtime.center, args.roomId ?? "", args.filePath ?? "", context.sessionID, context);
|
|
266
272
|
try {
|
|
267
|
-
const runtime = currentRuntime();
|
|
268
273
|
const explicitV2Join = runtime.protocol === "v2" && (args.action === "create" || args.action === "join");
|
|
269
274
|
const receiverOwnerID = explicitV2Join && runtime.transport.verifySession
|
|
270
275
|
? await runtime.transport.verifySession(context.sessionID) : undefined;
|
|
@@ -280,6 +285,8 @@ const roomExecute = async (
|
|
|
280
285
|
...(runtime.protocol === "v2" ? { protocol: "v2" as const, receiverOwnerID } : {}),
|
|
281
286
|
}, context.sessionID);
|
|
282
287
|
}
|
|
288
|
+
const announcementResult = await runAnnouncementTool(args, context.sessionID);
|
|
289
|
+
if (announcementResult !== undefined) return announcementResult;
|
|
283
290
|
// ponytail: act as the identity this session registered with on join
|
|
284
291
|
let selfName = identity();
|
|
285
292
|
let joinPrevName: string | undefined;
|
|
@@ -433,10 +440,12 @@ const roomExecute = async (
|
|
|
433
440
|
)
|
|
434
441
|
.join("\n") + (pollPage?.hasMore ? "\nMore unread messages remain; poll again." : "");
|
|
435
442
|
}
|
|
443
|
+
default:
|
|
444
|
+
return "error: unsupported room action";
|
|
436
445
|
}
|
|
437
446
|
}, READ_ONLY_ACTIONS.has(args.action));
|
|
438
447
|
for (const notification of notifications) {
|
|
439
|
-
void notifyRoom(notification.roomId, notification.roomName,
|
|
448
|
+
void notifyRoom(notification.roomId, notification.roomName,
|
|
440
449
|
context.sessionID, notification.messages).catch(() => {});
|
|
441
450
|
}
|
|
442
451
|
if (args.action === "poll" && pollMaxTs !== undefined && pollMaxTs > 0) {
|
|
@@ -449,7 +458,7 @@ const roomExecute = async (
|
|
|
449
458
|
};
|
|
450
459
|
|
|
451
460
|
const room = tool({
|
|
452
|
-
description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members",
|
|
461
|
+
description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; upload files and media",
|
|
453
462
|
args: roomArgs.shape,
|
|
454
463
|
execute: roomExecute,
|
|
455
464
|
});
|
|
@@ -479,7 +488,7 @@ export const setup = createV2Setup({
|
|
|
479
488
|
center: { center: centerUrl, token: centerToken, directory },
|
|
480
489
|
}),
|
|
481
490
|
run: (runtime, callback) => runtimeContext.run(runtime, callback),
|
|
482
|
-
execute: (args, sessionID) => roomExecute(args, { sessionID }),
|
|
491
|
+
execute: (args, sessionID, permissionContext) => roomExecute(args, { ...permissionContext, sessionID } as V1ToolContext),
|
|
483
492
|
observe: refreshSelf,
|
|
484
493
|
poll: pollKnownSessions,
|
|
485
494
|
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { deleteAnnouncement, getAnnouncement, listAnnouncements, putAnnouncement, validateAnnouncement } from "../src/announcements";
|
|
2
|
+
import { readState } from "../src/store";
|
|
3
|
+
|
|
4
|
+
const json = (body: unknown, status = 200) => Response.json(body, { status });
|
|
5
|
+
const object = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
6
|
+
|
|
7
|
+
export async function announcementRoutes(req: Request, url: URL): Promise<Response | undefined> {
|
|
8
|
+
const match = url.pathname.match(/^\/rooms\/([^/]+)\/announcements(?:\/([^/]+))?$/);
|
|
9
|
+
if (!match || !["GET", "PUT", "DELETE"].includes(req.method)) return undefined;
|
|
10
|
+
let roomID: string, name: string | undefined;
|
|
11
|
+
try { roomID = decodeURIComponent(match[1]!); name = match[2] === undefined ? undefined : decodeURIComponent(match[2]); }
|
|
12
|
+
catch { return json({ error: "invalid path" }, 400); }
|
|
13
|
+
const roomExists = await readState((svc) => { try { svc.getRoom(roomID); return true; } catch { return false; } });
|
|
14
|
+
if (!roomExists) return json({ error: "room not found" }, 404);
|
|
15
|
+
if (req.method === "GET") {
|
|
16
|
+
if (!name) return json({ announcements: await listAnnouncements(roomID) });
|
|
17
|
+
if (validateAnnouncement(name)) return json({ error: "invalid announcement name" }, 400);
|
|
18
|
+
const announcement = await getAnnouncement(roomID, name);
|
|
19
|
+
return announcement ? json({ announcement }) : json({ error: "announcement not found" }, 404);
|
|
20
|
+
}
|
|
21
|
+
let body: unknown;
|
|
22
|
+
try { body = await req.json(); } catch { return json({ error: "invalid JSON body" }, 400); }
|
|
23
|
+
if (!object(body) || typeof body.sessionID !== "string" || !body.sessionID) return json({ error: "sessionID is required" }, 400);
|
|
24
|
+
const member = await readState((_svc, registry) => Boolean(registry[roomID]?.[body.sessionID as string]));
|
|
25
|
+
if (!member) return json({ error: "not a room member" }, 403);
|
|
26
|
+
if (req.method === "PUT") {
|
|
27
|
+
const error = validateAnnouncement(name, body.content, true);
|
|
28
|
+
if (error) return json({ error }, 400);
|
|
29
|
+
const announcement = await putAnnouncement(roomID, name!.trim(), body.content as string);
|
|
30
|
+
return announcement ? json({ announcement }) : json({ error: "room not found" }, 404);
|
|
31
|
+
}
|
|
32
|
+
if (!name || validateAnnouncement(name)) return json({ error: "invalid announcement name" }, 400);
|
|
33
|
+
return await deleteAnnouncement(roomID, name) ? json({ ok: true }) : json({ error: "announcement not found" }, 404);
|
|
34
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2014 - 2022 Knut Sveidqvist
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/server/assets/NOTICE.txt
CHANGED
|
@@ -2,5 +2,6 @@ Browser vendors bundled locally; no external requests are made at runtime.
|
|
|
2
2
|
|
|
3
3
|
marked 18.0.4 — MIT License, see MARKED-LICENSE.
|
|
4
4
|
DOMPurify 3.4.7 — MPL 2.0 or Apache License 2.0, see DOMPURIFY-LICENSE.
|
|
5
|
+
Mermaid 11.12.2 — MIT License, see MERMAID-LICENSE.
|
|
5
6
|
|
|
6
|
-
Sources: https://www.npmjs.com/package/marked and https://www.npmjs.com/package/
|
|
7
|
+
Sources: https://www.npmjs.com/package/marked, https://www.npmjs.com/package/dompurify and https://www.npmjs.com/package/mermaid
|
package/server/assets/base.css
CHANGED
|
@@ -172,6 +172,21 @@
|
|
|
172
172
|
|
|
173
173
|
.hint { margin: 8px 0 0; font-size: 12.5px; color: var(--ink-3); }
|
|
174
174
|
|
|
175
|
+
.panel.announcement-panel { width: min(390px, calc(100vw - 32px)); max-height: min(65dvh, 560px); overflow: auto; }
|
|
176
|
+
.announcement-head, .announcement-actions { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
|
177
|
+
.announcement-head h3 { margin: 0; font-size: 15px; }
|
|
178
|
+
.announcement-list { list-style: none; padding: 0; margin: 10px 0; max-height: 150px; overflow: auto; }
|
|
179
|
+
.announcement-list button { width: 100%; padding: 8px 10px; border: 1px solid transparent; border-radius: 8px; background: transparent; color: var(--ink); text-align: left; font: inherit; cursor: pointer; }
|
|
180
|
+
.announcement-list button:hover, .announcement-list button[aria-current="true"] { background: var(--accent-soft); border-color: var(--line); }
|
|
181
|
+
.announcement-list button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
|
182
|
+
.announcement-form { border-top: 1px solid var(--line); padding-top: 10px; }
|
|
183
|
+
.announcement-form .field { margin-bottom: 8px; }
|
|
184
|
+
.announcement-form textarea { resize: vertical; min-height: 80px; max-height: 120px; }
|
|
185
|
+
.announcement-actions { justify-content: flex-start; flex-wrap: wrap; margin-top: 8px; }
|
|
186
|
+
.announcement-actions .btn.small { margin-top: 0; padding: 7px 7px; font-size: 12px; }
|
|
187
|
+
.danger-text { color: var(--danger) !important; }
|
|
188
|
+
.announcement-content { white-space: pre-wrap; overflow-wrap: anywhere; }
|
|
189
|
+
|
|
175
190
|
.token-box { margin-top: 18px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
|
|
176
191
|
.token-box summary {
|
|
177
192
|
cursor: pointer;
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { LS } from "./state.js";
|
|
2
|
+
|
|
3
|
+
export function initAnnouncements(app) {
|
|
4
|
+
const $ = app.$, drafts = new Map();
|
|
5
|
+
const panel = $("#announcementPanel"), trigger = $("#btnAnnouncements"), list = $("#announcementList");
|
|
6
|
+
let items = [], selected = "", generation = 0, roomGeneration = 0, editorRevision = 0, saveToken = 0;
|
|
7
|
+
const key = (id, name = selected) => `${id}\0${name ? `item\0${name}` : "new"}`;
|
|
8
|
+
const roomId = () => app.state.room?.id;
|
|
9
|
+
const currentRoom = (id, request) => roomId() === id && roomGeneration === request;
|
|
10
|
+
const draft = (id, name = selected) => drafts.get(key(id, name));
|
|
11
|
+
function storeDraft(id = roomId(), name = selected) {
|
|
12
|
+
if (id) drafts.set(key(id, name), { name: name || $("#announcementName").value, content: $("#announcementContent").value });
|
|
13
|
+
}
|
|
14
|
+
function editorSnapshot() {
|
|
15
|
+
return { selected, revision: editorRevision, name: $("#announcementName").value, content: $("#announcementContent").value };
|
|
16
|
+
}
|
|
17
|
+
const editorMatches = (snapshot) => selected === snapshot.selected && editorRevision === snapshot.revision;
|
|
18
|
+
function clearDraftIfUnchanged(id, name, snapshot) {
|
|
19
|
+
const saved = draft(id, name);
|
|
20
|
+
if (saved?.name === snapshot.name && saved.content === snapshot.content) drafts.delete(key(id, name));
|
|
21
|
+
}
|
|
22
|
+
function status(text) { $("#announcementStatus").textContent = text; }
|
|
23
|
+
function count() { $("#announcementCount").textContent = app.t("announcementCount", { count: Array.from($("#announcementContent").value).length }); }
|
|
24
|
+
function render() {
|
|
25
|
+
list.textContent = "";
|
|
26
|
+
for (const entry of items) {
|
|
27
|
+
const li = document.createElement("li"), button = document.createElement("button");
|
|
28
|
+
button.type = "button"; button.textContent = entry.name;
|
|
29
|
+
if (entry.name === selected) button.setAttribute("aria-current", "true");
|
|
30
|
+
button.addEventListener("click", (event) => { event.stopPropagation(); select(entry); });
|
|
31
|
+
li.append(button); list.append(li);
|
|
32
|
+
}
|
|
33
|
+
if (!items.length) status(app.t("announcementEmpty"));
|
|
34
|
+
}
|
|
35
|
+
function select(entry) {
|
|
36
|
+
const id = roomId(); if (!id) return;
|
|
37
|
+
const next = entry?.name || "";
|
|
38
|
+
if (next !== selected) editorRevision++;
|
|
39
|
+
selected = next;
|
|
40
|
+
const name = $("#announcementName"), content = $("#announcementContent");
|
|
41
|
+
name.value = selected; name.readOnly = Boolean(selected);
|
|
42
|
+
const saved = draft(id);
|
|
43
|
+
name.value = selected || saved?.name || "";
|
|
44
|
+
content.value = saved?.content ?? entry?.content ?? "";
|
|
45
|
+
$("#btnDeleteAnnouncement").hidden = !selected;
|
|
46
|
+
render(); count();
|
|
47
|
+
}
|
|
48
|
+
async function load(id = roomId()) {
|
|
49
|
+
if (!id) return;
|
|
50
|
+
const request = ++generation, context = roomGeneration; status(app.t("announcementLoading"));
|
|
51
|
+
try {
|
|
52
|
+
const result = await app.api(`/rooms/${encodeURIComponent(id)}/announcements`);
|
|
53
|
+
if (roomId() !== id || context !== roomGeneration || generation !== request) return;
|
|
54
|
+
items = Array.isArray(result.announcements) ? result.announcements : [];
|
|
55
|
+
status("");
|
|
56
|
+
const chosen = items.find((item) => item.name === selected);
|
|
57
|
+
if (!chosen) select(null); else select(chosen);
|
|
58
|
+
render();
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (roomId() !== id || context !== roomGeneration || generation !== request) return;
|
|
61
|
+
status(app.t("announcementLoadFailed"));
|
|
62
|
+
if (error.status === 401) app.openChatSettings();
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
$("#announcementContent").addEventListener("input", () => {
|
|
66
|
+
editorRevision++; count(); storeDraft();
|
|
67
|
+
});
|
|
68
|
+
$("#announcementName").addEventListener("input", () => {
|
|
69
|
+
editorRevision++; storeDraft();
|
|
70
|
+
});
|
|
71
|
+
$("#announcementForm").addEventListener("submit", async (event) => {
|
|
72
|
+
event.preventDefault();
|
|
73
|
+
const id = roomId(), name = $("#announcementName").value.trim(), content = $("#announcementContent").value;
|
|
74
|
+
if (!id || !name || Array.from(name).length > 64 || Array.from(content).length > 5000) return status(app.t("announcementInvalid"));
|
|
75
|
+
if (!selected && items.some((item) => item.name === name)) return status(app.t("announcementDuplicate"));
|
|
76
|
+
const context = roomGeneration, captured = editorSnapshot(), draftName = selected, button = $("#btnSaveAnnouncement"), token = ++saveToken;
|
|
77
|
+
storeDraft(id, draftName); button.disabled = true;
|
|
78
|
+
try {
|
|
79
|
+
const result = await app.api(`/rooms/${encodeURIComponent(id)}/announcements/${encodeURIComponent(name)}`, {
|
|
80
|
+
method: "PUT", body: JSON.stringify({ sessionID: LS.sessionID, content }),
|
|
81
|
+
});
|
|
82
|
+
if (currentRoom(id, context)) {
|
|
83
|
+
generation++; items = [...items.filter((item) => item.name !== name), result.announcement]; render();
|
|
84
|
+
clearDraftIfUnchanged(id, draftName, captured);
|
|
85
|
+
if (editorMatches(captured)) { select(result.announcement); status(app.t("announcementSaved")); }
|
|
86
|
+
}
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (currentRoom(id, context) && editorMatches(captured)) status(error.status === 403 ? error.message : app.t("announcementLoadFailed"));
|
|
89
|
+
}
|
|
90
|
+
finally { if (token === saveToken) button.disabled = false; }
|
|
91
|
+
});
|
|
92
|
+
$("#btnNewAnnouncement").addEventListener("click", () => { select(null); $("#announcementName").focus(); });
|
|
93
|
+
$("#btnDeleteAnnouncement").addEventListener("click", async () => {
|
|
94
|
+
const id = roomId(), name = selected;
|
|
95
|
+
if (!id || !name || !confirm(app.t("announcementDeleteConfirm", { name }))) return;
|
|
96
|
+
const context = roomGeneration, captured = editorSnapshot();
|
|
97
|
+
try {
|
|
98
|
+
await app.api(`/rooms/${encodeURIComponent(id)}/announcements/${encodeURIComponent(name)}`, { method: "DELETE", body: JSON.stringify({ sessionID: LS.sessionID }) });
|
|
99
|
+
if (currentRoom(id, context)) {
|
|
100
|
+
generation++; items = items.filter((item) => item.name !== name); render();
|
|
101
|
+
clearDraftIfUnchanged(id, name, captured);
|
|
102
|
+
if (editorMatches(captured)) { select(null); status(app.t("announcementDeleted")); }
|
|
103
|
+
}
|
|
104
|
+
} catch (error) { if (currentRoom(id, context) && editorMatches(captured)) status(error.message); }
|
|
105
|
+
});
|
|
106
|
+
$("#btnRefreshAnnouncements").addEventListener("click", () => void load());
|
|
107
|
+
trigger.addEventListener("click", () => {
|
|
108
|
+
const open = panel.hidden; app.closePanels(); panel.hidden = !open;
|
|
109
|
+
trigger.setAttribute("aria-expanded", String(open)); if (open) { void load(); $("#announcementHeading").focus(); }
|
|
110
|
+
});
|
|
111
|
+
document.addEventListener("keydown", (event) => { if (event.key === "Escape" && !panel.hidden) { app.closePanels(); trigger.focus(); } });
|
|
112
|
+
const close = app.closePanels;
|
|
113
|
+
app.closePanels = () => { close(); panel.hidden = true; trigger.setAttribute("aria-expanded", "false"); };
|
|
114
|
+
document.addEventListener("chat-room-activated", (event) => {
|
|
115
|
+
const id = event.detail;
|
|
116
|
+
roomGeneration++; generation++; saveToken++; $("#btnSaveAnnouncement").disabled = false;
|
|
117
|
+
selected = ""; items = []; select(null); void load(id);
|
|
118
|
+
});
|
|
119
|
+
}
|