@alexsun-top/opencode-chat-room 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +2 -2
  3. package/README.md +38 -6
  4. package/README.zh-CN.md +38 -6
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +5074 -3212
  7. package/package.json +23 -3
  8. package/packages/chat-room-channeld/README.md +98 -25
  9. package/packages/chat-room-channeld/dist/feishu-adapter.js +912 -149
  10. package/packages/chat-room-channeld/src/adapter.ts +36 -2
  11. package/packages/chat-room-channeld/src/config.ts +63 -1
  12. package/packages/chat-room-channeld/src/delivery.ts +6 -1
  13. package/packages/chat-room-channeld/src/feishu-adapter.ts +122 -292
  14. package/packages/chat-room-channeld/src/feishu-card.ts +27 -0
  15. package/packages/chat-room-channeld/src/feishu-inbound.ts +158 -0
  16. package/packages/chat-room-channeld/src/feishu-live.ts +355 -0
  17. package/packages/chat-room-channeld/src/feishu-send.ts +342 -0
  18. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +173 -0
  19. package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
  20. package/packages/chat-room-channeld/src/host.ts +120 -2
  21. package/packages/chat-room-channeld/src/inbound.ts +26 -0
  22. package/packages/chat-room-channeld/src/state.ts +17 -0
  23. package/packages/chat-room-channeld/src/stats.ts +43 -1
  24. package/server/admin-state.ts +13 -13
  25. package/server/app.ts +95 -0
  26. package/server/assets/NOTICE.txt +2 -1
  27. package/server/assets/base.css +15 -9
  28. package/server/assets/chat/announcements.js +70 -7
  29. package/server/assets/chat/doc-preview.js +184 -35
  30. package/server/assets/chat/events.js +3 -0
  31. package/server/assets/chat/files.js +46 -4
  32. package/server/assets/chat/index.js +2 -0
  33. package/server/assets/chat/integration-editor.js +163 -0
  34. package/server/assets/chat/integration-values.js +124 -0
  35. package/server/assets/chat/integrations.js +498 -0
  36. package/server/assets/chat/locales/de.js +40 -4
  37. package/server/assets/chat/locales/es.js +40 -4
  38. package/server/assets/chat/locales/fr.js +40 -4
  39. package/server/assets/chat/locales/it.js +40 -4
  40. package/server/assets/chat/locales/ja.js +40 -4
  41. package/server/assets/chat/locales/ko.js +40 -4
  42. package/server/assets/chat/markdown.js +22 -8
  43. package/server/assets/chat/messages.js +5 -5
  44. package/server/assets/chat/office-preview.js +69 -0
  45. package/server/assets/chat/panels.js +36 -0
  46. package/server/assets/chat/recall.js +58 -7
  47. package/server/assets/chat/receipts.js +15 -3
  48. package/server/assets/chat/reminders.js +69 -8
  49. package/server/assets/chat/resource-format.js +11 -0
  50. package/server/assets/chat/settings.js +30 -2
  51. package/server/assets/chat/side-pane.js +1 -2
  52. package/server/assets/chat/state.js +93 -10
  53. package/server/assets/chat/system-events.js +32 -0
  54. package/server/assets/chat/system-messages.js +23 -14
  55. package/server/assets/chat/task-row.js +0 -6
  56. package/server/assets/chat/tasks.js +121 -33
  57. package/server/assets/code-highlight.css +55 -32
  58. package/server/assets/conversation.css +123 -23
  59. package/server/assets/doc-preview.css +35 -3
  60. package/server/assets/files.css +5 -0
  61. package/server/assets/fluent-icons.svg +2 -0
  62. package/server/assets/monaco/LICENSE +21 -0
  63. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  64. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  65. package/server/assets/monaco/editor.worker.js +45 -0
  66. package/server/assets/monaco/integration-rules.css +1 -0
  67. package/server/assets/monaco/integration-rules.js +1297 -0
  68. package/server/assets/monaco/json.worker.js +77 -0
  69. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  70. package/server/assets/office/docx.bundle.js +33 -0
  71. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  72. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  73. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  74. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  75. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  76. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  77. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  78. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  79. package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
  80. package/server/assets/office/pptx.bundle.js +104 -0
  81. package/server/assets/office/xlsx.bundle.js +141 -0
  82. package/server/assets/recall.css +5 -4
  83. package/server/assets/responsive.css +50 -11
  84. package/server/assets/settings.css +73 -1
  85. package/server/assets/tasks.css +57 -7
  86. package/server/channel-integration.ts +519 -0
  87. package/server/channel-settings.ts +77 -0
  88. package/server/channels.ts +261 -18
  89. package/server/chat-server.ts +32 -580
  90. package/server/chat.html +187 -21
  91. package/server/http-server.ts +3 -182
  92. package/server/resource-routes.ts +16 -16
  93. package/server/routes/inbox.ts +100 -0
  94. package/server/routes/pages.ts +83 -0
  95. package/server/routes/questions.ts +39 -0
  96. package/server/routes/room-actions.ts +162 -0
  97. package/server/routes/rooms.ts +160 -0
  98. package/server/startup.ts +84 -0
  99. package/server/sw.js +4 -0
  100. package/server/task-routes.ts +1 -1
  101. package/src/center/center-client.ts +2 -10
  102. package/src/config/file-config.ts +7 -54
  103. package/src/platform/http-server.ts +182 -0
  104. package/src/protocol/addressing.ts +21 -0
  105. package/src/protocol/config.ts +58 -0
  106. package/src/protocol/room.ts +51 -0
  107. package/src/rooms/resources.ts +26 -16
  108. package/src/rooms/room-service.ts +2 -48
  109. package/src/rooms/storage.ts +329 -0
  110. package/src/rooms/tasks.ts +21 -5
  111. package/src/runtime/watch.ts +1 -1
  112. package/src/state/pg-database.ts +183 -0
  113. package/src/state/pg-migrate.ts +175 -0
  114. package/src/state/pg-sql.mjs +175 -0
  115. package/src/state/pg-worker.mjs +148 -0
  116. package/src/state/sqlite-announcements.ts +25 -0
  117. package/src/state/sqlite-database.ts +121 -0
  118. package/src/state/sqlite-legacy.ts +90 -0
  119. package/src/state/sqlite-members.ts +155 -0
  120. package/src/state/sqlite-messages.ts +288 -0
  121. package/src/state/sqlite-resources.ts +39 -0
  122. package/src/state/sqlite-rooms.ts +87 -0
  123. package/src/state/sqlite-schema.ts +80 -0
  124. package/src/state/sqlite-state-store.ts +33 -0
  125. package/src/state/sqlite-state.ts +15 -897
  126. package/src/state/sqlite-tasks.ts +65 -0
  127. package/src/state/sqlite-transaction.ts +13 -0
  128. package/src/state/sqlite.ts +21 -1
  129. package/src/state/store.ts +5 -1
  130. package/src/tui/app.mjs +32 -19
  131. package/src/tui/config.mjs +12 -4
  132. package/src/tui/i18n.mjs +38 -0
  133. package/src/tui/info-app.mjs +50 -51
  134. package/src/tui/info-content.mjs +79 -44
  135. package/src/tui/join-app.mjs +9 -9
  136. package/src/tui/locales/en.mjs +349 -0
  137. package/src/tui/locales/zh-CN.mjs +349 -0
  138. package/src/tui/main.mjs +85 -37
  139. package/src/tui/markdown.mjs +3 -2
  140. package/src/tui/mentions.mjs +3 -1
  141. package/src/tui/message-app.mjs +22 -21
  142. package/src/tui/message-view.mjs +2 -1
  143. package/src/tui/palette-app.mjs +9 -8
  144. package/src/tui/palette.mjs +30 -24
  145. package/src/tui/prefs.mjs +92 -0
  146. package/src/tui/reminder-app.mjs +18 -17
  147. package/src/tui/room-settings-app.mjs +30 -28
  148. package/src/tui/settings-app.mjs +153 -0
  149. package/src/tui/ui-content.mjs +65 -86
  150. package/src/tui/ui-help.mjs +73 -0
  151. package/src/tui/ui-overlay-view.mjs +23 -7
  152. package/src/tui/ui-suggest.mjs +6 -5
  153. package/src/tui/ui-theme.mjs +37 -33
  154. package/src/tui/ui-view.mjs +22 -7
  155. package/src/tui/ui.mjs +15 -3
  156. package/src/web/editor.worker.ts +1 -0
  157. package/src/web/integration-rules-editor.ts +439 -0
  158. package/src/web/integration-rules.ts +22 -0
  159. package/src/web/integration-schema.ts +228 -0
  160. package/src/web/json.worker.ts +1 -0
  161. package/src/web/office-viewer.ts +221 -0
@@ -6,16 +6,26 @@ import { randomUUID } from "node:crypto";
6
6
  import path from "node:path";
7
7
  import { parse as parseYaml } from "yaml";
8
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";
9
16
  import { databasePath, writeState } from "../src/state/store.ts";
10
17
  import { openStateDatabase } from "../src/state/sqlite-state.ts";
18
+ import { writeSqliteStateWithDatabase } from "../src/state/sqlite-state.ts";
11
19
  import {
12
20
  parseConfig,
13
21
  type ChannelConfig,
14
22
  type RuleTarget,
15
23
  } from "../packages/chat-room-channeld/src/config.ts";
16
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";
17
26
  import { EVENT_SCHEMA_VERSION, type Endpoint, type IngestEvent } from "../packages/chat-room-channeld/src/protocol.ts";
18
27
  import { matchRules, targetKey } from "../packages/chat-room-channeld/src/rules.ts";
28
+ import { inboundRoomText, matchInboundRoutes } from "../packages/chat-room-channeld/src/inbound.ts";
19
29
  import {
20
30
  isTerminalDeliveryState,
21
31
  readChannelStats,
@@ -34,8 +44,20 @@ export type ChannelDeps = {
34
44
  deliveryIntervalMs?: number;
35
45
  };
36
46
 
37
- // The center accepts an optional receipt because an account disabled mid-send
38
- // records a terminal `unknown` without one; the message must not invent one.
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.
39
61
  export type DeliveryResultCallback = (
40
62
  event: IngestEvent | undefined,
41
63
  delivery: DeliveryRow,
@@ -112,14 +134,45 @@ export function createDeliveryResultHandler(): DeliveryResultCallback {
112
134
  }
113
135
 
114
136
  /**
115
- * Start the relay host when `server.channeld.enabled` is on. A missing or
116
- * invalid config fails startup; an adapter start failure only disables channels.
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.
117
143
  */
118
- export async function startChannels(
119
- settings: ServerSettings,
120
- deps: ChannelDeps = {},
121
- ): Promise<ChannelsRuntime | undefined> {
122
- if (!settings.channeld?.enabled) return undefined;
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 {
123
176
  const configPath = settings.channeld.config;
124
177
  if (!configPath) {
125
178
  throw new Error(
@@ -129,11 +182,21 @@ export async function startChannels(
129
182
  const stateDir = path.dirname(databasePath());
130
183
  const stateFile = resolveChannelStateFile(stateDir, settings.channeld.stateFile);
131
184
  const config = loadChannelConfig(configPath, stateFile);
132
- mkdirSync(stateDir, { recursive: true, mode: 0o700 });
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);
133
195
  const host = createHost(config, {
134
196
  spawnAdapter: deps.spawnAdapter,
135
197
  deliveryIntervalMs: deps.deliveryIntervalMs,
136
198
  onDeliveryResult: createDeliveryResultHandler(),
199
+ ...inbound,
137
200
  });
138
201
  try {
139
202
  await host.start();
@@ -146,15 +209,174 @@ export async function startChannels(
146
209
  return { host, config };
147
210
  }
148
211
 
149
- export async function stopChannels(runtime: ChannelsRuntime | undefined): Promise<void> {
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> {
150
228
  if (!runtime) return;
151
229
  try {
152
- await runtime.host.stop();
230
+ await runtime.host.stop(options);
153
231
  } catch (error) {
154
232
  console.warn(`[chat-room] channeld stop failed: ${error instanceof Error ? error.message : String(error)}`);
155
233
  }
156
234
  }
157
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
+
158
380
  function parseTarget(value: unknown): RuleTarget | undefined {
159
381
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
160
382
  const raw = value as Record<string, unknown>;
@@ -166,7 +388,7 @@ function parseTarget(value: unknown): RuleTarget | undefined {
166
388
  return { platform: raw.platform, account: raw.account, room: raw.room };
167
389
  }
168
390
 
169
- type ForwardableMessage = { text: string; createdAt: number };
391
+ type ForwardableMessage = { text: string; createdAt: number; parentMessageId?: string };
170
392
 
171
393
  /** A malformed percent escape must not become a 500. */
172
394
  function decodeSegment(segment: string): string | undefined {
@@ -198,10 +420,19 @@ async function readForwardableMessage(
198
420
  ): Promise<ForwardableMessage | undefined> {
199
421
  if (!await memberName(roomId, sessionID)) return undefined;
200
422
  const db = await openStateDatabase(databasePath());
201
- const row = db.query("SELECT text, created_at, recalled_at FROM messages WHERE room_id = ? AND id = ?")
202
- .get(roomId, messageId) as { text: string; created_at: number; recalled_at: number | null } | null;
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;
203
430
  if (!row || row.recalled_at !== null) return undefined;
204
- return { text: row.text, createdAt: Number(row.created_at) };
431
+ return {
432
+ text: row.text,
433
+ createdAt: Number(row.created_at),
434
+ ...(row.answer_to ? { parentMessageId: row.answer_to } : {}),
435
+ };
205
436
  }
206
437
 
207
438
  async function isRoomMember(roomId: string, sessionID: string): Promise<boolean> {
@@ -238,17 +469,23 @@ function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[]
238
469
  * POST /rooms/:roomId/forward and GET /rooms/:roomId/forward-targets.
239
470
  * No runtime means the feature is off: the route stays absent.
240
471
  */
472
+ export type ChannelRuntimeSource = ChannelsRuntime | ChannelController | undefined;
473
+
241
474
  export async function channelRoutes(
242
475
  req: Request,
243
476
  url: URL,
244
- runtime: ChannelsRuntime | undefined,
477
+ source: ChannelRuntimeSource,
245
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;
246
483
  if (!runtime) return undefined;
247
484
 
248
485
  if (url.pathname === "/channeld/status") {
249
486
  if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
250
487
  try {
251
- return json(readChannelStats(runtime.config.stateFile));
488
+ return json(readChannelStats(runtime.config.stateFile, Date.now(), runtime.host.accountRuntimeStates));
252
489
  } catch {
253
490
  return json({ error: "channel state unavailable" }, 503);
254
491
  }
@@ -283,6 +520,11 @@ export async function channelRoutes(
283
520
 
284
521
  const source: Endpoint = { platform: "chatroom", accountId: "center", roomId };
285
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;
286
528
  const event: IngestEvent = {
287
529
  schemaVersion: EVENT_SCHEMA_VERSION,
288
530
  eventId: `fwd-${randomUUID()}`,
@@ -294,6 +536,7 @@ export async function channelRoutes(
294
536
  sourceDedupKey: `forward:${messageId}:${targetKey(requestedTarget)}`,
295
537
  selectedMessage: { endpoint: source, nativeMessageId: messageId, text: message.text },
296
538
  requestedTarget,
539
+ ...(parent ? { parent } : {}),
297
540
  occurredAt: new Date(message.createdAt).toISOString(),
298
541
  receivedAt: new Date().toISOString(),
299
542
  content: { text: message.text },