@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
@@ -0,0 +1,557 @@
1
+ // Channel D integration: opt-in forwarding from a room message to an external
2
+ // IM endpoint through the channeld relay host. The host keeps its own SQLite
3
+ // file, so disabling the feature (or deleting channeld.sqlite) is a full rollback.
4
+ import { mkdirSync, readFileSync } from "node:fs";
5
+ import { randomUUID } from "node:crypto";
6
+ import path from "node:path";
7
+ import { parse as parseYaml } from "yaml";
8
+ import type { ServerSettings } from "../src/config/file-config.ts";
9
+ import {
10
+ adminMessage,
11
+ persistRoomSettings,
12
+ readAdminBody,
13
+ type ChannelSettingsPatch,
14
+ } from "./channel-settings.ts";
15
+ import { handleIntegrationAdmin } from "./channel-integration.ts";
16
+ import { databasePath, writeState } from "../src/state/store.ts";
17
+ import { openStateDatabase } from "../src/state/sqlite-state.ts";
18
+ import { writeSqliteStateWithDatabase } from "../src/state/sqlite-state.ts";
19
+ import {
20
+ parseConfig,
21
+ type ChannelConfig,
22
+ type RuleTarget,
23
+ } from "../packages/chat-room-channeld/src/config.ts";
24
+ import { createHost, type ChannelHost, type SpawnAdapter } from "../packages/chat-room-channeld/src/host.ts";
25
+ import { validateTargets } from "../packages/chat-room-channeld/src/host-helpers.ts";
26
+ import { EVENT_SCHEMA_VERSION, type Endpoint, type IngestEvent } from "../packages/chat-room-channeld/src/protocol.ts";
27
+ import { matchRules, targetKey } from "../packages/chat-room-channeld/src/rules.ts";
28
+ import { inboundRoomText, matchInboundRoutes } from "../packages/chat-room-channeld/src/inbound.ts";
29
+ import {
30
+ isTerminalDeliveryState,
31
+ readChannelStats,
32
+ type DeliveryRow,
33
+ type ReceiptRow,
34
+ } from "../packages/chat-room-channeld/src/state.ts";
35
+ import { jsonObject } from "./json-body.ts";
36
+
37
+ export type ChannelsRuntime = {
38
+ host: ChannelHost;
39
+ config: ChannelConfig;
40
+ };
41
+
42
+ export type ChannelDeps = {
43
+ spawnAdapter?: SpawnAdapter;
44
+ deliveryIntervalMs?: number;
45
+ };
46
+
47
+ export type { ChannelSettingsPatch } from "./channel-settings.ts";
48
+ export type ChannelControllerDeps = ChannelDeps & {
49
+ env?: NodeJS.ProcessEnv;
50
+ persistSettings?: (next: ChannelSettingsPatch) => Promise<boolean> | boolean;
51
+ };
52
+ export interface ChannelController {
53
+ readonly runtime: ChannelsRuntime | undefined;
54
+ readonly enabled: boolean;
55
+ start(): Promise<void>;
56
+ stop(): Promise<void>;
57
+ handle(req: Request, url: URL): Promise<Response | undefined>;
58
+ }
59
+
60
+ // A disabled mid-send account records terminal `unknown` without a receipt.
61
+ export type DeliveryResultCallback = (
62
+ event: IngestEvent | undefined,
63
+ delivery: DeliveryRow,
64
+ receipt: ReceiptRow | undefined,
65
+ ) => void;
66
+
67
+ const json = (body: unknown, status = 200) => Response.json(body, { status });
68
+ const IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
69
+ const MAX_SESSION = 128;
70
+ const MAX_REQUEST_ID = 200;
71
+
72
+ /** Load a channeld YAML config, with the center owning the state file path. */
73
+ function loadChannelConfig(file: string, stateFile: string): ChannelConfig {
74
+ let text: string;
75
+ try {
76
+ text = readFileSync(file, "utf8");
77
+ } catch {
78
+ throw new Error(`channeld config: cannot read ${file}`);
79
+ }
80
+ let raw: unknown;
81
+ try {
82
+ raw = parseYaml(text);
83
+ } catch {
84
+ throw new Error(`channeld config: ${file} is not valid YAML/JSON`);
85
+ }
86
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
87
+ throw new Error(`channeld config: ${file} must contain a mapping`);
88
+ }
89
+ // Override any YAML stateFile: a stale path must never point at the room database.
90
+ return parseConfig({ ...(raw as Record<string, unknown>), stateFile });
91
+ }
92
+
93
+ function resolveChannelStateFile(stateDir: string, configured: string | undefined): string {
94
+ const file = configured
95
+ ? (path.isAbsolute(configured) ? configured : path.resolve(stateDir, configured))
96
+ : path.join(stateDir, "channeld.sqlite");
97
+ if (path.resolve(file) === path.join(stateDir, "chat-room.sqlite")) {
98
+ throw new Error("chatroom config: server.channeld.stateFile must not be the room database");
99
+ }
100
+ return file;
101
+ }
102
+
103
+ function deliverySystemMessage(delivery: DeliveryRow, receipt: ReceiptRow | undefined): string {
104
+ if (delivery.state === "sent") return `Forwarded to ${delivery.target}`;
105
+ const raw = receipt?.detail || delivery.lastError || receipt?.state || delivery.state;
106
+ // Keep the system row inside the 5000-char message limit even for a huge adapter detail.
107
+ const reason = String(raw).replace(/[\r\n;]+/g, " ").trim().slice(0, 500) || delivery.state;
108
+ return `Forward to ${delivery.target} failed: ${reason}`;
109
+ }
110
+
111
+ /**
112
+ * Build the terminal-delivery publisher. One system message per delivery, and
113
+ * only for a forward event that came from this center.
114
+ */
115
+ export function createDeliveryResultHandler(): DeliveryResultCallback {
116
+ const notified = new Set<string>();
117
+ return (event, delivery, receipt) => {
118
+ if (!isTerminalDeliveryState(delivery.state)) return;
119
+ if (notified.has(delivery.deliveryId)) return;
120
+ const source = event?.source;
121
+ if (
122
+ event?.kind !== "message.forward_requested"
123
+ || source?.platform !== "chatroom"
124
+ || source.accountId !== "center"
125
+ ) return;
126
+ notified.add(delivery.deliveryId);
127
+ const text = deliverySystemMessage(delivery, receipt);
128
+ void writeState((svc) => {
129
+ svc.addEvent(source.roomId, text);
130
+ }).catch((error: unknown) => {
131
+ console.warn(`[chat-room] could not write the channeld result message: ${error instanceof Error ? error.message : String(error)}`);
132
+ });
133
+ };
134
+ }
135
+
136
+ /**
137
+ * Build the inbound-room notifier. One room message is appended per committed
138
+ * event and route. The marker table and message append share one SQLite
139
+ * transaction, so a retry after a transport failure cannot duplicate a room
140
+ * message; a failed append rolls the channel event back in the host so Feishu
141
+ * retries instead of ACKing a lost notification. Inbound events never match
142
+ * outbound rules.
143
+ */
144
+ export function createInboundRelay(config: ChannelConfig): {
145
+ onIngestCommitted: (event: IngestEvent) => Promise<void>;
146
+ notificationOnly: (event: IngestEvent) => boolean;
147
+ } {
148
+ return {
149
+ notificationOnly: (event) => matchInboundRoutes(config, event).length > 0,
150
+ onIngestCommitted: async (event) => {
151
+ for (const route of matchInboundRoutes(config, event)) {
152
+ const text = inboundRoomText(event, route);
153
+ if (!text) continue;
154
+ await writeSqliteStateWithDatabase(databasePath(), (svc, _registry, db) => {
155
+ db.exec(
156
+ `CREATE TABLE IF NOT EXISTS channel_inbound_relays (
157
+ event_id TEXT NOT NULL,
158
+ room_id TEXT NOT NULL,
159
+ relayed_at INTEGER NOT NULL,
160
+ PRIMARY KEY (event_id, room_id)
161
+ )`,
162
+ );
163
+ const inserted = db.query(
164
+ "INSERT OR IGNORE INTO channel_inbound_relays (event_id, room_id, relayed_at) VALUES (?, ?, ?)",
165
+ ).run(event.eventId, route.to.room, Date.now());
166
+ if (Number(inserted.changes) === 0) return;
167
+ svc.addEvent(route.to.room, text);
168
+ });
169
+ }
170
+ },
171
+ };
172
+ }
173
+
174
+ /** Parse and fully validate a config before an old runtime is touched. */
175
+ function loadValidChannelConfig(settings: ServerSettings): ChannelConfig {
176
+ const configPath = settings.channeld.config;
177
+ if (!configPath) {
178
+ throw new Error(
179
+ "chatroom config: server.channeld is enabled but no config file is set (server.channeld.config or CHAT_ROOM_CHANNELD_CONFIG)",
180
+ );
181
+ }
182
+ const stateDir = path.dirname(databasePath());
183
+ const stateFile = resolveChannelStateFile(stateDir, settings.channeld.stateFile);
184
+ const config = loadChannelConfig(configPath, stateFile);
185
+ validateTargets(config);
186
+ return config;
187
+ }
188
+
189
+ async function activateRuntime(
190
+ config: ChannelConfig,
191
+ deps: ChannelDeps,
192
+ ): Promise<ChannelsRuntime | undefined> {
193
+ mkdirSync(path.dirname(config.stateFile), { recursive: true, mode: 0o700 });
194
+ const inbound = createInboundRelay(config);
195
+ const host = createHost(config, {
196
+ spawnAdapter: deps.spawnAdapter,
197
+ deliveryIntervalMs: deps.deliveryIntervalMs,
198
+ onDeliveryResult: createDeliveryResultHandler(),
199
+ ...inbound,
200
+ });
201
+ try {
202
+ await host.start();
203
+ } catch (error) {
204
+ console.warn(`[chat-room] channeld disabled: ${error instanceof Error ? error.message : String(error)}`);
205
+ // A partially started host may still own adapters or the state file.
206
+ await stopChannels({ host, config });
207
+ return undefined;
208
+ }
209
+ return { host, config };
210
+ }
211
+
212
+ /**
213
+ * Start the relay host when `server.channeld.enabled` is on. A missing or
214
+ * invalid config fails startup; an adapter start failure only disables channels.
215
+ */
216
+ export async function startChannels(
217
+ settings: ServerSettings,
218
+ deps: ChannelDeps = {},
219
+ ): Promise<ChannelsRuntime | undefined> {
220
+ if (!settings.channeld?.enabled) return undefined;
221
+ return activateRuntime(loadValidChannelConfig(settings), deps);
222
+ }
223
+
224
+ export async function stopChannels(
225
+ runtime: ChannelsRuntime | undefined,
226
+ options: { abortInFlight?: boolean } = {},
227
+ ): Promise<void> {
228
+ if (!runtime) return;
229
+ try {
230
+ await runtime.host.stop(options);
231
+ } catch (error) {
232
+ console.warn(`[chat-room] channeld stop failed: ${error instanceof Error ? error.message : String(error)}`);
233
+ }
234
+ }
235
+
236
+ export function createChannelController(
237
+ initial: ServerSettings,
238
+ deps: ChannelControllerDeps = {},
239
+ ): ChannelController {
240
+ const env = deps.env ?? process.env;
241
+ let settings: ServerSettings = { ...initial, channeld: { ...initial.channeld } };
242
+ let runtime: ChannelsRuntime | undefined;
243
+ let queue: Promise<unknown> = Promise.resolve();
244
+
245
+ // Admin mutations run one at a time so a reload cannot race enable/disable.
246
+ const serial = <T>(fn: () => Promise<T>): Promise<T> => {
247
+ const run = queue.then(fn, fn);
248
+ queue = run.then(() => undefined, () => undefined);
249
+ return run;
250
+ };
251
+ const persist = async (next: ChannelSettingsPatch): Promise<boolean> => {
252
+ try {
253
+ if (deps.persistSettings) return await deps.persistSettings(next);
254
+ return await persistRoomSettings(env, next);
255
+ } catch {
256
+ return false;
257
+ }
258
+ };
259
+ const withConfig = (config: string | undefined): ServerSettings =>
260
+ config ? { ...settings, channeld: { ...settings.channeld, enabled: true, config } } : settings;
261
+
262
+ const disableCore = async (): Promise<Response> => {
263
+ const old = runtime;
264
+ runtime = undefined;
265
+ await stopChannels(old, { abortInFlight: true });
266
+ settings = { ...settings, channeld: { ...settings.channeld, enabled: false } };
267
+ const persisted = await persist({ enabled: false, config: settings.channeld.config });
268
+ return json({ enabled: false, persisted, restartRequired: !persisted });
269
+ };
270
+
271
+ const activateCore = async (configPath: string): Promise<Response> => {
272
+ let config: ChannelConfig;
273
+ try {
274
+ config = loadValidChannelConfig(withConfig(configPath));
275
+ } catch (error) {
276
+ return json({ error: adminMessage(error) }, 400);
277
+ }
278
+ const previousRuntime = runtime;
279
+ const previous = previousRuntime ? { settings, config: previousRuntime.config } : undefined;
280
+ runtime = undefined;
281
+ if (previousRuntime) await stopChannels(previousRuntime, { abortInFlight: true });
282
+
283
+ let next: ChannelsRuntime | undefined;
284
+ try {
285
+ next = await activateRuntime(config, deps);
286
+ } catch (error) {
287
+ console.warn(`[chat-room] relay restart failed: ${adminMessage(error)}`);
288
+ }
289
+ if (next) {
290
+ runtime = next;
291
+ settings = withConfig(configPath);
292
+ const persisted = await persist({ enabled: true, config: configPath });
293
+ return json({ enabled: true, persisted, restartRequired: !persisted });
294
+ }
295
+
296
+ if (previous) {
297
+ let restored: ChannelsRuntime | undefined;
298
+ try {
299
+ restored = await activateRuntime(previous.config, deps);
300
+ } catch (error) {
301
+ console.warn(`[chat-room] relay restore failed: ${adminMessage(error)}`);
302
+ }
303
+ if (restored) {
304
+ runtime = restored;
305
+ settings = previous.settings;
306
+ return json({
307
+ error: "relay failed to start; previous configuration restored",
308
+ enabled: true,
309
+ restored: true,
310
+ }, 502);
311
+ }
312
+ }
313
+ settings = { ...settings, channeld: { ...settings.channeld, enabled: false } };
314
+ const persisted = await persist({ enabled: false, config: settings.channeld.config });
315
+ return json({
316
+ error: previous
317
+ ? "relay failed to start and the previous runtime could not be restored"
318
+ : "relay failed to start",
319
+ enabled: false,
320
+ persisted,
321
+ restartRequired: !persisted,
322
+ }, 500);
323
+ };
324
+
325
+ const handle = async (req: Request, url: URL): Promise<Response | undefined> => {
326
+ const adminPath = url.pathname === "/channeld/reload"
327
+ || url.pathname === "/channeld/enable"
328
+ || url.pathname === "/channeld/disable";
329
+ const integrationPath = url.pathname === "/channeld/plugins"
330
+ || url.pathname === "/channeld/integration";
331
+ if (!adminPath && !integrationPath) return channelRoutes(req, url, runtime);
332
+ if (env.CHATROOM_ALLOW_ADMIN !== "true") return undefined;
333
+ if (integrationPath) {
334
+ return serial(() => handleIntegrationAdmin(req, url, {
335
+ enabled: () => Boolean(runtime),
336
+ runtime: () => runtime,
337
+ activate: activateCore,
338
+ disable: disableCore,
339
+ }));
340
+ }
341
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
342
+
343
+ if (url.pathname === "/channeld/disable") return serial(disableCore);
344
+
345
+ const body = await readAdminBody(req);
346
+ if (!body.ok) return json({ error: "invalid request body" }, 400);
347
+ const configPath = body.config ?? settings.channeld.config;
348
+ if (!configPath) {
349
+ return json({ error: "relay has no configuration path; provide one with {config}" }, 400);
350
+ }
351
+ if (url.pathname === "/channeld/reload" && !runtime) {
352
+ return json({ error: "relay is disabled; enable it first" }, 409);
353
+ }
354
+ if (url.pathname === "/channeld/enable" && runtime && (!body.config || body.config === settings.channeld.config)) {
355
+ const persisted = await persist({ enabled: true, config: settings.channeld.config });
356
+ return json({ enabled: true, persisted, restartRequired: !persisted });
357
+ }
358
+ return serial(() => activateCore(configPath));
359
+ };
360
+
361
+ return {
362
+ get runtime() {
363
+ return runtime;
364
+ },
365
+ get enabled() {
366
+ return Boolean(runtime);
367
+ },
368
+ start: () => serial(async () => {
369
+ runtime = await startChannels(settings, deps);
370
+ }),
371
+ stop: () => serial(async () => {
372
+ const old = runtime;
373
+ runtime = undefined;
374
+ await stopChannels(old);
375
+ }),
376
+ handle,
377
+ };
378
+ }
379
+
380
+ function parseTarget(value: unknown): RuleTarget | undefined {
381
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
382
+ const raw = value as Record<string, unknown>;
383
+ if (
384
+ typeof raw.platform !== "string" || !IDENTIFIER.test(raw.platform)
385
+ || typeof raw.account !== "string" || !IDENTIFIER.test(raw.account)
386
+ || typeof raw.room !== "string" || !IDENTIFIER.test(raw.room)
387
+ ) return undefined;
388
+ return { platform: raw.platform, account: raw.account, room: raw.room };
389
+ }
390
+
391
+ type ForwardableMessage = { text: string; createdAt: number; parentMessageId?: string };
392
+
393
+ /** A malformed percent escape must not become a 500. */
394
+ function decodeSegment(segment: string): string | undefined {
395
+ try {
396
+ return decodeURIComponent(segment);
397
+ } catch {
398
+ return undefined;
399
+ }
400
+ }
401
+
402
+ /** Registry + participant join: a stale registry row after a kick is not a member. */
403
+ async function memberName(roomId: string, sessionID: string): Promise<string | undefined> {
404
+ const db = await openStateDatabase(databasePath());
405
+ const row = db.query(
406
+ `SELECT g.name FROM registry g
407
+ JOIN rooms r ON r.id = g.room_id
408
+ JOIN participants p ON p.room_id = g.room_id
409
+ AND p.id = CASE WHEN r.kind = 'direct' THEN g.session_id ELSE g.name END
410
+ WHERE g.room_id = ? AND g.session_id = ?`,
411
+ ).get(roomId, sessionID) as { name: string } | null;
412
+ return row?.name;
413
+ }
414
+
415
+ /** Member + live message check; undefined covers missing, recalled, and non-member. */
416
+ async function readForwardableMessage(
417
+ roomId: string,
418
+ messageId: string,
419
+ sessionID: string,
420
+ ): Promise<ForwardableMessage | undefined> {
421
+ if (!await memberName(roomId, sessionID)) return undefined;
422
+ const db = await openStateDatabase(databasePath());
423
+ const row = db.query("SELECT text, created_at, answer_to, recalled_at FROM messages WHERE room_id = ? AND id = ?")
424
+ .get(roomId, messageId) as {
425
+ text: string;
426
+ created_at: number;
427
+ answer_to: string | null;
428
+ recalled_at: number | null;
429
+ } | null;
430
+ if (!row || row.recalled_at !== null) return undefined;
431
+ return {
432
+ text: row.text,
433
+ createdAt: Number(row.created_at),
434
+ ...(row.answer_to ? { parentMessageId: row.answer_to } : {}),
435
+ };
436
+ }
437
+
438
+ async function isRoomMember(roomId: string, sessionID: string): Promise<boolean> {
439
+ return Boolean(await memberName(roomId, sessionID));
440
+ }
441
+
442
+ /** Targets of rules whose source is this room's forward requests and whose account is ready. */
443
+ function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[] {
444
+ const probe: IngestEvent = {
445
+ schemaVersion: EVENT_SCHEMA_VERSION,
446
+ eventId: "forward-targets",
447
+ kind: "message.forward_requested",
448
+ source: { platform: "chatroom", accountId: "center", roomId },
449
+ actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: "" },
450
+ sourceDedupKey: "forward-targets",
451
+ receivedAt: new Date(0).toISOString(),
452
+ };
453
+ const config = runtime.config;
454
+ const seen = new Set<string>();
455
+ const targets: RuleTarget[] = [];
456
+ for (const rule of matchRules(config, probe)) {
457
+ for (const target of rule.to) {
458
+ if (runtime.host.targetStatus(target.platform, target.account) !== "ready") continue;
459
+ const key = `${target.platform}/${target.account}/${target.room}`;
460
+ if (seen.has(key)) continue;
461
+ seen.add(key);
462
+ targets.push(target);
463
+ }
464
+ }
465
+ return targets;
466
+ }
467
+
468
+ /**
469
+ * POST /rooms/:roomId/forward and GET /rooms/:roomId/forward-targets.
470
+ * No runtime means the feature is off: the route stays absent.
471
+ */
472
+ export type ChannelRuntimeSource = ChannelsRuntime | ChannelController | undefined;
473
+
474
+ export async function channelRoutes(
475
+ req: Request,
476
+ url: URL,
477
+ source: ChannelRuntimeSource,
478
+ ): Promise<Response | undefined> {
479
+ // A controller keeps its own swappable runtime; plain runtimes stay supported
480
+ // for callers and tests that manage one host directly.
481
+ if (source && "handle" in source) return source.handle(req, url);
482
+ const runtime = source;
483
+ if (!runtime) return undefined;
484
+
485
+ if (url.pathname === "/channeld/status") {
486
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
487
+ try {
488
+ return json(readChannelStats(runtime.config.stateFile, Date.now(), runtime.host.accountRuntimeStates));
489
+ } catch {
490
+ return json({ error: "channel state unavailable" }, 503);
491
+ }
492
+ }
493
+
494
+ const forward = url.pathname.match(/^\/rooms\/([^/]+)\/forward$/);
495
+ if (forward) {
496
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
497
+ const roomId = decodeSegment(forward[1]!);
498
+ if (!roomId) return json({ error: "message not found" }, 404);
499
+ const body = await jsonObject<Record<string, unknown>>(req);
500
+ if (!body) return json({ error: "JSON object body is required" }, 400);
501
+ const sessionID = typeof body.sessionID === "string" ? body.sessionID.trim() : "";
502
+ const messageId = typeof body.messageId === "string" ? body.messageId.trim() : "";
503
+ if (!sessionID || sessionID.length > MAX_SESSION || !messageId || messageId.length > MAX_SESSION) {
504
+ return json({ error: "sessionID and messageId are required" }, 400);
505
+ }
506
+ const target = parseTarget(body.target);
507
+ if (!target) return json({ error: "target must contain platform, account, and room identifiers" }, 400);
508
+ const requestId = body.requestId === undefined
509
+ ? undefined
510
+ : typeof body.requestId === "string" && body.requestId.trim() && body.requestId.trim().length <= MAX_REQUEST_ID
511
+ ? body.requestId.trim()
512
+ : null;
513
+ if (requestId === null) return json({ error: `requestId must be a non-empty string (max ${MAX_REQUEST_ID})` }, 400);
514
+
515
+ const message = await readForwardableMessage(roomId, messageId, sessionID);
516
+ if (!message) return json({ error: "message not found" }, 404);
517
+ if (runtime.host.targetStatus(target.platform, target.account) !== "ready") {
518
+ return json({ error: "forward target is unavailable" }, 409);
519
+ }
520
+
521
+ const source: Endpoint = { platform: "chatroom", accountId: "center", roomId };
522
+ const requestedTarget: Endpoint = { platform: target.platform, accountId: target.account, roomId: target.room };
523
+ // A room reply quotes its parent only when that parent already went to the
524
+ // same external endpoint; the native id comes from channel_echoes.
525
+ const parent = message.parentMessageId
526
+ ? runtime.host.findProviderMessage(requestedTarget, message.parentMessageId)
527
+ : undefined;
528
+ const event: IngestEvent = {
529
+ schemaVersion: EVENT_SCHEMA_VERSION,
530
+ eventId: `fwd-${randomUUID()}`,
531
+ kind: "message.forward_requested",
532
+ source,
533
+ actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: sessionID },
534
+ ...(requestId ? { providerEventId: requestId } : {}),
535
+ // The same message and target always reuse this key, so a retry is one event.
536
+ sourceDedupKey: `forward:${messageId}:${targetKey(requestedTarget)}`,
537
+ selectedMessage: { endpoint: source, nativeMessageId: messageId, text: message.text },
538
+ requestedTarget,
539
+ ...(parent ? { parent } : {}),
540
+ occurredAt: new Date(message.createdAt).toISOString(),
541
+ receivedAt: new Date().toISOString(),
542
+ content: { text: message.text },
543
+ };
544
+ const result = await runtime.host.ingest(event);
545
+ return json({ eventId: result.eventId ?? event.eventId }, 202);
546
+ }
547
+
548
+ const targets = url.pathname.match(/^\/rooms\/([^/]+)\/forward-targets$/);
549
+ if (!targets) return undefined;
550
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
551
+ const roomId = decodeSegment(targets[1]!);
552
+ if (!roomId) return json({ error: "room not found" }, 404);
553
+ const sessionID = (url.searchParams.get("sessionID") ?? "").trim();
554
+ if (!sessionID || sessionID.length > MAX_SESSION) return json({ error: "sessionID is required" }, 400);
555
+ if (!await isRoomMember(roomId, sessionID)) return json({ error: "room not found" }, 404);
556
+ return json({ targets: forwardTargets(runtime, roomId) });
557
+ }