@alexsun-top/opencode-chat-room 0.8.6 → 0.8.8

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.
@@ -348,9 +348,8 @@
348
348
  the all-read icon without depending on font metrics. */
349
349
  .message-readers { flex: 0 0 24px; align-self: flex-end; display: grid; place-items: center; margin: 0; padding: 0; width: 24px; height: 24px; border: 1px solid var(--line); border-radius: 50%; color: var(--ink-3); background: var(--surface); font: inherit; font-size: 10px; line-height: 1; cursor: pointer; box-shadow: 0 1px 3px rgb(20 40 32 / .06); }
350
350
  .message-readers[data-reader-state="empty"], .message-readers[data-reader-state="unknown"] { background: var(--surface-2); }
351
- .message-readers[data-reader-state="delivered"] { color: var(--ink-2); background: var(--surface-2); }
352
351
  .message-readers[data-reader-state="all"] { border-color: color-mix(in srgb, var(--accent) 45%, var(--line)); color: var(--accent); background: var(--accent-soft); }
353
- .message-read-check, .message-delivered-icon { display: block; width: 14px; height: 14px; }
352
+ .message-read-check { display: block; width: 14px; height: 14px; }
354
353
  .reader-delivered { margin-top: 10px; padding-top: 8px; border-top: 1px solid var(--line); }
355
354
  .message-readers:hover, .message-readers[aria-expanded="true"] { border-color: var(--accent); color: var(--accent); }
356
355
  .message-readers:focus-visible, .reader-close:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
@@ -718,17 +717,17 @@
718
717
  #roomList > li > .room-row, #roomListChat > li > .room-row { flex: 1; min-width: 0; }
719
718
  .room-row[draggable="true"] { cursor: grab; }
720
719
  .room-row.dragging { opacity: .45; }
721
- .room-row.drop-target { outline: 2px dashed var(--accent); outline-offset: 2px; }
722
- .room-move { display: none; flex-direction: column; gap: 2px; margin-left: 2px; }
723
- .room-move-btn { display: grid; place-items: center; width: 26px; height: 24px; padding: 0; border: 1px solid transparent; border-radius: 7px; color: var(--ink-3); background: transparent; cursor: pointer; }
724
- .room-move-btn:hover { color: var(--accent); border-color: var(--line); background: var(--surface); }
725
- .room-move-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
726
- .room-move-btn:disabled { opacity: .3; cursor: default; }
727
- .room-move-btn svg { width: 14px; height: 14px; }
728
- @media (hover: none), (pointer: coarse) {
729
- .room-move { display: flex; }
720
+ .room-row.dragging { opacity: .45; }
721
+ /* Insertion line: one clear target while dragging, no outline box. */
722
+ .room-row.drop-before { box-shadow: inset 0 2px 0 var(--accent); }
723
+ .room-row.drop-after { box-shadow: inset 0 -2px 0 var(--accent); }
724
+ .room-row[draggable="true"] { cursor: grab; }
725
+ .room-grip { display: none; margin-left: 4px; padding: 0 4px; color: var(--ink-3); touch-action: none; cursor: grab; user-select: none; }
726
+ @media (pointer: coarse) {
727
+ .room-grip { display: inline-block; }
730
728
  .room-row[draggable="true"] { cursor: pointer; }
731
729
  }
730
+ }
732
731
  #roomList[aria-busy="true"], #roomListChat[aria-busy="true"] { opacity: .6; transition: opacity .15s ease; }
733
732
  #btnRefreshRooms.is-refreshing svg { animation: spin .8s linear infinite; }
734
733
  @media (prefers-reduced-motion: reduce) { #btnRefreshRooms.is-refreshing svg { animation: none; opacity: .6; } }
@@ -25,7 +25,7 @@ import { createHost, type ChannelHost, type SpawnAdapter } from "../packages/cha
25
25
  import { validateTargets } from "../packages/chat-room-channeld/src/host-helpers.ts";
26
26
  import { EVENT_SCHEMA_VERSION, type Endpoint, type IngestEvent } from "../packages/chat-room-channeld/src/protocol.ts";
27
27
  import { matchRules, targetKey } from "../packages/chat-room-channeld/src/rules.ts";
28
- import { inboundRoomText, matchInboundRoutes } from "../packages/chat-room-channeld/src/inbound.ts";
28
+ import { inboundRoomText, inboundRoutes } from "../packages/chat-room-channeld/src/inbound.ts";
29
29
  import { forwardAttachments, inboundAttachments, prepareSendPayload } from "./channel-attachments.ts";
30
30
  import {
31
31
  isTerminalDeliveryState,
@@ -147,9 +147,9 @@ export function createInboundRelay(config: ChannelConfig): {
147
147
  notificationOnly: (event: IngestEvent) => boolean;
148
148
  } {
149
149
  return {
150
- notificationOnly: (event) => matchInboundRoutes(config, event).length > 0,
150
+ notificationOnly: (event) => inboundRoutes(config, event).length > 0,
151
151
  onIngestCommitted: async (event) => {
152
- for (const route of matchInboundRoutes(config, event)) {
152
+ for (const route of inboundRoutes(config, event)) {
153
153
  const text = inboundRoomText(event, route);
154
154
  if (!text && !event.content?.attachments?.length) continue;
155
155
  // Resource uploads are idempotent per event, room, and index, so a
@@ -171,6 +171,23 @@ export function createInboundRelay(config: ChannelConfig): {
171
171
  ).run(event.eventId, route.to.room, Date.now());
172
172
  if (Number(inserted.changes) === 0) return;
173
173
  svc.addEvent(route.to.room, body);
174
+ // Remember where this room's inbound came from so a reply can return
175
+ // to the same chat without a per-chat rule.
176
+ db.exec(
177
+ `CREATE TABLE IF NOT EXISTS channel_inbound_sources (
178
+ room_id TEXT NOT NULL,
179
+ platform TEXT NOT NULL,
180
+ account TEXT NOT NULL,
181
+ chat_id TEXT NOT NULL,
182
+ last_at INTEGER NOT NULL,
183
+ PRIMARY KEY (room_id, platform, account, chat_id)
184
+ )`,
185
+ );
186
+ db.query(
187
+ `INSERT INTO channel_inbound_sources (room_id, platform, account, chat_id, last_at)
188
+ VALUES (?, ?, ?, ?, ?)
189
+ ON CONFLICT(room_id, platform, account, chat_id) DO UPDATE SET last_at = excluded.last_at`,
190
+ ).run(route.to.room, event.source.platform, event.source.accountId, route.from.room, Date.now());
174
191
  });
175
192
  }
176
193
  },
@@ -332,7 +349,8 @@ export function createChannelController(
332
349
  const handle = async (req: Request, url: URL): Promise<Response | undefined> => {
333
350
  const adminPath = url.pathname === "/channeld/reload"
334
351
  || url.pathname === "/channeld/enable"
335
- || url.pathname === "/channeld/disable";
352
+ || url.pathname === "/channeld/disable"
353
+ || url.pathname === "/channeld/op";
336
354
  const integrationPath = url.pathname === "/channeld/plugins"
337
355
  || url.pathname.startsWith("/channeld/plugins/")
338
356
  || url.pathname === "/channeld/integration";
@@ -350,6 +368,22 @@ export function createChannelController(
350
368
 
351
369
  if (url.pathname === "/channeld/disable") return serial(disableCore);
352
370
 
371
+ if (url.pathname === "/channeld/op") {
372
+ if (!runtime) return json({ error: "relay is disabled; enable it first" }, 409);
373
+ const raw = await req.json().catch(() => undefined) as Record<string, unknown> | undefined;
374
+ const account = typeof raw?.account === "string" ? raw.account.trim() : "";
375
+ const op = typeof raw?.op === "string" ? raw.op.trim() : "";
376
+ if (!account || !op) return json({ error: "account and op are required" }, 400);
377
+ const params = raw?.params && typeof raw.params === "object" && !Array.isArray(raw.params)
378
+ ? raw.params as Record<string, unknown>
379
+ : {};
380
+ try {
381
+ return json({ ok: true, result: await runtime.host.runOp(account, op, params) });
382
+ } catch (error) {
383
+ return json({ error: error instanceof Error ? error.message : String(error) }, 502);
384
+ }
385
+ }
386
+
353
387
  const body = await readAdminBody(req);
354
388
  if (!body.ok) return json({ error: "invalid request body" }, 400);
355
389
  const configPath = body.config ?? settings.channeld.config;
@@ -448,7 +482,7 @@ async function isRoomMember(roomId: string, sessionID: string): Promise<boolean>
448
482
  }
449
483
 
450
484
  /** Targets of rules whose source is this room's forward requests and whose account is ready. */
451
- function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[] {
485
+ async function forwardTargets(runtime: ChannelsRuntime, roomId: string): Promise<RuleTarget[]> {
452
486
  const probe: IngestEvent = {
453
487
  schemaVersion: EVENT_SCHEMA_VERSION,
454
488
  eventId: "forward-targets",
@@ -463,6 +497,7 @@ function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[]
463
497
  const targets: RuleTarget[] = [];
464
498
  for (const rule of matchRules(config, probe)) {
465
499
  for (const target of rule.to) {
500
+ if (target.room === "*") continue;
466
501
  if (runtime.host.targetStatus(target.platform, target.account) !== "ready") continue;
467
502
  const key = `${target.platform}/${target.account}/${target.room}`;
468
503
  if (seen.has(key)) continue;
@@ -470,6 +505,24 @@ function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[]
470
505
  targets.push(target);
471
506
  }
472
507
  }
508
+ // Dynamic targets: only rooms whose rules declare a wildcard target may send
509
+ // a reply back to a chat that wrote to them; the server records the chat.
510
+ const wildcards = matchRules(config, probe)
511
+ .flatMap((rule) => rule.to)
512
+ .filter((target) => target.room === "*");
513
+ if (wildcards.length) {
514
+ const db = await openStateDatabase(databasePath());
515
+ const rows = db.query(
516
+ "SELECT platform, account, chat_id FROM channel_inbound_sources WHERE room_id = ? ORDER BY last_at DESC LIMIT 20",
517
+ ).all(roomId) as Array<{ platform: string; account: "string"; chat_id: string }>;
518
+ for (const row of rows) {
519
+ const matched = wildcards.find((target) => target.platform === row.platform && target.account === row.account);
520
+ if (!matched || seen.has(`${row.platform}/${row.account}/${row.chat_id}`)) continue;
521
+ if (runtime.host.targetStatus(row.platform, row.account) !== "ready") continue;
522
+ seen.add(`${row.platform}/${row.account}/${row.chat_id}`);
523
+ targets.push({ platform: row.platform, account: row.account, room: row.chat_id });
524
+ }
525
+ }
473
526
  return targets;
474
527
  }
475
528
 
@@ -522,7 +575,7 @@ export async function channelRoutes(
522
575
 
523
576
  const message = await readForwardableMessage(roomId, messageId, sessionID);
524
577
  if (!message) return json({ error: "message not found" }, 404);
525
- if (!forwardTargets(runtime, roomId).some((candidate) =>
578
+ if (!(await forwardTargets(runtime, roomId)).some((candidate) =>
526
579
  candidate.platform === target.platform && candidate.account === target.account && candidate.room === target.room)) {
527
580
  return json({ error: "forward target is unavailable" }, 409);
528
581
  }
@@ -564,5 +617,5 @@ export async function channelRoutes(
564
617
  const sessionID = (url.searchParams.get("sessionID") ?? "").trim();
565
618
  if (!sessionID || sessionID.length > MAX_SESSION) return json({ error: "sessionID is required" }, 400);
566
619
  if (!await isRoomMember(roomId, sessionID)) return json({ error: "room not found" }, 404);
567
- return json({ targets: forwardTargets(runtime, roomId) });
620
+ return json({ targets: await forwardTargets(runtime, roomId) });
568
621
  }
@@ -17,6 +17,10 @@ const serve = createApp({
17
17
  token: bootstrap.token,
18
18
  serveWakeUrl: bootstrap.serveWakeUrl,
19
19
  channeld: () => channels,
20
+ mcp: {
21
+ center: `http://127.0.0.1:${bootstrap.port}`,
22
+ sessionID: process.env.CHAT_ROOM_MCP_SESSION ?? "ses_mcp_http",
23
+ },
20
24
  });
21
25
  // Test-only request accounting: asset hits prove whether a warm open re-downloaded.
22
26
  const handle: typeof serve = process.env.CHAT_ROOM_TEST_ACCESS_LOG === "1"
@@ -0,0 +1,88 @@
1
+ // Streamable HTTP transport for the MCP room tool (MCP 2025-03-26).
2
+ // Stateless: every POST carries one JSON-RPC message or a batch; SSE is not
3
+ // offered, so requests answer with application/json and notifications get 202.
4
+ import { randomUUID, timingSafeEqual } from "node:crypto";
5
+
6
+ import { createMcpHandler } from "../src/mcp/server.ts";
7
+
8
+ const MAX_BODY_BYTES = 1_048_576;
9
+
10
+ export type McpHttpOptions = {
11
+ sessionID: string;
12
+ center: string;
13
+ token?: string;
14
+ };
15
+
16
+ function json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {
17
+ return new Response(JSON.stringify(body), {
18
+ status,
19
+ headers: { "content-type": "application/json", ...headers },
20
+ });
21
+ }
22
+
23
+ function sameSecret(given: string, secret: string): boolean {
24
+ const a = Buffer.from(given);
25
+ const b = Buffer.from(secret);
26
+ return a.length === b.length && timingSafeEqual(a, b);
27
+ }
28
+
29
+ function bearer(req: Request, token: string): boolean {
30
+ const header = req.headers.get("authorization") ?? "";
31
+ return header.startsWith("Bearer ") && sameSecret(header.slice("Bearer ".length), token);
32
+ }
33
+
34
+ function allowed(req: Request, url: URL, token: string | undefined): boolean {
35
+ if (url.pathname === "/mcp") return !token || bearer(req, token);
36
+ // A secret path lets clients that only offer "no authentication" connect.
37
+ const secret = url.pathname.slice("/mcp/".length);
38
+ return Boolean(token) && !secret.includes("/") && sameSecret(secret, token!);
39
+ }
40
+
41
+ function notify(): Response {
42
+ return new Response(null, { status: 202 });
43
+ }
44
+
45
+ export async function mcpHttpRoutes(
46
+ req: Request,
47
+ url: URL,
48
+ options: McpHttpOptions,
49
+ ): Promise<Response | undefined> {
50
+ if (url.pathname !== "/mcp" && !url.pathname.startsWith("/mcp/")) return undefined;
51
+ if (!allowed(req, url, options.token)) return json({ error: "unauthorized" }, 401);
52
+ if (req.method === "GET") {
53
+ return new Response("SSE stream not supported; use POST", { status: 405, headers: { allow: "POST, DELETE" } });
54
+ }
55
+ if (req.method === "DELETE") return new Response(null, { status: 204 });
56
+ if (req.method !== "POST") {
57
+ return new Response(null, { status: 405, headers: { allow: "POST, DELETE" } });
58
+ }
59
+ if (!req.headers.get("content-type")?.includes("application/json")) {
60
+ return json({ error: "content-type must be application/json" }, 415);
61
+ }
62
+ const body = await req.text();
63
+ if (Buffer.byteLength(body) > MAX_BODY_BYTES) return json({ error: "request body too large" }, 413);
64
+ let message: unknown;
65
+ try {
66
+ message = JSON.parse(body);
67
+ } catch {
68
+ return json({ jsonrpc: "2.0", id: null, error: { code: -32700, message: "parse error" } }, 400);
69
+ }
70
+
71
+ const handler = createMcpHandler(options.center, options.sessionID, options.token);
72
+ const initialize = !Array.isArray(message) && Boolean(message) && typeof message === "object" &&
73
+ (message as { method?: unknown }).method === "initialize";
74
+ const headers: Record<string, string> = initialize ? { "mcp-session-id": randomUUID() } : {};
75
+
76
+ if (Array.isArray(message)) {
77
+ if (!message.length) return notify();
78
+ const responses: unknown[] = [];
79
+ for (const item of message) {
80
+ const response = await handler(item);
81
+ if (response) responses.push(response);
82
+ }
83
+ return responses.length ? json(responses, 200, headers) : notify();
84
+ }
85
+
86
+ const response = await handler(message);
87
+ return response ? json(response, 200, headers) : notify();
88
+ }
@@ -7,9 +7,14 @@ import { withStateTransaction } from "../src/state/sqlite-state.ts";
7
7
  import { writeSqliteStateWithDatabase } from "../src/state/sqlite-state-store.ts";
8
8
  import { databasePath } from "../src/state/store.ts";
9
9
  import { operatorAuthorized } from "./operator-auth.ts";
10
- import { getOperatorRoom, insertOperatorAudit, listOperatorAudit, listOperatorCandidates, listOperatorRooms } from "./operator-state.ts";
10
+ import { getOperatorRoom, insertOperatorAction, insertOperatorAudit, listOperatorActions, listOperatorAudit, listOperatorCandidates, listOperatorMembers, listOperatorRooms } from "./operator-state.ts";
11
11
  import { applyOwnerTransfer } from "./room-owner.ts";
12
+ import { clearPendingAdmission } from "../src/center/queue.ts";
13
+ import { removeRoomResources } from "../src/rooms/resources.ts";
14
+ import { findJoinRequest, removeJoinRequest } from "../src/state/sqlite-state.ts";
15
+ import { joinRoomMember } from "./room-join.ts";
12
16
 
17
+ type RoomId = string;
13
18
  type OperatorOptions = { here: string; token?: string };
14
19
 
15
20
  const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {
@@ -24,6 +29,9 @@ const PAGE_CSP = "default-src 'none'; script-src 'self'; style-src 'self'; conne
24
29
  // worker cannot claim them. They carry no data or credentials.
25
30
  const STATIC_FILES: Record<string, { file: string; type: string }> = {
26
31
  "/system/operator.js": { file: "assets/chat/operator.js", type: "text/javascript; charset=utf-8" },
32
+ "/system/operator-api.js": { file: "assets/chat/operator-api.js", type: "text/javascript; charset=utf-8" },
33
+ "/system/operator-i18n.js": { file: "assets/chat/operator-i18n.js", type: "text/javascript; charset=utf-8" },
34
+ "/system/operator-manage.js": { file: "assets/chat/operator-manage.js", type: "text/javascript; charset=utf-8" },
27
35
  "/system/operator.css": { file: "operator.css", type: "text/css; charset=utf-8" },
28
36
  };
29
37
 
@@ -69,8 +77,35 @@ export async function operatorRoutes(req: Request, url: URL, options: OperatorOp
69
77
  }
70
78
  const detail = p.match(/^\/system\/rooms\/([^/]+)$/);
71
79
  if (detail) {
80
+ const roomId = decodeSegment(detail[1]!);
81
+ if (req.method === "GET") return await roomDetail(roomId);
82
+ if (req.method === "DELETE") return await deleteRoom(req, roomId);
83
+ return json({ error: "method not allowed" }, 405);
84
+ }
85
+ const rename = p.match(/^\/system\/rooms\/([^/]+)\/rename$/);
86
+ if (rename) {
87
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
88
+ return await renameRoom(req, decodeSegment(rename[1]!));
89
+ }
90
+ const joins = p.match(/^\/system\/rooms\/([^/]+)\/join-requests$/);
91
+ if (joins) {
72
92
  if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
73
- return await roomDetail(decodeSegment(detail[1]!));
93
+ return await listJoins(decodeSegment(joins[1]!));
94
+ }
95
+ const joinAction = p.match(/^\/system\/rooms\/([^/]+)\/join-requests\/([^/]+)\/(approve|deny)$/);
96
+ if (joinAction) {
97
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
98
+ return await reviewJoin(decodeSegment(joinAction[1]!), decodeSegment(joinAction[2]!), joinAction[3] === "approve");
99
+ }
100
+ const memberRole = p.match(/^\/system\/rooms\/([^/]+)\/members\/role$/);
101
+ if (memberRole) {
102
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
103
+ return await setMemberRole(req, decodeSegment(memberRole[1]!));
104
+ }
105
+ const memberRemove = p.match(/^\/system\/rooms\/([^/]+)\/members\/remove$/);
106
+ if (memberRemove) {
107
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
108
+ return await removeMember(req, decodeSegment(memberRemove[1]!));
74
109
  }
75
110
  const owner = p.match(/^\/system\/rooms\/([^/]+)\/owner$/);
76
111
  if (owner) {
@@ -89,7 +124,13 @@ async function roomDetail(roomId: string): Promise<Response> {
89
124
  const detail = await readOnly((db) => {
90
125
  const room = getOperatorRoom(db, roomId);
91
126
  if (!room) return undefined;
92
- return { room, candidates: listOperatorCandidates(db, roomId), audit: listOperatorAudit(db, roomId) };
127
+ const pendingJoins = Number((db.query("SELECT COUNT(*) AS n FROM room_join_requests WHERE room_id=?").get(roomId) as { n: number } | null)?.n ?? 0);
128
+ return {
129
+ room: { ...room, admins: [...(room.adminIds ?? [])], members: listOperatorMembers(db, roomId), pendingJoins },
130
+ candidates: listOperatorCandidates(db, roomId),
131
+ audit: listOperatorAudit(db, roomId),
132
+ actions: listOperatorActions(db, roomId),
133
+ };
93
134
  });
94
135
  return detail ? json(detail) : json({ error: "not found" }, 404);
95
136
  }
@@ -148,3 +189,154 @@ async function transferOwner(req: Request, roomId: string): Promise<Response> {
148
189
  }
149
190
  return json({ changed: result.changed });
150
191
  }
192
+
193
+
194
+ async function readJson(req: Request): Promise<Record<string, unknown> | undefined> {
195
+ try {
196
+ const value: unknown = await req.json();
197
+ return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
198
+ } catch { return undefined; }
199
+ }
200
+
201
+ async function renameRoom(req: Request, roomId: string): Promise<Response> {
202
+ const body = await readJson(req);
203
+ if (!body) return json({ error: "invalid request" }, 400);
204
+ const name = typeof body.name === "string" ? body.name.trim() : "";
205
+ if (!name || name.length > 64) return json({ error: "name must be 1-64 characters" }, 400);
206
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, _registry, db) => {
207
+ let room: Room;
208
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
209
+ if ((room.kind ?? "group") !== "group") return { status: 404 as const };
210
+ const previous = room.name;
211
+ if (previous === name) return { changed: false };
212
+ room.name = name;
213
+ svcAddEvent(svc, roomId, `System operator renamed the room from "${previous}" to "${name}"`);
214
+ insertOperatorAction(db, roomId, "rename", name, previous);
215
+ return { changed: true };
216
+ });
217
+ return "status" in result ? json({ error: "not found" }, 404) : json({ changed: result.changed });
218
+ }
219
+
220
+ function svcAddEvent(svc: { addEvent(roomId: string, text: string): unknown }, roomId: string, text: string): void {
221
+ svc.addEvent(roomId, text);
222
+ }
223
+
224
+ async function deleteRoom(req: Request, roomId: string): Promise<Response> {
225
+ const body = await readJson(req);
226
+ if (!body) return json({ error: "invalid request" }, 400);
227
+ const confirmName = typeof body.name === "string" ? body.name.trim() : "";
228
+ if (!confirmName || confirmName.length > 64) return json({ error: "type the room name to confirm" }, 400);
229
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
230
+ let room: Room;
231
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
232
+ if ((room.kind ?? "group") !== "group") return { status: 404 as const };
233
+ if (room.name !== confirmName) return { status: 409 as const, error: "room name does not match" };
234
+ const sessions = Object.entries(registry[roomId] ?? {}).map(([sid]) => sid);
235
+ svc.deleteRoom(roomId);
236
+ delete registry[roomId];
237
+ insertOperatorAction(db, roomId, "delete", room.name, `${sessions.length} members`);
238
+ return { sessions };
239
+ });
240
+ if ("status" in result) return result.status === 404 ? json({ error: "not found" }, 404) : json({ error: result.error }, 409);
241
+ await removeRoomResources(roomId).catch(() => console.error("failed to clean deleted room resources", roomId));
242
+ for (const sid of result.sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
243
+ return json({ ok: true });
244
+ }
245
+
246
+ async function setMemberRole(req: Request, roomId: RoomId): Promise<Response> {
247
+ const body = await readJson(req);
248
+ if (!body) return json({ error: "invalid request" }, 400);
249
+ const name = typeof body.name === "string" ? body.name.trim() : "";
250
+ const role = body.role === "admin" || body.role === "member" ? body.role : undefined;
251
+ if (!name || name.length > 64 || !role) return json({ error: "name and role are required" }, 400);
252
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
253
+ let room: Room;
254
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
255
+ const entry = Object.values(registry[roomId] ?? {}).find((candidate) => candidate.name === name && isUser(candidate));
256
+ if (!entry) return { status: 409 as const, error: "target is not a joined human member" };
257
+ if (name === room.ownerId) return { status: 409 as const, error: "the owner is already an administrator" };
258
+ const admins = new Set(room.adminIds ?? []);
259
+ if (role === "admin") admins.add(name); else admins.delete(name);
260
+ room.adminIds = [...adminsCheck(admins)];
261
+ const ids = new Set(room.adminMembershipIDs ?? []);
262
+ if (role === "admin" && entry.membershipID) ids.add(entry.membershipID);
263
+ if (role === "member" && entry.membershipID) ids.delete(entry.membershipID);
264
+ if (ids.size) room.adminMembershipIDs = [...ids]; else delete room.adminMembershipIDs;
265
+ insertOperatorAction(db, roomId, role === "admin" ? "grant-admin" : "revoke-admin", name, "");
266
+ return { changed: true };
267
+ });
268
+ return "status" in result ? json({ error: result.error }, result.status) : json({ changed: result.changed });
269
+ }
270
+
271
+ function adminsCheck(names: Set<string>): Set<string> { return names; }
272
+
273
+ async function removeMember(req: Request, roomId: string): Promise<Response> {
274
+ const body = await readJson(req);
275
+ if (!body) return json({ error: "invalid request" }, 400);
276
+ const name = typeof body.name === "string" ? body.name.trim() : "";
277
+ if (!name || name.length > 64) return json({ error: "name is required" }, 400);
278
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
279
+ let room: Room;
280
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
281
+ if (name === room.ownerId) return { status: 409 as const, error: "the owner cannot be removed; transfer the room first" };
282
+ const sessions = Object.entries(registry[roomId] ?? {}).filter(([, entry]) => entry.name === name).map(([sid]) => sid);
283
+ if (!sessions.length) return { status: 404 as const };
284
+ for (const sid of sessions) delete registry[roomId]![sid];
285
+ for (const [id, participant] of [...room.participants]) if (participant.name === name) svc.leaveRoom(roomId, id);
286
+ if (room.adminIds) { room.adminIds = room.adminIds.filter((admin) => admin !== name); if (!room.adminIds.length) delete room.adminIds; }
287
+ insertOperatorAction(db, roomId, "remove-member", name, `${sessions.length} sessions`);
288
+ return { sessions };
289
+ });
290
+ if ("status" in result) return result.status === 404 ? json({ error: "not found" }, 404) : json({ error: result.error }, 409);
291
+ for (const sid of result.sessions) clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
292
+ return json({ ok: true });
293
+ }
294
+
295
+
296
+ async function listJoins(roomId: string): Promise<Response> {
297
+ if (!roomId || roomId.length > 128) return json({ error: "not found" }, 404);
298
+ const rows = await readOnly((db) => db.query(
299
+ "SELECT session_id AS sessionID,participant_id AS participantId,name,is_agent AS isAgent,created_at AS createdAt FROM room_join_requests WHERE room_id=? ORDER BY created_at"
300
+ ).all(roomId) as Array<{ sessionID: string; participantId: string; name: string; isAgent: number; createdAt: number }>);
301
+ return json({ requests: rows.map((row) => ({
302
+ sessionID: String(row.sessionID), participantId: String(row.participantId), name: String(row.name),
303
+ isAgent: Number(row.isAgent) === 1, createdAt: Number(row.createdAt),
304
+ })) });
305
+ }
306
+
307
+ async function reviewJoin(roomId: string, requestSessionID: string, approve: boolean): Promise<Response> {
308
+ if (!roomId || roomId.length > 128 || !requestSessionID || requestSessionID.length > 128) return json({ error: "not found" }, 404);
309
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
310
+ let room: Room;
311
+ try { room = svc.getRoom(roomId); } catch { return { status: 404 as const }; }
312
+ const request = findJoinRequest(db, roomId, requestSessionID);
313
+ if (!request) return { status: 404 as const, error: "join request not found" };
314
+ if (!approve) {
315
+ removeJoinRequest(db, roomId, requestSessionID);
316
+ insertOperatorAction(db, roomId, "deny-join", request.name, "");
317
+ return { ok: true as const };
318
+ }
319
+ if (registry[roomId]?.[request.sessionID]) {
320
+ removeJoinRequest(db, roomId, requestSessionID);
321
+ return { status: 409 as const, error: "requester already joined the room" };
322
+ }
323
+ if (svc.containsParticipant(roomId, request.participantId)) {
324
+ removeJoinRequest(db, roomId, requestSessionID);
325
+ return { status: 409 as const, error: "participant name is already in use in this room" };
326
+ }
327
+ removeJoinRequest(db, roomId, requestSessionID);
328
+ joinRoomMember(svc, registry, roomId, {
329
+ sessionID: request.sessionID,
330
+ participantId: request.participantId,
331
+ name: request.name,
332
+ ...(request.protocol ? { protocol: request.protocol } : {}),
333
+ ...(request.receiverOwnerID ? { receiverOwnerID: request.receiverOwnerID } : {}),
334
+ ...(request.directory ? { directory: request.directory } : {}),
335
+ ...(request.host ? { host: request.host } : {}),
336
+ notify: true,
337
+ });
338
+ insertOperatorAction(db, roomId, "approve-join", request.name, "");
339
+ return { ok: true as const };
340
+ });
341
+ return "ok" in result ? json({ ok: true }) : json({ error: result.error }, result.status);
342
+ }
@@ -2,10 +2,21 @@ import { randomUUID } from "node:crypto";
2
2
  import { isUser } from "../src/state/roles.ts";
3
3
  import type { StateDatabase } from "../src/state/sqlite.ts";
4
4
 
5
- export type OperatorRoom = { id: string; name: string; ownerId: string };
6
- export type OperatorRoomDetail = OperatorRoom & { ownerMembershipID: string | null };
5
+ export type OperatorRoom = {
6
+ id: string; name: string; ownerId: string; kind: "group";
7
+ memberCount: number; agentCount: number; lastActiveAt: number | null;
8
+ };
9
+ export type OperatorRoomDetail = OperatorRoom & {
10
+ ownerMembershipID: string | null;
11
+ adminIds: string[];
12
+ admins: string[];
13
+ members: OperatorMember[];
14
+ pendingJoins: number;
15
+ };
16
+ export type OperatorMember = { name: string; role: "owner" | "admin" | "member"; isAgent: boolean; lastSeenAt: number | null };
7
17
  export type OperatorCandidate = { name: string; membershipID: string };
8
18
  export type OperatorAudit = { createdAt: number; previousOwner: string; targetName: string; reason: string };
19
+ export type OperatorAction = { createdAt: number; action: string; target: string; detail: string };
9
20
  export type OperatorAuditInput = {
10
21
  roomId: string;
11
22
  previousOwner: string;
@@ -17,18 +28,71 @@ export type OperatorAuditInput = {
17
28
  };
18
29
 
19
30
  export function listOperatorRooms(db: StateDatabase): OperatorRoom[] {
20
- const rows = db.query("SELECT id,name,owner_id AS ownerId FROM rooms WHERE COALESCE(kind,'group')='group' ORDER BY created_at,id").all() as Array<{ id: string; name: string; ownerId: string }>;
21
- return rows.map((row) => ({ id: String(row.id), name: String(row.name), ownerId: String(row.ownerId) }));
31
+ const rows = db.query(`SELECT r.id,r.name,r.owner_id AS ownerId,
32
+ (SELECT COUNT(*) FROM participants p WHERE p.room_id=r.id) AS memberCount,
33
+ (SELECT COUNT(*) FROM registry g WHERE g.room_id=r.id AND g.protocol IS NOT NULL) AS agentCount,
34
+ (SELECT MAX(m.created_at) FROM messages m WHERE m.room_id=r.id) AS lastActiveAt
35
+ FROM rooms r WHERE COALESCE(r.kind,'group')='group' ORDER BY r.created_at,r.id`).all() as Array<{
36
+ id: string; name: string; ownerId: string; memberCount: number; agentCount: number; lastActiveAt: number | null;
37
+ }>;
38
+ return rows.map((row) => ({
39
+ id: String(row.id), name: String(row.name), ownerId: String(row.ownerId), kind: "group" as const,
40
+ memberCount: Number(row.memberCount), agentCount: Number(row.agentCount),
41
+ lastActiveAt: row.lastActiveAt === null ? null : Number(row.lastActiveAt),
42
+ }));
43
+ }
44
+
45
+ export function listOperatorMembers(db: StateDatabase, roomId: string): OperatorMember[] {
46
+ const room = db.query("SELECT owner_id AS ownerId,admin_names AS adminNames FROM rooms WHERE id=?").get(roomId) as
47
+ { ownerId: string; admin_names?: string; adminNames: string | null } | null;
48
+ if (!room) return [];
49
+ const admins = new Set<string>(room.adminNames ? JSON.parse(String(room.adminNames)) as string[] : []);
50
+ const rows = db.query(`SELECT p.name AS name, g.protocol AS protocol, g.last_seen_at AS lastSeenAt
51
+ FROM participants p LEFT JOIN registry g ON g.room_id=p.room_id AND (g.name=p.name OR g.name=p.id)
52
+ WHERE p.room_id=? ORDER BY p.joined_at, p.name`).all(roomId) as Array<{
53
+ name: string; protocol: string | null; lastSeenAt: number | null;
54
+ }>;
55
+ return rows.map((row) => {
56
+ const name = String(row.name);
57
+ return {
58
+ name,
59
+ role: name === String(room.ownerId) ? "owner" as const : admins.has(name) ? "admin" as const : "member" as const,
60
+ isAgent: row.protocol !== null,
61
+ lastSeenAt: row.lastSeenAt === null ? null : Number(row.lastSeenAt),
62
+ };
63
+ });
64
+ }
65
+
66
+ export function listOperatorActions(db: StateDatabase, roomId: string): OperatorAction[] {
67
+ const rows = db.query("SELECT created_at AS createdAt,action,target,detail FROM system_operator_actions WHERE room_id=? ORDER BY created_at DESC,id DESC LIMIT 50").all(roomId) as Array<{
68
+ createdAt: number; action: string; target: string; detail: string;
69
+ }>;
70
+ return rows.map((row) => ({
71
+ createdAt: Number(row.createdAt), action: String(row.action), target: String(row.target), detail: String(row.detail),
72
+ }));
73
+ }
74
+
75
+ export function insertOperatorAction(db: StateDatabase, roomId: string, action: string, target: string, detail: string): void {
76
+ db.query("INSERT INTO system_operator_actions(id,room_id,actor,action,target,detail,created_at) VALUES(?,?,?,?,?,?,?)")
77
+ .run(randomUUID(), roomId, "operator", action, target.slice(0, 200), detail.slice(0, 500), Date.now());
22
78
  }
23
79
 
24
- export function getOperatorRoom(db: StateDatabase, roomId: string): OperatorRoomDetail | undefined {
25
- const row = db.query("SELECT id,name,owner_id AS ownerId,owner_membership_id AS ownerMembershipID,kind FROM rooms WHERE id=?").get(roomId) as {
80
+ export function getOperatorRoom(db: StateDatabase, roomId: string): Omit<OperatorRoomDetail, "members" | "admins" | "pendingJoins"> | undefined {
81
+ const row = db.query(`SELECT r.id,r.name,r.owner_id AS ownerId,r.owner_membership_id AS ownerMembershipID,r.kind,r.admin_names AS adminNames,
82
+ (SELECT COUNT(*) FROM participants p WHERE p.room_id=r.id) AS memberCount,
83
+ (SELECT COUNT(*) FROM registry g WHERE g.room_id=r.id AND g.protocol IS NOT NULL) AS agentCount,
84
+ (SELECT MAX(m.created_at) FROM messages m WHERE m.room_id=r.id) AS lastActiveAt
85
+ FROM rooms r WHERE r.id=?`).get(roomId) as {
26
86
  id: string; name: string; ownerId: string; ownerMembershipID: string | null; kind: string | null;
87
+ adminNames: string | null; memberCount: number; agentCount: number; lastActiveAt: number | null;
27
88
  } | null;
28
89
  if (!row || (row.kind ?? "group") !== "group") return undefined;
29
90
  return {
30
- id: String(row.id), name: String(row.name), ownerId: String(row.ownerId),
31
- ownerMembershipID: row.ownerMembershipID ? String(row.ownerMembershipID) : null,
91
+ id: String(row.id), name: String(row.name), ownerMembershipID: row.ownerMembershipID ? String(row.ownerMembershipID) : null,
92
+ ownerId: String(row.ownerId), kind: "group" as const,
93
+ memberCount: Number(row.memberCount), agentCount: Number(row.agentCount),
94
+ lastActiveAt: row.lastActiveAt === null ? null : Number(row.lastActiveAt),
95
+ adminIds: row.adminNames ? JSON.parse(String(row.adminNames)) : [],
32
96
  };
33
97
  }
34
98
 
@@ -137,3 +137,32 @@ dialog p { margin: 0 0 8px; }
137
137
  *, *::before, *::after { animation: none !important; transition: none !important; }
138
138
  .status-slot[data-busy]::after { display: none; }
139
139
  }
140
+
141
+ /* Room list, members, joins, and administrator actions. */
142
+ .operator-tools { display: flex; justify-content: flex-end; gap: 8px; flex: none; }
143
+ .room-tools { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; }
144
+ .room-tools .input { flex: 1; }
145
+ .room-main { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
146
+ .room-meta { grid-column: 1 / -1; color: var(--ink-3); font-size: 12.5px; overflow-wrap: anywhere; }
147
+ .member-list, .join-list { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
148
+ .member-row, .join-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 6px 12px; padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
149
+ .member-head, .join-head { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 8px; min-width: 0; }
150
+ .member-name, .join-name { font-weight: 650; overflow-wrap: anywhere; }
151
+ .member-badges { display: inline-flex; flex-wrap: wrap; gap: 6px; }
152
+ .badge { display: inline-flex; align-items: center; padding: 1px 8px; border-radius: 999px; background: var(--surface-2); color: var(--ink-2); font-size: 11.5px; font-weight: 650; }
153
+ .badge.role-owner { background: color-mix(in srgb, var(--accent) 18%, var(--surface)); color: var(--accent); }
154
+ .badge.role-admin { background: color-mix(in srgb, var(--warning) 16%, var(--surface)); color: var(--warning); }
155
+ .badge.agent { background: var(--accent-soft); color: var(--accent); }
156
+ .member-seen, .join-time { color: var(--ink-3); font-size: 12.5px; }
157
+ .member-controls, .join-controls { display: flex; flex-wrap: wrap; gap: 8px; justify-content: flex-end; }
158
+ .card form, .card .btn { margin-top: 12px; }
159
+ .card .btn { margin-top: 12px; }
160
+ .danger-card { border-color: color-mix(in srgb, var(--danger) 40%, var(--line)); }
161
+ .btn.danger { background: var(--danger); color: #fffdf6; }
162
+ .btn.danger:hover { filter: brightness(1.06); }
163
+ [dir="rtl"] .member-controls, [dir="rtl"] .join-controls { justify-content: flex-start; }
164
+ @media (max-width: 560px) {
165
+ .member-row, .join-row { grid-template-columns: 1fr; }
166
+ .member-controls, .join-controls { justify-content: flex-start; }
167
+ .room-tools { flex-wrap: wrap; }
168
+ }