@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
@@ -52,7 +52,7 @@ Discuss shared questions in the room rather than opening private dialogs. Consol
52
52
  - For `join`, `name` is your own participant display name, not the room name. Use `roomId` to identify the room. For example, to join room `project-alpha` as `reviewer`, pass `{"action":"join","roomId":"<project-alpha-room-id>","name":"reviewer"}`. For `create`, `name` is the new room's name instead.
53
53
  - To rename yourself in a room, `leave` it and `join` it again with the new `name`. Earlier messages keep their original author name; in an approval room, rejoining may return pending until an administrator approves it.
54
54
  - Use `send` for messages, `poll` for full messages when needed, and `leave` to exit. A truncated preview is not the full message.
55
- - Tasks: `task_list` takes `roomId`; `task_create` takes `title` plus optional `description`, `assignee`, `dueDate`, `participants`, `conclusion`, and `steps`; `task_update` and `task_delete` take `taskId`, and update also needs at least one changed field. Steps are strings or `{ text, done }`, and object steps must always send the boolean. The creator or a room administrator may edit or delete a task and its steps; the assignee may change `status` (todo, doing, done) or toggle matching step completion. Use `task_list` to read creator, assignee, due date, participants, progress, and conclusion. Keep the room task list current yourself: create a task for multi-step work you take on, move it to `doing`, tick steps and add a conclusion as you finish them, and mark it `done` rather than leaving stale entries.
55
+ - Tasks: `task_list` takes `roomId`; `task_create` takes `title` plus optional `description`, `assignee`, `dueDate`, `participants`, `conclusion`, and `steps`; `task_update` and `task_delete` take `taskId`, and update also needs at least one changed field. Steps are strings or `{ text, done }`, and object steps must always send the boolean. The creator or a room administrator may edit or delete a task and its steps; the assignee may change `status` (todo, doing, done) or toggle matching step completion. Use `task_list` to read creator, assignee, due date, participants, progress, and conclusion. Keep the room task list current yourself: create a task for multi-step work you take on, move it to `doing`, tick steps and add a conclusion as you finish them, and mark it `done` rather than leaving stale entries. Manage it proactively rather than waiting to be asked: any work that spans several steps or lanes belongs in a task, with its steps and conclusion kept current. The task panel is a workspace view, not a property of one room: when it is open and the member switches rooms, it should stay open and show the new room's tasks.
56
56
  - Address the intended participant in the message text; use room broadcasts only for genuinely shared work.
57
57
  - Shared room tokens grant room access and management. A direct conversation is not private from other token holders.
58
58
 
@@ -17,6 +17,7 @@ import {
17
17
  import type { InboxItem } from "./center-inbox.ts";
18
18
  import { assertDeliveryLease } from "./session-delivery.ts";
19
19
  import { formatTasks, taskFields, validateTaskFields, type Task } from "../agent/task-tool.ts";
20
+ import type { CatchUpOptions, CatchUpPage } from "../protocol/addressing.ts";
20
21
  export { queueAdmissionId } from "./queue.ts";
21
22
  export { createQueueTransport, sendAsyncNotification, sendQueue } from "./queue-transport.ts";
22
23
  export type { QueueTransport, PushResult } from "./queue-transport.ts";
@@ -132,6 +133,41 @@ export async function request(
132
133
  return data;
133
134
  }
134
135
 
136
+ /** Fetch one message by stable ID; a recalled message returns the server tombstone. */
137
+ export async function getMessage(opts: CenterOpts, roomId: string, messageId: string, sessionID: string): Promise<Json> {
138
+ return request(
139
+ opts,
140
+ `/rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}?sessionID=${encodeURIComponent(sessionID)}`,
141
+ "GET",
142
+ );
143
+ }
144
+
145
+ export type { CatchUpOptions, CatchUpPage };
146
+
147
+ /** Page forward from a persisted seq. Strictly read-only: no receipts, read
148
+ * watermark, wake, or model call happens on this path. */
149
+ export async function catchUp(
150
+ opts: CenterOpts,
151
+ roomId: string,
152
+ params: CatchUpOptions,
153
+ ): Promise<CatchUpPage> {
154
+ const { sessionID, afterSeq, limit } = params;
155
+ if (afterSeq !== undefined && (!Number.isSafeInteger(afterSeq) || afterSeq < 0)) {
156
+ throw new Error("afterSeq must be a non-negative integer");
157
+ }
158
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)) {
159
+ throw new Error("limit must be between 1 and 200");
160
+ }
161
+ const query = new URLSearchParams({ sessionID });
162
+ if (afterSeq !== undefined) query.set("afterSeq", String(afterSeq));
163
+ if (limit !== undefined) query.set("limit", String(limit));
164
+ return (await request(
165
+ opts,
166
+ `/rooms/${encodeURIComponent(roomId)}/catch-up?${query}`,
167
+ "GET",
168
+ )) as unknown as CatchUpPage;
169
+ }
170
+
135
171
  export async function markQueued(
136
172
  opts: CenterOpts,
137
173
  roomId: string,
@@ -163,6 +199,11 @@ export async function centerAction(
163
199
  name?: string;
164
200
  roomId?: string;
165
201
  messageId?: string;
202
+ parentMessageId?: string;
203
+ replyToMessageID?: string;
204
+ clientMessageID?: string;
205
+ afterSeq?: number;
206
+ limit?: number;
166
207
  text?: string;
167
208
  announcementName?: string;
168
209
  content?: string;
@@ -335,6 +376,26 @@ export async function centerAction(
335
376
  await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks/${encodeURIComponent(args.taskId)}`, "DELETE", { sessionID });
336
377
  return `task deleted: ${args.taskId}`;
337
378
  }
379
+ case "get_message": {
380
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
381
+ if (!args.messageId) return "error: messageId is required; use the full message ID returned by send, poll, or catch_up";
382
+ return JSON.stringify(await getMessage(opts, args.roomId, args.messageId, sessionID));
383
+ }
384
+ case "catch_up": {
385
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
386
+ if (args.afterSeq !== undefined && (!Number.isSafeInteger(args.afterSeq) || args.afterSeq < 0)) {
387
+ return "error: afterSeq must be a non-negative integer";
388
+ }
389
+ if (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1 || args.limit > 200)) {
390
+ return "error: limit must be between 1 and 200";
391
+ }
392
+ const page = await catchUp(opts, args.roomId, {
393
+ sessionID,
394
+ ...(args.afterSeq === undefined ? {} : { afterSeq: args.afterSeq }),
395
+ ...(args.limit === undefined ? {} : { limit: args.limit }),
396
+ });
397
+ return JSON.stringify(page);
398
+ }
338
399
  case "send": {
339
400
  if (!args.roomId) {
340
401
  return "error: roomId is required; use a room UUID from the room list, not the room name";
@@ -346,7 +407,16 @@ export async function centerAction(
346
407
  opts,
347
408
  `/rooms/${encodeURIComponent(args.roomId)}/messages`,
348
409
  "POST",
349
- { sessionID, text: args.text.trim(), ...(args.isQuestion ? { isQuestion: true } : {}) },
410
+ {
411
+ sessionID,
412
+ text: args.text.trim(),
413
+ ...(args.isQuestion ? { isQuestion: true } : {}),
414
+ // replyToMessageID stays for old callers; parentMessageId is the alias
415
+ // the server and the newer agent surfaces use.
416
+ ...(args.replyToMessageID ? { replyToMessageID: args.replyToMessageID } : {}),
417
+ ...(args.parentMessageId ? { parentMessageId: args.parentMessageId } : {}),
418
+ ...(args.clientMessageID ? { clientMessageID: args.clientMessageID } : {}),
419
+ },
350
420
  );
351
421
  const parsed = toRoom(room);
352
422
  const sentID = [...parsed.messages].reverse()
@@ -3,49 +3,14 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { parse as parseYaml } from "yaml";
5
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
- };
6
+ import type {
7
+ ChannelDSettings,
8
+ ClientSettings,
9
+ RoomFileConfig,
10
+ ServerSettings,
11
+ } from "../protocol/config.ts";
34
12
 
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
- };
13
+ export type { ChannelDSettings, ClientSettings, RoomFileConfig, ServerSettings };
49
14
 
50
15
  const FILE_NAMES = ["chatroom.json", "chatroom.jsonc", "chatroom.yaml", "chatroom.yml"] as const;
51
16
  const PEER_NAME = /^[A-Za-z0-9_-]{1,32}$/;
@@ -78,6 +43,16 @@ function optionalBoolean(value: unknown, where: string): boolean | undefined {
78
43
  return value;
79
44
  }
80
45
 
46
+ function parseChanneld(value: unknown): NonNullable<RoomFileConfig["server"]>["channeld"] {
47
+ const raw = asRecord(value, "server.channeld");
48
+ if (!raw) return undefined;
49
+ return {
50
+ enabled: optionalBoolean(raw.enabled, "server.channeld.enabled"),
51
+ config: optionalString(raw.config, "server.channeld.config"),
52
+ stateFile: optionalString(raw.stateFile, "server.channeld.stateFile"),
53
+ };
54
+ }
55
+
81
56
  function parseServer(value: unknown): RoomFileConfig["server"] {
82
57
  const raw = asRecord(value, "server");
83
58
  if (!raw) return undefined;
@@ -96,6 +71,7 @@ function parseServer(value: unknown): RoomFileConfig["server"] {
96
71
  stateDir: optionalString(raw.stateDir, "server.stateDir"),
97
72
  wakeServeUrl: optionalString(raw.wakeServeUrl, "server.wakeServeUrl"),
98
73
  maxFileSizeMb,
74
+ channeld: parseChanneld(raw.channeld),
99
75
  };
100
76
  }
101
77
 
@@ -274,6 +250,12 @@ export function resolveServerSettings(file: RoomFileConfig | null, env: NodeJS.P
274
250
  if (maxFileSizeMb !== undefined && (!Number.isFinite(maxFileSizeMb) || maxFileSizeMb <= 0)) {
275
251
  throw new Error("CHAT_ROOM_MAX_FILE_SIZE_MB must be a positive finite number");
276
252
  }
253
+ // A configured Channel D config implies opt-in; CHAT_ROOM_CHANNELD=0 still forces it off.
254
+ const channeldRaw = envValue(env, "CHAT_ROOM_CHANNELD");
255
+ const channeldConfig = envValue(env, "CHAT_ROOM_CHANNELD_CONFIG") ?? file?.server?.channeld?.config;
256
+ const channeldEnabled = channeldRaw === undefined
257
+ ? file?.server?.channeld?.enabled ?? Boolean(channeldConfig)
258
+ : channeldRaw === "1" || channeldRaw === "true";
277
259
  return {
278
260
  host: envValue(env, "CHAT_ROOM_SERVER_HOST") ?? envValue(env, "HOST") ?? file?.server?.host ?? "0.0.0.0",
279
261
  port,
@@ -281,6 +263,11 @@ export function resolveServerSettings(file: RoomFileConfig | null, env: NodeJS.P
281
263
  stateDir: envValue(env, "CHAT_ROOM_STATE_DIR") ?? file?.server?.stateDir,
282
264
  wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.server?.wakeServeUrl ?? "",
283
265
  maxFileSizeMb,
266
+ channeld: {
267
+ enabled: channeldEnabled,
268
+ config: channeldConfig,
269
+ stateFile: file?.server?.channeld?.stateFile,
270
+ },
284
271
  };
285
272
  }
286
273
 
@@ -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
+ }
@@ -0,0 +1,21 @@
1
+ // Wire shapes shared by center clients and server-side addressing routes.
2
+ // Keep this file type-only so both Bun and Node consumers can import it
3
+ // without pulling runtime code into a plugin bundle.
4
+
5
+ export type MessageRef = { id: string; seq: number };
6
+
7
+ export type CatchUpOptions = {
8
+ sessionID: string;
9
+ afterSeq?: number;
10
+ limit?: number;
11
+ };
12
+
13
+ export type CatchUpPage = {
14
+ messages: Array<Record<string, unknown>>;
15
+ nextCursor: number;
16
+ hasMore: boolean;
17
+ unreadMentions: MessageRef[];
18
+ unreadMentionCount: number;
19
+ unansweredQuestions: MessageRef[];
20
+ unansweredQuestionCount: number;
21
+ };
@@ -0,0 +1,58 @@
1
+ // Configuration shapes shared by the server, CLI, and center clients.
2
+ // This module is type-only so importing it never pulls in file I/O.
3
+
4
+ export type ChannelDSettings = {
5
+ enabled: boolean;
6
+ config?: string;
7
+ stateFile?: string;
8
+ };
9
+
10
+ export type ServerSettings = {
11
+ host: string;
12
+ port: string;
13
+ token?: string;
14
+ stateDir?: string;
15
+ wakeServeUrl: string;
16
+ maxFileSizeMb?: number;
17
+ channeld: ChannelDSettings;
18
+ };
19
+
20
+ export type ClientSettings = {
21
+ url: string;
22
+ token: string;
23
+ wakeServeUrl: string;
24
+ };
25
+
26
+ // A shared, human-editable configuration file. Environment variables still
27
+ // win over the file so a deployment can override one value without editing it.
28
+ export type RoomFileConfig = {
29
+ url?: string;
30
+ token?: string;
31
+ server?: {
32
+ host?: string;
33
+ port?: number;
34
+ token?: string;
35
+ stateDir?: string;
36
+ wakeServeUrl?: string;
37
+ maxFileSizeMb?: number;
38
+ channeld?: {
39
+ enabled?: boolean;
40
+ config?: string;
41
+ stateFile?: string;
42
+ };
43
+ };
44
+ client?: {
45
+ url?: string;
46
+ token?: string;
47
+ participant?: string;
48
+ wakeServeUrl?: string;
49
+ delivery?: boolean;
50
+ deliveryIntervalMs?: number;
51
+ requestTimeoutMs?: number;
52
+ codexBin?: string;
53
+ };
54
+ p2p?: {
55
+ enabled?: boolean;
56
+ peers?: Record<string, { url: string; token?: string }>;
57
+ };
58
+ };
@@ -0,0 +1,51 @@
1
+ // Room domain shapes shared by the service layer, center clients, and tests.
2
+ // This module is type-only; the RoomService behavior stays in src/rooms.
3
+
4
+ export type Participant = {
5
+ id: string;
6
+ name: string;
7
+ joinedAt: number;
8
+ };
9
+
10
+ export type Message = {
11
+ id: string;
12
+ roomId: string;
13
+ senderId: string;
14
+ senderSessionID?: string;
15
+ text: string;
16
+ createdAt: number;
17
+ isQuestion?: boolean;
18
+ answerToMessageID?: string;
19
+ answeredByMessageID?: string;
20
+ // Soft recall: the original text stays in storage for member reveal, while
21
+ // read paths expose the message as a tombstone.
22
+ recalledAt?: number;
23
+ recalledBy?: string;
24
+ };
25
+
26
+ export type JoinPolicy = "open" | "approval";
27
+
28
+ export type Room = {
29
+ id: string;
30
+ name: string;
31
+ description?: string;
32
+ // Absent means "open" so rooms created before approvals existed stay open.
33
+ joinPolicy?: JoinPolicy;
34
+ ownerId: string;
35
+ // Server-issued membership binding for the owner and the explicitly chosen successor.
36
+ // Display names remain the public identity; the membership IDs guard against name reuse.
37
+ ownerMembershipID?: string;
38
+ successorId?: string;
39
+ successorMembershipID?: string;
40
+ // Humans authorized by the owner or another admin; the owner is always an admin.
41
+ adminIds?: string[];
42
+ // Server-issued membership bindings matching adminIds, so a same-name session
43
+ // does not inherit delegation. Missing for legacy rooms; names are the fallback.
44
+ adminMembershipIDs?: string[];
45
+ participants: Map<string, Participant>;
46
+ messages: Message[];
47
+ createdAt: number;
48
+ kind?: "group" | "direct";
49
+ directSessionIDs?: string[];
50
+ directPair?: string;
51
+ };
@@ -3,6 +3,7 @@ import { promises as fs } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { databasePath, readState } from "../state/store.ts";
5
5
  import { getResource, listResources, putResource, removeResource, type StoredResource } from "../state/sqlite-state.ts";
6
+ import { resourceStorage, resourceStorageKey, StorageConflictError, type ResourceStorage } from "./storage.ts";
6
7
 
7
8
  export type Resource = StoredResource;
8
9
  export class ResourceError extends Error {
@@ -59,7 +60,7 @@ async function waitForResource(roomID: string, id: string): Promise<Resource | u
59
60
  return undefined;
60
61
  }
61
62
 
62
- export async function uploadResource(roomID: string, filename: string, body: ReadableStream<Uint8Array>, limitBytes: number, uploader?: { sessionID: string; name: string }, requestedID?: string): Promise<Resource> {
63
+ export async function uploadResource(roomID: string, filename: string, body: ReadableStream<Uint8Array>, limitBytes: number, uploader?: { sessionID: string; name: string }, requestedID?: string, storage?: ResourceStorage): Promise<Resource> {
63
64
  if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
64
65
  if (requestedID !== undefined && !uuid.test(requestedID)) throw new ResourceError(400, "invalid resource id");
65
66
  if (!Number.isSafeInteger(limitBytes) || limitBytes <= 0) throw new Error("limitBytes must be a positive safe integer");
@@ -71,13 +72,14 @@ export async function uploadResource(roomID: string, filename: string, body: Rea
71
72
  const existing = await getResource(databasePath(), roomID, requestedID);
72
73
  if (existing) return replay(existing, name, uploader);
73
74
  }
75
+ const store = storage ?? resourceStorage();
74
76
  const dir = roomDirectory(roomID);
75
77
  await fs.mkdir(dir, { recursive: true, mode: 0o700 });
76
78
  const id = requestedID ?? randomUUID();
79
+ const key = resourceStorageKey(roomID, id);
77
80
  const temp = path.join(dir, `${id}.${randomUUID()}.tmp`);
78
- const dest = resourcePath({ id, roomID } as Resource);
79
81
  let handle: Awaited<ReturnType<typeof fs.open>> | undefined;
80
- let linked = false;
82
+ let stored = false;
81
83
  try {
82
84
  handle = await fs.open(temp, "wx", 0o600);
83
85
  const reader = body.getReader();
@@ -105,16 +107,21 @@ export async function uploadResource(roomID: string, filename: string, body: Rea
105
107
  } finally { reader.releaseLock(); }
106
108
  const resource: Resource = { id, roomID, name, mimeType: mime(prefix.subarray(0, prefixSize)), size, createdAt: Date.now(), ...(uploader ? { uploaderSessionID: uploader.sessionID, uploaderName: uploader.name } : {}) };
107
109
  await handle.close(); handle = undefined;
108
- // link() creates the final name only if absent; rename() would replace another attempt's file.
109
- try { await fs.link(temp, dest); linked = true; }
110
- catch (error) {
110
+ try {
111
+ // Local mode links the temp file into place; S3 uploads it and keeps a cache
112
+ // copy when configured. Both reject an existing key instead of overwriting.
113
+ await store.put(key, temp, resource.mimeType);
114
+ stored = true;
115
+ } catch (error) {
116
+ if (error instanceof StorageConflictError) {
117
+ const existing = requestedID ? await waitForResource(roomID, id) : undefined;
118
+ if (existing) return replay(existing, name, uploader);
119
+ throw new ResourceError(409, "resource id conflict");
120
+ }
121
+ throw error;
122
+ } finally {
111
123
  await fs.rm(temp, { force: true }).catch(() => {});
112
- if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
113
- const existing = requestedID ? await waitForResource(roomID, id) : undefined;
114
- if (existing) return replay(existing, name, uploader);
115
- throw new ResourceError(409, "resource id conflict");
116
124
  }
117
- await fs.rm(temp, { force: true }).catch(() => {});
118
125
  try { if (!await putResource(databasePath(), resource)) throw new ResourceError(404, "room not found"); }
119
126
  catch (error) {
120
127
  const existing = requestedID ? await getResource(databasePath(), roomID, id).catch(() => undefined) : undefined;
@@ -125,7 +132,7 @@ export async function uploadResource(roomID: string, filename: string, body: Rea
125
132
  } catch (error) {
126
133
  await handle?.close().catch(() => {});
127
134
  await fs.rm(temp, { force: true }).catch(() => {});
128
- if (linked) await fs.rm(dest, { force: true }).catch(() => {});
135
+ if (stored) await store.delete(key).catch(() => {});
129
136
  throw error;
130
137
  }
131
138
  }
@@ -142,17 +149,20 @@ export async function findResource(roomID: string, id: string): Promise<Resource
142
149
  if (!uuid.test(id)) return undefined;
143
150
  return getResource(databasePath(), roomID, id);
144
151
  }
145
- export async function deleteResource(roomID: string, id: string): Promise<boolean> {
152
+ export async function openResource(resource: Pick<Resource, "id" | "roomID">, start?: number, end?: number, storage?: ResourceStorage) {
153
+ return (storage ?? resourceStorage()).open(resourceStorageKey(resource.roomID, resource.id), start, end);
154
+ }
155
+ export async function deleteResource(roomID: string, id: string, storage?: ResourceStorage): Promise<boolean> {
146
156
  const resource = await findResource(roomID, id);
147
157
  if (!resource) return false;
148
158
  await removeResource(databasePath(), roomID, id);
149
- await fs.rm(resourcePath(resource), { force: true });
159
+ await (storage ?? resourceStorage()).delete(resourceStorageKey(resource.roomID, resource.id));
150
160
  return true;
151
161
  }
152
- export async function removeRoomResources(roomID: string): Promise<void> {
162
+ export async function removeRoomResources(roomID: string, storage?: ResourceStorage): Promise<void> {
153
163
  if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
154
164
  if (await readState((service) => service.listRooms().some((room) => room.id === roomID))) {
155
165
  throw new ResourceError(409, "room still exists; resource cleanup was not performed");
156
166
  }
157
- await fs.rm(roomDirectory(roomID), { recursive: true, force: true });
167
+ await (storage ?? resourceStorage()).deletePrefix(roomID);
158
168
  }