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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +10 -10
  3. package/README.zh-CN.md +10 -10
  4. package/dist/cli.js +544 -88
  5. package/package.json +4 -4
  6. package/packages/chat-room-channeld/README.md +17 -12
  7. package/packages/chat-room-channeld/src/adapter.ts +145 -7
  8. package/packages/chat-room-channeld/src/host.ts +24 -9
  9. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  10. package/packages/chat-room-channeld/src/protocol.ts +52 -1
  11. package/packages/chat-room-channeld/src/rules.ts +7 -2
  12. package/plugin.ts +1 -1
  13. package/server/assets/base.css +8 -2
  14. package/server/assets/chat/admin.js +0 -2
  15. package/server/assets/chat/announcements.js +2 -4
  16. package/server/assets/chat/chat-background.js +177 -0
  17. package/server/assets/chat/confirm-dialog.js +0 -1
  18. package/server/assets/chat/create-room-dialog.js +0 -1
  19. package/server/assets/chat/diagram-viewer.js +7 -1
  20. package/server/assets/chat/doc-preview.js +71 -15
  21. package/server/assets/chat/events.js +13 -5
  22. package/server/assets/chat/files.js +10 -6
  23. package/server/assets/chat/image-zoom.js +8 -1
  24. package/server/assets/chat/index.js +4 -2
  25. package/server/assets/chat/integration-account-schema.js +99 -0
  26. package/server/assets/chat/integration-editor.js +1 -1
  27. package/server/assets/chat/integrations.js +207 -57
  28. package/server/assets/chat/locales/de.js +1 -1
  29. package/server/assets/chat/locales/es.js +1 -1
  30. package/server/assets/chat/locales/fr.js +1 -1
  31. package/server/assets/chat/locales/it.js +1 -1
  32. package/server/assets/chat/locales/ja.js +1 -1
  33. package/server/assets/chat/locales/ko.js +1 -1
  34. package/server/assets/chat/markdown-footnotes.js +1 -1
  35. package/server/assets/chat/markdown.js +23 -0
  36. package/server/assets/chat/messages.js +1 -0
  37. package/server/assets/chat/palette.js +6 -1
  38. package/server/assets/chat/panels.js +23 -3
  39. package/server/assets/chat/receipts.js +2 -3
  40. package/server/assets/chat/reminders.js +2 -4
  41. package/server/assets/chat/replies.js +0 -6
  42. package/server/assets/chat/rooms.js +1 -6
  43. package/server/assets/chat/settings.js +69 -3
  44. package/server/assets/chat/shortcuts.js +0 -3
  45. package/server/assets/chat/side-pane.js +33 -8
  46. package/server/assets/chat/state.js +48 -18
  47. package/server/assets/chat/system-events.js +29 -3
  48. package/server/assets/chat/system-messages.js +9 -0
  49. package/server/assets/chat/tasks.js +2 -8
  50. package/server/assets/chat/window-controls.js +37 -0
  51. package/server/assets/code-highlight.css +22 -6
  52. package/server/assets/conversation.css +55 -12
  53. package/server/assets/doc-preview.css +6 -1
  54. package/server/assets/files.css +3 -0
  55. package/server/assets/monaco/integration-rules.css +1 -1
  56. package/server/assets/monaco/integration-rules.js +841 -533
  57. package/server/assets/responsive.css +32 -2
  58. package/server/assets/settings.css +117 -13
  59. package/server/assets/window-controls.css +36 -0
  60. package/server/channel-attachments.ts +133 -0
  61. package/server/channel-integration.ts +79 -26
  62. package/server/channels.ts +15 -5
  63. package/server/chat.html +71 -37
  64. package/server/manifest.webmanifest +1 -0
  65. package/server/sw.js +1 -0
  66. package/src/center/center-client.ts +1 -1
  67. package/src/state/pg-database.ts +5 -5
  68. package/src/state/pg-migrate.ts +7 -7
  69. package/src/state/pg-worker.mjs +2 -17
  70. package/src/state/sqlite-database.ts +14 -5
  71. package/src/state/sqlite-rooms.ts +130 -23
  72. package/src/state/sqlite-state-store.ts +6 -5
  73. package/src/state/sqlite.ts +3 -3
  74. package/src/web/integration-rules-editor.ts +139 -5
  75. package/src/web/integration-rules.ts +6 -2
  76. package/src/web/integration-schema.ts +7 -6
  77. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  78. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  79. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  80. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  81. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  82. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  83. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  84. 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}'"`,
@@ -9610,6 +9755,90 @@ var init_log = __esm(() => {
9610
9755
  // packages/chat-room-channeld/src/adapter.ts
9611
9756
  import { spawn as spawn2 } from "node:child_process";
9612
9757
  import { StringDecoder as StringDecoder2 } from "node:string_decoder";
9758
+ function adapterChildEnv(account) {
9759
+ const env = { ...process.env, ...account.env };
9760
+ let options = env.NODE_OPTIONS?.trim() ?? "";
9761
+ for (const flag of ADAPTER_NODE_OPTIONS) {
9762
+ if (!options.split(/\s+/).includes(flag))
9763
+ options = options ? `${options} ${flag}` : flag;
9764
+ }
9765
+ env.NODE_OPTIONS = options;
9766
+ env.CHANNELD_ACCOUNT_ID = account.id;
9767
+ env.CHANNELD_PLATFORM = account.platform;
9768
+ return env;
9769
+ }
9770
+ function readAccountFields(value) {
9771
+ if (!Array.isArray(value))
9772
+ return;
9773
+ const fields = [];
9774
+ const seen = new Set;
9775
+ for (const item of value) {
9776
+ if (!item || typeof item !== "object")
9777
+ continue;
9778
+ const raw = item;
9779
+ const key = typeof raw.key === "string" ? raw.key.trim() : "";
9780
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || seen.has(key))
9781
+ continue;
9782
+ const field = { key };
9783
+ if (typeof raw.label === "string" && raw.label.trim())
9784
+ field.label = raw.label.trim();
9785
+ if (typeof raw.type === "string" && ["string", "secret", "boolean", "number", "select"].includes(raw.type)) {
9786
+ field.type = raw.type;
9787
+ }
9788
+ if (raw.required === true)
9789
+ field.required = true;
9790
+ if (typeof raw.default === "string")
9791
+ field.default = raw.default;
9792
+ if (typeof raw.description === "string" && raw.description.trim())
9793
+ field.description = raw.description.trim();
9794
+ if (Array.isArray(raw.options)) {
9795
+ 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));
9796
+ if (options.length)
9797
+ field.options = options;
9798
+ }
9799
+ seen.add(key);
9800
+ fields.push(field);
9801
+ }
9802
+ return fields.length ? fields : undefined;
9803
+ }
9804
+ function readCapabilities(result, accountId) {
9805
+ if (!result || typeof result !== "object")
9806
+ return;
9807
+ const accounts = result.accounts;
9808
+ if (!accounts || typeof accounts !== "object")
9809
+ return;
9810
+ const raw = accounts[accountId];
9811
+ if (!raw || typeof raw !== "object")
9812
+ return;
9813
+ const entry = raw;
9814
+ const capabilities = {};
9815
+ if (typeof entry.displayName === "string" && entry.displayName.trim()) {
9816
+ capabilities.displayName = entry.displayName.trim();
9817
+ }
9818
+ const attachment = entry.attachments;
9819
+ if (attachment && typeof attachment === "object") {
9820
+ const value = attachment;
9821
+ const kinds = Array.isArray(value.kinds) ? value.kinds.filter((kind) => kind === "image" || kind === "file") : [];
9822
+ if (kinds.length) {
9823
+ capabilities.attachments = { kinds };
9824
+ if (Number.isSafeInteger(value.imageMaxBytes) && value.imageMaxBytes > 0) {
9825
+ capabilities.attachments.imageMaxBytes = value.imageMaxBytes;
9826
+ }
9827
+ if (Number.isSafeInteger(value.fileMaxBytes) && value.fileMaxBytes > 0) {
9828
+ capabilities.attachments.fileMaxBytes = value.fileMaxBytes;
9829
+ }
9830
+ }
9831
+ }
9832
+ const account = entry.account;
9833
+ if (account && typeof account === "object") {
9834
+ const value = account;
9835
+ const schema = readAccountFields(value.schema);
9836
+ const env = readAccountFields(value.env);
9837
+ if (schema || env)
9838
+ capabilities.account = { ...schema ? { schema } : {}, ...env ? { env } : {} };
9839
+ }
9840
+ return Object.keys(capabilities).length ? capabilities : undefined;
9841
+ }
9613
9842
 
9614
9843
  class AdapterProcess {
9615
9844
  #account;
@@ -9628,6 +9857,7 @@ class AdapterProcess {
9628
9857
  #stopping = false;
9629
9858
  #gone = false;
9630
9859
  #pollutionError;
9860
+ #capabilities;
9631
9861
  constructor(options) {
9632
9862
  this.#account = options.account;
9633
9863
  this.#onIngest = options.onIngest;
@@ -9640,6 +9870,9 @@ class AdapterProcess {
9640
9870
  get accountId() {
9641
9871
  return this.#account.id;
9642
9872
  }
9873
+ get capabilities() {
9874
+ return this.#capabilities;
9875
+ }
9643
9876
  async start() {
9644
9877
  if (this.#child)
9645
9878
  throw new Error(`adapter ${this.#account.id} already started`);
@@ -9648,12 +9881,7 @@ class AdapterProcess {
9648
9881
  throw new Error(`adapter ${this.#account.id} has an empty command`);
9649
9882
  const child = spawn2(command, args, {
9650
9883
  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
- }
9884
+ env: adapterChildEnv(this.#account)
9657
9885
  });
9658
9886
  this.#child = child;
9659
9887
  this.#attach(child);
@@ -9667,6 +9895,7 @@ class AdapterProcess {
9667
9895
  maxFrameBytes: MAX_FRAME_BYTES
9668
9896
  }, this.#initializeTimeoutMs);
9669
9897
  this.#assertReportedPlatform("initialize", initialized);
9898
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
9670
9899
  const started = await this.#call("start", { accounts: [this.#account.id], cursors: {} }, this.#initializeTimeoutMs);
9671
9900
  this.#assertReportedPlatform("start", started);
9672
9901
  } catch (error) {
@@ -9681,6 +9910,45 @@ ${tail}` : ""}`);
9681
9910
  this.#started = true;
9682
9911
  log.info("adapter started", { account: this.#account.id });
9683
9912
  }
9913
+ async probe() {
9914
+ if (this.#child)
9915
+ throw new Error(`adapter ${this.#account.id} already started`);
9916
+ const [command, ...args] = this.#account.adapter.command;
9917
+ if (!command)
9918
+ throw new Error(`adapter ${this.#account.id} has an empty command`);
9919
+ const child = spawn2(command, args, {
9920
+ stdio: ["pipe", "pipe", "pipe"],
9921
+ env: adapterChildEnv(this.#account)
9922
+ });
9923
+ this.#child = child;
9924
+ this.#attach(child);
9925
+ try {
9926
+ const initialized = await this.#call("initialize", {
9927
+ protocolVersions: [PROTOCOL_VERSION],
9928
+ eventSchemas: [EVENT_SCHEMA_VERSION],
9929
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
9930
+ platform: this.#account.platform,
9931
+ accounts: [this.#account.id],
9932
+ maxFrameBytes: MAX_FRAME_BYTES
9933
+ }, this.#initializeTimeoutMs);
9934
+ const reported = initialized && typeof initialized === "object" ? initialized.platform : undefined;
9935
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
9936
+ return {
9937
+ ...typeof reported === "string" && reported.trim() ? { platform: reported.trim() } : {},
9938
+ ...this.#capabilities ? { capabilities: this.#capabilities } : {}
9939
+ };
9940
+ } catch (error) {
9941
+ const tail = this.#stderrTail.trim();
9942
+ const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
9943
+ throw new Error(`adapter probe failed: ${message}${tail ? `
9944
+ stderr:
9945
+ ${tail}` : ""}`);
9946
+ } finally {
9947
+ await this.stop().catch(() => {
9948
+ return;
9949
+ });
9950
+ }
9951
+ }
9684
9952
  async send(deliveryId, attemptId, idempotencyKey, target, payload) {
9685
9953
  if (!this.#started || !this.#child) {
9686
9954
  return { state: "unknown", detail: "adapter is not running" };
@@ -9985,7 +10253,7 @@ ${tail}` : ""}`);
9985
10253
  this.#detachStreams(child);
9986
10254
  }
9987
10255
  }
9988
- var SEND_STATES, STDERR_TAIL_LIMIT = 4096, DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4, DEFAULT_SEND_TIMEOUT_MS = 15000;
10256
+ var SEND_STATES, STDERR_TAIL_LIMIT = 4096, DEFAULT_INITIALIZE_TIMEOUT_MS = 1e4, DEFAULT_SEND_TIMEOUT_MS = 15000, ADAPTER_NODE_OPTIONS;
9989
10257
  var init_adapter = __esm(() => {
9990
10258
  init_framing();
9991
10259
  init_log();
@@ -9997,6 +10265,10 @@ var init_adapter = __esm(() => {
9997
10265
  "unsupported",
9998
10266
  "unknown"
9999
10267
  ];
10268
+ ADAPTER_NODE_OPTIONS = [
10269
+ "--experimental-transform-types",
10270
+ "--disable-warning=ExperimentalWarning"
10271
+ ];
10000
10272
  });
10001
10273
 
10002
10274
  // packages/chat-room-channeld/src/config.ts
@@ -10362,7 +10634,33 @@ function readPlugin(pluginId) {
10362
10634
  const file = path18.join(dir, name);
10363
10635
  if (path18.dirname(file) !== dir || !existsSync6(file))
10364
10636
  return;
10365
- return { dir, file, meta: { id, name, platform } };
10637
+ const displayName = typeof meta.displayName === "string" && meta.displayName.trim() ? meta.displayName.trim() : undefined;
10638
+ const account = isRecord3(meta.account) ? meta.account : undefined;
10639
+ return {
10640
+ dir,
10641
+ file,
10642
+ meta: { id, name, platform, ...displayName ? { displayName } : {}, ...account ? { account } : {} }
10643
+ };
10644
+ }
10645
+ function downloadPlugin(pluginId) {
10646
+ const plugin = readPlugin(pluginId);
10647
+ if (!plugin)
10648
+ return json17({ error: "plugin not found" }, 404);
10649
+ let bytes;
10650
+ try {
10651
+ bytes = readFileSync5(plugin.file);
10652
+ } catch {
10653
+ return json17({ error: "plugin not found" }, 404);
10654
+ }
10655
+ const name = plugin.meta.name.replace(/[^\x20-\x7e]|["\\]/g, "_");
10656
+ return new Response(new Uint8Array(bytes), {
10657
+ headers: {
10658
+ "Content-Type": "application/octet-stream",
10659
+ "Content-Disposition": `attachment; filename="${name}"; filename*=UTF-8''${encodeURIComponent(plugin.meta.name)}`,
10660
+ "Cache-Control": "no-store",
10661
+ "X-Content-Type-Options": "nosniff"
10662
+ }
10663
+ });
10366
10664
  }
10367
10665
  function uploadedPlugins() {
10368
10666
  let entries;
@@ -10373,7 +10671,13 @@ function uploadedPlugins() {
10373
10671
  }
10374
10672
  return entries.flatMap((pluginId) => {
10375
10673
  const plugin = readPlugin(pluginId);
10376
- return plugin ? [{ pluginId: plugin.meta.id, name: plugin.meta.name, platform: plugin.meta.platform }] : [];
10674
+ return plugin ? [{
10675
+ pluginId: plugin.meta.id,
10676
+ name: plugin.meta.name,
10677
+ platform: plugin.meta.platform,
10678
+ ...plugin.meta.displayName ? { displayName: plugin.meta.displayName } : {},
10679
+ ...plugin.meta.account ? { account: plugin.meta.account } : {}
10680
+ }] : [];
10377
10681
  }).sort((left, right) => left.pluginId.localeCompare(right.pluginId));
10378
10682
  }
10379
10683
  function readManaged() {
@@ -10579,6 +10883,18 @@ async function getIntegration(control) {
10579
10883
  }
10580
10884
  }
10581
10885
  async function handleIntegrationAdmin(req, url, control) {
10886
+ const download = /^\/channeld\/plugins\/([^/]+)\/download$/.exec(url.pathname);
10887
+ if (download) {
10888
+ if (req.method !== "GET")
10889
+ return json17({ error: "method not allowed" }, 405);
10890
+ let pluginId;
10891
+ try {
10892
+ pluginId = decodeURIComponent(download[1]);
10893
+ } catch {
10894
+ return json17({ error: "plugin not found" }, 404);
10895
+ }
10896
+ return downloadPlugin(pluginId);
10897
+ }
10582
10898
  if (url.pathname === "/channeld/plugins") {
10583
10899
  if (req.method !== "POST")
10584
10900
  return json17({ error: "method not allowed" }, 405);
@@ -10598,22 +10914,13 @@ async function uploadPlugin(req) {
10598
10914
  if (!body.ok || !isRecord3(body.value)) {
10599
10915
  return json17({ error: "plugin body must be a JSON object" }, 400);
10600
10916
  }
10601
- const { name, platform, source } = body.value;
10917
+ const { name = "plugin.js", source } = body.value;
10602
10918
  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);
10919
+ return json17({ error: "name must be a safe .js, .mjs, .cjs, or .ts file name" }, 400);
10607
10920
  }
10608
10921
  if (typeof source !== "string" || Buffer.byteLength(source, "utf8") > MAX_PLUGIN_BYTES) {
10609
10922
  return json17({ error: `source must be UTF-8 text of at most ${MAX_PLUGIN_BYTES} bytes` }, 400);
10610
10923
  }
10611
- let env;
10612
- try {
10613
- env = envValue2(body.value.env);
10614
- } catch (error) {
10615
- return json17({ error: publicError(error) }, 400);
10616
- }
10617
10924
  const root = integrationRoot();
10618
10925
  const pluginId = randomUUID17();
10619
10926
  const tempDir = path18.join(root, "tmp", pluginId);
@@ -10622,14 +10929,10 @@ async function uploadPlugin(req) {
10622
10929
  try {
10623
10930
  mkdirSync3(tempDir, { recursive: true, mode: 448 });
10624
10931
  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
10932
  const account = {
10629
10933
  id: `plugin-${pluginId}`,
10630
- platform,
10631
- adapter: { command: ["node", pluginFile] },
10632
- env
10934
+ platform: "plugin",
10935
+ adapter: { command: ["node", pluginFile] }
10633
10936
  };
10634
10937
  const adapter = new AdapterProcess({
10635
10938
  account,
@@ -10637,16 +10940,31 @@ async function uploadPlugin(req) {
10637
10940
  onExit: () => {},
10638
10941
  initializeTimeoutMs: HANDSHAKE_TIMEOUT_MS
10639
10942
  });
10640
- try {
10641
- await adapter.start();
10642
- } finally {
10643
- await adapter.stop();
10943
+ const probed = await adapter.probe();
10944
+ const platform = probed.platform;
10945
+ if (!platform || !IDENTIFIER2.test(platform)) {
10946
+ throw new Error("plugin must declare a platform in initialize");
10644
10947
  }
10948
+ const meta = {
10949
+ id: pluginId,
10950
+ name,
10951
+ platform,
10952
+ ...probed.capabilities?.displayName ? { displayName: probed.capabilities.displayName } : {},
10953
+ ...probed.capabilities?.account ? { account: probed.capabilities.account } : {}
10954
+ };
10955
+ writeFileSync3(path18.join(tempDir, "meta.json"), `${JSON.stringify(meta)}
10956
+ `, { mode: 384 });
10645
10957
  mkdirSync3(pluginsRoot(), { recursive: true, mode: 448 });
10646
10958
  if (existsSync6(finalDir))
10647
10959
  throw new Error("plugin id collision");
10648
10960
  renameSync(tempDir, finalDir);
10649
- return json17({ pluginId, name, platform }, 201);
10961
+ return json17({
10962
+ pluginId,
10963
+ name,
10964
+ platform,
10965
+ ...meta.displayName ? { displayName: meta.displayName } : {},
10966
+ ...meta.account ? { account: meta.account } : {}
10967
+ }, 201);
10650
10968
  } catch (error) {
10651
10969
  try {
10652
10970
  rmSync(tempDir, { recursive: true, force: true });
@@ -10654,14 +10972,14 @@ async function uploadPlugin(req) {
10654
10972
  return json17({ error: handshakeError(error) }, 400);
10655
10973
  }
10656
10974
  }
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 });
10975
+ 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
10976
  var init_channel_integration = __esm(() => {
10659
10977
  init_adapter();
10660
10978
  init_config();
10661
10979
  init_store();
10662
10980
  init_channel_settings();
10663
10981
  IDENTIFIER2 = /^[A-Za-z0-9._-]{1,128}$/;
10664
- PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs)$/;
10982
+ PLUGIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:js|mjs|cjs|ts)$/;
10665
10983
  ENV_KEY2 = /^[A-Za-z_][A-Za-z0-9_]*$/;
10666
10984
  RESERVED_ENV2 = new Set(["CHANNELD_ACCOUNT_ID", "CHANNELD_PLATFORM"]);
10667
10985
  MAX_PLUGIN_BYTES = 256 * 1024;
@@ -10731,13 +11049,15 @@ function planPayload(rule, event, target) {
10731
11049
  room: target.roomId
10732
11050
  });
10733
11051
  let payload;
10734
- if (rendered.degraded === "empty") {
11052
+ if (rendered.degraded === "empty" && !event.content?.attachments?.length) {
10735
11053
  if (rule.onUnsupported === "drop")
10736
11054
  return { dropped: "rendered text is empty" };
10737
11055
  payload = { text: UNSUPPORTED_NOTICE, degraded: "empty" };
10738
11056
  } else {
10739
11057
  payload = { text: rendered.text };
10740
11058
  }
11059
+ if (event.content?.attachments?.length)
11060
+ payload.attachments = event.content.attachments;
10741
11061
  if (event.parent) {
10742
11062
  if (sameEndpoint(event.parent.endpoint, target)) {
10743
11063
  payload.parent = event.parent;
@@ -11407,6 +11727,7 @@ class ChannelHost {
11407
11727
  #onDeliveryResult;
11408
11728
  #onIngestCommitted;
11409
11729
  #notificationOnly;
11730
+ #prepareSendPayload;
11410
11731
  #adapters = new Map;
11411
11732
  #timers = new Map;
11412
11733
  #inFlight = new Map;
@@ -11432,6 +11753,7 @@ class ChannelHost {
11432
11753
  this.#onDeliveryResult = deps.onDeliveryResult;
11433
11754
  this.#onIngestCommitted = deps.onIngestCommitted;
11434
11755
  this.#notificationOnly = deps.notificationOnly;
11756
+ this.#prepareSendPayload = deps.prepareSendPayload;
11435
11757
  }
11436
11758
  get disabledAccounts() {
11437
11759
  return [...this.#disabled];
@@ -11719,12 +12041,23 @@ class ChannelHost {
11719
12041
  this.#gate.begin(accountId);
11720
12042
  try {
11721
12043
  let receipt;
12044
+ let cleanup;
11722
12045
  try {
11723
- receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, JSON.parse(row.payload));
12046
+ const stored = JSON.parse(row.payload);
12047
+ if (this.#prepareSendPayload) {
12048
+ const prepared = await this.#prepareSendPayload(stored, adapter.capabilities);
12049
+ cleanup = prepared.cleanup;
12050
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, prepared.payload);
12051
+ } else {
12052
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, stored);
12053
+ }
11724
12054
  } catch (error) {
11725
12055
  receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
11726
12056
  } finally {
11727
12057
  inFlight.delete(row.deliveryId);
12058
+ await cleanup?.().catch(() => {
12059
+ return;
12060
+ });
11728
12061
  }
11729
12062
  if (this.#stopReason)
11730
12063
  receipt = { state: "unknown", detail: this.#stopReason };
@@ -11896,20 +12229,135 @@ var init_host = __esm(() => {
11896
12229
  function matchInboundRoutes(config, event) {
11897
12230
  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
12231
  }
12232
+ function platformLabel(platform) {
12233
+ const value = platform.trim();
12234
+ return value ? value[0].toUpperCase() + value.slice(1) : "Channel";
12235
+ }
11899
12236
  function inboundRoomText(event, route) {
11900
12237
  const text = event.content?.text?.trim();
11901
- if (!text)
12238
+ const attachments = event.content?.attachments ?? [];
12239
+ if (!text && attachments.length === 0)
11902
12240
  return;
11903
12241
  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}`;
12242
+ const messageID = event.message?.nativeMessageId ?? event.providerEventId ?? "unknown";
12243
+ const names = attachments.map((attachment) => attachment.kind === "image" ? "[image]" : `[file ${attachment.name}]`).join(", ");
12244
+ const body = text ? text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text : names;
12245
+ return `[${platformLabel(event.source.platform)} ${route.from.account}] message_id=${messageID} chat_id=${event.source.roomId} sender=${actor}: ${body}`;
11906
12246
  }
11907
12247
  var MAX_RELAY_TEXT = 4000;
11908
12248
 
12249
+ // server/channel-attachments.ts
12250
+ import { createHash as createHash8 } from "node:crypto";
12251
+ import { createReadStream as createReadStream3, createWriteStream } from "node:fs";
12252
+ import { promises as fs7 } from "node:fs";
12253
+ import os10 from "node:os";
12254
+ import path19 from "node:path";
12255
+ import { Readable as Readable4 } from "node:stream";
12256
+ import { pipeline as pipeline2 } from "node:stream/promises";
12257
+ async function forwardAttachments(roomId, text) {
12258
+ 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);
12259
+ const attachments = [];
12260
+ for (const id of ids) {
12261
+ const resource = await findResource(roomId, id).catch(() => {
12262
+ return;
12263
+ });
12264
+ if (!resource) {
12265
+ attachments.push({ kind: "file", name: "attachment", error: "resource unavailable" });
12266
+ continue;
12267
+ }
12268
+ attachments.push({
12269
+ kind: resource.mimeType.startsWith("image/") ? "image" : "file",
12270
+ name: resource.name,
12271
+ mimeType: resource.mimeType,
12272
+ size: resource.size,
12273
+ resourceId: resource.id,
12274
+ roomId
12275
+ });
12276
+ }
12277
+ return attachments;
12278
+ }
12279
+ async function prepareSendPayload(payload, capabilities) {
12280
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
12281
+ return { payload };
12282
+ const attachments = payload.attachments;
12283
+ if (!Array.isArray(attachments) || attachments.length === 0)
12284
+ return { payload };
12285
+ const directory = await fs7.mkdtemp(path19.join(os10.tmpdir(), "chat-room-outbound-"));
12286
+ const files = [];
12287
+ for (const raw of attachments) {
12288
+ if (!raw || typeof raw !== "object")
12289
+ continue;
12290
+ const attachment = raw;
12291
+ if (!attachment.resourceId || !attachment.roomId) {
12292
+ files.push(attachment);
12293
+ continue;
12294
+ }
12295
+ try {
12296
+ const resource = await findResource(attachment.roomId, attachment.resourceId);
12297
+ if (!resource)
12298
+ throw new Error("resource not found");
12299
+ const limit = resource.mimeType.startsWith("image/") ? capabilities?.attachments?.imageMaxBytes : capabilities?.attachments?.fileMaxBytes;
12300
+ if (limit !== undefined && resource.size > limit)
12301
+ throw new Error(`exceeds adapter attachment limit (${limit} bytes)`);
12302
+ const opened = await openResource(resource);
12303
+ if (!opened)
12304
+ throw new Error("resource content is missing");
12305
+ const extension = path19.extname(resource.name).toLowerCase();
12306
+ const file = path19.join(directory, `${resource.id}${/^\.[a-z0-9]{1,10}$/.test(extension) ? extension : ".bin"}`);
12307
+ await pipeline2(Readable4.fromWeb(opened.stream), createWriteStream(file, { mode: 384 }));
12308
+ files.push({ ...attachment, name: resource.name, mimeType: resource.mimeType, size: resource.size, path: file });
12309
+ } catch (error) {
12310
+ files.push({ ...attachment, error: error instanceof Error ? error.message : String(error) });
12311
+ }
12312
+ }
12313
+ return {
12314
+ payload: { ...payload, attachments: files },
12315
+ cleanup: () => fs7.rm(directory, { recursive: true, force: true })
12316
+ };
12317
+ }
12318
+ function stableResourceID(eventId, roomId, index) {
12319
+ const hex = createHash8("sha256").update(`${eventId}:${roomId}:${index}`).digest("hex");
12320
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
12321
+ }
12322
+ function readableAdapterFile(value) {
12323
+ if (typeof value !== "string" || !path19.isAbsolute(value))
12324
+ return;
12325
+ const prefix = path19.join(os10.tmpdir(), "chat-room-channeld-");
12326
+ return path19.resolve(value).startsWith(prefix) ? path19.resolve(value) : undefined;
12327
+ }
12328
+ async function inboundAttachments(event, roomId) {
12329
+ const attachments = event.content?.attachments ?? [];
12330
+ const markers = [];
12331
+ for (const [index, attachment] of attachments.entries()) {
12332
+ if (attachment.error) {
12333
+ markers.push(`[attachment unavailable: ${attachment.error}]`);
12334
+ continue;
12335
+ }
12336
+ const file = readableAdapterFile(attachment.path);
12337
+ if (!file) {
12338
+ markers.push("[attachment unavailable: no local file]");
12339
+ continue;
12340
+ }
12341
+ try {
12342
+ const info = await fs7.stat(file);
12343
+ if (!info.isFile() || info.size > maxResourceBytes())
12344
+ throw new Error("file is not a regular file within the upload limit");
12345
+ 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));
12346
+ markers.push(`[[resource:${resource.id}]]`);
12347
+ } catch (error) {
12348
+ markers.push(`[attachment upload failed: ${error instanceof Error ? error.message : String(error)}]`);
12349
+ }
12350
+ }
12351
+ return markers;
12352
+ }
12353
+ var init_channel_attachments = __esm(() => {
12354
+ init_resources();
12355
+ });
12356
+
11909
12357
  // server/channels.ts
11910
- import { mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "node:fs";
11911
12358
  import { randomUUID as randomUUID19 } from "node:crypto";
11912
- import path19 from "node:path";
12359
+ import { mkdirSync as mkdirSync4, readFileSync as readFileSync6 } from "node:fs";
12360
+ import path20 from "node:path";
11913
12361
  import { parse as parseYaml5 } from "yaml";
11914
12362
  function loadChannelConfig(file, stateFile) {
11915
12363
  let text;
@@ -11930,8 +12378,8 @@ function loadChannelConfig(file, stateFile) {
11930
12378
  return parseConfig({ ...raw, stateFile });
11931
12379
  }
11932
12380
  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")) {
12381
+ const file = configured ? path20.isAbsolute(configured) ? configured : path20.resolve(stateDir, configured) : path20.join(stateDir, "channeld.sqlite");
12382
+ if (path20.resolve(file) === path20.join(stateDir, "chat-room.sqlite")) {
11935
12383
  throw new Error("chatroom config: server.channeld.stateFile must not be the room database");
11936
12384
  }
11937
12385
  return file;
@@ -11968,7 +12416,12 @@ function createInboundRelay(config) {
11968
12416
  onIngestCommitted: async (event) => {
11969
12417
  for (const route of matchInboundRoutes(config, event)) {
11970
12418
  const text = inboundRoomText(event, route);
11971
- if (!text)
12419
+ if (!text && !event.content?.attachments?.length)
12420
+ continue;
12421
+ const markers = await inboundAttachments(event, route.to.room);
12422
+ const body = [text, ...markers].filter(Boolean).join(`
12423
+ `);
12424
+ if (!body)
11972
12425
  continue;
11973
12426
  await writeSqliteStateWithDatabase(databasePath(), (svc, _registry, db) => {
11974
12427
  db.exec(`CREATE TABLE IF NOT EXISTS channel_inbound_relays (
@@ -11980,7 +12433,7 @@ function createInboundRelay(config) {
11980
12433
  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
12434
  if (Number(inserted.changes) === 0)
11982
12435
  return;
11983
- svc.addEvent(route.to.room, text);
12436
+ svc.addEvent(route.to.room, body);
11984
12437
  });
11985
12438
  }
11986
12439
  }
@@ -11991,19 +12444,20 @@ function loadValidChannelConfig(settings) {
11991
12444
  if (!configPath) {
11992
12445
  throw new Error("chatroom config: server.channeld is enabled but no config file is set (server.channeld.config or CHAT_ROOM_CHANNELD_CONFIG)");
11993
12446
  }
11994
- const stateDir = path19.dirname(databasePath());
12447
+ const stateDir = path20.dirname(databasePath());
11995
12448
  const stateFile = resolveChannelStateFile(stateDir, settings.channeld.stateFile);
11996
12449
  const config = loadChannelConfig(configPath, stateFile);
11997
12450
  validateTargets(config);
11998
12451
  return config;
11999
12452
  }
12000
12453
  async function activateRuntime(config, deps) {
12001
- mkdirSync4(path19.dirname(config.stateFile), { recursive: true, mode: 448 });
12454
+ mkdirSync4(path20.dirname(config.stateFile), { recursive: true, mode: 448 });
12002
12455
  const inbound = createInboundRelay(config);
12003
12456
  const host = createHost(config, {
12004
12457
  spawnAdapter: deps.spawnAdapter,
12005
12458
  deliveryIntervalMs: deps.deliveryIntervalMs,
12006
12459
  onDeliveryResult: createDeliveryResultHandler(),
12460
+ prepareSendPayload,
12007
12461
  ...inbound
12008
12462
  });
12009
12463
  try {
@@ -12113,7 +12567,7 @@ function createChannelController(initial, deps = {}) {
12113
12567
  };
12114
12568
  const handle = async (req, url) => {
12115
12569
  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";
12570
+ const integrationPath = url.pathname === "/channeld/plugins" || url.pathname.startsWith("/channeld/plugins/") || url.pathname === "/channeld/integration";
12117
12571
  if (!adminPath && !integrationPath)
12118
12572
  return channelRoutes(req, url, runtime);
12119
12573
  if (env.CHATROOM_ALLOW_ADMIN !== "true")
@@ -12272,6 +12726,7 @@ async function channelRoutes(req, url, source) {
12272
12726
  if (runtime.host.targetStatus(target.platform, target.account) !== "ready") {
12273
12727
  return json18({ error: "forward target is unavailable" }, 409);
12274
12728
  }
12729
+ const attachments = await forwardAttachments(roomId, message.text);
12275
12730
  const source = { platform: "chatroom", accountId: "center", roomId };
12276
12731
  const requestedTarget = { platform: target.platform, accountId: target.account, roomId: target.room };
12277
12732
  const parent = message.parentMessageId ? runtime.host.findProviderMessage(requestedTarget, message.parentMessageId) : undefined;
@@ -12288,7 +12743,7 @@ async function channelRoutes(req, url, source) {
12288
12743
  ...parent ? { parent } : {},
12289
12744
  occurredAt: new Date(message.createdAt).toISOString(),
12290
12745
  receivedAt: new Date().toISOString(),
12291
- content: { text: message.text }
12746
+ content: { text: message.text, ...attachments.length ? { attachments } : {} }
12292
12747
  };
12293
12748
  const result = await runtime.host.ingest(event);
12294
12749
  return json18({ eventId: result.eventId ?? event.eventId }, 202);
@@ -12308,7 +12763,7 @@ async function channelRoutes(req, url, source) {
12308
12763
  return json18({ error: "room not found" }, 404);
12309
12764
  return json18({ targets: forwardTargets(runtime, roomId) });
12310
12765
  }
12311
- var json18 = (body, status = 200) => Response.json(body, { status }), IDENTIFIER3, MAX_SESSION4 = 128, MAX_REQUEST_ID = 200;
12766
+ var json18 = (body, status = 200) => Response.json(body, { status, headers: { "Cache-Control": "no-store" } }), IDENTIFIER3, MAX_SESSION4 = 128, MAX_REQUEST_ID = 200;
12312
12767
  var init_channels = __esm(() => {
12313
12768
  init_channel_settings();
12314
12769
  init_channel_integration();
@@ -12318,13 +12773,14 @@ var init_channels = __esm(() => {
12318
12773
  init_config();
12319
12774
  init_host();
12320
12775
  init_rules();
12776
+ init_channel_attachments();
12321
12777
  init_state();
12322
12778
  IDENTIFIER3 = /^[A-Za-z0-9._-]{1,128}$/;
12323
12779
  });
12324
12780
 
12325
12781
  // server/startup.ts
12326
12782
  import { existsSync as existsSync7 } from "node:fs";
12327
- import path20 from "node:path";
12783
+ import path21 from "node:path";
12328
12784
  import { fileURLToPath as fileURLToPath5 } from "node:url";
12329
12785
  function parsePort(value) {
12330
12786
  const port = Number(value);
@@ -12334,8 +12790,8 @@ function parsePort(value) {
12334
12790
  return port;
12335
12791
  }
12336
12792
  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");
12793
+ const moduleDir = path21.dirname(fileURLToPath5(import.meta.url));
12794
+ const here = existsSync7(path21.join(moduleDir, "chat.html")) ? moduleDir : path21.resolve(moduleDir, "../server");
12339
12795
  const settings = resolveServerSettings(loadRoomConfig());
12340
12796
  maxRoomTasks();
12341
12797
  const hostname = settings.host;