@alexsun-top/opencode-chat-room 0.7.7 → 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 (97) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/LICENSE +21 -0
  3. package/README.md +45 -36
  4. package/README.zh-CN.md +50 -41
  5. package/dist/cli.js +2696 -365
  6. package/package.json +14 -4
  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/announcements.js +5 -2
  32. package/server/assets/chat/clipboard.js +30 -0
  33. package/server/assets/chat/copy-action.js +48 -0
  34. package/server/assets/chat/diagram-viewer.js +253 -0
  35. package/server/assets/chat/doc-preview.js +149 -12
  36. package/server/assets/chat/events.js +25 -4
  37. package/server/assets/chat/files.js +26 -5
  38. package/server/assets/chat/forward.js +69 -0
  39. package/server/assets/chat/history-loader.js +3 -1
  40. package/server/assets/chat/index.js +11 -1
  41. package/server/assets/chat/join-requests.js +6 -3
  42. package/server/assets/chat/locales/de.js +7 -2
  43. package/server/assets/chat/locales/es.js +7 -2
  44. package/server/assets/chat/locales/fr.js +7 -2
  45. package/server/assets/chat/locales/it.js +7 -2
  46. package/server/assets/chat/locales/ja.js +7 -2
  47. package/server/assets/chat/locales/ko.js +7 -2
  48. package/server/assets/chat/markdown-footnotes.js +115 -0
  49. package/server/assets/chat/markdown.js +65 -113
  50. package/server/assets/chat/messages.js +6 -3
  51. package/server/assets/chat/palette.js +33 -16
  52. package/server/assets/chat/pwa.js +2 -0
  53. package/server/assets/chat/questions.js +5 -0
  54. package/server/assets/chat/replies.js +7 -1
  55. package/server/assets/chat/resource-format.js +74 -0
  56. package/server/assets/chat/rooms.js +3 -0
  57. package/server/assets/chat/shiki.js +87 -0
  58. package/server/assets/chat/side-pane.js +143 -0
  59. package/server/assets/chat/state.js +63 -9
  60. package/server/assets/chat/system-messages.js +2 -0
  61. package/server/assets/chat/task-row.js +2 -1
  62. package/server/assets/chat/tasks.js +29 -2
  63. package/server/assets/chat/viewport.js +5 -0
  64. package/server/assets/code-highlight.css +20 -31
  65. package/server/assets/conversation.css +27 -2
  66. package/server/assets/diagram-viewer.css +141 -0
  67. package/server/assets/doc-preview.css +26 -6
  68. package/server/assets/responsive.css +87 -13
  69. package/server/assets/shiki.bundle.js +152 -0
  70. package/server/assets/tasks.css +1 -4
  71. package/server/channels.ts +314 -0
  72. package/server/chat-server.ts +36 -8
  73. package/server/chat.html +33 -5
  74. package/server/resource-routes.ts +3 -1
  75. package/server/sw.js +236 -4
  76. package/skills/chatroom/SKILL.md +1 -1
  77. package/src/agent/chatroom-skill.ts +8 -2
  78. package/src/center/center-client.ts +79 -1
  79. package/src/config/file-config.ts +34 -0
  80. package/src/rooms/resources.ts +2 -2
  81. package/src/runtime/v2-plugin.ts +8 -2
  82. package/src/runtime/watch.ts +41 -7
  83. package/src/state/sqlite-state.ts +67 -18
  84. package/src/state/store.ts +11 -5
  85. package/src/tui/app.mjs +10 -2
  86. package/src/tui/http.mjs +16 -2
  87. package/src/tui/info-app.mjs +24 -15
  88. package/src/tui/join-app.mjs +3 -3
  89. package/src/tui/main.mjs +1 -1
  90. package/src/tui/markdown.mjs +5 -3
  91. package/src/tui/mentions.mjs +3 -3
  92. package/src/tui/message-app.mjs +14 -11
  93. package/src/tui/palette-app.mjs +10 -7
  94. package/src/tui/reminder-app.mjs +14 -10
  95. package/src/tui/ui-content.mjs +3 -1
  96. package/server/assets/HIGHLIGHT-LICENSE +0 -29
  97. package/server/assets/highlight-10.7.3.min.js +0 -1358
package/server/sw.js CHANGED
@@ -18,7 +18,7 @@ const STATIC = [
18
18
  "/assets/files.css",
19
19
  "/assets/tasks.css",
20
20
  "/assets/doc-preview.css",
21
- "/assets/highlight-10.7.3.min.js",
21
+ "/assets/diagram-viewer.css",
22
22
  "/assets/marked-18.0.4.js",
23
23
  "/assets/dompurify-3.4.7.js",
24
24
  "/assets/mermaid-11.12.2.min.js",
@@ -27,9 +27,31 @@ const STATIC = [
27
27
  "/assets/icons/apple-touch-icon.png",
28
28
  "/manifest.webmanifest",
29
29
  ];
30
- 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)));
31
31
  const versioned = (path) => `${path}?v=${VERSION}`;
32
32
 
33
+ // Recently viewed images live in their own cache: a release upgrades CACHE, but a photo
34
+ // should survive until the person changes identity, it ages out, or the caps evict it.
35
+ const MEDIA_CACHE = "oc-chat-media";
36
+ const MEDIA_INDEX = "/__media-index__";
37
+ const MEDIA_IDENTITY = "/__media-identity__";
38
+ const MEDIA_PATH = /^\/rooms\/[^/]+\/resources\/[^/]+\/content$/;
39
+ const IDENTITY_PATTERN = /^[0-9a-f]{16}$/;
40
+ const REVALIDATE_MS = 10 * 60 * 1000;
41
+ const MEDIA_LIMITS = { entries: 80, bytes: 64 * 1024 * 1024, age: 30 * 24 * 60 * 60 * 1000 };
42
+ // Tests lower these numbers before seeding entries; production keeps the values above.
43
+ self.__MEDIA_LIMITS__ = MEDIA_LIMITS;
44
+
45
+ // The page owns the identity (a hash of its token and session ID); this worker only
46
+ // partitions the cache by it. Unknown identity means network-only.
47
+ let mediaIdentity;
48
+ let mediaQueue = Promise.resolve();
49
+ const queueMedia = (task) => {
50
+ const run = mediaQueue.then(task, task);
51
+ mediaQueue = run.catch(() => {});
52
+ return run;
53
+ };
54
+
33
55
  self.addEventListener("install", (event) => {
34
56
  event.waitUntil((async () => {
35
57
  const cache = await caches.open(CACHE);
@@ -59,14 +81,29 @@ self.addEventListener("install", (event) => {
59
81
  });
60
82
 
61
83
  self.addEventListener("message", (event) => {
62
- if (event.data?.type === "SKIP_WAITING") event.waitUntil(self.skipWaiting());
84
+ if (event.data?.type === "SKIP_WAITING") {
85
+ event.waitUntil(self.skipWaiting());
86
+ return;
87
+ }
88
+ // The first message is a cheap moment to enforce the age policy even if the worker
89
+ // was already active when this release first loaded.
90
+ if (!self.__mediaPruned) {
91
+ self.__mediaPruned = true;
92
+ event.waitUntil(pruneMedia().catch(() => {}));
93
+ }
94
+ if (event.data?.type === "SET_MEDIA_IDENTITY") event.waitUntil(setMediaIdentity(event.data.identity).catch(() => {}));
95
+ else if (event.data?.type === "CLEAR_MEDIA_CACHE") event.waitUntil(clearMedia().catch(() => {}));
63
96
  });
64
97
 
65
98
  self.addEventListener("activate", (event) => {
66
99
  event.waitUntil((async () => {
67
- for (const key of await caches.keys()) if (key !== CACHE) await caches.delete(key);
100
+ for (const key of await caches.keys()) {
101
+ if (key !== CACHE && key !== MEDIA_CACHE && key.startsWith("oc-chat-")) await caches.delete(key);
102
+ }
68
103
  await self.clients.claim();
69
104
  })());
105
+ // Housekeeping must never delay or fail activation.
106
+ event.waitUntil(pruneMedia().catch(() => {}));
70
107
  });
71
108
 
72
109
  self.addEventListener("fetch", (event) => {
@@ -74,6 +111,12 @@ self.addEventListener("fetch", (event) => {
74
111
  if (request.method !== "GET") return;
75
112
  const url = new URL(request.url);
76
113
  if (url.origin !== self.location.origin) return;
114
+ if (MEDIA_PATH.test(url.pathname)) {
115
+ // Partial responses do not belong in a whole-body cache; leave ranges to the browser.
116
+ if (request.headers.has("range")) return;
117
+ event.respondWith(mediaResponse(event));
118
+ return;
119
+ }
77
120
  // Chat data never comes from a cache: a stale answer would show a room that was deleted
78
121
  // and messages that were already read.
79
122
  if (url.pathname !== SHELL && !url.pathname.startsWith("/assets/")) return;
@@ -98,3 +141,192 @@ self.addEventListener("fetch", (event) => {
98
141
  return cached || network;
99
142
  })());
100
143
  });
144
+
145
+ // Cache Storage drops URL fragments, so the partition rides a reserved query parameter.
146
+ // The index keeps the readable `${url}#${identity}` form.
147
+ const mediaBodyKey = (url, identity) => `${url}${url.includes("?") ? "&" : "?"}__media_identity__=${identity}`;
148
+ const mediaIndexKey = (url, identity) => `${url}#${identity}`;
149
+
150
+ const isMediaEntry = (item) => Boolean(item)
151
+ && typeof item.url === "string" && typeof item.key === "string" && typeof item.identity === "string"
152
+ && Number.isFinite(item.size) && item.size >= 0
153
+ && Number.isFinite(item.usedAt) && Number.isFinite(item.revalidatedAt);
154
+
155
+ const isCacheable = (response) => response.status !== 206
156
+ && response.ok && response.type === "basic"
157
+ && (response.headers.get("content-type") || "").startsWith("image/");
158
+
159
+ const tagged = (response, state) => {
160
+ const headers = new Headers(response.headers);
161
+ headers.set("X-Media-Cache", state);
162
+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
163
+ };
164
+
165
+ async function loadMediaIdentity() {
166
+ if (mediaIdentity !== undefined) return mediaIdentity;
167
+ mediaIdentity = null;
168
+ try {
169
+ const cache = await caches.open(MEDIA_CACHE);
170
+ const response = await cache.match(MEDIA_IDENTITY);
171
+ const value = response ? await response.json() : null;
172
+ if (typeof value?.identity === "string" && IDENTITY_PATTERN.test(value.identity)) mediaIdentity = value.identity;
173
+ } catch { /* No stored identity means network-only media. */ }
174
+ return mediaIdentity;
175
+ }
176
+
177
+ async function saveMediaIdentity(identity) {
178
+ const cache = await caches.open(MEDIA_CACHE);
179
+ await cache.put(MEDIA_IDENTITY, new Response(JSON.stringify({ identity }), { headers: { "Content-Type": "application/json" } }));
180
+ }
181
+
182
+ async function setMediaIdentity(identity) {
183
+ if (typeof identity !== "string" || !IDENTITY_PATTERN.test(identity)) return;
184
+ await queueMedia(async () => {
185
+ const previous = await loadMediaIdentity();
186
+ mediaIdentity = identity;
187
+ if (previous === identity) {
188
+ await saveMediaIdentity(identity);
189
+ return;
190
+ }
191
+ // A different browser identity must never read the previous one's cached images.
192
+ await caches.delete(MEDIA_CACHE);
193
+ await saveMediaIdentity(identity);
194
+ });
195
+ }
196
+
197
+ async function clearMedia() {
198
+ await queueMedia(async () => {
199
+ const identity = await loadMediaIdentity();
200
+ await caches.delete(MEDIA_CACHE);
201
+ if (identity) await saveMediaIdentity(identity);
202
+ });
203
+ }
204
+
205
+ async function readIndex(cache) {
206
+ const response = await cache.match(MEDIA_INDEX);
207
+ if (!response) return [];
208
+ try {
209
+ const value = await response.json();
210
+ if (!Array.isArray(value)) throw new Error("invalid index");
211
+ return value.filter(isMediaEntry);
212
+ } catch {
213
+ // A damaged index cannot account for bodies; drop them so the caps stay meaningful.
214
+ for (const request of await cache.keys()) {
215
+ const path = new URL(request.url).pathname;
216
+ if (path !== MEDIA_INDEX && path !== MEDIA_IDENTITY) await cache.delete(request);
217
+ }
218
+ await cache.delete(MEDIA_INDEX);
219
+ return [];
220
+ }
221
+ }
222
+
223
+ const writeIndex = (cache, items) => cache.put(MEDIA_INDEX, new Response(JSON.stringify(items), { headers: { "Content-Type": "application/json" } }));
224
+
225
+ async function applyLimits(cache, items) {
226
+ const kept = [...items].sort((a, b) => a.usedAt - b.usedAt);
227
+ let bytes = kept.reduce((sum, item) => sum + item.size, 0);
228
+ const evicted = [];
229
+ while (kept.length > MEDIA_LIMITS.entries || (bytes > MEDIA_LIMITS.bytes && kept.length)) {
230
+ const item = kept.shift();
231
+ bytes -= item.size;
232
+ evicted.push(item);
233
+ }
234
+ for (const item of evicted) await cache.delete(mediaBodyKey(item.url, item.identity));
235
+ await writeIndex(cache, kept);
236
+ }
237
+
238
+ async function storeMedia(url, identity, response) {
239
+ const blob = await response.blob();
240
+ await queueMedia(async () => {
241
+ // An identity switch queued between fetch and put must not resurrect old bytes.
242
+ if (mediaIdentity !== identity) return;
243
+ const cache = await caches.open(MEDIA_CACHE);
244
+ await cache.put(mediaBodyKey(url, identity), new Response(blob, {
245
+ status: response.status, statusText: response.statusText, headers: response.headers,
246
+ }));
247
+ const key = mediaIndexKey(url, identity), now = Date.now();
248
+ const items = (await readIndex(cache)).filter((item) => item.key !== key);
249
+ items.push({ key, url, identity, size: blob.size, usedAt: now, revalidatedAt: now });
250
+ await applyLimits(cache, items);
251
+ });
252
+ }
253
+
254
+ const touchMedia = (url, identity) => queueMedia(async () => {
255
+ const cache = await caches.open(MEDIA_CACHE);
256
+ const items = await readIndex(cache);
257
+ const item = items.find((entry) => entry.url === url && entry.identity === identity);
258
+ if (!item) return;
259
+ item.usedAt = Date.now();
260
+ await writeIndex(cache, items);
261
+ });
262
+
263
+ const revalidating = new Set();
264
+ function revalidateMedia(request, url, identity) {
265
+ const key = mediaIndexKey(url, identity);
266
+ if (revalidating.has(key)) return Promise.resolve();
267
+ revalidating.add(key);
268
+ return (async () => {
269
+ try {
270
+ const response = await fetch(request);
271
+ if (response.status === 401 || response.status === 403 || response.status === 404) {
272
+ await queueMedia(async () => {
273
+ const cache = await caches.open(MEDIA_CACHE);
274
+ const items = await readIndex(cache);
275
+ const kept = items.filter((item) => item.key !== key);
276
+ await cache.delete(mediaBodyKey(url, identity));
277
+ if (kept.length !== items.length) await writeIndex(cache, kept);
278
+ });
279
+ } else if (response.status === 200 && isCacheable(response)) {
280
+ await storeMedia(url, identity, response);
281
+ }
282
+ } catch { /* A failed revalidation must not remove a working entry. */ }
283
+ finally { revalidating.delete(key); }
284
+ })();
285
+ }
286
+
287
+ async function pruneMedia() {
288
+ await queueMedia(async () => {
289
+ const cache = await caches.open(MEDIA_CACHE);
290
+ const items = await readIndex(cache);
291
+ const cutoff = Date.now() - MEDIA_LIMITS.age;
292
+ const fresh = items.filter((item) => item.usedAt >= cutoff);
293
+ for (const item of items) if (item.usedAt < cutoff) await cache.delete(mediaBodyKey(item.url, item.identity));
294
+ await applyLimits(cache, fresh);
295
+ });
296
+ }
297
+
298
+ async function mediaResponse(event) {
299
+ try {
300
+ return await serveMedia(event);
301
+ } catch {
302
+ // Cache Storage can be unavailable (private modes, quota). Media then stays network-only.
303
+ try { return tagged(await fetch(event.request), "bypass"); }
304
+ catch { return Response.error(); }
305
+ }
306
+ }
307
+
308
+ async function serveMedia(event) {
309
+ const request = event.request;
310
+ const identity = await loadMediaIdentity();
311
+ if (!identity) {
312
+ try { return tagged(await fetch(request), "bypass"); }
313
+ catch { return Response.error(); }
314
+ }
315
+ const url = request.url;
316
+ const cache = await caches.open(MEDIA_CACHE);
317
+ const cached = await cache.match(mediaBodyKey(url, identity));
318
+ if (cached) {
319
+ event.waitUntil(touchMedia(url, identity).catch(() => {}));
320
+ const entry = (await readIndex(cache)).find((item) => item.key === mediaIndexKey(url, identity));
321
+ // Serving stale is fine; revalidation is background hygiene for revocation/deletion.
322
+ if (!entry || Date.now() - entry.revalidatedAt > REVALIDATE_MS) event.waitUntil(revalidateMedia(request, url, identity).catch(() => {}));
323
+ return tagged(cached, "hit");
324
+ }
325
+ try {
326
+ const response = await fetch(request);
327
+ if (isCacheable(response)) await storeMedia(url, identity, response.clone()).catch(() => {});
328
+ return tagged(response, "miss");
329
+ } catch {
330
+ return Response.error();
331
+ }
332
+ }
@@ -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.
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
 
@@ -1,7 +1,13 @@
1
- import { readFileSync } from "node:fs";
1
+ import { existsSync, readFileSync } from "node:fs";
2
2
  import { fileURLToPath } from "node:url";
3
3
 
4
- const path = fileURLToPath(new URL("../../skills/chatroom/SKILL.md", import.meta.url));
4
+ // Bundled into dist/cli.js the module sits one level shallower than in src/agent,
5
+ // so try both layouts instead of hard-coding a single relative path.
6
+ const candidates = [
7
+ new URL("../../skills/chatroom/SKILL.md", import.meta.url),
8
+ new URL("../skills/chatroom/SKILL.md", import.meta.url),
9
+ ].map((url) => fileURLToPath(url));
10
+ const path = candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]!;
5
11
  const source = readFileSync(path, "utf8");
6
12
  const [, metadata = "", content = source] = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/) ?? [];
7
13
  const description = metadata.match(/^description:\s*(.+)$/m)?.[1]?.trim();
@@ -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
 
@@ -134,9 +134,9 @@ export function resourcePath(resource: Pick<Resource, "id" | "roomID">): string
134
134
  if (!uuid.test(resource.roomID) || !uuid.test(resource.id)) throw new ResourceError(404, "resource not found");
135
135
  return path.join(roomDirectory(resource.roomID), resource.id);
136
136
  }
137
- export async function listRoomResources(roomID: string, limit = 500, offset = 0): Promise<{ items: Resource[]; total: number }> {
137
+ export async function listRoomResources(roomID: string, limit = 500, offset = 0, beforeID?: string): Promise<{ items: Resource[]; total: number }> {
138
138
  if (!uuid.test(roomID)) throw new ResourceError(404, "room not found");
139
- return listResources(databasePath(), roomID, limit, offset);
139
+ return listResources(databasePath(), roomID, limit, offset, beforeID);
140
140
  }
141
141
  export async function findResource(roomID: string, id: string): Promise<Resource | undefined> {
142
142
  if (!uuid.test(id)) return undefined;
@@ -81,7 +81,7 @@ export function createV2Setup(deps: {
81
81
  });
82
82
  toolRegistration = await context.tool.transform((editor) => editor.add({
83
83
  name: "room",
84
- description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages; list members, announcements and tasks; create, update and delete room tasks; manage reminders. In an approval room join returns pending: you are not a member yet; call join_status to check whether an administrator approved you. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
84
+ description: "Chat room operations: create, join, join_status, leave and list rooms; send and poll messages; get_message fetches one message by ID (recalled messages come back as tombstones); catch_up pages messages after a seq cursor and is read-only (no read receipt or wake); send accepts parentMessageId to reply. List members, announcements and tasks; create, update and delete room tasks; manage reminders. In an approval room join returns pending: you are not a member yet; call join_status to check whether an administrator approved you. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media; upload_resource returns a [[resource:UUID]] marker, and the attachment renders only when that exact marker is included in a send message. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup. delete_resource removes an uploaded file; servers allow human room administrators any resource and agents only their own uploads.",
85
85
  options: { codemode: false },
86
86
  input: roomSchema(),
87
87
  execute: async (args, toolContext) => {
@@ -169,13 +169,19 @@ export function createV2Setup(deps: {
169
169
 
170
170
  export function roomSchema() {
171
171
  return z.object({
172
- action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
172
+ action: z.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "get_message", "catch_up", "members", "upload_resource", "read_resource", "delete_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete", "task_list", "task_create", "task_update", "task_delete"]),
173
173
  name: z.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
174
174
  roomId: z.string().optional(),
175
+ messageId: z.string().optional().describe("For get_message: the full message ID returned by send, poll, or catch_up."),
175
176
  resourceId: z.string().optional(),
176
177
  filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
177
178
  text: z.string().max(5000).optional(),
178
179
  isQuestion: z.boolean().optional(),
180
+ parentMessageId: z.string().optional().describe("For send: the ID of the message this one answers or replies to."),
181
+ replyToMessageID: z.string().optional().describe("Legacy alias of parentMessageId for send."),
182
+ clientMessageID: z.string().max(100).optional().describe("For send: idempotency key; retrying with the same ID and parent creates one message."),
183
+ afterSeq: z.number().int().min(0).optional().describe("For catch_up: return messages with seq greater than this cursor; omit to start at 0."),
184
+ limit: z.number().int().min(1).max(200).optional().describe("For catch_up: page size from 1 to 200; the server default is 50."),
179
185
  announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
180
186
  content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
181
187
  taskId: z.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
@@ -1,6 +1,6 @@
1
1
  import { Buffer } from "node:buffer";
2
2
  import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
3
- import { realpathSync } from "node:fs";
3
+ import { existsSync, realpathSync } from "node:fs";
4
4
  import { appendFile, chmod, link, mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises";
5
5
  import { spawn } from "node:child_process";
6
6
  import { fileURLToPath } from "node:url";
@@ -212,6 +212,26 @@ function sameController(value: unknown, record: WatchRecord, status: string): bo
212
212
  body.instanceID === record.instanceID && body.nonce === record.nonce;
213
213
  }
214
214
 
215
+ // Run the same entry script that started this process. A relative ../cli.ts
216
+ // only exists in the source layout; inside dist/cli.js it would point outside
217
+ // the package (and Node cannot run a .ts daemon from node_modules).
218
+ function cliEntryPath(): string {
219
+ // Installed packages run through a bin shim (node_modules/.bin/...), so resolve
220
+ // the symlink before checking the file name; the shim itself is not cli.js.
221
+ const argv = process.argv[1];
222
+ if (argv) {
223
+ let resolved = path.resolve(argv);
224
+ try { resolved = realpathSync(resolved); } catch { /* keep the resolved path */ }
225
+ if (/^cli\.(?:ts|js)$/.test(path.basename(resolved))) return resolved;
226
+ }
227
+ const candidates = [
228
+ fileURLToPath(new URL("../../dist/cli.js", import.meta.url)),
229
+ fileURLToPath(new URL("../../cli.ts", import.meta.url)),
230
+ fileURLToPath(new URL("../cli.js", import.meta.url)),
231
+ ];
232
+ return candidates.find((candidate) => existsSync(candidate)) ?? candidates[0]!;
233
+ }
234
+
215
235
  export async function watchStatus(): Promise<"running" | "stopped" | "unavailable" | "starting"> {
216
236
  const record = await readRecord();
217
237
  if (!record) {
@@ -222,7 +242,8 @@ export async function watchStatus(): Promise<"running" | "stopped" | "unavailabl
222
242
  return await control(record) ? "running" : "unavailable";
223
243
  }
224
244
 
225
- export async function startWatcher(beforePublish?: () => Promise<void>): Promise<string> {
245
+ // readyTimeoutMs is a test seam so the timeout cleanup can be exercised quickly.
246
+ export async function startWatcher(beforePublish?: () => Promise<void>, readyTimeoutMs = 20_000): Promise<string> {
226
247
  await privateDirectory();
227
248
  const own: WatchRecord = { phase: "starting", token: randomBytes(32).toString("base64url"), nonce: randomBytes(16).toString("hex"), instanceID: randomBytes(16).toString("hex"), pid: process.pid, createdAt: Date.now() };
228
249
  const reservation = await reserveWatcher(own, beforePublish);
@@ -241,17 +262,17 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
241
262
  }
242
263
  throw new Error("watcher state exists or is starting; no process was signaled");
243
264
  }
244
- const cli = fileURLToPath(new URL("../../cli.ts", import.meta.url));
265
+ const cli = cliEntryPath();
245
266
  let childError: Error | undefined;
246
- const child = spawn(process.execPath, [path.resolve(cli), "watch", "run"], {
267
+ const child = spawn(process.execPath, [cli, "watch", "run"], {
247
268
  detached: true, stdio: "ignore",
248
269
  env: { ...process.env, CHAT_ROOM_WATCH_CONTROL_TOKEN: own.token, CHAT_ROOM_WATCH_START_NONCE: own.nonce, CHAT_ROOM_WATCH_INSTANCE_ID: own.instanceID },
249
270
  });
250
271
  child.once("error", (error) => { childError = error; });
251
272
  child.unref();
252
- const deadline = Date.now() + 20_000;
273
+ const deadline = Date.now() + readyTimeoutMs;
253
274
  while (Date.now() < deadline) {
254
- if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
275
+ if (childError) { await removeRecord(own.token, own.nonce); releaseWatcherClaim(profile(), own.instanceID); throw childError; }
255
276
  const record = await readRecord();
256
277
  if (record?.token === own.token && record.nonce === own.nonce && record.phase === "running" && await control(record)) {
257
278
  return "watcher started";
@@ -263,7 +284,20 @@ export async function startWatcher(beforePublish?: () => Promise<void>): Promise
263
284
  }
264
285
  await new Promise((resolve) => setTimeout(resolve, 100));
265
286
  }
266
- throw new Error("watcher did not become ready; its process was not signaled");
287
+ // Leaving the child alive would keep the pid claim and block every later
288
+ // start, so stop it and release this attempt instead of only throwing.
289
+ child.kill("SIGTERM");
290
+ if (child.exitCode === null) {
291
+ // Give the dying daemon a bounded moment to finish its shutdown sweep so a
292
+ // new start cannot overlap it while the old pid still holds leases.
293
+ await Promise.race([
294
+ new Promise((resolve) => child.once("exit", resolve)),
295
+ new Promise((resolve) => setTimeout(resolve, 1000)),
296
+ ]);
297
+ }
298
+ await removeRecord(own.token, own.nonce);
299
+ releaseWatcherClaim(profile(), own.instanceID);
300
+ throw new Error("watcher did not become ready; its process was stopped");
267
301
  }
268
302
 
269
303
  export async function stopWatcher(): Promise<string> {