@alexsun-top/opencode-chat-room 0.5.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 CHANGED
@@ -1,5 +1,19 @@
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
+
3
17
  ## 0.5.0 — 2026-11-08
4
18
 
5
19
  - Keep room notifications compact: room identity and message content remain, while repeated response instructions move into the bundled `chatroom` skill.
package/README.md CHANGED
@@ -131,6 +131,12 @@ Use a fenced code block tagged `mermaid` in a message to render a diagram. The r
131
131
 
132
132
  ### Files and media
133
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
+
134
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.
135
141
 
136
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.
@@ -197,6 +203,8 @@ Then start opencode normally. Room state lives on the central server. Clients on
197
203
 
198
204
  ## Tool reference
199
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
+
200
208
  | Action | Args | Result |
201
209
  |---|---|---|
202
210
  | `create` | `name` (required) | Creates the room; creator becomes owner and first member |
package/README.zh-CN.md CHANGED
@@ -131,6 +131,12 @@ Agent 可调用 `room`,传入 `action: "send"`、`roomId`、`text` 和 `isQues
131
131
 
132
132
  ### 文件与多媒体
133
133
 
134
+ 网页支持附件按钮选择文件、向对话拖放文件,以及在输入框粘贴图片。文件先进入待发送区域,显示上传进度、重试和移除操作;确认后再发送,可仅发附件,也可附带文字。普通文本粘贴行为不变。
135
+
136
+ 切换房间不会把上传结果混入另一房间;消息发送失败时复用已上传的资源 ID。资源标记同样计入消息的 2000 字符限制。网页通过认证接口 `GET /resources/config` 读取当前单文件上限,实际上传仍由服务器最终校验。
137
+
138
+ 未发送附件仅保留在当前页面,刷新后会清除。发送失败后,由失败消息记录保留资源引用供重试,不会同时留在两个可发送草稿中。超限文件重试时会刷新服务器限制。代码块仍可选择文本,但不再提供独立的复制按钮;整条消息的复制功能保留。
139
+
134
140
  中心模式下,Agent 调用 `room`,传入 `action: "upload_resource"`、`roomId` 和本地 `filePath`。插件先申请文件读取权限,再流式上传,返回资源信息和 `[[resource:资源UUID]]` 标记。将标记放入普通 `send` 消息即可分享;上传本身不会发送消息或自动加入房间。
135
141
 
136
142
  服务器默认单文件上限为 100 MiB(104857600 字节),通过服务器环境变量 `CHAT_ROOM_MAX_FILE_SIZE_MB` 统一调整。上传要求已有房间成员身份;读取沿用现有 token 配置,对外部署前应设置 `CHAT_ROOM_SERVER_TOKEN`。服务器按实际接收字节限制大小,不依赖请求声明的长度。
@@ -196,6 +202,8 @@ export CHAT_ROOM_SERVER_TOKEN=secret # 仅当服务器设置了 token 时
196
202
 
197
203
  ## 工具参考
198
204
 
205
+ 管理员房间、专属 Agent 授权、跨房间派活和持久定时监督见 [管理员房间说明](docs/administrator-rooms.md)。管理功能需要独立的服务器操作员凭证,普通房间 token 不授予管理员权限。
206
+
199
207
  | 操作 | 参数 | 结果 |
200
208
  |---|---|---|
201
209
  | `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.1",
4
4
  "description": "A chat-room plugin and central server for OpenCode.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -32,10 +32,17 @@
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",
35
41
  "server/wake.ts",
36
42
  "server/chat.html",
37
43
  "server/assets",
38
44
  "CHANGELOG.md",
45
+ "docs/administrator-rooms.md",
39
46
  "README.md",
40
47
  "README.zh-CN.md"
41
48
  ],
package/plugin.ts CHANGED
@@ -23,16 +23,14 @@ 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 { adminTool, adminToolDescription, adminToolSchema } from "./src/admin-client";
36
34
  // ponytail: CHAT_ROOM_SERVER_URL switches to central mode (all state on a
37
35
  // central server); unset = standalone local-file mode
38
36
  const centerUrl = process.env.CHAT_ROOM_SERVER_URL ?? "";
@@ -184,7 +182,6 @@ const notifier = createNotifier({
184
182
  const { notifyRoom, notifyTarget } = notifier;
185
183
  const restoreScans = new Map<string, { afterTs: number; untilTs?: number }>();
186
184
  const restoreKey = (sid: string, roomID: string, ownerID = "") => JSON.stringify([ownerID, sid, roomID]);
187
-
188
185
  export async function pollKnownSessions(
189
186
  sessions: ReadonlySet<string>,
190
187
  transport: QueueTransport,
@@ -304,7 +301,7 @@ const roomExecute = async (
304
301
  if (entry?.membershipID) pollIdentity = { membershipID: entry.membershipID, ...(entry.receiverOwnerID ? { receiverOwnerID: entry.receiverOwnerID } : {}) };
305
302
  selfName = entry?.name ?? selfName;
306
303
  pollLastRead = entry?.lastReadTs ?? 0;
307
- if (entry) pollPage = await readUnreadMessages(args.roomId, pollLastRead, 100);
304
+ if (entry) pollPage = await readUnreadMessages(args.roomId, pollLastRead, 100, context.sessionID, selfName);
308
305
  }
309
306
  const result = await withRooms<string>(
310
307
  (svc, registry) => {
@@ -456,13 +453,17 @@ const roomExecute = async (
456
453
  return `error: ${err instanceof Error ? err.message : String(err)}`;
457
454
  }
458
455
  };
459
-
460
456
  const room = tool({
461
457
  description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; upload files and media",
462
458
  args: roomArgs.shape,
463
459
  execute: roomExecute,
464
460
  });
465
461
 
462
+ const admin = tool({
463
+ description: adminToolDescription,
464
+ args: adminToolSchema.shape,
465
+ execute: (args, context) => adminTool(args, context, currentRuntime().center, currentRuntime().transport),
466
+ });
466
467
  export const server = createV1Server({
467
468
  runtime: (input, transport) => ({
468
469
  protocol: "v1",
@@ -473,12 +474,12 @@ export const server = createV1Server({
473
474
  }),
474
475
  run: (runtime, callback) => runtimeContext.run(runtime, callback),
475
476
  room,
477
+ admin,
476
478
  observe: refreshSelf,
477
479
  checkInbox: (runtime, sessionID) => checkCenterInbox(runtime.center, sessionID, runtime.transport),
478
480
  wake: (runtime, sessions) => wakeSessions(runtime.center, runtime.transport, serveWakeUrl, sessions),
479
481
  central: Boolean(centerUrl),
480
482
  });
481
-
482
483
  export const setup = createV2Setup({
483
484
  runtime: (directory, transport) => ({
484
485
  protocol: "v2",
@@ -489,6 +490,7 @@ export const setup = createV2Setup({
489
490
  }),
490
491
  run: (runtime, callback) => runtimeContext.run(runtime, callback),
491
492
  execute: (args, sessionID, permissionContext) => roomExecute(args, { ...permissionContext, sessionID } as V1ToolContext),
493
+ admin: (args, sessionID, transport, center) => adminTool(args, { sessionID }, center, transport),
492
494
  observe: refreshSelf,
493
495
  poll: pollKnownSessions,
494
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
+ }
@@ -0,0 +1,154 @@
1
+ import { databasePath } from "../src/store";
2
+ import { readHistoryPage } from "../src/sqlite-state";
3
+ import { adminEnabled, hasAdminCapability, isOperator } from "./admin-auth";
4
+ import { adminPlanRoutes } from "./admin-plan-routes";
5
+ import { adminTaskRoutes } from "./admin-task-routes";
6
+ import { binding, digest, ensureAdminSchema, exec, isAgentMember, many, matchesHash, newSecret, one, publicRoom, tx, validCurrent, enroll } from "./admin-state";
7
+ import type { Binding } from "./admin-state";
8
+ import { startAdminScheduler } from "./admin-scheduler";
9
+
10
+ const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
11
+ const object = (value: unknown): value is Record<string, unknown> => !!value && typeof value === "object" && !Array.isArray(value);
12
+ startAdminScheduler();
13
+
14
+ export async function adminRoutes(request: Request, url: URL): Promise<Response | undefined> {
15
+ if (!url.pathname.startsWith("/admin/") && !url.pathname.startsWith("/supervision/")) return undefined;
16
+ if (!adminEnabled) return json({ error: "admin API is disabled" }, 503);
17
+ try {
18
+ await ensureAdminSchema();
19
+ const task = await adminTaskRoutes(request, url);
20
+ if (task) return task;
21
+ const plan = await adminPlanRoutes(request, url);
22
+ if (plan) return plan;
23
+ return await rootRoutes(request, url);
24
+ } catch (error) {
25
+ if (error instanceof SyntaxError || error instanceof URIError) return json({ error: "invalid request" }, 400);
26
+ return json({ error: "admin request failed" }, 500);
27
+ }
28
+ }
29
+
30
+ async function rootRoutes(request: Request, url: URL): Promise<Response> {
31
+ const path = url.pathname;
32
+ if (request.method === "GET" && path === "/admin/rooms") return listRooms(request);
33
+ if (request.method === "POST" && path === "/admin/rooms") return createBinding(request);
34
+ const claim = path.match(/^\/admin\/rooms\/([^/]+)\/claim$/);
35
+ if (claim && request.method === "POST") return claimBinding(request, decodeURIComponent(claim[1]!));
36
+ const room = path.match(/^\/admin\/rooms\/([^/]+)(?:\/(overview|history))?$/);
37
+ if (!room) return json({ error: "not found" }, 404);
38
+ const roomID = decodeURIComponent(room[1]!);
39
+ if (request.method === "PUT" && !room[2]) return rotateBinding(request, roomID);
40
+ if (request.method === "DELETE" && !room[2]) return revokeBinding(request, roomID);
41
+ if (request.method === "GET" && room[2] === "overview") return overview(request, roomID);
42
+ if (request.method === "GET" && room[2] === "history") return history(request, url, roomID);
43
+ return json({ error: "method not allowed" }, 405);
44
+ }
45
+
46
+ async function listRooms(request: Request): Promise<Response> {
47
+ if (!isOperator(request)) return json({ error: "operator token required" }, 401);
48
+ return json({ rooms: await tx(db => many<Binding>(db, "SELECT * FROM admin_rooms ORDER BY created_at LIMIT 200").map(publicRoom)) });
49
+ }
50
+
51
+ async function createBinding(request: Request): Promise<Response> {
52
+ if (!isOperator(request)) return json({ error: "operator token required" }, 401);
53
+ const body: unknown = await request.json();
54
+ if (!object(body) || !bounded(body.roomId, 128) || !bounded(body.targetRoomId, 128) ||
55
+ !bounded(body.sessionID, 128) || typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 ||
56
+ !bounded(body.membershipID, 128)) return json({ error: "invalid admin binding" }, 400);
57
+ const { roomId, targetRoomId, sessionID, receiverOwnerID, membershipID } = body as {
58
+ roomId: string; targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string;
59
+ };
60
+ const result = await tx(db => {
61
+ const admin = one<{ kind: string }>(db, "SELECT kind FROM rooms WHERE id=?", roomId);
62
+ if (!admin) return { status: 404 as const, error: "admin room not found" };
63
+ if (admin.kind !== "group") return { status: 400 as const, error: "admin room must be a group room" };
64
+ if (one(db, "SELECT 1 FROM admin_rooms WHERE room_id=?", roomId)) return { status: 409 as const, error: "admin room already designated; use PUT to rotate" };
65
+ if (!one(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomId)) return { status: 404 as const, error: "target room not found" };
66
+ if (!isAgentMember(db, targetRoomId, sessionID, receiverOwnerID, membershipID)) return { status: 409 as const, error: "target agent binding is not active" };
67
+ const issued = enroll(db, roomId, targetRoomId, sessionID, receiverOwnerID, membershipID, 1);
68
+ const adminBinding = binding(db, roomId);
69
+ return issued && adminBinding ? { status: 201 as const, issued, adminRoom: publicRoom(adminBinding) } : { status: 409 as const, error: "admin room cannot be designated" };
70
+ });
71
+ return "issued" in result ? json({ adminRoom: result.adminRoom, ...result.issued }, result.status) : json({ error: result.error }, result.status);
72
+ }
73
+
74
+ function bounded(value: unknown, max: number): value is string {
75
+ return typeof value === "string" && value.trim().length > 0 && value.length <= max;
76
+ }
77
+
78
+ async function claimBinding(request: Request, roomID: string): Promise<Response> {
79
+ const body: unknown = await request.json();
80
+ if (!object(body) || !bounded(body.sessionID, 128) || typeof body.receiverOwnerID !== "string" ||
81
+ body.receiverOwnerID.length > 128 || !bounded(body.enrollmentKey, 256)) return json({ error: "invalid claim" }, 400);
82
+ const { sessionID, receiverOwnerID, enrollmentKey } = body as { sessionID: string; receiverOwnerID: string; enrollmentKey: string };
83
+ const result = await tx(db => {
84
+ const b = binding(db, roomID);
85
+ if (!b || b.session_id !== sessionID || b.receiver_owner_id !== receiverOwnerID ||
86
+ b.enrollment_expires <= Date.now() || !matchesHash(enrollmentKey, b.enrollment_hash) ||
87
+ !isAgentMember(db, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id)) return null;
88
+ const capability = newSecret();
89
+ const saved = exec(db, "UPDATE admin_rooms SET capability_hash=?,enrollment_hash='',enrollment_expires=0 WHERE room_id=? AND generation=? AND enrollment_hash=? AND enrollment_expires>?",
90
+ digest(capability), roomID, b.generation, b.enrollment_hash, Date.now());
91
+ return saved.changes === 1 ? { capability, adminRoom: publicRoom({ ...b, capability_hash: digest(capability) }) } : null;
92
+ });
93
+ return result ? json(result) : json({ error: "claim rejected" }, 409);
94
+ }
95
+
96
+ async function rotateBinding(request: Request, roomID: string): Promise<Response> {
97
+ if (!isOperator(request)) return json({ error: "operator token required" }, 401);
98
+ const body: unknown = await request.json();
99
+ if (!object(body) || !bounded(body.targetRoomId, 128) || !bounded(body.sessionID, 128) ||
100
+ typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 || !bounded(body.membershipID, 128)) return json({ error: "invalid binding" }, 400);
101
+ const { targetRoomId, sessionID, receiverOwnerID, membershipID } = body as {
102
+ targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string;
103
+ };
104
+ const result = await tx(db => {
105
+ const old = binding(db, roomID);
106
+ if (!old) return null;
107
+ if (!isAgentMember(db, targetRoomId, sessionID, receiverOwnerID, membershipID)) return null;
108
+ const issued = enroll(db, roomID, targetRoomId, sessionID, receiverOwnerID, membershipID, old.generation + 1);
109
+ const current = binding(db, roomID);
110
+ return issued && current ? { issued, adminRoom: publicRoom(current) } : null;
111
+ });
112
+ return result ? json({ adminRoom: result.adminRoom, ...result.issued }) : json({ error: "admin room or active agent binding not found" }, 409);
113
+ }
114
+
115
+ async function revokeBinding(request: Request, roomID: string): Promise<Response> {
116
+ if (!isOperator(request)) return json({ error: "operator token required" }, 401);
117
+ const deleted = await tx(db => exec(db, "DELETE FROM admin_rooms WHERE room_id=?", roomID).changes);
118
+ return deleted ? json({ ok: true }) : json({ error: "admin room not found" }, 404);
119
+ }
120
+
121
+ async function overview(request: Request, roomID: string): Promise<Response> {
122
+ const result = await tx(db => {
123
+ const b = binding(db, roomID);
124
+ if (!b) return { status: 404 as const };
125
+ if (!authorized(request, b)) return { status: 401 as const };
126
+ if (!isOperator(request) && !validCurrent(db, b)) return { status: 409 as const };
127
+ const rooms = many<{ id: string; name: string; createdAt: number }>(db, "SELECT id,name,created_at AS createdAt FROM rooms ORDER BY created_at DESC LIMIT 200")
128
+ .map(room => ({ ...room, members: many(db, "SELECT g.session_id AS sessionID,g.name,g.protocol,g.receiver_owner_id AS receiverOwnerID,g.work_state AS workState,g.last_seen_at AS lastSeenAt FROM registry g WHERE g.room_id=? ORDER BY g.name", room.id) }));
129
+ const tasks = many(db, "SELECT id,admin_room_id AS adminRoomId,admin_generation AS generation,target_room_id AS targetRoomId,target_session_id AS targetSessionID,text,status,progress,created_at AS createdAt,updated_at AS updatedAt FROM admin_tasks WHERE admin_room_id=? ORDER BY created_at DESC LIMIT 200", roomID);
130
+ const plans = many(db, "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", roomID);
131
+ return { rooms, tasks, plans };
132
+ });
133
+ return "status" in result ? json({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "binding is no longer active" }, result.status) : json(result);
134
+ }
135
+
136
+ async function history(request: Request, url: URL, roomID: string): Promise<Response> {
137
+ const targetRoomID = url.searchParams.get("targetRoomId") ?? "";
138
+ const rawLimit = url.searchParams.get("limit");
139
+ const limit = rawLimit === null ? 20 : Number(rawLimit);
140
+ if (!bounded(targetRoomID, 128) || !Number.isSafeInteger(limit) || limit < 1 || limit > 50) return json({ error: "invalid history request" }, 400);
141
+ const allowed = await tx(db => {
142
+ const b = binding(db, roomID);
143
+ if (!b) return 404;
144
+ if (!authorized(request, b)) return 401;
145
+ if (!isOperator(request) && !validCurrent(db, b)) return 409;
146
+ return one(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomID) ? 200 : 404;
147
+ });
148
+ if (allowed !== 200) return json({ error: allowed === 401 ? "unauthorized" : allowed === 404 ? "room not found" : "binding is no longer active" }, allowed);
149
+ return json(await readHistoryPage(databasePath(), targetRoomID, undefined, limit));
150
+ }
151
+
152
+ function authorized(request: Request, b: import("./admin-state").Binding): boolean {
153
+ return isOperator(request) || hasAdminCapability(request, b);
154
+ }
@@ -0,0 +1,42 @@
1
+ import { binding, exec, many, tx, validCurrent } from "./admin-state";
2
+ import { randomUUID } from "node:crypto";
3
+
4
+ type PlanRow = { id: string; admin_room_id: string; interval_seconds: number; next_run_at: number; text: string };
5
+ type OpenTask = { text: string; status: string; progress: string };
6
+ type Reminder = { id: string; acknowledged: number };
7
+
8
+ export async function tickAdminScheduler(now = Date.now()): Promise<void> {
9
+ await tx((db) => {
10
+ const due = many<PlanRow>(db, "SELECT * FROM admin_plans WHERE paused=0 AND next_run_at<=? ORDER BY next_run_at LIMIT 100", now);
11
+ for (const plan of due) {
12
+ const b = binding(db, plan.admin_room_id);
13
+ if (!b || !validCurrent(db, b)) {
14
+ exec(db, "UPDATE admin_plans SET next_run_at=? WHERE id=?", now + plan.interval_seconds * 1000, plan.id);
15
+ continue;
16
+ }
17
+ const tasks = many<OpenTask>(db, "SELECT text,status,progress FROM admin_tasks WHERE admin_room_id=? AND status IN ('pending','working','blocked') ORDER BY created_at DESC LIMIT 20", b.room_id);
18
+ const summary = tasks.length ? `\nOpen tasks:\n${tasks.map(t => `- ${t.status}: ${t.text}${t.progress ? ` (${t.progress})` : ""}`).join("\n")}` : "\nNo open tasks.";
19
+ const text = `${plan.text}${summary}`.slice(0, 5000);
20
+ const taskID = `plan:${plan.id}`;
21
+ const existing = db.query("SELECT id,acknowledged FROM admin_deliveries WHERE admin_room_id=? AND kind='supervision' AND task_id=?").get(b.room_id, taskID) as Reminder | null;
22
+ if (existing && !existing.acknowledged) {
23
+ exec(db, "UPDATE admin_deliveries SET text=?,created_at=?,generation=?,recipient_room_id=?,session_id=?,owner_id=?,membership_id=? WHERE id=?", text, now, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id, existing.id);
24
+ } else if (existing) {
25
+ const id = randomUUID();
26
+ exec(db, "UPDATE admin_deliveries SET id=?,admission_id=?,text=?,created_at=?,generation=?,recipient_room_id=?,session_id=?,owner_id=?,membership_id=?,acknowledged=0 WHERE id=?", id, `msg_${id}`, text, now, b.generation, b.target_room_id, b.session_id, b.receiver_owner_id, b.membership_id, existing.id);
27
+ } else {
28
+ const id = randomUUID();
29
+ exec(db, "INSERT INTO admin_deliveries(id,admin_room_id,generation,recipient_room_id,session_id,owner_id,membership_id,kind,text,task_id,admission_id,created_at) VALUES(?,?,?,?,?,?,?,'supervision',?,?,?,?)", id,b.room_id,b.generation,b.target_room_id,b.session_id,b.receiver_owner_id,b.membership_id,text,taskID,`msg_${id}`,now);
30
+ }
31
+ exec(db, "UPDATE admin_plans SET next_run_at=? WHERE id=?", now + plan.interval_seconds * 1000, plan.id);
32
+ }
33
+ });
34
+ }
35
+
36
+ let timer: ReturnType<typeof setInterval> | undefined;
37
+ export function startAdminScheduler(): void {
38
+ if (timer || !process.env.CHAT_ROOM_ADMIN_TOKEN || !process.env.CHAT_ROOM_SERVER_TOKEN || process.env.CHAT_ROOM_ADMIN_TOKEN === process.env.CHAT_ROOM_SERVER_TOKEN) return;
39
+ timer = setInterval(() => { void tickAdminScheduler().catch(() => {}); }, 5000);
40
+ timer.unref?.();
41
+ }
42
+ export function stopAdminScheduler(): void { if (timer) clearInterval(timer); timer = undefined; }
@@ -0,0 +1,61 @@
1
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import type { Database, SQLQueryBindings } from "bun:sqlite";
3
+ import { databasePath } from "../src/store";
4
+ import { initializeAdminSchema, withStateTransaction } from "../src/sqlite-state";
5
+
6
+ const hash = (value: string) => createHash("sha256").update(value).digest("hex");
7
+ const secret = () => randomBytes(32).toString("base64url");
8
+ const row = <T>(db: Database, sql: string, ...args: SQLQueryBindings[]) => db.query(sql).get(...args) as T | null;
9
+ const all = <T>(db: Database, sql: string, ...args: SQLQueryBindings[]) => db.query(sql).all(...args) as T[];
10
+ const run = (db: Database, sql: string, ...args: SQLQueryBindings[]) => db.query(sql).run(...args);
11
+ export type AdminRoom = { roomId: string; targetRoomId: string; sessionID: string; receiverOwnerID: string; membershipID: string; generation: number; enrolled: boolean; createdAt: number };
12
+ export type Binding = { room_id: string; target_room_id: string; session_id: string; receiver_owner_id: string; membership_id: string; generation: number; enrollment_hash: string; enrollment_expires: number; capability_hash: string | null; created_at: number };
13
+ export const digest = hash;
14
+ export const newSecret = secret;
15
+ export function safeEqual(a: string, b: string): boolean {
16
+ const left = Buffer.from(hash(a), "hex"), right = Buffer.from(hash(b), "hex");
17
+ return timingSafeEqual(left, right);
18
+ }
19
+ export function matchesHash(value: string, stored: string): boolean {
20
+ const left = Buffer.from(hash(value), "hex"), right = Buffer.from(stored, "hex");
21
+ return right.length === 32 && timingSafeEqual(left, right);
22
+ }
23
+ export async function ensureAdminSchema() { await initializeAdminSchema(databasePath()); }
24
+ export async function tx<T>(fn: (db: Database) => T) { await ensureAdminSchema(); return withStateTransaction(databasePath(), fn); }
25
+ export function publicRoom(b: Binding): AdminRoom { return { roomId: b.room_id, targetRoomId: b.target_room_id, sessionID: b.session_id, receiverOwnerID: b.receiver_owner_id, membershipID: b.membership_id, generation: b.generation, enrolled: Boolean(b.capability_hash), createdAt: b.created_at }; }
26
+ export function binding(db: Database, roomID: string) { return row<Binding>(db, "SELECT * FROM admin_rooms WHERE room_id=?", roomID); }
27
+ export function currentMember(db: Database, b: Binding) {
28
+ return row(db, `SELECT g.membership_id,g.receiver_owner_id,g.protocol,g.host,p.id AS participant_id
29
+ FROM registry g JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN (SELECT kind FROM rooms WHERE id=g.room_id)='direct' THEN g.session_id ELSE g.name END
30
+ WHERE g.room_id=? AND g.session_id=?`, b.target_room_id, b.session_id) as { membership_id: string; receiver_owner_id: string | null; protocol: string | null; host: string | null; participant_id: string } | null;
31
+ }
32
+ export function validCurrent(db: Database, b: Binding): boolean {
33
+ const m = currentMember(db, b);
34
+ return !!m && m.membership_id === b.membership_id && (m.receiver_owner_id ?? "") === b.receiver_owner_id && (m.protocol === "v1" || m.protocol === "v2" || Boolean(m.host));
35
+ }
36
+ export function enroll(db: Database, roomID: string, targetRoomID: string, sessionID: string, ownerID: string, membershipID: string, generation: number, createdAt = Date.now()) {
37
+ if (!row(db, "SELECT 1 FROM rooms WHERE id=? AND kind='group'", roomID) || !row(db, "SELECT 1 FROM rooms WHERE id=?", targetRoomID)) return undefined;
38
+ const nextKey = secret(), expiresAt = Date.now() + 600_000;
39
+ run(db, `INSERT INTO admin_rooms(room_id,target_room_id,session_id,receiver_owner_id,membership_id,generation,enrollment_hash,enrollment_expires,capability_hash,created_at)
40
+ VALUES(?,?,?,?,?,?,?,?,NULL,?) ON CONFLICT(room_id) DO UPDATE SET target_room_id=excluded.target_room_id,session_id=excluded.session_id,receiver_owner_id=excluded.receiver_owner_id,membership_id=excluded.membership_id,generation=excluded.generation,enrollment_hash=excluded.enrollment_hash,enrollment_expires=excluded.enrollment_expires,capability_hash=NULL`,
41
+ roomID, targetRoomID, sessionID, ownerID, membershipID, generation, hash(nextKey), expiresAt, createdAt);
42
+ run(db, "UPDATE admin_tasks SET status='cancelled',delivery_token_hash='',updated_at=? WHERE admin_room_id=? AND status IN ('pending','working','blocked')", Date.now(), roomID);
43
+ run(db, "DELETE FROM admin_deliveries WHERE admin_room_id=?", roomID);
44
+ run(db, "UPDATE admin_plans SET paused=1 WHERE admin_room_id=?", roomID);
45
+ return { enrollmentKey: nextKey, expiresAt };
46
+ }
47
+ export function isAgentMember(db: Database, roomID: string, sessionID: string, ownerID: string, membershipID: string) {
48
+ const entry = row<{ membership_id: string; receiver_owner_id: string | null; protocol: string | null; host: string | null }>(db,
49
+ `SELECT g.membership_id,g.receiver_owner_id,g.protocol,g.host FROM registry g JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN (SELECT kind FROM rooms WHERE id=g.room_id)='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?`, roomID, sessionID);
50
+ return !!entry && entry.membership_id === membershipID && (entry.receiver_owner_id ?? "") === ownerID && (entry.protocol === "v1" || entry.protocol === "v2" || Boolean(entry.host));
51
+ }
52
+ export type Recipient = { roomID: string; sessionID: string; ownerID: string; membershipID: string };
53
+ export function queue(db: Database, b: Binding, kind: string, text: string, taskID: string | null = null, taskToken: string | null = null, recipient: Recipient = { roomID: b.target_room_id, sessionID: b.session_id, ownerID: b.receiver_owner_id, membershipID: b.membership_id }) {
54
+ const id = randomUUID();
55
+ run(db, `INSERT INTO admin_deliveries(id,admin_room_id,generation,recipient_room_id,session_id,owner_id,membership_id,kind,text,task_id,task_token,admission_id,created_at)
56
+ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(admin_room_id,kind,task_id) DO UPDATE SET text=excluded.text,task_token=excluded.task_token,generation=excluded.generation,recipient_room_id=excluded.recipient_room_id,session_id=excluded.session_id,owner_id=excluded.owner_id,membership_id=excluded.membership_id,created_at=excluded.created_at,acknowledged=0`,
57
+ id,b.room_id,b.generation,recipient.roomID,recipient.sessionID,recipient.ownerID,recipient.membershipID,kind,text,taskID,taskToken,`msg_${id}`,Date.now());
58
+ }
59
+ export function one<T>(db: Database, sql: string, ...args: SQLQueryBindings[]) { return row<T>(db, sql, ...args); }
60
+ export function many<T>(db: Database, sql: string, ...args: SQLQueryBindings[]) { return all<T>(db, sql, ...args); }
61
+ export { run as exec, randomUUID };