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

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 (67) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/LICENSE +21 -0
  3. package/README.md +45 -36
  4. package/README.zh-CN.md +50 -41
  5. package/dist/cli.js +2629 -350
  6. package/package.json +13 -3
  7. package/packages/chat-room-channeld/README.md +242 -0
  8. package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
  9. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  10. package/packages/chat-room-channeld/src/adapter.ts +475 -0
  11. package/packages/chat-room-channeld/src/cli.ts +124 -0
  12. package/packages/chat-room-channeld/src/config.ts +207 -0
  13. package/packages/chat-room-channeld/src/delivery.ts +158 -0
  14. package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
  15. package/packages/chat-room-channeld/src/framing.ts +128 -0
  16. package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
  17. package/packages/chat-room-channeld/src/host.ts +509 -0
  18. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  19. package/packages/chat-room-channeld/src/log.ts +26 -0
  20. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  21. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  22. package/packages/chat-room-channeld/src/published.ts +37 -0
  23. package/packages/chat-room-channeld/src/rules.ts +127 -0
  24. package/packages/chat-room-channeld/src/state.ts +485 -0
  25. package/packages/chat-room-channeld/src/stats.ts +167 -0
  26. package/plugin.ts +22 -5
  27. package/server/addressing-routes.ts +130 -0
  28. package/server/assets/NOTICE.txt +2 -2
  29. package/server/assets/SHIKI-LICENSE +22 -0
  30. package/server/assets/base.css +9 -1
  31. package/server/assets/chat/doc-preview.js +3 -4
  32. package/server/assets/chat/forward.js +69 -0
  33. package/server/assets/chat/index.js +2 -0
  34. package/server/assets/chat/locales/de.js +5 -0
  35. package/server/assets/chat/locales/es.js +5 -0
  36. package/server/assets/chat/locales/fr.js +5 -0
  37. package/server/assets/chat/locales/it.js +5 -0
  38. package/server/assets/chat/locales/ja.js +5 -0
  39. package/server/assets/chat/locales/ko.js +5 -0
  40. package/server/assets/chat/markdown-footnotes.js +115 -0
  41. package/server/assets/chat/markdown.js +24 -35
  42. package/server/assets/chat/palette.js +1 -1
  43. package/server/assets/chat/replies.js +7 -1
  44. package/server/assets/chat/shiki.js +87 -0
  45. package/server/assets/chat/side-pane.js +8 -1
  46. package/server/assets/chat/state.js +14 -1
  47. package/server/assets/chat/system-messages.js +2 -0
  48. package/server/assets/code-highlight.css +20 -31
  49. package/server/assets/conversation.css +3 -2
  50. package/server/assets/doc-preview.css +2 -1
  51. package/server/assets/responsive.css +5 -0
  52. package/server/assets/shiki.bundle.js +152 -0
  53. package/server/channels.ts +314 -0
  54. package/server/chat-server.ts +27 -4
  55. package/server/chat.html +10 -3
  56. package/server/sw.js +1 -2
  57. package/skills/chatroom/SKILL.md +1 -1
  58. package/src/center/center-client.ts +79 -1
  59. package/src/config/file-config.ts +34 -0
  60. package/src/runtime/v2-plugin.ts +8 -2
  61. package/src/runtime/watch.ts +3 -2
  62. package/src/state/sqlite-state.ts +42 -11
  63. package/src/state/store.ts +9 -3
  64. package/src/tui/http.mjs +16 -2
  65. package/src/tui/main.mjs +1 -1
  66. package/server/assets/HIGHLIGHT-LICENSE +0 -29
  67. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -0,0 +1,314 @@
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 { databasePath, writeState } from "../src/state/store.ts";
10
+ import { openStateDatabase } from "../src/state/sqlite-state.ts";
11
+ import {
12
+ parseConfig,
13
+ type ChannelConfig,
14
+ type RuleTarget,
15
+ } from "../packages/chat-room-channeld/src/config.ts";
16
+ import { createHost, type ChannelHost, type SpawnAdapter } from "../packages/chat-room-channeld/src/host.ts";
17
+ import { EVENT_SCHEMA_VERSION, type Endpoint, type IngestEvent } from "../packages/chat-room-channeld/src/protocol.ts";
18
+ import { matchRules, targetKey } from "../packages/chat-room-channeld/src/rules.ts";
19
+ import {
20
+ isTerminalDeliveryState,
21
+ readChannelStats,
22
+ type DeliveryRow,
23
+ type ReceiptRow,
24
+ } from "../packages/chat-room-channeld/src/state.ts";
25
+ import { jsonObject } from "./json-body.ts";
26
+
27
+ export type ChannelsRuntime = {
28
+ host: ChannelHost;
29
+ config: ChannelConfig;
30
+ };
31
+
32
+ export type ChannelDeps = {
33
+ spawnAdapter?: SpawnAdapter;
34
+ deliveryIntervalMs?: number;
35
+ };
36
+
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.
39
+ export type DeliveryResultCallback = (
40
+ event: IngestEvent | undefined,
41
+ delivery: DeliveryRow,
42
+ receipt: ReceiptRow | undefined,
43
+ ) => void;
44
+
45
+ const json = (body: unknown, status = 200) => Response.json(body, { status });
46
+ const IDENTIFIER = /^[A-Za-z0-9._-]{1,128}$/;
47
+ const MAX_SESSION = 128;
48
+ const MAX_REQUEST_ID = 200;
49
+
50
+ /** Load a channeld YAML config, with the center owning the state file path. */
51
+ function loadChannelConfig(file: string, stateFile: string): ChannelConfig {
52
+ let text: string;
53
+ try {
54
+ text = readFileSync(file, "utf8");
55
+ } catch {
56
+ throw new Error(`channeld config: cannot read ${file}`);
57
+ }
58
+ let raw: unknown;
59
+ try {
60
+ raw = parseYaml(text);
61
+ } catch {
62
+ throw new Error(`channeld config: ${file} is not valid YAML/JSON`);
63
+ }
64
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
65
+ throw new Error(`channeld config: ${file} must contain a mapping`);
66
+ }
67
+ // Override any YAML stateFile: a stale path must never point at the room database.
68
+ return parseConfig({ ...(raw as Record<string, unknown>), stateFile });
69
+ }
70
+
71
+ function resolveChannelStateFile(stateDir: string, configured: string | undefined): string {
72
+ const file = configured
73
+ ? (path.isAbsolute(configured) ? configured : path.resolve(stateDir, configured))
74
+ : path.join(stateDir, "channeld.sqlite");
75
+ if (path.resolve(file) === path.join(stateDir, "chat-room.sqlite")) {
76
+ throw new Error("chatroom config: server.channeld.stateFile must not be the room database");
77
+ }
78
+ return file;
79
+ }
80
+
81
+ function deliverySystemMessage(delivery: DeliveryRow, receipt: ReceiptRow | undefined): string {
82
+ if (delivery.state === "sent") return `Forwarded to ${delivery.target}`;
83
+ const raw = receipt?.detail || delivery.lastError || receipt?.state || delivery.state;
84
+ // Keep the system row inside the 5000-char message limit even for a huge adapter detail.
85
+ const reason = String(raw).replace(/[\r\n;]+/g, " ").trim().slice(0, 500) || delivery.state;
86
+ return `Forward to ${delivery.target} failed: ${reason}`;
87
+ }
88
+
89
+ /**
90
+ * Build the terminal-delivery publisher. One system message per delivery, and
91
+ * only for a forward event that came from this center.
92
+ */
93
+ export function createDeliveryResultHandler(): DeliveryResultCallback {
94
+ const notified = new Set<string>();
95
+ return (event, delivery, receipt) => {
96
+ if (!isTerminalDeliveryState(delivery.state)) return;
97
+ if (notified.has(delivery.deliveryId)) return;
98
+ const source = event?.source;
99
+ if (
100
+ event?.kind !== "message.forward_requested"
101
+ || source?.platform !== "chatroom"
102
+ || source.accountId !== "center"
103
+ ) return;
104
+ notified.add(delivery.deliveryId);
105
+ const text = deliverySystemMessage(delivery, receipt);
106
+ void writeState((svc) => {
107
+ svc.addEvent(source.roomId, text);
108
+ }).catch((error: unknown) => {
109
+ console.warn(`[chat-room] could not write the channeld result message: ${error instanceof Error ? error.message : String(error)}`);
110
+ });
111
+ };
112
+ }
113
+
114
+ /**
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.
117
+ */
118
+ export async function startChannels(
119
+ settings: ServerSettings,
120
+ deps: ChannelDeps = {},
121
+ ): Promise<ChannelsRuntime | undefined> {
122
+ if (!settings.channeld?.enabled) return undefined;
123
+ const configPath = settings.channeld.config;
124
+ if (!configPath) {
125
+ throw new Error(
126
+ "chatroom config: server.channeld is enabled but no config file is set (server.channeld.config or CHAT_ROOM_CHANNELD_CONFIG)",
127
+ );
128
+ }
129
+ const stateDir = path.dirname(databasePath());
130
+ const stateFile = resolveChannelStateFile(stateDir, settings.channeld.stateFile);
131
+ const config = loadChannelConfig(configPath, stateFile);
132
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
133
+ const host = createHost(config, {
134
+ spawnAdapter: deps.spawnAdapter,
135
+ deliveryIntervalMs: deps.deliveryIntervalMs,
136
+ onDeliveryResult: createDeliveryResultHandler(),
137
+ });
138
+ try {
139
+ await host.start();
140
+ } catch (error) {
141
+ console.warn(`[chat-room] channeld disabled: ${error instanceof Error ? error.message : String(error)}`);
142
+ // A partially started host may still own adapters or the state file.
143
+ await stopChannels({ host, config });
144
+ return undefined;
145
+ }
146
+ return { host, config };
147
+ }
148
+
149
+ export async function stopChannels(runtime: ChannelsRuntime | undefined): Promise<void> {
150
+ if (!runtime) return;
151
+ try {
152
+ await runtime.host.stop();
153
+ } catch (error) {
154
+ console.warn(`[chat-room] channeld stop failed: ${error instanceof Error ? error.message : String(error)}`);
155
+ }
156
+ }
157
+
158
+ function parseTarget(value: unknown): RuleTarget | undefined {
159
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
160
+ const raw = value as Record<string, unknown>;
161
+ if (
162
+ typeof raw.platform !== "string" || !IDENTIFIER.test(raw.platform)
163
+ || typeof raw.account !== "string" || !IDENTIFIER.test(raw.account)
164
+ || typeof raw.room !== "string" || !IDENTIFIER.test(raw.room)
165
+ ) return undefined;
166
+ return { platform: raw.platform, account: raw.account, room: raw.room };
167
+ }
168
+
169
+ type ForwardableMessage = { text: string; createdAt: number };
170
+
171
+ /** A malformed percent escape must not become a 500. */
172
+ function decodeSegment(segment: string): string | undefined {
173
+ try {
174
+ return decodeURIComponent(segment);
175
+ } catch {
176
+ return undefined;
177
+ }
178
+ }
179
+
180
+ /** Registry + participant join: a stale registry row after a kick is not a member. */
181
+ async function memberName(roomId: string, sessionID: string): Promise<string | undefined> {
182
+ const db = await openStateDatabase(databasePath());
183
+ const row = db.query(
184
+ `SELECT g.name FROM registry g
185
+ JOIN rooms r ON r.id = g.room_id
186
+ JOIN participants p ON p.room_id = g.room_id
187
+ AND p.id = CASE WHEN r.kind = 'direct' THEN g.session_id ELSE g.name END
188
+ WHERE g.room_id = ? AND g.session_id = ?`,
189
+ ).get(roomId, sessionID) as { name: string } | null;
190
+ return row?.name;
191
+ }
192
+
193
+ /** Member + live message check; undefined covers missing, recalled, and non-member. */
194
+ async function readForwardableMessage(
195
+ roomId: string,
196
+ messageId: string,
197
+ sessionID: string,
198
+ ): Promise<ForwardableMessage | undefined> {
199
+ if (!await memberName(roomId, sessionID)) return undefined;
200
+ 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;
203
+ if (!row || row.recalled_at !== null) return undefined;
204
+ return { text: row.text, createdAt: Number(row.created_at) };
205
+ }
206
+
207
+ async function isRoomMember(roomId: string, sessionID: string): Promise<boolean> {
208
+ return Boolean(await memberName(roomId, sessionID));
209
+ }
210
+
211
+ /** Targets of rules whose source is this room's forward requests and whose account is ready. */
212
+ function forwardTargets(runtime: ChannelsRuntime, roomId: string): RuleTarget[] {
213
+ const probe: IngestEvent = {
214
+ schemaVersion: EVENT_SCHEMA_VERSION,
215
+ eventId: "forward-targets",
216
+ kind: "message.forward_requested",
217
+ source: { platform: "chatroom", accountId: "center", roomId },
218
+ actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: "" },
219
+ sourceDedupKey: "forward-targets",
220
+ receivedAt: new Date(0).toISOString(),
221
+ };
222
+ const config = runtime.config;
223
+ const seen = new Set<string>();
224
+ const targets: RuleTarget[] = [];
225
+ for (const rule of matchRules(config, probe)) {
226
+ for (const target of rule.to) {
227
+ if (runtime.host.targetStatus(target.platform, target.account) !== "ready") continue;
228
+ const key = `${target.platform}/${target.account}/${target.room}`;
229
+ if (seen.has(key)) continue;
230
+ seen.add(key);
231
+ targets.push(target);
232
+ }
233
+ }
234
+ return targets;
235
+ }
236
+
237
+ /**
238
+ * POST /rooms/:roomId/forward and GET /rooms/:roomId/forward-targets.
239
+ * No runtime means the feature is off: the route stays absent.
240
+ */
241
+ export async function channelRoutes(
242
+ req: Request,
243
+ url: URL,
244
+ runtime: ChannelsRuntime | undefined,
245
+ ): Promise<Response | undefined> {
246
+ if (!runtime) return undefined;
247
+
248
+ if (url.pathname === "/channeld/status") {
249
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
250
+ try {
251
+ return json(readChannelStats(runtime.config.stateFile));
252
+ } catch {
253
+ return json({ error: "channel state unavailable" }, 503);
254
+ }
255
+ }
256
+
257
+ const forward = url.pathname.match(/^\/rooms\/([^/]+)\/forward$/);
258
+ if (forward) {
259
+ if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
260
+ const roomId = decodeSegment(forward[1]!);
261
+ if (!roomId) return json({ error: "message not found" }, 404);
262
+ const body = await jsonObject<Record<string, unknown>>(req);
263
+ if (!body) return json({ error: "JSON object body is required" }, 400);
264
+ const sessionID = typeof body.sessionID === "string" ? body.sessionID.trim() : "";
265
+ const messageId = typeof body.messageId === "string" ? body.messageId.trim() : "";
266
+ if (!sessionID || sessionID.length > MAX_SESSION || !messageId || messageId.length > MAX_SESSION) {
267
+ return json({ error: "sessionID and messageId are required" }, 400);
268
+ }
269
+ const target = parseTarget(body.target);
270
+ if (!target) return json({ error: "target must contain platform, account, and room identifiers" }, 400);
271
+ const requestId = body.requestId === undefined
272
+ ? undefined
273
+ : typeof body.requestId === "string" && body.requestId.trim() && body.requestId.trim().length <= MAX_REQUEST_ID
274
+ ? body.requestId.trim()
275
+ : null;
276
+ if (requestId === null) return json({ error: `requestId must be a non-empty string (max ${MAX_REQUEST_ID})` }, 400);
277
+
278
+ const message = await readForwardableMessage(roomId, messageId, sessionID);
279
+ if (!message) return json({ error: "message not found" }, 404);
280
+ if (runtime.host.targetStatus(target.platform, target.account) !== "ready") {
281
+ return json({ error: "forward target is unavailable" }, 409);
282
+ }
283
+
284
+ const source: Endpoint = { platform: "chatroom", accountId: "center", roomId };
285
+ const requestedTarget: Endpoint = { platform: target.platform, accountId: target.account, roomId: target.room };
286
+ const event: IngestEvent = {
287
+ schemaVersion: EVENT_SCHEMA_VERSION,
288
+ eventId: `fwd-${randomUUID()}`,
289
+ kind: "message.forward_requested",
290
+ source,
291
+ actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: sessionID },
292
+ ...(requestId ? { providerEventId: requestId } : {}),
293
+ // The same message and target always reuse this key, so a retry is one event.
294
+ sourceDedupKey: `forward:${messageId}:${targetKey(requestedTarget)}`,
295
+ selectedMessage: { endpoint: source, nativeMessageId: messageId, text: message.text },
296
+ requestedTarget,
297
+ occurredAt: new Date(message.createdAt).toISOString(),
298
+ receivedAt: new Date().toISOString(),
299
+ content: { text: message.text },
300
+ };
301
+ const result = await runtime.host.ingest(event);
302
+ return json({ eventId: result.eventId ?? event.eventId }, 202);
303
+ }
304
+
305
+ const targets = url.pathname.match(/^\/rooms\/([^/]+)\/forward-targets$/);
306
+ if (!targets) return undefined;
307
+ if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
308
+ const roomId = decodeSegment(targets[1]!);
309
+ if (!roomId) return json({ error: "room not found" }, 404);
310
+ const sessionID = (url.searchParams.get("sessionID") ?? "").trim();
311
+ if (!sessionID || sessionID.length > MAX_SESSION) return json({ error: "sessionID is required" }, 400);
312
+ if (!await isRoomMember(roomId, sessionID)) return json({ error: "room not found" }, 404);
313
+ return json({ targets: forwardTargets(runtime, roomId) });
314
+ }
@@ -20,6 +20,7 @@ import { readInbox } from "./inbox.ts";
20
20
  import { isReceiverOwnerID } from "../src/state/receiver-owner.ts";
21
21
  import { claimWake, touchActive, wakeMentionedSessions } from "./wake.ts";
22
22
  import { historyRoute } from "./history-route.ts";
23
+ import { addressingRoutes } from "./addressing-routes.ts";
23
24
  import { messageRecallRoutes } from "./message-recall-routes.ts";
24
25
  import { roomPayload } from "./room-payload.ts";
25
26
  import { isUser, settleAdmins, settleOwner } from "./room-owner.ts";
@@ -32,6 +33,7 @@ import { adminRoutes } from "./admin-routes.ts";
32
33
  import { joinRequestRoutes } from "./join-requests.ts";
33
34
  import { joinRoomMember } from "./room-join.ts";
34
35
  import { roomReminderRoutes, startRoomReminderScheduler } from "./room-reminders.ts";
36
+ import { channelRoutes, startChannels, stopChannels, type ChannelsRuntime } from "./channels.ts";
35
37
  import { loadRoomConfig, resolveServerSettings } from "../src/config/file-config.ts";
36
38
  import { startServer } from "./http-server.ts";
37
39
 
@@ -60,6 +62,8 @@ const hostname = settings.host;
60
62
  const displayHostname = hostname.includes(":") ? `[${hostname}]` : hostname;
61
63
  const port = parsePort(settings.port);
62
64
  const token = settings.token;
65
+ // Set before the request handler runs; the forward routes stay absent when off.
66
+ let channels: ChannelsRuntime | undefined;
63
67
 
64
68
  // The state directory and upload limit are read lazily from the environment;
65
69
  // publish the file values before the first database or upload call.
@@ -104,7 +108,7 @@ async function handle(req: Request): Promise<Response> {
104
108
  return json({ error: "chat page not found" }, 404);
105
109
  }
106
110
  const version = await chatVersionTag();
107
- return new Response(html.replaceAll("{{version}}", version), {
111
+ return new Response(html.replaceAll("{{version}}", version).replaceAll("{{channeld}}", channels ? "on" : "off"), {
108
112
  headers: {
109
113
  "Content-Type": "text/html; charset=utf-8",
110
114
  "Cache-Control": "no-store",
@@ -163,8 +167,12 @@ async function handle(req: Request): Promise<Response> {
163
167
  if (resource) return resource;
164
168
  const history = await historyRoute(url);
165
169
  if (history) return history;
170
+ const addressing = await addressingRoutes(req, url);
171
+ if (addressing) return addressing;
166
172
  const recall = await messageRecallRoutes(req, url);
167
173
  if (recall) return recall;
174
+ const channel = await channelRoutes(req, url, channels);
175
+ if (channel) return channel;
168
176
  if (req.method === "GET" && p === "/rooms/summary") {
169
177
  // ponytail: 轻量房间摘要(不含消息)——wakeSessions 每 10s 用它计算
170
178
  // latest,避免下载全部房间历史(orc-1 #5)
@@ -443,8 +451,9 @@ async function handle(req: Request): Promise<Response> {
443
451
  if (text.length > 5000) {
444
452
  return json({ error: "text too long (max 5000)" }, 400);
445
453
  }
446
- const replyTo = (body as Record<string, unknown>).replyToMessageID;
447
- if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo)) return json({ error: "replyToMessageID must be a non-empty message ID" }, 400);
454
+ // parentMessageId is the addressing alias of the web client's reply field.
455
+ const replyTo = (body as Record<string, unknown>).replyToMessageID ?? (body as Record<string, unknown>).parentMessageId;
456
+ if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo)) return json({ error: "parentMessageId must be a non-empty message ID" }, 400);
448
457
  // Optional retry key: a lost response may be retried without creating a twin.
449
458
  const clientMessageID = (body as Record<string, unknown>).clientMessageID;
450
459
  if (clientMessageID !== undefined && (typeof clientMessageID !== "string" || !clientMessageID || clientMessageID.length > 100)) {
@@ -455,8 +464,10 @@ async function handle(req: Request): Promise<Response> {
455
464
  if (result.status !== "ok") {
456
465
  if (result.status === "missing") return json({ error: "room not found" }, 404);
457
466
  if (result.status === "target") return json({ error: "reply target not found in room" }, 404);
467
+ if (result.status === "recalled") return json({ error: "reply target was recalled" }, 409);
458
468
  if (result.status === "question") return json({ error: "use the question answers endpoint to reply to a question" }, 409);
459
- return json({ error: "session is not a room member" }, 409);
469
+ // Reply addressing is member-only and uniformly missing otherwise.
470
+ return json({ error: "not found" }, 404);
460
471
  }
461
472
  touchActive(sessionID);
462
473
  const room = await read((svc) => svc.getRoom(roomId));
@@ -558,6 +569,18 @@ const config = {
558
569
 
559
570
  export default config;
560
571
 
572
+ // Channel D is opt-in. A missing config aborts startup; a failed adapter start
573
+ // only logs and leaves the forward routes absent.
574
+ channels = await startChannels(settings);
575
+ if (channels) {
576
+ let stopping: Promise<void> | undefined;
577
+ const stop = () => {
578
+ stopping ??= stopChannels(channels).finally(() => process.exit(0));
579
+ };
580
+ process.once("SIGINT", stop);
581
+ process.once("SIGTERM", stop);
582
+ }
583
+
561
584
  // Bun auto-serves the default export when this file is the entrypoint. Node and
562
585
  // Deno have no such convention, so they start the shared adapter explicitly.
563
586
  if (import.meta.main && typeof Bun === "undefined") await startServer(config);
package/server/chat.html CHANGED
@@ -35,7 +35,7 @@
35
35
  <link rel="stylesheet" href="/assets/doc-preview.css?v={{version}}">
36
36
  <link rel="stylesheet" href="/assets/diagram-viewer.css?v={{version}}">
37
37
  </head>
38
- <body>
38
+ <body data-channeld="{{channeld}}">
39
39
 
40
40
  <main id="app">
41
41
  <section id="restoreView" class="restore-view" role="status" aria-live="polite">
@@ -615,7 +615,7 @@
615
615
  <p class="doc-preview-meta"><span id="docPreviewSize"></span><span id="docPreviewLanguage" class="doc-preview-language" hidden></span><span id="docPreviewStatus" role="status" aria-live="polite"></span></p>
616
616
  </div>
617
617
  <div class="doc-preview-actions">
618
- <button id="btnDocPreviewDownload" class="btn ghost small doc-preview-download" type="button" data-i18n="resourceDownload">Download</button>
618
+ <button id="btnDocPreviewDownload" class="btn ghost small doc-preview-download" type="button" data-i18n="resourceDownload"><svg class="fluent-icon" aria-hidden="true" viewBox="0 0 24 24"><use href="/assets/fluent-icons.svg#fluent-arrow_download-24"></use></svg><span class="i18n-label">Download</span></button>
619
619
  <button id="btnCloseDocPreview" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close"><svg class="fluent-icon close-icon" aria-hidden="true" viewBox="0 0 24 24"><use href="/assets/fluent-icons.svg#fluent-dismiss-24"></use></svg></button>
620
620
  </div>
621
621
  </header>
@@ -672,6 +672,14 @@
672
672
  </div>
673
673
  </dialog>
674
674
 
675
+ <dialog id="forwardDialog" class="admin-dialog" aria-labelledby="forwardHeading">
676
+ <header class="admin-dialog-head"><h2 id="forwardHeading" data-i18n="forwardTitle">Forward message</h2><div class="admin-dialog-actions"><button id="btnCloseForward" class="reader-close" type="button" aria-label="Close" data-i18n-aria-label="close"><svg class="fluent-icon close-icon" aria-hidden="true" viewBox="0 0 24 24"><use href="/assets/fluent-icons.svg#fluent-dismiss-24"></use></svg></button></div></header>
677
+ <p class="hint" data-i18n="forwardHint">Choose where to forward this message.</p>
678
+ <div id="forwardTargets" class="forward-targets"></div>
679
+ <p id="forwardStatus" class="hint" role="status" aria-live="polite"></p>
680
+ <div class="announcement-actions"><button id="btnCancelForward" class="btn ghost small" type="button" data-i18n="cancel">Cancel</button></div>
681
+ </dialog>
682
+
675
683
  <!-- Alt+Space: message search and common commands in one keyboard-first surface. -->
676
684
  <dialog id="paletteDialog" class="admin-dialog palette-dialog" aria-labelledby="paletteHeading" aria-describedby="paletteHint">
677
685
  <header class="palette-head">
@@ -762,7 +770,6 @@
762
770
 
763
771
  <script src="/assets/marked-18.0.4.js?v={{version}}"></script>
764
772
  <script src="/assets/dompurify-3.4.7.js?v={{version}}"></script>
765
- <script src="/assets/highlight-10.7.3.min.js?v={{version}}"></script>
766
773
  <script src="/assets/mermaid-11.12.2.min.js?v={{version}}" defer></script>
767
774
  <script type="module" src="/assets/chat/index.js"></script>
768
775
  </body>
package/server/sw.js CHANGED
@@ -19,7 +19,6 @@ const STATIC = [
19
19
  "/assets/tasks.css",
20
20
  "/assets/doc-preview.css",
21
21
  "/assets/diagram-viewer.css",
22
- "/assets/highlight-10.7.3.min.js",
23
22
  "/assets/marked-18.0.4.js",
24
23
  "/assets/dompurify-3.4.7.js",
25
24
  "/assets/mermaid-11.12.2.min.js",
@@ -28,7 +27,7 @@ const STATIC = [
28
27
  "/assets/icons/apple-touch-icon.png",
29
28
  "/manifest.webmanifest",
30
29
  ];
31
- const VERSIONED = new Set(STATIC.filter((path) => path.endsWith(".css") || /^\/assets\/(?:highlight|marked|dompurify|mermaid)-/.test(path)));
30
+ const VERSIONED = new Set(STATIC.filter((path) => path.endsWith(".css") || /^\/assets\/(?:marked|dompurify|mermaid)-/.test(path)));
32
31
  const versioned = (path) => `${path}?v=${VERSION}`;
33
32
 
34
33
  // Recently viewed images live in their own cache: a release upgrades CACHE, but a photo
@@ -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
 
@@ -132,6 +132,50 @@ export async function request(
132
132
  return data;
133
133
  }
134
134
 
135
+ /** Fetch one message by stable ID; a recalled message returns the server tombstone. */
136
+ export async function getMessage(opts: CenterOpts, roomId: string, messageId: string, sessionID: string): Promise<Json> {
137
+ return request(
138
+ opts,
139
+ `/rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}?sessionID=${encodeURIComponent(sessionID)}`,
140
+ "GET",
141
+ );
142
+ }
143
+
144
+ export type CatchUpOptions = { sessionID: string; afterSeq?: number; limit?: number };
145
+ export type CatchUpPage = {
146
+ messages: Array<Record<string, unknown>>;
147
+ nextCursor: number;
148
+ hasMore: boolean;
149
+ unreadMentions: Array<{ id: string; seq: number }>;
150
+ unreadMentionCount: number;
151
+ unansweredQuestions: Array<{ id: string; seq: number }>;
152
+ unansweredQuestionCount: number;
153
+ };
154
+
155
+ /** Page forward from a persisted seq. Strictly read-only: no receipts, read
156
+ * watermark, wake, or model call happens on this path. */
157
+ export async function catchUp(
158
+ opts: CenterOpts,
159
+ roomId: string,
160
+ params: CatchUpOptions,
161
+ ): Promise<CatchUpPage> {
162
+ const { sessionID, afterSeq, limit } = params;
163
+ if (afterSeq !== undefined && (!Number.isSafeInteger(afterSeq) || afterSeq < 0)) {
164
+ throw new Error("afterSeq must be a non-negative integer");
165
+ }
166
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)) {
167
+ throw new Error("limit must be between 1 and 200");
168
+ }
169
+ const query = new URLSearchParams({ sessionID });
170
+ if (afterSeq !== undefined) query.set("afterSeq", String(afterSeq));
171
+ if (limit !== undefined) query.set("limit", String(limit));
172
+ return (await request(
173
+ opts,
174
+ `/rooms/${encodeURIComponent(roomId)}/catch-up?${query}`,
175
+ "GET",
176
+ )) as unknown as CatchUpPage;
177
+ }
178
+
135
179
  export async function markQueued(
136
180
  opts: CenterOpts,
137
181
  roomId: string,
@@ -163,6 +207,11 @@ export async function centerAction(
163
207
  name?: string;
164
208
  roomId?: string;
165
209
  messageId?: string;
210
+ parentMessageId?: string;
211
+ replyToMessageID?: string;
212
+ clientMessageID?: string;
213
+ afterSeq?: number;
214
+ limit?: number;
166
215
  text?: string;
167
216
  announcementName?: string;
168
217
  content?: string;
@@ -335,6 +384,26 @@ export async function centerAction(
335
384
  await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks/${encodeURIComponent(args.taskId)}`, "DELETE", { sessionID });
336
385
  return `task deleted: ${args.taskId}`;
337
386
  }
387
+ case "get_message": {
388
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
389
+ if (!args.messageId) return "error: messageId is required; use the full message ID returned by send, poll, or catch_up";
390
+ return JSON.stringify(await getMessage(opts, args.roomId, args.messageId, sessionID));
391
+ }
392
+ case "catch_up": {
393
+ if (!args.roomId) return "error: roomId is required; use a room UUID from the room list, not the room name";
394
+ if (args.afterSeq !== undefined && (!Number.isSafeInteger(args.afterSeq) || args.afterSeq < 0)) {
395
+ return "error: afterSeq must be a non-negative integer";
396
+ }
397
+ if (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1 || args.limit > 200)) {
398
+ return "error: limit must be between 1 and 200";
399
+ }
400
+ const page = await catchUp(opts, args.roomId, {
401
+ sessionID,
402
+ ...(args.afterSeq === undefined ? {} : { afterSeq: args.afterSeq }),
403
+ ...(args.limit === undefined ? {} : { limit: args.limit }),
404
+ });
405
+ return JSON.stringify(page);
406
+ }
338
407
  case "send": {
339
408
  if (!args.roomId) {
340
409
  return "error: roomId is required; use a room UUID from the room list, not the room name";
@@ -346,7 +415,16 @@ export async function centerAction(
346
415
  opts,
347
416
  `/rooms/${encodeURIComponent(args.roomId)}/messages`,
348
417
  "POST",
349
- { sessionID, text: args.text.trim(), ...(args.isQuestion ? { isQuestion: true } : {}) },
418
+ {
419
+ sessionID,
420
+ text: args.text.trim(),
421
+ ...(args.isQuestion ? { isQuestion: true } : {}),
422
+ // replyToMessageID stays for old callers; parentMessageId is the alias
423
+ // the server and the newer agent surfaces use.
424
+ ...(args.replyToMessageID ? { replyToMessageID: args.replyToMessageID } : {}),
425
+ ...(args.parentMessageId ? { parentMessageId: args.parentMessageId } : {}),
426
+ ...(args.clientMessageID ? { clientMessageID: args.clientMessageID } : {}),
427
+ },
350
428
  );
351
429
  const parsed = toRoom(room);
352
430
  const sentID = [...parsed.messages].reverse()
@@ -15,6 +15,11 @@ export type RoomFileConfig = {
15
15
  stateDir?: string;
16
16
  wakeServeUrl?: string;
17
17
  maxFileSizeMb?: number;
18
+ channeld?: {
19
+ enabled?: boolean;
20
+ config?: string;
21
+ stateFile?: string;
22
+ };
18
23
  };
19
24
  client?: {
20
25
  url?: string;
@@ -32,6 +37,12 @@ export type RoomFileConfig = {
32
37
  };
33
38
  };
34
39
 
40
+ export type ChannelDSettings = {
41
+ enabled: boolean;
42
+ config?: string;
43
+ stateFile?: string;
44
+ };
45
+
35
46
  export type ServerSettings = {
36
47
  host: string;
37
48
  port: string;
@@ -39,6 +50,7 @@ export type ServerSettings = {
39
50
  stateDir?: string;
40
51
  wakeServeUrl: string;
41
52
  maxFileSizeMb?: number;
53
+ channeld: ChannelDSettings;
42
54
  };
43
55
 
44
56
  export type ClientSettings = {
@@ -78,6 +90,16 @@ function optionalBoolean(value: unknown, where: string): boolean | undefined {
78
90
  return value;
79
91
  }
80
92
 
93
+ function parseChanneld(value: unknown): NonNullable<RoomFileConfig["server"]>["channeld"] {
94
+ const raw = asRecord(value, "server.channeld");
95
+ if (!raw) return undefined;
96
+ return {
97
+ enabled: optionalBoolean(raw.enabled, "server.channeld.enabled"),
98
+ config: optionalString(raw.config, "server.channeld.config"),
99
+ stateFile: optionalString(raw.stateFile, "server.channeld.stateFile"),
100
+ };
101
+ }
102
+
81
103
  function parseServer(value: unknown): RoomFileConfig["server"] {
82
104
  const raw = asRecord(value, "server");
83
105
  if (!raw) return undefined;
@@ -96,6 +118,7 @@ function parseServer(value: unknown): RoomFileConfig["server"] {
96
118
  stateDir: optionalString(raw.stateDir, "server.stateDir"),
97
119
  wakeServeUrl: optionalString(raw.wakeServeUrl, "server.wakeServeUrl"),
98
120
  maxFileSizeMb,
121
+ channeld: parseChanneld(raw.channeld),
99
122
  };
100
123
  }
101
124
 
@@ -274,6 +297,12 @@ export function resolveServerSettings(file: RoomFileConfig | null, env: NodeJS.P
274
297
  if (maxFileSizeMb !== undefined && (!Number.isFinite(maxFileSizeMb) || maxFileSizeMb <= 0)) {
275
298
  throw new Error("CHAT_ROOM_MAX_FILE_SIZE_MB must be a positive finite number");
276
299
  }
300
+ // A configured Channel D config implies opt-in; CHAT_ROOM_CHANNELD=0 still forces it off.
301
+ const channeldRaw = envValue(env, "CHAT_ROOM_CHANNELD");
302
+ const channeldConfig = envValue(env, "CHAT_ROOM_CHANNELD_CONFIG") ?? file?.server?.channeld?.config;
303
+ const channeldEnabled = channeldRaw === undefined
304
+ ? file?.server?.channeld?.enabled ?? Boolean(channeldConfig)
305
+ : channeldRaw === "1" || channeldRaw === "true";
277
306
  return {
278
307
  host: envValue(env, "CHAT_ROOM_SERVER_HOST") ?? envValue(env, "HOST") ?? file?.server?.host ?? "0.0.0.0",
279
308
  port,
@@ -281,6 +310,11 @@ export function resolveServerSettings(file: RoomFileConfig | null, env: NodeJS.P
281
310
  stateDir: envValue(env, "CHAT_ROOM_STATE_DIR") ?? file?.server?.stateDir,
282
311
  wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.server?.wakeServeUrl ?? "",
283
312
  maxFileSizeMb,
313
+ channeld: {
314
+ enabled: channeldEnabled,
315
+ config: channeldConfig,
316
+ stateFile: file?.server?.channeld?.stateFile,
317
+ },
284
318
  };
285
319
  }
286
320