@alexsun-top/opencode-chat-room 0.7.3 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +12 -5
  3. package/README.zh-CN.md +12 -5
  4. package/cli.ts +26 -6
  5. package/dist/cli.js +7804 -0
  6. package/package.json +19 -6
  7. package/plugin.ts +7 -4
  8. package/server/admin-auth.ts +1 -1
  9. package/server/admin-routes.ts +2 -2
  10. package/server/admin-state.ts +2 -1
  11. package/server/assets/FLUENT-ICONS-LICENSE +25 -0
  12. package/server/assets/NOTICE.txt +2 -1
  13. package/server/assets/attachments.css +1 -1
  14. package/server/assets/base.css +29 -7
  15. package/server/assets/chat/admin.js +43 -3
  16. package/server/assets/chat/announcements.js +5 -3
  17. package/server/assets/chat/confirm-dialog.js +12 -2
  18. package/server/assets/chat/create-room-dialog.js +5 -3
  19. package/server/assets/chat/events.js +32 -7
  20. package/server/assets/chat/files.js +369 -0
  21. package/server/assets/chat/history-loader.js +36 -26
  22. package/server/assets/chat/icons.js +15 -0
  23. package/server/assets/chat/index.js +7 -1
  24. package/server/assets/chat/locales/de.js +19 -2
  25. package/server/assets/chat/locales/es.js +19 -2
  26. package/server/assets/chat/locales/fr.js +19 -2
  27. package/server/assets/chat/locales/it.js +19 -2
  28. package/server/assets/chat/locales/ja.js +19 -2
  29. package/server/assets/chat/locales/ko.js +19 -2
  30. package/server/assets/chat/markdown.js +5 -33
  31. package/server/assets/chat/message-polling.js +61 -6
  32. package/server/assets/chat/message-window.js +28 -0
  33. package/server/assets/chat/messages.js +32 -12
  34. package/server/assets/chat/palette.js +396 -0
  35. package/server/assets/chat/pwa.js +67 -9
  36. package/server/assets/chat/recall.js +3 -2
  37. package/server/assets/chat/replies.js +2 -1
  38. package/server/assets/chat/rooms.js +20 -7
  39. package/server/assets/chat/search.js +137 -0
  40. package/server/assets/chat/settings.js +11 -5
  41. package/server/assets/chat/shortcuts.js +1 -1
  42. package/server/assets/chat/state.js +38 -4
  43. package/server/assets/code-highlight.css +0 -5
  44. package/server/assets/conversation.css +5 -4
  45. package/server/assets/edit-room.css +77 -0
  46. package/server/assets/files.css +222 -0
  47. package/server/assets/fluent-icons.svg +42 -0
  48. package/server/assets/icons.css +9 -0
  49. package/server/assets/palette.css +263 -0
  50. package/server/assets/recall.css +2 -2
  51. package/server/assets/responsive.css +6 -5
  52. package/server/assets/room-create.css +1 -1
  53. package/server/assets/settings.css +10 -7
  54. package/server/chat-server.ts +46 -29
  55. package/server/chat.html +175 -61
  56. package/server/http-server.ts +182 -0
  57. package/server/join-requests.ts +4 -4
  58. package/server/manifest.webmanifest +1 -1
  59. package/server/member-routes.ts +3 -3
  60. package/server/message-recall-routes.ts +1 -1
  61. package/server/newrooms.ts +4 -4
  62. package/server/resource-routes.ts +19 -4
  63. package/server/room-join.ts +1 -1
  64. package/server/room-payload.ts +1 -1
  65. package/server/sw.js +12 -1
  66. package/server/wake.ts +1 -1
  67. package/src/README.md +4 -2
  68. package/src/config/file-config.ts +294 -0
  69. package/src/rooms/resource-read.ts +2 -1
  70. package/src/rooms/resource-upload.ts +6 -3
  71. package/src/rooms/resources.ts +7 -2
  72. package/src/runtime/watch.ts +13 -8
  73. package/src/state/receiver-state.ts +3 -5
  74. package/src/state/sqlite-state.ts +11 -7
  75. package/src/state/sqlite.ts +80 -0
  76. package/src/state/store.ts +1 -0
  77. package/src/tui/app.mjs +417 -0
  78. package/src/tui/config.mjs +194 -0
  79. package/src/tui/http.mjs +103 -0
  80. package/src/tui/main.mjs +176 -0
  81. package/src/tui/messages.mjs +67 -0
  82. package/src/tui/palette-app.mjs +265 -0
  83. package/src/tui/palette.mjs +101 -0
  84. package/src/tui/session.mjs +40 -0
  85. package/src/tui/ui-content.mjs +426 -0
  86. package/src/tui/ui-theme.mjs +60 -0
  87. package/src/tui/ui-view.mjs +452 -0
  88. package/src/tui/ui.mjs +262 -0
  89. package/src/tests/announcement-board.ts +0 -186
@@ -0,0 +1,182 @@
1
+ // ponytail: node:http <-> web Request/Response adapter. Product code uses the
2
+ // web handler shape, so Bun (auto-serve), Node and Deno share one implementation.
3
+ import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
4
+ import { Buffer } from "node:buffer";
5
+ import { Readable } from "node:stream";
6
+ import { pipeline } from "node:stream/promises";
7
+
8
+ export type ServerOptions = {
9
+ hostname: string;
10
+ port: number;
11
+ fetch(request: Request): Response | Promise<Response>;
12
+ maxRequestBodySize?: number;
13
+ idleTimeout?: number;
14
+ };
15
+
16
+ export type StartedServer = {
17
+ port: number;
18
+ close(): Promise<void>;
19
+ };
20
+
21
+ const hopByHop = new Set(["connection", "keep-alive", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade"]);
22
+
23
+ function requestURL(req: IncomingMessage, hostname: string, port: number): string {
24
+ const path = req.url ?? "/";
25
+ if (/^https?:\/\//i.test(path)) return path;
26
+ const host = req.headers.host ?? (hostname.includes(":") ? `[${hostname}]:${port}` : `${hostname}:${port}`);
27
+ return `http://${host}${path}`;
28
+ }
29
+
30
+ function requestHeaders(req: IncomingMessage): Headers {
31
+ const headers = new Headers();
32
+ const raw = req.rawHeaders;
33
+ for (let i = 0; i + 1 < raw.length; i += 2) {
34
+ const name = raw[i]!.toLowerCase();
35
+ if (!hopByHop.has(name)) headers.append(name, raw[i + 1]!);
36
+ }
37
+ return headers;
38
+ }
39
+
40
+ function sendJson(res: ServerResponse, status: number, message: string): void {
41
+ if (res.headersSent || res.destroyed) {
42
+ res.destroy();
43
+ return;
44
+ }
45
+ const body = JSON.stringify({ error: message });
46
+ res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) });
47
+ res.end(body);
48
+ }
49
+
50
+ // The response must reach the client before the unread request body is
51
+ // discarded, so destroy only after the 413 has been flushed to the socket.
52
+ function rejectTooLarge(req: IncomingMessage, res: ServerResponse): void {
53
+ res.setHeader("Connection", "close");
54
+ res.once("finish", () => req.destroy());
55
+ sendJson(res, 413, "request body too large");
56
+ }
57
+
58
+ async function discardBody(response: Response): Promise<void> {
59
+ try { await response.body?.cancel(); } catch { /* A locked or already-consumed body needs no cleanup. */ }
60
+ }
61
+
62
+ async function writeResponse(res: ServerResponse, response: Response, method: string): Promise<void> {
63
+ const headers: Record<string, string | string[]> = {};
64
+ response.headers.forEach((value, name) => {
65
+ if (name !== "set-cookie") headers[name] = value;
66
+ });
67
+ const cookies = response.headers.getSetCookie?.() ?? [];
68
+ if (cookies.length) headers["set-cookie"] = cookies;
69
+ res.writeHead(response.status, headers);
70
+ if (method === "HEAD" || response.status === 204 || response.status === 304 || !response.body) {
71
+ await discardBody(response);
72
+ res.end();
73
+ return;
74
+ }
75
+ // pipeline destroys the web stream (and so cancels the source) when the
76
+ // client disconnects, which is the abort propagation we need here.
77
+ await pipeline(Readable.fromWeb(response.body as unknown as import("node:stream/web").ReadableStream), res);
78
+ }
79
+
80
+ async function serve(
81
+ req: IncomingMessage,
82
+ res: ServerResponse,
83
+ hostname: string,
84
+ port: number,
85
+ handler: ServerOptions["fetch"],
86
+ maxBody: number,
87
+ ): Promise<void> {
88
+ const abort = new AbortController();
89
+ const onAborted = () => abort.abort();
90
+ req.once("aborted", onAborted);
91
+ req.once("error", onAborted);
92
+ const method = req.method ?? "GET";
93
+ let tooLarge = false;
94
+ let body: ReadableStream<Uint8Array> | undefined;
95
+ try {
96
+ const declared = Number(req.headers["content-length"]);
97
+ if (Number.isFinite(declared) && declared > maxBody) {
98
+ rejectTooLarge(req, res);
99
+ return;
100
+ }
101
+ if (method !== "GET" && method !== "HEAD") {
102
+ let received = 0;
103
+ body = (Readable.toWeb(req) as unknown as ReadableStream<Uint8Array>).pipeThrough(new TransformStream<Uint8Array, Uint8Array>({
104
+ transform(chunk, controller) {
105
+ received += chunk.byteLength;
106
+ if (received > maxBody) {
107
+ tooLarge = true;
108
+ controller.error(new Error("request body too large"));
109
+ return;
110
+ }
111
+ controller.enqueue(chunk);
112
+ },
113
+ }));
114
+ }
115
+ const request = new Request(requestURL(req, hostname, port), {
116
+ method,
117
+ headers: requestHeaders(req),
118
+ body,
119
+ signal: abort.signal,
120
+ ...(body ? { duplex: "half" } : {}),
121
+ } as RequestInit);
122
+ const response = await handler(request);
123
+ if (tooLarge) {
124
+ await discardBody(response);
125
+ rejectTooLarge(req, res);
126
+ return;
127
+ }
128
+ await writeResponse(res, response, method);
129
+ } catch {
130
+ if (tooLarge) {
131
+ rejectTooLarge(req, res);
132
+ } else if (!abort.signal.aborted && !res.headersSent) {
133
+ sendJson(res, 500, "internal server error");
134
+ } else if (!res.destroyed) {
135
+ res.destroy();
136
+ }
137
+ } finally {
138
+ req.off("aborted", onAborted);
139
+ req.off("error", onAborted);
140
+ // A handler may answer without reading the request (for example a 401);
141
+ // cancel the stream so the remaining body is not buffered in memory.
142
+ if (body) void body.cancel().catch(() => {});
143
+ else if (!req.readableEnded) req.resume();
144
+ }
145
+ }
146
+
147
+ export async function startServer(options: ServerOptions): Promise<StartedServer> {
148
+ const maxBody = options.maxRequestBodySize ?? Infinity;
149
+ const server = createServer((req, res) => {
150
+ void serve(req, res, options.hostname, options.port, options.fetch, maxBody);
151
+ });
152
+ // Bun's idleTimeout is socket inactivity, not a total request deadline: a
153
+ // slow upload must not be cut by either Node timer.
154
+ if (options.idleTimeout && options.idleTimeout > 0) server.timeout = options.idleTimeout * 1000;
155
+ server.requestTimeout = 0;
156
+ await new Promise<void>((resolve, reject) => {
157
+ const onError = (error: Error) => reject(error);
158
+ server.once("error", onError);
159
+ server.listen(options.port, options.hostname, () => {
160
+ server.off("error", onError);
161
+ resolve();
162
+ });
163
+ });
164
+ const address = server.address();
165
+ const port = typeof address === "object" && address ? address.port : options.port;
166
+ let closing: Promise<void> | undefined;
167
+ return {
168
+ port,
169
+ close() {
170
+ closing ??= new Promise<void>((resolve) => {
171
+ if (!server.listening) {
172
+ resolve();
173
+ return;
174
+ }
175
+ server.close(() => resolve());
176
+ server.closeIdleConnections();
177
+ server.closeAllConnections();
178
+ });
179
+ return closing;
180
+ },
181
+ };
182
+ }
@@ -1,9 +1,9 @@
1
1
  import { databasePath, listJoinRequests, readJoinRequest, readState } from "../src/state/store.ts";
2
2
  import { findJoinRequest, removeJoinRequest, writeSqliteStateWithDatabase } from "../src/state/sqlite-state.ts";
3
- import { binding, tx, validCurrent } from "./admin-state";
4
- import { hasAdminCapability } from "./admin-auth";
5
- import { isRoomAdmin } from "./room-owner";
6
- import { joinRoomMember } from "./room-join";
3
+ import { binding, tx, validCurrent } from "./admin-state.ts";
4
+ import { hasAdminCapability } from "./admin-auth.ts";
5
+ import { isRoomAdmin } from "./room-owner.ts";
6
+ import { joinRoomMember } from "./room-join.ts";
7
7
 
8
8
  const json = (body: unknown, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
9
9
 
@@ -6,7 +6,7 @@
6
6
  "scope": "/",
7
7
  "display": "standalone",
8
8
  "background_color": "#f3f1ea",
9
- "theme_color": "#22695c",
9
+ "theme_color": "#f3f1ea",
10
10
  "icons": [
11
11
  { "src": "/assets/icons/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
12
12
  { "src": "/assets/icons/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
@@ -2,9 +2,9 @@ import { memberActivity, type WorkState } from "../src/state/member-state.ts";
2
2
  import { acknowledgeRead, acknowledgeReadWithReceipts, readReceipts, readState, recordMessageReceipts, reportPresence, type ReceiptEvidence, type ReceiptIdentity } from "../src/state/store.ts";
3
3
  import { isReceiverOwnerID } from "../src/state/receiver-owner.ts";
4
4
  import { clearPendingAdmission } from "../src/center/queue.ts";
5
- import { touchActive } from "./wake";
6
- import { announcementRoutes } from "./announcement-routes";
7
- import { jsonObject } from "./json-body";
5
+ import { touchActive } from "./wake.ts";
6
+ import { announcementRoutes } from "./announcement-routes.ts";
7
+ import { jsonObject } from "./json-body.ts";
8
8
 
9
9
  const json = (body: unknown, status = 200) => Response.json(body, { status });
10
10
  const states = new Set<WorkState>(["working", "idle", "waiting", "unknown"]);
@@ -1,5 +1,5 @@
1
1
  import { recallMessage, revealMessageContent } from "../src/state/store.ts";
2
- import { jsonObject } from "./json-body";
2
+ import { jsonObject } from "./json-body.ts";
3
3
 
4
4
  const json = (body: unknown, status = 200) => Response.json(body, { status });
5
5
  const MAX_SESSION = 128;
@@ -1,12 +1,12 @@
1
1
  import RoomService, { RoomError, type Room } from "../src/rooms/room-service.ts";
2
2
  import { databasePath, writeState } from "../src/state/store.ts";
3
3
  import { writeSqliteStateWithDatabase } from "../src/state/sqlite-state.ts";
4
- import { binding, enroll, exec, tx, validCurrent } from "./admin-state";
5
- import { hasAdminCapability } from "./admin-auth";
6
- import { roomPayload } from "./room-payload";
4
+ import { binding, enroll, exec, tx, validCurrent } from "./admin-state.ts";
5
+ import { hasAdminCapability } from "./admin-auth.ts";
6
+ import { roomPayload } from "./room-payload.ts";
7
7
  import { clearPendingAdmission } from "../src/center/queue.ts";
8
8
  import { removeRoomResources } from "../src/rooms/resources.ts";
9
- import { isOwnerEntry, isRoomAdmin, isUser } from "./room-owner";
9
+ import { isOwnerEntry, isRoomAdmin, isUser } from "./room-owner.ts";
10
10
 
11
11
  const json = (body: unknown, status = 200) => Response.json(body, { status });
12
12
  const mutate = <T>(fn: (service: RoomService, registry: import("../src/state/store.ts").Registry) => T) => writeState(fn);
@@ -1,7 +1,9 @@
1
+ import { createReadStream } from "node:fs";
1
2
  import { stat } from "node:fs/promises";
2
- import { deleteResource, findResource, maxResourceBytes, resourcePath, uploadResource, type Resource } from "../src/rooms/resources.ts";
3
+ import { Readable } from "node:stream";
4
+ import { deleteResource, findResource, listRoomResources, maxResourceBytes, resourcePath, uploadResource, type Resource } from "../src/rooms/resources.ts";
3
5
  import { readState } from "../src/state/store.ts";
4
- import { isRoomAdmin, isUser } from "./room-owner";
6
+ import { isRoomAdmin, isUser } from "./room-owner.ts";
5
7
 
6
8
  const json = (body: unknown, status = 200) => Response.json(body, { status });
7
9
  const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -18,9 +20,22 @@ export async function resourceRoutes(req: Request, url: URL): Promise<Response |
18
20
  }
19
21
  const upload = url.pathname.match(/^\/rooms\/([^/]+)\/resources$/);
20
22
  const item = url.pathname.match(/^\/rooms\/([^/]+)\/resources\/([^/]+)(\/content)?$/);
21
- if ((!upload || req.method !== "POST") && (!item || (req.method !== "GET" && !(req.method === "DELETE" && !item[3])))) return undefined;
23
+ if (!upload && !item) return undefined;
24
+ if (upload && req.method !== "POST" && req.method !== "GET") return undefined;
25
+ if (item && req.method !== "GET" && !(req.method === "DELETE" && !item[3])) return undefined;
22
26
  try {
23
27
  const roomID = decodeURIComponent((upload ?? item)![1]!);
28
+ if (upload && req.method === "GET") {
29
+ const sessionID = req.headers.get("x-session-id") ?? "";
30
+ const entry = await readState((_svc, registry) => registry[roomID]?.[sessionID]);
31
+ if (!entry) return json({ error: "forbidden" }, 403);
32
+ const rawLimit = Number(url.searchParams.get("limit") ?? 500);
33
+ const rawOffset = Number(url.searchParams.get("offset") ?? 0);
34
+ const limit = Number.isSafeInteger(rawLimit) ? Math.min(1000, Math.max(1, rawLimit)) : 500;
35
+ const offset = Number.isSafeInteger(rawOffset) ? Math.max(0, rawOffset) : 0;
36
+ const page = await listRoomResources(roomID, limit, offset);
37
+ return json({ resources: page.items, total: page.total, limit, offset }, 200);
38
+ }
24
39
  if (upload) {
25
40
  const sessionID = req.headers.get("x-session-id") ?? "";
26
41
  const entry = await readState((_svc, registry) => registry[roomID]?.[sessionID]);
@@ -78,5 +93,5 @@ async function content(req: Request, resource: Resource): Promise<Response> {
78
93
  const inline = /^(image\/(png|jpeg|gif|webp)|audio\/(mpeg|ogg|wav)|video\/(mp4|webm))$/.test(resource.mimeType);
79
94
  const headers = new Headers({ ...safeHeaders, "Content-Type": resource.mimeType, "Content-Disposition": contentDisposition(resource.name, inline), "Content-Length": String(end - start + 1) });
80
95
  if (status === 206) headers.set("Content-Range", `bytes ${start}-${end}/${info.size}`);
81
- return new Response(Bun.file(path).slice(start, end + 1).stream(), { status, headers });
96
+ return new Response(Readable.toWeb(createReadStream(path, { start, end })) as unknown as ReadableStream, { status, headers });
82
97
  }
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import RoomService, { type Room } from "../src/rooms/room-service.ts";
3
3
  import type { Registry, RegistryEntry } from "../src/state/store.ts";
4
- import { bindOwner, isUser } from "./room-owner";
4
+ import { bindOwner, isUser } from "./room-owner.ts";
5
5
 
6
6
  export type JoinMember = {
7
7
  sessionID: string;
@@ -1,6 +1,6 @@
1
1
  import { countOpenQuestions, readHistory } from "../src/state/store.ts";
2
2
  import type { Room } from "../src/rooms/room-service.ts";
3
- import { binding, tx } from "./admin-state";
3
+ import { binding, tx } from "./admin-state.ts";
4
4
 
5
5
  // Initial page of history sent when a room is opened; older pages load on scroll.
6
6
  export const ROOM_WINDOW = 100;
package/server/sw.js CHANGED
@@ -4,6 +4,8 @@ const CACHE = `oc-chat-${VERSION}`;
4
4
  const SHELL = "/chat";
5
5
  const STATIC = [
6
6
  "/assets/base.css",
7
+ "/assets/icons.css",
8
+ "/assets/fluent-icons.svg",
7
9
  "/assets/settings.css",
8
10
  "/assets/conversation.css",
9
11
  "/assets/recall.css",
@@ -11,6 +13,9 @@ const STATIC = [
11
13
  "/assets/responsive.css",
12
14
  "/assets/code-highlight.css",
13
15
  "/assets/room-create.css",
16
+ "/assets/edit-room.css",
17
+ "/assets/palette.css",
18
+ "/assets/files.css",
14
19
  "/assets/highlight-10.7.3.min.js",
15
20
  "/assets/icons/icon-192.png",
16
21
  "/assets/icons/icon-512.png",
@@ -36,10 +41,16 @@ self.addEventListener("install", (event) => {
36
41
  pending.push(new URL(match[1], `https://chat.invalid${url}`).pathname);
37
42
  }
38
43
  }
39
- await self.skipWaiting();
44
+ // A first install should control immediately. A replacement waits until the page
45
+ // asks for it, so an open conversation is never reloaded without consent.
46
+ if (!self.registration.active) await self.skipWaiting();
40
47
  })());
41
48
  });
42
49
 
50
+ self.addEventListener("message", (event) => {
51
+ if (event.data?.type === "SKIP_WAITING") event.waitUntil(self.skipWaiting());
52
+ });
53
+
43
54
  self.addEventListener("activate", (event) => {
44
55
  event.waitUntil((async () => {
45
56
  for (const key of await caches.keys()) if (key !== CACHE) await caches.delete(key);
package/server/wake.ts CHANGED
@@ -4,7 +4,7 @@ import { formatNotificationLines, formatServeWakePrompt, readQuestionExcerpt, re
4
4
  import { clearPendingAdmission, getOrCreatePendingAdmission, markPendingAdmissionAdmitted, pendingAdmission, prunePendingAdmission, rejectPendingAdmission, type QueueItem } from "../src/center/queue.ts";
5
5
  import { sendAsyncNotification } from "../src/center/queue-transport.ts";
6
6
  import { notificationPrefix } from "../src/center/notification-budget.ts";
7
- import { readInbox, type InboxItem } from "./inbox";
7
+ import { readInbox, type InboxItem } from "./inbox.ts";
8
8
  import { explicitlyAddresses } from "../src/center/mentions.ts";
9
9
 
10
10
  const wakeClaims = new Map<string, number>();
package/src/README.md CHANGED
@@ -5,12 +5,14 @@ takes through the plugin.
5
5
 
6
6
  | Folder | What lives there | Read it when |
7
7
  | --- | --- | --- |
8
- | `state/` | Persistence and the data model: `store.ts` (the room store), `sqlite-state.ts` (SQLite tables, join requests and pages), `member-state.ts`, `receiver-state.ts`, `receiver-owner.ts` | A value must survive a restart, or a query must be paged |
8
+ | `state/` | Persistence and the data model: `store.ts` (the room store), `sqlite-state.ts` (SQLite tables, join requests and pages), `sqlite.ts` (the `node:sqlite` adapter), `member-state.ts`, `receiver-state.ts`, `receiver-owner.ts` | A value must survive a restart, or a query must be paged |
9
9
  | `rooms/` | The room domain: `room-service.ts` (rooms, messages, participants, join policy), `announcements.ts`, `resources.ts` (+ upload/read helpers) | You need to change what a room is or what it holds |
10
10
  | `center/` | Talking to a remote center: `center-client.ts`, `center-inbox.ts`, `center-wake.ts`, the delivery `queue*`, `session-delivery.ts`, `reminder-client.ts`, `mentions.ts` | A message must leave this process, or a reply must come back |
11
11
  | `agent/` | The agent-facing side: presence and receipts, the admin client and credentials, the room skill text, and the announcement tool | You are changing what an agent can do or what it is told |
12
+ | `config/` | The shared `chatroom.json` / JSONC / YAML loader and environment precedence used by the server and every client | You are adding a configuration field or changing its precedence |
12
13
  | `runtime/` | Entry points and the running loop: `v1-plugin.ts`, `v2-plugin.ts`, `v2-receiver.ts`, `watch.ts`, `background.ts`, `plugin-notifications.ts` | You are changing startup, the poll loop, or host hooks |
13
- | `tests/` | Every `*.test.ts` under `src/`. Run one with `bun test src/tests/<name>.test.ts` | You changed behaviour and need the proof |
14
+ | `tui/` | The OpenTUI terminal client: `app.mjs` (headless state), `ui*.mjs` (renderables), `config.mjs`, `http.mjs`, `session.mjs`, `palette*.mjs` | You are changing the `opencode-chat-room cli` experience |
15
+ | `tests/` | Every `*.test.ts` under `src/`. Run one with `bun test src/tests/<name>.test.ts`; TUI tests run with `bun test src/tui/test` | You changed behaviour and need the proof |
14
16
 
15
17
  The entry points that the host and the CLI load stay at the repository root:
16
18
  `plugin.ts`, `cli.ts`, `index.ts`, with the HTTP server in `server/`. Join
@@ -0,0 +1,294 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { parse as parseYaml } from "yaml";
5
+
6
+ // A shared, human-editable configuration file. Environment variables still
7
+ // win over the file so a deployment can override one value without editing it.
8
+ export type RoomFileConfig = {
9
+ url?: string;
10
+ token?: string;
11
+ server?: {
12
+ host?: string;
13
+ port?: number;
14
+ token?: string;
15
+ stateDir?: string;
16
+ wakeServeUrl?: string;
17
+ maxFileSizeMb?: number;
18
+ };
19
+ client?: {
20
+ url?: string;
21
+ token?: string;
22
+ participant?: string;
23
+ wakeServeUrl?: string;
24
+ delivery?: boolean;
25
+ deliveryIntervalMs?: number;
26
+ requestTimeoutMs?: number;
27
+ codexBin?: string;
28
+ };
29
+ p2p?: {
30
+ enabled?: boolean;
31
+ peers?: Record<string, { url: string; token?: string }>;
32
+ };
33
+ };
34
+
35
+ export type ServerSettings = {
36
+ host: string;
37
+ port: string;
38
+ token?: string;
39
+ stateDir?: string;
40
+ wakeServeUrl: string;
41
+ maxFileSizeMb?: number;
42
+ };
43
+
44
+ export type ClientSettings = {
45
+ url: string;
46
+ token: string;
47
+ wakeServeUrl: string;
48
+ };
49
+
50
+ const FILE_NAMES = ["chatroom.json", "chatroom.jsonc", "chatroom.yaml", "chatroom.yml"] as const;
51
+ const PEER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
52
+
53
+ function asRecord(value: unknown, where: string): Record<string, unknown> | undefined {
54
+ if (value === undefined) return undefined;
55
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
56
+ throw new Error(`chatroom config: ${where} must be an object`);
57
+ }
58
+ return value as Record<string, unknown>;
59
+ }
60
+
61
+ function optionalString(value: unknown, where: string): string | undefined {
62
+ if (value === undefined) return undefined;
63
+ if (typeof value !== "string") throw new Error(`chatroom config: ${where} must be a string`);
64
+ return value;
65
+ }
66
+
67
+ function optionalNumber(value: unknown, where: string): number | undefined {
68
+ if (value === undefined) return undefined;
69
+ if (typeof value !== "number" || !Number.isFinite(value)) {
70
+ throw new Error(`chatroom config: ${where} must be a finite number`);
71
+ }
72
+ return value;
73
+ }
74
+
75
+ function optionalBoolean(value: unknown, where: string): boolean | undefined {
76
+ if (value === undefined) return undefined;
77
+ if (typeof value !== "boolean") throw new Error(`chatroom config: ${where} must be true or false`);
78
+ return value;
79
+ }
80
+
81
+ function parseServer(value: unknown): RoomFileConfig["server"] {
82
+ const raw = asRecord(value, "server");
83
+ if (!raw) return undefined;
84
+ const port = optionalNumber(raw.port, "server.port");
85
+ if (port !== undefined && (!Number.isInteger(port) || port < 1 || port > 65535)) {
86
+ throw new Error("chatroom config: server.port must be an integer from 1 to 65535");
87
+ }
88
+ const maxFileSizeMb = optionalNumber(raw.maxFileSizeMb, "server.maxFileSizeMb");
89
+ if (maxFileSizeMb !== undefined && maxFileSizeMb <= 0) {
90
+ throw new Error("chatroom config: server.maxFileSizeMb must be greater than zero");
91
+ }
92
+ return {
93
+ host: optionalString(raw.host, "server.host"),
94
+ port,
95
+ token: optionalString(raw.token, "server.token"),
96
+ stateDir: optionalString(raw.stateDir, "server.stateDir"),
97
+ wakeServeUrl: optionalString(raw.wakeServeUrl, "server.wakeServeUrl"),
98
+ maxFileSizeMb,
99
+ };
100
+ }
101
+
102
+ function parseClient(value: unknown): RoomFileConfig["client"] {
103
+ const raw = asRecord(value, "client");
104
+ if (!raw) return undefined;
105
+ const deliveryIntervalMs = optionalNumber(raw.deliveryIntervalMs, "client.deliveryIntervalMs");
106
+ if (deliveryIntervalMs !== undefined && deliveryIntervalMs < 1000) {
107
+ throw new Error("chatroom config: client.deliveryIntervalMs must be at least 1000");
108
+ }
109
+ const requestTimeoutMs = optionalNumber(raw.requestTimeoutMs, "client.requestTimeoutMs");
110
+ if (requestTimeoutMs !== undefined && requestTimeoutMs < 1000) {
111
+ throw new Error("chatroom config: client.requestTimeoutMs must be at least 1000");
112
+ }
113
+ return {
114
+ url: optionalString(raw.url, "client.url"),
115
+ token: optionalString(raw.token, "client.token"),
116
+ participant: optionalString(raw.participant, "client.participant"),
117
+ wakeServeUrl: optionalString(raw.wakeServeUrl, "client.wakeServeUrl"),
118
+ delivery: optionalBoolean(raw.delivery, "client.delivery"),
119
+ deliveryIntervalMs,
120
+ requestTimeoutMs,
121
+ codexBin: optionalString(raw.codexBin, "client.codexBin"),
122
+ };
123
+ }
124
+
125
+ function parsePeers(value: unknown): RoomFileConfig["p2p"] {
126
+ const raw = asRecord(value, "p2p");
127
+ if (!raw) return undefined;
128
+ const enabled = optionalBoolean(raw.enabled, "p2p.enabled");
129
+ const peersRaw = asRecord(raw.peers, "p2p.peers");
130
+ const peers: Record<string, { url: string; token?: string }> = {};
131
+ for (const [name, entry] of Object.entries(peersRaw ?? {})) {
132
+ if (!PEER_NAME.test(name)) {
133
+ throw new Error(`chatroom config: p2p.peers.${name} is not a valid peer name`);
134
+ }
135
+ const peer = asRecord(entry, `p2p.peers.${name}`);
136
+ const url = optionalString(peer?.url, `p2p.peers.${name}.url`);
137
+ if (!url || !/^https?:\/\/[^/]+/.test(url)) {
138
+ throw new Error(`chatroom config: p2p.peers.${name}.url must be an http(s) origin`);
139
+ }
140
+ peers[name] = { url: url.replace(/\/+$/, ""), token: optionalString(peer?.token, `p2p.peers.${name}.token`) };
141
+ }
142
+ return { enabled, peers };
143
+ }
144
+
145
+ function parseRoomConfig(value: unknown): RoomFileConfig {
146
+ const raw = asRecord(value, "root");
147
+ if (!raw) return {};
148
+ return {
149
+ url: optionalString(raw.url, "url"),
150
+ token: optionalString(raw.token, "token"),
151
+ server: parseServer(raw.server),
152
+ client: parseClient(raw.client),
153
+ p2p: parsePeers(raw.p2p),
154
+ };
155
+ }
156
+
157
+ /** Remove comments and trailing commas without touching quoted strings. */
158
+ function stripJsonc(source: string): string {
159
+ let out = "";
160
+ let quote = "";
161
+ let escaped = false;
162
+ let comma = -1;
163
+ for (let i = 0; i < source.length; i++) {
164
+ const char = source[i]!;
165
+ const next = source[i + 1];
166
+ if (quote) {
167
+ out += char;
168
+ if (escaped) escaped = false;
169
+ else if (char === "\\") escaped = true;
170
+ else if (char === quote) quote = "";
171
+ continue;
172
+ }
173
+ if (char === '"') {
174
+ quote = char;
175
+ comma = -1;
176
+ out += char;
177
+ continue;
178
+ }
179
+ if (char === "/" && next === "/") {
180
+ while (i < source.length && source[i] !== "\n") i++;
181
+ out += "\n";
182
+ continue;
183
+ }
184
+ if (char === "/" && next === "*") {
185
+ i += 2;
186
+ while (i < source.length && !(source[i] === "*" && source[i + 1] === "/")) i++;
187
+ i++;
188
+ continue;
189
+ }
190
+ if (char === ",") {
191
+ comma = out.length;
192
+ out += char;
193
+ continue;
194
+ }
195
+ if (char === "}" || char === "]") {
196
+ if (comma >= 0) {
197
+ out = out.slice(0, comma) + out.slice(comma + 1);
198
+ comma = -1;
199
+ }
200
+ out += char;
201
+ continue;
202
+ }
203
+ if (!/\s/.test(char)) comma = -1;
204
+ out += char;
205
+ }
206
+ return out;
207
+ }
208
+
209
+ function parseFile(file: string): RoomFileConfig {
210
+ let text: string;
211
+ try {
212
+ text = readFileSync(file, "utf8");
213
+ } catch {
214
+ throw new Error(`chatroom config: cannot read ${file}`);
215
+ }
216
+ const extension = path.extname(file).toLowerCase();
217
+ try {
218
+ if (extension === ".yaml" || extension === ".yml") return parseRoomConfig(parseYaml(text));
219
+ if (extension === ".jsonc") return parseRoomConfig(JSON.parse(stripJsonc(text)));
220
+ if (extension === ".json") return parseRoomConfig(JSON.parse(text));
221
+ try {
222
+ return parseRoomConfig(JSON.parse(text));
223
+ } catch {
224
+ return parseRoomConfig(parseYaml(text));
225
+ }
226
+ } catch (error) {
227
+ if (error instanceof SyntaxError || (error as Error)?.name === "YAMLParseError") {
228
+ // Never include parser source text: a malformed file may contain a token.
229
+ throw new Error(`chatroom config: ${file} is not valid JSON/YAML`);
230
+ }
231
+ throw error;
232
+ }
233
+ }
234
+
235
+ function candidateDirs(env: NodeJS.ProcessEnv, cwd: string): string[] {
236
+ const home = env.HOME || os.homedir();
237
+ const configHome = env.XDG_CONFIG_HOME || path.join(home, ".config");
238
+ return [...new Set([cwd, path.join(configHome, "chatroom")])];
239
+ }
240
+
241
+ /** Resolve the config path; explicit CHAT_ROOM_CONFIG must exist. */
242
+ export function findRoomConfigFile(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): string | null {
243
+ const explicit = env.CHAT_ROOM_CONFIG?.trim();
244
+ if (explicit) {
245
+ const file = explicit.startsWith("~/") ? path.join(env.HOME || os.homedir(), explicit.slice(2)) : path.resolve(cwd, explicit);
246
+ if (!existsSync(file)) throw new Error(`chatroom config: CHAT_ROOM_CONFIG file does not exist: ${file}`);
247
+ return file;
248
+ }
249
+ for (const dir of candidateDirs(env, cwd)) {
250
+ for (const name of FILE_NAMES) {
251
+ const file = path.join(dir, name);
252
+ if (existsSync(file)) return file;
253
+ }
254
+ }
255
+ return null;
256
+ }
257
+
258
+ /** Read the first found chatroom.json(c)/yaml/yml, or null when absent. */
259
+ export function loadRoomConfig(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): RoomFileConfig | null {
260
+ const file = findRoomConfigFile(env, cwd);
261
+ return file ? parseFile(file) : null;
262
+ }
263
+
264
+ function envValue(env: NodeJS.ProcessEnv, key: string): string | undefined {
265
+ const value = env[key];
266
+ return value === undefined || value === "" ? undefined : value;
267
+ }
268
+
269
+ /** Environment overrides the file; server.token/client.token are not logged. */
270
+ export function resolveServerSettings(file: RoomFileConfig | null, env: NodeJS.ProcessEnv = process.env): ServerSettings {
271
+ const port = envValue(env, "CHAT_ROOM_SERVER_PORT") ?? envValue(env, "PORT") ?? String(file?.server?.port ?? 4399);
272
+ const maxRaw = envValue(env, "CHAT_ROOM_MAX_FILE_SIZE_MB");
273
+ const maxFileSizeMb = maxRaw === undefined ? file?.server?.maxFileSizeMb : Number(maxRaw);
274
+ if (maxFileSizeMb !== undefined && (!Number.isFinite(maxFileSizeMb) || maxFileSizeMb <= 0)) {
275
+ throw new Error("CHAT_ROOM_MAX_FILE_SIZE_MB must be a positive finite number");
276
+ }
277
+ return {
278
+ host: envValue(env, "CHAT_ROOM_SERVER_HOST") ?? envValue(env, "HOST") ?? file?.server?.host ?? "0.0.0.0",
279
+ port,
280
+ token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.server?.token ?? file?.token,
281
+ stateDir: envValue(env, "CHAT_ROOM_STATE_DIR") ?? file?.server?.stateDir,
282
+ wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.server?.wakeServeUrl ?? "",
283
+ maxFileSizeMb,
284
+ };
285
+ }
286
+
287
+ /** Environment overrides the file; client.url/token fall back to top-level. */
288
+ export function resolveClientSettings(file: RoomFileConfig | null, env: NodeJS.ProcessEnv = process.env): ClientSettings {
289
+ return {
290
+ url: envValue(env, "CHAT_ROOM_SERVER_URL") ?? file?.client?.url ?? file?.url ?? "",
291
+ token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.client?.token ?? file?.token ?? "",
292
+ wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.client?.wakeServeUrl ?? file?.server?.wakeServeUrl ?? "",
293
+ };
294
+ }