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

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 (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +1008 -274
  5. package/package.json +10 -7
  6. package/packages/chat-room-channeld/README.md +42 -15
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +150 -7
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +41 -11
  11. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  12. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  13. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  14. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  15. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  16. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  17. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  18. package/packages/chat-room-channeld/src/protocol.ts +53 -1
  19. package/packages/chat-room-channeld/src/rules.ts +7 -2
  20. package/packages/chat-room-channeld/src/state.ts +73 -97
  21. package/packages/chat-room-channeld/src/stats.ts +140 -109
  22. package/plugin.ts +1 -1
  23. package/server/assets/base.css +11 -3
  24. package/server/assets/chat/admin-badge.js +32 -30
  25. package/server/assets/chat/admin.js +198 -163
  26. package/server/assets/chat/announcements.js +295 -210
  27. package/server/assets/chat/attachment-store.js +106 -75
  28. package/server/assets/chat/attachments.js +686 -441
  29. package/server/assets/chat/chat-background.js +206 -0
  30. package/server/assets/chat/clipboard.js +44 -25
  31. package/server/assets/chat/confirm-dialog.js +36 -34
  32. package/server/assets/chat/copy-action.js +40 -40
  33. package/server/assets/chat/create-room-dialog.js +50 -48
  34. package/server/assets/chat/diagram-viewer.js +293 -228
  35. package/server/assets/chat/doc-preview.js +510 -388
  36. package/server/assets/chat/editor.js +423 -335
  37. package/server/assets/chat/events.js +637 -502
  38. package/server/assets/chat/files.js +476 -426
  39. package/server/assets/chat/history-loader.js +79 -73
  40. package/server/assets/chat/icons.js +9 -11
  41. package/server/assets/chat/image-zoom.js +239 -169
  42. package/server/assets/chat/index.js +6 -5
  43. package/server/assets/chat/install-prompt.js +86 -66
  44. package/server/assets/chat/integration-account-schema.js +101 -0
  45. package/server/assets/chat/integration-editor.js +162 -153
  46. package/server/assets/chat/integration-values.js +109 -100
  47. package/server/assets/chat/integrations.js +696 -479
  48. package/server/assets/chat/join-requests.js +408 -358
  49. package/server/assets/chat/locales/de.js +193 -194
  50. package/server/assets/chat/locales/es.js +193 -194
  51. package/server/assets/chat/locales/fr.js +193 -194
  52. package/server/assets/chat/locales/index.js +1 -2
  53. package/server/assets/chat/locales/it.js +193 -194
  54. package/server/assets/chat/locales/ja.js +193 -193
  55. package/server/assets/chat/locales/ko.js +193 -193
  56. package/server/assets/chat/markdown-footnotes.js +134 -102
  57. package/server/assets/chat/markdown.js +553 -386
  58. package/server/assets/chat/members.js +236 -197
  59. package/server/assets/chat/mentions.js +157 -133
  60. package/server/assets/chat/message-cache.js +40 -33
  61. package/server/assets/chat/message-polling.js +280 -227
  62. package/server/assets/chat/message-window.js +74 -55
  63. package/server/assets/chat/messages.js +552 -479
  64. package/server/assets/chat/office-preview.js +46 -45
  65. package/server/assets/chat/palette.js +450 -412
  66. package/server/assets/chat/panels.js +94 -58
  67. package/server/assets/chat/pwa.js +144 -73
  68. package/server/assets/chat/questions.js +372 -302
  69. package/server/assets/chat/recall.js +320 -273
  70. package/server/assets/chat/receipts.js +149 -122
  71. package/server/assets/chat/reminders.js +331 -216
  72. package/server/assets/chat/replies.js +165 -136
  73. package/server/assets/chat/resource-format.js +59 -62
  74. package/server/assets/chat/room-list.js +58 -55
  75. package/server/assets/chat/room-watcher.js +72 -50
  76. package/server/assets/chat/rooms.js +623 -505
  77. package/server/assets/chat/search.js +136 -114
  78. package/server/assets/chat/settings.js +229 -140
  79. package/server/assets/chat/shiki.js +61 -62
  80. package/server/assets/chat/shortcuts.js +212 -190
  81. package/server/assets/chat/side-pane.js +166 -131
  82. package/server/assets/chat/state.js +851 -707
  83. package/server/assets/chat/system-events.js +55 -27
  84. package/server/assets/chat/system-messages.js +59 -49
  85. package/server/assets/chat/task-form.js +178 -182
  86. package/server/assets/chat/task-row.js +158 -155
  87. package/server/assets/chat/tasks.js +653 -593
  88. package/server/assets/chat/viewport.js +32 -29
  89. package/server/assets/chat/window-controls.js +37 -0
  90. package/server/assets/code-highlight.css +22 -6
  91. package/server/assets/conversation.css +65 -16
  92. package/server/assets/doc-preview.css +6 -1
  93. package/server/assets/files.css +3 -0
  94. package/server/assets/monaco/integration-rules.css +1 -1
  95. package/server/assets/monaco/integration-rules.js +841 -533
  96. package/server/assets/responsive.css +32 -2
  97. package/server/assets/settings.css +117 -13
  98. package/server/assets/window-controls.css +36 -0
  99. package/server/channel-attachments.ts +133 -0
  100. package/server/channel-integration.ts +79 -26
  101. package/server/channels.ts +15 -5
  102. package/server/chat-server.ts +9 -1
  103. package/server/chat.html +73 -38
  104. package/server/manifest.webmanifest +1 -0
  105. package/server/routes/pages.ts +7 -5
  106. package/server/sw.js +346 -267
  107. package/src/center/center-client.ts +1 -1
  108. package/src/state/pg-database.ts +5 -5
  109. package/src/state/pg-migrate.ts +7 -7
  110. package/src/state/pg-worker.mjs +2 -17
  111. package/src/state/sqlite-database.ts +14 -5
  112. package/src/state/sqlite-rooms.ts +130 -23
  113. package/src/state/sqlite-state-store.ts +6 -5
  114. package/src/state/sqlite.ts +3 -3
  115. package/src/web/integration-rules-editor.ts +141 -5
  116. package/src/web/integration-rules.ts +6 -2
  117. package/src/web/integration-schema.ts +7 -6
  118. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  119. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  120. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  121. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  122. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  123. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  124. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  125. package/server/assets/chat/forward.js +0 -69
package/dist/cli.js CHANGED
@@ -129,7 +129,7 @@ function isBusyError(error) {
129
129
  const err = error;
130
130
  if (!err)
131
131
  return false;
132
- if (err.code === "40001" || err.code === "40P01")
132
+ if (err.code === "40001" || err.code === "40P01" || err.code === "55P03")
133
133
  return true;
134
134
  if (typeof err.errcode === "number" && ((err.errcode & 255) === 5 || (err.errcode & 255) === 6))
135
135
  return true;
@@ -960,44 +960,174 @@ import { randomUUID as randomUUID5 } from "node:crypto";
960
960
  function roomColumns(room) {
961
961
  return room.adminIds?.length ? JSON.stringify([...new Set(room.adminIds)]) : null;
962
962
  }
963
+ function roomValues(room) {
964
+ return [
965
+ room.name,
966
+ room.ownerId,
967
+ room.createdAt,
968
+ room.kind ?? "group",
969
+ room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null,
970
+ room.directPair ?? null,
971
+ room.description ?? null,
972
+ roomColumns(room),
973
+ adminBindings(room),
974
+ room.ownerMembershipID ?? null,
975
+ room.successorId ?? null,
976
+ room.successorMembershipID ?? null,
977
+ room.joinPolicy ?? null
978
+ ];
979
+ }
980
+ function messageValues(message) {
981
+ return [
982
+ message.id,
983
+ message.roomId,
984
+ message.senderId,
985
+ message.senderSessionID ?? null,
986
+ message.text,
987
+ message.createdAt,
988
+ message.isQuestion ? 1 : 0,
989
+ message.answerToMessageID ?? null,
990
+ message.answeredByMessageID ?? null,
991
+ message.recalledAt ?? null,
992
+ message.recalledBy ?? null
993
+ ];
994
+ }
995
+ function mutableMessageValues(message) {
996
+ return [
997
+ message.isQuestion ? 1 : 0,
998
+ message.answerToMessageID ?? null,
999
+ message.answeredByMessageID ?? null,
1000
+ message.recalledAt ?? null,
1001
+ message.recalledBy ?? null
1002
+ ];
1003
+ }
1004
+ function registryValues(entry) {
1005
+ return [
1006
+ entry.serverUrl,
1007
+ entry.apiPrefix,
1008
+ entry.protocol ?? null,
1009
+ entry.name,
1010
+ entry.lastReadTs ?? null,
1011
+ entry.lastQueuedTs ?? null,
1012
+ entry.directory ?? null,
1013
+ entry.host ?? null,
1014
+ entry.receiverOwnerID ?? null,
1015
+ entry.membershipID ?? null,
1016
+ entry.workState ?? null,
1017
+ entry.lastSeenAt ?? null
1018
+ ];
1019
+ }
963
1020
  function insertRoom(db, room) {
964
- db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description,admin_names,admin_membership_ids,owner_membership_id,successor_name,successor_membership_id,join_policy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)").run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null, room.description ?? null, roomColumns(room), adminBindings(room), ...roomBindings(room), room.joinPolicy ?? null);
1021
+ db.query(ROOM_INSERT).run(room.id, ...roomValues(room));
965
1022
  const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
966
1023
  for (const p of room.participants.values())
967
1024
  participant.run(room.id, p.id, p.name, p.joinedAt);
968
- const message = db.query("INSERT INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
1025
+ const message = db.query(MESSAGE_INSERT);
969
1026
  for (const m of room.messages)
970
- message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt, m.isQuestion ? 1 : 0, m.answerToMessageID ?? null, m.answeredByMessageID ?? null, m.recalledAt ?? null, m.recalledBy ?? null);
1027
+ message.run(...messageValues(m));
971
1028
  }
972
1029
  function replaceRegistry(db, registry) {
973
1030
  db.exec("DELETE FROM registry");
974
- const insert = db.query("INSERT INTO registry(room_id,session_id,server_url,api_prefix,protocol,name,last_read_ts,last_queued_ts,directory,host,receiver_owner_id,membership_id,work_state,last_seen_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
1031
+ const insert = db.query(REGISTRY_INSERT);
975
1032
  for (const [roomID, members] of Object.entries(registry))
976
1033
  for (const [sessionID, r] of Object.entries(members)) {
977
1034
  r.membershipID ||= randomUUID5();
978
- insert.run(roomID, sessionID, r.serverUrl, r.apiPrefix, r.protocol ?? null, r.name, r.lastReadTs ?? null, r.lastQueuedTs ?? null, r.directory ?? null, r.host ?? null, r.receiverOwnerID ?? null, r.membershipID, r.workState ?? null, r.lastSeenAt ?? null);
1035
+ insert.run(roomID, sessionID, ...registryValues(r));
979
1036
  }
980
1037
  }
981
- function persistState(db, rooms, registry) {
982
- const roomRow = db.query("INSERT INTO rooms(id,name,owner_id,created_at,kind,direct_sessions,direct_pair,description,admin_names,admin_membership_ids,owner_membership_id,successor_name,successor_membership_id,join_policy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,owner_id=excluded.owner_id,created_at=excluded.created_at,kind=excluded.kind,direct_sessions=excluded.direct_sessions,direct_pair=excluded.direct_pair,description=excluded.description,admin_names=excluded.admin_names,admin_membership_ids=excluded.admin_membership_ids,owner_membership_id=excluded.owner_membership_id,successor_name=excluded.successor_name,successor_membership_id=excluded.successor_membership_id,join_policy=excluded.join_policy");
983
- const participant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
984
- const message = db.query("INSERT OR IGNORE INTO messages(id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by) VALUES(?,?,?,?,?,?,?,?,?,?,?)");
985
- const removeParticipants = db.query("DELETE FROM participants WHERE room_id=?");
986
- const keep = new Set(rooms.map((room) => room.id));
987
- const existing = db.query("SELECT id FROM rooms").all();
1038
+ function persistStateDiff(db, before, after) {
1039
+ const beforeRooms = new Map(before.rooms.map((room) => [room.id, room]));
1040
+ const afterRooms = new Map(after.rooms.map((room) => [room.id, room]));
988
1041
  const deleteRoom = db.query("DELETE FROM rooms WHERE id=?");
989
- for (const row of existing)
990
- if (!keep.has(row.id))
991
- deleteRoom.run(row.id);
992
- for (const room of rooms) {
993
- roomRow.run(room.id, room.name, room.ownerId, room.createdAt, room.kind ?? "group", room.directSessionIDs ? JSON.stringify(room.directSessionIDs) : null, room.directPair ?? null, room.description ?? null, roomColumns(room), adminBindings(room), ...roomBindings(room), room.joinPolicy ?? null);
994
- removeParticipants.run(room.id);
995
- for (const p of room.participants.values())
996
- participant.run(room.id, p.id, p.name, p.joinedAt);
997
- for (const m of room.messages)
998
- message.run(m.id, room.id, m.senderId, m.senderSessionID ?? null, m.text, m.createdAt, m.isQuestion ? 1 : 0, m.answerToMessageID ?? null, m.answeredByMessageID ?? null, m.recalledAt ?? null, m.recalledBy ?? null);
999
- }
1000
- replaceRegistry(db, registry);
1042
+ for (const room of before.rooms)
1043
+ if (!afterRooms.has(room.id))
1044
+ deleteRoom.run(room.id);
1045
+ const insertRoomRow = db.query(ROOM_INSERT);
1046
+ const insertParticipant = db.query("INSERT INTO participants VALUES(?,?,?,?)");
1047
+ const updateParticipant = db.query("UPDATE participants SET name=?,joined_at=? WHERE room_id=? AND id=?");
1048
+ const deleteParticipant = db.query("DELETE FROM participants WHERE room_id=? AND id=?");
1049
+ const message = db.query(MESSAGE_UPSERT);
1050
+ for (const room of after.rooms) {
1051
+ const previous = beforeRooms.get(room.id);
1052
+ if (!previous) {
1053
+ insertRoomRow.run(room.id, ...roomValues(room));
1054
+ for (const p of room.participants.values())
1055
+ insertParticipant.run(room.id, p.id, p.name, p.joinedAt);
1056
+ for (const m of room.messages)
1057
+ message.run(...messageValues(m));
1058
+ continue;
1059
+ }
1060
+ updateChanged(db, "rooms", ROOM_FIELDS, roomValues(previous), roomValues(room), "id=?", [room.id]);
1061
+ for (const [id, participant] of room.participants) {
1062
+ const prior = previous.participants.get(id);
1063
+ if (!prior)
1064
+ insertParticipant.run(room.id, id, participant.name, participant.joinedAt);
1065
+ else if (prior.name !== participant.name || prior.joinedAt !== participant.joinedAt) {
1066
+ updateParticipant.run(participant.name, participant.joinedAt, room.id, id);
1067
+ }
1068
+ }
1069
+ for (const id of previous.participants.keys())
1070
+ if (!room.participants.has(id))
1071
+ deleteParticipant.run(room.id, id);
1072
+ const previousMessages = new Map(previous.messages.map((item) => [item.id, item]));
1073
+ for (const item of room.messages) {
1074
+ const prior = previousMessages.get(item.id);
1075
+ if (!prior)
1076
+ message.run(...messageValues(item));
1077
+ else
1078
+ updateChanged(db, "messages", MESSAGE_MUTABLE_FIELDS, mutableMessageValues(prior), mutableMessageValues(item), "id=?", [item.id]);
1079
+ }
1080
+ }
1081
+ for (const members of Object.values(after.registry))
1082
+ for (const entry of Object.values(members))
1083
+ entry.membershipID ||= randomUUID5();
1084
+ const insertRegistry = db.query(REGISTRY_INSERT);
1085
+ for (const [roomID, members] of Object.entries(after.registry)) {
1086
+ for (const [sessionID, entry] of Object.entries(members)) {
1087
+ const previous = before.registry[roomID]?.[sessionID];
1088
+ if (!previous)
1089
+ insertRegistry.run(roomID, sessionID, ...registryValues(entry));
1090
+ else
1091
+ updateChanged(db, "registry", REGISTRY_FIELDS, registryValues(previous), registryValues(entry), "room_id=? AND session_id=?", [roomID, sessionID]);
1092
+ }
1093
+ }
1094
+ const deleteRegistry = db.query("DELETE FROM registry WHERE room_id=? AND session_id=?");
1095
+ for (const [roomID, members] of Object.entries(before.registry)) {
1096
+ for (const sessionID of Object.keys(members)) {
1097
+ if (!after.registry[roomID]?.[sessionID])
1098
+ deleteRegistry.run(roomID, sessionID);
1099
+ }
1100
+ }
1101
+ }
1102
+ function updateChanged(db, table, fields, before, after, where, key) {
1103
+ const changed = [];
1104
+ for (let index = 0;index < fields.length; index++) {
1105
+ if (before[index] === after[index])
1106
+ continue;
1107
+ changed.push({ field: fields[index], value: after[index] });
1108
+ }
1109
+ if (!changed.length)
1110
+ return;
1111
+ db.query(`UPDATE ${table} SET ${changed.map(({ field }) => `${field}=?`).join(",")} WHERE ${where}`).run(...changed.map(({ value }) => value), ...key);
1112
+ }
1113
+ function cloneRoom(room) {
1114
+ return {
1115
+ ...room,
1116
+ ...room.adminIds ? { adminIds: [...room.adminIds] } : {},
1117
+ ...room.adminMembershipIDs ? { adminMembershipIDs: [...room.adminMembershipIDs] } : {},
1118
+ ...room.directSessionIDs ? { directSessionIDs: [...room.directSessionIDs] } : {},
1119
+ participants: new Map([...room.participants].map(([id, p]) => [id, { ...p }])),
1120
+ messages: room.messages.map((message) => ({ ...message }))
1121
+ };
1122
+ }
1123
+ function cloneState(state) {
1124
+ const registry = Object.create(null);
1125
+ for (const [roomID, members] of Object.entries(state.registry)) {
1126
+ registry[roomID] = Object.create(null);
1127
+ for (const [sessionID, entry] of Object.entries(members))
1128
+ registry[roomID][sessionID] = { ...entry };
1129
+ }
1130
+ return { rooms: state.rooms.map(cloneRoom), registry };
1001
1131
  }
1002
1132
  function readRoomSummaries(db) {
1003
1133
  const rows = db.query("SELECT r.id,r.name,COALESCE(MAX(m.created_at),0) AS latestMsgTs FROM rooms r LEFT JOIN messages m ON m.room_id=r.id GROUP BY r.id,r.name,r.created_at ORDER BY r.created_at,r.id").all();
@@ -1060,8 +1190,17 @@ function readState(db) {
1060
1190
  };
1061
1191
  return { rooms, registry };
1062
1192
  }
1063
- var adminBindings = (room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null, roomBindings = (room) => [room.ownerMembershipID ?? null, room.successorId ?? null, room.successorMembershipID ?? null];
1064
- var init_sqlite_rooms = () => {};
1193
+ var ROOM_COLUMNS = "name,owner_id,created_at,kind,direct_sessions,direct_pair,description,admin_names,admin_membership_ids,owner_membership_id,successor_name,successor_membership_id,join_policy", ROOM_FIELDS, ROOM_INSERT, MESSAGE_COLUMNS = "id,room_id,sender_id,sender_session_id,text,created_at,is_question,answer_to,answered_by,recalled_at,recalled_by", MESSAGE_FIELDS, MESSAGE_INSERT, MESSAGE_UPSERT, MESSAGE_MUTABLE_FIELDS, REGISTRY_COLUMNS = "server_url,api_prefix,protocol,name,last_read_ts,last_queued_ts,directory,host,receiver_owner_id,membership_id,work_state,last_seen_at", REGISTRY_FIELDS, REGISTRY_INSERT, adminBindings = (room) => room.adminMembershipIDs?.length ? JSON.stringify([...new Set(room.adminMembershipIDs)]) : null;
1194
+ var init_sqlite_rooms = __esm(() => {
1195
+ ROOM_FIELDS = ROOM_COLUMNS.split(",");
1196
+ ROOM_INSERT = `INSERT INTO rooms(id,${ROOM_COLUMNS}) VALUES(?,${ROOM_FIELDS.map(() => "?").join(",")})`;
1197
+ MESSAGE_FIELDS = MESSAGE_COLUMNS.split(",");
1198
+ MESSAGE_INSERT = `INSERT INTO messages(${MESSAGE_COLUMNS}) VALUES(${MESSAGE_FIELDS.map(() => "?").join(",")})`;
1199
+ MESSAGE_UPSERT = `${MESSAGE_INSERT} ON CONFLICT(id) DO UPDATE SET is_question=excluded.is_question,answer_to=excluded.answer_to,answered_by=excluded.answered_by,recalled_at=excluded.recalled_at,recalled_by=excluded.recalled_by`;
1200
+ MESSAGE_MUTABLE_FIELDS = ["is_question", "answer_to", "answered_by", "recalled_at", "recalled_by"];
1201
+ REGISTRY_FIELDS = REGISTRY_COLUMNS.split(",");
1202
+ REGISTRY_INSERT = `INSERT INTO registry(room_id,session_id,${REGISTRY_COLUMNS}) VALUES(?,?,${REGISTRY_FIELDS.map(() => "?").join(",")})`;
1203
+ });
1065
1204
 
1066
1205
  // src/state/sqlite-legacy.ts
1067
1206
  import { readFileSync } from "node:fs";
@@ -1241,7 +1380,12 @@ async function initializeReminderSchema(file) {
1241
1380
  async function initializePostgres(connectionString) {
1242
1381
  const db = new PgDatabase(connectionString);
1243
1382
  try {
1244
- await initializeSchema(db);
1383
+ db.exec("SELECT pg_advisory_lock(hashtext('chat-room-schema'))");
1384
+ try {
1385
+ await initializeSchema(db);
1386
+ } finally {
1387
+ db.exec("SELECT pg_advisory_unlock(hashtext('chat-room-schema'))");
1388
+ }
1245
1389
  return db;
1246
1390
  } catch (error) {
1247
1391
  db.close();
@@ -1431,13 +1575,14 @@ async function writeSqliteState(file, callback) {
1431
1575
  async function writeSqliteStateWithDatabase(file, callback) {
1432
1576
  const db = await openStateDatabase(file);
1433
1577
  return immediate2(db, () => {
1434
- const state = readState(db);
1578
+ const before = readState(db);
1579
+ const working = cloneState(before);
1435
1580
  const service = new RoomService;
1436
- service.hydrate(state.rooms);
1437
- const result = callback(service, state.registry, db);
1581
+ service.hydrate(working.rooms);
1582
+ const result = callback(service, working.registry, db);
1438
1583
  if (result && typeof result.then === "function")
1439
1584
  throw new Error("writeState callback must be synchronous");
1440
- persistState(db, service.listRooms(), state.registry);
1585
+ persistStateDiff(db, before, { rooms: service.listRooms(), registry: working.registry });
1441
1586
  return result;
1442
1587
  });
1443
1588
  }
@@ -3044,7 +3189,7 @@ ${result.announcement.content}`;
3044
3189
  const parsed = toRoom(room);
3045
3190
  const sentID = [...parsed.messages].reverse().find((message) => message.senderSessionID === sessionID && message.text === args.text.trim())?.id ?? parsed.messages.at(-1)?.id;
3046
3191
  return `sent: ${args.text.trim()}
3047
- ${sentID ? `message id: ${sentID}
3192
+ ${sentID ? `message_id=${sentID} room_id=${parsed.id}
3048
3193
  ` : ""}${formatRoom(svcOf(room), parsed)}`;
3049
3194
  }
3050
3195
  case "recall": {
@@ -5593,7 +5738,7 @@ var connection, centerUrl, centerToken, serveWakeUrl, runtimeContext, defaultRun
5593
5738
  const room = svc.getRoom(args.roomId);
5594
5739
  notifications.push({ roomId: args.roomId, roomName: room.name, messages: [...room.messages] });
5595
5740
  return `sent: ${args.text}
5596
- message id: ${msg.id}
5741
+ message_id=${msg.id} room_id=${room.id}
5597
5742
  ${formatRoom(svc, room)}`;
5598
5743
  }
5599
5744
  case "poll": {
@@ -6398,9 +6543,9 @@ import { existsSync as existsSync5 } from "node:fs";
6398
6543
  function backupGuidance(sourcePath) {
6399
6544
  const stamp = new Date().toISOString().replace(/[:.]/g, "-");
6400
6545
  return [
6401
- "PostgreSQL state is experimental and single-instance in 0.8.1.",
6546
+ "PostgreSQL state is experimental (0.8.2 multi-instance milestone).",
6402
6547
  "Stop the chat-room server before migrating; this command takes a SQLite write lock,",
6403
- "but only --yes confirms that the server is actually stopped.",
6548
+ "but nothing blocks a running PostgreSQL writer. Only --yes confirms the server is stopped.",
6404
6549
  "",
6405
6550
  "Make a WAL-safe SQLite backup first (do not copy only chat-room.sqlite while WAL is active):",
6406
6551
  ` sqlite3 ${JSON.stringify(sourcePath)} ".backup '${sourcePath}.backup-${stamp}'"`,
@@ -8885,10 +9030,11 @@ function chatVersionTag(here) {
8885
9030
  }
8886
9031
  async function pageRoutes(req, url, here, channeld) {
8887
9032
  const p = url.pathname;
8888
- if (req.method === "GET" && p === "/") {
9033
+ const read = req.method === "GET" || req.method === "HEAD";
9034
+ if (read && p === "/") {
8889
9035
  return Response.redirect(new URL("/chat", url).toString(), 302);
8890
9036
  }
8891
- if (req.method === "GET" && p === "/chat") {
9037
+ if (read && p === "/chat") {
8892
9038
  const html = await fs6.readFile(path16.join(here, "chat.html"), "utf8").catch(() => null);
8893
9039
  if (html === null) {
8894
9040
  return json12({ error: "chat page not found" }, 404);
@@ -8901,7 +9047,7 @@ async function pageRoutes(req, url, here, channeld) {
8901
9047
  }
8902
9048
  });
8903
9049
  }
8904
- if (req.method === "GET" && p === "/manifest.webmanifest") {
9050
+ if (read && p === "/manifest.webmanifest") {
8905
9051
  const body = await fs6.readFile(path16.join(here, "manifest.webmanifest"), "utf8").catch(() => null);
8906
9052
  if (body === null)
8907
9053
  return json12({ error: "manifest not found" }, 404);
@@ -8909,7 +9055,7 @@ async function pageRoutes(req, url, here, channeld) {
8909
9055
  headers: { "Content-Type": "application/manifest+json; charset=utf-8", "Cache-Control": "no-store" }
8910
9056
  });
8911
9057
  }
8912
- if (req.method === "GET" && p === "/sw.js") {
9058
+ if (read && p === "/sw.js") {
8913
9059
  const body = await fs6.readFile(path16.join(here, "sw.js"), "utf8").catch(() => null);
8914
9060
  if (body === null)
8915
9061
  return json12({ error: "service worker not found" }, 404);
@@ -8922,7 +9068,7 @@ async function pageRoutes(req, url, here, channeld) {
8922
9068
  }
8923
9069
  });
8924
9070
  }
8925
- if (req.method === "GET" && p.startsWith("/assets/")) {
9071
+ if (read && p.startsWith("/assets/")) {
8926
9072
  let relative;
8927
9073
  try {
8928
9074
  relative = decodeURIComponent(p.slice("/assets/".length));
@@ -9610,6 +9756,96 @@ var init_log = __esm(() => {
9610
9756
  // packages/chat-room-channeld/src/adapter.ts
9611
9757
  import { spawn as spawn2 } from "node:child_process";
9612
9758
  import { StringDecoder as StringDecoder2 } from "node:string_decoder";
9759
+ function adapterChildEnv(account) {
9760
+ const env = { ...process.env, ...account.env };
9761
+ let options = env.NODE_OPTIONS?.trim() ?? "";
9762
+ for (const flag of ADAPTER_NODE_OPTIONS) {
9763
+ if (!options.split(/\s+/).includes(flag))
9764
+ options = options ? `${options} ${flag}` : flag;
9765
+ }
9766
+ env.NODE_OPTIONS = options;
9767
+ env.CHANNELD_ACCOUNT_ID = account.id;
9768
+ env.CHANNELD_PLATFORM = account.platform;
9769
+ return env;
9770
+ }
9771
+ function readAccountFields(value) {
9772
+ if (!Array.isArray(value))
9773
+ return;
9774
+ const fields = [];
9775
+ const seen = new Set;
9776
+ for (const item of value) {
9777
+ if (!item || typeof item !== "object")
9778
+ continue;
9779
+ const raw = item;
9780
+ const key = typeof raw.key === "string" ? raw.key.trim() : "";
9781
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || seen.has(key))
9782
+ continue;
9783
+ const field = { key };
9784
+ if (typeof raw.label === "string" && raw.label.trim())
9785
+ field.label = raw.label.trim();
9786
+ if (typeof raw.type === "string" && ["string", "secret", "boolean", "number", "select"].includes(raw.type)) {
9787
+ field.type = raw.type;
9788
+ }
9789
+ if (raw.required === true)
9790
+ field.required = true;
9791
+ if (typeof raw.default === "string")
9792
+ field.default = raw.default;
9793
+ if (typeof raw.description === "string" && raw.description.trim())
9794
+ field.description = raw.description.trim();
9795
+ if (Array.isArray(raw.options)) {
9796
+ const options = raw.options.filter((option) => Boolean(option) && typeof option === "object").map((option) => typeof option.value === "string" && option.value ? { value: option.value, ...typeof option.label === "string" && option.label ? { label: option.label } : {} } : undefined).filter((option) => Boolean(option));
9797
+ if (options.length)
9798
+ field.options = options;
9799
+ }
9800
+ seen.add(key);
9801
+ fields.push(field);
9802
+ }
9803
+ return fields.length ? fields : undefined;
9804
+ }
9805
+ function readCapabilities(result, accountId) {
9806
+ if (!result || typeof result !== "object")
9807
+ return;
9808
+ const accounts = result.accounts;
9809
+ if (!accounts || typeof accounts !== "object")
9810
+ return;
9811
+ const raw = accounts[accountId];
9812
+ if (!raw || typeof raw !== "object")
9813
+ return;
9814
+ const entry = raw;
9815
+ const capabilities = {};
9816
+ if (typeof entry.displayName === "string" && entry.displayName.trim()) {
9817
+ capabilities.displayName = entry.displayName.trim();
9818
+ }
9819
+ const attachment = entry.attachments;
9820
+ if (attachment && typeof attachment === "object") {
9821
+ const value = attachment;
9822
+ const kinds = Array.isArray(value.kinds) ? value.kinds.filter((kind) => kind === "image" || kind === "file") : [];
9823
+ if (kinds.length) {
9824
+ capabilities.attachments = { kinds };
9825
+ if (Number.isSafeInteger(value.imageMaxBytes) && value.imageMaxBytes > 0) {
9826
+ capabilities.attachments.imageMaxBytes = value.imageMaxBytes;
9827
+ }
9828
+ if (Number.isSafeInteger(value.fileMaxBytes) && value.fileMaxBytes > 0) {
9829
+ capabilities.attachments.fileMaxBytes = value.fileMaxBytes;
9830
+ }
9831
+ }
9832
+ }
9833
+ const account = entry.account;
9834
+ if (account && typeof account === "object") {
9835
+ const value = account;
9836
+ const schema = readAccountFields(value.schema);
9837
+ const env = readAccountFields(value.env);
9838
+ if (schema || env)
9839
+ capabilities.account = { ...schema ? { schema } : {}, ...env ? { env } : {} };
9840
+ }
9841
+ const send = entry.send;
9842
+ if (send && typeof send === "object") {
9843
+ const value = send.idempotency;
9844
+ if (typeof value === "string" && value.trim())
9845
+ capabilities.send = { idempotency: value.trim() };
9846
+ }
9847
+ return Object.keys(capabilities).length ? capabilities : undefined;
9848
+ }
9613
9849
 
9614
9850
  class AdapterProcess {
9615
9851
  #account;
@@ -9628,6 +9864,7 @@ class AdapterProcess {
9628
9864
  #stopping = false;
9629
9865
  #gone = false;
9630
9866
  #pollutionError;
9867
+ #capabilities;
9631
9868
  constructor(options) {
9632
9869
  this.#account = options.account;
9633
9870
  this.#onIngest = options.onIngest;
@@ -9640,6 +9877,9 @@ class AdapterProcess {
9640
9877
  get accountId() {
9641
9878
  return this.#account.id;
9642
9879
  }
9880
+ get capabilities() {
9881
+ return this.#capabilities;
9882
+ }
9643
9883
  async start() {
9644
9884
  if (this.#child)
9645
9885
  throw new Error(`adapter ${this.#account.id} already started`);
@@ -9648,12 +9888,7 @@ class AdapterProcess {
9648
9888
  throw new Error(`adapter ${this.#account.id} has an empty command`);
9649
9889
  const child = spawn2(command, args, {
9650
9890
  stdio: ["pipe", "pipe", "pipe"],
9651
- env: {
9652
- ...process.env,
9653
- ...this.#account.env,
9654
- CHANNELD_ACCOUNT_ID: this.#account.id,
9655
- CHANNELD_PLATFORM: this.#account.platform
9656
- }
9891
+ env: adapterChildEnv(this.#account)
9657
9892
  });
9658
9893
  this.#child = child;
9659
9894
  this.#attach(child);
@@ -9667,6 +9902,7 @@ class AdapterProcess {
9667
9902
  maxFrameBytes: MAX_FRAME_BYTES
9668
9903
  }, this.#initializeTimeoutMs);
9669
9904
  this.#assertReportedPlatform("initialize", initialized);
9905
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
9670
9906
  const started = await this.#call("start", { accounts: [this.#account.id], cursors: {} }, this.#initializeTimeoutMs);
9671
9907
  this.#assertReportedPlatform("start", started);
9672
9908
  } catch (error) {
@@ -9681,6 +9917,45 @@ ${tail}` : ""}`);
9681
9917
  this.#started = true;
9682
9918
  log.info("adapter started", { account: this.#account.id });
9683
9919
  }
9920
+ async probe() {
9921
+ if (this.#child)
9922
+ throw new Error(`adapter ${this.#account.id} already started`);
9923
+ const [command, ...args] = this.#account.adapter.command;
9924
+ if (!command)
9925
+ throw new Error(`adapter ${this.#account.id} has an empty command`);
9926
+ const child = spawn2(command, args, {
9927
+ stdio: ["pipe", "pipe", "pipe"],
9928
+ env: adapterChildEnv(this.#account)
9929
+ });
9930
+ this.#child = child;
9931
+ this.#attach(child);
9932
+ try {
9933
+ const initialized = await this.#call("initialize", {
9934
+ protocolVersions: [PROTOCOL_VERSION],
9935
+ eventSchemas: [EVENT_SCHEMA_VERSION],
9936
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
9937
+ platform: this.#account.platform,
9938
+ accounts: [this.#account.id],
9939
+ maxFrameBytes: MAX_FRAME_BYTES
9940
+ }, this.#initializeTimeoutMs);
9941
+ const reported = initialized && typeof initialized === "object" ? initialized.platform : undefined;
9942
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
9943
+ return {
9944
+ ...typeof reported === "string" && reported.trim() ? { platform: reported.trim() } : {},
9945
+ ...this.#capabilities ? { capabilities: this.#capabilities } : {}
9946
+ };
9947
+ } catch (error) {
9948
+ const tail = this.#stderrTail.trim();
9949
+ const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
9950
+ throw new Error(`adapter probe failed: ${message}${tail ? `
9951
+ stderr:
9952
+ ${tail}` : ""}`);
9953
+ } finally {
9954
+ await this.stop().catch(() => {
9955
+ return;
9956
+ });
9957
+ }
9958
+ }
9684
9959
  async send(deliveryId, attemptId, idempotencyKey, target, payload) {
9685
9960
  if (!this.#started || !this.#child) {
9686
9961
  return { state: "unknown", detail: "adapter is not running" };
@@ -9985,7 +10260,7 @@ ${tail}` : ""}`);
9985
10260
  this.#detachStreams(child);
9986
10261
  }
9987
10262
  }
9988
- var SEND_STATES, STDERR_TAIL_LIMIT = 4096, DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4, DEFAULT_SEND_TIMEOUT_MS = 15000;
10263
+ var SEND_STATES, STDERR_TAIL_LIMIT = 4096, DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4, DEFAULT_SEND_TIMEOUT_MS = 15000, ADAPTER_NODE_OPTIONS;
9989
10264
  var init_adapter = __esm(() => {
9990
10265
  init_framing();
9991
10266
  init_log();
@@ -9997,6 +10272,10 @@ var init_adapter = __esm(() => {
9997
10272
  "unsupported",
9998
10273
  "unknown"
9999
10274
  ];
10275
+ ADAPTER_NODE_OPTIONS = [
10276
+ "--experimental-transform-types",
10277
+ "--disable-warning=ExperimentalWarning"
10278
+ ];
10000
10279
  });
10001
10280
 
10002
10281
  // packages/chat-room-channeld/src/config.ts
@@ -10362,7 +10641,33 @@ function readPlugin(pluginId) {
10362
10641
  const file = path18.join(dir, name);
10363
10642
  if (path18.dirname(file) !== dir || !existsSync6(file))
10364
10643
  return;
10365
- return { dir, file, meta: { id, name, platform } };
10644
+ const displayName = typeof meta.displayName === "string" && meta.displayName.trim() ? meta.displayName.trim() : undefined;
10645
+ const account = isRecord3(meta.account) ? meta.account : undefined;
10646
+ return {
10647
+ dir,
10648
+ file,
10649
+ meta: { id, name, platform, ...displayName ? { displayName } : {}, ...account ? { account } : {} }
10650
+ };
10651
+ }
10652
+ function downloadPlugin(pluginId) {
10653
+ const plugin = readPlugin(pluginId);
10654
+ if (!plugin)
10655
+ return json17({ error: "plugin not found" }, 404);
10656
+ let bytes;
10657
+ try {
10658
+ bytes = readFileSync5(plugin.file);
10659
+ } catch {
10660
+ return json17({ error: "plugin not found" }, 404);
10661
+ }
10662
+ const name = plugin.meta.name.replace(/[^\x20-\x7e]|["\\]/g, "_");
10663
+ return new Response(new Uint8Array(bytes), {
10664
+ headers: {
10665
+ "Content-Type": "application/octet-stream",
10666
+ "Content-Disposition": `attachment; filename="${name}"; filename*=UTF-8''${encodeURIComponent(plugin.meta.name)}`,
10667
+ "Cache-Control": "no-store",
10668
+ "X-Content-Type-Options": "nosniff"
10669
+ }
10670
+ });
10366
10671
  }
10367
10672
  function uploadedPlugins() {
10368
10673
  let entries;
@@ -10373,7 +10678,13 @@ function uploadedPlugins() {
10373
10678
  }
10374
10679
  return entries.flatMap((pluginId) => {
10375
10680
  const plugin = readPlugin(pluginId);
10376
- return plugin ? [{ pluginId: plugin.meta.id, name: plugin.meta.name, platform: plugin.meta.platform }] : [];
10681
+ return plugin ? [{
10682
+ pluginId: plugin.meta.id,
10683
+ name: plugin.meta.name,
10684
+ platform: plugin.meta.platform,
10685
+ ...plugin.meta.displayName ? { displayName: plugin.meta.displayName } : {},
10686
+ ...plugin.meta.account ? { account: plugin.meta.account } : {}
10687
+ }] : [];
10377
10688
  }).sort((left, right) => left.pluginId.localeCompare(right.pluginId));
10378
10689
  }
10379
10690
  function readManaged() {
@@ -10579,6 +10890,18 @@ async function getIntegration(control) {
10579
10890
  }
10580
10891
  }
10581
10892
  async function handleIntegrationAdmin(req, url, control) {
10893
+ const download = /^\/channeld\/plugins\/([^/]+)\/download$/.exec(url.pathname);
10894
+ if (download) {
10895
+ if (req.method !== "GET")
10896
+ return json17({ error: "method not allowed" }, 405);
10897
+ let pluginId;
10898
+ try {
10899
+ pluginId = decodeURIComponent(download[1]);
10900
+ } catch {
10901
+ return json17({ error: "plugin not found" }, 404);
10902
+ }
10903
+ return downloadPlugin(pluginId);
10904
+ }
10582
10905
  if (url.pathname === "/channeld/plugins") {
10583
10906
  if (req.method !== "POST")
10584
10907
  return json17({ error: "method not allowed" }, 405);
@@ -10598,22 +10921,13 @@ async function uploadPlugin(req) {
10598
10921
  if (!body.ok || !isRecord3(body.value)) {
10599
10922
  return json17({ error: "plugin body must be a JSON object" }, 400);
10600
10923
  }
10601
- const { name, platform, source } = body.value;
10924
+ const { name = "plugin.js", source } = body.value;
10602
10925
  if (typeof name !== "string" || !PLUGIN_NAME.test(name) || name.length > 128) {
10603
- return json17({ error: "name must be a safe .js, .mjs, or .cjs file name" }, 400);
10604
- }
10605
- if (typeof platform !== "string" || !IDENTIFIER2.test(platform)) {
10606
- return json17({ error: "platform must be a safe identifier" }, 400);
10926
+ return json17({ error: "name must be a safe .js, .mjs, .cjs, or .ts file name" }, 400);
10607
10927
  }
10608
10928
  if (typeof source !== "string" || Buffer.byteLength(source, "utf8") > MAX_PLUGIN_BYTES) {
10609
10929
  return json17({ error: `source must be UTF-8 text of at most ${MAX_PLUGIN_BYTES} bytes` }, 400);
10610
10930
  }
10611
- let env;
10612
- try {
10613
- env = envValue2(body.value.env);
10614
- } catch (error) {
10615
- return json17({ error: publicError(error) }, 400);
10616
- }
10617
10931
  const root = integrationRoot();
10618
10932
  const pluginId = randomUUID17();
10619
10933
  const tempDir = path18.join(root, "tmp", pluginId);
@@ -10622,14 +10936,10 @@ async function uploadPlugin(req) {
10622
10936
  try {
10623
10937
  mkdirSync3(tempDir, { recursive: true, mode: 448 });
10624
10938
  writeFileSync3(pluginFile, source, { mode: 384 });
10625
- const meta = { id: pluginId, name, platform };
10626
- writeFileSync3(path18.join(tempDir, "meta.json"), `${JSON.stringify(meta)}
10627
- `, { mode: 384 });
10628
10939
  const account = {
10629
10940
  id: `plugin-${pluginId}`,
10630
- platform,
10631
- adapter: { command: ["node", pluginFile] },
10632
- env
10941
+ platform: "plugin",
10942
+ adapter: { command: ["node", pluginFile] }
10633
10943
  };
10634
10944
  const adapter = new AdapterProcess({
10635
10945
  account,
@@ -10637,16 +10947,31 @@ async function uploadPlugin(req) {
10637
10947
  onExit: () => {},
10638
10948
  initializeTimeoutMs: HANDSHAKE_TIMEOUT_MS
10639
10949
  });
10640
- try {
10641
- await adapter.start();
10642
- } finally {
10643
- await adapter.stop();
10950
+ const probed = await adapter.probe();
10951
+ const platform = probed.platform;
10952
+ if (!platform || !IDENTIFIER2.test(platform)) {
10953
+ throw new Error("plugin must declare a platform in initialize");
10644
10954
  }
10955
+ const meta = {
10956
+ id: pluginId,
10957
+ name,
10958
+ platform,
10959
+ ...probed.capabilities?.displayName ? { displayName: probed.capabilities.displayName } : {},
10960
+ ...probed.capabilities?.account ? { account: probed.capabilities.account } : {}
10961
+ };
10962
+ writeFileSync3(path18.join(tempDir, "meta.json"), `${JSON.stringify(meta)}
10963
+ `, { mode: 384 });
10645
10964
  mkdirSync3(pluginsRoot(), { recursive: true, mode: 448 });
10646
10965
  if (existsSync6(finalDir))
10647
10966
  throw new Error("plugin id collision");
10648
10967
  renameSync(tempDir, finalDir);
10649
- return json17({ pluginId, name, platform }, 201);
10968
+ return json17({
10969
+ pluginId,
10970
+ name,
10971
+ platform,
10972
+ ...meta.displayName ? { displayName: meta.displayName } : {},
10973
+ ...meta.account ? { account: meta.account } : {}
10974
+ }, 201);
10650
10975
  } catch (error) {
10651
10976
  try {
10652
10977
  rmSync(tempDir, { recursive: true, force: true });
@@ -10654,14 +10979,14 @@ async function uploadPlugin(req) {
10654
10979
  return json17({ error: handshakeError(error) }, 400);
10655
10980
  }
10656
10981
  }
10657
- var IDENTIFIER2, PLUGIN_NAME, ENV_KEY2, RESERVED_ENV2, MAX_ENV = 64, MAX_ENV_VALUE2 = 8192, MAX_PLUGIN_BYTES, MAX_REQUEST_BYTES, HANDSHAKE_TIMEOUT_MS = 3000, json17 = (body, status = 200) => Response.json(body, { status });
10982
+ var IDENTIFIER2, PLUGIN_NAME, ENV_KEY2, RESERVED_ENV2, MAX_ENV = 64, MAX_ENV_VALUE2 = 8192, MAX_PLUGIN_BYTES, MAX_REQUEST_BYTES, HANDSHAKE_TIMEOUT_MS = 3000, json17 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } });
10658
10983
  var init_channel_integration = __esm(() => {
10659
10984
  init_adapter();
10660
10985
  init_config();
10661
10986
  init_store();
10662
10987
  init_channel_settings();
10663
10988
  IDENTIFIER2 = /^[A-Za-z0-9._-]{1,128}$/;
10664
- PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs)$/;
10989
+ PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs|ts)$/;
10665
10990
  ENV_KEY2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
10666
10991
  RESERVED_ENV2 = new Set(["CHANNELD_ACCOUNT_ID", "CHANNELD_PLATFORM"]);
10667
10992
  MAX_PLUGIN_BYTES = 256 * 1024;
@@ -10731,13 +11056,15 @@ function planPayload(rule, event, target) {
10731
11056
  room: target.roomId
10732
11057
  });
10733
11058
  let payload;
10734
- if (rendered.degraded === "empty") {
11059
+ if (rendered.degraded === "empty" && !event.content?.attachments?.length) {
10735
11060
  if (rule.onUnsupported === "drop")
10736
11061
  return { dropped: "rendered text is empty" };
10737
11062
  payload = { text: UNSUPPORTED_NOTICE, degraded: "empty" };
10738
11063
  } else {
10739
11064
  payload = { text: rendered.text };
10740
11065
  }
11066
+ if (event.content?.attachments?.length)
11067
+ payload.attachments = event.content.attachments;
10741
11068
  if (event.parent) {
10742
11069
  if (sameEndpoint(event.parent.endpoint, target)) {
10743
11070
  payload.parent = event.parent;
@@ -10754,6 +11081,290 @@ var init_rules = __esm(() => {
10754
11081
  init_config();
10755
11082
  });
10756
11083
 
11084
+ // packages/chat-room-channeld/src/pg/database.ts
11085
+ import { existsSync as existsSync7 } from "node:fs";
11086
+ import { MessageChannel as MessageChannel2, receiveMessageOnPort as receiveMessageOnPort2, Worker as Worker2 } from "node:worker_threads";
11087
+ import { fileURLToPath as fileURLToPath5 } from "node:url";
11088
+ function workerURL2() {
11089
+ const candidates = [
11090
+ new URL("./worker.mjs", import.meta.url),
11091
+ new URL("../packages/chat-room-channeld/src/pg/worker.mjs", import.meta.url),
11092
+ new URL("../packages/chat-room-channeld/dist/pg/worker.mjs", import.meta.url),
11093
+ new URL("../../src/pg/worker.mjs", import.meta.url)
11094
+ ];
11095
+ for (const candidate of candidates)
11096
+ if (existsSync7(fileURLToPath5(candidate)))
11097
+ return candidate;
11098
+ return candidates[0];
11099
+ }
11100
+ function databaseError2(error) {
11101
+ const result = new Error(String(error?.message ?? "PostgreSQL query failed"));
11102
+ Object.assign(result, error);
11103
+ return result;
11104
+ }
11105
+
11106
+ class PgDatabase2 {
11107
+ #worker;
11108
+ #port;
11109
+ #timeout;
11110
+ #lockTimeout;
11111
+ #nextID = 1;
11112
+ #depth = 0;
11113
+ #savepoints = 0;
11114
+ #broken;
11115
+ #closed = false;
11116
+ constructor(connectionString, options = {}) {
11117
+ if (!connectionString)
11118
+ throw new Error("PostgreSQL connection string is empty");
11119
+ this.#timeout = options.timeout ?? 5000;
11120
+ this.#lockTimeout = Math.max(1, this.#timeout - 1000);
11121
+ const ready = new SharedArrayBuffer(4);
11122
+ const { port1, port2 } = new MessageChannel2;
11123
+ this.#port = port1;
11124
+ this.#worker = new Worker2(workerURL2());
11125
+ this.#worker.unref();
11126
+ this.#port.unref();
11127
+ try {
11128
+ this.#worker.postMessage({
11129
+ type: "init",
11130
+ connectionString,
11131
+ ready,
11132
+ statementTimeout: Math.max(1, this.#timeout - 500),
11133
+ port: port2
11134
+ }, [port2]);
11135
+ } catch (error) {
11136
+ this.#worker.terminate();
11137
+ this.#port.close();
11138
+ throw error;
11139
+ }
11140
+ const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
11141
+ if (status === "timed-out") {
11142
+ this.#worker.terminate();
11143
+ throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
11144
+ }
11145
+ const message = receiveMessageOnPort2(this.#port)?.message;
11146
+ if (message?.type === "fatal") {
11147
+ this.#worker.terminate();
11148
+ throw databaseError2(message.error);
11149
+ }
11150
+ }
11151
+ query(sql) {
11152
+ return {
11153
+ all: (...params) => this.#request("all", sql, params).rows,
11154
+ get: (...params) => this.#request("get", sql, params).row,
11155
+ run: (...params) => {
11156
+ const result = this.#request("run", sql, params);
11157
+ return { changes: result.changes ?? 0, lastInsertRowid: result.lastInsertRowid ?? 0 };
11158
+ }
11159
+ };
11160
+ }
11161
+ prepare(sql) {
11162
+ return this.query(sql);
11163
+ }
11164
+ exec(sql) {
11165
+ this.#request("exec", sql, []);
11166
+ }
11167
+ transaction(fn) {
11168
+ const run = (immediate) => this.#run(fn, immediate);
11169
+ return Object.assign(() => run(false), {
11170
+ deferred: () => run(false),
11171
+ immediate: () => run(true)
11172
+ });
11173
+ }
11174
+ close() {
11175
+ if (this.#closed)
11176
+ return;
11177
+ this.#closed = true;
11178
+ const signal = new SharedArrayBuffer(4);
11179
+ try {
11180
+ this.#port.postMessage({ type: "close", signal });
11181
+ Atomics.wait(new Int32Array(signal), 0, 0, 2000);
11182
+ } catch {}
11183
+ this.#port.close();
11184
+ this.#worker.terminate();
11185
+ }
11186
+ #run(fn, immediate) {
11187
+ const nested = this.#depth > 0;
11188
+ const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
11189
+ if (nested) {
11190
+ this.exec(`SAVEPOINT ${savepoint}`);
11191
+ } else {
11192
+ this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
11193
+ if (immediate) {
11194
+ try {
11195
+ this.exec(`SET LOCAL lock_timeout = '${this.#lockTimeout}ms'; SELECT pg_advisory_xact_lock(hashtext('channeld-state')); SET LOCAL lock_timeout = 0`);
11196
+ } catch (error) {
11197
+ try {
11198
+ this.exec("ROLLBACK");
11199
+ } catch {}
11200
+ throw error;
11201
+ }
11202
+ }
11203
+ }
11204
+ this.#depth++;
11205
+ try {
11206
+ const result = fn();
11207
+ this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
11208
+ return result;
11209
+ } catch (error) {
11210
+ try {
11211
+ this.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
11212
+ } catch {}
11213
+ throw error;
11214
+ } finally {
11215
+ this.#depth--;
11216
+ }
11217
+ }
11218
+ #request(mode, sql, params) {
11219
+ if (this.#broken)
11220
+ throw this.#broken;
11221
+ if (this.#closed)
11222
+ throw new Error("PostgreSQL database is closed");
11223
+ const id = this.#nextID++;
11224
+ const signal = new SharedArrayBuffer(4);
11225
+ this.#port.postMessage({ id, mode, sql, params, signal });
11226
+ const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
11227
+ if (status === "timed-out") {
11228
+ this.#broken = Object.assign(new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the database connection must be reopened`), { code: "PG_BRIDGE_TIMEOUT" });
11229
+ throw this.#broken;
11230
+ }
11231
+ const message = receiveMessageOnPort2(this.#port)?.message;
11232
+ if (!message || message.id !== id) {
11233
+ this.#broken = Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
11234
+ throw this.#broken;
11235
+ }
11236
+ if (!message.ok)
11237
+ throw databaseError2(message.error);
11238
+ return message;
11239
+ }
11240
+ }
11241
+ var init_database = () => {};
11242
+
11243
+ // packages/chat-room-channeld/src/pg/schema.ts
11244
+ function initializeChannelSchema(db, options = {}) {
11245
+ db.exec(SCHEMA);
11246
+ const columns = db.query("PRAGMA table_info(channel_echoes)").all();
11247
+ if (!columns.some((column) => column.name === "created_at")) {
11248
+ db.exec("ALTER TABLE channel_echoes ADD COLUMN created_at INTEGER NOT NULL DEFAULT 0");
11249
+ }
11250
+ if (options.backfillEchoOrder) {
11251
+ db.exec("UPDATE channel_echoes SET created_at = rowid WHERE created_at = 0");
11252
+ }
11253
+ }
11254
+ var SCHEMA = `
11255
+ CREATE TABLE IF NOT EXISTS channel_events (
11256
+ event_id TEXT PRIMARY KEY,
11257
+ dedup_key TEXT NOT NULL UNIQUE,
11258
+ payload TEXT NOT NULL,
11259
+ ingress_seq INTEGER,
11260
+ committed_at INTEGER NOT NULL
11261
+ );
11262
+ CREATE TABLE IF NOT EXISTS channel_deliveries (
11263
+ delivery_id TEXT PRIMARY KEY,
11264
+ event_id TEXT NOT NULL,
11265
+ rule_id TEXT NOT NULL,
11266
+ rule_version INTEGER NOT NULL,
11267
+ target TEXT NOT NULL,
11268
+ idempotency_key TEXT NOT NULL UNIQUE,
11269
+ payload TEXT NOT NULL,
11270
+ state TEXT NOT NULL,
11271
+ attempt_count INTEGER NOT NULL DEFAULT 0,
11272
+ next_attempt_at INTEGER,
11273
+ last_error TEXT,
11274
+ provider_message TEXT,
11275
+ created_at INTEGER NOT NULL,
11276
+ updated_at INTEGER NOT NULL
11277
+ );
11278
+ CREATE TABLE IF NOT EXISTS channel_receipts (
11279
+ receipt_id TEXT PRIMARY KEY,
11280
+ delivery_id TEXT NOT NULL,
11281
+ attempt_id TEXT NOT NULL,
11282
+ state TEXT NOT NULL,
11283
+ provider_message TEXT,
11284
+ detail TEXT,
11285
+ observed_at INTEGER NOT NULL
11286
+ );
11287
+ CREATE TABLE IF NOT EXISTS channel_echoes (
11288
+ endpoint TEXT NOT NULL,
11289
+ native_message_id TEXT NOT NULL,
11290
+ logical_message_id TEXT NOT NULL,
11291
+ delivery_id TEXT,
11292
+ created_at INTEGER NOT NULL DEFAULT 0,
11293
+ PRIMARY KEY (endpoint, native_message_id)
11294
+ );
11295
+ `;
11296
+
11297
+ // packages/chat-room-channeld/src/pg/sqlite.ts
11298
+ import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
11299
+ function bindings2(params) {
11300
+ let values;
11301
+ for (let index = 0;index < params.length; index++) {
11302
+ const value = params[index];
11303
+ if (value === undefined || typeof value === "boolean") {
11304
+ values ??= params.slice();
11305
+ values[index] = value === undefined ? null : value ? 1 : 0;
11306
+ }
11307
+ }
11308
+ return values ?? params;
11309
+ }
11310
+
11311
+ class Statement2 {
11312
+ #statement;
11313
+ constructor(statement) {
11314
+ this.#statement = statement;
11315
+ }
11316
+ all(...params) {
11317
+ return this.#statement.all(...bindings2(params));
11318
+ }
11319
+ get(...params) {
11320
+ return this.#statement.get(...bindings2(params)) ?? null;
11321
+ }
11322
+ run(...params) {
11323
+ const result = this.#statement.run(...bindings2(params));
11324
+ return { changes: Number(result.changes), lastInsertRowid: Number(result.lastInsertRowid) };
11325
+ }
11326
+ }
11327
+
11328
+ class Database2 {
11329
+ #db;
11330
+ #savepoints = 0;
11331
+ constructor(file, options = {}) {
11332
+ this.#db = options.readOnly ? new DatabaseSync2(file, { readOnly: true }) : new DatabaseSync2(file);
11333
+ }
11334
+ query(sql) {
11335
+ return new Statement2(this.#db.prepare(sql));
11336
+ }
11337
+ prepare(sql) {
11338
+ return this.query(sql);
11339
+ }
11340
+ exec(sql) {
11341
+ this.#db.exec(sql);
11342
+ }
11343
+ transaction(fn) {
11344
+ const run = (begin) => this.#run(begin, fn);
11345
+ return Object.assign(() => run("BEGIN"), { deferred: () => run("BEGIN"), immediate: () => run("BEGIN IMMEDIATE") });
11346
+ }
11347
+ close() {
11348
+ this.#db.close();
11349
+ }
11350
+ #run(begin, fn) {
11351
+ const nested = this.#db.isTransaction;
11352
+ const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
11353
+ this.#db.exec(nested ? `SAVEPOINT ${savepoint}` : begin);
11354
+ try {
11355
+ const result = fn();
11356
+ this.#db.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
11357
+ return result;
11358
+ } catch (error) {
11359
+ try {
11360
+ this.#db.exec(nested ? `ROLLBACK TO ${savepoint}; RELEASE ${savepoint}` : "ROLLBACK");
11361
+ } catch {}
11362
+ throw error;
11363
+ }
11364
+ }
11365
+ }
11366
+ var init_sqlite2 = () => {};
11367
+
10757
11368
  // packages/chat-room-channeld/src/published.ts
10758
11369
  function buildPublishedResult(delivery, receipt, now) {
10759
11370
  const occurredAt = new Date(now).toISOString();
@@ -10778,13 +11389,12 @@ var PUBLISHED_RESULT_PREFIX = "result.published:";
10778
11389
  var init_published = () => {};
10779
11390
 
10780
11391
  // packages/chat-room-channeld/src/stats.ts
10781
- import { DatabaseSync as DatabaseSync2 } from "node:sqlite";
10782
11392
  function sanitizeAccountError(value) {
10783
11393
  const redacted = value.replace(/\bBearer\s+\S+/gi, "Bearer [redacted]").replace(/\b(secret|token|password|passwd|authorization|api[_-]?key)\b\s*[:=]\s*\S+/gi, "$1=[redacted]");
10784
11394
  return redacted.replace(/[\r\n\t]+/g, " ").replace(/\s+/g, " ").trim().slice(0, MAX_LAST_ERROR);
10785
11395
  }
10786
- function count(db, sql) {
10787
- const row = db.prepare(sql).get();
11396
+ function count(db, sql, ...params) {
11397
+ const row = db.query(sql).get(...params);
10788
11398
  return Number(row.count);
10789
11399
  }
10790
11400
  function accountKey(target) {
@@ -10797,52 +11407,33 @@ function accountKey(target) {
10797
11407
  function readChannelStats(path, now = Date.now(), runtime = new Map) {
10798
11408
  let db;
10799
11409
  try {
10800
- db = new DatabaseSync2(path, { readOnly: true });
11410
+ db = new Database2(path, { readOnly: true });
10801
11411
  db.exec("PRAGMA busy_timeout = 2000");
10802
- const names = new Set(db.prepare("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => String(row.name)));
11412
+ const names = new Set(db.query("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((row) => String(row.name)));
10803
11413
  if (REQUIRED_TABLES.some((table) => !names.has(table))) {
10804
11414
  throw new Error(`channel state not found: ${path}`);
10805
11415
  }
10806
- const stateCounts = {};
10807
- const accounts = new Map;
10808
- let oldestBacklogAt = null;
10809
- const rows = db.prepare("SELECT target, state, created_at FROM channel_deliveries").all();
10810
- for (const row of rows) {
10811
- const state = String(row.state);
10812
- stateCounts[state] = (stateCounts[state] ?? 0) + 1;
10813
- const key = accountKey(String(row.target));
10814
- let account = accounts.get(key);
10815
- if (!account) {
10816
- account = {
10817
- account: key,
10818
- state: "unknown",
10819
- queueDepth: 0,
10820
- oldestBacklogAt: null,
10821
- unknown: 0,
10822
- retryable: 0,
10823
- rateLimited: 0
10824
- };
10825
- accounts.set(key, account);
10826
- }
10827
- if (state === "unknown")
10828
- account.unknown += 1;
10829
- if (state === "retryable")
10830
- account.retryable += 1;
10831
- if (state === "rate_limited")
10832
- account.rateLimited += 1;
10833
- if (QUEUE_STATES.has(state)) {
10834
- const createdAt = Number(row.created_at);
10835
- account.queueDepth += 1;
10836
- if (account.oldestBacklogAt === null || createdAt < account.oldestBacklogAt) {
10837
- account.oldestBacklogAt = createdAt;
10838
- }
10839
- if (oldestBacklogAt === null || createdAt < oldestBacklogAt) {
10840
- oldestBacklogAt = createdAt;
10841
- }
10842
- }
10843
- }
10844
- for (const [key, live] of runtime) {
10845
- const account = accounts.get(key) ?? {
11416
+ return buildStats(db, now, runtime);
11417
+ } catch {
11418
+ throw new Error(`channel state not found: ${path}`);
11419
+ } finally {
11420
+ try {
11421
+ db?.close();
11422
+ } catch {}
11423
+ }
11424
+ }
11425
+ function buildStats(db, now, runtime) {
11426
+ const stateCounts = {};
11427
+ const accounts = new Map;
11428
+ let oldestBacklogAt = null;
11429
+ const rows = db.query("SELECT target, state, created_at FROM channel_deliveries").all();
11430
+ for (const row of rows) {
11431
+ const state = String(row.state);
11432
+ stateCounts[state] = (stateCounts[state] ?? 0) + 1;
11433
+ const key = accountKey(String(row.target));
11434
+ let account = accounts.get(key);
11435
+ if (!account) {
11436
+ account = {
10846
11437
  account: key,
10847
11438
  state: "unknown",
10848
11439
  queueDepth: 0,
@@ -10851,77 +11442,93 @@ function readChannelStats(path, now = Date.now(), runtime = new Map) {
10851
11442
  retryable: 0,
10852
11443
  rateLimited: 0
10853
11444
  };
10854
- account.state = live.state;
10855
- const lastError = live.lastError ? sanitizeAccountError(live.lastError) : "";
10856
- if (lastError)
10857
- account.lastError = lastError;
10858
11445
  accounts.set(key, account);
10859
11446
  }
10860
- const pending = stateCounts.pending ?? 0;
10861
- const retryable = stateCounts.retryable ?? 0;
10862
- const rateLimited = stateCounts.rate_limited ?? 0;
10863
- const failed = (stateCounts.permanent ?? 0) + (stateCounts.unsupported ?? 0) + (stateCounts.exhausted ?? 0);
10864
- return {
10865
- generatedAt: now,
10866
- events: count(db, "SELECT COUNT(*) AS count FROM channel_events"),
10867
- publishedResults: count(db, "SELECT COUNT(*) AS count FROM channel_events WHERE json_extract(payload, '$.kind') = 'result.published'"),
10868
- eventsWithoutDeliveries: count(db, `SELECT COUNT(*) AS count FROM channel_events e
10869
- WHERE json_extract(e.payload, '$.kind') IS NOT 'result.published'
10870
- AND NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.event_id = e.event_id)`),
10871
- deliveriesWithoutEvent: count(db, `SELECT COUNT(*) AS count FROM channel_deliveries d
10872
- WHERE NOT EXISTS (SELECT 1 FROM channel_events e WHERE e.event_id = d.event_id)`),
10873
- receiptsWithoutDelivery: count(db, `SELECT COUNT(*) AS count FROM channel_receipts r
10874
- WHERE NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.delivery_id = r.delivery_id)`),
10875
- deliveries: {
10876
- total: rows.length,
10877
- pending,
10878
- inFlight: stateCounts.in_flight ?? 0,
10879
- retryable,
10880
- rateLimited,
10881
- paused: stateCounts.paused ?? 0,
10882
- unknown: stateCounts.unknown ?? 0,
10883
- sent: stateCounts.sent ?? 0,
10884
- failed
10885
- },
10886
- queueDepth: pending + retryable + rateLimited,
10887
- oldestBacklogAt,
10888
- oldestBacklogAgeMs: oldestBacklogAt === null ? null : now - oldestBacklogAt,
10889
- accounts: [...accounts.values()].sort((left, right) => left.account < right.account ? -1 : left.account > right.account ? 1 : 0)
11447
+ if (state === "unknown")
11448
+ account.unknown += 1;
11449
+ if (state === "retryable")
11450
+ account.retryable += 1;
11451
+ if (state === "rate_limited")
11452
+ account.rateLimited += 1;
11453
+ if (QUEUE_STATES.has(state)) {
11454
+ const createdAt = Number(row.created_at);
11455
+ account.queueDepth += 1;
11456
+ if (account.oldestBacklogAt === null || createdAt < account.oldestBacklogAt) {
11457
+ account.oldestBacklogAt = createdAt;
11458
+ }
11459
+ if (oldestBacklogAt === null || createdAt < oldestBacklogAt) {
11460
+ oldestBacklogAt = createdAt;
11461
+ }
11462
+ }
11463
+ }
11464
+ for (const [key, live] of runtime) {
11465
+ const account = accounts.get(key) ?? {
11466
+ account: key,
11467
+ state: "unknown",
11468
+ queueDepth: 0,
11469
+ oldestBacklogAt: null,
11470
+ unknown: 0,
11471
+ retryable: 0,
11472
+ rateLimited: 0
10890
11473
  };
10891
- } catch (error) {
10892
- if (error instanceof Error && error.message.startsWith("channel state not found:"))
10893
- throw error;
10894
- throw new Error(`channel state not found: ${path}`);
10895
- } finally {
10896
- try {
10897
- db?.close();
10898
- } catch {}
10899
- }
11474
+ account.state = live.state;
11475
+ const lastError = live.lastError ? sanitizeAccountError(live.lastError) : "";
11476
+ if (lastError)
11477
+ account.lastError = lastError;
11478
+ accounts.set(key, account);
11479
+ }
11480
+ const pending = stateCounts.pending ?? 0;
11481
+ const retryable = stateCounts.retryable ?? 0;
11482
+ const rateLimited = stateCounts.rate_limited ?? 0;
11483
+ const failed = (stateCounts.permanent ?? 0) + (stateCounts.unsupported ?? 0) + (stateCounts.exhausted ?? 0);
11484
+ const publishedPattern = `${PUBLISHED_RESULT_PREFIX}%`;
11485
+ return {
11486
+ generatedAt: now,
11487
+ events: count(db, "SELECT COUNT(*) AS count FROM channel_events"),
11488
+ publishedResults: count(db, "SELECT COUNT(*) AS count FROM channel_events WHERE dedup_key LIKE ?", publishedPattern),
11489
+ eventsWithoutDeliveries: count(db, `SELECT COUNT(*) AS count FROM channel_events e
11490
+ WHERE e.dedup_key NOT LIKE ?
11491
+ AND NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.event_id = e.event_id)`, publishedPattern),
11492
+ deliveriesWithoutEvent: count(db, `SELECT COUNT(*) AS count FROM channel_deliveries d
11493
+ WHERE NOT EXISTS (SELECT 1 FROM channel_events e WHERE e.event_id = d.event_id)`),
11494
+ receiptsWithoutDelivery: count(db, `SELECT COUNT(*) AS count FROM channel_receipts r
11495
+ WHERE NOT EXISTS (SELECT 1 FROM channel_deliveries d WHERE d.delivery_id = r.delivery_id)`),
11496
+ deliveries: {
11497
+ total: rows.length,
11498
+ pending,
11499
+ inFlight: stateCounts.in_flight ?? 0,
11500
+ retryable,
11501
+ rateLimited,
11502
+ paused: stateCounts.paused ?? 0,
11503
+ unknown: stateCounts.unknown ?? 0,
11504
+ sent: stateCounts.sent ?? 0,
11505
+ failed
11506
+ },
11507
+ queueDepth: pending + retryable + rateLimited,
11508
+ oldestBacklogAt,
11509
+ oldestBacklogAgeMs: oldestBacklogAt === null ? null : now - oldestBacklogAt,
11510
+ accounts: [...accounts.values()].sort((left, right) => left.account < right.account ? -1 : left.account > right.account ? 1 : 0)
11511
+ };
10900
11512
  }
10901
11513
  var REQUIRED_TABLES, QUEUE_STATES, MAX_LAST_ERROR = 200;
10902
11514
  var init_stats = __esm(() => {
11515
+ init_database();
11516
+ init_sqlite2();
11517
+ init_published();
10903
11518
  REQUIRED_TABLES = ["channel_events", "channel_deliveries", "channel_receipts"];
10904
11519
  QUEUE_STATES = new Set(["pending", "retryable", "rate_limited"]);
10905
11520
  });
10906
11521
 
10907
11522
  // packages/chat-room-channeld/src/state.ts
10908
11523
  import { randomUUID as randomUUID18 } from "node:crypto";
10909
- import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
10910
11524
  function isTerminalDeliveryState(state) {
10911
11525
  return TERMINAL_DELIVERY_STATES.includes(state);
10912
11526
  }
10913
11527
  function transaction(db, fn) {
10914
- db.exec("BEGIN IMMEDIATE");
10915
- try {
10916
- const value = fn();
10917
- db.exec("COMMIT");
10918
- return value;
10919
- } catch (error) {
10920
- try {
10921
- db.exec("ROLLBACK");
10922
- } catch {}
10923
- throw error;
10924
- }
11528
+ return db.transaction(fn).immediate();
11529
+ }
11530
+ function likePrefix(value) {
11531
+ return `${value.replace(/[\\%_]/g, (ch) => `\\${ch}`)}%`;
10925
11532
  }
10926
11533
  function toDelivery(row) {
10927
11534
  return {
@@ -10953,8 +11560,11 @@ function toReceipt(row) {
10953
11560
  };
10954
11561
  }
10955
11562
  function openState(path) {
10956
- const db = new DatabaseSync3(path);
10957
- db.exec(SCHEMA);
11563
+ const url = process.env.CHAT_ROOM_DATABASE_URL?.trim();
11564
+ return createChannelState(url ? new PgDatabase2(url) : new Database2(path));
11565
+ }
11566
+ function createChannelState(db) {
11567
+ initializeChannelSchema(db, { backfillEchoOrder: db instanceof Database2 });
10958
11568
  let closed = false;
10959
11569
  function getDelivery(deliveryId) {
10960
11570
  const row = db.prepare("SELECT * FROM channel_deliveries WHERE delivery_id = ?").get(deliveryId);
@@ -11002,11 +11612,11 @@ function openState(path) {
11002
11612
  nextPendingDelivery(accountKey, now) {
11003
11613
  const prefix = `${accountKey.replace(/\/+$/, "")}/`;
11004
11614
  const row = db.prepare(`SELECT * FROM channel_deliveries
11005
- WHERE substr(target, 1, length(?)) = ?
11615
+ WHERE target LIKE ? ESCAPE '\\'
11006
11616
  AND state IN ('pending', 'retryable', 'rate_limited')
11007
11617
  AND (next_attempt_at IS NULL OR next_attempt_at <= ?)
11008
11618
  ORDER BY created_at ASC, delivery_id ASC
11009
- LIMIT 1`).get(prefix, prefix, now);
11619
+ LIMIT 1`).get(likePrefix(prefix), now);
11010
11620
  return row ? toDelivery(row) : undefined;
11011
11621
  },
11012
11622
  markDelivery(deliveryId, state, patch = {}) {
@@ -11023,14 +11633,15 @@ function openState(path) {
11023
11633
  },
11024
11634
  recordSent(input) {
11025
11635
  const receiptId = `rcp-${randomUUID18()}`;
11636
+ const observedAt = input.observedAt ?? Date.now();
11026
11637
  transaction(db, () => {
11027
11638
  db.prepare(`INSERT INTO channel_receipts
11028
11639
  (receipt_id, delivery_id, attempt_id, state, provider_message, detail, observed_at)
11029
- VALUES (?, ?, ?, 'sent', ?, ?, ?)`).run(receiptId, input.deliveryId, input.attemptId, input.providerMessage, input.detail ?? null, input.observedAt ?? Date.now());
11640
+ VALUES (?, ?, ?, 'sent', ?, ?, ?)`).run(receiptId, input.deliveryId, input.attemptId, input.providerMessage, input.detail ?? null, observedAt);
11030
11641
  if (input.echo) {
11031
11642
  db.prepare(`INSERT OR IGNORE INTO channel_echoes
11032
- (endpoint, native_message_id, logical_message_id, delivery_id)
11033
- VALUES (?, ?, ?, ?)`).run(input.echo.endpoint, input.echo.nativeMessageId, input.echo.logicalMessageId, input.deliveryId);
11643
+ (endpoint, native_message_id, logical_message_id, delivery_id, created_at)
11644
+ VALUES (?, ?, ?, ?, ?)`).run(input.echo.endpoint, input.echo.nativeMessageId, input.echo.logicalMessageId, input.deliveryId, observedAt);
11034
11645
  }
11035
11646
  });
11036
11647
  return receiptId;
@@ -11039,27 +11650,27 @@ function openState(path) {
11039
11650
  const prefix = `${accountKey.replace(/\/+$/, "")}/`;
11040
11651
  const result = db.prepare(`UPDATE channel_deliveries
11041
11652
  SET state = 'paused', next_attempt_at = NULL, last_error = ?, updated_at = ?
11042
- WHERE substr(target, 1, length(?)) = ?
11043
- AND state IN ('pending', 'retryable', 'rate_limited')`).run(reason, Date.now(), prefix, prefix);
11653
+ WHERE target LIKE ? ESCAPE '\\'
11654
+ AND state IN ('pending', 'retryable', 'rate_limited')`).run(reason, Date.now(), likePrefix(prefix));
11044
11655
  return Number(result.changes);
11045
11656
  },
11046
11657
  abandonUnconfiguredDeliveries(configuredAccountKeys) {
11047
- const configured = [...new Set(configuredAccountKeys)];
11048
- const accountKeySql = `CASE WHEN instr(target, '/') > 0
11049
- AND instr(substr(target, instr(target, '/') + 1), '/') > 0
11050
- THEN substr(target, 1, instr(target, '/') + instr(substr(target, instr(target, '/') + 1), '/') - 1)
11051
- ELSE target END`;
11052
- const filter = configured.length > 0 ? `AND (${accountKeySql}) NOT IN (${configured.map(() => "?").join(", ")})` : "";
11658
+ const configured = new Set(configuredAccountKeys);
11053
11659
  const rows = db.prepare(`SELECT * FROM channel_deliveries
11054
11660
  WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
11055
- ${filter}
11056
- ORDER BY created_at ASC, delivery_id ASC`).all(...configured);
11661
+ ORDER BY created_at ASC, delivery_id ASC`).all().filter((row) => !configured.has(accountKey(String(row.target))));
11057
11662
  if (rows.length === 0)
11058
11663
  return [];
11059
- transaction(db, () => db.prepare(`UPDATE channel_deliveries
11060
- SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
11061
- WHERE state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')
11062
- ${filter}`).run("account is not configured; add it back to retry", Date.now(), ...configured));
11664
+ const update = db.prepare(`UPDATE channel_deliveries
11665
+ SET state = 'unknown', next_attempt_at = NULL, last_error = ?, updated_at = ?
11666
+ WHERE delivery_id = ?
11667
+ AND state IN ('pending', 'retryable', 'rate_limited', 'in_flight', 'paused')`);
11668
+ transaction(db, () => {
11669
+ const now = Date.now();
11670
+ for (const row of rows) {
11671
+ update.run("account is not configured; add it back to retry", now, String(row.delivery_id));
11672
+ }
11673
+ });
11063
11674
  return rows.map((row) => ({ ...toDelivery(row), state: "unknown" }));
11064
11675
  },
11065
11676
  resumePausedDeliveries() {
@@ -11068,12 +11679,23 @@ function openState(path) {
11068
11679
  WHERE state = 'paused'`).run(Date.now());
11069
11680
  return Number(result.changes);
11070
11681
  },
11071
- recoverInFlightDeliveries() {
11072
- const result = db.prepare(`UPDATE channel_deliveries
11073
- SET state = 'pending', next_attempt_at = NULL,
11682
+ recoverInFlightDeliveries(idempotentAccountKeys) {
11683
+ const idempotent = new Set(idempotentAccountKeys);
11684
+ const rows = db.prepare("SELECT delivery_id, target FROM channel_deliveries WHERE state = 'in_flight'").all();
11685
+ if (!rows.length)
11686
+ return 0;
11687
+ const now = Date.now();
11688
+ const update = db.prepare(`UPDATE channel_deliveries
11689
+ SET state = ?, next_attempt_at = NULL,
11074
11690
  last_error = 'recovered stale in_flight after restart', updated_at = ?
11075
- WHERE state = 'in_flight'`).run(Date.now());
11076
- return Number(result.changes);
11691
+ WHERE delivery_id = ? AND state = 'in_flight'`);
11692
+ transaction(db, () => {
11693
+ for (const row of rows) {
11694
+ const state = idempotent.has(accountKey(String(row.target))) ? "pending" : "unknown";
11695
+ update.run(state, now, String(row.delivery_id));
11696
+ }
11697
+ });
11698
+ return rows.length;
11077
11699
  },
11078
11700
  recordReceipt(input) {
11079
11701
  const receiptId = `rcp-${randomUUID18()}`;
@@ -11094,8 +11716,8 @@ function openState(path) {
11094
11716
  },
11095
11717
  recordEcho(endpoint, nativeMessageId, logicalMessageId, deliveryId) {
11096
11718
  db.prepare(`INSERT OR IGNORE INTO channel_echoes
11097
- (endpoint, native_message_id, logical_message_id, delivery_id)
11098
- VALUES (?, ?, ?, ?)`).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null);
11719
+ (endpoint, native_message_id, logical_message_id, delivery_id, created_at)
11720
+ VALUES (?, ?, ?, ?, ?)`).run(endpoint, nativeMessageId, logicalMessageId, deliveryId ?? null, Date.now());
11099
11721
  },
11100
11722
  findEcho(endpoint, nativeMessageId) {
11101
11723
  const row = db.prepare("SELECT logical_message_id FROM channel_echoes WHERE endpoint = ? AND native_message_id = ?").get(endpoint, nativeMessageId);
@@ -11104,7 +11726,7 @@ function openState(path) {
11104
11726
  findProviderMessage(endpoint, logicalMessageId) {
11105
11727
  const row = db.prepare(`SELECT native_message_id FROM channel_echoes
11106
11728
  WHERE endpoint = ? AND logical_message_id = ? AND delivery_id IS NOT NULL
11107
- ORDER BY rowid DESC LIMIT 1`).get(endpoint, logicalMessageId);
11729
+ ORDER BY created_at DESC LIMIT 1`).get(endpoint, logicalMessageId);
11108
11730
  return row ? String(row.native_message_id) : undefined;
11109
11731
  },
11110
11732
  getDelivery,
@@ -11130,50 +11752,13 @@ function openState(path) {
11130
11752
  }
11131
11753
  };
11132
11754
  }
11133
- var DELIVERY_STATES, TERMINAL_DELIVERY_STATES, SCHEMA = `
11134
- CREATE TABLE IF NOT EXISTS channel_events (
11135
- event_id TEXT PRIMARY KEY,
11136
- dedup_key TEXT NOT NULL UNIQUE,
11137
- payload TEXT NOT NULL,
11138
- ingress_seq INTEGER,
11139
- committed_at INTEGER NOT NULL
11140
- );
11141
- CREATE TABLE IF NOT EXISTS channel_deliveries (
11142
- delivery_id TEXT PRIMARY KEY,
11143
- event_id TEXT NOT NULL,
11144
- rule_id TEXT NOT NULL,
11145
- rule_version INTEGER NOT NULL,
11146
- target TEXT NOT NULL,
11147
- idempotency_key TEXT NOT NULL UNIQUE,
11148
- payload TEXT NOT NULL,
11149
- state TEXT NOT NULL,
11150
- attempt_count INTEGER NOT NULL DEFAULT 0,
11151
- next_attempt_at INTEGER,
11152
- last_error TEXT,
11153
- provider_message TEXT,
11154
- created_at INTEGER NOT NULL,
11155
- updated_at INTEGER NOT NULL
11156
- );
11157
- CREATE TABLE IF NOT EXISTS channel_receipts (
11158
- receipt_id TEXT PRIMARY KEY,
11159
- delivery_id TEXT NOT NULL,
11160
- attempt_id TEXT NOT NULL,
11161
- state TEXT NOT NULL,
11162
- provider_message TEXT,
11163
- detail TEXT,
11164
- observed_at INTEGER NOT NULL
11165
- );
11166
- CREATE TABLE IF NOT EXISTS channel_echoes (
11167
- endpoint TEXT NOT NULL,
11168
- native_message_id TEXT NOT NULL,
11169
- logical_message_id TEXT NOT NULL,
11170
- delivery_id TEXT,
11171
- PRIMARY KEY (endpoint, native_message_id)
11172
- );
11173
- `;
11755
+ var DELIVERY_STATES, TERMINAL_DELIVERY_STATES;
11174
11756
  var init_state = __esm(() => {
11757
+ init_database();
11758
+ init_sqlite2();
11175
11759
  init_published();
11176
11760
  init_stats();
11761
+ init_stats();
11177
11762
  DELIVERY_STATES = [
11178
11763
  "pending",
11179
11764
  "in_flight",
@@ -11407,6 +11992,7 @@ class ChannelHost {
11407
11992
  #onDeliveryResult;
11408
11993
  #onIngestCommitted;
11409
11994
  #notificationOnly;
11995
+ #prepareSendPayload;
11410
11996
  #adapters = new Map;
11411
11997
  #timers = new Map;
11412
11998
  #inFlight = new Map;
@@ -11432,6 +12018,7 @@ class ChannelHost {
11432
12018
  this.#onDeliveryResult = deps.onDeliveryResult;
11433
12019
  this.#onIngestCommitted = deps.onIngestCommitted;
11434
12020
  this.#notificationOnly = deps.notificationOnly;
12021
+ this.#prepareSendPayload = deps.prepareSendPayload;
11435
12022
  }
11436
12023
  get disabledAccounts() {
11437
12024
  return [...this.#disabled];
@@ -11470,9 +12057,6 @@ class ChannelHost {
11470
12057
  const resumed = state.resumePausedDeliveries();
11471
12058
  if (resumed > 0)
11472
12059
  log.info(`resumed ${resumed} paused deliveries`);
11473
- const recovered = state.recoverInFlightDeliveries();
11474
- if (recovered > 0)
11475
- log.warn(`recovered ${recovered} stale in-flight deliveries`);
11476
12060
  this.#running = true;
11477
12061
  this.#starting = true;
11478
12062
  const started = [];
@@ -11528,6 +12112,16 @@ class ChannelHost {
11528
12112
  state.pauseAccountDeliveries(`${account.platform}/${account.id}`, "account disabled until restart");
11529
12113
  }
11530
12114
  }
12115
+ const idempotentKeys = this.#config.accounts.filter((account) => !this.#disabled.has(account.id)).filter((account) => this.#adapters.get(account.id)?.capabilities?.send?.idempotency === "persistent_delivery_key").map((account) => `${account.platform}/${account.id}`);
12116
+ const recovered = state.recoverInFlightDeliveries(idempotentKeys);
12117
+ if (recovered > 0) {
12118
+ log.warn(`recovered ${recovered} stale in-flight deliveries`);
12119
+ for (const account of this.#config.accounts) {
12120
+ if (!this.#disabled.has(account.id) && idempotentKeys.includes(`${account.platform}/${account.id}`)) {
12121
+ this.#schedule(account.id);
12122
+ }
12123
+ }
12124
+ }
11531
12125
  const usable = started.filter((accountId) => !this.#disabled.has(accountId));
11532
12126
  if (usable.length === 0) {
11533
12127
  this.#running = false;
@@ -11719,12 +12313,23 @@ class ChannelHost {
11719
12313
  this.#gate.begin(accountId);
11720
12314
  try {
11721
12315
  let receipt;
12316
+ let cleanup;
11722
12317
  try {
11723
- receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, JSON.parse(row.payload));
12318
+ const stored = JSON.parse(row.payload);
12319
+ if (this.#prepareSendPayload) {
12320
+ const prepared = await this.#prepareSendPayload(stored, adapter.capabilities);
12321
+ cleanup = prepared.cleanup;
12322
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, prepared.payload);
12323
+ } else {
12324
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, stored);
12325
+ }
11724
12326
  } catch (error) {
11725
12327
  receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
11726
12328
  } finally {
11727
12329
  inFlight.delete(row.deliveryId);
12330
+ await cleanup?.().catch(() => {
12331
+ return;
12332
+ });
11728
12333
  }
11729
12334
  if (this.#stopReason)
11730
12335
  receipt = { state: "unknown", detail: this.#stopReason };
@@ -11896,20 +12501,135 @@ var init_host = __esm(() => {
11896
12501
  function matchInboundRoutes(config, event) {
11897
12502
  return config.inbound.filter((route) => route.from.platform === event.source.platform && route.from.account === event.source.accountId && route.from.room === event.source.roomId && (route.from.event === undefined || route.from.event === event.kind));
11898
12503
  }
12504
+ function platformLabel(platform) {
12505
+ const value = platform.trim();
12506
+ return value ? value[0].toUpperCase() + value.slice(1) : "Channel";
12507
+ }
11899
12508
  function inboundRoomText(event, route) {
11900
12509
  const text = event.content?.text?.trim();
11901
- if (!text)
12510
+ const attachments = event.content?.attachments ?? [];
12511
+ if (!text && attachments.length === 0)
11902
12512
  return;
11903
12513
  const actor = event.actor.nativeUserId || "unknown";
11904
- const body = text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text;
11905
- return `[Feishu ${route.from.account}] ${actor}: ${body}`;
12514
+ const messageID = event.message?.nativeMessageId ?? event.providerEventId ?? "unknown";
12515
+ const names = attachments.map((attachment) => attachment.kind === "image" ? "[image]" : `[file ${attachment.name}]`).join(", ");
12516
+ const body = text ? text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text : names;
12517
+ return `[${platformLabel(event.source.platform)} ${route.from.account}] message_id=${messageID} chat_id=${event.source.roomId} sender=${actor}: ${body}`;
11906
12518
  }
11907
12519
  var MAX_RELAY_TEXT = 4000;
11908
12520
 
12521
+ // server/channel-attachments.ts
12522
+ import { createHash as createHash8 } from "node:crypto";
12523
+ import { createReadStream as createReadStream3, createWriteStream } from "node:fs";
12524
+ import { promises as fs7 } from "node:fs";
12525
+ import os10 from "node:os";
12526
+ import path19 from "node:path";
12527
+ import { Readable as Readable4 } from "node:stream";
12528
+ import { pipeline as pipeline2 } from "node:stream/promises";
12529
+ async function forwardAttachments(roomId, text) {
12530
+ const ids = [...text.matchAll(/\[\[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)].map((match) => match[1]).filter((id, index, all) => all.indexOf(id) === index);
12531
+ const attachments = [];
12532
+ for (const id of ids) {
12533
+ const resource = await findResource(roomId, id).catch(() => {
12534
+ return;
12535
+ });
12536
+ if (!resource) {
12537
+ attachments.push({ kind: "file", name: "attachment", error: "resource unavailable" });
12538
+ continue;
12539
+ }
12540
+ attachments.push({
12541
+ kind: resource.mimeType.startsWith("image/") ? "image" : "file",
12542
+ name: resource.name,
12543
+ mimeType: resource.mimeType,
12544
+ size: resource.size,
12545
+ resourceId: resource.id,
12546
+ roomId
12547
+ });
12548
+ }
12549
+ return attachments;
12550
+ }
12551
+ async function prepareSendPayload(payload, capabilities) {
12552
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
12553
+ return { payload };
12554
+ const attachments = payload.attachments;
12555
+ if (!Array.isArray(attachments) || attachments.length === 0)
12556
+ return { payload };
12557
+ const directory = await fs7.mkdtemp(path19.join(os10.tmpdir(), "chat-room-outbound-"));
12558
+ const files = [];
12559
+ for (const raw of attachments) {
12560
+ if (!raw || typeof raw !== "object")
12561
+ continue;
12562
+ const attachment = raw;
12563
+ if (!attachment.resourceId || !attachment.roomId) {
12564
+ files.push(attachment);
12565
+ continue;
12566
+ }
12567
+ try {
12568
+ const resource = await findResource(attachment.roomId, attachment.resourceId);
12569
+ if (!resource)
12570
+ throw new Error("resource not found");
12571
+ const limit = resource.mimeType.startsWith("image/") ? capabilities?.attachments?.imageMaxBytes : capabilities?.attachments?.fileMaxBytes;
12572
+ if (limit !== undefined && resource.size > limit)
12573
+ throw new Error(`exceeds adapter attachment limit (${limit} bytes)`);
12574
+ const opened = await openResource(resource);
12575
+ if (!opened)
12576
+ throw new Error("resource content is missing");
12577
+ const extension = path19.extname(resource.name).toLowerCase();
12578
+ const file = path19.join(directory, `${resource.id}${/^\.[a-z0-9]{1,10}$/.test(extension) ? extension : ".bin"}`);
12579
+ await pipeline2(Readable4.fromWeb(opened.stream), createWriteStream(file, { mode: 384 }));
12580
+ files.push({ ...attachment, name: resource.name, mimeType: resource.mimeType, size: resource.size, path: file });
12581
+ } catch (error) {
12582
+ files.push({ ...attachment, error: error instanceof Error ? error.message : String(error) });
12583
+ }
12584
+ }
12585
+ return {
12586
+ payload: { ...payload, attachments: files },
12587
+ cleanup: () => fs7.rm(directory, { recursive: true, force: true })
12588
+ };
12589
+ }
12590
+ function stableResourceID(eventId, roomId, index) {
12591
+ const hex = createHash8("sha256").update(`${eventId}:${roomId}:${index}`).digest("hex");
12592
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
12593
+ }
12594
+ function readableAdapterFile(value) {
12595
+ if (typeof value !== "string" || !path19.isAbsolute(value))
12596
+ return;
12597
+ const prefix = path19.join(os10.tmpdir(), "chat-room-channeld-");
12598
+ return path19.resolve(value).startsWith(prefix) ? path19.resolve(value) : undefined;
12599
+ }
12600
+ async function inboundAttachments(event, roomId) {
12601
+ const attachments = event.content?.attachments ?? [];
12602
+ const markers = [];
12603
+ for (const [index, attachment] of attachments.entries()) {
12604
+ if (attachment.error) {
12605
+ markers.push(`[attachment unavailable: ${attachment.error}]`);
12606
+ continue;
12607
+ }
12608
+ const file = readableAdapterFile(attachment.path);
12609
+ if (!file) {
12610
+ markers.push("[attachment unavailable: no local file]");
12611
+ continue;
12612
+ }
12613
+ try {
12614
+ const info = await fs7.stat(file);
12615
+ if (!info.isFile() || info.size > maxResourceBytes())
12616
+ throw new Error("file is not a regular file within the upload limit");
12617
+ const resource = await uploadResource(roomId, attachment.name || `${attachment.kind}-${index + 1}`, Readable4.toWeb(createReadStream3(file)), maxResourceBytes(), { sessionID: `channel:${event.source.accountId}`, name: `${platformLabel(event.source.platform)} ${event.source.accountId}` }, stableResourceID(event.eventId, roomId, index));
12618
+ markers.push(`[[resource:${resource.id}]]`);
12619
+ } catch (error) {
12620
+ markers.push(`[attachment upload failed: ${error instanceof Error ? error.message : String(error)}]`);
12621
+ }
12622
+ }
12623
+ return markers;
12624
+ }
12625
+ var init_channel_attachments = __esm(() => {
12626
+ init_resources();
12627
+ });
12628
+
11909
12629
  // server/channels.ts
11910
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "node:fs";
11911
12630
  import { randomUUID as randomUUID19 } from "node:crypto";
11912
- import path19 from "node:path";
12631
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "node:fs";
12632
+ import path20 from "node:path";
11913
12633
  import { parse as parseYaml5 } from "yaml";
11914
12634
  function loadChannelConfig(file, stateFile) {
11915
12635
  let text;
@@ -11930,8 +12650,8 @@ function loadChannelConfig(file, stateFile) {
11930
12650
  return parseConfig({ ...raw, stateFile });
11931
12651
  }
11932
12652
  function resolveChannelStateFile(stateDir, configured) {
11933
- const file = configured ? path19.isAbsolute(configured) ? configured : path19.resolve(stateDir, configured) : path19.join(stateDir, "channeld.sqlite");
11934
- if (path19.resolve(file) === path19.join(stateDir, "chat-room.sqlite")) {
12653
+ const file = configured ? path20.isAbsolute(configured) ? configured : path20.resolve(stateDir, configured) : path20.join(stateDir, "channeld.sqlite");
12654
+ if (path20.resolve(file) === path20.join(stateDir, "chat-room.sqlite")) {
11935
12655
  throw new Error("chatroom config: server.channeld.stateFile must not be the room database");
11936
12656
  }
11937
12657
  return file;
@@ -11968,7 +12688,12 @@ function createInboundRelay(config) {
11968
12688
  onIngestCommitted: async (event) => {
11969
12689
  for (const route of matchInboundRoutes(config, event)) {
11970
12690
  const text = inboundRoomText(event, route);
11971
- if (!text)
12691
+ if (!text && !event.content?.attachments?.length)
12692
+ continue;
12693
+ const markers = await inboundAttachments(event, route.to.room);
12694
+ const body = [text, ...markers].filter(Boolean).join(`
12695
+ `);
12696
+ if (!body)
11972
12697
  continue;
11973
12698
  await writeSqliteStateWithDatabase(databasePath(), (svc, _registry, db) => {
11974
12699
  db.exec(`CREATE TABLE IF NOT EXISTS channel_inbound_relays (
@@ -11980,7 +12705,7 @@ function createInboundRelay(config) {
11980
12705
  const inserted = db.query("INSERT OR IGNORE INTO channel_inbound_relays (event_id, room_id, relayed_at) VALUES (?, ?, ?)").run(event.eventId, route.to.room, Date.now());
11981
12706
  if (Number(inserted.changes) === 0)
11982
12707
  return;
11983
- svc.addEvent(route.to.room, text);
12708
+ svc.addEvent(route.to.room, body);
11984
12709
  });
11985
12710
  }
11986
12711
  }
@@ -11991,19 +12716,20 @@ function loadValidChannelConfig(settings) {
11991
12716
  if (!configPath) {
11992
12717
  throw new Error("chatroom config: server.channeld is enabled but no config file is set (server.channeld.config or CHAT_ROOM_CHANNELD_CONFIG)");
11993
12718
  }
11994
- const stateDir = path19.dirname(databasePath());
12719
+ const stateDir = path20.dirname(databasePath());
11995
12720
  const stateFile = resolveChannelStateFile(stateDir, settings.channeld.stateFile);
11996
12721
  const config = loadChannelConfig(configPath, stateFile);
11997
12722
  validateTargets(config);
11998
12723
  return config;
11999
12724
  }
12000
12725
  async function activateRuntime(config, deps) {
12001
- mkdirSync4(path19.dirname(config.stateFile), { recursive: true, mode: 448 });
12726
+ mkdirSync4(path20.dirname(config.stateFile), { recursive: true, mode: 448 });
12002
12727
  const inbound = createInboundRelay(config);
12003
12728
  const host = createHost(config, {
12004
12729
  spawnAdapter: deps.spawnAdapter,
12005
12730
  deliveryIntervalMs: deps.deliveryIntervalMs,
12006
12731
  onDeliveryResult: createDeliveryResultHandler(),
12732
+ prepareSendPayload,
12007
12733
  ...inbound
12008
12734
  });
12009
12735
  try {
@@ -12113,7 +12839,7 @@ function createChannelController(initial, deps = {}) {
12113
12839
  };
12114
12840
  const handle = async (req, url) => {
12115
12841
  const adminPath = url.pathname === "/channeld/reload" || url.pathname === "/channeld/enable" || url.pathname === "/channeld/disable";
12116
- const integrationPath = url.pathname === "/channeld/plugins" || url.pathname === "/channeld/integration";
12842
+ const integrationPath = url.pathname === "/channeld/plugins" || url.pathname.startsWith("/channeld/plugins/") || url.pathname === "/channeld/integration";
12117
12843
  if (!adminPath && !integrationPath)
12118
12844
  return channelRoutes(req, url, runtime);
12119
12845
  if (env.CHATROOM_ALLOW_ADMIN !== "true")
@@ -12272,6 +12998,7 @@ async function channelRoutes(req, url, source) {
12272
12998
  if (runtime.host.targetStatus(target.platform, target.account) !== "ready") {
12273
12999
  return json18({ error: "forward target is unavailable" }, 409);
12274
13000
  }
13001
+ const attachments = await forwardAttachments(roomId, message.text);
12275
13002
  const source = { platform: "chatroom", accountId: "center", roomId };
12276
13003
  const requestedTarget = { platform: target.platform, accountId: target.account, roomId: target.room };
12277
13004
  const parent = message.parentMessageId ? runtime.host.findProviderMessage(requestedTarget, message.parentMessageId) : undefined;
@@ -12288,7 +13015,7 @@ async function channelRoutes(req, url, source) {
12288
13015
  ...parent ? { parent } : {},
12289
13016
  occurredAt: new Date(message.createdAt).toISOString(),
12290
13017
  receivedAt: new Date().toISOString(),
12291
- content: { text: message.text }
13018
+ content: { text: message.text, ...attachments.length ? { attachments } : {} }
12292
13019
  };
12293
13020
  const result = await runtime.host.ingest(event);
12294
13021
  return json18({ eventId: result.eventId ?? event.eventId }, 202);
@@ -12308,7 +13035,7 @@ async function channelRoutes(req, url, source) {
12308
13035
  return json18({ error: "room not found" }, 404);
12309
13036
  return json18({ targets: forwardTargets(runtime, roomId) });
12310
13037
  }
12311
- var json18 = (body, status = 200) => Response.json(body, { status }), IDENTIFIER3, MAX_SESSION4 = 128, MAX_REQUEST_ID = 200;
13038
+ var json18 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } }), IDENTIFIER3, MAX_SESSION4 = 128, MAX_REQUEST_ID = 200;
12312
13039
  var init_channels = __esm(() => {
12313
13040
  init_channel_settings();
12314
13041
  init_channel_integration();
@@ -12318,14 +13045,15 @@ var init_channels = __esm(() => {
12318
13045
  init_config();
12319
13046
  init_host();
12320
13047
  init_rules();
13048
+ init_channel_attachments();
12321
13049
  init_state();
12322
13050
  IDENTIFIER3 = /^[A-Za-z0-9._-]{1,128}$/;
12323
13051
  });
12324
13052
 
12325
13053
  // server/startup.ts
12326
- import { existsSync as existsSync7 } from "node:fs";
12327
- import path20 from "node:path";
12328
- import { fileURLToPath as fileURLToPath5 } from "node:url";
13054
+ import { existsSync as existsSync8 } from "node:fs";
13055
+ import path21 from "node:path";
13056
+ import { fileURLToPath as fileURLToPath6 } from "node:url";
12329
13057
  function parsePort(value) {
12330
13058
  const port = Number(value);
12331
13059
  if (!Number.isInteger(port) || port < 1 || port > 65535) {
@@ -12334,8 +13062,8 @@ function parsePort(value) {
12334
13062
  return port;
12335
13063
  }
12336
13064
  async function loadServerBootstrap() {
12337
- const moduleDir = path20.dirname(fileURLToPath5(import.meta.url));
12338
- const here = existsSync7(path20.join(moduleDir, "chat.html")) ? moduleDir : path20.resolve(moduleDir, "../server");
13065
+ const moduleDir = path21.dirname(fileURLToPath6(import.meta.url));
13066
+ const here = existsSync8(path21.join(moduleDir, "chat.html")) ? moduleDir : path21.resolve(moduleDir, "../server");
12339
13067
  const settings = resolveServerSettings(loadRoomConfig());
12340
13068
  maxRoomTasks();
12341
13069
  const hostname = settings.host;
@@ -12379,7 +13107,7 @@ var init_startup = __esm(() => {
12379
13107
  });
12380
13108
 
12381
13109
  // server/chat-server.ts
12382
- var bootstrap, channels, handle, config, chat_server_default;
13110
+ var bootstrap, channels, serve2, handle, config, chat_server_default;
12383
13111
  var init_chat_server = __esm(async () => {
12384
13112
  init_http_server();
12385
13113
  init_room_reminders();
@@ -12387,12 +13115,18 @@ var init_chat_server = __esm(async () => {
12387
13115
  init_wake();
12388
13116
  await init_app();
12389
13117
  bootstrap = await loadServerBootstrap();
12390
- handle = createApp({
13118
+ serve2 = createApp({
12391
13119
  here: bootstrap.here,
12392
13120
  token: bootstrap.token,
12393
13121
  serveWakeUrl: bootstrap.serveWakeUrl,
12394
13122
  channeld: () => channels
12395
13123
  });
13124
+ handle = process.env.CHAT_ROOM_TEST_ACCESS_LOG === "1" ? (request) => {
13125
+ const path = new URL(request.url).pathname;
13126
+ if (path.startsWith("/assets/"))
13127
+ console.log(`[asset] ${path}`);
13128
+ return serve2(request);
13129
+ } : serve2;
12396
13130
  config = {
12397
13131
  hostname: bootstrap.hostname,
12398
13132
  port: bootstrap.port,
@@ -12415,9 +13149,9 @@ var init_chat_server = __esm(async () => {
12415
13149
 
12416
13150
  // cli.ts
12417
13151
  import { spawnSync } from "node:child_process";
12418
- import { existsSync as existsSync8 } from "node:fs";
13152
+ import { existsSync as existsSync9 } from "node:fs";
12419
13153
  import { readFile as readFile3 } from "node:fs/promises";
12420
- import { fileURLToPath as fileURLToPath6 } from "node:url";
13154
+ import { fileURLToPath as fileURLToPath7 } from "node:url";
12421
13155
  var usage = `Usage: opencode-chat-room [options]
12422
13156
 
12423
13157
  Options:
@@ -12464,7 +13198,7 @@ function relaunchTuiWithBun() {
12464
13198
  const supported = major > 1 || major === 1 && (minor > 3 || minor === 3 && patch >= 14);
12465
13199
  if (!supported)
12466
13200
  return;
12467
- const child = spawnSync("bun", [fileURLToPath6(import.meta.url), ...process.argv.slice(2)], {
13201
+ const child = spawnSync("bun", [fileURLToPath7(import.meta.url), ...process.argv.slice(2)], {
12468
13202
  stdio: "inherit",
12469
13203
  env: process.env
12470
13204
  });
@@ -12474,7 +13208,7 @@ if (args[0] === "cli") {
12474
13208
  relaunchTuiWithBun();
12475
13209
  const packaged = new URL("../src/tui/main.mjs", import.meta.url);
12476
13210
  const source = new URL("./src/tui/main.mjs", import.meta.url);
12477
- const entry = existsSync8(fileURLToPath6(packaged)) ? packaged : source;
13211
+ const entry = existsSync9(fileURLToPath7(packaged)) ? packaged : source;
12478
13212
  const { main } = await import(entry.href);
12479
13213
  process.exit(await main(args.slice(1)));
12480
13214
  }