@alexsun-top/opencode-chat-room 0.5.0 → 0.5.2

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 (54) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +23 -7
  3. package/README.zh-CN.md +23 -7
  4. package/docs/administrator-rooms.md +51 -0
  5. package/package.json +11 -2
  6. package/plugin.ts +29 -12
  7. package/server/admin-auth.ts +16 -0
  8. package/server/admin-plan-routes.ts +79 -0
  9. package/server/admin-routes.ts +154 -0
  10. package/server/admin-scheduler.ts +42 -0
  11. package/server/admin-state.ts +61 -0
  12. package/server/admin-task-routes.ts +182 -0
  13. package/server/assets/base.css +55 -43
  14. package/server/assets/chat/admin.js +223 -0
  15. package/server/assets/chat/attachments.js +240 -0
  16. package/server/assets/chat/editor.js +211 -0
  17. package/server/assets/chat/events.js +34 -10
  18. package/server/assets/chat/index.js +8 -0
  19. package/server/assets/chat/markdown.js +1 -12
  20. package/server/assets/chat/members.js +1 -1
  21. package/server/assets/chat/mentions.js +38 -28
  22. package/server/assets/chat/message-window.js +18 -0
  23. package/server/assets/chat/messages.js +64 -46
  24. package/server/assets/chat/questions.js +113 -41
  25. package/server/assets/chat/receipts.js +0 -1
  26. package/server/assets/chat/reminders.js +101 -0
  27. package/server/assets/chat/replies.js +149 -0
  28. package/server/assets/chat/rooms.js +30 -10
  29. package/server/assets/chat/state.js +68 -18
  30. package/server/assets/conversation.css +111 -45
  31. package/server/assets/responsive.css +83 -28
  32. package/server/chat-server.ts +23 -6
  33. package/server/chat.html +82 -31
  34. package/server/inbox.ts +5 -1
  35. package/server/newrooms.ts +27 -10
  36. package/server/resource-routes.ts +3 -0
  37. package/server/room-reminders.ts +212 -0
  38. package/server/wake.ts +11 -15
  39. package/skills/chatroom/SKILL.md +21 -1
  40. package/src/admin-client.ts +130 -0
  41. package/src/admin-credentials.ts +58 -0
  42. package/src/agent-receipts.ts +13 -18
  43. package/src/center-client.ts +1 -1
  44. package/src/center-inbox.ts +2 -0
  45. package/src/plugin-notifications.ts +4 -0
  46. package/src/queue.ts +7 -2
  47. package/src/reminder-client.ts +50 -0
  48. package/src/resource-read.ts +118 -0
  49. package/src/resources.ts +1 -1
  50. package/src/sqlite-state.ts +89 -21
  51. package/src/store.ts +22 -8
  52. package/src/supervision-inbox.ts +62 -0
  53. package/src/v1-plugin.ts +13 -3
  54. package/src/v2-plugin.ts +24 -7
@@ -10,7 +10,7 @@ type State = { rooms: Room[]; registry: Registry };
10
10
  type Page<T> = { items: T[]; hasMore: boolean };
11
11
  const databases = new Map<string, Promise<Database>>();
12
12
 
13
- function open(file: string): Promise<Database> {
13
+ export function openStateDatabase(file: string): Promise<Database> {
14
14
  const known = databases.get(file);
15
15
  if (known) return known;
16
16
  const pending = initialize(file);
@@ -19,6 +19,43 @@ function open(file: string): Promise<Database> {
19
19
  return pending;
20
20
  }
21
21
 
22
+ export async function withStateTransaction<T>(file: string, callback: (db: Database) => T): Promise<T> {
23
+ const db = await openStateDatabase(file);
24
+ return immediate(db, () => callback(db));
25
+ }
26
+
27
+ export async function initializeAdminSchema(file: string): Promise<void> {
28
+ await withStateTransaction(file, db => {
29
+ db.exec(`CREATE TABLE IF NOT EXISTS admin_rooms(room_id TEXT PRIMARY KEY REFERENCES rooms(id) ON DELETE CASCADE,target_room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,session_id TEXT NOT NULL,receiver_owner_id TEXT NOT NULL,membership_id TEXT NOT NULL,generation INTEGER NOT NULL,enrollment_hash TEXT NOT NULL,enrollment_expires INTEGER NOT NULL,capability_hash TEXT,created_at INTEGER NOT NULL);
30
+ CREATE TABLE IF NOT EXISTS admin_tasks(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,admin_generation INTEGER NOT NULL DEFAULT 1,target_room_id TEXT NOT NULL,target_session_id TEXT NOT NULL,target_owner_id TEXT NOT NULL DEFAULT '',target_membership_id TEXT NOT NULL DEFAULT '',text TEXT NOT NULL,status TEXT NOT NULL,progress TEXT NOT NULL,delivery_token_hash TEXT NOT NULL DEFAULT '',created_at INTEGER NOT NULL,updated_at INTEGER NOT NULL);
31
+ CREATE TABLE IF NOT EXISTS admin_plans(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,name TEXT NOT NULL,interval_seconds INTEGER NOT NULL,text TEXT NOT NULL,paused INTEGER NOT NULL,next_run_at INTEGER NOT NULL,created_at INTEGER NOT NULL);
32
+ CREATE TABLE IF NOT EXISTS admin_deliveries(id TEXT PRIMARY KEY,admin_room_id TEXT NOT NULL REFERENCES admin_rooms(room_id) ON DELETE CASCADE,generation INTEGER NOT NULL,recipient_room_id TEXT NOT NULL DEFAULT '',session_id TEXT NOT NULL,owner_id TEXT NOT NULL,membership_id TEXT NOT NULL,kind TEXT NOT NULL,text TEXT NOT NULL,task_id TEXT,task_token TEXT,admission_id TEXT NOT NULL,created_at INTEGER NOT NULL,acknowledged INTEGER NOT NULL DEFAULT 0,UNIQUE(admin_room_id,kind,task_id));
33
+ CREATE INDEX IF NOT EXISTS admin_delivery_target ON admin_deliveries(session_id,owner_id,acknowledged);`);
34
+ const taskColumns = db.query("PRAGMA table_info(admin_tasks)").all() as Array<{ name: string }>;
35
+ if (!taskColumns.some(column => column.name === "delivery_token_hash")) db.exec("ALTER TABLE admin_tasks ADD COLUMN delivery_token_hash TEXT NOT NULL DEFAULT ''");
36
+ if (!taskColumns.some(column => column.name === "admin_generation")) db.exec("ALTER TABLE admin_tasks ADD COLUMN admin_generation INTEGER NOT NULL DEFAULT 1");
37
+ if (!taskColumns.some(column => column.name === "target_owner_id")) db.exec("ALTER TABLE admin_tasks ADD COLUMN target_owner_id TEXT NOT NULL DEFAULT ''");
38
+ if (!taskColumns.some(column => column.name === "target_membership_id")) db.exec("ALTER TABLE admin_tasks ADD COLUMN target_membership_id TEXT NOT NULL DEFAULT ''");
39
+ const deliveryColumns = db.query("PRAGMA table_info(admin_deliveries)").all() as Array<{ name: string }>;
40
+ if (!deliveryColumns.some(column => column.name === "task_token")) db.exec("ALTER TABLE admin_deliveries ADD COLUMN task_token TEXT");
41
+ if (!deliveryColumns.some(column => column.name === "recipient_room_id")) db.exec("ALTER TABLE admin_deliveries ADD COLUMN recipient_room_id TEXT NOT NULL DEFAULT ''");
42
+ db.exec("UPDATE admin_deliveries SET admission_id='msg_' || substr(admission_id,7) WHERE admission_id LIKE 'admin:%'");
43
+ });
44
+ }
45
+
46
+ export async function initializeReminderSchema(file: string): Promise<void> {
47
+ await withStateTransaction(file, db => db.exec(`CREATE TABLE IF NOT EXISTS room_reminders(
48
+ id TEXT PRIMARY KEY, room_id TEXT NOT NULL REFERENCES rooms(id) ON DELETE CASCADE,
49
+ creator_session_id TEXT NOT NULL, text TEXT NOT NULL, schedule_type TEXT NOT NULL,
50
+ at TEXT, expression TEXT, timezone TEXT, paused INTEGER NOT NULL DEFAULT 0,
51
+ next_run_at INTEGER NOT NULL, created_at INTEGER NOT NULL, last_error TEXT);`));
52
+ await withStateTransaction(file, db => {
53
+ const columns = db.query("PRAGMA table_info(room_reminders)").all() as Array<{ name: string }>;
54
+ if (!columns.some(column => column.name === "initiator")) db.exec("ALTER TABLE room_reminders ADD COLUMN initiator TEXT NOT NULL DEFAULT ''");
55
+ if (!columns.some(column => column.name === "last_error")) db.exec("ALTER TABLE room_reminders ADD COLUMN last_error TEXT");
56
+ });
57
+ }
58
+
22
59
  async function initialize(file: string): Promise<Database> {
23
60
  mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
24
61
  chmodSync(path.dirname(file), 0o700);
@@ -51,16 +88,16 @@ async function initialize(file: string): Promise<Database> {
51
88
 
52
89
  export type Announcement = { roomID: string; name: string; content: string; updatedAt: number };
53
90
  export async function listAnnouncements(file: string, roomID: string): Promise<Announcement[]> {
54
- const db = await open(file);
91
+ const db = await openStateDatabase(file);
55
92
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return [];
56
93
  return db.query("SELECT room_id AS roomID,name,content,updated_at AS updatedAt FROM announcements WHERE room_id=? ORDER BY name").all(roomID) as Announcement[];
57
94
  }
58
95
  export async function getAnnouncement(file: string, roomID: string, name: string): Promise<Announcement | undefined> {
59
- const db = await open(file);
96
+ const db = await openStateDatabase(file);
60
97
  return db.query("SELECT room_id AS roomID,name,content,updated_at AS updatedAt FROM announcements WHERE room_id=? AND name=?").get(roomID, name) as Announcement | undefined;
61
98
  }
62
99
  export async function putAnnouncement(file: string, roomID: string, name: string, content: string, updatedAt: number): Promise<Announcement | undefined> {
63
- const db = await open(file);
100
+ const db = await openStateDatabase(file);
64
101
  return immediate(db, () => {
65
102
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return undefined;
66
103
  db.query("INSERT INTO announcements(room_id,name,content,updated_at) VALUES(?,?,?,?) ON CONFLICT(room_id,name) DO UPDATE SET content=excluded.content,updated_at=excluded.updated_at").run(roomID, name, content, updatedAt);
@@ -68,13 +105,13 @@ export async function putAnnouncement(file: string, roomID: string, name: string
68
105
  });
69
106
  }
70
107
  export async function deleteAnnouncement(file: string, roomID: string, name: string): Promise<boolean> {
71
- const db = await open(file);
108
+ const db = await openStateDatabase(file);
72
109
  return immediate(db, () => db.query("DELETE FROM announcements WHERE room_id=? AND name=?").run(roomID, name).changes > 0);
73
110
  }
74
111
 
75
112
  export type StoredResource = { id: string; roomID: string; name: string; mimeType: string; size: number; createdAt: number };
76
113
  export async function putResource(file: string, resource: StoredResource): Promise<boolean> {
77
- const db = await open(file);
114
+ const db = await openStateDatabase(file);
78
115
  return immediate(db, () => {
79
116
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(resource.roomID)) return false;
80
117
  db.query("INSERT INTO resources(id,room_id,name,mime_type,size,created_at) VALUES(?,?,?,?,?,?)")
@@ -83,7 +120,7 @@ export async function putResource(file: string, resource: StoredResource): Promi
83
120
  });
84
121
  }
85
122
  export async function getResource(file: string, roomID: string, id: string): Promise<StoredResource | undefined> {
86
- const db = await open(file);
123
+ const db = await openStateDatabase(file);
87
124
  const row = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt FROM resources WHERE room_id=? AND id=?")
88
125
  .get(roomID, id) as StoredResource | null;
89
126
  return row ?? undefined;
@@ -279,12 +316,16 @@ function readState(db: Database): State {
279
316
 
280
317
  export type HistoryMessage = Message & { seq: number };
281
318
  export async function writeSqliteState<T>(file: string, callback: (service: RoomService, registry: Registry) => T): Promise<T> {
282
- const db = await open(file);
319
+ return writeSqliteStateWithDatabase(file, (service, registry) => callback(service, registry));
320
+ }
321
+
322
+ export async function writeSqliteStateWithDatabase<T>(file: string, callback: (service: RoomService, registry: Registry, db: Database) => T): Promise<T> {
323
+ const db = await openStateDatabase(file);
283
324
  return immediate(db, () => {
284
325
  const state = readState(db);
285
326
  const service = new RoomService();
286
327
  service.hydrate(state.rooms);
287
- const result = callback(service, state.registry);
328
+ const result = callback(service, state.registry, db);
288
329
  if (result && typeof (result as { then?: unknown }).then === "function") throw new Error("writeState callback must be synchronous");
289
330
  persistState(db, service.listRooms(), state.registry);
290
331
  return result;
@@ -292,17 +333,17 @@ export async function writeSqliteState<T>(file: string, callback: (service: Room
292
333
  }
293
334
 
294
335
  export async function readSqliteState(file: string): Promise<State> {
295
- const db = await open(file);
336
+ const db = await openStateDatabase(file);
296
337
  return db.transaction(() => readState(db)).deferred();
297
338
  }
298
339
 
299
340
  export async function readQuestions(file: string, roomID: string): Promise<Message[]> {
300
- const db = await open(file);
341
+ const db = await openStateDatabase(file);
301
342
  return (db.query("SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL ORDER BY seq").all(roomID) as Array<Record<string, string | number | null>>).map(rowMessage);
302
343
  }
303
344
 
304
345
  export async function answerQuestion(file: string, roomID: string, questionID: string, sessionID: string, text: string): Promise<{ status: "ok"; answer: Message } | { status: "missing" | "member" | "question" | "answered" }> {
305
- const db = await open(file);
346
+ const db = await openStateDatabase(file);
306
347
  return immediate(db, () => {
307
348
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
308
349
  const member = db.query("SELECT g.name,r.kind FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?").get(roomID, sessionID) as { name: string; kind: string } | null;
@@ -319,8 +360,35 @@ export async function answerQuestion(file: string, roomID: string, questionID: s
319
360
  });
320
361
  }
321
362
 
363
+ export async function sendReply(file: string, roomID: string, targetID: string, sessionID: string, text: string): Promise<{ status: "ok"; message: Message } | { status: "missing" | "member" | "target" | "question" }> {
364
+ const db = await openStateDatabase(file);
365
+ return immediate(db, () => {
366
+ if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID)) return { status: "missing" };
367
+ const member = db.query("SELECT g.name,r.kind FROM registry g JOIN rooms r ON r.id=g.room_id JOIN participants p ON p.room_id=g.room_id AND p.id=CASE WHEN r.kind='direct' THEN g.session_id ELSE g.name END WHERE g.room_id=? AND g.session_id=?").get(roomID, sessionID) as { name: string; kind: string } | null;
368
+ if (!member) return { status: "member" };
369
+ const target = db.query("SELECT is_question FROM messages WHERE room_id=? AND id=?").get(roomID, targetID) as { is_question: number } | null;
370
+ if (!target) return { status: "target" };
371
+ if (target.is_question) return { status: "question" };
372
+ const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID) as { created_at: number } | null;
373
+ const message: Message = { id: randomUUID(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name, senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1), answerToMessageID: targetID };
374
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to) VALUES(?,?,?,?,?,?,0,?)").run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, targetID);
375
+ return { status: "ok", message };
376
+ });
377
+ }
378
+
379
+ function questionExcerpt(text: string): string {
380
+ const chars = Array.from(text);
381
+ return chars.length <= 200 ? text : `${chars.slice(0, 100).join("")}…${chars.slice(-100).join("")}`;
382
+ }
383
+
384
+ export async function readQuestionExcerpt(file: string, roomID: string, questionID: string): Promise<string | undefined> {
385
+ const db = await openStateDatabase(file);
386
+ const row = db.query("SELECT text FROM messages WHERE room_id=? AND id=? AND is_question=1").get(roomID, questionID) as { text: string } | null;
387
+ return row ? questionExcerpt(row.text) : undefined;
388
+ }
389
+
322
390
  export async function readUnreadPage(file: string, roomID: string, afterTs: number, limit = 100, sessionID?: string, senderName?: string, newest = false): Promise<Page<Message>> {
323
- const db = await open(file);
391
+ const db = await openStateDatabase(file);
324
392
  const take = Math.min(200, Math.max(1, limit));
325
393
  const rows = db.query(`SELECT id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? AND created_at>? AND
326
394
  (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
@@ -332,12 +400,12 @@ export async function readUnreadPage(file: string, roomID: string, afterTs: numb
332
400
  }
333
401
 
334
402
  export async function readInboxPage(file: string, sessionID: string, roomFilter: string | null, excludeSelf: boolean, limit = 100, afterTs?: number) {
335
- const db = await open(file);
403
+ const db = await openStateDatabase(file);
336
404
  return db.transaction(() => {
337
405
  const take = Math.min(200, Math.max(1, limit));
338
406
  const members = db.query("SELECT room_id,last_queued_ts FROM registry WHERE session_id=? AND (? IS NULL OR room_id=?)").all(sessionID, roomFilter, roomFilter) as Array<{ room_id: string; last_queued_ts: number | null }>;
339
- const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,m.is_question,m.answer_to,m.answered_by,r.name AS room_name,r.kind AS room_kind
340
- FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id
407
+ const rows = db.query(`SELECT m.id,m.room_id,m.sender_id,m.sender_session_id,m.text,m.created_at,m.is_question,m.answer_to,m.answered_by,r.name AS room_name,r.kind AS room_kind,q.text AS answer_question_text
408
+ FROM messages m JOIN registry g ON g.room_id=m.room_id JOIN rooms r ON r.id=m.room_id LEFT JOIN messages q ON q.room_id=m.room_id AND q.id=m.answer_to AND q.is_question=1
341
409
  WHERE g.session_id=? AND (? IS NULL OR m.room_id=?) AND
342
410
  m.created_at > coalesce(?,CASE WHEN ? THEN max(coalesce(g.last_read_ts,0),coalesce(g.last_queued_ts,0)) ELSE coalesce(g.last_read_ts,0) END) AND
343
411
  (?=0 OR (m.sender_session_id IS NOT NULL AND m.sender_session_id!=?) OR (m.sender_session_id IS NULL AND m.sender_id!=g.name))
@@ -346,7 +414,7 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
346
414
  const hasMore = rows.length > take;
347
415
  const items = rows.slice(0, take).map((row) => {
348
416
  const message = rowMessage(row);
349
- return { ...message, roomName: String(row.room_name), roomKind: (row.room_kind === "direct" ? "direct" : "group") as "direct" | "group" };
417
+ return { ...message, ...(row.answer_question_text !== null ? { answerQuestionExcerpt: questionExcerpt(String(row.answer_question_text)) } : {}), roomName: String(row.room_name), roomKind: (row.room_kind === "direct" ? "direct" : "group") as "direct" | "group" };
350
418
  });
351
419
  const queuedTs = Object.fromEntries(members.map((member) => [member.room_id, member.last_queued_ts ?? 0]));
352
420
  return { member: members.length > 0, items, queuedTs, hasMore };
@@ -354,7 +422,7 @@ export async function readInboxPage(file: string, sessionID: string, roomFilter:
354
422
  }
355
423
 
356
424
  export async function readHistoryPage(file: string, roomID: string, beforeSeq?: number, limit = 100, excludeSessionID?: string, excludeName = ""): Promise<{ messages: HistoryMessage[]; nextBeforeSeq: number | null; hasMore: boolean }> {
357
- const db = await open(file);
425
+ const db = await openStateDatabase(file);
358
426
  const take = Math.min(200, Math.max(1, limit));
359
427
  const rows = db.query(`SELECT seq,id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
360
428
  (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
@@ -366,7 +434,7 @@ export async function readHistoryPage(file: string, roomID: string, beforeSeq?:
366
434
  }
367
435
 
368
436
  export async function readMessageReceipts(file: string, roomID: string, messageIDs?: string[]): Promise<MessageReceipt[] | undefined> {
369
- const db = await open(file);
437
+ const db = await openStateDatabase(file);
370
438
  return db.transaction(() => {
371
439
  if (messageIDs && (!messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => !id))) return undefined;
372
440
  const requested = messageIDs ? [...new Set(messageIDs)] : undefined;
@@ -385,7 +453,7 @@ export async function readMessageReceipts(file: string, roomID: string, messageI
385
453
  export async function writeMessageReceipts(file: string, roomID: string, sessionID: string, messageIDs: string[], evidence: ReceiptEvidence, identity: ReceiptIdentity, readAt: number, readThroughTs?: number): Promise<ReceiptWriteResult> {
386
454
  if (!messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => typeof id !== "string" || !id || id.length > 128) || !["displayed", "tool", "context"].includes(evidence)) return { status: "messageIDs", acceptedIDs: [] };
387
455
  const ids = [...new Set(messageIDs)];
388
- const db = await open(file);
456
+ const db = await openStateDatabase(file);
389
457
  return immediate(db, () => {
390
458
  const member = db.query("SELECT membership_id,server_url,api_prefix,protocol,name,receiver_owner_id,host FROM registry WHERE room_id=? AND session_id=?").get(roomID, sessionID) as Record<string, string | null> | null;
391
459
  if (!member || member.membership_id !== identity.membershipID || !receiptOwnerMatches({
@@ -411,7 +479,7 @@ export async function writeMessageReceipts(file: string, roomID: string, session
411
479
  }
412
480
 
413
481
  export async function writePresenceState(file: string, reports: PresenceReport[], ownerID: string | undefined, sequence: number | undefined, now: number): Promise<{ stale: boolean; updatedSessionIDs: string[] }> {
414
- const db = await open(file);
482
+ const db = await openStateDatabase(file);
415
483
  return immediate(db, () => {
416
484
  if (ownerID && sequence !== undefined) {
417
485
  const current = db.query("SELECT last_sequence FROM presence_sequences WHERE owner_id=?").get(ownerID) as { last_sequence: number } | null;
package/src/store.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  import path from "node:path";
5
5
  import os from "node:os";
6
6
  import RoomService, { type Message, type Room } from "./room-service";
7
- import { answerQuestion as sqliteAnswerQuestion, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
7
+ import { answerQuestion as sqliteAnswerQuestion, sendReply as sqliteSendReply, readHistoryPage, readInboxPage as sqliteInboxPage, readMessageReceipts, readQuestionExcerpt as sqliteQuestionExcerpt, readQuestions as sqliteReadQuestions, readSqliteState, readUnreadPage, writeMessageReceipts, writePresenceState, writeSqliteState, type HistoryMessage } from "./sqlite-state";
8
8
 
9
9
  export function statePath(): string {
10
10
  // JSON path remains the migration source; SQLite lives beside it.
@@ -36,6 +36,8 @@ export async function readHistory(roomID: string, beforeSeq?: number, limit = 10
36
36
  }
37
37
  export async function readQuestions(roomID: string): Promise<Message[]> { return sqliteReadQuestions(databasePath(), roomID); }
38
38
  export async function answerQuestion(roomID: string, questionID: string, sessionID: string, text: string) { return sqliteAnswerQuestion(databasePath(), roomID, questionID, sessionID, text); }
39
+ export async function sendReply(roomID: string, targetID: string, sessionID: string, text: string) { return sqliteSendReply(databasePath(), roomID, targetID, sessionID, text); }
40
+ export async function readQuestionExcerpt(roomID: string, questionID: string) { return sqliteQuestionExcerpt(databasePath(), roomID, questionID); }
39
41
 
40
42
  export async function loadRooms(): Promise<Room[]> {
41
43
  return (await readSqliteState(databasePath())).rooms;
@@ -109,20 +111,32 @@ const MAX_LINES = 20;
109
111
  // lines were folded or message text was truncated; callers must not advance
110
112
  // the watermark until a full poll confirms it.
111
113
  export function formatNotificationLines(
112
- items: ReadonlyArray<{ createdAt: number; senderId: string; text: string }>,
113
- ): { lines: string[]; capped: boolean } {
114
- const countCapped = items.length > MAX_LINES;
114
+ items: ReadonlyArray<{ createdAt: number; senderId: string; text: string; answerQuestionExcerpt?: string }>,
115
+ ): { lines: string[]; capped: boolean; visibleIndices: number[] } {
116
+ const visible: Array<{ item: typeof items[number]; index: number }> = [];
117
+ let lineCount = 0;
118
+ for (let index = items.length - 1; index >= 0; index--) {
119
+ const item = items[index]!;
120
+ const required = item.answerQuestionExcerpt ? 2 : 1;
121
+ if (lineCount + required > MAX_LINES) break;
122
+ visible.unshift({ item, index });
123
+ lineCount += required;
124
+ }
125
+ const countCapped = visible.length < items.length;
115
126
  const textCapped = items.some((it) => it.text.length > MAX_LINE);
116
127
  const capped = countCapped || textCapped;
117
- const lines = items.slice(-MAX_LINES).map((it) => {
128
+ const lines = visible.flatMap(({ item: it }) => {
118
129
  const text =
119
130
  it.text.length > MAX_LINE ? `${it.text.slice(0, MAX_LINE)}\u2026` : it.text;
120
- return `- [${timeOf(it.createdAt)}] ${it.senderId}: ${text}`;
131
+ return [
132
+ ...(it.answerQuestionExcerpt ? [` ↳ Answer to: “${it.answerQuestionExcerpt.replace(/[\r\n]+/g, " ")}”`] : []),
133
+ `- [${timeOf(it.createdAt)}] ${it.senderId}: ${text}`,
134
+ ];
121
135
  });
122
136
  if (countCapped) {
123
- lines.unshift(`\u2026 and ${items.length - MAX_LINES} earlier messages`);
137
+ lines.unshift(`\u2026 and ${items.length - visible.length} earlier messages`);
124
138
  }
125
- return { lines, capped };
139
+ return { lines, capped, visibleIndices: visible.map(({ index }) => index) };
126
140
  }
127
141
 
128
142
  export function authHeader(): string {
@@ -0,0 +1,62 @@
1
+ import { request, type CenterOpts } from "./center-client";
2
+ import { sendAsyncNotification, sendQueue, type QueueTransport } from "./queue-transport";
3
+ import { loadAdminCapability, saveTaskToken } from "./admin-credentials";
4
+ import { protectedAdminRequest } from "./admin-client";
5
+
6
+ type Delivery = { id: string; admissionID?: string; adminRoomId?: string; kind: "task" | "supervision"; text: string; taskId?: string; taskToken?: string; targetRoomId?: string };
7
+ type Inbox = { deliveries?: Delivery[]; supervisionRoomIds?: string[] };
8
+
9
+ function promptText(item: Delivery, taskToken?: string): string {
10
+ const text = taskToken ? item.text.replaceAll(taskToken, "[redacted]") : item.text;
11
+ if (item.kind === "task") {
12
+ const source = item.targetRoomId ? ` Target room: ${item.targetRoomId}.` : "";
13
+ return `<supervision>Task from admin room ${item.adminRoomId}.${source} Task ID: ${item.taskId}. Report progress using admin(action="task_progress", taskId="${item.taskId}", status="working", progress="...").\nTask: ${text}</supervision>`;
14
+ }
15
+ return `<supervision>Reminder from admin room ${item.adminRoomId}. Use admin(action="admin_overview", roomId="${item.adminRoomId}") to review it.\n${text}</supervision>`;
16
+ }
17
+
18
+ async function push(opts: CenterOpts, sessionID: string, ownerID: string, transport: QueueTransport,
19
+ item: Delivery, capability?: string): Promise<void> {
20
+ const text = promptText(item, capability ?? item.taskToken);
21
+ const admissionID = item.admissionID ?? item.id;
22
+ const result = transport.protocol === "v1" ? await sendAsyncNotification(transport, sessionID, text)
23
+ : await sendQueue(transport, sessionID, text, admissionID, "steer");
24
+ if (result !== "delivered") return;
25
+ const body = { id: item.id, sessionID, receiverOwnerID: ownerID };
26
+ if (capability) await protectedAdminRequest(opts, "/supervision/ack", "POST", capability, sessionID, ownerID, body);
27
+ else await request(opts, "/supervision/ack", "POST", body);
28
+ }
29
+
30
+ export async function checkSupervisionInbox(opts: CenterOpts, sessionID: string, transport: QueueTransport): Promise<void> {
31
+ if (!opts.center || (transport.protocol === "v2" && !transport.receiverOwnerID)) return;
32
+ const ownerID = transport.receiverOwnerID ?? "";
33
+ let inbox: Inbox;
34
+ try {
35
+ const query = new URLSearchParams({ sessionID, receiverOwnerID: ownerID });
36
+ inbox = await request(opts, `/supervision/inbox?${query}`, "GET") as Inbox;
37
+ } catch { return; }
38
+ if (!inbox || typeof inbox !== "object") return;
39
+
40
+ for (const item of (Array.isArray(inbox.deliveries) ? inbox.deliveries : []).slice(0, 50)) {
41
+ if (item?.kind !== "task" || !item.id || !item.taskId || !item.taskToken || typeof item.text !== "string") continue;
42
+ try { await saveTaskToken({ center: opts.center, taskId: item.taskId, sessionID, ownerID }, item.taskToken); }
43
+ catch { continue; }
44
+ try { await push(opts, sessionID, ownerID, transport, item); } catch { /* Retry the durable item next sweep. */ }
45
+ }
46
+
47
+ const hintedRooms = Array.isArray(inbox.supervisionRoomIds)
48
+ ? [...new Set(inbox.supervisionRoomIds.filter((room): room is string => typeof room === "string" && !!room))].slice(0, 50)
49
+ : [];
50
+ for (const roomId of hintedRooms) {
51
+ const capability = await loadAdminCapability({ center: opts.center, roomId, sessionID, ownerID });
52
+ if (!capability) continue;
53
+ try {
54
+ const query = new URLSearchParams({ sessionID, receiverOwnerID: ownerID, adminRoomId: roomId });
55
+ const result = await protectedAdminRequest(opts, `/supervision/inbox?${query}`, "GET", capability, sessionID, ownerID) as Inbox;
56
+ for (const item of (Array.isArray(result.deliveries) ? result.deliveries : []).slice(0, 50)) {
57
+ if (item?.kind !== "supervision" || item.adminRoomId !== roomId || !item.id || typeof item.text !== "string") continue;
58
+ try { await push(opts, sessionID, ownerID, transport, item, capability); } catch { /* Retry with the same server-issued ID next sweep. */ }
59
+ }
60
+ } catch { /* A room's protected feed does not block other admin rooms or task delivery. */ }
61
+ }
62
+ }
package/src/v1-plugin.ts CHANGED
@@ -9,6 +9,7 @@ export function createV1Server(deps: {
9
9
  runtime(input: PluginInput, transport: QueueTransport): V2Runtime;
10
10
  run<T>(runtime: V2Runtime, callback: () => T): T;
11
11
  room: ToolDefinition;
12
+ admin?: ToolDefinition;
12
13
  observe(runtime: V2Runtime, sessionID: string): Promise<void>;
13
14
  checkInbox(runtime: V2Runtime, sessionID: string): Promise<void>;
14
15
  wake(runtime: V2Runtime, sessions: ReadonlySet<string>): Promise<void>;
@@ -22,10 +23,16 @@ export function createV1Server(deps: {
22
23
  protocol: "v1" as const,
23
24
  };
24
25
  const runtime = deps.runtime(input, transport);
26
+ const adminTool = deps.admin;
25
27
  let timer: ReturnType<typeof setInterval> | undefined;
26
28
  if (deps.central) {
27
- void deps.run(runtime, () => deps.wake(runtime, sessions));
28
- timer = setInterval(() => void deps.run(runtime, () => deps.wake(runtime, sessions)), 10000);
29
+ const sweep = (pollInbox: boolean) => void deps.run(runtime, async () => {
30
+ await deps.wake(runtime, sessions).catch(() => {});
31
+ if (!pollInbox) return;
32
+ for (const sessionID of [...sessions]) await deps.checkInbox(runtime, sessionID).catch(() => {});
33
+ });
34
+ sweep(false);
35
+ timer = setInterval(() => sweep(true), 10000);
29
36
  }
30
37
  const room = {
31
38
  ...deps.room,
@@ -37,7 +44,10 @@ export function createV1Server(deps: {
37
44
  }),
38
45
  };
39
46
  return {
40
- tool: { room },
47
+ tool: { room, ...(adminTool ? { admin: {
48
+ ...adminTool,
49
+ execute: (args, context) => deps.run(runtime, () => adminTool.execute(args, context)),
50
+ } } : {}) },
41
51
  config: async (cfg: Config & { skills?: { paths?: string[]; urls?: string[] } }) => {
42
52
  cfg.skills ??= {};
43
53
  cfg.skills.paths = [...new Set([...(cfg.skills.paths ?? []), bundledSkillsPath])];
package/src/v2-plugin.ts CHANGED
@@ -6,6 +6,7 @@ import { receiverOwnerID } from "./receiver-owner";
6
6
  import { attachV2Receiver } from "./v2-receiver";
7
7
  import { observeReceiptContext, receiptDestination } from "./agent-receipts";
8
8
  import { chatroomSkill } from "./chatroom-skill";
9
+ import { adminToolDescription, adminToolSchema } from "./admin-client";
9
10
 
10
11
  type CenterOptions = { center: string; token: string; directory?: string };
11
12
  export type V2Runtime = {
@@ -19,7 +20,8 @@ export type V2Runtime = {
19
20
  export function createV2Setup(deps: {
20
21
  runtime(directory: string, transport: QueueTransport): V2Runtime;
21
22
  run<T>(runtime: V2Runtime, callback: () => T): T;
22
- execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string, permissionContext: { directory: string; worktree?: string; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> }): Promise<string>;
23
+ execute(args: z.infer<ReturnType<typeof roomSchema>>, sessionID: string, permissionContext: { directory: string; worktree?: string; signal?: AbortSignal; ask(input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }): Promise<void> }): Promise<string>;
24
+ admin?: (args: z.infer<typeof adminToolSchema>, sessionID: string, transport: QueueTransport, center: CenterOptions) => Promise<string>;
23
25
  observe(runtime: V2Runtime, sessionID: string): Promise<void>;
24
26
  poll(sessions: ReadonlySet<string>, transport: QueueTransport, center: CenterOptions): Promise<void>;
25
27
  resolveOwner?: () => Promise<string | undefined>;
@@ -43,6 +45,7 @@ export function createV2Setup(deps: {
43
45
  };
44
46
  const runtime = deps.runtime(directory, transport);
45
47
  let toolRegistration: { dispose(): Promise<void> } | undefined;
48
+ let adminRegistration: { dispose(): Promise<void> } | undefined;
46
49
  let commandRegistration: { dispose(): Promise<void> } | undefined;
47
50
  let promptRegistration: { dispose(): Promise<void> } | undefined;
48
51
  let contextRegistration: { dispose(): Promise<void> } | undefined;
@@ -77,7 +80,7 @@ export function createV2Setup(deps: {
77
80
  });
78
81
  toolRegistration = await context.tool.transform((editor) => editor.add({
79
82
  name: "room",
80
- description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; upload files and media",
83
+ description: "Chat room operations: create, join, leave and list rooms; send and poll messages; list members and announcements; manage reminders. Reminder schedules use the server timezone unless an IANA timezone is provided; once schedules require an ISO datetime. Upload files and media. read_resource saves files to a private temporary path and leaves them there until removed or system cleanup.",
81
84
  options: { codemode: false },
82
85
  input: roomSchema(),
83
86
  execute: async (args, toolContext) => {
@@ -87,6 +90,7 @@ export function createV2Setup(deps: {
87
90
  const permissionContext = {
88
91
  directory: context.location.directory,
89
92
  worktree: context.location.directory,
93
+ signal: toolContext.signal,
90
94
  ask: (input: { permission: string; patterns: string[]; always: string[]; metadata: Record<string, unknown> }) => context.permission.assert({
91
95
  sessionID: toolContext.sessionID,
92
96
  agent: toolContext.agent,
@@ -97,10 +101,19 @@ export function createV2Setup(deps: {
97
101
  source: { type: "tool", messageID: toolContext.messageID, id: toolContext.id },
98
102
  }),
99
103
  };
100
- return { content: [{ type: "text", text: await deps.execute(args, toolContext.sessionID, permissionContext) }] };
104
+ const result = await deps.execute(args, toolContext.sessionID, permissionContext);
105
+ return { content: [{ type: "text", text: result }] };
101
106
  });
102
107
  },
103
108
  }));
109
+ if (deps.admin) adminRegistration = await context.tool.transform((editor) => editor.add({
110
+ name: "admin",
111
+ description: adminToolDescription,
112
+ options: { codemode: false },
113
+ input: adminToolSchema,
114
+ execute: async (args, toolContext) => ({ content: [{ type: "text", text: await deps.run(runtime,
115
+ () => deps.admin!(args, toolContext.sessionID, transport, runtime.center)) }] }),
116
+ }));
104
117
  commandRegistration = await context.command.transform((editor) => editor.add({
105
118
  name: "room",
106
119
  description: "Chat room operations",
@@ -127,26 +140,30 @@ export function createV2Setup(deps: {
127
140
  });
128
141
  } catch (error) {
129
142
  releaseReceiver?.();
130
- await dispose(toolRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
143
+ await dispose(toolRegistration, adminRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
131
144
  throw error;
132
145
  }
133
146
  return async () => {
134
147
  releaseReceiver?.();
135
- await dispose(toolRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
148
+ await dispose(toolRegistration, adminRegistration, commandRegistration, promptRegistration, contextRegistration, skillRegistration);
136
149
  };
137
150
  };
138
151
  }
139
152
 
140
- function roomSchema() {
153
+ export function roomSchema() {
141
154
  return z.object({
142
- action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete"]),
155
+ action: z.enum(["create", "join", "leave", "list", "send", "poll", "members", "upload_resource", "read_resource", "announcement_list", "announcement_read", "announcement_write", "announcement_delete", "reminder_list", "reminder_create", "reminder_update", "reminder_delete"]),
143
156
  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."),
144
157
  roomId: z.string().optional(),
158
+ resourceId: z.string().optional(),
145
159
  filePath: z.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
146
160
  text: z.string().max(2000).optional(),
147
161
  isQuestion: z.boolean().optional(),
148
162
  announcementName: z.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
149
163
  content: z.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
164
+ reminderId: z.string().optional(),
165
+ schedule: z.discriminatedUnion("type", [z.object({ type: z.literal("once"), at: z.string(), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() }), z.object({ type: z.literal("cron"), expression: z.string().regex(/^\S+\s+\S+\s+\S+\s+\S+\s+\S+$/), timezone: z.string().refine((value) => { try { new Intl.DateTimeFormat("en", { timeZone: value }); return true; } catch { return false; } }, "timezone must be an IANA timezone").optional() })]).optional(),
166
+ paused: z.boolean().optional(),
150
167
  }).superRefine((args, ctx) => {
151
168
  if (args.action === "join" && !args.name?.trim()) {
152
169
  ctx.addIssue({ code: "custom", path: ["name"], message: "name is required to join a room" });