@alexsun-top/opencode-chat-room 0.8.0 → 0.8.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.
Files changed (161) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +2 -2
  3. package/README.md +38 -6
  4. package/README.zh-CN.md +38 -6
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +5074 -3212
  7. package/package.json +23 -3
  8. package/packages/chat-room-channeld/README.md +98 -25
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
  10. package/packages/chat-room-channeld/src/adapter.ts +36 -2
  11. package/packages/chat-room-channeld/src/config.ts +63 -1
  12. package/packages/chat-room-channeld/src/delivery.ts +6 -1
  13. package/packages/chat-room-channeld/src/feishu-adapter.ts +122 -292
  14. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  15. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  16. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  17. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  18. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  19. package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
  20. package/packages/chat-room-channeld/src/host.ts +120 -2
  21. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  22. package/packages/chat-room-channeld/src/state.ts +17 -0
  23. package/packages/chat-room-channeld/src/stats.ts +43 -1
  24. package/server/admin-state.ts +13 -13
  25. package/server/app.ts +95 -0
  26. package/server/assets/NOTICE.txt +2 -1
  27. package/server/assets/base.css +15 -9
  28. package/server/assets/chat/announcements.js +70 -7
  29. package/server/assets/chat/doc-preview.js +184 -35
  30. package/server/assets/chat/events.js +3 -0
  31. package/server/assets/chat/files.js +46 -4
  32. package/server/assets/chat/index.js +2 -0
  33. package/server/assets/chat/integration-editor.js +163 -0
  34. package/server/assets/chat/integration-values.js +124 -0
  35. package/server/assets/chat/integrations.js +498 -0
  36. package/server/assets/chat/locales/de.js +40 -4
  37. package/server/assets/chat/locales/es.js +40 -4
  38. package/server/assets/chat/locales/fr.js +40 -4
  39. package/server/assets/chat/locales/it.js +40 -4
  40. package/server/assets/chat/locales/ja.js +40 -4
  41. package/server/assets/chat/locales/ko.js +40 -4
  42. package/server/assets/chat/markdown.js +22 -8
  43. package/server/assets/chat/messages.js +5 -5
  44. package/server/assets/chat/office-preview.js +69 -0
  45. package/server/assets/chat/panels.js +36 -0
  46. package/server/assets/chat/recall.js +58 -7
  47. package/server/assets/chat/receipts.js +15 -3
  48. package/server/assets/chat/reminders.js +69 -8
  49. package/server/assets/chat/resource-format.js +11 -0
  50. package/server/assets/chat/settings.js +30 -2
  51. package/server/assets/chat/side-pane.js +1 -2
  52. package/server/assets/chat/state.js +93 -10
  53. package/server/assets/chat/system-events.js +32 -0
  54. package/server/assets/chat/system-messages.js +23 -14
  55. package/server/assets/chat/task-row.js +0 -6
  56. package/server/assets/chat/tasks.js +121 -33
  57. package/server/assets/code-highlight.css +55 -32
  58. package/server/assets/conversation.css +123 -23
  59. package/server/assets/doc-preview.css +35 -3
  60. package/server/assets/files.css +5 -0
  61. package/server/assets/fluent-icons.svg +2 -0
  62. package/server/assets/monaco/LICENSE +21 -0
  63. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  64. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  65. package/server/assets/monaco/editor.worker.js +45 -0
  66. package/server/assets/monaco/integration-rules.css +1 -0
  67. package/server/assets/monaco/integration-rules.js +1297 -0
  68. package/server/assets/monaco/json.worker.js +77 -0
  69. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  70. package/server/assets/office/docx.bundle.js +33 -0
  71. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  72. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  73. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  74. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  75. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  76. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  77. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  78. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  79. package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
  80. package/server/assets/office/pptx.bundle.js +104 -0
  81. package/server/assets/office/xlsx.bundle.js +141 -0
  82. package/server/assets/recall.css +5 -4
  83. package/server/assets/responsive.css +50 -11
  84. package/server/assets/settings.css +73 -1
  85. package/server/assets/tasks.css +57 -7
  86. package/server/channel-integration.ts +519 -0
  87. package/server/channel-settings.ts +77 -0
  88. package/server/channels.ts +261 -18
  89. package/server/chat-server.ts +32 -580
  90. package/server/chat.html +187 -21
  91. package/server/http-server.ts +3 -182
  92. package/server/resource-routes.ts +16 -16
  93. package/server/routes/inbox.ts +100 -0
  94. package/server/routes/pages.ts +83 -0
  95. package/server/routes/questions.ts +39 -0
  96. package/server/routes/room-actions.ts +162 -0
  97. package/server/routes/rooms.ts +160 -0
  98. package/server/startup.ts +84 -0
  99. package/server/sw.js +4 -0
  100. package/server/task-routes.ts +1 -1
  101. package/src/center/center-client.ts +2 -10
  102. package/src/config/file-config.ts +7 -54
  103. package/src/platform/http-server.ts +182 -0
  104. package/src/protocol/addressing.ts +21 -0
  105. package/src/protocol/config.ts +58 -0
  106. package/src/protocol/room.ts +51 -0
  107. package/src/rooms/resources.ts +26 -16
  108. package/src/rooms/room-service.ts +2 -48
  109. package/src/rooms/storage.ts +329 -0
  110. package/src/rooms/tasks.ts +21 -5
  111. package/src/runtime/watch.ts +1 -1
  112. package/src/state/pg-database.ts +183 -0
  113. package/src/state/pg-migrate.ts +175 -0
  114. package/src/state/pg-sql.mjs +175 -0
  115. package/src/state/pg-worker.mjs +148 -0
  116. package/src/state/sqlite-announcements.ts +25 -0
  117. package/src/state/sqlite-database.ts +121 -0
  118. package/src/state/sqlite-legacy.ts +90 -0
  119. package/src/state/sqlite-members.ts +155 -0
  120. package/src/state/sqlite-messages.ts +288 -0
  121. package/src/state/sqlite-resources.ts +39 -0
  122. package/src/state/sqlite-rooms.ts +87 -0
  123. package/src/state/sqlite-schema.ts +80 -0
  124. package/src/state/sqlite-state-store.ts +33 -0
  125. package/src/state/sqlite-state.ts +15 -897
  126. package/src/state/sqlite-tasks.ts +65 -0
  127. package/src/state/sqlite-transaction.ts +13 -0
  128. package/src/state/sqlite.ts +21 -1
  129. package/src/state/store.ts +5 -1
  130. package/src/tui/app.mjs +32 -19
  131. package/src/tui/config.mjs +12 -4
  132. package/src/tui/i18n.mjs +38 -0
  133. package/src/tui/info-app.mjs +50 -51
  134. package/src/tui/info-content.mjs +79 -44
  135. package/src/tui/join-app.mjs +9 -9
  136. package/src/tui/locales/en.mjs +349 -0
  137. package/src/tui/locales/zh-CN.mjs +349 -0
  138. package/src/tui/main.mjs +85 -37
  139. package/src/tui/markdown.mjs +3 -2
  140. package/src/tui/mentions.mjs +3 -1
  141. package/src/tui/message-app.mjs +22 -21
  142. package/src/tui/message-view.mjs +2 -1
  143. package/src/tui/palette-app.mjs +9 -8
  144. package/src/tui/palette.mjs +30 -24
  145. package/src/tui/prefs.mjs +92 -0
  146. package/src/tui/reminder-app.mjs +18 -17
  147. package/src/tui/room-settings-app.mjs +30 -28
  148. package/src/tui/settings-app.mjs +153 -0
  149. package/src/tui/ui-content.mjs +65 -86
  150. package/src/tui/ui-help.mjs +73 -0
  151. package/src/tui/ui-overlay-view.mjs +23 -7
  152. package/src/tui/ui-suggest.mjs +6 -5
  153. package/src/tui/ui-theme.mjs +37 -33
  154. package/src/tui/ui-view.mjs +22 -7
  155. package/src/tui/ui.mjs +15 -3
  156. package/src/web/editor.worker.ts +1 -0
  157. package/src/web/integration-rules-editor.ts +439 -0
  158. package/src/web/integration-rules.ts +22 -0
  159. package/src/web/integration-schema.ts +228 -0
  160. package/src/web/json.worker.ts +1 -0
  161. package/src/web/office-viewer.ts +221 -0
@@ -0,0 +1,100 @@
1
+ // Inbox long-poll, queue acknowledgements and wake arbitration.
2
+ import { acknowledgeQueued } from "../../src/state/store.ts";
3
+ import { clearPendingAdmission } from "../../src/center/queue.ts";
4
+ import { readInbox } from "../inbox.ts";
5
+ import { jsonObject } from "../json-body.ts";
6
+ import { claimWake, touchActive } from "../wake.ts";
7
+
8
+ const json = (body: unknown, status = 200) =>
9
+ new Response(JSON.stringify(body), {
10
+ status,
11
+ headers: { "Content-Type": "application/json" },
12
+ });
13
+
14
+ const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
15
+
16
+ export async function inboxRoutes(req: Request, url: URL): Promise<Response | undefined> {
17
+ const p = url.pathname;
18
+ if (req.method === "GET" && p === "/inbox") {
19
+ const sessionID = url.searchParams.get("sessionID") ?? "";
20
+ const roomFilter = url.searchParams.get("roomId");
21
+ const afterValue = url.searchParams.get("afterTs");
22
+ const afterTs = afterValue === null ? undefined : Number(afterValue);
23
+ const recallVersionValue = url.searchParams.get("recallVersion");
24
+ if (url.searchParams.has("recallVersion") && (recallVersionValue === "" || !/^\d+$/.test(recallVersionValue ?? "") ||
25
+ !Number.isSafeInteger(Number(recallVersionValue)))) {
26
+ return json({ error: "recallVersion must be a non-negative safe integer" }, 400);
27
+ }
28
+ const clientRecallVersion = recallVersionValue === null ? undefined : Number(recallVersionValue);
29
+ if (url.searchParams.has("afterTs") && (afterValue === "" || !/^\d+$/.test(afterValue ?? "") ||
30
+ !Number.isSafeInteger(afterTs) || afterTs! < 0 || !roomFilter || url.searchParams.get("excludeSelf") !== "0")) {
31
+ return json({ error: "afterTs requires a roomId and excludeSelf=0, with a non-negative safe integer value" }, 400);
32
+ }
33
+ // ponytail: poll includes the caller's own messages (echo), the
34
+ // notification self-pull excludes them — aligned with standalone poll
35
+ const excludeSelf = url.searchParams.get("excludeSelf") === "1";
36
+ // long-poll: wait up to `timeout` ms for the first new message
37
+ // instead of returning empty immediately (web chat + sub-agent
38
+ // watchers); empty responses only happen on timeout
39
+ const timeout = Math.min(
40
+ Math.max(Number(url.searchParams.get("timeout") ?? 0) || 0, 0),
41
+ 30000,
42
+ );
43
+ const deadline = Date.now() + timeout;
44
+ let result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
45
+ // The client's rendered snapshot version is the baseline; using the first
46
+ // read instead would hide a recall that landed before this request started.
47
+ const initialRecallVersion = clientRecallVersion ?? result.recallVersion;
48
+ // A recall bumps the version without creating a message; wake the poll so
49
+ // the client can refetch the room snapshot (reliable version compare).
50
+ while (result.items.length === 0 && result.recallVersion === initialRecallVersion && Date.now() < deadline) {
51
+ // ponytail: 500ms between disk scans keeps notification latency under
52
+ // half a second; a longer interval makes deliveries feel stuck.
53
+ await sleep(Math.max(1, Math.min(500, deadline - Date.now())));
54
+ result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
55
+ }
56
+ return json(result);
57
+ }
58
+ if (req.method === "POST" && p === "/queued") {
59
+ const body = await jsonObject<Record<string, unknown>>(req);
60
+ if (!body) return json({ error: "JSON object body is required" }, 400);
61
+ const ts = Number(body.ts);
62
+ const roomId = String(body.roomId ?? "");
63
+ const sessionID = String(body.sessionID ?? "");
64
+ if (
65
+ body.ts === undefined ||
66
+ body.ts === null ||
67
+ !roomId ||
68
+ !sessionID ||
69
+ !Number.isFinite(ts)
70
+ ) {
71
+ return json({ error: "roomId/sessionID/finite ts are required" }, 400);
72
+ }
73
+ // Clamp to the room tail so a forged future ts cannot silence delivery.
74
+ const updated = await acknowledgeQueued(roomId, sessionID, ts);
75
+ if (updated === null) {
76
+ return json({ error: "registry entry not found" }, 404);
77
+ }
78
+ clearPendingAdmission(sessionID, roomId, updated);
79
+ touchActive(sessionID);
80
+ return json({ ok: true });
81
+ }
82
+ if (req.method === "POST" && p === "/active") {
83
+ // Active report: the plugin calls this for sessions it successfully pushed
84
+ // in-process (genuinely active), so the server avoids a duplicate serve wake.
85
+ const body = await jsonObject<Record<string, unknown>>(req);
86
+ if (!body) return json({ error: "JSON object body is required" }, 400);
87
+ touchActive(String(body.sessionID ?? ""));
88
+ return json({ ok: true });
89
+ }
90
+ if (req.method === "POST" && p === "/wake-claim") {
91
+ // ponytail: atomic cross-process wake dedupe (see claimWake) — the
92
+ // server only arbitrates, it never spawns anything itself
93
+ const body = await jsonObject<Record<string, unknown>>(req);
94
+ if (!body) return json({ error: "JSON object body is required" }, 400);
95
+ const sessionID = String(body.sessionID ?? "");
96
+ const ok = claimWake(sessionID);
97
+ return json({ ok });
98
+ }
99
+ return undefined;
100
+ }
@@ -0,0 +1,83 @@
1
+ // Static pages and assets served before the JSON API auth gate.
2
+ import { promises as fs } from "node:fs";
3
+ import path from "node:path";
4
+
5
+ const json = (body: unknown, status = 200) =>
6
+ new Response(JSON.stringify(body), {
7
+ status,
8
+ headers: { "Content-Type": "application/json" },
9
+ });
10
+
11
+ // The chat page shows this next to the app title; a missing package must not
12
+ // leave a placeholder behind.
13
+ let versionTag: Promise<string> | undefined;
14
+ function chatVersionTag(here: string): Promise<string> {
15
+ return (versionTag ??= fs.readFile(path.join(here, "../package.json"), "utf8")
16
+ .then((text) => {
17
+ const pkg = JSON.parse(text) as { version?: unknown };
18
+ return typeof pkg?.version === "string" && pkg.version ? `v${pkg.version}` : "";
19
+ })
20
+ .catch(() => ""));
21
+ }
22
+
23
+ export async function pageRoutes(
24
+ req: Request,
25
+ url: URL,
26
+ here: string,
27
+ channeld: boolean,
28
+ ): Promise<Response | undefined> {
29
+ const p = url.pathname;
30
+ if (req.method === "GET" && p === "/") {
31
+ return Response.redirect(new URL("/chat", url).toString(), 302);
32
+ }
33
+ if (req.method === "GET" && p === "/chat") {
34
+ const html = await fs
35
+ .readFile(path.join(here, "chat.html"), "utf8")
36
+ .catch(() => null);
37
+ if (html === null) {
38
+ return json({ error: "chat page not found" }, 404);
39
+ }
40
+ const version = await chatVersionTag(here);
41
+ return new Response(html.replaceAll("{{version}}", version)
42
+ .replaceAll("{{channeld}}", channeld ? "on" : "off")
43
+ .replaceAll("{{integrationsAdmin}}", process.env.CHATROOM_ALLOW_ADMIN === "true" ? "true" : "false"), {
44
+ headers: {
45
+ "Content-Type": "text/html; charset=utf-8",
46
+ "Cache-Control": "no-store",
47
+ },
48
+ });
49
+ }
50
+ // The install surface lives at the origin root so the worker controls /chat, not /assets.
51
+ if (req.method === "GET" && p === "/manifest.webmanifest") {
52
+ const body = await fs.readFile(path.join(here, "manifest.webmanifest"), "utf8").catch(() => null);
53
+ if (body === null) return json({ error: "manifest not found" }, 404);
54
+ return new Response(body, {
55
+ headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-store" },
56
+ });
57
+ }
58
+ if (req.method === "GET" && p === "/sw.js") {
59
+ const body = await fs.readFile(path.join(here, "sw.js"), "utf8").catch(() => null);
60
+ if (body === null) return json({ error: "service worker not found" }, 404);
61
+ const version = (await chatVersionTag(here)) || "dev";
62
+ return new Response(body.replaceAll("{{version}}", version), {
63
+ headers: {
64
+ "Content-Type": "text/javascript; charset=utf-8",
65
+ "Cache-Control": "no-store",
66
+ "Service-Worker-Allowed": "/",
67
+ },
68
+ });
69
+ }
70
+ if (req.method === "GET" && p.startsWith("/assets/")) {
71
+ let relative: string;
72
+ try { relative = decodeURIComponent(p.slice("/assets/".length)); }
73
+ catch { return json({ error: "invalid asset path" }, 400); }
74
+ const root = path.resolve(here, "assets");
75
+ const file = path.resolve(root, relative);
76
+ if (!relative || !file.startsWith(`${root}${path.sep}`) || !/\.(?:css|js|mjs|svg|png|jpg|ttf|woff2?)$/i.test(file)) return json({ error: "not found" }, 404);
77
+ const data = await fs.readFile(file).catch(() => null);
78
+ if (!data) return json({ error: "not found" }, 404);
79
+ const type = file.endsWith(".css") ? "text/css" : file.endsWith(".svg") ? "image/svg+xml" : /\.(?:js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".png") ? "image/png" : file.endsWith(".jpg") ? "image/jpeg" : file.endsWith(".ttf") ? "font/ttf" : "font/woff2";
80
+ return new Response(data, { headers: { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
81
+ }
82
+ return undefined;
83
+ }
@@ -0,0 +1,39 @@
1
+ // Room question listing and answer submission.
2
+ import { answerQuestion, readQuestions, readState } from "../../src/state/store.ts";
3
+ import { touchActive, wakeMentionedSessions } from "../wake.ts";
4
+
5
+ const json = (body: unknown, status = 200) =>
6
+ new Response(JSON.stringify(body), {
7
+ status,
8
+ headers: { "Content-Type": "application/json" },
9
+ });
10
+
11
+ export async function questionRoutes(req: Request, url: URL, serveWakeUrl: string): Promise<Response | undefined> {
12
+ const questions = url.pathname.match(/^\/rooms\/([^/]+)\/questions$/);
13
+ if (req.method === "GET" && questions) {
14
+ const roomId = decodeURIComponent(questions[1]!);
15
+ const exists = await readState((svc) => svc.listRooms().some((room) => room.id === roomId));
16
+ if (!exists) return json({ error: "room not found" }, 404);
17
+ return json({ questions: await readQuestions(roomId) });
18
+ }
19
+ const answer = url.pathname.match(/^\/rooms\/([^/]+)\/questions\/([^/]+)\/answers$/);
20
+ if (req.method === "POST" && answer) {
21
+ const roomId = decodeURIComponent(answer[1]!);
22
+ const questionID = decodeURIComponent(answer[2]!);
23
+ const body: unknown = await req.json();
24
+ if (!body || typeof body !== "object" || Array.isArray(body)) return json({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
25
+ const input = body as Record<string, unknown>;
26
+ if (typeof input.sessionID !== "string" || !input.sessionID || typeof input.text !== "string" || !input.text.trim() || input.text.trim().length > 5000) return json({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
27
+ const result = await answerQuestion(roomId, questionID, input.sessionID, input.text.trim());
28
+ if (result.status === "missing") return json({ error: "room not found" }, 404);
29
+ if (result.status === "question") return json({ error: "question not found" }, 404);
30
+ if (result.status === "member") return json({ error: "session is not a room member" }, 409);
31
+ if (result.status === "answered") return json({ error: "question already answered" }, 409);
32
+ if (result.status !== "ok") return json({ error: "question not found" }, 404);
33
+ touchActive(input.sessionID);
34
+ const room = await readState((svc) => svc.getRoom(roomId));
35
+ void wakeMentionedSessions(serveWakeUrl, roomId, room.name, result.answer.text, input.sessionID, result.answer);
36
+ return json({ questionID, answer: result.answer }, 201);
37
+ }
38
+ return undefined;
39
+ }
@@ -0,0 +1,162 @@
1
+ // Join, leave and message append routes for a single room.
2
+ import { appendRoomMessage, databasePath, readState, sendReply, writeState } from "../../src/state/store.ts";
3
+ import { saveJoinRequest, writeSqliteStateWithDatabase } from "../../src/state/sqlite-state.ts";
4
+ import { isReceiverOwnerID } from "../../src/state/receiver-owner.ts";
5
+ import { jsonObject } from "../json-body.ts";
6
+ import { isUser, settleAdmins, settleOwner } from "../room-owner.ts";
7
+ import { joinRoomMember } from "../room-join.ts";
8
+ import { roomPayload } from "../room-payload.ts";
9
+ import { touchActive, wakeMentionedSessions } from "../wake.ts";
10
+
11
+ const json = (body: unknown, status = 200) =>
12
+ new Response(JSON.stringify(body), {
13
+ status,
14
+ headers: { "Content-Type": "application/json" },
15
+ });
16
+
17
+ export async function roomActionRoutes(req: Request, url: URL, serveWakeUrl: string): Promise<Response | undefined> {
18
+ const m = url.pathname.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
19
+ if (!m) return undefined;
20
+ const roomId = decodeURIComponent(m[1]!);
21
+ const body = await jsonObject<Record<string, string>>(req);
22
+ if (!body) return json({ error: "JSON object body is required" }, 400);
23
+ const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
24
+ if (req.method === "POST" && m[2] === "join") {
25
+ if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
26
+ return json({ error: "invalid receiver ownership" }, 400);
27
+ }
28
+ // ponytail: F4/F5 — names must be non-empty, and re-joining under a
29
+ // new name must retire the old participant (no ghost members)
30
+ const id = typeof body.participantId === "string" ? body.participantId.trim() : "";
31
+ const name = typeof body.participantName === "string" ? body.participantName.trim() : "";
32
+ if (!id || !name || !sessionID) {
33
+ return json(
34
+ { error: "participantId/participantName/sessionID are required" },
35
+ 400,
36
+ );
37
+ }
38
+ if (id.length > 64 || name.length > 64) {
39
+ return json({ error: "name too long (max 64)" }, 400);
40
+ }
41
+ const result = await writeSqliteStateWithDatabase(databasePath(), (svc, reg, db) => {
42
+ const currentRoom = svc.getRoom(roomId);
43
+ // A restricted room treats a new identity as a pending request; no
44
+ // participant or registry entry exists until a reviewer approves.
45
+ if (currentRoom.joinPolicy === "approval" && currentRoom.kind !== "direct" && !reg[roomId]?.[sessionID]) {
46
+ if (svc.containsParticipant(roomId, id)) return { status: 409 as const, error: "participant name is already in use in this room" };
47
+ const duplicate = db.query("SELECT 1 FROM room_join_requests WHERE room_id=? AND session_id<>? AND (participant_id=? OR name=?)").get(roomId, sessionID, id, name);
48
+ if (duplicate) return { status: 409 as const, error: "participant name is already in use in this room" };
49
+ saveJoinRequest(db, {
50
+ roomID: roomId, sessionID, participantId: id, name,
51
+ isAgent: Boolean(body.protocol || body.receiverOwnerID || body.host),
52
+ createdAt: Date.now(),
53
+ ...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
54
+ ...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
55
+ ...(body.directory ? { directory: body.directory } : {}),
56
+ ...(body.host ? { host: body.host } : {}),
57
+ });
58
+ return { pending: true as const };
59
+ }
60
+ return { room: joinRoomMember(svc, reg, roomId, {
61
+ sessionID, participantId: id, name,
62
+ ...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
63
+ ...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
64
+ ...(body.directory ? { directory: body.directory } : {}),
65
+ host: body.host ?? "",
66
+ }) };
67
+ });
68
+ if ("status" in result) return json({ error: result.error }, result.status);
69
+ if ("pending" in result) return json({
70
+ status: "pending",
71
+ message: "Join request submitted. You are not a member yet; a human administrator must approve it before you can send or poll.",
72
+ }, 202);
73
+ touchActive(sessionID); // join = active
74
+ return json(await roomPayload(result.room), 201);
75
+ }
76
+ if (req.method === "POST" && m[2] === "leave") {
77
+ await writeState((svc, reg) => {
78
+ const room = svc.getRoom(roomId);
79
+ const entry = reg[roomId]?.[sessionID];
80
+ const participantId = room.kind === "direct" ? sessionID : entry?.name ?? sessionID;
81
+ // Shared-name guard: when another session still holds this name, remove
82
+ // only this registry entry, not the participant (otherwise a sibling tab
83
+ // would start getting NOT_JOINED).
84
+ const shared = Object.entries(reg[roomId] ?? {}).some(
85
+ ([sid, e]) => e.name === participantId && sid !== sessionID,
86
+ );
87
+ if (!shared) {
88
+ svc.leaveRoom(roomId, participantId);
89
+ svc.addEvent(roomId, `${participantId} left the room`);
90
+ }
91
+ if (reg[roomId]) {
92
+ delete reg[roomId][sessionID];
93
+ if (Object.keys(reg[roomId]).length === 0) {
94
+ delete reg[roomId];
95
+ }
96
+ }
97
+ // A departing delegated admin passes the role to the room's explicit successor.
98
+ if (entry?.name && room.ownerId && (room.adminIds ?? []).includes(entry.name)) {
99
+ const successor = Object.values(reg[roomId] ?? {}).find((candidate) =>
100
+ isUser(candidate) && (room.successorMembershipID ? candidate.membershipID === room.successorMembershipID : candidate.name === room.successorId));
101
+ if (successor?.name && successor.name !== room.ownerId) {
102
+ room.adminIds = [...new Set([...(room.adminIds ?? []).filter((name) => name !== successor.name), successor.name])];
103
+ if (successor.membershipID) room.adminMembershipIDs = [...new Set([...(room.adminMembershipIDs ?? []).filter((id) => id !== successor.membershipID), successor.membershipID])];
104
+ }
105
+ }
106
+ if (entry && (room.successorMembershipID ? entry.membershipID === room.successorMembershipID : entry.name === room.successorId)) {
107
+ delete room.successorId;
108
+ delete room.successorMembershipID;
109
+ }
110
+ // A departing owner hands the room to the next person; the last one leaves it open.
111
+ settleAdmins(svc.getRoom(roomId), reg[roomId] ?? {});
112
+ settleOwner(svc.getRoom(roomId), reg[roomId] ?? {});
113
+ });
114
+ return json({ ok: true });
115
+ }
116
+ if (req.method === "POST" && m[2] === "messages") {
117
+ const isQuestion = (body as Record<string, unknown>).isQuestion;
118
+ if (isQuestion !== undefined && typeof isQuestion !== "boolean") return json({ error: "isQuestion must be a boolean" }, 400);
119
+ // ponytail: F3 — mirror the plugin's zod limit at the HTTP boundary
120
+ const text = typeof body.text === "string" ? body.text.trim() : "";
121
+ if (!text) {
122
+ return json({ error: "text is required" }, 400);
123
+ }
124
+ if (text.length > 5000) {
125
+ return json({ error: "text too long (max 5000)" }, 400);
126
+ }
127
+ // parentMessageId is the addressing alias of the web client's reply field.
128
+ const replyTo = (body as Record<string, unknown>).replyToMessageID ?? (body as Record<string, unknown>).parentMessageId;
129
+ if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo)) return json({ error: "parentMessageId must be a non-empty message ID" }, 400);
130
+ // Optional retry key: a lost response may be retried without creating a twin.
131
+ const clientMessageID = (body as Record<string, unknown>).clientMessageID;
132
+ if (clientMessageID !== undefined && (typeof clientMessageID !== "string" || !clientMessageID || clientMessageID.length > 100)) {
133
+ return json({ error: "clientMessageID must be a non-empty string (max 100)" }, 400);
134
+ }
135
+ if (replyTo !== undefined) {
136
+ const result = await sendReply(roomId, replyTo, sessionID, text, clientMessageID);
137
+ if (result.status !== "ok") {
138
+ if (result.status === "missing") return json({ error: "room not found" }, 404);
139
+ if (result.status === "target") return json({ error: "reply target not found in room" }, 404);
140
+ if (result.status === "recalled") return json({ error: "reply target was recalled" }, 409);
141
+ if (result.status === "question") return json({ error: "use the question answers endpoint to reply to a question" }, 409);
142
+ // Reply addressing is member-only and uniformly missing otherwise.
143
+ return json({ error: "not found" }, 404);
144
+ }
145
+ touchActive(sessionID);
146
+ const room = await readState((svc) => svc.getRoom(roomId));
147
+ if (!result.duplicate) void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
148
+ return json(await roomPayload(room), 201);
149
+ }
150
+ const result = await appendRoomMessage(roomId, sessionID, text, isQuestion === true, clientMessageID);
151
+ if (result.status !== "ok") {
152
+ if (result.status === "missing") return json({ error: "room not found" }, 404);
153
+ return json({ error: "session is not a room member" }, 409);
154
+ }
155
+ touchActive(sessionID); // sender is active
156
+ const room = await readState((svc) => svc.getRoom(roomId));
157
+ // Immediate wake only when the message explicitly @-mentions members.
158
+ if (!result.duplicate) void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
159
+ return json(await roomPayload(room), 201);
160
+ }
161
+ return undefined;
162
+ }
@@ -0,0 +1,160 @@
1
+ // Room listing, creation, room snapshots and the session registry.
2
+ import { randomUUID } from "node:crypto";
3
+ import { readRoomSummaries, readState, writeState, type RegistryEntry } from "../../src/state/store.ts";
4
+ import { isReceiverOwnerID } from "../../src/state/receiver-owner.ts";
5
+ import { jsonObject } from "../json-body.ts";
6
+ import { roomPayload } from "../room-payload.ts";
7
+
8
+ const json = (body: unknown, status = 200) =>
9
+ new Response(JSON.stringify(body), {
10
+ status,
11
+ headers: { "Content-Type": "application/json" },
12
+ });
13
+
14
+ // Only canonical non-negative decimal integers are accepted; URLSearchParams
15
+ // keeps values as strings, so "1.5", "1e2" and "" must not be coerced.
16
+ const integerParam = (value: string): number | undefined => {
17
+ if (!/^\d+$/.test(value)) return undefined;
18
+ const parsed = Number(value);
19
+ return Number.isSafeInteger(parsed) ? parsed : undefined;
20
+ };
21
+
22
+ export async function roomListRoutes(req: Request, url: URL): Promise<Response | undefined> {
23
+ const p = url.pathname;
24
+ if (req.method === "GET" && p === "/rooms/summary") {
25
+ // Lightweight room summary without messages: wakeSessions polls this every
26
+ // 10s to compute the latest sequence without downloading full histories.
27
+ return json(await readRoomSummaries());
28
+ }
29
+ if (req.method === "GET" && p === "/receiver/memberships") {
30
+ const ownerID = url.searchParams.get("ownerID");
31
+ if (!isReceiverOwnerID(ownerID)) return json({ error: "invalid ownerID" }, 400);
32
+ const sessionIDs = await readState((_svc, registry) => {
33
+ return [...new Set(Object.values(registry).flatMap((entries) =>
34
+ Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id),
35
+ ))];
36
+ });
37
+ return json({ sessionIDs });
38
+ }
39
+ if (req.method === "GET" && p === "/rooms") {
40
+ const caller = url.searchParams.get("sessionID");
41
+ const limitParam = url.searchParams.get("limit");
42
+ const offsetParam = url.searchParams.get("offset");
43
+ // No page size with an offset; reject rather than silently ignoring it.
44
+ if (limitParam === null && offsetParam !== null) return json({ error: "offset requires limit" }, 400);
45
+ let limit: number | undefined;
46
+ let offset = 0;
47
+ if (limitParam !== null) {
48
+ limit = integerParam(limitParam);
49
+ if (limit === undefined || limit < 1 || limit > 200) return json({ error: "limit must be an integer between 1 and 200" }, 400);
50
+ if (offsetParam !== null) {
51
+ offset = integerParam(offsetParam) ?? -1;
52
+ if (offset < 0) return json({ error: "offset must be a non-negative integer" }, 400);
53
+ }
54
+ }
55
+ const rows = await readState((svc, registry) => svc.listRooms()
56
+ .filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller))
57
+ .map((room) => ({ room, entry: caller ? registry[room.id]?.[caller] : undefined })));
58
+ // Without limit keep the legacy bare array and full list; with limit only
59
+ // hydrate the room payloads on the requested page.
60
+ const page = limit === undefined ? rows : rows.slice(offset, offset + limit);
61
+ const rooms = [];
62
+ for (const { room, entry } of page) {
63
+ // The browser keeps its watermark per tab; a new tab starts from this one.
64
+ rooms.push({ ...await roomPayload(room), joined: Boolean(entry), ...(entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {}) });
65
+ }
66
+ if (limit === undefined) return json(rooms);
67
+ const nextOffset = offset + rooms.length < rows.length ? offset + rooms.length : null;
68
+ return json({ rooms, hasMore: nextOffset !== null, nextOffset });
69
+ }
70
+ return undefined;
71
+ }
72
+
73
+ export async function roomCreateRoute(req: Request, url: URL): Promise<Response | undefined> {
74
+ if (!(req.method === "POST" && url.pathname === "/rooms")) return undefined;
75
+ const body = await jsonObject<Record<string, string>>(req);
76
+ if (!body) return json({ error: "JSON object body is required" }, 400);
77
+ if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
78
+ return json({ error: "invalid receiver ownership" }, 400);
79
+ }
80
+ const name = body.name?.trim();
81
+ if (!name) {
82
+ return json({ error: "name is required" }, 400);
83
+ }
84
+ if (name.length > 64) {
85
+ return json({ error: "name too long (max 64)" }, 400);
86
+ }
87
+ const owner = (body.ownerId ?? "").trim() || "访客";
88
+ if (owner.length > 64) {
89
+ return json({ error: "ownerId too long (max 64)" }, 400);
90
+ }
91
+ if (body.joinPolicy !== undefined && body.joinPolicy !== "open" && body.joinPolicy !== "approval") {
92
+ return json({ error: "joinPolicy must be open or approval" }, 400);
93
+ }
94
+ const joinPolicy = body.joinPolicy === "approval" ? "approval" : body.joinPolicy === "open" ? "open" : undefined;
95
+ const room = await writeState((svc, reg) => {
96
+ const created = svc.createRoom(name, owner, joinPolicy);
97
+ if (body.sessionID) {
98
+ const regRoom = (reg[created.id] =
99
+ reg[created.id] ?? Object.create(null) as Record<string, RegistryEntry>);
100
+ regRoom[body.sessionID] = {
101
+ // ponytail: central mode self-pulls the inbox; no cross-host URL
102
+ serverUrl: "",
103
+ apiPrefix: "/api",
104
+ membershipID: randomUUID(),
105
+ ...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
106
+ ...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
107
+ name: owner,
108
+ directory: body.directory || undefined,
109
+ // Owning host: cross-machine @-wake is executed only by the owner.
110
+ host: body.host ?? "",
111
+ lastReadTs: Math.max(
112
+ Date.now(),
113
+ created.messages.at(-1)?.createdAt ?? 0,
114
+ ),
115
+ lastQueuedTs: 0,
116
+ };
117
+ created.ownerMembershipID = regRoom[body.sessionID]!.membershipID;
118
+ }
119
+ return created;
120
+ });
121
+ return json(await roomPayload(room), 201);
122
+ }
123
+
124
+ export async function roomDetailRoutes(req: Request, url: URL): Promise<Response | undefined> {
125
+ const g = url.pathname.match(/^\/rooms\/([^/]+)$/);
126
+ if (g && req.method === "GET") {
127
+ const room = await readState((svc) =>
128
+ svc.getRoom(decodeURIComponent(g[1]!)),
129
+ );
130
+ return json(await roomPayload(room));
131
+ }
132
+ const r = url.pathname.match(/^\/rooms\/([^/]+)\/registry$/);
133
+ if (r && req.method === "GET") {
134
+ // ponytail: session registry for the in-plugin wake watcher — lets the
135
+ // plugin find which sessions have unread messages without polling every
136
+ // session's inbox; host is included for the @-wake ownership gate
137
+ const roomId = decodeURIComponent(r[1]!);
138
+ const reg = await readState((svc, registry) => {
139
+ const entries = registry[roomId] ?? {};
140
+ return Object.fromEntries(
141
+ Object.entries(entries).map(([sid, e]) => [
142
+ sid,
143
+ {
144
+ name: e.name,
145
+ membershipID: e.membershipID,
146
+ protocol: e.protocol,
147
+ receiverOwnerID: e.receiverOwnerID,
148
+ lastReadTs: e.lastReadTs ?? 0,
149
+ lastQueuedTs: e.lastQueuedTs ?? 0,
150
+ host: e.host ?? "",
151
+ directory: e.directory,
152
+ roomKind: svc.getRoom(roomId).kind ?? "group",
153
+ },
154
+ ]),
155
+ );
156
+ });
157
+ return json(reg);
158
+ }
159
+ return undefined;
160
+ }
@@ -0,0 +1,84 @@
1
+ // Server startup: config resolution, environment publication, storage
2
+ // readiness and the Channel D lifecycle.
3
+ import { existsSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { loadRoomConfig, resolveServerSettings, type ServerSettings } from "../src/config/file-config.ts";
7
+ import { maxResourceBytes } from "../src/rooms/resources.ts";
8
+ import { resourceStorage } from "../src/rooms/storage.ts";
9
+ import { maxRoomTasks } from "../src/rooms/tasks.ts";
10
+ import { createChannelController, type ChannelController } from "./channels.ts";
11
+
12
+ export type ServerBootstrap = {
13
+ settings: ServerSettings;
14
+ here: string;
15
+ hostname: string;
16
+ displayHostname: string;
17
+ port: number;
18
+ token?: string;
19
+ serveWakeUrl: string;
20
+ maxRequestBodySize: number;
21
+ };
22
+
23
+ function parsePort(value: string): number {
24
+ const port = Number(value);
25
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
26
+ throw new Error(
27
+ `Invalid server port "${value}": expected an integer from 1 to 65535`,
28
+ );
29
+ }
30
+ return port;
31
+ }
32
+
33
+ export async function loadServerBootstrap(): Promise<ServerBootstrap> {
34
+ // The bundled CLI lives in dist/, while its published server files stay in server/.
35
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
36
+ const here = existsSync(path.join(moduleDir, "chat.html")) ? moduleDir : path.resolve(moduleDir, "../server");
37
+ const settings = resolveServerSettings(loadRoomConfig());
38
+ // A malformed limit stops startup instead of silently clamping.
39
+ maxRoomTasks();
40
+ const hostname = settings.host;
41
+ const displayHostname = hostname.includes(":") ? `[${hostname}]` : hostname;
42
+ const port = parsePort(settings.port);
43
+ const token = settings.token;
44
+ // The state directory and upload limit are read lazily from the environment;
45
+ // publish the file values before the first database or upload call.
46
+ if (!process.env.CHAT_ROOM_STATE_DIR && settings.stateDir) process.env.CHAT_ROOM_STATE_DIR = settings.stateDir;
47
+ if (!process.env.CHAT_ROOM_MAX_FILE_SIZE_MB && settings.maxFileSizeMb !== undefined) {
48
+ process.env.CHAT_ROOM_MAX_FILE_SIZE_MB = String(settings.maxFileSizeMb);
49
+ }
50
+ // Storage validation and the S3 HeadBucket check run before the server listens.
51
+ // A bucket, credential, or network failure stops startup; there is no local fallback.
52
+ await resourceStorage().ready();
53
+ // Deployment-configured wake URL: an @mention wakes an exited session
54
+ // immediately (no polling delay). Without it the plugin timer is the fallback.
55
+ // This is explicit configuration, not a guess that OpenCode exists.
56
+ return {
57
+ settings,
58
+ here,
59
+ hostname,
60
+ displayHostname,
61
+ port,
62
+ token,
63
+ serveWakeUrl: settings.wakeServeUrl,
64
+ maxRequestBodySize: Math.max(128 * 1024 * 1024, maxResourceBytes()),
65
+ };
66
+ }
67
+
68
+ // Channel D is opt-in. A missing config aborts startup; a failed adapter start
69
+ // only logs and leaves the forward routes absent. Admin routes can swap the
70
+ // runtime later without restarting the main server.
71
+ export async function startChannelLifecycle(
72
+ settings: ServerSettings,
73
+ assign: (controller: ChannelController) => void,
74
+ ): Promise<void> {
75
+ const channelController = createChannelController(settings);
76
+ assign(channelController);
77
+ await channelController.start();
78
+ let stopping: Promise<void> | undefined;
79
+ const stopChannelsNow = () => {
80
+ stopping ??= channelController.stop().finally(() => process.exit(0));
81
+ };
82
+ process.once("SIGINT", stopChannelsNow);
83
+ process.once("SIGTERM", stopChannelsNow);
84
+ }
package/server/sw.js CHANGED
@@ -19,6 +19,10 @@ const STATIC = [
19
19
  "/assets/tasks.css",
20
20
  "/assets/doc-preview.css",
21
21
  "/assets/diagram-viewer.css",
22
+ "/assets/chat/office-preview.js",
23
+ "/assets/office/docx.bundle.js",
24
+ "/assets/office/xlsx.bundle.js",
25
+ "/assets/office/pptx.bundle.js",
22
26
  "/assets/marked-18.0.4.js",
23
27
  "/assets/dompurify-3.4.7.js",
24
28
  "/assets/mermaid-11.12.2.min.js",
@@ -24,7 +24,7 @@ export async function taskRoutes(req: Request, url: URL): Promise<Response | und
24
24
  const session = sessionID(url.searchParams.get("sessionID"));
25
25
  if (!session) return json({ error: "sessionID is required" }, 400);
26
26
  const result = await listTasks(roomID, session);
27
- return "error" in result ? json({ error: result.error }, result.status) : json({ tasks: result.tasks });
27
+ return "error" in result ? json({ error: result.error }, result.status) : json({ tasks: result.tasks, limit: result.limit });
28
28
  }
29
29
  if (req.method !== "POST" && req.method !== "DELETE") return json({ error: "method not allowed" }, 405);
30
30
  const body = await jsonObject<Record<string, unknown>>(req);