@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/dist/cli.js CHANGED
@@ -854,9 +854,10 @@ async function putResource(file, resource) {
854
854
  return true;
855
855
  });
856
856
  }
857
- async function listResources(file, roomID, limit = 500, offset = 0) {
857
+ async function listResources(file, roomID, limit = 500, offset = 0, beforeID) {
858
858
  const db = await initialize2(file);
859
- const items = db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?").all(roomID, limit, offset);
859
+ const cursor = beforeID ? db.query("SELECT created_at AS createdAt,id FROM resources WHERE room_id=? AND id=?").get(roomID, beforeID) : null;
860
+ const items = cursor ? db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? AND (created_at<? OR (created_at=? AND id<?)) ORDER BY created_at DESC, id DESC LIMIT ?").all(roomID, cursor.createdAt, cursor.createdAt, cursor.id, limit) : db.query("SELECT id,room_id AS roomID,name,mime_type AS mimeType,size,created_at AS createdAt,uploader_session_id AS uploaderSessionID,uploader_name AS uploaderName FROM resources WHERE room_id=? ORDER BY created_at DESC, id DESC LIMIT ? OFFSET ?").all(roomID, limit, offset);
860
861
  const total = Number(db.query("SELECT COUNT(*) AS count FROM resources WHERE room_id=?").get(roomID)?.count ?? 0);
861
862
  return { items, total };
862
863
  }
@@ -920,6 +921,10 @@ async function ensureRoomColumns(db) {
920
921
  db.exec("ALTER TABLE messages ADD COLUMN recalled_at INTEGER");
921
922
  if (!messageColumns.some((column) => column.name === "recalled_by"))
922
923
  db.exec("ALTER TABLE messages ADD COLUMN recalled_by TEXT");
924
+ if (!messageColumns.some((column) => column.name === "client_msg_id"))
925
+ db.exec("ALTER TABLE messages ADD COLUMN client_msg_id TEXT");
926
+ db.exec("DROP INDEX IF EXISTS messages_client_id");
927
+ db.exec("CREATE UNIQUE INDEX IF NOT EXISTS messages_client_id ON messages(room_id,sender_session_id,client_msg_id) WHERE client_msg_id IS NOT NULL");
923
928
  db.exec("CREATE INDEX IF NOT EXISTS messages_pending_questions ON messages(room_id,is_question,answered_by,seq)");
924
929
  db.exec("CREATE INDEX IF NOT EXISTS messages_room_recalled ON messages(room_id,recalled_at)");
925
930
  const taskColumns = db.query("PRAGMA table_info(room_tasks)").all();
@@ -1250,6 +1255,11 @@ async function readQuestions(file, roomID) {
1250
1255
  const db = await openStateDatabase(file);
1251
1256
  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 AND recalled_at IS NULL ORDER BY seq").all(roomID).map(rowMessage);
1252
1257
  }
1258
+ async function readOpenQuestionRefs(file, roomID, limit = MAX_OPEN_QUESTION_REFS) {
1259
+ const db = await openStateDatabase(file);
1260
+ const take = Number.isSafeInteger(limit) ? Math.min(MAX_OPEN_QUESTION_REFS, Math.max(1, limit)) : MAX_OPEN_QUESTION_REFS;
1261
+ return db.query("SELECT id,seq FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL AND recalled_at IS NULL ORDER BY seq LIMIT ?").all(roomID, take).map((row) => ({ id: String(row.id), seq: Number(row.seq) }));
1262
+ }
1253
1263
  async function countOpenQuestions(file, roomID) {
1254
1264
  const db = await openStateDatabase(file);
1255
1265
  const row = db.query("SELECT COUNT(*) AS count FROM messages WHERE room_id=? AND is_question=1 AND answered_by IS NULL AND recalled_at IS NULL").get(roomID);
@@ -1278,7 +1288,7 @@ async function answerQuestion(file, roomID, questionID, sessionID, text) {
1278
1288
  return { status: "ok", answer };
1279
1289
  });
1280
1290
  }
1281
- async function appendRoomMessage(file, roomID, sessionID, text, isQuestion) {
1291
+ async function appendRoomMessage(file, roomID, sessionID, text, isQuestion, clientMessageID) {
1282
1292
  const db = await openStateDatabase(file);
1283
1293
  return immediate2(db, () => {
1284
1294
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID))
@@ -1286,6 +1296,11 @@ async function appendRoomMessage(file, roomID, sessionID, text, isQuestion) {
1286
1296
  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);
1287
1297
  if (!member)
1288
1298
  return { status: "member" };
1299
+ if (clientMessageID) {
1300
+ const existing = 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 client_msg_id=? AND sender_session_id=?").get(roomID, clientMessageID, sessionID);
1301
+ if (existing)
1302
+ return { status: "ok", message: rowMessage(existing), duplicate: true };
1303
+ }
1289
1304
  const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID);
1290
1305
  const message = {
1291
1306
  id: randomUUID4(),
@@ -1296,12 +1311,12 @@ async function appendRoomMessage(file, roomID, sessionID, text, isQuestion) {
1296
1311
  createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1),
1297
1312
  ...isQuestion ? { isQuestion: true } : {}
1298
1313
  };
1299
- db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question) VALUES(?,?,?,?,?,?,?)").run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, isQuestion ? 1 : 0);
1314
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,client_msg_id) VALUES(?,?,?,?,?,?,?,?)").run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, isQuestion ? 1 : 0, clientMessageID ?? null);
1300
1315
  noteMessageInsert(db, roomID);
1301
1316
  return { status: "ok", message };
1302
1317
  });
1303
1318
  }
1304
- async function sendReply(file, roomID, targetID, sessionID, text) {
1319
+ async function sendReply(file, roomID, targetID, sessionID, text, clientMessageID) {
1305
1320
  const db = await openStateDatabase(file);
1306
1321
  return immediate2(db, () => {
1307
1322
  if (!db.query("SELECT 1 FROM rooms WHERE id=?").get(roomID))
@@ -1309,14 +1324,21 @@ async function sendReply(file, roomID, targetID, sessionID, text) {
1309
1324
  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);
1310
1325
  if (!member)
1311
1326
  return { status: "member" };
1327
+ if (clientMessageID) {
1328
+ const existing = 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 client_msg_id=? AND sender_session_id=?").get(roomID, clientMessageID, sessionID);
1329
+ if (existing)
1330
+ return { status: "ok", message: rowMessage(existing), duplicate: true };
1331
+ }
1312
1332
  const target = db.query("SELECT is_question,recalled_at FROM messages WHERE room_id=? AND id=?").get(roomID, targetID);
1313
- if (!target || target.recalled_at !== null)
1333
+ if (!target)
1314
1334
  return { status: "target" };
1335
+ if (target.recalled_at !== null)
1336
+ return { status: "recalled" };
1315
1337
  if (target.is_question)
1316
1338
  return { status: "question" };
1317
1339
  const tail = db.query("SELECT created_at FROM messages WHERE room_id=? ORDER BY seq DESC LIMIT 1").get(roomID);
1318
1340
  const message = { id: randomUUID4(), roomId: roomID, senderId: member.kind === "direct" ? sessionID : member.name, senderSessionID: sessionID, text, createdAt: Math.max(Date.now(), (tail?.created_at ?? 0) + 1), answerToMessageID: targetID };
1319
- 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);
1341
+ db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,client_msg_id) VALUES(?,?,?,?,?,?,0,?,?)").run(message.id, roomID, message.senderId, sessionID, text, message.createdAt, targetID, clientMessageID ?? null);
1320
1342
  noteMessageInsert(db, roomID);
1321
1343
  return { status: "ok", message };
1322
1344
  });
@@ -1449,22 +1471,33 @@ async function readInboxPage(file, sessionID, roomFilter, excludeSelf, limit = 1
1449
1471
  return { member: members.length > 0, items, queuedTs, hasMore, recallVersion: version };
1450
1472
  }).deferred();
1451
1473
  }
1452
- async function readHistoryPage(file, roomID, beforeSeq, limit = 100, excludeSessionID, excludeName = "") {
1474
+ function historyRowMessage(row) {
1475
+ const message = rowMessage(row);
1476
+ const recalledAt = row.recalled_at === null || row.recalled_at === undefined ? undefined : Number(row.recalled_at);
1477
+ return { ...message, ...recalledAt !== undefined ? { text: "", recalledAt, ...row.recalled_by ? { recalledBy: String(row.recalled_by) } : {} } : {}, seq: Number(row.seq) };
1478
+ }
1479
+ async function readHistoryPage(file, roomID, beforeSeq, limit = 100, excludeSessionID, excludeName = "", afterSeq) {
1453
1480
  const db = await openStateDatabase(file);
1454
1481
  return db.transaction(() => {
1455
1482
  const take = Math.min(200, Math.max(1, limit));
1456
- const rows = db.query(`SELECT seq,id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
1457
- (? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))
1458
- ORDER BY seq DESC LIMIT ?`).all(...beforeSeq === undefined ? [roomID] : [roomID, beforeSeq], excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1);
1483
+ const exclude = `(? IS NULL OR (sender_session_id IS NOT NULL AND sender_session_id!=?) OR (sender_session_id IS NULL AND sender_id!=?))`;
1484
+ if (afterSeq !== undefined) {
1485
+ const rows = db.query(`SELECT ${HISTORY_COLUMNS} FROM messages WHERE room_id=? AND seq>? AND ${exclude} ORDER BY seq ASC LIMIT ?`).all(roomID, afterSeq, excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1);
1486
+ const hasMore = rows.length > take;
1487
+ return { messages: rows.slice(0, take).map(historyRowMessage), nextBeforeSeq: null, hasMore, recallVersion: recallVersion(db, roomID) };
1488
+ }
1489
+ const rows = db.query(`SELECT ${HISTORY_COLUMNS} FROM messages WHERE room_id=? ${beforeSeq === undefined ? "" : "AND seq<? "}AND
1490
+ ${exclude} ORDER BY seq DESC LIMIT ?`).all(...beforeSeq === undefined ? [roomID] : [roomID, beforeSeq], excludeSessionID ?? null, excludeSessionID ?? null, excludeName, take + 1);
1459
1491
  const hasMore = rows.length > take;
1460
- const messages = rows.slice(0, take).reverse().map((row) => {
1461
- const message = rowMessage(row);
1462
- const recalledAt = row.recalled_at === null || row.recalled_at === undefined ? undefined : Number(row.recalled_at);
1463
- return { ...message, ...recalledAt !== undefined ? { text: "", recalledAt, ...row.recalled_by ? { recalledBy: String(row.recalled_by) } : {} } : {}, seq: Number(row.seq) };
1464
- });
1492
+ const messages = rows.slice(0, take).reverse().map(historyRowMessage);
1465
1493
  return { messages, nextBeforeSeq: hasMore ? messages[0]?.seq ?? null : null, hasMore, recallVersion: recallVersion(db, roomID) };
1466
1494
  }).deferred();
1467
1495
  }
1496
+ async function readMessage(file, roomID, messageID) {
1497
+ const db = await openStateDatabase(file);
1498
+ const row = db.query(`SELECT ${HISTORY_COLUMNS} FROM messages WHERE room_id=? AND id=?`).get(roomID, messageID);
1499
+ return row ? historyRowMessage(row) : undefined;
1500
+ }
1468
1501
  async function readMessageReceipts(file, roomID, messageIDs) {
1469
1502
  const db = await openStateDatabase(file);
1470
1503
  return db.transaction(() => {
@@ -1598,7 +1631,7 @@ var databases2, ROOM_TASK_STATUSES, ROOM_TASK_COLUMNS = "id,room_id AS roomId,ti
1598
1631
  status: row.status,
1599
1632
  participants: jsonArray(row.participants),
1600
1633
  steps: jsonArray(row.steps)
1601
- }), pause2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), adminBindings = (room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null, roomBindings = (room) => [room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null], JOIN_REQUEST_COLUMNS = "session_id AS sessionID,participant_id AS participantId,name,protocol,receiver_owner_id AS receiverOwnerID,directory,host,is_agent AS isAgent,created_at AS createdAt", MAX_RETAINED_MESSAGES = 1e6, retentionCounters;
1634
+ }), pause2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), adminBindings = (room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null, roomBindings = (room) => [room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null], JOIN_REQUEST_COLUMNS = "session_id AS sessionID,participant_id AS participantId,name,protocol,receiver_owner_id AS receiverOwnerID,directory,host,is_agent AS isAgent,created_at AS createdAt", MAX_OPEN_QUESTION_REFS = 200, MAX_RETAINED_MESSAGES = 1e6, retentionCounters, HISTORY_COLUMNS = "seq,id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by";
1602
1635
  var init_sqlite_state = __esm(() => {
1603
1636
  init_room_service();
1604
1637
  init_sqlite();
@@ -1608,7 +1641,7 @@ var init_sqlite_state = __esm(() => {
1608
1641
  });
1609
1642
 
1610
1643
  // src/state/store.ts
1611
- import { Buffer } from "node:buffer";
1644
+ import { Buffer as Buffer2 } from "node:buffer";
1612
1645
  import path4 from "node:path";
1613
1646
  import os3 from "node:os";
1614
1647
  function statePath() {
@@ -1636,8 +1669,14 @@ async function readUnreadMessages(roomID, afterTs, limit = 100, sessionID, sende
1636
1669
  async function readInboxMessages(sessionID, roomID, excludeSelf, limit = 100, afterTs) {
1637
1670
  return readInboxPage(databasePath(), sessionID, roomID, excludeSelf, limit, afterTs);
1638
1671
  }
1639
- async function readHistory(roomID, beforeSeq, limit = 100, exclude) {
1640
- return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name);
1672
+ async function readHistory(roomID, beforeSeq, limit = 100, exclude, afterSeq) {
1673
+ return readHistoryPage(databasePath(), roomID, beforeSeq, limit, exclude?.sessionID, exclude?.name, afterSeq);
1674
+ }
1675
+ async function readMessage2(roomID, messageID) {
1676
+ return readMessage(databasePath(), roomID, messageID);
1677
+ }
1678
+ async function readOpenQuestionRefs2(roomID, limit = MAX_OPEN_QUESTION_REFS) {
1679
+ return readOpenQuestionRefs(databasePath(), roomID, limit);
1641
1680
  }
1642
1681
  async function readQuestions2(roomID) {
1643
1682
  return readQuestions(databasePath(), roomID);
@@ -1654,11 +1693,11 @@ function acknowledgeQueued2(roomID, sessionID, ts) {
1654
1693
  async function answerQuestion2(roomID, questionID, sessionID, text) {
1655
1694
  return answerQuestion(databasePath(), roomID, questionID, sessionID, text);
1656
1695
  }
1657
- async function sendReply2(roomID, targetID, sessionID, text) {
1658
- return sendReply(databasePath(), roomID, targetID, sessionID, text);
1696
+ async function sendReply2(roomID, targetID, sessionID, text, clientMessageID) {
1697
+ return sendReply(databasePath(), roomID, targetID, sessionID, text, clientMessageID);
1659
1698
  }
1660
- function appendRoomMessage2(roomID, sessionID, text, isQuestion) {
1661
- return appendRoomMessage(databasePath(), roomID, sessionID, text, isQuestion);
1699
+ function appendRoomMessage2(roomID, sessionID, text, isQuestion, clientMessageID) {
1700
+ return appendRoomMessage(databasePath(), roomID, sessionID, text, isQuestion, clientMessageID);
1662
1701
  }
1663
1702
  async function readQuestionExcerpt2(roomID, questionID) {
1664
1703
  return readQuestionExcerpt(databasePath(), roomID, questionID);
@@ -1738,7 +1777,7 @@ function authHeader() {
1738
1777
  if (!pwd) {
1739
1778
  return "";
1740
1779
  }
1741
- return `Basic ${Buffer.from(`${process.env.OPENCODE_SERVER_USERNAME ?? "opencode"}:${pwd}`).toString("base64")}`;
1780
+ return `Basic ${Buffer2.from(`${process.env.OPENCODE_SERVER_USERNAME ?? "opencode"}:${pwd}`).toString("base64")}`;
1742
1781
  }
1743
1782
  function timeOf(ts) {
1744
1783
  return new Date(ts).toLocaleTimeString("en-US", { hour12: false });
@@ -2485,6 +2524,24 @@ async function request(opts, path, method, body, extraHeaders) {
2485
2524
  }
2486
2525
  return data;
2487
2526
  }
2527
+ async function getMessage(opts, roomId, messageId, sessionID) {
2528
+ return request(opts, `/rooms/${encodeURIComponent(roomId)}/messages/${encodeURIComponent(messageId)}?sessionID=${encodeURIComponent(sessionID)}`, "GET");
2529
+ }
2530
+ async function catchUp(opts, roomId, params) {
2531
+ const { sessionID, afterSeq, limit } = params;
2532
+ if (afterSeq !== undefined && (!Number.isSafeInteger(afterSeq) || afterSeq < 0)) {
2533
+ throw new Error("afterSeq must be a non-negative integer");
2534
+ }
2535
+ if (limit !== undefined && (!Number.isSafeInteger(limit) || limit < 1 || limit > 200)) {
2536
+ throw new Error("limit must be between 1 and 200");
2537
+ }
2538
+ const query = new URLSearchParams({ sessionID });
2539
+ if (afterSeq !== undefined)
2540
+ query.set("afterSeq", String(afterSeq));
2541
+ if (limit !== undefined)
2542
+ query.set("limit", String(limit));
2543
+ return await request(opts, `/rooms/${encodeURIComponent(roomId)}/catch-up?${query}`, "GET");
2544
+ }
2488
2545
  async function markQueued(opts, roomId, sessionID, ts) {
2489
2546
  assertDeliveryLease();
2490
2547
  return request(opts, "/queued", "POST", { roomId, sessionID, ts }).then(() => true).catch(() => false);
@@ -2650,6 +2707,29 @@ ${result.announcement.content}`;
2650
2707
  await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/tasks/${encodeURIComponent(args.taskId)}`, "DELETE", { sessionID });
2651
2708
  return `task deleted: ${args.taskId}`;
2652
2709
  }
2710
+ case "get_message": {
2711
+ if (!args.roomId)
2712
+ return "error: roomId is required; use a room UUID from the room list, not the room name";
2713
+ if (!args.messageId)
2714
+ return "error: messageId is required; use the full message ID returned by send, poll, or catch_up";
2715
+ return JSON.stringify(await getMessage(opts, args.roomId, args.messageId, sessionID));
2716
+ }
2717
+ case "catch_up": {
2718
+ if (!args.roomId)
2719
+ return "error: roomId is required; use a room UUID from the room list, not the room name";
2720
+ if (args.afterSeq !== undefined && (!Number.isSafeInteger(args.afterSeq) || args.afterSeq < 0)) {
2721
+ return "error: afterSeq must be a non-negative integer";
2722
+ }
2723
+ if (args.limit !== undefined && (!Number.isSafeInteger(args.limit) || args.limit < 1 || args.limit > 200)) {
2724
+ return "error: limit must be between 1 and 200";
2725
+ }
2726
+ const page = await catchUp(opts, args.roomId, {
2727
+ sessionID,
2728
+ ...args.afterSeq === undefined ? {} : { afterSeq: args.afterSeq },
2729
+ ...args.limit === undefined ? {} : { limit: args.limit }
2730
+ });
2731
+ return JSON.stringify(page);
2732
+ }
2653
2733
  case "send": {
2654
2734
  if (!args.roomId) {
2655
2735
  return "error: roomId is required; use a room UUID from the room list, not the room name";
@@ -2657,7 +2737,14 @@ ${result.announcement.content}`;
2657
2737
  if (!args.text?.trim()) {
2658
2738
  return "error: text is required; pass a non-empty message body";
2659
2739
  }
2660
- const room = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/messages`, "POST", { sessionID, text: args.text.trim(), ...args.isQuestion ? { isQuestion: true } : {} });
2740
+ const room = await request(opts, `/rooms/${encodeURIComponent(args.roomId)}/messages`, "POST", {
2741
+ sessionID,
2742
+ text: args.text.trim(),
2743
+ ...args.isQuestion ? { isQuestion: true } : {},
2744
+ ...args.replyToMessageID ? { replyToMessageID: args.replyToMessageID } : {},
2745
+ ...args.parentMessageId ? { parentMessageId: args.parentMessageId } : {},
2746
+ ...args.clientMessageID ? { clientMessageID: args.clientMessageID } : {}
2747
+ });
2661
2748
  const parsed = toRoom(room);
2662
2749
  const sentID = [...parsed.messages].reverse().find((message) => message.senderSessionID === sessionID && message.text === args.text.trim())?.id ?? parsed.messages.at(-1)?.id;
2663
2750
  return `sent: ${args.text.trim()}
@@ -2763,6 +2850,16 @@ function optionalBoolean(value, where) {
2763
2850
  throw new Error(`chatroom config: ${where} must be true or false`);
2764
2851
  return value;
2765
2852
  }
2853
+ function parseChanneld(value) {
2854
+ const raw = asRecord(value, "server.channeld");
2855
+ if (!raw)
2856
+ return;
2857
+ return {
2858
+ enabled: optionalBoolean(raw.enabled, "server.channeld.enabled"),
2859
+ config: optionalString(raw.config, "server.channeld.config"),
2860
+ stateFile: optionalString(raw.stateFile, "server.channeld.stateFile")
2861
+ };
2862
+ }
2766
2863
  function parseServer(value) {
2767
2864
  const raw = asRecord(value, "server");
2768
2865
  if (!raw)
@@ -2781,7 +2878,8 @@ function parseServer(value) {
2781
2878
  token: optionalString(raw.token, "server.token"),
2782
2879
  stateDir: optionalString(raw.stateDir, "server.stateDir"),
2783
2880
  wakeServeUrl: optionalString(raw.wakeServeUrl, "server.wakeServeUrl"),
2784
- maxFileSizeMb
2881
+ maxFileSizeMb,
2882
+ channeld: parseChanneld(raw.channeld)
2785
2883
  };
2786
2884
  }
2787
2885
  function parseClient(value) {
@@ -2961,13 +3059,21 @@ function resolveServerSettings(file, env = process.env) {
2961
3059
  if (maxFileSizeMb !== undefined && (!Number.isFinite(maxFileSizeMb) || maxFileSizeMb <= 0)) {
2962
3060
  throw new Error("CHAT_ROOM_MAX_FILE_SIZE_MB must be a positive finite number");
2963
3061
  }
3062
+ const channeldRaw = envValue(env, "CHAT_ROOM_CHANNELD");
3063
+ const channeldConfig = envValue(env, "CHAT_ROOM_CHANNELD_CONFIG") ?? file?.server?.channeld?.config;
3064
+ const channeldEnabled = channeldRaw === undefined ? file?.server?.channeld?.enabled ?? Boolean(channeldConfig) : channeldRaw === "1" || channeldRaw === "true";
2964
3065
  return {
2965
3066
  host: envValue(env, "CHAT_ROOM_SERVER_HOST") ?? envValue(env, "HOST") ?? file?.server?.host ?? "0.0.0.0",
2966
3067
  port,
2967
3068
  token: envValue(env, "CHAT_ROOM_SERVER_TOKEN") ?? file?.server?.token ?? file?.token,
2968
3069
  stateDir: envValue(env, "CHAT_ROOM_STATE_DIR") ?? file?.server?.stateDir,
2969
3070
  wakeServeUrl: envValue(env, "CHAT_ROOM_WAKE_SERVE_URL") ?? file?.server?.wakeServeUrl ?? "",
2970
- maxFileSizeMb
3071
+ maxFileSizeMb,
3072
+ channeld: {
3073
+ enabled: channeldEnabled,
3074
+ config: channeldConfig,
3075
+ stateFile: file?.server?.channeld?.stateFile
3076
+ }
2971
3077
  };
2972
3078
  }
2973
3079
  function resolveClientSettings(file, env = process.env) {
@@ -3969,11 +4075,15 @@ var init_plugin_notifications = __esm(() => {
3969
4075
  });
3970
4076
 
3971
4077
  // src/agent/chatroom-skill.ts
3972
- import { readFileSync as readFileSync3 } from "node:fs";
4078
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "node:fs";
3973
4079
  import { fileURLToPath } from "node:url";
3974
- var path8, source, metadata, content, description, chatroomSkill;
4080
+ var candidates, path8, source, metadata, content, description, chatroomSkill;
3975
4081
  var init_chatroom_skill = __esm(() => {
3976
- path8 = fileURLToPath(new URL("../../skills/chatroom/SKILL.md", import.meta.url));
4082
+ candidates = [
4083
+ new URL("../../skills/chatroom/SKILL.md", import.meta.url),
4084
+ new URL("../skills/chatroom/SKILL.md", import.meta.url)
4085
+ ].map((url) => fileURLToPath(url));
4086
+ path8 = candidates.find((candidate) => existsSync2(candidate)) ?? candidates[0];
3977
4087
  source = readFileSync3(path8, "utf8");
3978
4088
  [, metadata = "", content = source] = source.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/) ?? [];
3979
4089
  description = metadata.match(/^description:\s*(.+)$/m)?.[1]?.trim();
@@ -4237,7 +4347,7 @@ function createV2Setup(deps) {
4237
4347
  });
4238
4348
  toolRegistration = await context.tool.transform((editor) => editor.add({
4239
4349
  name: "room",
4240
- 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.",
4350
+ 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.",
4241
4351
  options: { codemode: false },
4242
4352
  input: roomSchema(),
4243
4353
  execute: async (args, toolContext) => {
@@ -4336,13 +4446,19 @@ The user invoked /room. Use the room tool to perform this command.`,
4336
4446
  }
4337
4447
  function roomSchema() {
4338
4448
  return z2.object({
4339
- action: z2.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"]),
4449
+ action: z2.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"]),
4340
4450
  name: z2.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
4341
4451
  roomId: z2.string().optional(),
4452
+ messageId: z2.string().optional().describe("For get_message: the full message ID returned by send, poll, or catch_up."),
4342
4453
  resourceId: z2.string().optional(),
4343
4454
  filePath: z2.string().optional().describe("Local regular file to upload; central mode only; requires host read permission."),
4344
4455
  text: z2.string().max(5000).optional(),
4345
4456
  isQuestion: z2.boolean().optional(),
4457
+ parentMessageId: z2.string().optional().describe("For send: the ID of the message this one answers or replies to."),
4458
+ replyToMessageID: z2.string().optional().describe("Legacy alias of parentMessageId for send."),
4459
+ clientMessageID: z2.string().max(100).optional().describe("For send: idempotency key; retrying with the same ID and parent creates one message."),
4460
+ afterSeq: z2.number().int().min(0).optional().describe("For catch_up: return messages with seq greater than this cursor; omit to start at 0."),
4461
+ limit: z2.number().int().min(1).max(200).optional().describe("For catch_up: page size from 1 to 200; the server default is 50."),
4346
4462
  announcementName: z2.string().optional().describe("Name of a room announcement; distinct from participant or room name."),
4347
4463
  content: z2.string().optional().describe("Announcement content, at most 5000 Unicode characters."),
4348
4464
  taskId: z2.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
@@ -5029,7 +5145,7 @@ var connection, centerUrl, centerToken, serveWakeUrl, runtimeContext, defaultRun
5029
5145
  const explicitV2Join = runtime.protocol === "v2" && (args.action === "create" || args.action === "join");
5030
5146
  const receiverOwnerID = explicitV2Join && runtime.transport.verifySession ? await runtime.transport.verifySession(context.sessionID) : undefined;
5031
5147
  if (runtime.center.center) {
5032
- if (args.action !== "poll") {
5148
+ if (args.action !== "poll" && args.action !== "get_message" && args.action !== "catch_up") {
5033
5149
  checkCenterInbox(runtime.center, context.sessionID, runtime.transport);
5034
5150
  }
5035
5151
  return await centerAction(runtime.center, {
@@ -5168,6 +5284,12 @@ var connection, centerUrl, centerToken, serveWakeUrl, runtimeContext, defaultRun
5168
5284
  if (!args.roomId) {
5169
5285
  return "error: roomId is required; use a room UUID from the room list, not the room name";
5170
5286
  }
5287
+ if (args.parentMessageId || args.replyToMessageID) {
5288
+ return "error: replies require central server mode (CHAT_ROOM_SERVER_URL)";
5289
+ }
5290
+ if (args.clientMessageID) {
5291
+ return "error: clientMessageID requires central server mode (CHAT_ROOM_SERVER_URL)";
5292
+ }
5171
5293
  if (!args.text?.trim()) {
5172
5294
  return "error: text is required; pass a non-empty message body";
5173
5295
  }
@@ -5197,6 +5319,9 @@ ${formatRoom(svc, room)}`;
5197
5319
  `) + (pollPage?.hasMore ? `
5198
5320
  More unread messages remain; poll again.` : "");
5199
5321
  }
5322
+ case "get_message":
5323
+ case "catch_up":
5324
+ return `error: ${args.action} requires central server mode (CHAT_ROOM_SERVER_URL)`;
5200
5325
  default:
5201
5326
  return "error: unsupported room action";
5202
5327
  }
@@ -5252,14 +5377,19 @@ var init_plugin = __esm(() => {
5252
5377
  restoreScans2 = new Map;
5253
5378
  READ_ONLY_ACTIONS = new Set(["list", "members", "poll", "join_status", "announcement_list", "announcement_read", "task_list"]);
5254
5379
  roomArgs = z3.object({
5255
- action: z3.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "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"]),
5380
+ action: z3.enum(["create", "join", "join_status", "leave", "list", "send", "poll", "recall", "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"]),
5256
5381
  name: z3.string().max(64).optional().describe("For join: your own participant display name, NOT the room name (required). For create: the new room name."),
5257
5382
  roomId: z3.string().optional().describe("Room UUID, not the room name. Required for resource actions and every room-scoped action."),
5258
- messageId: z3.string().optional().describe("For recall: the full message ID returned by send or poll; required for recall."),
5383
+ messageId: z3.string().optional().describe("For recall and get_message: the full message ID returned by send, poll, or catch_up."),
5259
5384
  resourceId: z3.string().optional().describe("Resource UUID returned by upload_resource. read_resource and delete_resource also require roomId."),
5260
5385
  filePath: z3.string().optional().describe("Absolute path to a regular local file to upload; central mode only; requires host read permission."),
5261
5386
  text: z3.string().max(5000).optional().describe("Message text, at most 5000 characters; required for send."),
5262
5387
  isQuestion: z3.boolean().optional().describe("For send: mark the message as a question awaiting an answer."),
5388
+ parentMessageId: z3.string().optional().describe("For send: the ID of the message this one answers or replies to."),
5389
+ replyToMessageID: z3.string().optional().describe("Legacy alias of parentMessageId for send."),
5390
+ clientMessageID: z3.string().max(100).optional().describe("For send: idempotency key; retrying with the same ID and parent creates one message."),
5391
+ afterSeq: z3.number().int().min(0).optional().describe("For catch_up: return messages with seq greater than this cursor; omit to start at 0."),
5392
+ limit: z3.number().int().min(1).max(200).optional().describe("For catch_up: page size from 1 to 200; the server default is 50."),
5263
5393
  announcementName: z3.string().optional().describe("Exact announcement name from announcement_list; distinct from participant or room name."),
5264
5394
  content: z3.string().optional().describe("Announcement content, at most 5000 Unicode characters; required for announcement_write."),
5265
5395
  taskId: z3.string().optional().describe("Task UUID from task_list; required for task_update and task_delete."),
@@ -5295,7 +5425,7 @@ var init_plugin = __esm(() => {
5295
5425
  }
5296
5426
  });
5297
5427
  room = tool({
5298
- description: 'Chat room operations: create, join, leave and list rooms; send, poll and recall messages; list members, announcements and tasks; create, update and delete room tasks; manage reminders. Sent and polled messages carry full message IDs; recall takes roomId plus messageId and withdraws the message for everyone (agents their own, room admins any). 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. Resource actions need both roomId (the room UUID) and resourceId (the UUID in the marker); the marker alone does not identify the room. 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. Room joinPolicy "approval" makes join a pending request: you are not a member while pending, never claim otherwise, and use join_status to check whether a human administrator approved it.',
5428
+ description: "Chat room operations: create, join, leave and list rooms; send, poll and recall 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 to a message. List members, announcements and tasks; create, update and delete room tasks; manage reminders. Sent and polled messages carry full message IDs; recall takes roomId plus messageId and withdraws the message for everyone (agents their own, room admins any). 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. Resource actions need both roomId (the room UUID) and resourceId (the UUID in the marker); the marker alone does not identify the room. 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. Room joinPolicy \"approval\" makes join a pending request: you are not a member while pending, never claim otherwise, and use join_status to check whether a human administrator approved it.",
5299
5429
  args: roomArgs.shape,
5300
5430
  execute: roomExecute
5301
5431
  });
@@ -5338,7 +5468,7 @@ var init_plugin = __esm(() => {
5338
5468
 
5339
5469
  // server/http-server.ts
5340
5470
  import { createServer } from "node:http";
5341
- import { Buffer as Buffer2 } from "node:buffer";
5471
+ import { Buffer as Buffer3 } from "node:buffer";
5342
5472
  import { Readable as Readable2 } from "node:stream";
5343
5473
  import { pipeline } from "node:stream/promises";
5344
5474
  function requestURL(req, hostname, port) {
@@ -5364,7 +5494,7 @@ function sendJson(res, status, message) {
5364
5494
  return;
5365
5495
  }
5366
5496
  const body = JSON.stringify({ error: message });
5367
- res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer2.byteLength(body) });
5497
+ res.writeHead(status, { "Content-Type": "application/json", "Content-Length": Buffer3.byteLength(body) });
5368
5498
  res.end(body);
5369
5499
  }
5370
5500
  function rejectTooLarge(req, res) {
@@ -5494,9 +5624,9 @@ var init_http_server = __esm(() => {
5494
5624
  });
5495
5625
 
5496
5626
  // src/runtime/watch.ts
5497
- import { Buffer as Buffer3 } from "node:buffer";
5627
+ import { Buffer as Buffer4 } from "node:buffer";
5498
5628
  import { createHash as createHash6, randomBytes, timingSafeEqual } from "node:crypto";
5499
- import { realpathSync } from "node:fs";
5629
+ import { existsSync as existsSync3, realpathSync } from "node:fs";
5500
5630
  import { appendFile, chmod as chmod2, link, mkdir as mkdir2, readFile as readFile2, rename as rename2, unlink, writeFile as writeFile2 } from "node:fs/promises";
5501
5631
  import { spawn } from "node:child_process";
5502
5632
  import { fileURLToPath as fileURLToPath3 } from "node:url";
@@ -5600,8 +5730,8 @@ async function reserveWatcher(record, beforePublish) {
5600
5730
  function authorized(request, token) {
5601
5731
  const supplied = request.headers.get("Authorization") ?? "";
5602
5732
  const expected = `Bearer ${token}`;
5603
- const a = Buffer3.from(supplied);
5604
- const b = Buffer3.from(expected);
5733
+ const a = Buffer4.from(supplied);
5734
+ const b = Buffer4.from(expected);
5605
5735
  return a.length === b.length && timingSafeEqual(a, b);
5606
5736
  }
5607
5737
  async function watcherSweep(deps = defaultSweepDeps()) {
@@ -5715,6 +5845,23 @@ function sameController(value, record, status) {
5715
5845
  const body = value;
5716
5846
  return body.status === status && body.pid === record.pid && body.instanceID === record.instanceID && body.nonce === record.nonce;
5717
5847
  }
5848
+ function cliEntryPath() {
5849
+ const argv = process.argv[1];
5850
+ if (argv) {
5851
+ let resolved = path12.resolve(argv);
5852
+ try {
5853
+ resolved = realpathSync(resolved);
5854
+ } catch {}
5855
+ if (/^cli\.(?:ts|js)$/.test(path12.basename(resolved)))
5856
+ return resolved;
5857
+ }
5858
+ const candidates = [
5859
+ fileURLToPath3(new URL("../../dist/cli.js", import.meta.url)),
5860
+ fileURLToPath3(new URL("../../cli.ts", import.meta.url)),
5861
+ fileURLToPath3(new URL("../cli.js", import.meta.url))
5862
+ ];
5863
+ return candidates.find((candidate) => existsSync3(candidate)) ?? candidates[0];
5864
+ }
5718
5865
  async function watchStatus() {
5719
5866
  const record = await readRecord();
5720
5867
  if (!record) {
@@ -5729,7 +5876,7 @@ async function watchStatus() {
5729
5876
  return watcherProcessMayExist(record.pid) && Date.now() - (record.createdAt ?? 0) < 30000 ? "starting" : "unavailable";
5730
5877
  return await control(record) ? "running" : "unavailable";
5731
5878
  }
5732
- async function startWatcher(beforePublish) {
5879
+ async function startWatcher(beforePublish, readyTimeoutMs = 20000) {
5733
5880
  await privateDirectory();
5734
5881
  const own = { phase: "starting", token: randomBytes(32).toString("base64url"), nonce: randomBytes(16).toString("hex"), instanceID: randomBytes(16).toString("hex"), pid: process.pid, createdAt: Date.now() };
5735
5882
  const reservation = await reserveWatcher(own, beforePublish);
@@ -5751,9 +5898,9 @@ async function startWatcher(beforePublish) {
5751
5898
  }
5752
5899
  throw new Error("watcher state exists or is starting; no process was signaled");
5753
5900
  }
5754
- const cli = fileURLToPath3(new URL("../../cli.ts", import.meta.url));
5901
+ const cli = cliEntryPath();
5755
5902
  let childError;
5756
- const child = spawn(process.execPath, [path12.resolve(cli), "watch", "run"], {
5903
+ const child = spawn(process.execPath, [cli, "watch", "run"], {
5757
5904
  detached: true,
5758
5905
  stdio: "ignore",
5759
5906
  env: { ...process.env, CHAT_ROOM_WATCH_CONTROL_TOKEN: own.token, CHAT_ROOM_WATCH_START_NONCE: own.nonce, CHAT_ROOM_WATCH_INSTANCE_ID: own.instanceID }
@@ -5762,7 +5909,7 @@ async function startWatcher(beforePublish) {
5762
5909
  childError = error;
5763
5910
  });
5764
5911
  child.unref();
5765
- const deadline = Date.now() + 20000;
5912
+ const deadline = Date.now() + readyTimeoutMs;
5766
5913
  while (Date.now() < deadline) {
5767
5914
  if (childError) {
5768
5915
  await removeRecord(own.token, own.nonce);
@@ -5780,7 +5927,16 @@ async function startWatcher(beforePublish) {
5780
5927
  }
5781
5928
  await new Promise((resolve) => setTimeout(resolve, 100));
5782
5929
  }
5783
- throw new Error("watcher did not become ready; its process was not signaled");
5930
+ child.kill("SIGTERM");
5931
+ if (child.exitCode === null) {
5932
+ await Promise.race([
5933
+ new Promise((resolve) => child.once("exit", resolve)),
5934
+ new Promise((resolve) => setTimeout(resolve, 1000))
5935
+ ]);
5936
+ }
5937
+ await removeRecord(own.token, own.nonce);
5938
+ releaseWatcherClaim(profile(), own.instanceID);
5939
+ throw new Error("watcher did not become ready; its process was stopped");
5784
5940
  }
5785
5941
  async function stopWatcher() {
5786
5942
  const record = await readRecord();
@@ -6105,6 +6261,128 @@ var init_history_route = __esm(() => {
6105
6261
  init_store();
6106
6262
  });
6107
6263
 
6264
+ // server/addressing-routes.ts
6265
+ function decode(value) {
6266
+ try {
6267
+ return decodeURIComponent(value);
6268
+ } catch {
6269
+ return;
6270
+ }
6271
+ }
6272
+ async function memberContext(roomID, sessionID) {
6273
+ return readState2((service, registry) => {
6274
+ const room = service.listRooms().find((candidate) => candidate.id === roomID);
6275
+ const entry = sessionID && sessionID.length <= MAX_SESSION ? registry[roomID]?.[sessionID] : undefined;
6276
+ const allowed = Boolean(room && entry) && (room.kind === "direct" ? Boolean(room.directSessionIDs?.includes(sessionID)) : service.containsParticipant(roomID, entry.name));
6277
+ return {
6278
+ allowed,
6279
+ name: entry?.name ?? "",
6280
+ roomKind: room?.kind === "direct" ? "direct" : "group",
6281
+ senderNames: new Map([...room?.participants.values() ?? []].map((participant) => [participant.id, participant.name]))
6282
+ };
6283
+ });
6284
+ }
6285
+ function extractResourceIDs(text) {
6286
+ return [...new Set([...text.matchAll(RESOURCE_MARKER)].map((match) => match[1]))];
6287
+ }
6288
+ function messageView(message, senderName) {
6289
+ if (message.recalledAt !== undefined) {
6290
+ return {
6291
+ id: message.id,
6292
+ roomId: message.roomId,
6293
+ seq: message.seq,
6294
+ senderId: message.senderId,
6295
+ createdAt: message.createdAt,
6296
+ recalled: true,
6297
+ recalledAt: message.recalledAt,
6298
+ recalledBy: message.recalledBy ?? null,
6299
+ text: null,
6300
+ unavailable: "recalled",
6301
+ resourceIDs: []
6302
+ };
6303
+ }
6304
+ return {
6305
+ id: message.id,
6306
+ roomId: message.roomId,
6307
+ seq: message.seq,
6308
+ senderId: message.senderId,
6309
+ senderName,
6310
+ text: message.text,
6311
+ createdAt: message.createdAt,
6312
+ isQuestion: message.isQuestion === true,
6313
+ parentMessageId: message.answerToMessageID ?? null,
6314
+ answeredByMessageId: message.answeredByMessageID ?? null,
6315
+ recalled: false,
6316
+ resourceIDs: extractResourceIDs(message.text)
6317
+ };
6318
+ }
6319
+ async function getMessage2(req, url, match) {
6320
+ if (req.method !== "GET")
6321
+ return json({ error: "method not allowed" }, 405);
6322
+ const roomID = decode(match[1]), messageID = decode(match[2]);
6323
+ if (roomID === undefined || messageID === undefined)
6324
+ return json({ error: "not found" }, 404);
6325
+ const sessionID = url.searchParams.get("sessionID") ?? "";
6326
+ const access = await memberContext(roomID, sessionID);
6327
+ if (!access.allowed)
6328
+ return json({ error: "not found" }, 404);
6329
+ const message = await readMessage2(roomID, messageID);
6330
+ if (!message)
6331
+ return json({ error: "not found" }, 404);
6332
+ return json(messageView(message, access.senderNames.get(message.senderId) ?? message.senderId));
6333
+ }
6334
+ async function catchUp2(req, url, match) {
6335
+ if (req.method !== "GET")
6336
+ return json({ error: "method not allowed" }, 405);
6337
+ const roomID = decode(match[1]);
6338
+ if (roomID === undefined)
6339
+ return json({ error: "not found" }, 404);
6340
+ const afterText = url.searchParams.get("afterSeq");
6341
+ const limitText = url.searchParams.get("limit");
6342
+ if (afterText !== null && !/^\d+$/.test(afterText) || limitText !== null && !/^\d+$/.test(limitText)) {
6343
+ return json({ error: "afterSeq must be a non-negative integer and limit must be 1-200" }, 400);
6344
+ }
6345
+ const afterSeq = afterText === null ? 0 : Number(afterText);
6346
+ const limit = limitText === null ? DEFAULT_LIMIT : Number(limitText);
6347
+ if (!Number.isSafeInteger(afterSeq) || !Number.isSafeInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
6348
+ return json({ error: "afterSeq must be a non-negative integer and limit must be 1-200" }, 400);
6349
+ }
6350
+ const sessionID = url.searchParams.get("sessionID") ?? "";
6351
+ const access = await memberContext(roomID, sessionID);
6352
+ if (!access.allowed)
6353
+ return json({ error: "not found" }, 404);
6354
+ const page = await readHistory(roomID, undefined, limit, undefined, afterSeq);
6355
+ const messages = page.messages.map((message) => messageView(message, access.senderNames.get(message.senderId) ?? message.senderId));
6356
+ const unreadMentions = page.messages.filter((message) => message.recalledAt === undefined && explicitlyAddresses(message, access.name, sessionID, access.roomKind)).map((message) => ({ id: message.id, seq: message.seq }));
6357
+ const [unansweredQuestions, unansweredQuestionCount] = await Promise.all([
6358
+ readOpenQuestionRefs2(roomID),
6359
+ countOpenQuestions2(roomID)
6360
+ ]);
6361
+ return json({
6362
+ messages,
6363
+ nextCursor: page.messages.at(-1)?.seq ?? afterSeq,
6364
+ hasMore: page.hasMore,
6365
+ unreadMentions,
6366
+ unreadMentionCount: unreadMentions.length,
6367
+ unansweredQuestions,
6368
+ unansweredQuestionCount
6369
+ });
6370
+ }
6371
+ async function addressingRoutes(req, url) {
6372
+ const message = url.pathname.match(/^\/rooms\/([^/]+)\/messages\/([^/]+)$/);
6373
+ if (message)
6374
+ return getMessage2(req, url, message);
6375
+ const resume = url.pathname.match(/^\/rooms\/([^/]+)\/catch-up$/);
6376
+ if (resume)
6377
+ return catchUp2(req, url, resume);
6378
+ return;
6379
+ }
6380
+ var json = (body, status = 200) => Response.json(body, { status }), MAX_SESSION = 128, DEFAULT_LIMIT = 50, MAX_LIMIT = 200, RESOURCE_MARKER;
6381
+ var init_addressing_routes = __esm(() => {
6382
+ init_store();
6383
+ RESOURCE_MARKER = /\[\[resource:([0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\]\]/gi;
6384
+ });
6385
+
6108
6386
  // server/json-body.ts
6109
6387
  async function jsonObject(req) {
6110
6388
  try {
@@ -6120,57 +6398,57 @@ async function messageRecallRoutes(req, url) {
6120
6398
  const recall = url.pathname.match(/^\/rooms\/([^/]+)\/messages\/([^/]+)\/recall$/);
6121
6399
  if (recall) {
6122
6400
  if (req.method !== "POST")
6123
- return json({ error: "method not allowed" }, 405);
6401
+ return json2({ error: "method not allowed" }, 405);
6124
6402
  const roomID = decodeURIComponent(recall[1]);
6125
6403
  const messageID = decodeURIComponent(recall[2]);
6126
6404
  const body = await jsonObject(req);
6127
6405
  if (!body)
6128
- return json({ error: "JSON object body is required" }, 400);
6406
+ return json2({ error: "JSON object body is required" }, 400);
6129
6407
  const sessionID = typeof body.sessionID === "string" ? body.sessionID.trim() : "";
6130
- if (!sessionID || sessionID.length > MAX_SESSION)
6131
- return json({ error: "sessionID is required" }, 400);
6408
+ if (!sessionID || sessionID.length > MAX_SESSION2)
6409
+ return json2({ error: "sessionID is required" }, 400);
6132
6410
  const result = await recallMessage2(roomID, messageID, sessionID);
6133
6411
  if (result.status === "missing")
6134
- return json({ error: "message not found" }, 404);
6412
+ return json2({ error: "message not found" }, 404);
6135
6413
  if (result.status === "member")
6136
- return json({ error: "session is not a room member" }, 409);
6414
+ return json2({ error: "session is not a room member" }, 409);
6137
6415
  if (result.status === "forbidden")
6138
- return json({ error: "not allowed to recall this message" }, 403);
6416
+ return json2({ error: "not allowed to recall this message" }, 403);
6139
6417
  if (result.status !== "ok")
6140
- return json({ error: "recall failed" }, 409);
6141
- return json({ ok: true, messageID: result.messageID, recalledAt: result.recalledAt, recalledBy: result.recalledBy });
6418
+ return json2({ error: "recall failed" }, 409);
6419
+ return json2({ ok: true, messageID: result.messageID, recalledAt: result.recalledAt, recalledBy: result.recalledBy });
6142
6420
  }
6143
6421
  const content = url.pathname.match(/^\/rooms\/([^/]+)\/messages\/([^/]+)\/content$/);
6144
6422
  if (!content)
6145
6423
  return;
6146
6424
  if (req.method !== "GET")
6147
- return json({ error: "method not allowed" }, 405);
6425
+ return json2({ error: "method not allowed" }, 405);
6148
6426
  const roomID = decodeURIComponent(content[1]);
6149
6427
  const messageID = decodeURIComponent(content[2]);
6150
6428
  const sessionID = url.searchParams.get("sessionID") ?? "";
6151
- if (!sessionID || sessionID.length > MAX_SESSION)
6152
- return json({ error: "sessionID is required" }, 400);
6429
+ if (!sessionID || sessionID.length > MAX_SESSION2)
6430
+ return json2({ error: "sessionID is required" }, 400);
6153
6431
  const result = await revealMessageContent2(roomID, messageID, sessionID);
6154
6432
  if (result.status === "missing")
6155
- return json({ error: "message not found" }, 404);
6433
+ return json2({ error: "message not found" }, 404);
6156
6434
  if (result.status === "member")
6157
- return json({ error: "session is not a room member" }, 409);
6435
+ return json2({ error: "session is not a room member" }, 409);
6158
6436
  if (result.status === "hidden")
6159
- return json({ error: "message is not recalled" }, 409);
6437
+ return json2({ error: "message is not recalled" }, 409);
6160
6438
  if (result.status !== "ok")
6161
- return json({ error: "message not found" }, 404);
6162
- return json({ messageID: result.messageID, text: result.text, senderId: result.senderId, createdAt: result.createdAt, recalledAt: result.recalledAt });
6439
+ return json2({ error: "message not found" }, 404);
6440
+ return json2({ messageID: result.messageID, text: result.text, senderId: result.senderId, createdAt: result.createdAt, recalledAt: result.recalledAt });
6163
6441
  }
6164
- var json = (body, status = 200) => Response.json(body, { status }), MAX_SESSION = 128;
6442
+ var json2 = (body, status = 200) => Response.json(body, { status }), MAX_SESSION2 = 128;
6165
6443
  var init_message_recall_routes = __esm(() => {
6166
6444
  init_store();
6167
6445
  });
6168
6446
 
6169
6447
  // server/admin-state.ts
6170
- import { Buffer as Buffer4 } from "node:buffer";
6448
+ import { Buffer as Buffer5 } from "node:buffer";
6171
6449
  import { createHash as createHash7, randomBytes as randomBytes2, randomUUID as randomUUID10, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
6172
6450
  function matchesHash(value, stored) {
6173
- const left = Buffer4.from(hash2(value), "hex"), right = Buffer4.from(stored, "hex");
6451
+ const left = Buffer5.from(hash2(value), "hex"), right = Buffer5.from(stored, "hex");
6174
6452
  return right.length === 32 && timingSafeEqual2(left, right);
6175
6453
  }
6176
6454
  async function ensureAdminSchema() {
@@ -6509,10 +6787,10 @@ function resourcePath(resource) {
6509
6787
  throw new ResourceError(404, "resource not found");
6510
6788
  return path13.join(roomDirectory(resource.roomID), resource.id);
6511
6789
  }
6512
- async function listRoomResources(roomID, limit = 500, offset = 0) {
6790
+ async function listRoomResources(roomID, limit = 500, offset = 0, beforeID) {
6513
6791
  if (!uuid2.test(roomID))
6514
6792
  throw new ResourceError(404, "room not found");
6515
- return listResources(databasePath(), roomID, limit, offset);
6793
+ return listResources(databasePath(), roomID, limit, offset, beforeID);
6516
6794
  }
6517
6795
  async function findResource(roomID, id) {
6518
6796
  if (!uuid2.test(id))
@@ -6559,12 +6837,12 @@ async function roomManagement(req, url) {
6559
6837
  if (req.method === "POST" && p === "/direct") {
6560
6838
  const body = await objectBody(req);
6561
6839
  if (!body)
6562
- return json2({ error: "JSON object body is required" }, 400);
6840
+ return json3({ error: "JSON object body is required" }, 400);
6563
6841
  const roomId = typeof body.roomId === "string" ? body.roomId : "";
6564
6842
  const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
6565
6843
  const targetSessionID = typeof body.targetSessionID === "string" ? body.targetSessionID : "";
6566
6844
  if (!roomId || !sessionID || !targetSessionID || sessionID === targetSessionID || sessionID.length > 128 || targetSessionID.length > 128)
6567
- return json2({ error: "roomId and distinct sessionIDs are required" }, 400);
6845
+ return json3({ error: "roomId and distinct sessionIDs are required" }, 400);
6568
6846
  const result = await mutate((svc, registry) => {
6569
6847
  svc.getRoom(roomId);
6570
6848
  const actor = registry[roomId]?.[sessionID], target = registry[roomId]?.[targetSessionID];
@@ -6590,18 +6868,18 @@ async function roomManagement(req, url) {
6590
6868
  }
6591
6869
  return { room: direct, created: !existing };
6592
6870
  });
6593
- return json2(await roomPayload(result.room), result.created ? 201 : 200);
6871
+ return json3(await roomPayload(result.room), result.created ? 201 : 200);
6594
6872
  }
6595
6873
  const kick = p.match(/^\/rooms\/([^/]+)\/kick$/);
6596
6874
  if (kick && req.method === "POST") {
6597
6875
  const roomId = decodeURIComponent(kick[1]);
6598
6876
  const body = await objectBody(req);
6599
6877
  if (!body)
6600
- return json2({ error: "JSON object body is required" }, 400);
6878
+ return json3({ error: "JSON object body is required" }, 400);
6601
6879
  const actor = typeof body.sessionID === "string" ? body.sessionID : "";
6602
6880
  const target = typeof body.targetSessionID === "string" ? body.targetSessionID : "";
6603
6881
  if (!actor || !target || actor === target || actor.length > 128 || target.length > 128)
6604
- return json2({ error: "distinct sessionIDs are required" }, 400);
6882
+ return json3({ error: "distinct sessionIDs are required" }, 400);
6605
6883
  const agentBinding = await tx((db) => {
6606
6884
  const b = binding(db, roomId);
6607
6885
  return b && b.target_room_id === roomId && b.session_id === actor && validCurrent(db, b) && hasAdminCapability(req, b) ? b : undefined;
@@ -6650,29 +6928,29 @@ async function roomManagement(req, url) {
6650
6928
  return { message, target };
6651
6929
  });
6652
6930
  clearPendingAdmission(result.target, roomId, Number.MAX_SAFE_INTEGER);
6653
- return json2({ ok: true, createdAt: result.message.createdAt });
6931
+ return json3({ ok: true, createdAt: result.message.createdAt });
6654
6932
  }
6655
6933
  const edit = p.match(/^\/rooms\/([^/]+)$/);
6656
6934
  if (edit && req.method === "PATCH") {
6657
6935
  const roomId = decodeURIComponent(edit[1]);
6658
6936
  const body = await objectBody(req);
6659
6937
  if (!body)
6660
- return json2({ error: "JSON object body is required" }, 400);
6938
+ return json3({ error: "JSON object body is required" }, 400);
6661
6939
  const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
6662
6940
  if (!sessionID || sessionID.length > 128)
6663
- return json2({ error: "sessionID is required" }, 400);
6941
+ return json3({ error: "sessionID is required" }, 400);
6664
6942
  if (body.name !== undefined && (typeof body.name !== "string" || !body.name.trim() || body.name.trim().length > 64))
6665
- return json2({ error: "name must be 1-64 characters" }, 400);
6943
+ return json3({ error: "name must be 1-64 characters" }, 400);
6666
6944
  if (body.description !== undefined && (typeof body.description !== "string" || body.description.length > 2000))
6667
- return json2({ error: "description too long (max 2000)" }, 400);
6945
+ return json3({ error: "description too long (max 2000)" }, 400);
6668
6946
  if (body.joinPolicy !== undefined && body.joinPolicy !== "open" && body.joinPolicy !== "approval")
6669
- return json2({ error: "joinPolicy must be open or approval" }, 400);
6947
+ return json3({ error: "joinPolicy must be open or approval" }, 400);
6670
6948
  if (body.adminSessionID !== undefined && body.adminSessionID !== null && (typeof body.adminSessionID !== "string" || body.adminSessionID.length > 128))
6671
- return json2({ error: "invalid adminSessionID" }, 400);
6949
+ return json3({ error: "invalid adminSessionID" }, 400);
6672
6950
  if (body.adminIds !== undefined && (!Array.isArray(body.adminIds) || body.adminIds.length > 50 || body.adminIds.some((name) => typeof name !== "string" || !name.trim() || name.trim().length > 64)))
6673
- return json2({ error: "adminIds must be up to 50 member names" }, 400);
6951
+ return json3({ error: "adminIds must be up to 50 member names" }, 400);
6674
6952
  if (body.successorId !== undefined && body.successorId !== null && (typeof body.successorId !== "string" || !body.successorId.trim() || body.successorId.trim().length > 64))
6675
- return json2({ error: "successorId must be a member name or null" }, 400);
6953
+ return json3({ error: "successorId must be a member name or null" }, 400);
6676
6954
  const successorId = typeof body.successorId === "string" ? body.successorId.trim() : body.successorId === null ? null : undefined;
6677
6955
  const adminIds = Array.isArray(body.adminIds) ? [...new Set(body.adminIds.map((name) => name.trim()))] : undefined;
6678
6956
  const name = typeof body.name === "string" ? body.name.trim() : undefined;
@@ -6680,7 +6958,7 @@ async function roomManagement(req, url) {
6680
6958
  const joinPolicy = body.joinPolicy === "open" || body.joinPolicy === "approval" ? body.joinPolicy : undefined;
6681
6959
  const adminSessionID = typeof body.adminSessionID === "string" ? body.adminSessionID : body.adminSessionID === null ? null : undefined;
6682
6960
  if (body.ownerId !== undefined && (typeof body.ownerId !== "string" || !body.ownerId.trim() || body.ownerId.trim().length > 64))
6683
- return json2({ error: "ownerId must be 1-64 characters" }, 400);
6961
+ return json3({ error: "ownerId must be 1-64 characters" }, 400);
6684
6962
  const nextOwner = typeof body.ownerId === "string" ? body.ownerId.trim() : undefined;
6685
6963
  const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
6686
6964
  const room = svc.getRoom(roomId);
@@ -6804,18 +7082,18 @@ async function roomManagement(req, url) {
6804
7082
  return { room };
6805
7083
  });
6806
7084
  if ("error" in result)
6807
- return json2({ error: result.error }, result.status);
6808
- return json2(await roomPayload(result.room));
7085
+ return json3({ error: result.error }, result.status);
7086
+ return json3(await roomPayload(result.room));
6809
7087
  }
6810
7088
  const remove = p.match(/^\/rooms\/([^/]+)$/);
6811
7089
  if (remove && req.method === "DELETE") {
6812
7090
  const roomId = decodeURIComponent(remove[1]);
6813
7091
  const body = await objectBody(req);
6814
7092
  if (!body)
6815
- return json2({ error: "JSON object body is required" }, 400);
7093
+ return json3({ error: "JSON object body is required" }, 400);
6816
7094
  const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
6817
7095
  if (!sessionID || sessionID.length > 128)
6818
- return json2({ error: "sessionID is required" }, 400);
7096
+ return json3({ error: "sessionID is required" }, 400);
6819
7097
  const sessions = await mutate((svc, registry) => {
6820
7098
  const room = svc.getRoom(roomId);
6821
7099
  const actor = registry[roomId]?.[sessionID];
@@ -6831,11 +7109,11 @@ async function roomManagement(req, url) {
6831
7109
  await removeRoomResources(roomId).catch(() => console.error("failed to clean deleted room resources", roomId));
6832
7110
  for (const sid of sessions)
6833
7111
  clearPendingAdmission(sid, roomId, Number.MAX_SAFE_INTEGER);
6834
- return json2({ ok: true });
7112
+ return json3({ ok: true });
6835
7113
  }
6836
7114
  return;
6837
7115
  }
6838
- var json2 = (body, status = 200) => Response.json(body, { status }), mutate = (fn) => writeState(fn);
7116
+ var json3 = (body, status = 200) => Response.json(body, { status }), mutate = (fn) => writeState(fn);
6839
7117
  var init_newrooms = __esm(() => {
6840
7118
  init_room_service();
6841
7119
  init_store();
@@ -6858,7 +7136,7 @@ async function announcementRoutes(req, url) {
6858
7136
  roomID = decodeURIComponent(match[1]);
6859
7137
  name = match[2] === undefined ? undefined : decodeURIComponent(match[2]);
6860
7138
  } catch {
6861
- return json3({ error: "invalid path" }, 400);
7139
+ return json4({ error: "invalid path" }, 400);
6862
7140
  }
6863
7141
  const roomExists = await readState2((svc) => {
6864
7142
  try {
@@ -6869,38 +7147,38 @@ async function announcementRoutes(req, url) {
6869
7147
  }
6870
7148
  });
6871
7149
  if (!roomExists)
6872
- return json3({ error: "room not found" }, 404);
7150
+ return json4({ error: "room not found" }, 404);
6873
7151
  if (req.method === "GET") {
6874
7152
  if (!name)
6875
- return json3({ announcements: await listAnnouncements2(roomID) });
7153
+ return json4({ announcements: await listAnnouncements2(roomID) });
6876
7154
  if (validateAnnouncement(name))
6877
- return json3({ error: "invalid announcement name" }, 400);
7155
+ return json4({ error: "invalid announcement name" }, 400);
6878
7156
  const announcement = await getAnnouncement2(roomID, name);
6879
- return announcement ? json3({ announcement }) : json3({ error: "announcement not found" }, 404);
7157
+ return announcement ? json4({ announcement }) : json4({ error: "announcement not found" }, 404);
6880
7158
  }
6881
7159
  let body;
6882
7160
  try {
6883
7161
  body = await req.json();
6884
7162
  } catch {
6885
- return json3({ error: "invalid JSON body" }, 400);
7163
+ return json4({ error: "invalid JSON body" }, 400);
6886
7164
  }
6887
7165
  if (!object(body) || typeof body.sessionID !== "string" || !body.sessionID)
6888
- return json3({ error: "sessionID is required" }, 400);
7166
+ return json4({ error: "sessionID is required" }, 400);
6889
7167
  const member = await readState2((_svc, registry) => Boolean(registry[roomID]?.[body.sessionID]));
6890
7168
  if (!member)
6891
- return json3({ error: "not a room member" }, 403);
7169
+ return json4({ error: "not a room member" }, 403);
6892
7170
  if (req.method === "PUT") {
6893
7171
  const error = validateAnnouncement(name, body.content, true);
6894
7172
  if (error)
6895
- return json3({ error }, 400);
7173
+ return json4({ error }, 400);
6896
7174
  const announcement = await putAnnouncement2(roomID, name.trim(), body.content);
6897
- return announcement ? json3({ announcement }) : json3({ error: "room not found" }, 404);
7175
+ return announcement ? json4({ announcement }) : json4({ error: "room not found" }, 404);
6898
7176
  }
6899
7177
  if (!name || validateAnnouncement(name))
6900
- return json3({ error: "invalid announcement name" }, 400);
6901
- return await deleteAnnouncement2(roomID, name) ? json3({ ok: true }) : json3({ error: "announcement not found" }, 404);
7178
+ return json4({ error: "invalid announcement name" }, 400);
7179
+ return await deleteAnnouncement2(roomID, name) ? json4({ ok: true }) : json4({ error: "announcement not found" }, 404);
6902
7180
  }
6903
- var json3 = (body, status = 200) => Response.json(body, { status }), object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
7181
+ var json4 = (body, status = 200) => Response.json(body, { status }), object = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
6904
7182
  var init_announcement_routes = __esm(() => {
6905
7183
  init_announcements();
6906
7184
  init_store();
@@ -6908,7 +7186,7 @@ var init_announcement_routes = __esm(() => {
6908
7186
 
6909
7187
  // server/task-routes.ts
6910
7188
  function sessionID(value) {
6911
- return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION2 ? value : undefined;
7189
+ return typeof value === "string" && value.length > 0 && value.length <= MAX_SESSION3 ? value : undefined;
6912
7190
  }
6913
7191
  async function taskRoutes(req, url) {
6914
7192
  const collection = url.pathname.match(/^\/rooms\/([^/]+)\/tasks$/);
@@ -6920,48 +7198,48 @@ async function taskRoutes(req, url) {
6920
7198
  roomID = decodeURIComponent((collection ?? item)[1]);
6921
7199
  taskID = item ? decodeURIComponent(item[2]) : undefined;
6922
7200
  } catch {
6923
- return json4({ error: "invalid path" }, 400);
7201
+ return json5({ error: "invalid path" }, 400);
6924
7202
  }
6925
7203
  if (collection) {
6926
7204
  if (req.method === "GET") {
6927
7205
  const session = sessionID(url.searchParams.get("sessionID"));
6928
7206
  if (!session)
6929
- return json4({ error: "sessionID is required" }, 400);
7207
+ return json5({ error: "sessionID is required" }, 400);
6930
7208
  const result = await listTasks(roomID, session);
6931
- return "error" in result ? json4({ error: result.error }, result.status) : json4({ tasks: result.tasks });
7209
+ return "error" in result ? json5({ error: result.error }, result.status) : json5({ tasks: result.tasks });
6932
7210
  }
6933
7211
  if (req.method !== "POST" && req.method !== "DELETE")
6934
- return json4({ error: "method not allowed" }, 405);
7212
+ return json5({ error: "method not allowed" }, 405);
6935
7213
  const body = await jsonObject(req);
6936
7214
  if (!body)
6937
- return json4({ error: "JSON object body is required" }, 400);
7215
+ return json5({ error: "JSON object body is required" }, 400);
6938
7216
  const session = sessionID(body.sessionID);
6939
7217
  if (!session)
6940
- return json4({ error: "sessionID is required" }, 400);
7218
+ return json5({ error: "sessionID is required" }, 400);
6941
7219
  if (req.method === "DELETE") {
6942
7220
  const result = await clearCompletedTasks(roomID, session);
6943
- return "error" in result ? json4({ error: result.error }, result.status) : json4({ ok: true, count: result.count });
7221
+ return "error" in result ? json5({ error: result.error }, result.status) : json5({ ok: true, count: result.count });
6944
7222
  }
6945
7223
  const fields = { title: body.title, description: body.description, assignee: body.assignee, dueDate: body.dueDate, participants: body.participants, conclusion: body.conclusion, steps: body.steps };
6946
7224
  const result = await createTask(roomID, session, fields);
6947
- return "error" in result ? json4({ error: result.error }, result.status) : json4({ task: result.task }, 201);
7225
+ return "error" in result ? json5({ error: result.error }, result.status) : json5({ task: result.task }, 201);
6948
7226
  }
6949
7227
  if (req.method !== "PATCH" && req.method !== "DELETE")
6950
- return json4({ error: "method not allowed" }, 405);
7228
+ return json5({ error: "method not allowed" }, 405);
6951
7229
  const body = await jsonObject(req);
6952
7230
  if (!body)
6953
- return json4({ error: "JSON object body is required" }, 400);
7231
+ return json5({ error: "JSON object body is required" }, 400);
6954
7232
  const session = sessionID(body.sessionID);
6955
7233
  if (!session)
6956
- return json4({ error: "sessionID is required" }, 400);
7234
+ return json5({ error: "sessionID is required" }, 400);
6957
7235
  if (req.method === "DELETE") {
6958
7236
  const result = await deleteTask(roomID, taskID, session);
6959
- return "error" in result ? json4({ error: result.error }, result.status) : json4({ ok: true });
7237
+ return "error" in result ? json5({ error: result.error }, result.status) : json5({ ok: true });
6960
7238
  }
6961
7239
  const result = await updateTask(roomID, taskID, session, { title: body.title, description: body.description, assignee: body.assignee, status: body.status, dueDate: body.dueDate, participants: body.participants, conclusion: body.conclusion, steps: body.steps });
6962
- return "error" in result ? json4({ error: result.error }, result.status) : json4({ task: result.task });
7240
+ return "error" in result ? json5({ error: result.error }, result.status) : json5({ task: result.task });
6963
7241
  }
6964
- var json4 = (body, status = 200) => Response.json(body, { status }), MAX_SESSION2 = 128;
7242
+ var json5 = (body, status = 200) => Response.json(body, { status }), MAX_SESSION3 = 128;
6965
7243
  var init_task_routes = __esm(() => {
6966
7244
  init_tasks();
6967
7245
  });
@@ -6980,14 +7258,14 @@ async function memberRoutes(req, url) {
6980
7258
  if (req.method === "POST" && url.pathname === "/read") {
6981
7259
  const body = await jsonObject(req);
6982
7260
  if (!body)
6983
- return json5({ error: "JSON object body is required" }, 400);
7261
+ return json6({ error: "JSON object body is required" }, 400);
6984
7262
  const ts = body.ts;
6985
7263
  const roomId = String(body.roomId ?? "");
6986
7264
  const sessionID = String(body.sessionID ?? "");
6987
7265
  const messageIDs = body.messageIDs;
6988
7266
  const hasReceipts = messageIDs !== undefined;
6989
7267
  if (body.ts === undefined || body.ts === null || !roomId || !sessionID || typeof ts !== "number" || !Number.isSafeInteger(ts) || ts <= 0 || hasReceipts && (!Array.isArray(messageIDs) || !messageIDs.length || messageIDs.length > 500 || messageIDs.some((id) => typeof id !== "string" || !id || id.length > 128) || typeof body.membershipID !== "string" || !body.membershipID || body.membershipID.length > 128 || typeof body.evidence !== "string" || !["displayed", "tool", "context"].includes(body.evidence) || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID))) {
6990
- return json5({ error: "invalid read acknowledgement" }, 400);
7268
+ return json6({ error: "invalid read acknowledgement" }, 400);
6991
7269
  }
6992
7270
  if (hasReceipts) {
6993
7271
  const result = await acknowledgeReadWithReceipts(roomId, sessionID, ts, messageIDs, body.evidence, {
@@ -6995,45 +7273,45 @@ async function memberRoutes(req, url) {
6995
7273
  ...typeof body.receiverOwnerID === "string" ? { receiverOwnerID: body.receiverOwnerID } : {}
6996
7274
  });
6997
7275
  if (result.status === "membership")
6998
- return json5({ error: "membership generation mismatch" }, 409);
7276
+ return json6({ error: "membership generation mismatch" }, 409);
6999
7277
  if (result.status === "messageIDs")
7000
- return json5({ error: "message IDs do not belong to this room" }, 400);
7278
+ return json6({ error: "message IDs do not belong to this room" }, 400);
7001
7279
  if (result.status !== "ok")
7002
- return json5({ error: "read acknowledgement rejected" }, 400);
7280
+ return json6({ error: "read acknowledgement rejected" }, 400);
7003
7281
  clearPendingAdmission(sessionID, roomId, result.readThroughTs ?? 0);
7004
7282
  touchActive(sessionID);
7005
- return json5({ ok: true, acceptedIDs: result.acceptedIDs });
7283
+ return json6({ ok: true, acceptedIDs: result.acceptedIDs });
7006
7284
  }
7007
7285
  const actualTs = await acknowledgeRead2(roomId, sessionID, ts);
7008
7286
  if (actualTs === null)
7009
- return json5({ error: "registry entry not found" }, 404);
7287
+ return json6({ error: "registry entry not found" }, 404);
7010
7288
  clearPendingAdmission(sessionID, roomId, actualTs);
7011
7289
  touchActive(sessionID);
7012
- return json5({ ok: true });
7290
+ return json6({ ok: true });
7013
7291
  }
7014
7292
  const receiptRoute = url.pathname.match(/^\/rooms\/([^/]+)\/receipts$/);
7015
7293
  if (req.method === "POST" && receiptRoute) {
7016
7294
  const body = await req.json();
7017
7295
  if (!object2(body))
7018
- return json5({ error: "JSON object body is required" }, 400);
7296
+ return json6({ error: "JSON object body is required" }, 400);
7019
7297
  const { sessionID, membershipID, evidence } = body;
7020
7298
  const ids = body.messageIDs;
7021
7299
  const ownerID = body.receiverOwnerID;
7022
7300
  if (typeof sessionID !== "string" || !sessionID || sessionID.length > 128 || typeof membershipID !== "string" || !membershipID || membershipID.length > 128 || !Array.isArray(ids) || !ids.length || ids.length > 500 || ids.some((id) => typeof id !== "string" || !id || id.length > 128) || typeof evidence !== "string" || !["displayed", "tool", "context"].includes(evidence) || ownerID !== undefined && !isReceiverOwnerID(ownerID))
7023
- return json5({ error: "invalid message receipt" }, 400);
7301
+ return json6({ error: "invalid message receipt" }, 400);
7024
7302
  const identity = { membershipID, ...typeof ownerID === "string" ? { receiverOwnerID: ownerID } : {} };
7025
7303
  const result = await recordMessageReceipts(decodeURIComponent(receiptRoute[1]), sessionID, ids, evidence, identity);
7026
7304
  if (result.status === "membership")
7027
- return json5({ error: "membership generation mismatch" }, 409);
7305
+ return json6({ error: "membership generation mismatch" }, 409);
7028
7306
  if (result.status === "messageIDs")
7029
- return json5({ error: "message IDs do not belong to this room" }, 400);
7030
- return json5({ acceptedIDs: result.acceptedIDs });
7307
+ return json6({ error: "message IDs do not belong to this room" }, 400);
7308
+ return json6({ acceptedIDs: result.acceptedIDs });
7031
7309
  }
7032
7310
  const match = url.pathname.match(/^\/rooms\/([^/]+)\/(members|receipts)$/);
7033
7311
  if (req.method === "GET" && match) {
7034
7312
  const roomID = decodeURIComponent(match[1]);
7035
7313
  if (match[2] === "members")
7036
- return json5(await readState2((svc, registry) => {
7314
+ return json6(await readState2((svc, registry) => {
7037
7315
  svc.getRoom(roomID);
7038
7316
  return Object.entries(registry[roomID] ?? {}).map(([sessionID, entry]) => ({
7039
7317
  sessionID,
@@ -7052,25 +7330,25 @@ async function memberRoutes(req, url) {
7052
7330
  const filter = url.searchParams.get("messageIDs");
7053
7331
  const ids = filter === null ? undefined : filter.split(",");
7054
7332
  if (ids && (!ids.length || ids.length > 500 || ids.some((id) => !id || id.length > 128)))
7055
- return json5({ error: "invalid message IDs" }, 400);
7333
+ return json6({ error: "invalid message IDs" }, 400);
7056
7334
  const receipts = await readReceipts(roomID, ids);
7057
7335
  if (!receipts)
7058
- return json5({ error: "message IDs do not belong to this room" }, 400);
7059
- return json5({ receipts: receipts.map((item) => ({ messageID: item.messageID, readers: item.readers.map((reader) => ({ ...reader, currentMember: Boolean(registry[reader.sessionID]) })) })), semantics: "per-message" });
7336
+ return json6({ error: "message IDs do not belong to this room" }, 400);
7337
+ return json6({ receipts: receipts.map((item) => ({ messageID: item.messageID, readers: item.readers.map((reader) => ({ ...reader, currentMember: Boolean(registry[reader.sessionID]) })) })), semantics: "per-message" });
7060
7338
  }
7061
7339
  if (req.method !== "POST" || url.pathname !== "/presence")
7062
7340
  return;
7063
7341
  const body = await req.json();
7064
7342
  if (!object2(body) || !Array.isArray(body.sessions) || body.sessions.length > 200)
7065
- return json5({ error: "sessions must be an array of at most 200 reports" }, 400);
7343
+ return json6({ error: "sessions must be an array of at most 200 reports" }, 400);
7066
7344
  const ownerID = body.ownerID;
7067
7345
  const sequence = body.sequence;
7068
7346
  if (ownerID !== undefined && !isReceiverOwnerID(ownerID) || ownerID === undefined && sequence !== undefined || ownerID !== undefined && (typeof sequence !== "number" || !Number.isSafeInteger(sequence) || sequence <= 0))
7069
- return json5({ error: "invalid owner sequence" }, 400);
7347
+ return json6({ error: "invalid owner sequence" }, 400);
7070
7348
  const reports = new Map;
7071
7349
  for (const item of body.sessions) {
7072
7350
  if (!object2(item) || typeof item.sessionID !== "string" || !item.sessionID || item.sessionID.length > 128 || typeof item.state !== "string" || !states.has(item.state) || item.receiverOwnerID !== undefined && (!isReceiverOwnerID(item.receiverOwnerID) || item.receiverOwnerID !== ownerID) || ownerID === undefined && item.receiverOwnerID !== undefined)
7073
- return json5({ error: "invalid presence report" }, 400);
7351
+ return json6({ error: "invalid presence report" }, 400);
7074
7352
  reports.set(item.sessionID, {
7075
7353
  sessionID: item.sessionID,
7076
7354
  state: item.state,
@@ -7078,9 +7356,9 @@ async function memberRoutes(req, url) {
7078
7356
  });
7079
7357
  }
7080
7358
  const result = await reportPresence([...reports.values()], ownerID, sequence);
7081
- return json5({ updatedSessionIDs: result.stale ? [] : result.updatedSessionIDs });
7359
+ return json6({ updatedSessionIDs: result.stale ? [] : result.updatedSessionIDs });
7082
7360
  }
7083
- var json5 = (body, status = 200) => Response.json(body, { status }), states;
7361
+ var json6 = (body, status = 200) => Response.json(body, { status }), states;
7084
7362
  var init_member_routes = __esm(() => {
7085
7363
  init_store();
7086
7364
  init_receiver_owner();
@@ -7117,63 +7395,64 @@ async function resourceRoutes(req, url) {
7117
7395
  const sessionID = req.headers.get("x-session-id") ?? "";
7118
7396
  const entry = await readState2((_svc, registry) => registry[roomID]?.[sessionID]);
7119
7397
  if (!entry)
7120
- return json6({ error: "forbidden" }, 403);
7398
+ return json7({ error: "forbidden" }, 403);
7121
7399
  const rawLimit = Number(url.searchParams.get("limit") ?? 500);
7122
7400
  const rawOffset = Number(url.searchParams.get("offset") ?? 0);
7123
7401
  const limit = Number.isSafeInteger(rawLimit) ? Math.min(1000, Math.max(1, rawLimit)) : 500;
7124
7402
  const offset = Number.isSafeInteger(rawOffset) ? Math.max(0, rawOffset) : 0;
7125
- const page = await listRoomResources(roomID, limit, offset);
7126
- return json6({ resources: page.items, total: page.total, limit, offset }, 200);
7403
+ const before = url.searchParams.get("before");
7404
+ const page = await listRoomResources(roomID, limit, offset, before && uuid3.test(before) ? before : undefined);
7405
+ return json7({ resources: page.items, total: page.total, limit, offset }, 200);
7127
7406
  }
7128
7407
  if (upload) {
7129
7408
  const sessionID = req.headers.get("x-session-id") ?? "";
7130
7409
  const entry = await readState2((_svc, registry) => registry[roomID]?.[sessionID]);
7131
7410
  if (!entry)
7132
- return json6({ error: "forbidden" }, 403);
7411
+ return json7({ error: "forbidden" }, 403);
7133
7412
  const encoded = req.headers.get("x-file-name");
7134
7413
  if (!encoded)
7135
- return json6({ error: "invalid filename" }, 400);
7414
+ return json7({ error: "invalid filename" }, 400);
7136
7415
  let filename;
7137
7416
  try {
7138
7417
  filename = decodeURIComponent(encoded);
7139
7418
  } catch {
7140
- return json6({ error: "invalid filename" }, 400);
7419
+ return json7({ error: "invalid filename" }, 400);
7141
7420
  }
7142
7421
  if (!filename || filename.length > 255 || /[\\/\r\n\0]/.test(filename) || filename === "." || filename === "..")
7143
- return json6({ error: "invalid filename" }, 400);
7422
+ return json7({ error: "invalid filename" }, 400);
7144
7423
  const requestedID = req.headers.get("x-resource-id");
7145
7424
  if (requestedID !== null && !uuid3.test(requestedID))
7146
- return json6({ error: "invalid resource id" }, 400);
7425
+ return json7({ error: "invalid resource id" }, 400);
7147
7426
  const resource = await uploadResource(roomID, filename, req.body ?? new Blob([]).stream(), maxResourceBytes(), { sessionID, name: entry.name }, requestedID ?? undefined);
7148
- return json6({ resource }, 201);
7427
+ return json7({ resource }, 201);
7149
7428
  }
7150
7429
  const id = decodeURIComponent(item[2]);
7151
7430
  if (!uuid3.test(id))
7152
- return json6({ error: "resource not found" }, 404);
7431
+ return json7({ error: "resource not found" }, 404);
7153
7432
  const resource = await findResource(roomID, id);
7154
7433
  if (!resource)
7155
- return json6({ error: "resource not found" }, 404);
7434
+ return json7({ error: "resource not found" }, 404);
7156
7435
  if (req.method === "DELETE") {
7157
7436
  const sessionID = req.headers.get("x-session-id") ?? "";
7158
7437
  const context = await readState2((svc, registry) => ({ room: svc.getRoom(roomID), entry: registry[roomID]?.[sessionID] }));
7159
7438
  if (!context.entry)
7160
- return json6({ error: "forbidden" }, 403);
7439
+ return json7({ error: "forbidden" }, 403);
7161
7440
  const ownAgentUpload = !isUser(context.entry) && resource.uploaderSessionID === sessionID;
7162
7441
  if (!isRoomAdmin(context.room, context.entry) && !ownAgentUpload)
7163
- return json6({ error: "forbidden" }, 403);
7442
+ return json7({ error: "forbidden" }, 403);
7164
7443
  await deleteResource(roomID, id);
7165
- return json6({ ok: true });
7444
+ return json7({ ok: true });
7166
7445
  }
7167
7446
  if (!item[3])
7168
- return json6({ resource });
7447
+ return json7({ resource });
7169
7448
  return await content2(req, resource);
7170
7449
  } catch (error) {
7171
7450
  if (error instanceof URIError)
7172
- return json6({ error: "invalid resource request" }, 400);
7451
+ return json7({ error: "invalid resource request" }, 400);
7173
7452
  const status = typeof error === "object" && error !== null && "status" in error ? Number(error.status) : 500;
7174
7453
  if (status >= 400 && status < 500)
7175
- return json6({ error: status === 413 ? "file exceeds maximum size" : status === 404 ? "resource not found" : status === 403 ? "forbidden" : "invalid resource request" }, status);
7176
- return json6({ error: "internal server error" }, 500);
7454
+ return json7({ error: status === 413 ? "file exceeds maximum size" : status === 404 ? "resource not found" : status === 403 ? "forbidden" : "invalid resource request" }, status);
7455
+ return json7({ error: "internal server error" }, 500);
7177
7456
  }
7178
7457
  }
7179
7458
  async function content2(req, resource) {
@@ -7215,7 +7494,7 @@ async function content2(req, resource) {
7215
7494
  headers.set("Content-Range", `bytes ${start}-${end}/${info.size}`);
7216
7495
  return new Response(Readable3.toWeb(createReadStream2(path, { start, end })), { status, headers });
7217
7496
  }
7218
- var json6 = (body, status = 200) => Response.json(body, { status }), uuid3, safeHeaders;
7497
+ var json7 = (body, status = 200) => Response.json(body, { status }), uuid3, safeHeaders;
7219
7498
  var init_resource_routes = __esm(() => {
7220
7499
  init_resources();
7221
7500
  init_store();
@@ -7233,8 +7512,8 @@ async function adminRoutes(request, url) {
7233
7512
  return await rootRoutes(request, url);
7234
7513
  } catch (error) {
7235
7514
  if (error instanceof SyntaxError || error instanceof URIError)
7236
- return json7({ error: "invalid request" }, 400);
7237
- return json7({ error: "admin request failed" }, 500);
7515
+ return json8({ error: "invalid request" }, 400);
7516
+ return json8({ error: "admin request failed" }, 500);
7238
7517
  }
7239
7518
  }
7240
7519
  async function rootRoutes(request, url) {
@@ -7244,13 +7523,13 @@ async function rootRoutes(request, url) {
7244
7523
  return claimBinding(request, decodeURIComponent(claim[1]));
7245
7524
  const room = path.match(/^\/admin\/rooms\/([^/]+)(?:\/(overview|history))?$/);
7246
7525
  if (!room)
7247
- return json7({ error: "not found" }, 404);
7526
+ return json8({ error: "not found" }, 404);
7248
7527
  const roomID = decodeURIComponent(room[1]);
7249
7528
  if (request.method === "GET" && room[2] === "overview")
7250
7529
  return overview(request, roomID);
7251
7530
  if (request.method === "GET" && room[2] === "history")
7252
7531
  return history(request, url, roomID);
7253
- return json7({ error: "method not allowed" }, 405);
7532
+ return json8({ error: "method not allowed" }, 405);
7254
7533
  }
7255
7534
  function bounded(value, max) {
7256
7535
  return typeof value === "string" && value.trim().length > 0 && value.length <= max;
@@ -7258,7 +7537,7 @@ function bounded(value, max) {
7258
7537
  async function claimBinding(request, roomID) {
7259
7538
  const body = await request.json();
7260
7539
  if (!object3(body) || !bounded(body.sessionID, 128) || typeof body.receiverOwnerID !== "string" || body.receiverOwnerID.length > 128 || !bounded(body.enrollmentKey, 256))
7261
- return json7({ error: "invalid claim" }, 400);
7540
+ return json8({ error: "invalid claim" }, 400);
7262
7541
  const { sessionID, receiverOwnerID, enrollmentKey } = body;
7263
7542
  const result = await tx((db) => {
7264
7543
  const b = binding(db, roomID);
@@ -7268,7 +7547,7 @@ async function claimBinding(request, roomID) {
7268
7547
  const saved = run(db, "UPDATE admin_rooms SET capability_hash=?,enrollment_hash='',enrollment_expires=0 WHERE room_id=? AND generation=? AND enrollment_hash=? AND enrollment_expires>?", digest(capability), roomID, b.generation, b.enrollment_hash, Date.now());
7269
7548
  return saved.changes === 1 ? { capability, adminRoom: publicRoom({ ...b, capability_hash: digest(capability) }) } : null;
7270
7549
  });
7271
- return result ? json7(result) : json7({ error: "claim rejected" }, 409);
7550
+ return result ? json8(result) : json8({ error: "claim rejected" }, 409);
7272
7551
  }
7273
7552
  async function overview(request, roomID) {
7274
7553
  const result = await tx((db) => {
@@ -7284,16 +7563,16 @@ async function overview(request, roomID) {
7284
7563
  const rooms = many(db, "SELECT id,name,created_at AS createdAt FROM rooms WHERE id=?", roomID).map((room) => ({ ...room, members: many(db, "SELECT g.session_id AS sessionID,g.name,g.protocol,g.receiver_owner_id AS receiverOwnerID,g.work_state AS workState,g.last_seen_at AS lastSeenAt FROM registry g WHERE g.room_id=? ORDER BY g.name", room.id) }));
7285
7564
  return { rooms };
7286
7565
  });
7287
- return "status" in result ? json7({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "binding is no longer active" }, result.status) : json7(result);
7566
+ return "status" in result ? json8({ error: result.status === 404 ? "admin room not found" : result.status === 401 ? "unauthorized" : "binding is no longer active" }, result.status) : json8(result);
7288
7567
  }
7289
7568
  async function history(request, url, roomID) {
7290
7569
  const targetRoomID = url.searchParams.get("targetRoomId") ?? "";
7291
7570
  if (!bounded(targetRoomID, 128))
7292
- return json7({ error: "invalid history request" }, 400);
7571
+ return json8({ error: "invalid history request" }, 400);
7293
7572
  const rawLimit = url.searchParams.get("limit");
7294
7573
  const limit = rawLimit === null ? 20 : Number(rawLimit);
7295
7574
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 50)
7296
- return json7({ error: "invalid history request" }, 400);
7575
+ return json8({ error: "invalid history request" }, 400);
7297
7576
  const allowed = await tx((db) => {
7298
7577
  const b = binding(db, roomID);
7299
7578
  if (!b)
@@ -7307,12 +7586,12 @@ async function history(request, url, roomID) {
7307
7586
  return 200;
7308
7587
  });
7309
7588
  if (allowed !== 200)
7310
- return json7({ error: allowed === 401 ? "unauthorized" : allowed === 404 ? "room not found" : "binding is no longer active" }, allowed);
7589
+ return json8({ error: allowed === 401 ? "unauthorized" : allowed === 404 ? "room not found" : "binding is no longer active" }, allowed);
7311
7590
  if (targetRoomID !== roomID)
7312
- return json7({ error: "room is outside this administrator's scope" }, 403);
7313
- return json7(await readHistoryPage(databasePath(), roomID, undefined, limit));
7591
+ return json8({ error: "room is outside this administrator's scope" }, 403);
7592
+ return json8(await readHistoryPage(databasePath(), roomID, undefined, limit));
7314
7593
  }
7315
- var json7 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } }), object3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
7594
+ var json8 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } }), object3 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
7316
7595
  var init_admin_routes = __esm(async () => {
7317
7596
  init_store();
7318
7597
  init_sqlite_state();
@@ -7393,37 +7672,37 @@ async function joinRequestRoutes(req, url) {
7393
7672
  const roomID = decodeURIComponent(status[1]);
7394
7673
  const sessionID = url.searchParams.get("sessionID") ?? "";
7395
7674
  if (!bounded2(sessionID))
7396
- return json8({ error: "sessionID is required" }, 400);
7675
+ return json9({ error: "sessionID is required" }, 400);
7397
7676
  const joined = await readState2((svc, registry) => {
7398
7677
  svc.getRoom(roomID);
7399
7678
  return Boolean(registry[roomID]?.[sessionID]);
7400
7679
  });
7401
7680
  if (joined)
7402
- return json8({ status: "joined" });
7403
- return json8({ status: await readJoinRequest2(roomID, sessionID) ? "pending" : "none" });
7681
+ return json9({ status: "joined" });
7682
+ return json9({ status: await readJoinRequest2(roomID, sessionID) ? "pending" : "none" });
7404
7683
  }
7405
7684
  if (list && req.method === "DELETE") {
7406
7685
  const roomID = decodeURIComponent(list[1]);
7407
7686
  const sessionID = url.searchParams.get("sessionID") ?? "";
7408
7687
  if (!bounded2(sessionID))
7409
- return json8({ error: "sessionID is required" }, 400);
7688
+ return json9({ error: "sessionID is required" }, 400);
7410
7689
  const removed = await writeSqliteStateWithDatabase(databasePath(), (svc, _registry, db) => {
7411
7690
  svc.getRoom(roomID);
7412
7691
  return removeJoinRequest(db, roomID, sessionID);
7413
7692
  });
7414
- return removed ? json8({ ok: true }) : json8({ error: "join request not found" }, 404);
7693
+ return removed ? json9({ ok: true }) : json9({ error: "join request not found" }, 404);
7415
7694
  }
7416
7695
  if (list && req.method === "GET") {
7417
7696
  const roomID = decodeURIComponent(list[1]);
7418
7697
  const actor = url.searchParams.get("sessionID") ?? "";
7419
7698
  if (!bounded2(actor))
7420
- return json8({ error: "sessionID is required" }, 400);
7699
+ return json9({ error: "sessionID is required" }, 400);
7421
7700
  const human = await humanReviewer(roomID, actor);
7422
7701
  const agent = !human && await agentReviewer(req, roomID, actor);
7423
7702
  if (!human && !agent)
7424
- return json8({ error: "only room administrators can review join requests" }, 403);
7703
+ return json9({ error: "only room administrators can review join requests" }, 403);
7425
7704
  const requests = await listJoinRequests2(roomID, agent);
7426
- return json8({ requests: requests.map(({ sessionID, participantId, name, isAgent, createdAt }) => ({ sessionID, participantId, name, isAgent, createdAt })) });
7705
+ return json9({ requests: requests.map(({ sessionID, participantId, name, isAgent, createdAt }) => ({ sessionID, participantId, name, isAgent, createdAt })) });
7427
7706
  }
7428
7707
  if (action && req.method === "POST") {
7429
7708
  const roomID = decodeURIComponent(action[1]);
@@ -7431,10 +7710,10 @@ async function joinRequestRoutes(req, url) {
7431
7710
  const decision = action[3];
7432
7711
  const body = await req.json();
7433
7712
  if (!body || typeof body !== "object" || Array.isArray(body))
7434
- return json8({ error: "JSON object body is required" }, 400);
7713
+ return json9({ error: "JSON object body is required" }, 400);
7435
7714
  const actor = typeof body.sessionID === "string" ? body.sessionID : "";
7436
7715
  if (!bounded2(actor))
7437
- return json8({ error: "sessionID is required" }, 400);
7716
+ return json9({ error: "sessionID is required" }, 400);
7438
7717
  const result = await writeSqliteStateWithDatabase(databasePath(), (svc, registry, db) => {
7439
7718
  const room = svc.getRoom(roomID);
7440
7719
  const actorEntry = registry[roomID]?.[actor];
@@ -7473,11 +7752,11 @@ async function joinRequestRoutes(req, url) {
7473
7752
  });
7474
7753
  return { ok: true };
7475
7754
  });
7476
- return "ok" in result ? json8({ ok: true }) : json8({ error: result.error }, result.status);
7755
+ return "ok" in result ? json9({ ok: true }) : json9({ error: result.error }, result.status);
7477
7756
  }
7478
- return json8({ error: "method not allowed" }, 405);
7757
+ return json9({ error: "method not allowed" }, 405);
7479
7758
  }
7480
- var json8 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
7759
+ var json9 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
7481
7760
  var init_join_requests = __esm(() => {
7482
7761
  init_store();
7483
7762
  init_sqlite_state();
@@ -7626,16 +7905,16 @@ async function roomReminderRoutes(req, url) {
7626
7905
  return null;
7627
7906
  return db.query("SELECT * FROM room_reminders WHERE room_id=? ORDER BY created_at,id").all(room);
7628
7907
  });
7629
- return items ? json9({ reminders: items.map(output) }) : json9({ error: "room not found or session is not a current member" }, 404);
7908
+ return items ? json10({ reminders: items.map(output) }) : json10({ error: "room not found or session is not a current member" }, 404);
7630
7909
  }
7631
7910
  if (req.method !== "POST" && req.method !== "PATCH" && req.method !== "DELETE")
7632
- return json9({ error: "method not allowed" }, 405);
7911
+ return json10({ error: "method not allowed" }, 405);
7633
7912
  const body = await req.json();
7634
7913
  if (!body || typeof body !== "object" || Array.isArray(body))
7635
- return json9({ error: "JSON object body is required" }, 400);
7914
+ return json10({ error: "JSON object body is required" }, 400);
7636
7915
  const input = body, session = input.sessionID;
7637
7916
  if (typeof session !== "string" || !session || session.length > 128)
7638
- return json9({ error: "sessionID is required" }, 400);
7917
+ return json10({ error: "sessionID is required" }, 400);
7639
7918
  const result = await withStateTransaction(dbFile(), (db) => {
7640
7919
  const who = member(db, room, session);
7641
7920
  if (!who)
@@ -7687,7 +7966,7 @@ async function roomReminderRoutes(req, url) {
7687
7966
  }
7688
7967
  });
7689
7968
  const { status, ...bodyOut } = result;
7690
- return json9(bodyOut, status);
7969
+ return json10(bodyOut, status);
7691
7970
  }
7692
7971
  async function tickRoomReminders(now = Date.now(), wake) {
7693
7972
  await initializeReminderSchema(dbFile());
@@ -7743,136 +8022,2169 @@ function startRoomReminderScheduler(wake) {
7743
8022
  }, 1000);
7744
8023
  timer2.unref?.();
7745
8024
  }
7746
- var json9 = (body, status = 200) => Response.json(body, { status }), dbFile = () => databasePath(), timer2;
8025
+ var json10 = (body, status = 200) => Response.json(body, { status }), dbFile = () => databasePath(), timer2;
7747
8026
  var init_room_reminders = __esm(() => {
7748
8027
  init_store();
7749
8028
  init_sqlite_state();
7750
8029
  });
7751
8030
 
7752
- // server/chat-server.ts
7753
- import { existsSync as existsSync2, promises as fs5 } from "node:fs";
7754
- import path14 from "node:path";
7755
- import { fileURLToPath as fileURLToPath4 } from "node:url";
7756
- import { randomUUID as randomUUID14 } from "node:crypto";
7757
- function parsePort(value) {
7758
- const port = Number(value);
7759
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
7760
- throw new Error(`Invalid server port "${value}": expected an integer from 1 to 65535`);
8031
+ // packages/chat-room-channeld/src/config.ts
8032
+ import { parse as parseYaml2 } from "yaml";
8033
+ function record2(value, where) {
8034
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
8035
+ throw new ConfigError(`config: ${where} must be a mapping`);
7761
8036
  }
7762
- return port;
8037
+ return value;
7763
8038
  }
7764
- function mutate2(fn) {
7765
- return writeState(fn);
8039
+ function stringValue(value, where) {
8040
+ if (typeof value !== "string" || !value.trim()) {
8041
+ throw new ConfigError(`config: ${where} must be a non-empty string`);
8042
+ }
8043
+ return value;
7766
8044
  }
7767
- function read(fn) {
7768
- return readState2(fn);
8045
+ function identifierValue(value, where) {
8046
+ const text = stringValue(value, where);
8047
+ if (!IDENTIFIER.test(text)) {
8048
+ throw new ConfigError(`config: ${where} must match /^[A-Za-z0-9._-]+$/ (letters, digits, dot, underscore, hyphen; "/" is not allowed)`);
8049
+ }
8050
+ return text;
7769
8051
  }
7770
- async function handle(req) {
7771
- const url = new URL(req.url);
7772
- const p = url.pathname;
7773
- if (req.method === "GET" && p === "/") {
7774
- return Response.redirect(new URL("/chat", url).toString(), 302);
8052
+ function optionalString2(value, where) {
8053
+ if (value === undefined)
8054
+ return;
8055
+ return stringValue(value, where);
8056
+ }
8057
+ function arrayValue(value, where) {
8058
+ if (!Array.isArray(value) || value.length === 0) {
8059
+ throw new ConfigError(`config: ${where} must be a non-empty array`);
7775
8060
  }
7776
- if (req.method === "GET" && p === "/chat") {
7777
- const html = await fs5.readFile(path14.join(here, "chat.html"), "utf8").catch(() => null);
7778
- if (html === null) {
7779
- return json10({ error: "chat page not found" }, 404);
7780
- }
7781
- const version = await chatVersionTag();
7782
- return new Response(html.replaceAll("{{version}}", version), {
7783
- headers: {
7784
- "Content-Type": "text/html; charset=utf-8",
7785
- "Cache-Control": "no-store"
8061
+ return value;
8062
+ }
8063
+ function parseTarget(value, where) {
8064
+ const raw = record2(value, where);
8065
+ return {
8066
+ platform: identifierValue(raw.platform, `${where}.platform`),
8067
+ account: identifierValue(raw.account, `${where}.account`),
8068
+ room: identifierValue(raw.room, `${where}.room`)
8069
+ };
8070
+ }
8071
+ function parseTransform(value, where) {
8072
+ const raw = record2(value, where);
8073
+ switch (raw.op) {
8074
+ case "prefix-source":
8075
+ case "trim":
8076
+ case "quote-preview":
8077
+ return { op: raw.op };
8078
+ case "truncate": {
8079
+ if (typeof raw.max !== "number" || !Number.isInteger(raw.max) || raw.max < 1) {
8080
+ throw new ConfigError(`config: ${where}.max must be a positive integer`);
7786
8081
  }
7787
- });
8082
+ return { op: "truncate", max: raw.max };
8083
+ }
8084
+ default:
8085
+ throw new ConfigError(`config: ${where}.op must be one of prefix-source, trim, truncate, quote-preview`);
7788
8086
  }
7789
- if (req.method === "GET" && p === "/manifest.webmanifest") {
7790
- const body = await fs5.readFile(path14.join(here, "manifest.webmanifest"), "utf8").catch(() => null);
7791
- if (body === null)
7792
- return json10({ error: "manifest not found" }, 404);
7793
- return new Response(body, {
7794
- headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-store" }
7795
- });
8087
+ }
8088
+ function parseAccount(value, where) {
8089
+ const raw = record2(value, where);
8090
+ const adapter = record2(raw.adapter, `${where}.adapter`);
8091
+ const command = arrayValue(adapter.command, `${where}.adapter.command`).map((item, index) => stringValue(item, `${where}.adapter.command[${index}]`));
8092
+ return {
8093
+ id: identifierValue(raw.id, `${where}.id`),
8094
+ platform: identifierValue(raw.platform, `${where}.platform`),
8095
+ adapter: { command, runtime: optionalString2(adapter.runtime, `${where}.adapter.runtime`) }
8096
+ };
8097
+ }
8098
+ function parseRule(value, where) {
8099
+ const raw = record2(value, where);
8100
+ const from = record2(raw.from, `${where}.from`);
8101
+ const version = raw.version;
8102
+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) {
8103
+ throw new ConfigError(`config: ${where}.version must be a positive integer`);
7796
8104
  }
7797
- if (req.method === "GET" && p === "/sw.js") {
7798
- const body = await fs5.readFile(path14.join(here, "sw.js"), "utf8").catch(() => null);
7799
- if (body === null)
7800
- return json10({ error: "service worker not found" }, 404);
7801
- const version = await chatVersionTag() || "dev";
7802
- return new Response(body.replaceAll("{{version}}", version), {
7803
- headers: {
7804
- "Content-Type": "text/javascript; charset=utf-8",
7805
- "Cache-Control": "no-store",
7806
- "Service-Worker-Allowed": "/"
7807
- }
7808
- });
8105
+ const transforms = raw.transforms === undefined ? [] : arrayValueAllowEmpty(raw.transforms, `${where}.transforms`).map((item, index) => parseTransform(item, `${where}.transforms[${index}]`));
8106
+ const missingParent = optionalString2(raw.onMissingParent, `${where}.onMissingParent`);
8107
+ if (missingParent !== undefined && missingParent !== "quote_or_unthreaded" && missingParent !== "drop") {
8108
+ throw new ConfigError(`config: ${where}.onMissingParent must be quote_or_unthreaded or drop`);
7809
8109
  }
7810
- if (req.method === "GET" && p.startsWith("/assets/")) {
7811
- let relative;
8110
+ const unsupported = optionalString2(raw.onUnsupported, `${where}.onUnsupported`);
8111
+ if (unsupported !== undefined && unsupported !== "text_with_notice" && unsupported !== "drop") {
8112
+ throw new ConfigError(`config: ${where}.onUnsupported must be text_with_notice or drop`);
8113
+ }
8114
+ return {
8115
+ id: stringValue(raw.id, `${where}.id`),
8116
+ version,
8117
+ from: {
8118
+ ...parseTarget({ platform: from.platform, account: from.account, room: from.room }, `${where}.from`),
8119
+ event: optionalString2(from.event, `${where}.from.event`)
8120
+ },
8121
+ transforms,
8122
+ to: arrayValue(raw.to, `${where}.to`).map((item, index) => parseTarget(item, `${where}.to[${index}]`)),
8123
+ onMissingParent: missingParent ?? "quote_or_unthreaded",
8124
+ onUnsupported: unsupported ?? "text_with_notice"
8125
+ };
8126
+ }
8127
+ function arrayValueAllowEmpty(value, where) {
8128
+ if (!Array.isArray(value))
8129
+ throw new ConfigError(`config: ${where} must be an array`);
8130
+ return value;
8131
+ }
8132
+ function parseConfig(value) {
8133
+ const raw = record2(value, "root");
8134
+ const stateFile = stringValue(raw.stateFile, "stateFile");
8135
+ const accounts = arrayValue(raw.accounts, "accounts").map((item, index) => parseAccount(item, `accounts[${index}]`));
8136
+ const rules = raw.rules === undefined ? [] : arrayValueAllowEmpty(raw.rules, "rules").map((item, index) => parseRule(item, `rules[${index}]`));
8137
+ const accountIds = new Set;
8138
+ for (const account of accounts) {
8139
+ if (accountIds.has(account.id))
8140
+ throw new ConfigError(`config: duplicate account id "${account.id}"`);
8141
+ accountIds.add(account.id);
8142
+ }
8143
+ const ruleKeys = new Set;
8144
+ for (const rule of rules) {
8145
+ const key = `${rule.id}@${rule.version}`;
8146
+ if (ruleKeys.has(key))
8147
+ throw new ConfigError(`config: duplicate rule "${rule.id}" version ${rule.version}`);
8148
+ ruleKeys.add(key);
8149
+ }
8150
+ return { stateFile, accounts, rules };
8151
+ }
8152
+ var ConfigError, IDENTIFIER;
8153
+ var init_config = __esm(() => {
8154
+ ConfigError = class ConfigError extends Error {
8155
+ constructor(message) {
8156
+ super(message);
8157
+ this.name = "ConfigError";
8158
+ }
8159
+ };
8160
+ IDENTIFIER = /^[A-Za-z0-9._-]+$/;
8161
+ });
8162
+
8163
+ // packages/chat-room-channeld/src/protocol.ts
8164
+ function hostRequestId(sequence) {
8165
+ return `${HOST_ID_PREFIX}${sequence}`;
8166
+ }
8167
+ function rpcRequest(id, method, params) {
8168
+ return params === undefined ? { jsonrpc: "2.0", id, method } : { jsonrpc: "2.0", id, method, params };
8169
+ }
8170
+ function rpcResult(id, result) {
8171
+ return { jsonrpc: "2.0", id, result };
8172
+ }
8173
+ function rpcError(id, code, message, data) {
8174
+ const error = data === undefined ? { code, message } : { code, message, data };
8175
+ return { jsonrpc: "2.0", id, error };
8176
+ }
8177
+ var PROTOCOL_VERSION = 1, EVENT_SCHEMA_VERSION = 1, MAX_FRAME_BYTES = 1048576, HOST_ID_PREFIX = "host-", RPC_METHOD_NOT_FOUND = -32601, RPC_INTERNAL_ERROR = -32603;
8178
+
8179
+ // packages/chat-room-channeld/src/framing.ts
8180
+ import { StringDecoder } from "node:string_decoder";
8181
+ function parseFrame(line) {
8182
+ const text = line.trim();
8183
+ if (!text)
8184
+ throw new Error("empty frame");
8185
+ let value;
8186
+ try {
8187
+ value = JSON.parse(text);
8188
+ } catch (error) {
8189
+ throw new Error(`invalid JSON frame: ${error instanceof Error ? error.message : String(error)}`);
8190
+ }
8191
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
8192
+ throw new Error("frame must be a JSON object");
8193
+ }
8194
+ return value;
8195
+ }
8196
+ function createFrameReader(onMessage, onError) {
8197
+ const decoder = new StringDecoder("utf8");
8198
+ let parts = [];
8199
+ let bytes = 0;
8200
+ let discarding = false;
8201
+ const dispatch = () => {
8202
+ const text = discarding ? "" : parts.join("");
8203
+ const wasDiscarding = discarding;
8204
+ parts = [];
8205
+ bytes = 0;
8206
+ discarding = false;
8207
+ if (wasDiscarding || !text.trim())
8208
+ return;
7812
8209
  try {
7813
- relative = decodeURIComponent(p.slice("/assets/".length));
7814
- } catch {
7815
- return json10({ error: "invalid asset path" }, 400);
8210
+ onMessage(parseFrame(text));
8211
+ } catch (error) {
8212
+ onError(error instanceof Error ? error : new Error(String(error)));
7816
8213
  }
7817
- const root = path14.resolve(here, "assets");
7818
- const file = path14.resolve(root, relative);
7819
- if (!relative || !file.startsWith(`${root}${path14.sep}`) || !/\.(?:css|js|mjs|svg|png|jpg|woff2?)$/i.test(file))
7820
- return json10({ error: "not found" }, 404);
7821
- const data = await fs5.readFile(file).catch(() => null);
7822
- if (!data)
7823
- return json10({ error: "not found" }, 404);
7824
- const type = file.endsWith(".css") ? "text/css" : file.endsWith(".svg") ? "image/svg+xml" : /\.(?:js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".png") ? "image/png" : file.endsWith(".jpg") ? "image/jpeg" : "font/woff2";
7825
- return new Response(data, { headers: { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
8214
+ };
8215
+ const consume = (segment) => {
8216
+ const decoded = decoder.write(segment);
8217
+ if (discarding)
8218
+ return;
8219
+ if (bytes + segment.length > MAX_FRAME_BYTES) {
8220
+ parts = [];
8221
+ bytes = 0;
8222
+ discarding = true;
8223
+ onError(new Error(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`));
8224
+ return;
8225
+ }
8226
+ bytes += segment.length;
8227
+ parts.push(decoded);
8228
+ };
8229
+ return (chunk) => {
8230
+ let start = 0;
8231
+ while (start <= chunk.length) {
8232
+ const newline = chunk.indexOf(10, start);
8233
+ const end = newline === -1 ? chunk.length : newline;
8234
+ consume(chunk.subarray(start, end));
8235
+ if (newline === -1)
8236
+ return;
8237
+ dispatch();
8238
+ start = newline + 1;
8239
+ }
8240
+ };
8241
+ }
8242
+ function writeError(error) {
8243
+ const code = error?.code;
8244
+ if (code && GONE_CODES.has(code))
8245
+ return new AdapterGoneError(`adapter stream is gone (${code})`);
8246
+ return error instanceof Error ? error : new Error(String(error));
8247
+ }
8248
+ function writeFrame(stream, value) {
8249
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
8250
+ throw new TypeError("frame must be a JSON object");
7826
8251
  }
7827
- if (["POST", "PUT", "PATCH", "DELETE"].includes(req.method) && !req.headers.get("content-type")?.includes("application/json") && !(/^\/rooms\/[^/]+\/resources$/.test(p) && req.method === "POST")) {
7828
- return json10({ error: "content-type must be application/json" }, 415);
8252
+ const writable = stream;
8253
+ if (writable.destroyed || writable.writableEnded) {
8254
+ throw new AdapterGoneError("adapter stream is closed");
7829
8255
  }
7830
- if (token && req.headers.get("authorization") !== `Bearer ${token}`) {
7831
- return json10({ error: "unauthorized" }, 401);
8256
+ const line = `${JSON.stringify(value)}
8257
+ `;
8258
+ if (Buffer.byteLength(line, "utf8") > MAX_FRAME_BYTES) {
8259
+ throw new RangeError(`frame exceeds MAX_FRAME_BYTES (${MAX_FRAME_BYTES} bytes)`);
7832
8260
  }
7833
- try {
7834
- const reminders = await roomReminderRoutes(req, url);
7835
- if (reminders)
7836
- return reminders;
7837
- const admin = await adminRoutes(req, url);
7838
- if (admin)
7839
- return admin;
7840
- const resource = await resourceRoutes(req, url);
7841
- if (resource)
7842
- return resource;
7843
- const history = await historyRoute(url);
7844
- if (history)
7845
- return history;
7846
- const recall = await messageRecallRoutes(req, url);
7847
- if (recall)
7848
- return recall;
7849
- if (req.method === "GET" && p === "/rooms/summary") {
7850
- const rooms = await read((svc) => svc.listRooms().map((r) => ({
7851
- id: r.id,
7852
- name: r.name,
7853
- latestMsgTs: r.messages.at(-1)?.createdAt ?? 0
7854
- })));
7855
- return json10(rooms);
7856
- }
7857
- if (req.method === "GET" && p === "/receiver/memberships") {
7858
- const ownerID = url.searchParams.get("ownerID");
7859
- if (!isReceiverOwnerID(ownerID))
7860
- return json10({ error: "invalid ownerID" }, 400);
7861
- const sessionIDs = await readState2((_svc, registry) => {
7862
- return [...new Set(Object.values(registry).flatMap((entries) => Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id)))];
8261
+ return new Promise((resolve, reject) => {
8262
+ const fail = (error) => reject(writeError(error));
8263
+ try {
8264
+ stream.write(line, (error) => {
8265
+ if (error)
8266
+ fail(error);
8267
+ else
8268
+ resolve();
7863
8269
  });
7864
- return json10({ sessionIDs });
8270
+ } catch (error) {
8271
+ fail(error);
7865
8272
  }
7866
- if (req.method === "GET" && p === "/rooms") {
7867
- const caller = url.searchParams.get("sessionID");
7868
- const rows = await readState2((svc, registry) => svc.listRooms().filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller)).map((room) => ({ room, entry: caller ? registry[room.id]?.[caller] : undefined })));
7869
- const rooms = [];
7870
- for (const { room, entry } of rows) {
7871
- rooms.push({ ...await roomPayload(room), joined: Boolean(entry), ...entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {} });
7872
- }
7873
- return json10(rooms);
8273
+ });
8274
+ }
8275
+ var AdapterGoneError, GONE_CODES;
8276
+ var init_framing = __esm(() => {
8277
+ AdapterGoneError = class AdapterGoneError extends Error {
8278
+ code = "ADAPTER_GONE";
8279
+ constructor(message) {
8280
+ super(message);
8281
+ this.name = "AdapterGoneError";
7874
8282
  }
7875
- const members = await memberRoutes(req, url);
8283
+ };
8284
+ GONE_CODES = new Set(["EPIPE", "ERR_STREAM_DESTROYED", "ERR_STREAM_WRITE_AFTER_END"]);
8285
+ });
8286
+
8287
+ // packages/chat-room-channeld/src/log.ts
8288
+ function write(level, message, fields = {}) {
8289
+ const parts = [new Date().toISOString(), level, message];
8290
+ if (fields.account)
8291
+ parts.push(`account=${fields.account}`);
8292
+ if (fields.delivery)
8293
+ parts.push(`delivery=${fields.delivery}`);
8294
+ if (fields.event)
8295
+ parts.push(`event=${fields.event}`);
8296
+ process.stderr.write(`${parts.join(" ")}
8297
+ `);
8298
+ }
8299
+ var log;
8300
+ var init_log = __esm(() => {
8301
+ log = {
8302
+ info(message, fields) {
8303
+ write("INFO", message, fields);
8304
+ },
8305
+ warn(message, fields) {
8306
+ write("WARN", message, fields);
8307
+ },
8308
+ error(message, fields) {
8309
+ write("ERROR", message, fields);
8310
+ }
8311
+ };
8312
+ });
8313
+
8314
+ // packages/chat-room-channeld/src/adapter.ts
8315
+ import { spawn as spawn2 } from "node:child_process";
8316
+ import { StringDecoder as StringDecoder2 } from "node:string_decoder";
8317
+
8318
+ class AdapterProcess {
8319
+ #account;
8320
+ #onIngest;
8321
+ #onExit;
8322
+ #onUnavailable;
8323
+ #initializeTimeoutMs;
8324
+ #sendTimeoutMs;
8325
+ #pending = new Map;
8326
+ #stderrDecoder = new StringDecoder2("utf8");
8327
+ #child;
8328
+ #sequence = 0;
8329
+ #stderrTail = "";
8330
+ #started = false;
8331
+ #stopping = false;
8332
+ #gone = false;
8333
+ #pollutionError;
8334
+ constructor(options) {
8335
+ this.#account = options.account;
8336
+ this.#onIngest = options.onIngest;
8337
+ this.#onExit = options.onExit;
8338
+ this.#onUnavailable = options.onUnavailable;
8339
+ this.#initializeTimeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;
8340
+ this.#sendTimeoutMs = options.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
8341
+ }
8342
+ get accountId() {
8343
+ return this.#account.id;
8344
+ }
8345
+ async start() {
8346
+ if (this.#child)
8347
+ throw new Error(`adapter ${this.#account.id} already started`);
8348
+ const [command, ...args] = this.#account.adapter.command;
8349
+ if (!command)
8350
+ throw new Error(`adapter ${this.#account.id} has an empty command`);
8351
+ const child = spawn2(command, args, {
8352
+ stdio: ["pipe", "pipe", "pipe"],
8353
+ env: {
8354
+ ...process.env,
8355
+ CHANNELD_ACCOUNT_ID: this.#account.id,
8356
+ CHANNELD_PLATFORM: this.#account.platform
8357
+ }
8358
+ });
8359
+ this.#child = child;
8360
+ this.#attach(child);
8361
+ try {
8362
+ await this.#call("initialize", {
8363
+ protocolVersions: [PROTOCOL_VERSION],
8364
+ eventSchemas: [EVENT_SCHEMA_VERSION],
8365
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
8366
+ platform: this.#account.platform,
8367
+ accounts: [this.#account.id],
8368
+ maxFrameBytes: MAX_FRAME_BYTES
8369
+ }, this.#initializeTimeoutMs);
8370
+ await this.#call("start", { accounts: [this.#account.id], cursors: {} }, this.#initializeTimeoutMs);
8371
+ } catch (error) {
8372
+ const tail = this.#stderrTail.trim();
8373
+ const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
8374
+ this.#stopping = true;
8375
+ this.#killNow();
8376
+ throw new Error(`adapter ${this.#account.id} failed to start: ${message}${tail ? `
8377
+ stderr:
8378
+ ${tail}` : ""}`);
8379
+ }
8380
+ this.#started = true;
8381
+ log.info("adapter started", { account: this.#account.id });
8382
+ }
8383
+ async send(deliveryId, attemptId, idempotencyKey, target, payload) {
8384
+ if (!this.#started || !this.#child) {
8385
+ return { state: "unknown", detail: "adapter is not running" };
8386
+ }
8387
+ try {
8388
+ const result = await this.#call("send", { deliveryId, attemptId, idempotencyKey, target, payload }, this.#sendTimeoutMs);
8389
+ const raw = result ?? {};
8390
+ if (!raw.state || !SEND_STATES.includes(raw.state)) {
8391
+ return { state: "unknown", detail: `adapter returned invalid state: ${String(raw.state)}` };
8392
+ }
8393
+ return {
8394
+ state: raw.state,
8395
+ providerMessage: raw.providerMessage,
8396
+ retryAfterMs: raw.retryAfterMs,
8397
+ detail: raw.detail
8398
+ };
8399
+ } catch (error) {
8400
+ return { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
8401
+ }
8402
+ }
8403
+ async stop() {
8404
+ if (this.#stopping)
8405
+ return;
8406
+ this.#stopping = true;
8407
+ this.#started = false;
8408
+ const child = this.#child;
8409
+ this.#rejectPending(new AdapterGoneError(`adapter ${this.#account.id} stopped`));
8410
+ if (!child) {
8411
+ this.#cleanup();
8412
+ return;
8413
+ }
8414
+ try {
8415
+ try {
8416
+ await this.#call("shutdown", {}, 1000);
8417
+ } catch {}
8418
+ try {
8419
+ child.stdin.end();
8420
+ } catch {}
8421
+ if (await this.#waitForExit(2000))
8422
+ return;
8423
+ child.kill("SIGTERM");
8424
+ if (await this.#waitForExit(1000))
8425
+ return;
8426
+ child.kill("SIGKILL");
8427
+ await this.#waitForExit(1000);
8428
+ } catch (error) {
8429
+ try {
8430
+ log.warn(`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`, { account: this.#account.id });
8431
+ } catch {}
8432
+ } finally {
8433
+ this.#cleanup();
8434
+ }
8435
+ }
8436
+ #attach(child) {
8437
+ child.stdin.on("error", (error) => this.#handleStdioError("stdin", error));
8438
+ child.stdout.on("error", (error) => this.#handleStdioError("stdout", error));
8439
+ child.stderr.on("error", (error) => this.#handleStdioError("stderr", error));
8440
+ const read = createFrameReader((message) => {
8441
+ this.#dispatch(message).catch((error) => {
8442
+ this.#markGone(`adapter ${this.#account.id} dispatch failed: ${error instanceof Error ? error.message : String(error)}`);
8443
+ });
8444
+ }, (error) => this.#handleStdoutPollution(error));
8445
+ child.stdout.on("data", (chunk) => read(chunk));
8446
+ child.stderr.on("data", (chunk) => {
8447
+ const text = this.#stderrDecoder.write(chunk);
8448
+ this.#stderrTail = `${this.#stderrTail}${text}`.slice(-STDERR_TAIL_LIMIT);
8449
+ for (const line of text.split(`
8450
+ `)) {
8451
+ if (line.trim())
8452
+ log.info(line, { account: this.#account.id });
8453
+ }
8454
+ });
8455
+ child.on("error", (error) => {
8456
+ this.#markGone(`adapter process error: ${error.message}`);
8457
+ });
8458
+ child.once("exit", (code, signal) => {
8459
+ this.#detachStreams(child);
8460
+ this.#child = undefined;
8461
+ this.#rejectPending(new Error(`adapter exited (code=${code} signal=${signal})`));
8462
+ if (!this.#stopping && !this.#gone && this.#started) {
8463
+ log.error(`adapter exited code=${code ?? "null"} signal=${signal ?? "none"}`, {
8464
+ account: this.#account.id
8465
+ });
8466
+ this.#onExit(code, signal);
8467
+ }
8468
+ this.#started = false;
8469
+ });
8470
+ }
8471
+ #handleStdioError(streamName, error) {
8472
+ const message = error instanceof Error ? error.message : String(error);
8473
+ this.#markGone(`adapter ${this.#account.id} ${streamName} error: ${message}`);
8474
+ }
8475
+ async#dispatch(message) {
8476
+ const id = message.id;
8477
+ if (id !== undefined && typeof message.method === "string") {
8478
+ await this.#handleRequest(id, message.method, message.params);
8479
+ return;
8480
+ }
8481
+ if (id === undefined) {
8482
+ log.warn("adapter frame has no id", { account: this.#account.id });
8483
+ return;
8484
+ }
8485
+ const pending = this.#pending.get(String(id));
8486
+ if (!pending) {
8487
+ log.warn(`adapter response for unknown id ${String(id)}`, { account: this.#account.id });
8488
+ return;
8489
+ }
8490
+ this.#pending.delete(String(id));
8491
+ clearTimeout(pending.timer);
8492
+ const rpcFailure = message.error;
8493
+ if (rpcFailure) {
8494
+ pending.reject(new Error(rpcFailure.message ?? "adapter JSON-RPC error"));
8495
+ return;
8496
+ }
8497
+ pending.resolve(message.result);
8498
+ }
8499
+ async#handleRequest(id, method, params) {
8500
+ const child = this.#child;
8501
+ if (!child)
8502
+ return;
8503
+ try {
8504
+ if (method === "ingest") {
8505
+ const result = await this.#onIngest(params);
8506
+ await writeFrame(child.stdin, rpcResult(id, result.duplicate ? { duplicate: true } : { committed: true }));
8507
+ } else if (method === "ping") {
8508
+ await writeFrame(child.stdin, rpcResult(id, { pong: true }));
8509
+ } else {
8510
+ await writeFrame(child.stdin, rpcError(id, RPC_METHOD_NOT_FOUND, `method not found: ${method}`));
8511
+ }
8512
+ } catch (error) {
8513
+ if (error instanceof AdapterGoneError) {
8514
+ this.#markGone(error.message);
8515
+ return;
8516
+ }
8517
+ const message = error instanceof Error ? error.message : String(error);
8518
+ const code = error?.code;
8519
+ if (code !== "ingest_buffer_overflow") {
8520
+ try {
8521
+ log.error(`adapter request ${method} failed: ${message}`, { account: this.#account.id });
8522
+ } catch {}
8523
+ }
8524
+ try {
8525
+ await writeFrame(child.stdin, rpcError(id, RPC_INTERNAL_ERROR, message));
8526
+ } catch (writeError) {
8527
+ if (writeError instanceof AdapterGoneError)
8528
+ this.#markGone(writeError.message);
8529
+ }
8530
+ }
8531
+ }
8532
+ #handleStdoutPollution(error) {
8533
+ if (this.#pollutionError)
8534
+ return;
8535
+ const message = `adapter ${this.#account.id} wrote non-protocol output to stdout; adapter stdout may contain protocol frames only, logs must go to stderr`;
8536
+ this.#pollutionError = new Error(message);
8537
+ try {
8538
+ log.error(message, { account: this.#account.id });
8539
+ } catch {}
8540
+ this.#markGone(message, false);
8541
+ }
8542
+ #markGone(reason, logReason = true) {
8543
+ if (this.#gone)
8544
+ return;
8545
+ this.#gone = true;
8546
+ this.#stopping = true;
8547
+ this.#started = false;
8548
+ if (logReason) {
8549
+ try {
8550
+ log.warn(reason, { account: this.#account.id });
8551
+ } catch {}
8552
+ }
8553
+ try {
8554
+ this.#onUnavailable?.(reason);
8555
+ } catch (error) {
8556
+ try {
8557
+ log.error(`adapter unavailable handler failed: ${error instanceof Error ? error.message : String(error)}`, { account: this.#account.id });
8558
+ } catch {}
8559
+ }
8560
+ this.#rejectPending(new AdapterGoneError(reason));
8561
+ try {
8562
+ this.#child?.kill("SIGKILL");
8563
+ } catch {}
8564
+ }
8565
+ #call(method, params, timeoutMs) {
8566
+ return new Promise((resolve, reject) => {
8567
+ if (this.#gone) {
8568
+ reject(new AdapterGoneError(`adapter ${this.#account.id} is gone`));
8569
+ return;
8570
+ }
8571
+ if (this.#pollutionError) {
8572
+ reject(this.#pollutionError);
8573
+ return;
8574
+ }
8575
+ const child = this.#child;
8576
+ if (!child || child.stdin.destroyed || child.stdin.writableEnded) {
8577
+ const error = new AdapterGoneError(`adapter ${this.#account.id} is not running`);
8578
+ reject(error);
8579
+ if (!this.#stopping)
8580
+ this.#markGone(error.message);
8581
+ return;
8582
+ }
8583
+ const id = hostRequestId(++this.#sequence);
8584
+ const timer = setTimeout(() => {
8585
+ this.#pending.delete(id);
8586
+ reject(new Error(`${method} timed out after ${timeoutMs}ms`));
8587
+ }, timeoutMs);
8588
+ this.#pending.set(id, {
8589
+ resolve: (value) => {
8590
+ clearTimeout(timer);
8591
+ resolve(value);
8592
+ },
8593
+ reject: (error) => {
8594
+ clearTimeout(timer);
8595
+ reject(error);
8596
+ },
8597
+ timer
8598
+ });
8599
+ const failedWrite = (error) => {
8600
+ this.#pending.delete(id);
8601
+ clearTimeout(timer);
8602
+ reject(error instanceof Error ? error : new Error(String(error)));
8603
+ if (error instanceof AdapterGoneError && !this.#stopping)
8604
+ this.#markGone(error.message);
8605
+ };
8606
+ try {
8607
+ writeFrame(child.stdin, rpcRequest(id, method, params)).catch(failedWrite);
8608
+ } catch (error) {
8609
+ failedWrite(error);
8610
+ }
8611
+ });
8612
+ }
8613
+ #waitForExit(ms) {
8614
+ const child = this.#child;
8615
+ if (!child || child.exitCode !== null || child.signalCode !== null)
8616
+ return Promise.resolve(true);
8617
+ return new Promise((resolve) => {
8618
+ const timer = setTimeout(() => {
8619
+ child.off("exit", onExit);
8620
+ resolve(false);
8621
+ }, ms);
8622
+ const onExit = () => {
8623
+ clearTimeout(timer);
8624
+ resolve(true);
8625
+ };
8626
+ child.once("exit", onExit);
8627
+ });
8628
+ }
8629
+ #rejectPending(error) {
8630
+ for (const [id, pending] of this.#pending) {
8631
+ this.#pending.delete(id);
8632
+ clearTimeout(pending.timer);
8633
+ pending.reject(error);
8634
+ }
8635
+ }
8636
+ #detachStreams(child) {
8637
+ for (const stream of [child.stdin, child.stdout, child.stderr]) {
8638
+ stream.removeAllListeners();
8639
+ stream.on("error", () => {});
8640
+ }
8641
+ child.removeAllListeners();
8642
+ child.on("error", () => {});
8643
+ }
8644
+ #killNow() {
8645
+ const child = this.#child;
8646
+ this.#child = undefined;
8647
+ this.#started = false;
8648
+ this.#rejectPending(new Error("adapter failed to start"));
8649
+ if (child) {
8650
+ this.#detachStreams(child);
8651
+ if (child.exitCode === null && child.signalCode === null)
8652
+ child.kill("SIGKILL");
8653
+ }
8654
+ }
8655
+ #cleanup() {
8656
+ const child = this.#child;
8657
+ this.#child = undefined;
8658
+ this.#started = false;
8659
+ this.#rejectPending(new Error("adapter stopped"));
8660
+ if (!child)
8661
+ return;
8662
+ this.#detachStreams(child);
8663
+ }
8664
+ }
8665
+ var SEND_STATES, STDERR_TAIL_LIMIT = 4096, DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4, DEFAULT_SEND_TIMEOUT_MS = 15000;
8666
+ var init_adapter = __esm(() => {
8667
+ init_framing();
8668
+ init_log();
8669
+ SEND_STATES = [
8670
+ "sent",
8671
+ "retryable",
8672
+ "rate_limited",
8673
+ "permanent",
8674
+ "unsupported",
8675
+ "unknown"
8676
+ ];
8677
+ });
8678
+
8679
+ // packages/chat-room-channeld/src/rules.ts
8680
+ function targetKey(endpoint) {
8681
+ const parts = [endpoint.platform, endpoint.accountId, endpoint.roomId];
8682
+ if (parts.some((part) => !part || part.includes("/"))) {
8683
+ throw new ConfigError('config: platform, account and room must be non-empty and must not contain "/"');
8684
+ }
8685
+ return parts.join("/");
8686
+ }
8687
+ function sameEndpoint(left, right) {
8688
+ return left.platform === right.platform && left.accountId === right.accountId && left.roomId === right.roomId;
8689
+ }
8690
+ function matchRules(config, event) {
8691
+ if (event.kind === "result.published")
8692
+ return [];
8693
+ const latest = new Map;
8694
+ for (const rule of config.rules) {
8695
+ const current = latest.get(rule.id);
8696
+ if (!current || rule.version > current.version)
8697
+ latest.set(rule.id, rule);
8698
+ }
8699
+ return [...latest.values()].filter((rule) => {
8700
+ const { from } = rule;
8701
+ return from.platform === event.source.platform && from.account === event.source.accountId && from.room === event.source.roomId && (from.event === undefined || from.event === event.kind);
8702
+ }).sort((left, right) => left.id === right.id ? left.version - right.version : left.id < right.id ? -1 : left.id > right.id ? 1 : 0);
8703
+ }
8704
+ function renderForTarget(rule, event, target) {
8705
+ let text = event.content?.text ?? "";
8706
+ if (!text)
8707
+ return { text: "", degraded: "empty" };
8708
+ for (const transform of rule.transforms) {
8709
+ switch (transform.op) {
8710
+ case "prefix-source":
8711
+ text = `[${event.source.platform}/${event.source.roomId}] ${text}`;
8712
+ break;
8713
+ case "trim":
8714
+ text = text.trim();
8715
+ break;
8716
+ case "truncate":
8717
+ if (text.length > transform.max)
8718
+ text = `${text.slice(0, transform.max)}…`;
8719
+ break;
8720
+ case "quote-preview": {
8721
+ const quote = event.selectedMessage?.text?.trim();
8722
+ if (quote) {
8723
+ const short = quote.length > QUOTE_PREVIEW_LIMIT ? `${quote.slice(0, QUOTE_PREVIEW_LIMIT)}…` : quote;
8724
+ text = `${text}
8725
+ > ${short}`;
8726
+ }
8727
+ break;
8728
+ }
8729
+ }
8730
+ }
8731
+ if (!text)
8732
+ return { text: "", degraded: "empty" };
8733
+ return { text };
8734
+ }
8735
+ function planPayload(rule, event, target) {
8736
+ const rendered = renderForTarget(rule, event, {
8737
+ platform: target.platform,
8738
+ account: target.accountId,
8739
+ room: target.roomId
8740
+ });
8741
+ let payload;
8742
+ if (rendered.degraded === "empty") {
8743
+ if (rule.onUnsupported === "drop")
8744
+ return { dropped: "rendered text is empty" };
8745
+ payload = { text: UNSUPPORTED_NOTICE, degraded: "empty" };
8746
+ } else {
8747
+ payload = { text: rendered.text };
8748
+ }
8749
+ if (event.parent) {
8750
+ if (sameEndpoint(event.parent.endpoint, target)) {
8751
+ payload.parent = event.parent;
8752
+ } else if (rule.onMissingParent === "drop") {
8753
+ return { dropped: "parent message mapping is unavailable" };
8754
+ } else {
8755
+ payload.degraded = "unthreaded";
8756
+ }
8757
+ }
8758
+ return { payload };
8759
+ }
8760
+ var QUOTE_PREVIEW_LIMIT = 280, UNSUPPORTED_NOTICE = "attachment/format unsupported";
8761
+ var init_rules = __esm(() => {
8762
+ init_config();
8763
+ });
8764
+
8765
+ // packages/chat-room-channeld/src/published.ts
8766
+ function buildPublishedResult(delivery, receipt, now) {
8767
+ const occurredAt = new Date(now).toISOString();
8768
+ return {
8769
+ schemaVersion: EVENT_SCHEMA_VERSION,
8770
+ eventId: `result-${delivery.deliveryId}`,
8771
+ kind: "result.published",
8772
+ source: { platform: "channeld", accountId: "host", roomId: delivery.deliveryId },
8773
+ actor: { platform: "channeld", identityNamespace: "system", nativeUserId: "channeld" },
8774
+ sourceDedupKey: `${PUBLISHED_RESULT_PREFIX}${delivery.deliveryId}`,
8775
+ cause: { rootEventId: delivery.eventId, visitedEndpoints: [], hopCount: 1 },
8776
+ occurredAt,
8777
+ receivedAt: occurredAt,
8778
+ forwardEventId: delivery.eventId,
8779
+ deliveryId: delivery.deliveryId,
8780
+ receiptId: receipt?.receiptId ?? null,
8781
+ state: delivery.state,
8782
+ target: delivery.target
8783
+ };
8784
+ }
8785
+ var PUBLISHED_RESULT_PREFIX = "result.published:";
8786
+ var init_published = () => {};
8787
+
8788
+ // packages/chat-room-channeld/src/stats.ts
8789
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
8790
+ function count(db, sql) {
8791
+ const row = db.prepare(sql).get();
8792
+ return Number(row.count);
8793
+ }
8794
+ function accountKey(target) {
8795
+ const first = target.indexOf("/");
8796
+ if (first < 0)
8797
+ return target;
8798
+ const second = target.indexOf("/", first + 1);
8799
+ return second === -1 ? target : target.slice(0, second);
8800
+ }
8801
+ function readChannelStats(path, now = Date.now()) {
8802
+ let db;
8803
+ try {
8804
+ db = new DatabaseSync2(path, { readOnly: true });
8805
+ db.exec("PRAGMA busy_timeout = 2000");
8806
+ const names = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => String(row.name)));
8807
+ if (REQUIRED_TABLES.some((table) => !names.has(table))) {
8808
+ throw new Error(`channel state not found: ${path}`);
8809
+ }
8810
+ const stateCounts = {};
8811
+ const accounts = new Map;
8812
+ let oldestBacklogAt = null;
8813
+ const rows = db.prepare("SELECT target, state, created_at FROM channel_deliveries").all();
8814
+ for (const row of rows) {
8815
+ const state = String(row.state);
8816
+ stateCounts[state] = (stateCounts[state] ?? 0) + 1;
8817
+ const key = accountKey(String(row.target));
8818
+ let account = accounts.get(key);
8819
+ if (!account) {
8820
+ account = {
8821
+ account: key,
8822
+ queueDepth: 0,
8823
+ oldestBacklogAt: null,
8824
+ unknown: 0,
8825
+ retryable: 0,
8826
+ rateLimited: 0
8827
+ };
8828
+ accounts.set(key, account);
8829
+ }
8830
+ if (state === "unknown")
8831
+ account.unknown += 1;
8832
+ if (state === "retryable")
8833
+ account.retryable += 1;
8834
+ if (state === "rate_limited")
8835
+ account.rateLimited += 1;
8836
+ if (QUEUE_STATES.has(state)) {
8837
+ const createdAt = Number(row.created_at);
8838
+ account.queueDepth += 1;
8839
+ if (account.oldestBacklogAt === null || createdAt < account.oldestBacklogAt) {
8840
+ account.oldestBacklogAt = createdAt;
8841
+ }
8842
+ if (oldestBacklogAt === null || createdAt < oldestBacklogAt) {
8843
+ oldestBacklogAt = createdAt;
8844
+ }
8845
+ }
8846
+ }
8847
+ const pending = stateCounts.pending ?? 0;
8848
+ const retryable = stateCounts.retryable ?? 0;
8849
+ const rateLimited = stateCounts.rate_limited ?? 0;
8850
+ const failed = (stateCounts.permanent ?? 0) + (stateCounts.unsupported ?? 0) + (stateCounts.exhausted ?? 0);
8851
+ return {
8852
+ generatedAt: now,
8853
+ events: count(db, "SELECT COUNT(*) AS count FROM channel_events"),
8854
+ publishedResults: count(db, "SELECT COUNT(*) AS count FROM channel_events WHERE json_extract(payload, '$.kind') = 'result.published'"),
8855
+ eventsWithoutDeliveries: count(db, `SELECT COUNT(*) AS count FROM channel_events e
8856
+ WHERE json_extract(e.payload, '$.kind') IS NOT 'result.published'
8857
+ AND NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.event_id = e.event_id)`),
8858
+ deliveriesWithoutEvent: count(db, `SELECT COUNT(*) AS count FROM channel_deliveries d
8859
+ WHERE NOT EXISTS (SELECT 1 FROM channel_events e WHERE e.event_id = d.event_id)`),
8860
+ receiptsWithoutDelivery: count(db, `SELECT COUNT(*) AS count FROM channel_receipts r
8861
+ WHERE NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.delivery_id = r.delivery_id)`),
8862
+ deliveries: {
8863
+ total: rows.length,
8864
+ pending,
8865
+ inFlight: stateCounts.in_flight ?? 0,
8866
+ retryable,
8867
+ rateLimited,
8868
+ paused: stateCounts.paused ?? 0,
8869
+ unknown: stateCounts.unknown ?? 0,
8870
+ sent: stateCounts.sent ?? 0,
8871
+ failed
8872
+ },
8873
+ queueDepth: pending + retryable + rateLimited,
8874
+ oldestBacklogAt,
8875
+ oldestBacklogAgeMs: oldestBacklogAt === null ? null : now - oldestBacklogAt,
8876
+ accounts: [...accounts.values()].sort((left, right) => left.account < right.account ? -1 : left.account > right.account ? 1 : 0)
8877
+ };
8878
+ } catch (error) {
8879
+ if (error instanceof Error && error.message.startsWith("channel state not found:"))
8880
+ throw error;
8881
+ throw new Error(`channel state not found: ${path}`);
8882
+ } finally {
8883
+ try {
8884
+ db?.close();
8885
+ } catch {}
8886
+ }
8887
+ }
8888
+ var REQUIRED_TABLES, QUEUE_STATES;
8889
+ var init_stats = __esm(() => {
8890
+ REQUIRED_TABLES = ["channel_events", "channel_deliveries", "channel_receipts"];
8891
+ QUEUE_STATES = new Set(["pending", "retryable", "rate_limited"]);
8892
+ });
8893
+
8894
+ // packages/chat-room-channeld/src/state.ts
8895
+ import { randomUUID as randomUUID14 } from "node:crypto";
8896
+ import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
8897
+ function isTerminalDeliveryState(state) {
8898
+ return TERMINAL_DELIVERY_STATES.includes(state);
8899
+ }
8900
+ function transaction(db, fn) {
8901
+ db.exec("BEGIN IMMEDIATE");
8902
+ try {
8903
+ const value = fn();
8904
+ db.exec("COMMIT");
8905
+ return value;
8906
+ } catch (error) {
8907
+ try {
8908
+ db.exec("ROLLBACK");
8909
+ } catch {}
8910
+ throw error;
8911
+ }
8912
+ }
8913
+ function toDelivery(row) {
8914
+ return {
8915
+ deliveryId: String(row.delivery_id),
8916
+ eventId: String(row.event_id),
8917
+ ruleId: String(row.rule_id),
8918
+ ruleVersion: Number(row.rule_version),
8919
+ target: String(row.target),
8920
+ idempotencyKey: String(row.idempotency_key),
8921
+ payload: String(row.payload),
8922
+ state: String(row.state),
8923
+ attemptCount: Number(row.attempt_count),
8924
+ nextAttemptAt: row.next_attempt_at === null ? null : Number(row.next_attempt_at),
8925
+ lastError: row.last_error === null ? null : String(row.last_error),
8926
+ providerMessage: row.provider_message === null ? null : String(row.provider_message),
8927
+ createdAt: Number(row.created_at),
8928
+ updatedAt: Number(row.updated_at)
8929
+ };
8930
+ }
8931
+ function toReceipt(row) {
8932
+ return {
8933
+ receiptId: String(row.receipt_id),
8934
+ deliveryId: String(row.delivery_id),
8935
+ attemptId: String(row.attempt_id),
8936
+ state: String(row.state),
8937
+ providerMessage: row.provider_message === null ? null : String(row.provider_message),
8938
+ detail: row.detail === null ? null : String(row.detail),
8939
+ observedAt: Number(row.observed_at)
8940
+ };
8941
+ }
8942
+ function openState(path) {
8943
+ const db = new DatabaseSync3(path);
8944
+ db.exec(SCHEMA);
8945
+ let closed = false;
8946
+ function getDelivery(deliveryId) {
8947
+ const row = db.prepare("SELECT * FROM channel_deliveries WHERE delivery_id = ?").get(deliveryId);
8948
+ return row ? toDelivery(row) : undefined;
8949
+ }
8950
+ return {
8951
+ commitIngest(event) {
8952
+ return transaction(db, () => {
8953
+ const existing = db.prepare("SELECT event_id FROM channel_events WHERE dedup_key = ?").get(event.sourceDedupKey);
8954
+ if (existing) {
8955
+ return { duplicate: true, existingEventId: String(existing.event_id) };
8956
+ }
8957
+ const max = db.prepare("SELECT COALESCE(MAX(ingress_seq), 0) AS seq FROM channel_events").get();
8958
+ const ingressSeq = event.ingressSeq ?? Number(max.seq) + 1;
8959
+ const stored = { ...event, ingressSeq };
8960
+ db.prepare(`INSERT INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
8961
+ VALUES (?, ?, ?, ?, ?)`).run(event.eventId, event.sourceDedupKey, JSON.stringify(stored), ingressSeq, Date.now());
8962
+ return { duplicate: false, eventId: event.eventId, ingressSeq };
8963
+ });
8964
+ },
8965
+ enqueueDeliveries(triggerEventId, rule, targets, payloads) {
8966
+ if (targets.length !== payloads.length) {
8967
+ throw new Error("enqueueDeliveries: targets and payloads must have the same length");
8968
+ }
8969
+ const now = Date.now();
8970
+ const created = [];
8971
+ transaction(db, () => {
8972
+ const insert = db.prepare(`INSERT OR IGNORE INTO channel_deliveries
8973
+ (delivery_id, event_id, rule_id, rule_version, target, idempotency_key, payload, state, created_at, updated_at)
8974
+ VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?)`);
8975
+ targets.forEach((target, index) => {
8976
+ const key = `${target.platform}/${target.account}/${target.room}`;
8977
+ const idempotencyKey = `${triggerEventId}:${rule.id}:${rule.version}:0:${key}`;
8978
+ const deliveryId = `dlv-${randomUUID14()}`;
8979
+ const result = insert.run(deliveryId, triggerEventId, rule.id, rule.version, key, idempotencyKey, payloads[index] ?? "", now, now);
8980
+ if (Number(result.changes) > 0)
8981
+ created.push({ deliveryId, target: key });
8982
+ });
8983
+ });
8984
+ return created;
8985
+ },
8986
+ nextPendingDelivery(accountKey, now) {
8987
+ const prefix = `${accountKey.replace(/\/+$/, "")}/`;
8988
+ const row = db.prepare(`SELECT * FROM channel_deliveries
8989
+ WHERE substr(target, 1, length(?)) = ?
8990
+ AND state IN ('pending', 'retryable', 'rate_limited')
8991
+ AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
8992
+ ORDER BY created_at ASC, delivery_id ASC
8993
+ LIMIT 1`).get(prefix, prefix, now);
8994
+ return row ? toDelivery(row) : undefined;
8995
+ },
8996
+ markDelivery(deliveryId, state, patch = {}) {
8997
+ if (!DELIVERY_STATES.includes(state))
8998
+ throw new Error(`unknown delivery state: ${state}`);
8999
+ const current = getDelivery(deliveryId);
9000
+ if (!current)
9001
+ throw new Error(`delivery not found: ${deliveryId}`);
9002
+ const terminal = isTerminalDeliveryState(state);
9003
+ const nextAttemptAt = patch.nextAttemptAt !== undefined ? patch.nextAttemptAt : terminal ? null : current.nextAttemptAt;
9004
+ db.prepare(`UPDATE channel_deliveries
9005
+ SET state = ?, attempt_count = ?, next_attempt_at = ?, last_error = ?, provider_message = ?, updated_at = ?
9006
+ WHERE delivery_id = ?`).run(state, patch.attemptCount ?? current.attemptCount, nextAttemptAt, patch.lastError !== undefined ? patch.lastError : current.lastError, patch.providerMessage !== undefined ? patch.providerMessage : current.providerMessage, Date.now(), deliveryId);
9007
+ },
9008
+ recordSent(input) {
9009
+ const receiptId = `rcp-${randomUUID14()}`;
9010
+ transaction(db, () => {
9011
+ db.prepare(`INSERT INTO channel_receipts
9012
+ (receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
9013
+ VALUES (?, ?, ?, 'sent', ?, ?, ?)`).run(receiptId, input.deliveryId, input.attemptId, input.providerMessage, input.detail ?? null, input.observedAt ?? Date.now());
9014
+ if (input.echo) {
9015
+ db.prepare(`INSERT OR IGNORE INTO channel_echoes
9016
+ (endpoint, native_message_id, logical_message_id, delivery_id)
9017
+ VALUES (?, ?, ?, ?)`).run(input.echo.endpoint, input.echo.nativeMessageId, input.echo.logicalMessageId, input.deliveryId);
9018
+ }
9019
+ });
9020
+ return receiptId;
9021
+ },
9022
+ pauseAccountDeliveries(accountKey, reason) {
9023
+ const prefix = `${accountKey.replace(/\/+$/, "")}/`;
9024
+ const result = db.prepare(`UPDATE channel_deliveries
9025
+ SET state = 'paused', next_attempt_at = NULL, last_error = ?, updated_at = ?
9026
+ WHERE substr(target, 1, length(?)) = ?
9027
+ AND state IN ('pending', 'retryable', 'rate_limited')`).run(reason, Date.now(), prefix, prefix);
9028
+ return Number(result.changes);
9029
+ },
9030
+ abandonUnconfiguredDeliveries(configuredAccountKeys) {
9031
+ const configured = [...new Set(configuredAccountKeys)];
9032
+ const accountKeySql = `CASE WHEN instr(target, '/') > 0
9033
+ AND instr(substr(target, instr(target, '/') + 1), '/') > 0
9034
+ THEN substr(target, 1, instr(target, '/') + instr(substr(target, instr(target, '/') + 1), '/') - 1)
9035
+ ELSE target END`;
9036
+ const filter = configured.length > 0 ? `AND (${accountKeySql}) NOT IN (${configured.map(() => "?").join(", ")})` : "";
9037
+ const rows = db.prepare(`SELECT * FROM channel_deliveries
9038
+ WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
9039
+ ${filter}
9040
+ ORDER BY created_at ASC, delivery_id ASC`).all(...configured);
9041
+ if (rows.length === 0)
9042
+ return [];
9043
+ transaction(db, () => db.prepare(`UPDATE channel_deliveries
9044
+ SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
9045
+ WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
9046
+ ${filter}`).run("account is not configured; add it back to retry", Date.now(), ...configured));
9047
+ return rows.map((row) => ({ ...toDelivery(row), state: "unknown" }));
9048
+ },
9049
+ resumePausedDeliveries() {
9050
+ const result = db.prepare(`UPDATE channel_deliveries
9051
+ SET state = 'pending', next_attempt_at = NULL, updated_at = ?
9052
+ WHERE state = 'paused'`).run(Date.now());
9053
+ return Number(result.changes);
9054
+ },
9055
+ recoverInFlightDeliveries() {
9056
+ const result = db.prepare(`UPDATE channel_deliveries
9057
+ SET state = 'pending', next_attempt_at = NULL,
9058
+ last_error = 'recovered stale in_flight after restart', updated_at = ?
9059
+ WHERE state = 'in_flight'`).run(Date.now());
9060
+ return Number(result.changes);
9061
+ },
9062
+ recordReceipt(input) {
9063
+ const receiptId = `rcp-${randomUUID14()}`;
9064
+ db.prepare(`INSERT INTO channel_receipts
9065
+ (receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
9066
+ VALUES (?, ?, ?, ?, ?, ?, ?)`).run(receiptId, input.deliveryId, input.attemptId, input.state, input.providerMessage ?? null, input.detail ?? null, input.observedAt ?? Date.now());
9067
+ return receiptId;
9068
+ },
9069
+ recordPublishedResult(delivery, receipt) {
9070
+ const now = Date.now();
9071
+ const event = buildPublishedResult(delivery, receipt, now);
9072
+ db.prepare(`INSERT OR IGNORE INTO channel_events (event_id, dedup_key, payload, ingress_seq, committed_at)
9073
+ VALUES (?, ?, ?, NULL, ?)`).run(event.eventId, event.sourceDedupKey, JSON.stringify(event), now);
9074
+ },
9075
+ getPublishedResult(deliveryId) {
9076
+ const row = db.prepare("SELECT payload FROM channel_events WHERE dedup_key = ?").get(`${PUBLISHED_RESULT_PREFIX}${deliveryId}`);
9077
+ return row ? JSON.parse(String(row.payload)) : undefined;
9078
+ },
9079
+ recordEcho(endpoint, nativeMessageId, logicalMessageId, deliveryId) {
9080
+ db.prepare(`INSERT OR IGNORE INTO channel_echoes
9081
+ (endpoint, native_message_id, logical_message_id, delivery_id)
9082
+ VALUES (?, ?, ?, ?)`).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null);
9083
+ },
9084
+ findEcho(endpoint, nativeMessageId) {
9085
+ const row = db.prepare("SELECT logical_message_id FROM channel_echoes WHERE endpoint = ? AND native_message_id = ?").get(endpoint, nativeMessageId);
9086
+ return row ? String(row.logical_message_id) : undefined;
9087
+ },
9088
+ getDelivery,
9089
+ getEvent(eventId) {
9090
+ const row = db.prepare("SELECT payload FROM channel_events WHERE event_id = ?").get(eventId);
9091
+ return row ? JSON.parse(String(row.payload)) : undefined;
9092
+ },
9093
+ listDeliveries() {
9094
+ return db.prepare("SELECT * FROM channel_deliveries ORDER BY created_at ASC, delivery_id ASC").all().map(toDelivery);
9095
+ },
9096
+ listReceipts(deliveryId) {
9097
+ return db.prepare("SELECT * FROM channel_receipts WHERE delivery_id = ? ORDER BY observed_at ASC, receipt_id ASC").all(deliveryId).map(toReceipt);
9098
+ },
9099
+ countEvents() {
9100
+ const row = db.prepare("SELECT COUNT(*) AS count FROM channel_events WHERE dedup_key NOT LIKE ?").get(`${PUBLISHED_RESULT_PREFIX}%`);
9101
+ return Number(row.count);
9102
+ },
9103
+ close() {
9104
+ if (closed)
9105
+ return;
9106
+ closed = true;
9107
+ db.close();
9108
+ }
9109
+ };
9110
+ }
9111
+ var DELIVERY_STATES, TERMINAL_DELIVERY_STATES, SCHEMA = `
9112
+ CREATE TABLE IF NOT EXISTS channel_events (
9113
+ event_id TEXT PRIMARY KEY,
9114
+ dedup_key TEXT NOT NULL UNIQUE,
9115
+ payload TEXT NOT NULL,
9116
+ ingress_seq INTEGER,
9117
+ committed_at INTEGER NOT NULL
9118
+ );
9119
+ CREATE TABLE IF NOT EXISTS channel_deliveries (
9120
+ delivery_id TEXT PRIMARY KEY,
9121
+ event_id TEXT NOT NULL,
9122
+ rule_id TEXT NOT NULL,
9123
+ rule_version INTEGER NOT NULL,
9124
+ target TEXT NOT NULL,
9125
+ idempotency_key TEXT NOT NULL UNIQUE,
9126
+ payload TEXT NOT NULL,
9127
+ state TEXT NOT NULL,
9128
+ attempt_count INTEGER NOT NULL DEFAULT 0,
9129
+ next_attempt_at INTEGER,
9130
+ last_error TEXT,
9131
+ provider_message TEXT,
9132
+ created_at INTEGER NOT NULL,
9133
+ updated_at INTEGER NOT NULL
9134
+ );
9135
+ CREATE TABLE IF NOT EXISTS channel_receipts (
9136
+ receipt_id TEXT PRIMARY KEY,
9137
+ delivery_id TEXT NOT NULL,
9138
+ attempt_id TEXT NOT NULL,
9139
+ state TEXT NOT NULL,
9140
+ provider_message TEXT,
9141
+ detail TEXT,
9142
+ observed_at INTEGER NOT NULL
9143
+ );
9144
+ CREATE TABLE IF NOT EXISTS channel_echoes (
9145
+ endpoint TEXT NOT NULL,
9146
+ native_message_id TEXT NOT NULL,
9147
+ logical_message_id TEXT NOT NULL,
9148
+ delivery_id TEXT,
9149
+ PRIMARY KEY (endpoint, native_message_id)
9150
+ );
9151
+ `;
9152
+ var init_state = __esm(() => {
9153
+ init_published();
9154
+ init_stats();
9155
+ DELIVERY_STATES = [
9156
+ "pending",
9157
+ "in_flight",
9158
+ "sent",
9159
+ "retryable",
9160
+ "rate_limited",
9161
+ "permanent",
9162
+ "unsupported",
9163
+ "unknown",
9164
+ "exhausted",
9165
+ "paused"
9166
+ ];
9167
+ TERMINAL_DELIVERY_STATES = [
9168
+ "sent",
9169
+ "permanent",
9170
+ "unsupported",
9171
+ "exhausted",
9172
+ "unknown"
9173
+ ];
9174
+ });
9175
+
9176
+ // packages/chat-room-channeld/src/delivery.ts
9177
+ function notifyDeliveryResult(state, deliveryId, handler, options) {
9178
+ if (options.notified.has(deliveryId))
9179
+ return;
9180
+ const delivery = state.getDelivery(deliveryId);
9181
+ if (!delivery || !isTerminalDeliveryState(delivery.state))
9182
+ return;
9183
+ const receipt = options.attemptId ? state.listReceipts(deliveryId).find((item) => item.attemptId === options.attemptId) : undefined;
9184
+ options.notified.add(deliveryId);
9185
+ try {
9186
+ state.recordPublishedResult(delivery, receipt);
9187
+ } catch (error) {
9188
+ log.warn(`could not record result.published: ${error instanceof Error ? error.message : String(error)}`, {
9189
+ delivery: deliveryId
9190
+ });
9191
+ }
9192
+ if (!handler)
9193
+ return;
9194
+ try {
9195
+ handler(state.getEvent(delivery.eventId), delivery, receipt);
9196
+ } catch (error) {
9197
+ log.warn(`onDeliveryResult failed: ${error instanceof Error ? error.message : String(error)}`, {
9198
+ delivery: deliveryId
9199
+ });
9200
+ }
9201
+ }
9202
+ function applyReceipt(state, row, attemptId, accountId, receipt, now) {
9203
+ const providerMessage = receipt.providerMessage ? JSON.stringify(receipt.providerMessage) : undefined;
9204
+ switch (receipt.state) {
9205
+ case "sent": {
9206
+ state.markDelivery(row.deliveryId, "sent", {
9207
+ providerMessage: providerMessage ?? null,
9208
+ lastError: null
9209
+ });
9210
+ const echo = receipt.providerMessage?.nativeMessageId && receipt.providerMessage.endpoint ? {
9211
+ endpoint: targetKey(receipt.providerMessage.endpoint),
9212
+ nativeMessageId: receipt.providerMessage.nativeMessageId,
9213
+ logicalMessageId: row.eventId
9214
+ } : undefined;
9215
+ state.recordSent({
9216
+ deliveryId: row.deliveryId,
9217
+ attemptId,
9218
+ providerMessage: providerMessage ?? null,
9219
+ detail: receipt.detail ?? null,
9220
+ echo
9221
+ });
9222
+ log.info("delivery sent", { account: accountId, delivery: row.deliveryId });
9223
+ break;
9224
+ }
9225
+ case "retryable":
9226
+ case "rate_limited": {
9227
+ if (attemptCount(row) >= MAX_ATTEMPTS) {
9228
+ state.markDelivery(row.deliveryId, "exhausted", {
9229
+ lastError: receipt.detail ?? "attempt limit reached"
9230
+ });
9231
+ state.recordReceipt({
9232
+ deliveryId: row.deliveryId,
9233
+ attemptId,
9234
+ state: "exhausted",
9235
+ detail: receipt.detail ?? "attempt limit reached"
9236
+ });
9237
+ log.error(`delivery exhausted after ${attemptCount(row)} attempts`, {
9238
+ account: accountId,
9239
+ delivery: row.deliveryId
9240
+ });
9241
+ break;
9242
+ }
9243
+ const delay = receipt.retryAfterMs ?? Math.min(2 ** attemptCount(row) * RETRY_BASE_MS, MAX_BACKOFF_MS);
9244
+ state.markDelivery(row.deliveryId, receipt.state, {
9245
+ nextAttemptAt: now + delay,
9246
+ lastError: receipt.detail ?? null
9247
+ });
9248
+ state.recordReceipt({
9249
+ deliveryId: row.deliveryId,
9250
+ attemptId,
9251
+ state: receipt.state,
9252
+ detail: receipt.detail ?? null
9253
+ });
9254
+ log.warn(`delivery ${receipt.state}; retry in ${delay}ms`, {
9255
+ account: accountId,
9256
+ delivery: row.deliveryId
9257
+ });
9258
+ break;
9259
+ }
9260
+ case "unknown": {
9261
+ state.markDelivery(row.deliveryId, "unknown", {
9262
+ lastError: receipt.detail ?? "unknown platform outcome"
9263
+ });
9264
+ state.recordReceipt({
9265
+ deliveryId: row.deliveryId,
9266
+ attemptId,
9267
+ state: "unknown",
9268
+ detail: receipt.detail ?? null
9269
+ });
9270
+ log.warn("delivery unknown; not retried", { account: accountId, delivery: row.deliveryId });
9271
+ break;
9272
+ }
9273
+ case "permanent":
9274
+ case "unsupported": {
9275
+ state.markDelivery(row.deliveryId, receipt.state, {
9276
+ lastError: receipt.detail ?? null
9277
+ });
9278
+ state.recordReceipt({
9279
+ deliveryId: row.deliveryId,
9280
+ attemptId,
9281
+ state: receipt.state,
9282
+ detail: receipt.detail ?? null
9283
+ });
9284
+ log.error(`delivery ${receipt.state}`, { account: accountId, delivery: row.deliveryId });
9285
+ break;
9286
+ }
9287
+ }
9288
+ }
9289
+ function attemptCount(row) {
9290
+ return row.attemptCount + 1;
9291
+ }
9292
+ var MAX_ATTEMPTS = 8, MAX_BACKOFF_MS = 30000, RETRY_BASE_MS = 500;
9293
+ var init_delivery = __esm(() => {
9294
+ init_log();
9295
+ init_rules();
9296
+ init_state();
9297
+ });
9298
+
9299
+ // packages/chat-room-channeld/src/host-helpers.ts
9300
+ function parseTarget2(value) {
9301
+ const parts = value.split("/");
9302
+ if (parts.length !== 3)
9303
+ return;
9304
+ const [platform, accountId, roomId] = parts;
9305
+ if (!platform || !accountId || !roomId)
9306
+ return;
9307
+ return { platform, accountId, roomId };
9308
+ }
9309
+ function startFailureReason(accountId, error) {
9310
+ const message = error instanceof Error ? error.message : String(error);
9311
+ const prefix = `adapter ${accountId} failed to start: `;
9312
+ return message.startsWith(prefix) ? message.slice(prefix.length) : message;
9313
+ }
9314
+ function validateTargets(config) {
9315
+ const accounts = new Map(config.accounts.map((account) => [account.id, account]));
9316
+ for (const rule of config.rules) {
9317
+ for (const target of rule.to) {
9318
+ const account = accounts.get(target.account);
9319
+ if (!account) {
9320
+ throw new Error(`config: rule "${rule.id}" targets unknown account "${target.account}"`);
9321
+ }
9322
+ if (account.platform !== target.platform) {
9323
+ throw new Error(`config: rule "${rule.id}" targets platform "${target.platform}" but account "${target.account}" is "${account.platform}"`);
9324
+ }
9325
+ }
9326
+ }
9327
+ }
9328
+ function toEndpoint(config, ruleId, target) {
9329
+ const account = config.accounts.find((item) => item.id === target.account);
9330
+ if (!account) {
9331
+ throw new Error(`config: rule "${ruleId}" targets unknown account "${target.account}"`);
9332
+ }
9333
+ return { platform: target.platform, accountId: account.id, roomId: target.room };
9334
+ }
9335
+
9336
+ // packages/chat-room-channeld/src/ingest-gate.ts
9337
+ class IngestGate {
9338
+ #onOverflow;
9339
+ #gates = new Map;
9340
+ constructor(onOverflow) {
9341
+ this.#onOverflow = onOverflow;
9342
+ }
9343
+ begin(accountId) {
9344
+ const gate = this.#gate(accountId);
9345
+ gate.sends += 1;
9346
+ }
9347
+ async finish(accountId, process2) {
9348
+ const gate = this.#gates.get(accountId);
9349
+ if (!gate)
9350
+ return;
9351
+ gate.sends = Math.max(0, gate.sends - 1);
9352
+ if (gate.sends > 0 || gate.draining)
9353
+ return;
9354
+ gate.draining = true;
9355
+ try {
9356
+ while (gate.queue.length > 0) {
9357
+ const item = gate.queue.shift();
9358
+ try {
9359
+ item.resolve(await process2(item.event));
9360
+ } catch (error) {
9361
+ item.reject(error instanceof Error ? error : new Error(String(error)));
9362
+ }
9363
+ }
9364
+ } finally {
9365
+ gate.draining = false;
9366
+ if (gate.sends === 0 && gate.queue.length === 0)
9367
+ this.#gates.delete(accountId);
9368
+ }
9369
+ }
9370
+ async run(accountId, event, process2) {
9371
+ const gate = this.#gates.get(accountId);
9372
+ if (!gate || !gate.draining && gate.sends === 0)
9373
+ return process2(event);
9374
+ if (gate.overflow)
9375
+ throw gate.overflow;
9376
+ if (gate.queue.length >= MAX_BUFFERED_INGESTS) {
9377
+ const error = new Error(`ingest buffer overflow for account ${accountId}; limit ${MAX_BUFFERED_INGESTS}; event ${event.eventId} dropped`);
9378
+ error.code = "ingest_buffer_overflow";
9379
+ gate.overflow = error;
9380
+ try {
9381
+ log.error(error.message, { account: accountId, event: event.eventId });
9382
+ } catch {}
9383
+ try {
9384
+ this.#onOverflow(accountId, event, error);
9385
+ } catch (callbackError) {
9386
+ try {
9387
+ log.error(`overflow handler failed: ${callbackError instanceof Error ? callbackError.message : String(callbackError)}`, { account: accountId });
9388
+ } catch {}
9389
+ }
9390
+ throw error;
9391
+ }
9392
+ return new Promise((resolve, reject) => {
9393
+ gate.queue.push({ event, resolve, reject });
9394
+ });
9395
+ }
9396
+ #gate(accountId) {
9397
+ const existing = this.#gates.get(accountId);
9398
+ if (existing)
9399
+ return existing;
9400
+ const gate = { sends: 0, draining: false, queue: [] };
9401
+ this.#gates.set(accountId, gate);
9402
+ return gate;
9403
+ }
9404
+ }
9405
+ var MAX_BUFFERED_INGESTS = 100;
9406
+ var init_ingest_gate = __esm(() => {
9407
+ init_log();
9408
+ });
9409
+
9410
+ // packages/chat-room-channeld/src/host.ts
9411
+ function defaultSpawnAdapter(account, context) {
9412
+ return new AdapterProcess({ account, ...context });
9413
+ }
9414
+
9415
+ class ChannelHost {
9416
+ #config;
9417
+ #stateFactory;
9418
+ #spawnAdapter;
9419
+ #now;
9420
+ #deliveryIntervalMs;
9421
+ #onDeliveryResult;
9422
+ #adapters = new Map;
9423
+ #timers = new Map;
9424
+ #inFlight = new Map;
9425
+ #notified = new Set;
9426
+ #active = new Set;
9427
+ #disabled = new Set;
9428
+ #gate = new IngestGate((accountId, _event, _error) => {
9429
+ this.#disableAccount(accountId, "ingest barrier limit reached");
9430
+ });
9431
+ #state;
9432
+ #running = false;
9433
+ #starting = false;
9434
+ #idleTimer;
9435
+ #rejectionHandler;
9436
+ constructor(config, deps = {}) {
9437
+ this.#config = config;
9438
+ this.#stateFactory = deps.stateFactory ?? openState;
9439
+ this.#spawnAdapter = deps.spawnAdapter ?? defaultSpawnAdapter;
9440
+ this.#now = deps.now ?? Date.now;
9441
+ this.#deliveryIntervalMs = deps.deliveryIntervalMs ?? 200;
9442
+ this.#onDeliveryResult = deps.onDeliveryResult;
9443
+ }
9444
+ get disabledAccounts() {
9445
+ return [...this.#disabled];
9446
+ }
9447
+ targetStatus(platform, accountId) {
9448
+ const account = this.#config.accounts.find((item) => item.id === accountId);
9449
+ if (!account || account.platform !== platform)
9450
+ return "missing";
9451
+ return this.#disabled.has(accountId) ? "disabled" : "ready";
9452
+ }
9453
+ async start() {
9454
+ if (this.#running)
9455
+ throw new Error("host is already running");
9456
+ validateTargets(this.#config);
9457
+ const state = this.#stateFactory(this.#config.stateFile);
9458
+ this.#state = state;
9459
+ this.#installRejectionGuard();
9460
+ const configuredKeys = this.#config.accounts.map((account) => `${account.platform}/${account.id}`);
9461
+ const abandoned = state.abandonUnconfiguredDeliveries(configuredKeys);
9462
+ if (abandoned.length > 0) {
9463
+ log.warn(`abandoned ${abandoned.length} deliveries for unconfigured accounts`);
9464
+ for (const row of abandoned) {
9465
+ notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { notified: this.#notified });
9466
+ }
9467
+ }
9468
+ const resumed = state.resumePausedDeliveries();
9469
+ if (resumed > 0)
9470
+ log.info(`resumed ${resumed} paused deliveries`);
9471
+ const recovered = state.recoverInFlightDeliveries();
9472
+ if (recovered > 0)
9473
+ log.warn(`recovered ${recovered} stale in-flight deliveries`);
9474
+ this.#running = true;
9475
+ this.#starting = true;
9476
+ const started = [];
9477
+ const failures = [];
9478
+ const tasks = this.#config.accounts.map(async (account) => {
9479
+ let adapter;
9480
+ try {
9481
+ adapter = this.#spawnAdapter(account, {
9482
+ onIngest: (event) => this.ingest(event),
9483
+ onExit: (code, signal) => this.#handleExit(account.id, code, signal),
9484
+ onUnavailable: (reason) => this.#disableAccount(account.id, reason)
9485
+ });
9486
+ this.#adapters.set(account.id, adapter);
9487
+ await adapter.start();
9488
+ this.#schedule(account.id);
9489
+ return { id: account.id };
9490
+ } catch (error) {
9491
+ const reason = startFailureReason(account.id, error);
9492
+ this.#disabled.add(account.id);
9493
+ log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
9494
+ if (adapter) {
9495
+ try {
9496
+ await adapter.stop();
9497
+ } catch {}
9498
+ }
9499
+ return { id: account.id, reason };
9500
+ }
9501
+ });
9502
+ const settled = await Promise.allSettled(tasks);
9503
+ this.#starting = false;
9504
+ settled.forEach((result, index) => {
9505
+ const account = this.#config.accounts[index];
9506
+ if (result.status === "fulfilled") {
9507
+ const { id, reason } = result.value;
9508
+ if (reason)
9509
+ failures.push({ id, reason });
9510
+ else
9511
+ started.push(id);
9512
+ } else {
9513
+ const reason = result.reason instanceof Error ? result.reason.message : String(result.reason);
9514
+ failures.push({ id: account.id, reason });
9515
+ this.#disabled.add(account.id);
9516
+ log.error(`adapter ${account.id} failed to start: ${reason}`, { account: account.id });
9517
+ }
9518
+ });
9519
+ for (const account of this.#config.accounts) {
9520
+ if (this.#disabled.has(account.id)) {
9521
+ state.pauseAccountDeliveries(`${account.platform}/${account.id}`, "account disabled until restart");
9522
+ }
9523
+ }
9524
+ const usable = started.filter((accountId) => !this.#disabled.has(accountId));
9525
+ if (usable.length === 0) {
9526
+ this.#running = false;
9527
+ this.#starting = false;
9528
+ this.#clearIdle();
9529
+ this.#removeRejectionGuard();
9530
+ for (const timer of this.#timers.values())
9531
+ clearTimeout(timer);
9532
+ this.#timers.clear();
9533
+ await this.#stopAdapters();
9534
+ state.close();
9535
+ this.#state = undefined;
9536
+ this.#disabled.clear();
9537
+ const detail = failures.map((failure) => `${failure.id}: ${failure.reason}`).join("; ");
9538
+ throw new Error(`no adapters started${detail ? `: ${detail}` : ""}`);
9539
+ }
9540
+ for (const failure of failures) {
9541
+ log.warn(`account ${failure.id} disabled until restart; queued deliveries paused`, {
9542
+ account: failure.id
9543
+ });
9544
+ }
9545
+ log.info(`host started: ${usable.length} accounts, ${failures.length} disabled, ${this.#config.rules.length} rules`);
9546
+ }
9547
+ async ingest(event) {
9548
+ return this.#gate.run(event.source.accountId, event, (item) => this.#processIngest(item));
9549
+ }
9550
+ async#processIngest(event) {
9551
+ const state = this.#state;
9552
+ if (!state)
9553
+ throw new Error("host is not running");
9554
+ if (event.message) {
9555
+ const endpoint = targetKey(event.message.endpoint);
9556
+ if (state.findEcho(endpoint, event.message.nativeMessageId)) {
9557
+ log.info("echo ingest skipped", { event: event.eventId });
9558
+ return { duplicate: false, eventId: event.eventId };
9559
+ }
9560
+ }
9561
+ const result = state.commitIngest(event);
9562
+ if (result.duplicate) {
9563
+ log.info("duplicate ingest skipped", { event: result.existingEventId });
9564
+ return { duplicate: true, eventId: result.existingEventId };
9565
+ }
9566
+ const stored = { ...event, ingressSeq: result.ingressSeq };
9567
+ log.info(`ingested ${stored.kind}`, { event: stored.eventId });
9568
+ if (stored.kind === "message.forward_requested") {
9569
+ const selected = stored.selectedMessage;
9570
+ const reason = !selected ? "selectedMessage is required" : !sameEndpoint(selected.endpoint, stored.source) ? "selectedMessage is outside the source room" : undefined;
9571
+ if (reason) {
9572
+ log.warn(`forward rejected: ${reason}`, { event: stored.eventId });
9573
+ return { duplicate: false, eventId: stored.eventId };
9574
+ }
9575
+ }
9576
+ const requestedTarget = stored.kind === "message.forward_requested" ? stored.requestedTarget : undefined;
9577
+ for (const rule of matchRules(this.#config, stored)) {
9578
+ const targets = [];
9579
+ const payloads = [];
9580
+ for (const target of rule.to) {
9581
+ const endpoint = toEndpoint(this.#config, rule.id, target);
9582
+ if (requestedTarget && !sameEndpoint(endpoint, requestedTarget))
9583
+ continue;
9584
+ const plan = planPayload(rule, stored, endpoint);
9585
+ if ("dropped" in plan) {
9586
+ log.warn(`rule ${rule.id}@${rule.version} dropped delivery to ${targetKey(endpoint)}: ${plan.dropped}`, { event: stored.eventId });
9587
+ continue;
9588
+ }
9589
+ targets.push(target);
9590
+ payloads.push(JSON.stringify(plan.payload));
9591
+ }
9592
+ if (targets.length === 0)
9593
+ continue;
9594
+ const created = state.enqueueDeliveries(stored.eventId, rule, targets, payloads);
9595
+ for (const delivery of created) {
9596
+ const endpoint = parseTarget2(delivery.target);
9597
+ if (endpoint && this.#disabled.has(endpoint.accountId)) {
9598
+ state.markDelivery(delivery.deliveryId, "paused", {
9599
+ lastError: "account disabled until restart"
9600
+ });
9601
+ }
9602
+ log.info(`delivery enqueued rule=${rule.id}@${rule.version}`, {
9603
+ delivery: delivery.deliveryId,
9604
+ event: stored.eventId
9605
+ });
9606
+ }
9607
+ }
9608
+ return { duplicate: false, eventId: stored.eventId };
9609
+ }
9610
+ async stop() {
9611
+ if (!this.#running && !this.#state) {
9612
+ this.#clearIdle();
9613
+ this.#removeRejectionGuard();
9614
+ return;
9615
+ }
9616
+ this.#running = false;
9617
+ this.#starting = false;
9618
+ this.#clearIdle();
9619
+ for (const timer of this.#timers.values())
9620
+ clearTimeout(timer);
9621
+ this.#timers.clear();
9622
+ await Promise.allSettled([...this.#active]);
9623
+ await this.#stopAdapters();
9624
+ this.#state?.close();
9625
+ this.#state = undefined;
9626
+ this.#adapters.clear();
9627
+ this.#inFlight.clear();
9628
+ this.#notified.clear();
9629
+ this.#disabled.clear();
9630
+ this.#removeRejectionGuard();
9631
+ log.info("host stopped");
9632
+ }
9633
+ #schedule(accountId) {
9634
+ if (!this.#running || this.#disabled.has(accountId))
9635
+ return;
9636
+ const timer = setTimeout(() => {
9637
+ this.#timers.delete(accountId);
9638
+ if (!this.#running)
9639
+ return;
9640
+ const task = this.#drainOnce(accountId).catch((error) => {
9641
+ log.error(`delivery loop failed: ${error instanceof Error ? error.message : String(error)}`, {
9642
+ account: accountId
9643
+ });
9644
+ }).finally(() => {
9645
+ this.#active.delete(task);
9646
+ this.#schedule(accountId);
9647
+ });
9648
+ this.#active.add(task);
9649
+ }, this.#deliveryIntervalMs);
9650
+ this.#timers.set(accountId, timer);
9651
+ }
9652
+ async#drainOnce(accountId) {
9653
+ if (!this.#running || this.#disabled.has(accountId))
9654
+ return;
9655
+ const state = this.#state;
9656
+ const adapter = this.#adapters.get(accountId);
9657
+ const account = this.#config.accounts.find((item) => item.id === accountId);
9658
+ if (!state || !adapter || !account)
9659
+ return;
9660
+ const accountKey = `${account.platform}/${account.id}`;
9661
+ const row = state.nextPendingDelivery(accountKey, this.#now());
9662
+ if (!row)
9663
+ return;
9664
+ await this.#deliver(state, adapter, accountId, row);
9665
+ }
9666
+ async#deliver(state, adapter, accountId, row) {
9667
+ const target = parseTarget2(row.target);
9668
+ if (!target) {
9669
+ state.markDelivery(row.deliveryId, "permanent", { lastError: `invalid target: ${row.target}` });
9670
+ state.recordReceipt({
9671
+ deliveryId: row.deliveryId,
9672
+ attemptId: "invalid-target",
9673
+ state: "permanent",
9674
+ detail: `invalid target: ${row.target}`
9675
+ });
9676
+ notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId: "invalid-target", notified: this.#notified });
9677
+ log.error(`invalid target ${row.target}`, { account: accountId, delivery: row.deliveryId });
9678
+ return;
9679
+ }
9680
+ const attempt = row.attemptCount + 1;
9681
+ const attemptId = `att-${row.deliveryId}-${attempt}`;
9682
+ state.markDelivery(row.deliveryId, "in_flight", { attemptCount: attempt });
9683
+ const inFlight = this.#inFlight.get(accountId) ?? new Set;
9684
+ this.#inFlight.set(accountId, inFlight);
9685
+ inFlight.add(row.deliveryId);
9686
+ this.#gate.begin(accountId);
9687
+ try {
9688
+ let receipt;
9689
+ try {
9690
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, JSON.parse(row.payload));
9691
+ } catch (error) {
9692
+ receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
9693
+ } finally {
9694
+ inFlight.delete(row.deliveryId);
9695
+ }
9696
+ applyReceipt(state, row, attemptId, accountId, receipt, this.#now());
9697
+ notifyDeliveryResult(state, row.deliveryId, this.#onDeliveryResult, { attemptId, notified: this.#notified });
9698
+ } finally {
9699
+ await this.#gate.finish(accountId, (event) => this.#processIngest(event));
9700
+ if (this.#disabled.has(accountId)) {
9701
+ this.#pauseAccountDeliveries(accountId, "account disabled until restart");
9702
+ }
9703
+ }
9704
+ }
9705
+ #pauseAccountDeliveries(accountId, reason) {
9706
+ const state = this.#state;
9707
+ const account = this.#config.accounts.find((item) => item.id === accountId);
9708
+ if (!state || !account)
9709
+ return;
9710
+ try {
9711
+ const paused = state.pauseAccountDeliveries(`${account.platform}/${account.id}`, reason);
9712
+ if (paused > 0) {
9713
+ log.info(`paused ${paused} deliveries for disabled account`, { account: accountId });
9714
+ }
9715
+ } catch (error) {
9716
+ this.#safeWarn(`could not pause deliveries: ${error instanceof Error ? error.message : String(error)}`, accountId);
9717
+ }
9718
+ }
9719
+ #disableAccount(accountId, reason) {
9720
+ if (this.#disabled.has(accountId))
9721
+ return;
9722
+ this.#disabled.add(accountId);
9723
+ const timer = this.#timers.get(accountId);
9724
+ if (timer) {
9725
+ clearTimeout(timer);
9726
+ this.#timers.delete(accountId);
9727
+ }
9728
+ const state = this.#state;
9729
+ const inFlight = this.#inFlight.get(accountId);
9730
+ if (state && inFlight && inFlight.size > 0) {
9731
+ for (const deliveryId of inFlight) {
9732
+ try {
9733
+ state.markDelivery(deliveryId, "unknown", { lastError: reason });
9734
+ notifyDeliveryResult(state, deliveryId, this.#onDeliveryResult, { notified: this.#notified });
9735
+ } catch (error) {
9736
+ this.#safeWarn(`could not mark delivery unknown: ${error instanceof Error ? error.message : String(error)}`, accountId, deliveryId);
9737
+ }
9738
+ }
9739
+ this.#inFlight.delete(accountId);
9740
+ this.#safeWarn(`marked ${inFlight.size} in-flight deliveries unknown`, accountId);
9741
+ }
9742
+ this.#pauseAccountDeliveries(accountId, reason);
9743
+ try {
9744
+ log.error(`account ${accountId} disabled: ${reason}`, { account: accountId });
9745
+ } catch {}
9746
+ try {
9747
+ const adapter = this.#adapters.get(accountId);
9748
+ if (adapter) {
9749
+ adapter.stop().catch((error) => {
9750
+ this.#safeWarn(`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`, accountId);
9751
+ });
9752
+ }
9753
+ } catch (error) {
9754
+ this.#safeWarn(`adapter stop failed: ${error instanceof Error ? error.message : String(error)}`, accountId);
9755
+ }
9756
+ this.#maybeIdle();
9757
+ }
9758
+ #handleExit(accountId, code, signal) {
9759
+ try {
9760
+ this.#disableAccount(accountId, `adapter exited (code=${code} signal=${signal})`);
9761
+ } catch (error) {
9762
+ this.#safeWarn(`disable after adapter exit failed: ${error instanceof Error ? error.message : String(error)}`, accountId);
9763
+ }
9764
+ }
9765
+ #safeWarn(message, accountId, deliveryId) {
9766
+ try {
9767
+ log.warn(message, { account: accountId, delivery: deliveryId });
9768
+ } catch {}
9769
+ }
9770
+ #maybeIdle() {
9771
+ try {
9772
+ if (!this.#running || this.#starting || this.#idleTimer)
9773
+ return;
9774
+ if (!this.#config.accounts.every((account) => this.#disabled.has(account.id)))
9775
+ return;
9776
+ log.warn("all accounts disabled; host idle until restart");
9777
+ this.#idleTimer = setInterval(() => {}, 60000);
9778
+ } catch {}
9779
+ }
9780
+ #clearIdle() {
9781
+ if (!this.#idleTimer)
9782
+ return;
9783
+ clearInterval(this.#idleTimer);
9784
+ this.#idleTimer = undefined;
9785
+ }
9786
+ #installRejectionGuard() {
9787
+ if (this.#rejectionHandler)
9788
+ return;
9789
+ this.#rejectionHandler = (reason) => {
9790
+ try {
9791
+ log.error(`unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}`);
9792
+ } catch {}
9793
+ };
9794
+ process.on("unhandledRejection", this.#rejectionHandler);
9795
+ }
9796
+ #removeRejectionGuard() {
9797
+ const handler = this.#rejectionHandler;
9798
+ if (!handler)
9799
+ return;
9800
+ this.#rejectionHandler = undefined;
9801
+ try {
9802
+ process.off("unhandledRejection", handler);
9803
+ } catch {}
9804
+ }
9805
+ async#stopAdapters() {
9806
+ await Promise.allSettled([...this.#adapters.values()].map((adapter) => adapter.stop()));
9807
+ this.#adapters.clear();
9808
+ }
9809
+ }
9810
+ function createHost(config, deps = {}) {
9811
+ return new ChannelHost(config, deps);
9812
+ }
9813
+ var init_host = __esm(() => {
9814
+ init_adapter();
9815
+ init_delivery();
9816
+ init_ingest_gate();
9817
+ init_log();
9818
+ init_rules();
9819
+ init_state();
9820
+ });
9821
+
9822
+ // server/channels.ts
9823
+ import { mkdirSync as mkdirSync3, readFileSync as readFileSync4 } from "node:fs";
9824
+ import { randomUUID as randomUUID15 } from "node:crypto";
9825
+ import path14 from "node:path";
9826
+ import { parse as parseYaml3 } from "yaml";
9827
+ function loadChannelConfig(file, stateFile) {
9828
+ let text;
9829
+ try {
9830
+ text = readFileSync4(file, "utf8");
9831
+ } catch {
9832
+ throw new Error(`channeld config: cannot read ${file}`);
9833
+ }
9834
+ let raw;
9835
+ try {
9836
+ raw = parseYaml3(text);
9837
+ } catch {
9838
+ throw new Error(`channeld config: ${file} is not valid YAML/JSON`);
9839
+ }
9840
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
9841
+ throw new Error(`channeld config: ${file} must contain a mapping`);
9842
+ }
9843
+ return parseConfig({ ...raw, stateFile });
9844
+ }
9845
+ function resolveChannelStateFile(stateDir, configured) {
9846
+ const file = configured ? path14.isAbsolute(configured) ? configured : path14.resolve(stateDir, configured) : path14.join(stateDir, "channeld.sqlite");
9847
+ if (path14.resolve(file) === path14.join(stateDir, "chat-room.sqlite")) {
9848
+ throw new Error("chatroom config: server.channeld.stateFile must not be the room database");
9849
+ }
9850
+ return file;
9851
+ }
9852
+ function deliverySystemMessage(delivery, receipt) {
9853
+ if (delivery.state === "sent")
9854
+ return `Forwarded to ${delivery.target}`;
9855
+ const raw = receipt?.detail || delivery.lastError || receipt?.state || delivery.state;
9856
+ const reason = String(raw).replace(/[\r\n;]+/g, " ").trim().slice(0, 500) || delivery.state;
9857
+ return `Forward to ${delivery.target} failed: ${reason}`;
9858
+ }
9859
+ function createDeliveryResultHandler() {
9860
+ const notified = new Set;
9861
+ return (event, delivery, receipt) => {
9862
+ if (!isTerminalDeliveryState(delivery.state))
9863
+ return;
9864
+ if (notified.has(delivery.deliveryId))
9865
+ return;
9866
+ const source = event?.source;
9867
+ if (event?.kind !== "message.forward_requested" || source?.platform !== "chatroom" || source.accountId !== "center")
9868
+ return;
9869
+ notified.add(delivery.deliveryId);
9870
+ const text = deliverySystemMessage(delivery, receipt);
9871
+ writeState((svc) => {
9872
+ svc.addEvent(source.roomId, text);
9873
+ }).catch((error) => {
9874
+ console.warn(`[chat-room] could not write the channeld result message: ${error instanceof Error ? error.message : String(error)}`);
9875
+ });
9876
+ };
9877
+ }
9878
+ async function startChannels(settings, deps = {}) {
9879
+ if (!settings.channeld?.enabled)
9880
+ return;
9881
+ const configPath = settings.channeld.config;
9882
+ if (!configPath) {
9883
+ throw new Error("chatroom config: server.channeld is enabled but no config file is set (server.channeld.config or CHAT_ROOM_CHANNELD_CONFIG)");
9884
+ }
9885
+ const stateDir = path14.dirname(databasePath());
9886
+ const stateFile = resolveChannelStateFile(stateDir, settings.channeld.stateFile);
9887
+ const config = loadChannelConfig(configPath, stateFile);
9888
+ mkdirSync3(stateDir, { recursive: true, mode: 448 });
9889
+ const host = createHost(config, {
9890
+ spawnAdapter: deps.spawnAdapter,
9891
+ deliveryIntervalMs: deps.deliveryIntervalMs,
9892
+ onDeliveryResult: createDeliveryResultHandler()
9893
+ });
9894
+ try {
9895
+ await host.start();
9896
+ } catch (error) {
9897
+ console.warn(`[chat-room] channeld disabled: ${error instanceof Error ? error.message : String(error)}`);
9898
+ await stopChannels({ host, config });
9899
+ return;
9900
+ }
9901
+ return { host, config };
9902
+ }
9903
+ async function stopChannels(runtime) {
9904
+ if (!runtime)
9905
+ return;
9906
+ try {
9907
+ await runtime.host.stop();
9908
+ } catch (error) {
9909
+ console.warn(`[chat-room] channeld stop failed: ${error instanceof Error ? error.message : String(error)}`);
9910
+ }
9911
+ }
9912
+ function parseTarget3(value) {
9913
+ if (!value || typeof value !== "object" || Array.isArray(value))
9914
+ return;
9915
+ const raw = value;
9916
+ if (typeof raw.platform !== "string" || !IDENTIFIER2.test(raw.platform) || typeof raw.account !== "string" || !IDENTIFIER2.test(raw.account) || typeof raw.room !== "string" || !IDENTIFIER2.test(raw.room))
9917
+ return;
9918
+ return { platform: raw.platform, account: raw.account, room: raw.room };
9919
+ }
9920
+ function decodeSegment(segment) {
9921
+ try {
9922
+ return decodeURIComponent(segment);
9923
+ } catch {
9924
+ return;
9925
+ }
9926
+ }
9927
+ async function memberName(roomId, sessionID) {
9928
+ const db = await openStateDatabase(databasePath());
9929
+ const row = db.query(`SELECT g.name FROM registry g
9930
+ JOIN rooms r ON r.id = g.room_id
9931
+ JOIN participants p ON p.room_id = g.room_id
9932
+ AND p.id = CASE WHEN r.kind = 'direct' THEN g.session_id ELSE g.name END
9933
+ WHERE g.room_id = ? AND g.session_id = ?`).get(roomId, sessionID);
9934
+ return row?.name;
9935
+ }
9936
+ async function readForwardableMessage(roomId, messageId, sessionID) {
9937
+ if (!await memberName(roomId, sessionID))
9938
+ return;
9939
+ const db = await openStateDatabase(databasePath());
9940
+ const row = db.query("SELECT text, created_at, recalled_at FROM messages WHERE room_id = ? AND id = ?").get(roomId, messageId);
9941
+ if (!row || row.recalled_at !== null)
9942
+ return;
9943
+ return { text: row.text, createdAt: Number(row.created_at) };
9944
+ }
9945
+ async function isRoomMember(roomId, sessionID) {
9946
+ return Boolean(await memberName(roomId, sessionID));
9947
+ }
9948
+ function forwardTargets(runtime, roomId) {
9949
+ const probe = {
9950
+ schemaVersion: EVENT_SCHEMA_VERSION,
9951
+ eventId: "forward-targets",
9952
+ kind: "message.forward_requested",
9953
+ source: { platform: "chatroom", accountId: "center", roomId },
9954
+ actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: "" },
9955
+ sourceDedupKey: "forward-targets",
9956
+ receivedAt: new Date(0).toISOString()
9957
+ };
9958
+ const config = runtime.config;
9959
+ const seen = new Set;
9960
+ const targets = [];
9961
+ for (const rule of matchRules(config, probe)) {
9962
+ for (const target of rule.to) {
9963
+ if (runtime.host.targetStatus(target.platform, target.account) !== "ready")
9964
+ continue;
9965
+ const key = `${target.platform}/${target.account}/${target.room}`;
9966
+ if (seen.has(key))
9967
+ continue;
9968
+ seen.add(key);
9969
+ targets.push(target);
9970
+ }
9971
+ }
9972
+ return targets;
9973
+ }
9974
+ async function channelRoutes(req, url, runtime) {
9975
+ if (!runtime)
9976
+ return;
9977
+ if (url.pathname === "/channeld/status") {
9978
+ if (req.method !== "GET")
9979
+ return json11({ error: "method not allowed" }, 405);
9980
+ try {
9981
+ return json11(readChannelStats(runtime.config.stateFile));
9982
+ } catch {
9983
+ return json11({ error: "channel state unavailable" }, 503);
9984
+ }
9985
+ }
9986
+ const forward = url.pathname.match(/^\/rooms\/([^/]+)\/forward$/);
9987
+ if (forward) {
9988
+ if (req.method !== "POST")
9989
+ return json11({ error: "method not allowed" }, 405);
9990
+ const roomId = decodeSegment(forward[1]);
9991
+ if (!roomId)
9992
+ return json11({ error: "message not found" }, 404);
9993
+ const body = await jsonObject(req);
9994
+ if (!body)
9995
+ return json11({ error: "JSON object body is required" }, 400);
9996
+ const sessionID = typeof body.sessionID === "string" ? body.sessionID.trim() : "";
9997
+ const messageId = typeof body.messageId === "string" ? body.messageId.trim() : "";
9998
+ if (!sessionID || sessionID.length > MAX_SESSION4 || !messageId || messageId.length > MAX_SESSION4) {
9999
+ return json11({ error: "sessionID and messageId are required" }, 400);
10000
+ }
10001
+ const target = parseTarget3(body.target);
10002
+ if (!target)
10003
+ return json11({ error: "target must contain platform, account, and room identifiers" }, 400);
10004
+ const requestId = body.requestId === undefined ? undefined : typeof body.requestId === "string" && body.requestId.trim() && body.requestId.trim().length <= MAX_REQUEST_ID ? body.requestId.trim() : null;
10005
+ if (requestId === null)
10006
+ return json11({ error: `requestId must be a non-empty string (max ${MAX_REQUEST_ID})` }, 400);
10007
+ const message = await readForwardableMessage(roomId, messageId, sessionID);
10008
+ if (!message)
10009
+ return json11({ error: "message not found" }, 404);
10010
+ if (runtime.host.targetStatus(target.platform, target.account) !== "ready") {
10011
+ return json11({ error: "forward target is unavailable" }, 409);
10012
+ }
10013
+ const source = { platform: "chatroom", accountId: "center", roomId };
10014
+ const requestedTarget = { platform: target.platform, accountId: target.account, roomId: target.room };
10015
+ const event = {
10016
+ schemaVersion: EVENT_SCHEMA_VERSION,
10017
+ eventId: `fwd-${randomUUID15()}`,
10018
+ kind: "message.forward_requested",
10019
+ source,
10020
+ actor: { platform: "chatroom", identityNamespace: "session", nativeUserId: sessionID },
10021
+ ...requestId ? { providerEventId: requestId } : {},
10022
+ sourceDedupKey: `forward:${messageId}:${targetKey(requestedTarget)}`,
10023
+ selectedMessage: { endpoint: source, nativeMessageId: messageId, text: message.text },
10024
+ requestedTarget,
10025
+ occurredAt: new Date(message.createdAt).toISOString(),
10026
+ receivedAt: new Date().toISOString(),
10027
+ content: { text: message.text }
10028
+ };
10029
+ const result = await runtime.host.ingest(event);
10030
+ return json11({ eventId: result.eventId ?? event.eventId }, 202);
10031
+ }
10032
+ const targets = url.pathname.match(/^\/rooms\/([^/]+)\/forward-targets$/);
10033
+ if (!targets)
10034
+ return;
10035
+ if (req.method !== "GET")
10036
+ return json11({ error: "method not allowed" }, 405);
10037
+ const roomId = decodeSegment(targets[1]);
10038
+ if (!roomId)
10039
+ return json11({ error: "room not found" }, 404);
10040
+ const sessionID = (url.searchParams.get("sessionID") ?? "").trim();
10041
+ if (!sessionID || sessionID.length > MAX_SESSION4)
10042
+ return json11({ error: "sessionID is required" }, 400);
10043
+ if (!await isRoomMember(roomId, sessionID))
10044
+ return json11({ error: "room not found" }, 404);
10045
+ return json11({ targets: forwardTargets(runtime, roomId) });
10046
+ }
10047
+ var json11 = (body, status = 200) => Response.json(body, { status }), IDENTIFIER2, MAX_SESSION4 = 128, MAX_REQUEST_ID = 200;
10048
+ var init_channels = __esm(() => {
10049
+ init_store();
10050
+ init_sqlite_state();
10051
+ init_config();
10052
+ init_host();
10053
+ init_rules();
10054
+ init_state();
10055
+ IDENTIFIER2 = /^[A-Za-z0-9._-]{1,128}$/;
10056
+ });
10057
+
10058
+ // server/chat-server.ts
10059
+ import { existsSync as existsSync4, promises as fs5 } from "node:fs";
10060
+ import path15 from "node:path";
10061
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
10062
+ import { randomUUID as randomUUID16 } from "node:crypto";
10063
+ function parsePort(value) {
10064
+ const port = Number(value);
10065
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
10066
+ throw new Error(`Invalid server port "${value}": expected an integer from 1 to 65535`);
10067
+ }
10068
+ return port;
10069
+ }
10070
+ function mutate2(fn) {
10071
+ return writeState(fn);
10072
+ }
10073
+ function read(fn) {
10074
+ return readState2(fn);
10075
+ }
10076
+ async function handle(req) {
10077
+ const url = new URL(req.url);
10078
+ const p = url.pathname;
10079
+ if (req.method === "GET" && p === "/") {
10080
+ return Response.redirect(new URL("/chat", url).toString(), 302);
10081
+ }
10082
+ if (req.method === "GET" && p === "/chat") {
10083
+ const html = await fs5.readFile(path15.join(here, "chat.html"), "utf8").catch(() => null);
10084
+ if (html === null) {
10085
+ return json12({ error: "chat page not found" }, 404);
10086
+ }
10087
+ const version = await chatVersionTag();
10088
+ return new Response(html.replaceAll("{{version}}", version).replaceAll("{{channeld}}", channels ? "on" : "off"), {
10089
+ headers: {
10090
+ "Content-Type": "text/html; charset=utf-8",
10091
+ "Cache-Control": "no-store"
10092
+ }
10093
+ });
10094
+ }
10095
+ if (req.method === "GET" && p === "/manifest.webmanifest") {
10096
+ const body = await fs5.readFile(path15.join(here, "manifest.webmanifest"), "utf8").catch(() => null);
10097
+ if (body === null)
10098
+ return json12({ error: "manifest not found" }, 404);
10099
+ return new Response(body, {
10100
+ headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-store" }
10101
+ });
10102
+ }
10103
+ if (req.method === "GET" && p === "/sw.js") {
10104
+ const body = await fs5.readFile(path15.join(here, "sw.js"), "utf8").catch(() => null);
10105
+ if (body === null)
10106
+ return json12({ error: "service worker not found" }, 404);
10107
+ const version = await chatVersionTag() || "dev";
10108
+ return new Response(body.replaceAll("{{version}}", version), {
10109
+ headers: {
10110
+ "Content-Type": "text/javascript; charset=utf-8",
10111
+ "Cache-Control": "no-store",
10112
+ "Service-Worker-Allowed": "/"
10113
+ }
10114
+ });
10115
+ }
10116
+ if (req.method === "GET" && p.startsWith("/assets/")) {
10117
+ let relative;
10118
+ try {
10119
+ relative = decodeURIComponent(p.slice("/assets/".length));
10120
+ } catch {
10121
+ return json12({ error: "invalid asset path" }, 400);
10122
+ }
10123
+ const root = path15.resolve(here, "assets");
10124
+ const file = path15.resolve(root, relative);
10125
+ if (!relative || !file.startsWith(`${root}${path15.sep}`) || !/\.(?:css|js|mjs|svg|png|jpg|woff2?)$/i.test(file))
10126
+ return json12({ error: "not found" }, 404);
10127
+ const data = await fs5.readFile(file).catch(() => null);
10128
+ if (!data)
10129
+ return json12({ error: "not found" }, 404);
10130
+ const type = file.endsWith(".css") ? "text/css" : file.endsWith(".svg") ? "image/svg+xml" : /\.(?:js|mjs)$/.test(file) ? "text/javascript" : file.endsWith(".png") ? "image/png" : file.endsWith(".jpg") ? "image/jpeg" : "font/woff2";
10131
+ return new Response(data, { headers: { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff" } });
10132
+ }
10133
+ if (["POST", "PUT", "PATCH", "DELETE"].includes(req.method) && !req.headers.get("content-type")?.includes("application/json") && !(/^\/rooms\/[^/]+\/resources$/.test(p) && req.method === "POST")) {
10134
+ return json12({ error: "content-type must be application/json" }, 415);
10135
+ }
10136
+ if (token && req.headers.get("authorization") !== `Bearer ${token}`) {
10137
+ return json12({ error: "unauthorized" }, 401);
10138
+ }
10139
+ try {
10140
+ const reminders = await roomReminderRoutes(req, url);
10141
+ if (reminders)
10142
+ return reminders;
10143
+ const admin = await adminRoutes(req, url);
10144
+ if (admin)
10145
+ return admin;
10146
+ const resource = await resourceRoutes(req, url);
10147
+ if (resource)
10148
+ return resource;
10149
+ const history = await historyRoute(url);
10150
+ if (history)
10151
+ return history;
10152
+ const addressing = await addressingRoutes(req, url);
10153
+ if (addressing)
10154
+ return addressing;
10155
+ const recall = await messageRecallRoutes(req, url);
10156
+ if (recall)
10157
+ return recall;
10158
+ const channel = await channelRoutes(req, url, channels);
10159
+ if (channel)
10160
+ return channel;
10161
+ if (req.method === "GET" && p === "/rooms/summary") {
10162
+ const rooms = await read((svc) => svc.listRooms().map((r) => ({
10163
+ id: r.id,
10164
+ name: r.name,
10165
+ latestMsgTs: r.messages.at(-1)?.createdAt ?? 0
10166
+ })));
10167
+ return json12(rooms);
10168
+ }
10169
+ if (req.method === "GET" && p === "/receiver/memberships") {
10170
+ const ownerID = url.searchParams.get("ownerID");
10171
+ if (!isReceiverOwnerID(ownerID))
10172
+ return json12({ error: "invalid ownerID" }, 400);
10173
+ const sessionIDs = await readState2((_svc, registry) => {
10174
+ return [...new Set(Object.values(registry).flatMap((entries) => Object.entries(entries).filter(([, entry]) => entry.protocol === "v2" && entry.receiverOwnerID === ownerID).map(([id]) => id)))];
10175
+ });
10176
+ return json12({ sessionIDs });
10177
+ }
10178
+ if (req.method === "GET" && p === "/rooms") {
10179
+ const caller = url.searchParams.get("sessionID");
10180
+ const rows = await readState2((svc, registry) => svc.listRooms().filter((room) => room.kind !== "direct" ? true : !!caller && room.directSessionIDs?.includes(caller)).map((room) => ({ room, entry: caller ? registry[room.id]?.[caller] : undefined })));
10181
+ const rooms = [];
10182
+ for (const { room, entry } of rows) {
10183
+ rooms.push({ ...await roomPayload(room), joined: Boolean(entry), ...entry?.lastReadTs ? { lastReadTs: entry.lastReadTs } : {} });
10184
+ }
10185
+ return json12(rooms);
10186
+ }
10187
+ const members = await memberRoutes(req, url);
7876
10188
  if (members)
7877
10189
  return members;
7878
10190
  const joinRequests = await joinRequestRoutes(req, url);
@@ -7884,23 +10196,23 @@ async function handle(req) {
7884
10196
  if (req.method === "POST" && p === "/rooms") {
7885
10197
  const body = await jsonObject(req);
7886
10198
  if (!body)
7887
- return json10({ error: "JSON object body is required" }, 400);
10199
+ return json12({ error: "JSON object body is required" }, 400);
7888
10200
  if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
7889
- return json10({ error: "invalid receiver ownership" }, 400);
10201
+ return json12({ error: "invalid receiver ownership" }, 400);
7890
10202
  }
7891
10203
  const name = body.name?.trim();
7892
10204
  if (!name) {
7893
- return json10({ error: "name is required" }, 400);
10205
+ return json12({ error: "name is required" }, 400);
7894
10206
  }
7895
10207
  if (name.length > 64) {
7896
- return json10({ error: "name too long (max 64)" }, 400);
10208
+ return json12({ error: "name too long (max 64)" }, 400);
7897
10209
  }
7898
10210
  const owner = (body.ownerId ?? "").trim() || "访客";
7899
10211
  if (owner.length > 64) {
7900
- return json10({ error: "ownerId too long (max 64)" }, 400);
10212
+ return json12({ error: "ownerId too long (max 64)" }, 400);
7901
10213
  }
7902
10214
  if (body.joinPolicy !== undefined && body.joinPolicy !== "open" && body.joinPolicy !== "approval") {
7903
- return json10({ error: "joinPolicy must be open or approval" }, 400);
10215
+ return json12({ error: "joinPolicy must be open or approval" }, 400);
7904
10216
  }
7905
10217
  const joinPolicy = body.joinPolicy === "approval" ? "approval" : body.joinPolicy === "open" ? "open" : undefined;
7906
10218
  const room = await mutate2((svc, reg) => {
@@ -7910,7 +10222,7 @@ async function handle(req) {
7910
10222
  regRoom[body.sessionID] = {
7911
10223
  serverUrl: "",
7912
10224
  apiPrefix: "/api",
7913
- membershipID: randomUUID14(),
10225
+ membershipID: randomUUID16(),
7914
10226
  ...body.protocol === "v2" ? { protocol: "v2" } : {},
7915
10227
  ...body.protocol === "v2" && isReceiverOwnerID(body.receiverOwnerID) ? { receiverOwnerID: body.receiverOwnerID } : {},
7916
10228
  name: owner,
@@ -7923,7 +10235,7 @@ async function handle(req) {
7923
10235
  }
7924
10236
  return created;
7925
10237
  });
7926
- return json10(await roomPayload(room), 201);
10238
+ return json12(await roomPayload(room), 201);
7927
10239
  }
7928
10240
  if (req.method === "GET" && p === "/inbox") {
7929
10241
  const sessionID = url.searchParams.get("sessionID") ?? "";
@@ -7932,11 +10244,11 @@ async function handle(req) {
7932
10244
  const afterTs = afterValue === null ? undefined : Number(afterValue);
7933
10245
  const recallVersionValue = url.searchParams.get("recallVersion");
7934
10246
  if (url.searchParams.has("recallVersion") && (recallVersionValue === "" || !/^\d+$/.test(recallVersionValue ?? "") || !Number.isSafeInteger(Number(recallVersionValue)))) {
7935
- return json10({ error: "recallVersion must be a non-negative safe integer" }, 400);
10247
+ return json12({ error: "recallVersion must be a non-negative safe integer" }, 400);
7936
10248
  }
7937
10249
  const clientRecallVersion = recallVersionValue === null ? undefined : Number(recallVersionValue);
7938
10250
  if (url.searchParams.has("afterTs") && (afterValue === "" || !/^\d+$/.test(afterValue ?? "") || !Number.isSafeInteger(afterTs) || afterTs < 0 || !roomFilter || url.searchParams.get("excludeSelf") !== "0")) {
7939
- return json10({ error: "afterTs requires a roomId and excludeSelf=0, with a non-negative safe integer value" }, 400);
10251
+ return json12({ error: "afterTs requires a roomId and excludeSelf=0, with a non-negative safe integer value" }, 400);
7940
10252
  }
7941
10253
  const excludeSelf = url.searchParams.get("excludeSelf") === "1";
7942
10254
  const timeout = Math.min(Math.max(Number(url.searchParams.get("timeout") ?? 0) || 0, 0), 30000);
@@ -7947,59 +10259,59 @@ async function handle(req) {
7947
10259
  await sleep(Math.max(1, Math.min(500, deadline - Date.now())));
7948
10260
  result = await readInbox(sessionID, roomFilter, excludeSelf, afterTs);
7949
10261
  }
7950
- return json10(result);
10262
+ return json12(result);
7951
10263
  }
7952
10264
  if (req.method === "POST" && p === "/queued") {
7953
10265
  const body = await jsonObject(req);
7954
10266
  if (!body)
7955
- return json10({ error: "JSON object body is required" }, 400);
10267
+ return json12({ error: "JSON object body is required" }, 400);
7956
10268
  const ts = Number(body.ts);
7957
10269
  const roomId = String(body.roomId ?? "");
7958
10270
  const sessionID = String(body.sessionID ?? "");
7959
10271
  if (body.ts === undefined || body.ts === null || !roomId || !sessionID || !Number.isFinite(ts)) {
7960
- return json10({ error: "roomId/sessionID/finite ts are required" }, 400);
10272
+ return json12({ error: "roomId/sessionID/finite ts are required" }, 400);
7961
10273
  }
7962
10274
  const updated = await acknowledgeQueued2(roomId, sessionID, ts);
7963
10275
  if (updated === null) {
7964
- return json10({ error: "registry entry not found" }, 404);
10276
+ return json12({ error: "registry entry not found" }, 404);
7965
10277
  }
7966
10278
  clearPendingAdmission(sessionID, roomId, updated);
7967
10279
  touchActive(sessionID);
7968
- return json10({ ok: true });
10280
+ return json12({ ok: true });
7969
10281
  }
7970
10282
  if (req.method === "POST" && p === "/active") {
7971
10283
  const body = await jsonObject(req);
7972
10284
  if (!body)
7973
- return json10({ error: "JSON object body is required" }, 400);
10285
+ return json12({ error: "JSON object body is required" }, 400);
7974
10286
  touchActive(String(body.sessionID ?? ""));
7975
- return json10({ ok: true });
10287
+ return json12({ ok: true });
7976
10288
  }
7977
10289
  if (req.method === "POST" && p === "/wake-claim") {
7978
10290
  const body = await jsonObject(req);
7979
10291
  if (!body)
7980
- return json10({ error: "JSON object body is required" }, 400);
10292
+ return json12({ error: "JSON object body is required" }, 400);
7981
10293
  const sessionID = String(body.sessionID ?? "");
7982
10294
  const ok = claimWake(sessionID);
7983
- return json10({ ok });
10295
+ return json12({ ok });
7984
10296
  }
7985
10297
  const m = p.match(/^\/rooms\/([^/]+)\/(join|leave|messages)$/);
7986
10298
  if (m) {
7987
10299
  const roomId = decodeURIComponent(m[1]);
7988
10300
  const body = await jsonObject(req);
7989
10301
  if (!body)
7990
- return json10({ error: "JSON object body is required" }, 400);
10302
+ return json12({ error: "JSON object body is required" }, 400);
7991
10303
  const sessionID = typeof body.sessionID === "string" ? body.sessionID : "";
7992
10304
  if (req.method === "POST" && m[2] === "join") {
7993
10305
  if (body.protocol !== undefined && body.protocol !== "v2" || body.receiverOwnerID !== undefined && !isReceiverOwnerID(body.receiverOwnerID)) {
7994
- return json10({ error: "invalid receiver ownership" }, 400);
10306
+ return json12({ error: "invalid receiver ownership" }, 400);
7995
10307
  }
7996
10308
  const id = typeof body.participantId === "string" ? body.participantId.trim() : "";
7997
10309
  const name = typeof body.participantName === "string" ? body.participantName.trim() : "";
7998
10310
  if (!id || !name || !sessionID) {
7999
- return json10({ error: "participantId/participantName/sessionID are required" }, 400);
10311
+ return json12({ error: "participantId/participantName/sessionID are required" }, 400);
8000
10312
  }
8001
10313
  if (id.length > 64 || name.length > 64) {
8002
- return json10({ error: "name too long (max 64)" }, 400);
10314
+ return json12({ error: "name too long (max 64)" }, 400);
8003
10315
  }
8004
10316
  const result = await writeSqliteStateWithDatabase(databasePath(), (svc, reg, db) => {
8005
10317
  const currentRoom = svc.getRoom(roomId);
@@ -8034,14 +10346,14 @@ async function handle(req) {
8034
10346
  }) };
8035
10347
  });
8036
10348
  if ("status" in result)
8037
- return json10({ error: result.error }, result.status);
10349
+ return json12({ error: result.error }, result.status);
8038
10350
  if ("pending" in result)
8039
- return json10({
10351
+ return json12({
8040
10352
  status: "pending",
8041
10353
  message: "Join request submitted. You are not a member yet; a human administrator must approve it before you can send or poll."
8042
10354
  }, 202);
8043
10355
  touchActive(sessionID);
8044
- return json10(await roomPayload(result.room), 201);
10356
+ return json12(await roomPayload(result.room), 201);
8045
10357
  }
8046
10358
  if (req.method === "POST" && m[2] === "leave") {
8047
10359
  await mutate2((svc, reg) => {
@@ -8074,48 +10386,56 @@ async function handle(req) {
8074
10386
  settleAdmins(svc.getRoom(roomId), reg[roomId] ?? {});
8075
10387
  settleOwner(svc.getRoom(roomId), reg[roomId] ?? {});
8076
10388
  });
8077
- return json10({ ok: true });
10389
+ return json12({ ok: true });
8078
10390
  }
8079
10391
  if (req.method === "POST" && m[2] === "messages") {
8080
10392
  const isQuestion = body.isQuestion;
8081
10393
  if (isQuestion !== undefined && typeof isQuestion !== "boolean")
8082
- return json10({ error: "isQuestion must be a boolean" }, 400);
10394
+ return json12({ error: "isQuestion must be a boolean" }, 400);
8083
10395
  const text = typeof body.text === "string" ? body.text.trim() : "";
8084
10396
  if (!text) {
8085
- return json10({ error: "text is required" }, 400);
10397
+ return json12({ error: "text is required" }, 400);
8086
10398
  }
8087
10399
  if (text.length > 5000) {
8088
- return json10({ error: "text too long (max 5000)" }, 400);
10400
+ return json12({ error: "text too long (max 5000)" }, 400);
8089
10401
  }
8090
- const replyTo = body.replyToMessageID;
10402
+ const replyTo = body.replyToMessageID ?? body.parentMessageId;
8091
10403
  if (replyTo !== undefined && (typeof replyTo !== "string" || !replyTo))
8092
- return json10({ error: "replyToMessageID must be a non-empty message ID" }, 400);
10404
+ return json12({ error: "parentMessageId must be a non-empty message ID" }, 400);
10405
+ const clientMessageID = body.clientMessageID;
10406
+ if (clientMessageID !== undefined && (typeof clientMessageID !== "string" || !clientMessageID || clientMessageID.length > 100)) {
10407
+ return json12({ error: "clientMessageID must be a non-empty string (max 100)" }, 400);
10408
+ }
8093
10409
  if (replyTo !== undefined) {
8094
- const result = await sendReply2(roomId, replyTo, sessionID, text);
10410
+ const result = await sendReply2(roomId, replyTo, sessionID, text, clientMessageID);
8095
10411
  if (result.status !== "ok") {
8096
10412
  if (result.status === "missing")
8097
- return json10({ error: "room not found" }, 404);
10413
+ return json12({ error: "room not found" }, 404);
8098
10414
  if (result.status === "target")
8099
- return json10({ error: "reply target not found in room" }, 404);
10415
+ return json12({ error: "reply target not found in room" }, 404);
10416
+ if (result.status === "recalled")
10417
+ return json12({ error: "reply target was recalled" }, 409);
8100
10418
  if (result.status === "question")
8101
- return json10({ error: "use the question answers endpoint to reply to a question" }, 409);
8102
- return json10({ error: "session is not a room member" }, 409);
10419
+ return json12({ error: "use the question answers endpoint to reply to a question" }, 409);
10420
+ return json12({ error: "not found" }, 404);
8103
10421
  }
8104
10422
  touchActive(sessionID);
8105
10423
  const room = await read((svc) => svc.getRoom(roomId));
8106
- wakeMentionedSessions(serveWakeUrl2, roomId, room.name, text, sessionID, result.message);
8107
- return json10(await roomPayload(room), 201);
10424
+ if (!result.duplicate)
10425
+ wakeMentionedSessions(serveWakeUrl2, roomId, room.name, text, sessionID, result.message);
10426
+ return json12(await roomPayload(room), 201);
8108
10427
  }
8109
- const result = await appendRoomMessage2(roomId, sessionID, text, isQuestion === true);
10428
+ const result = await appendRoomMessage2(roomId, sessionID, text, isQuestion === true, clientMessageID);
8110
10429
  if (result.status !== "ok") {
8111
10430
  if (result.status === "missing")
8112
- return json10({ error: "room not found" }, 404);
8113
- return json10({ error: "session is not a room member" }, 409);
10431
+ return json12({ error: "room not found" }, 404);
10432
+ return json12({ error: "session is not a room member" }, 409);
8114
10433
  }
8115
10434
  touchActive(sessionID);
8116
10435
  const room = await read((svc) => svc.getRoom(roomId));
8117
- wakeMentionedSessions(serveWakeUrl2, roomId, room.name, text, sessionID, result.message);
8118
- return json10(await roomPayload(room), 201);
10436
+ if (!result.duplicate)
10437
+ wakeMentionedSessions(serveWakeUrl2, roomId, room.name, text, sessionID, result.message);
10438
+ return json12(await roomPayload(room), 201);
8119
10439
  }
8120
10440
  }
8121
10441
  const questions = p.match(/^\/rooms\/([^/]+)\/questions$/);
@@ -8123,8 +10443,8 @@ async function handle(req) {
8123
10443
  const roomId = decodeURIComponent(questions[1]);
8124
10444
  const exists = await read((svc) => svc.listRooms().some((room) => room.id === roomId));
8125
10445
  if (!exists)
8126
- return json10({ error: "room not found" }, 404);
8127
- return json10({ questions: await readQuestions2(roomId) });
10446
+ return json12({ error: "room not found" }, 404);
10447
+ return json12({ questions: await readQuestions2(roomId) });
8128
10448
  }
8129
10449
  const answer = p.match(/^\/rooms\/([^/]+)\/questions\/([^/]+)\/answers$/);
8130
10450
  if (req.method === "POST" && answer) {
@@ -8132,30 +10452,30 @@ async function handle(req) {
8132
10452
  const questionID = decodeURIComponent(answer[2]);
8133
10453
  const body = await req.json();
8134
10454
  if (!body || typeof body !== "object" || Array.isArray(body))
8135
- return json10({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
10455
+ return json12({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
8136
10456
  const input = body;
8137
10457
  if (typeof input.sessionID !== "string" || !input.sessionID || typeof input.text !== "string" || !input.text.trim() || input.text.trim().length > 5000)
8138
- return json10({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
10458
+ return json12({ error: "sessionID and non-empty text (max 5000) are required" }, 400);
8139
10459
  const result = await answerQuestion2(roomId, questionID, input.sessionID, input.text.trim());
8140
10460
  if (result.status === "missing")
8141
- return json10({ error: "room not found" }, 404);
10461
+ return json12({ error: "room not found" }, 404);
8142
10462
  if (result.status === "question")
8143
- return json10({ error: "question not found" }, 404);
10463
+ return json12({ error: "question not found" }, 404);
8144
10464
  if (result.status === "member")
8145
- return json10({ error: "session is not a room member" }, 409);
10465
+ return json12({ error: "session is not a room member" }, 409);
8146
10466
  if (result.status === "answered")
8147
- return json10({ error: "question already answered" }, 409);
10467
+ return json12({ error: "question already answered" }, 409);
8148
10468
  if (result.status !== "ok")
8149
- return json10({ error: "question not found" }, 404);
10469
+ return json12({ error: "question not found" }, 404);
8150
10470
  touchActive(input.sessionID);
8151
10471
  const room = await read((svc) => svc.getRoom(roomId));
8152
10472
  wakeMentionedSessions(serveWakeUrl2, roomId, room.name, result.answer.text, input.sessionID, result.answer);
8153
- return json10({ questionID, answer: result.answer }, 201);
10473
+ return json12({ questionID, answer: result.answer }, 201);
8154
10474
  }
8155
10475
  const g = p.match(/^\/rooms\/([^/]+)$/);
8156
10476
  if (g && req.method === "GET") {
8157
10477
  const room = await read((svc) => svc.getRoom(decodeURIComponent(g[1])));
8158
- return json10(await roomPayload(room));
10478
+ return json12(await roomPayload(room));
8159
10479
  }
8160
10480
  const r = p.match(/^\/rooms\/([^/]+)\/registry$/);
8161
10481
  if (r && req.method === "GET") {
@@ -8177,22 +10497,22 @@ async function handle(req) {
8177
10497
  }
8178
10498
  ]));
8179
10499
  });
8180
- return json10(reg);
10500
+ return json12(reg);
8181
10501
  }
8182
- return json10({ error: "not found" }, 404);
10502
+ return json12({ error: "not found" }, 404);
8183
10503
  } catch (err) {
8184
10504
  if (err instanceof SyntaxError)
8185
- return json10({ error: "invalid JSON body" }, 400);
10505
+ return json12({ error: "invalid JSON body" }, 400);
8186
10506
  if (err instanceof RoomError) {
8187
- return json10({ error: err.message }, err.code === "ROOM_NOT_FOUND" ? 404 : err.code === "NOT_OWNER" ? 403 : 409);
10507
+ return json12({ error: err.message }, err.code === "ROOM_NOT_FOUND" ? 404 : err.code === "NOT_OWNER" ? 403 : 409);
8188
10508
  }
8189
- return json10({ error: err instanceof Error ? err.message : String(err) }, 500);
10509
+ return json12({ error: err instanceof Error ? err.message : String(err) }, 500);
8190
10510
  }
8191
10511
  }
8192
- var moduleDir, here, versionTag, chatVersionTag = () => versionTag ??= fs5.readFile(path14.join(here, "../package.json"), "utf8").then((text) => {
10512
+ var moduleDir, here, versionTag, chatVersionTag = () => versionTag ??= fs5.readFile(path15.join(here, "../package.json"), "utf8").then((text) => {
8193
10513
  const pkg = JSON.parse(text);
8194
10514
  return typeof pkg?.version === "string" && pkg.version ? `v${pkg.version}` : "";
8195
- }).catch(() => ""), settings, hostname, displayHostname, port, token, serveWakeUrl2, json10 = (body, status = 200) => new Response(JSON.stringify(body), {
10515
+ }).catch(() => ""), settings, hostname, displayHostname, port, token, channels, serveWakeUrl2, json12 = (body, status = 200) => new Response(JSON.stringify(body), {
8196
10516
  status,
8197
10517
  headers: { "Content-Type": "application/json" }
8198
10518
  }), sleep = (ms) => new Promise((r) => setTimeout(r, ms)), config, chat_server_default;
@@ -8205,6 +10525,7 @@ var init_chat_server = __esm(async () => {
8205
10525
  init_receiver_owner();
8206
10526
  init_wake();
8207
10527
  init_history_route();
10528
+ init_addressing_routes();
8208
10529
  init_message_recall_routes();
8209
10530
  init_room_payload();
8210
10531
  init_room_owner();
@@ -8215,11 +10536,12 @@ var init_chat_server = __esm(async () => {
8215
10536
  init_join_requests();
8216
10537
  init_room_join();
8217
10538
  init_room_reminders();
10539
+ init_channels();
8218
10540
  init_file_config();
8219
10541
  init_http_server();
8220
10542
  await init_admin_routes();
8221
- moduleDir = path14.dirname(fileURLToPath4(import.meta.url));
8222
- here = existsSync2(path14.join(moduleDir, "chat.html")) ? moduleDir : path14.resolve(moduleDir, "../server");
10543
+ moduleDir = path15.dirname(fileURLToPath4(import.meta.url));
10544
+ here = existsSync4(path15.join(moduleDir, "chat.html")) ? moduleDir : path15.resolve(moduleDir, "../server");
8223
10545
  settings = resolveServerSettings(loadRoomConfig());
8224
10546
  hostname = settings.host;
8225
10547
  displayHostname = hostname.includes(":") ? `[${hostname}]` : hostname;
@@ -8239,6 +10561,15 @@ var init_chat_server = __esm(async () => {
8239
10561
  maxRequestBodySize: Math.max(128 * 1024 * 1024, maxResourceBytes())
8240
10562
  };
8241
10563
  chat_server_default = config;
10564
+ channels = await startChannels(settings);
10565
+ if (channels) {
10566
+ let stopping;
10567
+ const stop = () => {
10568
+ stopping ??= stopChannels(channels).finally(() => process.exit(0));
10569
+ };
10570
+ process.once("SIGINT", stop);
10571
+ process.once("SIGTERM", stop);
10572
+ }
8242
10573
  if (false)
8243
10574
  ;
8244
10575
  console.log(`chat-room center listening on http://${displayHostname}:${port}${token ? " (token auth on)" : ""}`);
@@ -8250,7 +10581,7 @@ var init_chat_server = __esm(async () => {
8250
10581
 
8251
10582
  // cli.ts
8252
10583
  import { spawnSync } from "node:child_process";
8253
- import { existsSync as existsSync3 } from "node:fs";
10584
+ import { existsSync as existsSync5 } from "node:fs";
8254
10585
  import { readFile as readFile3 } from "node:fs/promises";
8255
10586
  import { fileURLToPath as fileURLToPath5 } from "node:url";
8256
10587
  var usage = `Usage: opencode-chat-room [options]
@@ -8307,7 +10638,7 @@ if (args[0] === "cli") {
8307
10638
  relaunchTuiWithBun();
8308
10639
  const packaged = new URL("../src/tui/main.mjs", import.meta.url);
8309
10640
  const source = new URL("./src/tui/main.mjs", import.meta.url);
8310
- const entry = existsSync3(fileURLToPath5(packaged)) ? packaged : source;
10641
+ const entry = existsSync5(fileURLToPath5(packaged)) ? packaged : source;
8311
10642
  const { main } = await import(entry.href);
8312
10643
  process.exit(await main(args.slice(1)));
8313
10644
  }