@alexsun-top/opencode-chat-room 0.7.8 → 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 (183) hide show
  1. package/CHANGELOG.md +43 -1
  2. package/LICENSE +21 -0
  3. package/README.md +77 -36
  4. package/README.zh-CN.md +82 -41
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +6905 -2764
  7. package/package.json +33 -3
  8. package/packages/chat-room-channeld/README.md +315 -0
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +1262 -0
  10. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  11. package/packages/chat-room-channeld/src/adapter.ts +509 -0
  12. package/packages/chat-room-channeld/src/cli.ts +124 -0
  13. package/packages/chat-room-channeld/src/config.ts +269 -0
  14. package/packages/chat-room-channeld/src/delivery.ts +163 -0
  15. package/packages/chat-room-channeld/src/feishu-adapter.ts +303 -0
  16. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  17. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  18. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  19. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  20. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  21. package/packages/chat-room-channeld/src/framing.ts +128 -0
  22. package/packages/chat-room-channeld/src/host-helpers.ts +52 -0
  23. package/packages/chat-room-channeld/src/host.ts +627 -0
  24. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  25. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  26. package/packages/chat-room-channeld/src/log.ts +26 -0
  27. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  28. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  29. package/packages/chat-room-channeld/src/published.ts +37 -0
  30. package/packages/chat-room-channeld/src/rules.ts +127 -0
  31. package/packages/chat-room-channeld/src/state.ts +502 -0
  32. package/packages/chat-room-channeld/src/stats.ts +209 -0
  33. package/plugin.ts +22 -5
  34. package/server/addressing-routes.ts +130 -0
  35. package/server/admin-state.ts +13 -13
  36. package/server/app.ts +95 -0
  37. package/server/assets/NOTICE.txt +3 -2
  38. package/server/assets/SHIKI-LICENSE +22 -0
  39. package/server/assets/base.css +24 -10
  40. package/server/assets/chat/announcements.js +70 -7
  41. package/server/assets/chat/doc-preview.js +187 -39
  42. package/server/assets/chat/events.js +3 -0
  43. package/server/assets/chat/files.js +46 -4
  44. package/server/assets/chat/forward.js +69 -0
  45. package/server/assets/chat/index.js +4 -0
  46. package/server/assets/chat/integration-editor.js +163 -0
  47. package/server/assets/chat/integration-values.js +124 -0
  48. package/server/assets/chat/integrations.js +498 -0
  49. package/server/assets/chat/locales/de.js +45 -4
  50. package/server/assets/chat/locales/es.js +45 -4
  51. package/server/assets/chat/locales/fr.js +45 -4
  52. package/server/assets/chat/locales/it.js +45 -4
  53. package/server/assets/chat/locales/ja.js +45 -4
  54. package/server/assets/chat/locales/ko.js +45 -4
  55. package/server/assets/chat/markdown-footnotes.js +115 -0
  56. package/server/assets/chat/markdown.js +46 -43
  57. package/server/assets/chat/messages.js +5 -5
  58. package/server/assets/chat/office-preview.js +69 -0
  59. package/server/assets/chat/palette.js +1 -1
  60. package/server/assets/chat/panels.js +36 -0
  61. package/server/assets/chat/recall.js +58 -7
  62. package/server/assets/chat/receipts.js +15 -3
  63. package/server/assets/chat/reminders.js +69 -8
  64. package/server/assets/chat/replies.js +7 -1
  65. package/server/assets/chat/resource-format.js +11 -0
  66. package/server/assets/chat/settings.js +30 -2
  67. package/server/assets/chat/shiki.js +87 -0
  68. package/server/assets/chat/side-pane.js +9 -3
  69. package/server/assets/chat/state.js +107 -11
  70. package/server/assets/chat/system-events.js +32 -0
  71. package/server/assets/chat/system-messages.js +23 -12
  72. package/server/assets/chat/task-row.js +0 -6
  73. package/server/assets/chat/tasks.js +121 -33
  74. package/server/assets/code-highlight.css +74 -62
  75. package/server/assets/conversation.css +126 -25
  76. package/server/assets/doc-preview.css +36 -3
  77. package/server/assets/files.css +5 -0
  78. package/server/assets/fluent-icons.svg +2 -0
  79. package/server/assets/monaco/LICENSE +21 -0
  80. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  81. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  82. package/server/assets/monaco/editor.worker.js +45 -0
  83. package/server/assets/monaco/integration-rules.css +1 -0
  84. package/server/assets/monaco/integration-rules.js +1297 -0
  85. package/server/assets/monaco/json.worker.js +77 -0
  86. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  87. package/server/assets/office/docx.bundle.js +33 -0
  88. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  89. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  90. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  91. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  92. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  93. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  94. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  95. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  96. package/server/assets/{HIGHLIGHT-LICENSE → office/licenses/zrender-LICENSE.txt} +2 -2
  97. package/server/assets/office/pptx.bundle.js +104 -0
  98. package/server/assets/office/xlsx.bundle.js +141 -0
  99. package/server/assets/recall.css +5 -4
  100. package/server/assets/responsive.css +52 -8
  101. package/server/assets/settings.css +73 -1
  102. package/server/assets/shiki.bundle.js +152 -0
  103. package/server/assets/tasks.css +57 -7
  104. package/server/channel-integration.ts +519 -0
  105. package/server/channel-settings.ts +77 -0
  106. package/server/channels.ts +557 -0
  107. package/server/chat-server.ts +33 -558
  108. package/server/chat.html +195 -22
  109. package/server/http-server.ts +3 -182
  110. package/server/resource-routes.ts +16 -16
  111. package/server/routes/inbox.ts +100 -0
  112. package/server/routes/pages.ts +83 -0
  113. package/server/routes/questions.ts +39 -0
  114. package/server/routes/room-actions.ts +162 -0
  115. package/server/routes/rooms.ts +160 -0
  116. package/server/startup.ts +84 -0
  117. package/server/sw.js +5 -2
  118. package/server/task-routes.ts +1 -1
  119. package/skills/chatroom/SKILL.md +1 -1
  120. package/src/center/center-client.ts +71 -1
  121. package/src/config/file-config.ts +29 -42
  122. package/src/platform/http-server.ts +182 -0
  123. package/src/protocol/addressing.ts +21 -0
  124. package/src/protocol/config.ts +58 -0
  125. package/src/protocol/room.ts +51 -0
  126. package/src/rooms/resources.ts +26 -16
  127. package/src/rooms/room-service.ts +2 -48
  128. package/src/rooms/storage.ts +329 -0
  129. package/src/rooms/tasks.ts +21 -5
  130. package/src/runtime/v2-plugin.ts +8 -2
  131. package/src/runtime/watch.ts +4 -3
  132. package/src/state/pg-database.ts +183 -0
  133. package/src/state/pg-migrate.ts +175 -0
  134. package/src/state/pg-sql.mjs +175 -0
  135. package/src/state/pg-worker.mjs +148 -0
  136. package/src/state/sqlite-announcements.ts +25 -0
  137. package/src/state/sqlite-database.ts +121 -0
  138. package/src/state/sqlite-legacy.ts +90 -0
  139. package/src/state/sqlite-members.ts +155 -0
  140. package/src/state/sqlite-messages.ts +288 -0
  141. package/src/state/sqlite-resources.ts +39 -0
  142. package/src/state/sqlite-rooms.ts +87 -0
  143. package/src/state/sqlite-schema.ts +80 -0
  144. package/src/state/sqlite-state-store.ts +33 -0
  145. package/src/state/sqlite-state.ts +15 -866
  146. package/src/state/sqlite-tasks.ts +65 -0
  147. package/src/state/sqlite-transaction.ts +13 -0
  148. package/src/state/sqlite.ts +21 -1
  149. package/src/state/store.ts +13 -3
  150. package/src/tui/app.mjs +32 -19
  151. package/src/tui/config.mjs +12 -4
  152. package/src/tui/http.mjs +16 -2
  153. package/src/tui/i18n.mjs +38 -0
  154. package/src/tui/info-app.mjs +50 -51
  155. package/src/tui/info-content.mjs +79 -44
  156. package/src/tui/join-app.mjs +9 -9
  157. package/src/tui/locales/en.mjs +349 -0
  158. package/src/tui/locales/zh-CN.mjs +349 -0
  159. package/src/tui/main.mjs +85 -37
  160. package/src/tui/markdown.mjs +3 -2
  161. package/src/tui/mentions.mjs +3 -1
  162. package/src/tui/message-app.mjs +22 -21
  163. package/src/tui/message-view.mjs +2 -1
  164. package/src/tui/palette-app.mjs +9 -8
  165. package/src/tui/palette.mjs +30 -24
  166. package/src/tui/prefs.mjs +92 -0
  167. package/src/tui/reminder-app.mjs +18 -17
  168. package/src/tui/room-settings-app.mjs +30 -28
  169. package/src/tui/settings-app.mjs +153 -0
  170. package/src/tui/ui-content.mjs +65 -86
  171. package/src/tui/ui-help.mjs +73 -0
  172. package/src/tui/ui-overlay-view.mjs +23 -7
  173. package/src/tui/ui-suggest.mjs +6 -5
  174. package/src/tui/ui-theme.mjs +37 -33
  175. package/src/tui/ui-view.mjs +22 -7
  176. package/src/tui/ui.mjs +15 -3
  177. package/src/web/editor.worker.ts +1 -0
  178. package/src/web/integration-rules-editor.ts +439 -0
  179. package/src/web/integration-rules.ts +22 -0
  180. package/src/web/integration-schema.ts +228 -0
  181. package/src/web/json.worker.ts +1 -0
  182. package/src/web/office-viewer.ts +221 -0
  183. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -1,573 +1,48 @@
1
- // ponytail: central chat-room server. Single HTTP service holding the
2
- // authoritative SQLite room database; plugins (central mode) talk to it
3
- // via CHAT_ROOM_SERVER_URL. Optional bearer token (CHAT_ROOM_SERVER_TOKEN).
4
- import { existsSync, promises as fs } from "node:fs";
5
- import path from "node:path";
6
- import { fileURLToPath } from "node:url";
7
- import { randomUUID } from "node:crypto";
8
- import RoomService, {
9
- RoomError,
10
- type Message,
11
- type Room,
12
- } from "../src/rooms/room-service.ts";
13
- import { acknowledgeQueued, answerQuestion, appendRoomMessage, databasePath, sendReply, readQuestions, readState, writeState, type Registry, type RegistryEntry } from "../src/state/store.ts";
14
- import { saveJoinRequest, writeSqliteStateWithDatabase } from "../src/state/sqlite-state.ts";
15
- import {
16
- admissionMatches,
17
- clearPendingAdmission,
18
- } from "../src/center/queue.ts";
19
- import { readInbox } from "./inbox.ts";
20
- import { isReceiverOwnerID } from "../src/state/receiver-owner.ts";
21
- import { claimWake, touchActive, wakeMentionedSessions } from "./wake.ts";
22
- import { historyRoute } from "./history-route.ts";
23
- import { messageRecallRoutes } from "./message-recall-routes.ts";
24
- import { roomPayload } from "./room-payload.ts";
25
- import { isUser, settleAdmins, settleOwner } from "./room-owner.ts";
26
- import { jsonObject } from "./json-body.ts";
27
- import { roomManagement } from "./newrooms.ts";
28
- import { memberRoutes } from "./member-routes.ts";
29
- import { resourceRoutes } from "./resource-routes.ts";
30
- import { maxResourceBytes } from "../src/rooms/resources.ts";
31
- import { adminRoutes } from "./admin-routes.ts";
32
- import { joinRequestRoutes } from "./join-requests.ts";
33
- import { joinRoomMember } from "./room-join.ts";
34
- import { roomReminderRoutes, startRoomReminderScheduler } from "./room-reminders.ts";
35
- import { loadRoomConfig, resolveServerSettings } from "../src/config/file-config.ts";
36
- import { startServer } from "./http-server.ts";
37
-
38
- // The chat page shows this next to the app title; a missing package must not
39
- // leave a placeholder behind.
40
- const moduleDir = path.dirname(fileURLToPath(import.meta.url));
41
- // The bundled CLI lives in dist/, while its published server files stay in server/.
42
- const here = existsSync(path.join(moduleDir, "chat.html")) ? moduleDir : path.resolve(moduleDir, "../server");
43
- let versionTag: Promise<string> | undefined;
44
- const chatVersionTag = () => (versionTag ??= fs.readFile(path.join(here, "../package.json"), "utf8")
45
- .then((text) => { const pkg = JSON.parse(text) as { version?: unknown }; return typeof pkg?.version === "string" && pkg.version ? `v${pkg.version}` : ""; })
46
- .catch(() => ""));
47
-
48
- function parsePort(value: string): number {
49
- const port = Number(value);
50
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
51
- throw new Error(
52
- `Invalid server port "${value}": expected an integer from 1 to 65535`,
53
- );
54
- }
55
- return port;
56
- }
57
-
58
- const settings = resolveServerSettings(loadRoomConfig());
59
- const hostname = settings.host;
60
- const displayHostname = hostname.includes(":") ? `[${hostname}]` : hostname;
61
- const port = parsePort(settings.port);
62
- const token = settings.token;
63
-
64
- // The state directory and upload limit are read lazily from the environment;
65
- // publish the file values before the first database or upload call.
66
- if (!process.env.CHAT_ROOM_STATE_DIR && settings.stateDir) process.env.CHAT_ROOM_STATE_DIR = settings.stateDir;
67
- if (!process.env.CHAT_ROOM_MAX_FILE_SIZE_MB && settings.maxFileSizeMb !== undefined) {
68
- process.env.CHAT_ROOM_MAX_FILE_SIZE_MB = String(settings.maxFileSizeMb);
69
- }
70
-
71
- // ponytail: 部署者显式配置的 serve 地址——消息到达时立即唤起被 @ 的已退出
72
- // session(零轮询延迟);未配置则跳过(插件定时器兜底)。这是显式配置,
73
- // 不是对 opencode 存在的假设
74
- const serveWakeUrl = settings.wakeServeUrl;
75
-
76
- const json = (body: unknown, status = 200) =>
77
- new Response(JSON.stringify(body), {
78
- status,
79
- headers: { "Content-Type": "application/json" },
80
- });
81
-
82
- function mutate<T>(fn: (svc: RoomService, registry: Registry) => T): Promise<T> {
83
- return writeState(fn);
84
- }
85
-
86
- function read<T>(fn: (svc: RoomService) => T): Promise<T> {
87
- return readState(fn);
88
- }
89
-
90
- const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
91
-
92
- // Database callbacks finish synchronously before any HTTP or long-poll wait.
93
- async function handle(req: Request): Promise<Response> {
94
- const url = new URL(req.url);
95
- const p = url.pathname;
96
- if (req.method === "GET" && p === "/") {
97
- return Response.redirect(new URL("/chat", url).toString(), 302);
98
- }
99
- if (req.method === "GET" && p === "/chat") {
100
- const html = await fs
101
- .readFile(path.join(here, "chat.html"), "utf8")
102
- .catch(() => null);
103
- if (html === null) {
104
- return json({ error: "chat page not found" }, 404);
105
- }
106
- const version = await chatVersionTag();
107
- return new Response(html.replaceAll("{{version}}", version), {
108
- headers: {
109
- "Content-Type": "text/html; charset=utf-8",
110
- "Cache-Control": "no-store",
111
- },
112
- });
113
- }
114
- // The install surface lives at the origin root so the worker controls /chat, not /assets.
115
- if (req.method === "GET" && p === "/manifest.webmanifest") {
116
- const body = await fs.readFile(path.join(here, "manifest.webmanifest"), "utf8").catch(() => null);
117
- if (body === null) return json({ error: "manifest not found" }, 404);
118
- return new Response(body, {
119
- headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-store" },
120
- });
121
- }
122
- if (req.method === "GET" && p === "/sw.js") {
123
- const body = await fs.readFile(path.join(here, "sw.js"), "utf8").catch(() => null);
124
- if (body === null) return json({ error: "service worker not found" }, 404);
125
- const version = (await chatVersionTag()) || "dev";
126
- return new Response(body.replaceAll("{{version}}", version), {
127
- headers: {
128
- "Content-Type": "text/javascript; charset=utf-8",
129
- "Cache-Control": "no-store",
130
- "Service-Worker-Allowed": "/",
131
- },
132
- });
133
- }
134
- if (req.method === "GET" && p.startsWith("/assets/")) {
135
- let relative: string;
136
- try { relative = decodeURIComponent(p.slice("/assets/".length)); }
137
- catch { return json({ error: "invalid asset path" }, 400); }
138
- const root = path.resolve(here, "assets");
139
- const file = path.resolve(root, relative);
140
- if (!relative || !file.startsWith(`${root}${path.sep}`) || !/\.(?:css|js|mjs|svg|png|jpg|woff2?)$/i.test(file)) return json({ error: "not found" }, 404);
141
- const data = await fs.readFile(file).catch(() => null);
142
- if (!data) return json({ error: "not found" }, 404);
143
- 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" : "font/woff2";
144
- return new Response(data, { headers: { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
145
- }
146
- // ponytail: F1 — reject non-JSON POSTs; a text/plain simple request from a
147
- // malicious page would otherwise mutate rooms cross-origin (no preflight)
148
- if (
149
- ["POST", "PUT", "PATCH", "DELETE"].includes(req.method) &&
150
- !req.headers.get("content-type")?.includes("application/json") &&
151
- !(/^\/rooms\/[^/]+\/resources$/.test(p) && req.method === "POST")
152
- ) {
153
- return json({ error: "content-type must be application/json" }, 415);
154
- }
155
- if (token && req.headers.get("authorization") !== `Bearer ${token}`) {
156
- return json({ error: "unauthorized" }, 401);
157
- }
158
- try {
159
- const reminders = await roomReminderRoutes(req, url);
160
- if (reminders) return reminders;
161
- const admin = await adminRoutes(req, url); if (admin) return admin;
162
- const resource = await resourceRoutes(req, url);
163
- if (resource) return resource;
164
- const history = await historyRoute(url);
165
- if (history) return history;
166
- const recall = await messageRecallRoutes(req, url);
167
- if (recall) return recall;
168
- if (req.method === "GET" && p === "/rooms/summary") {
169
- // ponytail: 轻量房间摘要(不含消息)——wakeSessions 每 10s 用它计算
170
- // latest,避免下载全部房间历史(orc-1 #5)
171
- const rooms = await read((svc) =>
172
- svc.listRooms().map((r) => ({
173
- id: r.id,
174
- name: r.name,
175
- latestMsgTs: r.messages.at(-1)?.createdAt ?? 0,
176
- })),
177
- );
178
- return json(rooms);
179
- }
180
- if (req.method === "GET" && p === "/receiver/memberships") {
181
- const ownerID = url.searchParams.get("ownerID");
182
- if (!isReceiverOwnerID(ownerID)) return json({ error: "invalid ownerID" }, 400);
183
- const sessionIDs = await readState((_svc, registry) => {
184
- return [...new Set(Object.values(registry).flatMap((entries) =>
185
- Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id),
186
- ))];
187
- });
188
- return json({ sessionIDs });
189
- }
190
- if (req.method === "GET" && p === "/rooms") {
191
- const caller = url.searchParams.get("sessionID");
192
- const rows = await readState((svc, registry) => svc.listRooms()
193
- .filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller))
194
- .map((room) => ({ room, entry: caller ? registry[room.id]?.[caller] : undefined })));
195
- const rooms = [];
196
- for (const { room, entry } of rows) {
197
- // The browser keeps its watermark per tab; a new tab starts from this one.
198
- rooms.push({ ...await roomPayload(room), joined: Boolean(entry), ...(entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {}) });
199
- }
200
- return json(rooms);
201
- }
202
- const members = await memberRoutes(req, url);
203
- if (members) return members;
204
- const joinRequests = await joinRequestRoutes(req, url);
205
- if (joinRequests) return joinRequests;
206
- const management = await roomManagement(req, url);
207
- if (management) return management;
208
- if (req.method === "POST" && p === "/rooms") {
209
- const body = await jsonObject<Record<string, string>>(req);
210
- if (!body) return json({ error: "JSON object body is required" }, 400);
211
- if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
212
- return json({ error: "invalid receiver ownership" }, 400);
213
- }
214
- const name = body.name?.trim();
215
- if (!name) {
216
- return json({ error: "name is required" }, 400);
217
- }
218
- if (name.length > 64) {
219
- return json({ error: "name too long (max 64)" }, 400);
220
- }
221
- const owner = (body.ownerId ?? "").trim() || "访客";
222
- if (owner.length > 64) {
223
- return json({ error: "ownerId too long (max 64)" }, 400);
224
- }
225
- if (body.joinPolicy !== undefined && body.joinPolicy !== "open" && body.joinPolicy !== "approval") {
226
- return json({ error: "joinPolicy must be open or approval" }, 400);
227
- }
228
- const joinPolicy = body.joinPolicy === "approval" ? "approval" : body.joinPolicy === "open" ? "open" : undefined;
229
- const room = await mutate((svc, reg) => {
230
- const created = svc.createRoom(name, owner, joinPolicy);
231
- if (body.sessionID) {
232
- const regRoom = (reg[created.id] =
233
- reg[created.id] ?? Object.create(null) as Record<string, RegistryEntry>);
234
- regRoom[body.sessionID] = {
235
- // ponytail: central mode self-pulls the inbox; no cross-host URL
236
- serverUrl: "",
237
- apiPrefix: "/api",
238
- membershipID: randomUUID(),
239
- ...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
240
- ...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
241
- name: owner,
242
- directory: body.directory || undefined,
243
- // ora-1 #2: 归属主机——跨机 @-wake 只由所属机器执行
244
- host: body.host ?? "",
245
- lastReadTs: Math.max(
246
- Date.now(),
247
- created.messages.at(-1)?.createdAt ?? 0,
248
- ),
249
- lastQueuedTs: 0,
250
- };
251
- created.ownerMembershipID = regRoom[body.sessionID]!.membershipID;
252
- }
253
- return created;
254
- });
255
- return json(await roomPayload(room), 201);
256
- }
257
- if (req.method === "GET" && p === "/inbox") {
258
- const sessionID = url.searchParams.get("sessionID") ?? "";
259
- const roomFilter = url.searchParams.get("roomId");
260
- const afterValue = url.searchParams.get("afterTs");
261
- const afterTs = afterValue === null ? undefined : Number(afterValue);
262
- const recallVersionValue = url.searchParams.get("recallVersion");
263
- if (url.searchParams.has("recallVersion") && (recallVersionValue === "" || !/^\d+$/.test(recallVersionValue ?? "") ||
264
- !Number.isSafeInteger(Number(recallVersionValue)))) {
265
- return json({ error: "recallVersion must be a non-negative safe integer" }, 400);
266
- }
267
- const clientRecallVersion = recallVersionValue === null ? undefined : Number(recallVersionValue);
268
- if (url.searchParams.has("afterTs") && (afterValue === "" || !/^\d+$/.test(afterValue ?? "") ||
269
- !Number.isSafeInteger(afterTs) || afterTs! < 0 || !roomFilter || url.searchParams.get("excludeSelf") !== "0")) {
270
- return json({ error: "afterTs requires a roomId and excludeSelf=0, with a non-negative safe integer value" }, 400);
271
- }
272
- // ponytail: poll includes the caller's own messages (echo), the
273
- // notification self-pull excludes them — aligned with standalone poll
274
- const excludeSelf = url.searchParams.get("excludeSelf") === "1";
275
- // long-poll: wait up to `timeout` ms for the first new message
276
- // instead of returning empty immediately (web chat + sub-agent
277
- // watchers); empty responses only happen on timeout
278
- const timeout = Math.min(
279
- Math.max(Number(url.searchParams.get("timeout") ?? 0) || 0, 0),
280
- 30000,
281
- );
282
- const deadline = Date.now() + timeout;
283
- let result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
284
- // The client's rendered snapshot version is the baseline; using the first
285
- // read instead would hide a recall that landed before this request started.
286
- const initialRecallVersion = clientRecallVersion ?? result.recallVersion;
287
- // A recall bumps the version without creating a message; wake the poll so
288
- // the client can refetch the room snapshot (reliable version compare).
289
- while (result.items.length === 0 && result.recallVersion === initialRecallVersion && Date.now() < deadline) {
290
- // ponytail: 500ms between disk scans keeps notification latency under
291
- // half a second; a longer interval makes deliveries feel stuck.
292
- await sleep(Math.max(1, Math.min(500, deadline - Date.now())));
293
- result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
294
- }
295
- return json(result);
296
- }
297
- if (req.method === "POST" && p === "/queued") {
298
- const body = await jsonObject<Record<string, unknown>>(req);
299
- if (!body) return json({ error: "JSON object body is required" }, 400);
300
- const ts = Number(body.ts);
301
- const roomId = String(body.roomId ?? "");
302
- const sessionID = String(body.sessionID ?? "");
303
- if (
304
- body.ts === undefined ||
305
- body.ts === null ||
306
- !roomId ||
307
- !sessionID ||
308
- !Number.isFinite(ts)
309
- ) {
310
- return json({ error: "roomId/sessionID/finite ts are required" }, 400);
311
- }
312
- // Clamp to the room tail so a forged future ts cannot silence delivery.
313
- const updated = await acknowledgeQueued(roomId, sessionID, ts);
314
- if (updated === null) {
315
- return json({ error: "registry entry not found" }, 404);
316
- }
317
- clearPendingAdmission(sessionID, roomId, updated);
318
- touchActive(sessionID);
319
- return json({ ok: true });
320
- }
321
- if (req.method === "POST" && p === "/active") {
322
- // ponytail: 活跃上报——插件对"进程内自推成功"的 session 调用(真实
323
- // 活跃);服务器据此避免 serve 双唤起
324
- const body = await jsonObject<Record<string, unknown>>(req);
325
- if (!body) return json({ error: "JSON object body is required" }, 400);
326
- touchActive(String(body.sessionID ?? ""));
327
- return json({ ok: true });
328
- }
329
- if (req.method === "POST" && p === "/wake-claim") {
330
- // ponytail: atomic cross-process wake dedupe (see claimWake) — the
331
- // server only arbitrates, it never spawns anything itself
332
- const body = await jsonObject<Record<string, unknown>>(req);
333
- if (!body) return json({ error: "JSON object body is required" }, 400);
334
- const sessionID = String(body.sessionID ?? "");
335
- const ok = claimWake(sessionID);
336
- return json({ ok });
337
- }
338
- const m = p.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
339
- if (m) {
340
- const roomId = decodeURIComponent(m[1]!);
341
- const body = await jsonObject<Record<string, string>>(req);
342
- if (!body) return json({ error: "JSON object body is required" }, 400);
343
- const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
344
- if (req.method === "POST" && m[2] === "join") {
345
- if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
346
- return json({ error: "invalid receiver ownership" }, 400);
347
- }
348
- // ponytail: F4/F5 — names must be non-empty, and re-joining under a
349
- // new name must retire the old participant (no ghost members)
350
- const id = typeof body.participantId === "string" ? body.participantId.trim() : "";
351
- const name = typeof body.participantName === "string" ? body.participantName.trim() : "";
352
- if (!id || !name || !sessionID) {
353
- return json(
354
- { error: "participantId/participantName/sessionID are required" },
355
- 400,
356
- );
357
- }
358
- if (id.length > 64 || name.length > 64) {
359
- return json({ error: "name too long (max 64)" }, 400);
360
- }
361
- const result = await writeSqliteStateWithDatabase(databasePath(), (svc, reg, db) => {
362
- const currentRoom = svc.getRoom(roomId);
363
- // A restricted room treats a new identity as a pending request; no
364
- // participant or registry entry exists until a reviewer approves.
365
- if (currentRoom.joinPolicy === "approval" && currentRoom.kind !== "direct" && !reg[roomId]?.[sessionID]) {
366
- if (svc.containsParticipant(roomId, id)) return { status: 409 as const, error: "participant name is already in use in this room" };
367
- 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);
368
- if (duplicate) return { status: 409 as const, error: "participant name is already in use in this room" };
369
- saveJoinRequest(db, {
370
- roomID: roomId, sessionID, participantId: id, name,
371
- isAgent: Boolean(body.protocol || body.receiverOwnerID || body.host),
372
- createdAt: Date.now(),
373
- ...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
374
- ...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
375
- ...(body.directory ? { directory: body.directory } : {}),
376
- ...(body.host ? { host: body.host } : {}),
377
- });
378
- return { pending: true as const };
379
- }
380
- return { room: joinRoomMember(svc, reg, roomId, {
381
- sessionID, participantId: id, name,
382
- ...(body.protocol === "v2" ? { protocol: "v2" as const } : {}),
383
- ...(body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {}),
384
- ...(body.directory ? { directory: body.directory } : {}),
385
- host: body.host ?? "",
386
- }) };
387
- });
388
- if ("status" in result) return json({ error: result.error }, result.status);
389
- if ("pending" in result) return json({
390
- status: "pending",
391
- message: "Join request submitted. You are not a member yet; a human administrator must approve it before you can send or poll.",
392
- }, 202);
393
- touchActive(sessionID); // join = active
394
- return json(await roomPayload(result.room), 201);
395
- }
396
- if (req.method === "POST" && m[2] === "leave") {
397
- await mutate((svc, reg) => {
398
- const room = svc.getRoom(roomId);
399
- const entry = reg[roomId]?.[sessionID];
400
- const participantId = room.kind === "direct" ? sessionID : entry?.name ?? sessionID;
401
- // ponytail: orc-2 #2——共享名守卫:还有别的 session 持有同名时,
402
- // 只移除本 entry,不移除参与者(否则兄弟 tab 发送会 NOT_JOINED)
403
- const shared = Object.entries(reg[roomId] ?? {}).some(
404
- ([sid, e]) => e.name === participantId && sid !== sessionID,
405
- );
406
- if (!shared) {
407
- svc.leaveRoom(roomId, participantId);
408
- svc.addEvent(roomId, `${participantId} left the room`);
409
- }
410
- if (reg[roomId]) {
411
- delete reg[roomId][sessionID];
412
- if (Object.keys(reg[roomId]).length === 0) {
413
- delete reg[roomId];
414
- }
415
- }
416
- // A departing delegated admin passes the role to the room's explicit successor.
417
- if (entry?.name && room.ownerId && (room.adminIds ?? []).includes(entry.name)) {
418
- const successor = Object.values(reg[roomId] ?? {}).find((candidate) =>
419
- isUser(candidate) && (room.successorMembershipID ? candidate.membershipID === room.successorMembershipID : candidate.name === room.successorId));
420
- if (successor?.name && successor.name !== room.ownerId) {
421
- room.adminIds = [...new Set([...(room.adminIds ?? []).filter((name) => name !== successor.name), successor.name])];
422
- if (successor.membershipID) room.adminMembershipIDs = [...new Set([...(room.adminMembershipIDs ?? []).filter((id) => id !== successor.membershipID), successor.membershipID])];
423
- }
424
- }
425
- if (entry && (room.successorMembershipID ? entry.membershipID === room.successorMembershipID : entry.name === room.successorId)) {
426
- delete room.successorId;
427
- delete room.successorMembershipID;
428
- }
429
- // A departing owner hands the room to the next person; the last one leaves it open.
430
- settleAdmins(svc.getRoom(roomId), reg[roomId] ?? {});
431
- settleOwner(svc.getRoom(roomId), reg[roomId] ?? {});
432
- });
433
- return json({ ok: true });
434
- }
435
- if (req.method === "POST" && m[2] === "messages") {
436
- const isQuestion = (body as Record<string, unknown>).isQuestion;
437
- if (isQuestion !== undefined && typeof isQuestion !== "boolean") return json({ error: "isQuestion must be a boolean" }, 400);
438
- // ponytail: F3 — mirror the plugin's zod limit at the HTTP boundary
439
- const text = typeof body.text === "string" ? body.text.trim() : "";
440
- if (!text) {
441
- return json({ error: "text is required" }, 400);
442
- }
443
- if (text.length > 5000) {
444
- return json({ error: "text too long (max 5000)" }, 400);
445
- }
446
- const replyTo = (body as Record<string, unknown>).replyToMessageID;
447
- if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo)) return json({ error: "replyToMessageID must be a non-empty message ID" }, 400);
448
- // Optional retry key: a lost response may be retried without creating a twin.
449
- const clientMessageID = (body as Record<string, unknown>).clientMessageID;
450
- if (clientMessageID !== undefined && (typeof clientMessageID !== "string" || !clientMessageID || clientMessageID.length > 100)) {
451
- return json({ error: "clientMessageID must be a non-empty string (max 100)" }, 400);
452
- }
453
- if (replyTo !== undefined) {
454
- const result = await sendReply(roomId, replyTo, sessionID, text, clientMessageID);
455
- if (result.status !== "ok") {
456
- if (result.status === "missing") return json({ error: "room not found" }, 404);
457
- if (result.status === "target") return json({ error: "reply target not found in room" }, 404);
458
- if (result.status === "question") return json({ error: "use the question answers endpoint to reply to a question" }, 409);
459
- return json({ error: "session is not a room member" }, 409);
460
- }
461
- touchActive(sessionID);
462
- const room = await read((svc) => svc.getRoom(roomId));
463
- if (!result.duplicate) void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
464
- return json(await roomPayload(room), 201);
465
- }
466
- const result = await appendRoomMessage(roomId, sessionID, text, isQuestion === true, clientMessageID);
467
- if (result.status !== "ok") {
468
- if (result.status === "missing") return json({ error: "room not found" }, 404);
469
- return json({ error: "session is not a room member" }, 409);
470
- }
471
- touchActive(sessionID); // 发送者活跃
472
- const room = await read((svc) => svc.getRoom(roomId));
473
- // ponytail: 即时唤起——仅 @ 点名成员时(核心需求)
474
- if (!result.duplicate) void wakeMentionedSessions(serveWakeUrl, roomId, room.name, text, sessionID, result.message);
475
- return json(await roomPayload(room), 201);
476
- }
477
- }
478
- const questions = p.match(/^\/rooms\/([^/]+)\/questions$/);
479
- if (req.method === "GET" && questions) {
480
- const roomId = decodeURIComponent(questions[1]!);
481
- const exists = await read((svc) => svc.listRooms().some((room) => room.id === roomId));
482
- if (!exists) return json({ error: "room not found" }, 404);
483
- return json({ questions: await readQuestions(roomId) });
484
- }
485
- const answer = p.match(/^\/rooms\/([^/]+)\/questions\/([^/]+)\/answers$/);
486
- if (req.method === "POST" && answer) {
487
- const roomId = decodeURIComponent(answer[1]!);
488
- const questionID = decodeURIComponent(answer[2]!);
489
- const body: unknown = await req.json();
490
- if (!body || typeof body !== "object" || Array.isArray(body)) return json({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
491
- const input = body as Record<string, unknown>;
492
- 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);
493
- const result = await answerQuestion(roomId, questionID, input.sessionID, input.text.trim());
494
- if (result.status === "missing") return json({ error: "room not found" }, 404);
495
- if (result.status === "question") return json({ error: "question not found" }, 404);
496
- if (result.status === "member") return json({ error: "session is not a room member" }, 409);
497
- if (result.status === "answered") return json({ error: "question already answered" }, 409);
498
- if (result.status !== "ok") return json({ error: "question not found" }, 404);
499
- touchActive(input.sessionID);
500
- const room = await read((svc) => svc.getRoom(roomId));
501
- void wakeMentionedSessions(serveWakeUrl, roomId, room.name, result.answer.text, input.sessionID, result.answer);
502
- return json({ questionID, answer: result.answer }, 201);
503
- }
504
- const g = p.match(/^\/rooms\/([^/]+)$/);
505
- if (g && req.method === "GET") {
506
- const room = await read((svc) =>
507
- svc.getRoom(decodeURIComponent(g[1]!)),
508
- );
509
- return json(await roomPayload(room));
510
- }
511
- const r = p.match(/^\/rooms\/([^/]+)\/registry$/);
512
- if (r && req.method === "GET") {
513
- // ponytail: session registry for the in-plugin wake watcher — lets the
514
- // plugin find which sessions have unread messages without polling every
515
- // session's inbox; host is included for the @-wake ownership gate
516
- const roomId = decodeURIComponent(r[1]!);
517
- const reg = await readState((svc, registry) => {
518
- const entries = registry[roomId] ?? {};
519
- return Object.fromEntries(
520
- Object.entries(entries).map(([sid, e]) => [
521
- sid,
522
- {
523
- name: e.name,
524
- membershipID: e.membershipID,
525
- protocol: e.protocol,
526
- receiverOwnerID: e.receiverOwnerID,
527
- lastReadTs: e.lastReadTs ?? 0,
528
- lastQueuedTs: e.lastQueuedTs ?? 0,
529
- host: e.host ?? "",
530
- directory: e.directory,
531
- roomKind: svc.getRoom(roomId).kind ?? "group",
532
- },
533
- ]),
534
- );
535
- });
536
- return json(reg);
537
- }
538
- return json({ error: "not found" }, 404);
539
- } catch (err) {
540
- if (err instanceof SyntaxError) return json({ error: "invalid JSON body" }, 400);
541
- if (err instanceof RoomError) {
542
- return json(
543
- { error: err.message },
544
- err.code === "ROOM_NOT_FOUND" ? 404 : err.code === "NOT_OWNER" ? 403 : 409,
545
- );
546
- }
547
- return json({ error: err instanceof Error ? err.message : String(err) }, 500);
548
- }
549
- }
550
-
1
+ // ponytail: central chat-room server. One HTTP service holding the
2
+ // authoritative room database (SQLite by default, PostgreSQL optional);
3
+ // plugins (central mode) talk to it via CHAT_ROOM_SERVER_URL. Optional bearer
4
+ // token (CHAT_ROOM_SERVER_TOKEN).
5
+ import { startServer } from "../src/platform/http-server.ts";
6
+ import { createApp } from "./app.ts";
7
+ import type { ChannelController } from "./channels.ts";
8
+ import { startRoomReminderScheduler } from "./room-reminders.ts";
9
+ import { loadServerBootstrap, startChannelLifecycle } from "./startup.ts";
10
+ import { wakeMentionedSessions } from "./wake.ts";
11
+
12
+ const bootstrap = await loadServerBootstrap();
13
+ // Set before the request handler runs; the controller reads its runtime lazily.
14
+ let channels: ChannelController | undefined;
15
+ const handle = createApp({
16
+ here: bootstrap.here,
17
+ token: bootstrap.token,
18
+ serveWakeUrl: bootstrap.serveWakeUrl,
19
+ channeld: () => channels,
20
+ });
551
21
  const config = {
552
- hostname,
553
- port,
22
+ hostname: bootstrap.hostname,
23
+ port: bootstrap.port,
554
24
  fetch: handle,
555
25
  idleTimeout: 60,
556
- maxRequestBodySize: Math.max(128 * 1024 * 1024, maxResourceBytes()),
26
+ maxRequestBodySize: bootstrap.maxRequestBodySize,
557
27
  };
558
-
559
28
  export default config;
560
29
 
30
+ // A missing Channel D config aborts startup; a failed adapter start only logs
31
+ // and leaves the forward routes absent. Signal shutdown drains channels first.
32
+ await startChannelLifecycle(bootstrap.settings, (controller) => {
33
+ channels = controller;
34
+ });
35
+
561
36
  // Bun auto-serves the default export when this file is the entrypoint. Node and
562
37
  // Deno have no such convention, so they start the shared adapter explicitly.
563
38
  if (import.meta.main && typeof Bun === "undefined") await startServer(config);
564
39
 
565
40
  console.log(
566
- `chat-room center listening on http://${displayHostname}:${port}${token ? " (token auth on)" : ""}`,
41
+ `chat-room center listening on http://${bootstrap.displayHostname}:${bootstrap.port}${bootstrap.token ? " (token auth on)" : ""}`,
567
42
  );
568
- startRoomReminderScheduler((roomId, roomName, text, message) => wakeMentionedSessions(serveWakeUrl, roomId, roomName, text, "", message));
569
- if (!token) {
43
+ startRoomReminderScheduler((roomId, roomName, text, message) => wakeMentionedSessions(bootstrap.serveWakeUrl, roomId, roomName, text, "", message));
44
+ if (!bootstrap.token) {
570
45
  console.warn(
571
46
  "chat-room center has NO token auth — set CHAT_ROOM_SERVER_TOKEN if this port is reachable from other hosts",
572
47
  );
573
- }
48
+ }