@alexsun-top/opencode-chat-room 0.8.4 → 0.8.6

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 (206) hide show
  1. package/CHANGELOG.md +17 -3
  2. package/README.md +5 -5
  3. package/README.zh-CN.md +5 -5
  4. package/cli.ts +20 -1
  5. package/dist/cli.js +3785 -1462
  6. package/package.json +19 -11
  7. package/packages/chat-room-channeld/README.md +16 -10
  8. package/packages/chat-room-channeld/src/delivery.ts +0 -4
  9. package/packages/chat-room-channeld/src/host.ts +48 -37
  10. package/packages/chat-room-channeld/src/inbound.ts +3 -6
  11. package/packages/chat-room-channeld/src/pg/database.ts +141 -49
  12. package/packages/chat-room-channeld/src/pg/sql.mjs +157 -142
  13. package/packages/chat-room-channeld/src/pg/sql.mts +175 -0
  14. package/packages/chat-room-channeld/src/pg/worker.mjs +148 -99
  15. package/packages/chat-room-channeld/src/pg/worker.mts +201 -0
  16. package/packages/chat-room-channeld/src/state-rows.ts +132 -0
  17. package/packages/chat-room-channeld/src/state.ts +129 -157
  18. package/plugin.ts +21 -5
  19. package/server/app.ts +9 -0
  20. package/server/assets/base.css +22 -2
  21. package/server/assets/chat/admin.js +17 -1
  22. package/server/assets/chat/announcements.js +79 -34
  23. package/server/assets/chat/attachments.js +3 -3
  24. package/server/assets/chat/clipboard.js +1 -1
  25. package/server/assets/chat/confirm-dialog.js +3 -0
  26. package/server/assets/chat/copy-action.js +1 -1
  27. package/server/assets/chat/create-room-dialog.js +7 -0
  28. package/server/assets/chat/diagram-viewer.js +4 -8
  29. package/server/assets/chat/doc-preview.js +71 -31
  30. package/server/assets/chat/editor.js +49 -10
  31. package/server/assets/chat/events.js +13 -6
  32. package/server/assets/chat/files.js +33 -27
  33. package/server/assets/chat/history-loader.js +31 -15
  34. package/server/assets/chat/integration-editor.js +27 -1
  35. package/server/assets/chat/integrations.js +108 -16
  36. package/server/assets/chat/join-requests.js +40 -2
  37. package/server/assets/chat/locales/de.js +5 -3
  38. package/server/assets/chat/locales/es.js +5 -3
  39. package/server/assets/chat/locales/fr.js +5 -3
  40. package/server/assets/chat/locales/it.js +5 -3
  41. package/server/assets/chat/locales/ja.js +5 -3
  42. package/server/assets/chat/locales/ko.js +5 -3
  43. package/server/assets/chat/markdown-footnotes.js +27 -15
  44. package/server/assets/chat/markdown.js +6 -12
  45. package/server/assets/chat/members.js +34 -22
  46. package/server/assets/chat/mentions.js +8 -5
  47. package/server/assets/chat/message-cache.js +9 -3
  48. package/server/assets/chat/message-polling.js +10 -4
  49. package/server/assets/chat/message-window.js +58 -1
  50. package/server/assets/chat/messages.js +90 -37
  51. package/server/assets/chat/office-preview.js +3 -3
  52. package/server/assets/chat/operator.js +624 -0
  53. package/server/assets/chat/palette.js +7 -10
  54. package/server/assets/chat/panels.js +42 -0
  55. package/server/assets/chat/questions.js +75 -58
  56. package/server/assets/chat/recall.js +14 -5
  57. package/server/assets/chat/receipts.js +63 -7
  58. package/server/assets/chat/refresh-timing.js +6 -0
  59. package/server/assets/chat/reminders.js +47 -13
  60. package/server/assets/chat/replies.js +39 -25
  61. package/server/assets/chat/resource-format.js +6 -3
  62. package/server/assets/chat/room-list.js +202 -3
  63. package/server/assets/chat/room-watcher.js +3 -1
  64. package/server/assets/chat/rooms.js +29 -7
  65. package/server/assets/chat/settings.js +37 -6
  66. package/server/assets/chat/shortcuts.js +3 -1
  67. package/server/assets/chat/side-pane.js +1 -1
  68. package/server/assets/chat/state.js +51 -18
  69. package/server/assets/chat/system-events.js +3 -2
  70. package/server/assets/chat/system-messages.js +15 -15
  71. package/server/assets/chat/tasks.js +37 -14
  72. package/server/assets/chat/window-controls.js +25 -15
  73. package/server/assets/code-highlight.css +0 -13
  74. package/server/assets/conversation.css +45 -5
  75. package/server/assets/doc-preview.css +9 -0
  76. package/server/assets/files.css +4 -0
  77. package/server/assets/monaco/integration-rules.js +1 -1
  78. package/server/assets/office/THIRD-PARTY-NOTICES.txt +23 -1
  79. package/server/assets/office/licenses/docx-preview-HEADER.txt +6 -0
  80. package/server/assets/office/licenses/echarts-LICENSE-d3.txt +27 -0
  81. package/server/assets/office/licenses/echarts-NOTICE.txt +5 -0
  82. package/server/assets/office/licenses/immediate-LICENSE.txt +20 -0
  83. package/server/assets/office/licenses/lie-LICENSE.txt +7 -0
  84. package/server/assets/office/licenses/pako-LICENSE.txt +21 -0
  85. package/server/assets/office/licenses/pako-ZLIB.txt +18 -0
  86. package/server/assets/office/licenses/setimmediate-LICENSE.txt +20 -0
  87. package/server/assets/responsive.css +12 -2
  88. package/server/assets/settings.css +3 -1
  89. package/server/assets/tasks.css +6 -1
  90. package/server/assets/window-controls.css +3 -1
  91. package/server/channels.ts +3 -2
  92. package/server/chat.html +7 -2
  93. package/server/inbox.ts +3 -1
  94. package/server/join-requests.ts +8 -1
  95. package/server/member-routes.ts +16 -2
  96. package/server/newrooms.ts +2 -13
  97. package/server/operator-auth.ts +21 -0
  98. package/server/operator-routes.ts +150 -0
  99. package/server/operator-state.ts +64 -0
  100. package/server/operator.css +139 -0
  101. package/server/room-owner.ts +17 -0
  102. package/server/routes/inbox.ts +15 -5
  103. package/server/routes/pages.ts +12 -2
  104. package/server/routes/room-actions.ts +4 -3
  105. package/server/sw.js +3 -1
  106. package/server/system.html +109 -0
  107. package/server/wake.ts +1 -1
  108. package/skills/chatroom/SKILL.md +9 -0
  109. package/src/README.md +1 -1
  110. package/src/acp/client.ts +254 -0
  111. package/src/acp/protocol.ts +300 -0
  112. package/src/acp/watch.ts +498 -0
  113. package/src/agent/agent-receipts.ts +98 -8
  114. package/src/center/center-client.ts +6 -1
  115. package/src/center/center-inbox.ts +54 -7
  116. package/src/center/center-wake.ts +57 -3
  117. package/src/center/forward-client.ts +48 -0
  118. package/src/center/mentions.ts +16 -3
  119. package/src/center/notification-delay.ts +139 -0
  120. package/src/center/queue.ts +3 -0
  121. package/src/config/file-config.ts +25 -0
  122. package/src/mcp/server.ts +389 -0
  123. package/src/protocol/config.ts +7 -0
  124. package/src/runtime/plugin-notifications.ts +43 -9
  125. package/src/runtime/v2-plugin.ts +14 -3
  126. package/src/runtime/v2-receiver.ts +10 -2
  127. package/src/runtime/watch.ts +5 -1
  128. package/src/state/pg-database.ts +133 -49
  129. package/src/state/pg-sql.mjs +157 -142
  130. package/src/state/pg-sql.mts +175 -0
  131. package/src/state/pg-worker.mjs +148 -99
  132. package/src/state/pg-worker.mts +201 -0
  133. package/src/state/receiver-state.ts +47 -0
  134. package/src/state/sqlite-database.ts +6 -2
  135. package/src/state/sqlite-members.ts +48 -4
  136. package/src/state/sqlite-messages.ts +25 -12
  137. package/src/state/sqlite-schema.ts +4 -1
  138. package/src/state/sqlite-state.ts +1 -1
  139. package/src/state/store.ts +31 -11
  140. package/src/tui/app-types.mjs +1 -0
  141. package/src/tui/app-types.mts +175 -0
  142. package/src/tui/app.mjs +473 -423
  143. package/src/tui/app.mts +543 -0
  144. package/src/tui/config.mjs +166 -158
  145. package/src/tui/config.mts +247 -0
  146. package/src/tui/http.mjs +239 -206
  147. package/src/tui/http.mts +412 -0
  148. package/src/tui/i18n.mjs +17 -20
  149. package/src/tui/i18n.mts +42 -0
  150. package/src/tui/info-app.mjs +431 -427
  151. package/src/tui/info-app.mts +500 -0
  152. package/src/tui/info-content.mjs +205 -199
  153. package/src/tui/info-content.mts +341 -0
  154. package/src/tui/join-app.mjs +75 -64
  155. package/src/tui/join-app.mts +99 -0
  156. package/src/tui/locales/en.mjs +302 -320
  157. package/src/tui/locales/en.mts +349 -0
  158. package/src/tui/locales/zh-CN.mjs +302 -320
  159. package/src/tui/locales/zh-CN.mts +349 -0
  160. package/src/tui/main.mjs +219 -213
  161. package/src/tui/main.mts +255 -0
  162. package/src/tui/markdown.mjs +128 -272
  163. package/src/tui/markdown.mts +152 -0
  164. package/src/tui/mentions.mjs +181 -184
  165. package/src/tui/mentions.mts +251 -0
  166. package/src/tui/message-app.mjs +181 -173
  167. package/src/tui/message-app.mts +213 -0
  168. package/src/tui/message-view.mjs +90 -111
  169. package/src/tui/message-view.mts +151 -0
  170. package/src/tui/messages.mjs +55 -49
  171. package/src/tui/messages.mts +106 -0
  172. package/src/tui/palette-app.mjs +364 -344
  173. package/src/tui/palette-app.mts +388 -0
  174. package/src/tui/palette.mjs +100 -98
  175. package/src/tui/palette.mts +176 -0
  176. package/src/tui/prefs.mjs +56 -63
  177. package/src/tui/prefs.mts +126 -0
  178. package/src/tui/reminder-app.mjs +191 -181
  179. package/src/tui/reminder-app.mts +228 -0
  180. package/src/tui/room-settings-app.mjs +275 -242
  181. package/src/tui/room-settings-app.mts +318 -0
  182. package/src/tui/session.mjs +30 -29
  183. package/src/tui/session.mts +51 -0
  184. package/src/tui/settings-app.mjs +151 -138
  185. package/src/tui/settings-app.mts +179 -0
  186. package/src/tui/ui-content.mjs +426 -421
  187. package/src/tui/ui-content.mts +499 -0
  188. package/src/tui/ui-help.mjs +58 -67
  189. package/src/tui/ui-help.mts +87 -0
  190. package/src/tui/ui-mentions.mjs +34 -36
  191. package/src/tui/ui-mentions.mts +60 -0
  192. package/src/tui/ui-overlay-view.mjs +259 -267
  193. package/src/tui/ui-overlay-view.mts +322 -0
  194. package/src/tui/ui-suggest-view.mjs +54 -57
  195. package/src/tui/ui-suggest-view.mts +78 -0
  196. package/src/tui/ui-suggest.mjs +164 -167
  197. package/src/tui/ui-suggest.mts +248 -0
  198. package/src/tui/ui-theme.mjs +52 -57
  199. package/src/tui/ui-theme.mts +98 -0
  200. package/src/tui/ui-view.mjs +267 -275
  201. package/src/tui/ui-view.mts +308 -0
  202. package/src/tui/ui.mjs +372 -359
  203. package/src/tui/ui.mts +440 -0
  204. package/src/tui/wire.mjs +215 -0
  205. package/src/tui/wire.mts +383 -0
  206. package/src/web/integration-rules-editor.ts +25 -2
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.8.4",
3
+ "version": "0.8.6",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -26,7 +26,11 @@
26
26
  "plugin.ts",
27
27
  "index.ts",
28
28
  "src",
29
+ "src/state/pg-*.mjs",
30
+ "src/tui/*.mjs",
31
+ "src/tui/locales/*.mjs",
29
32
  "packages/chat-room-channeld/src",
33
+ "packages/chat-room-channeld/src/pg/*.mjs",
30
34
  "packages/chat-room-channeld/dist/mock-adapter.js",
31
35
  "!src/tests",
32
36
  "!src/**/*.test.*",
@@ -48,6 +52,9 @@
48
52
  "server/message-recall-routes.ts",
49
53
  "server/room-payload.ts",
50
54
  "server/room-owner.ts",
55
+ "server/operator-auth.ts",
56
+ "server/operator-routes.ts",
57
+ "server/operator-state.ts",
51
58
  "server/newrooms.ts",
52
59
  "server/join-requests.ts",
53
60
  "server/room-join.ts",
@@ -61,6 +68,8 @@
61
68
  "server/room-reminders.ts",
62
69
  "server/wake.ts",
63
70
  "server/chat.html",
71
+ "server/system.html",
72
+ "server/operator.css",
64
73
  "server/manifest.webmanifest",
65
74
  "server/sw.js",
66
75
  "server/assets",
@@ -76,8 +85,9 @@
76
85
  "registry": "https://registry.npmjs.org/"
77
86
  },
78
87
  "scripts": {
79
- "build:web": "tsc -p tsconfig.web.json && tsc -p tsconfig.sw.json",
80
- "build:cli": "bun build cli.ts --target=node --packages external --outfile dist/cli.js >&2",
88
+ "build:web": "bun scripts/build-web.ts",
89
+ "build:runtime": "tsc --ignoreConfig --target es2022 --module nodenext --strict --noUncheckedIndexedAccess --skipLibCheck src/state/pg-*.mts packages/chat-room-channeld/src/pg/*.mts && tsc --ignoreConfig --target es2022 --module nodenext --noCheck src/tui/*.mts src/tui/locales/*.mts",
90
+ "build:cli": "bun run build:runtime && bun build cli.ts --target=node --packages external --outfile dist/cli.js >&2",
81
91
  "build:channeld-mock": "bun run --cwd packages/chat-room-channeld build:mock",
82
92
  "build:adapter-feishu": "bun scripts/build-feishu-adapter.ts",
83
93
  "build:monaco": "bun scripts/build-monaco.ts",
@@ -86,11 +96,9 @@
86
96
  "server": "node cli.ts",
87
97
  "server:bun": "bun cli.ts",
88
98
  "server:deno": "deno run --allow-env --allow-read --allow-write --allow-net cli.ts",
89
- "test": "bun run build:web && bun scripts/check-web-build.ts && bun scripts/check-web-types.ts && for file in src/tests/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done && bun run test:plugins && bun test src/tui/test --isolate",
99
+ "test": "bun run build:web && bun run build:runtime && bun scripts/check-web-build.ts && for file in src/tests/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done && bun run test:plugins && bun test src/tui/test --isolate",
90
100
  "test:plugins": "for dir in plugins/*/tests; do bun test \"$dir\" || exit; done",
91
- "typecheck": "bun run build:web && tsc --noEmit && bun scripts/check-web-types.ts && bun run typecheck:web-strict && bun run typecheck:sw-strict",
92
- "typecheck:web-strict": "tsc -p tsconfig.web.strict.json",
93
- "typecheck:sw-strict": "tsc -p tsconfig.sw.strict.json"
101
+ "typecheck": "bun run build:web && tsc --noEmit"
94
102
  },
95
103
  "engines": {
96
104
  "node": ">=24.2.0"
@@ -105,21 +113,21 @@
105
113
  "playwright": "1.64.1",
106
114
  "pptx-preview": "1.0.7",
107
115
  "shiki": "4.6.0",
116
+ "typescript": "7.0.2",
108
117
  "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
109
118
  },
110
- "peerDependencies": {
111
- "typescript": "^5"
112
- },
113
119
  "dependencies": {
114
120
  "@aws-sdk/client-s3": "^3.1178.0",
115
121
  "@opencode-ai/plugin": "^1.18.29",
116
122
  "@opencode/client": "2.0.32",
117
- "@opentui/core": "0.2.16",
118
123
  "croner": "11.0.0",
119
124
  "pg": "^8.23.1",
120
125
  "yaml": "^2.9.0",
121
126
  "zod": "4.1.8"
122
127
  },
128
+ "optionalDependencies": {
129
+ "@opentui/core": "0.9.12"
130
+ },
123
131
  "overrides": {
124
132
  "echarts": "6.1.0",
125
133
  "lodash": "4.18.1",
@@ -74,8 +74,9 @@ Run the suite from a checkout:
74
74
  bun test tests/*.test.ts
75
75
  ```
76
76
 
77
- The standalone tarball, once published, includes `tests/` and a self-contained
78
- `tsconfig.build.json`. To build and test from an installed tarball:
77
+ The standalone tarball, once published, includes `tests/` and the `.mts`
78
+ sources. The build script passes every compiler flag explicitly, so no
79
+ `tsconfig` file ships with it. To build and test from an installed tarball:
79
80
 
80
81
  ```sh
81
82
  cd node_modules/@alexsun-top/chat-room-channeld
@@ -223,19 +224,24 @@ The child process reads:
223
224
  - `FEISHU_HTTP_TIMEOUT_MS` (optional, default `10000`)
224
225
  - `FEISHU_CARD_VERSION` (optional, `1.0` default or `2.0`)
225
226
  - `FEISHU_INBOUND` (optional, `1` enables the event long connection)
226
- - `FEISHU_INBOUND_CHATS` (required with `FEISHU_INBOUND=1`; comma-separated
227
- group `chat_id` allowlist)
227
+ - `FEISHU_INBOUND_CHATS` (comma-separated group `chat_id` allowlist)
228
+ - `FEISHU_INBOUND_DM_CHAT` and `FEISHU_INBOUND_DM_OPEN_ID` (set both with
229
+ `FEISHU_INBOUND=1` to receive only one private chat from one app-scoped user;
230
+ this ignores the group allowlist)
228
231
 
229
232
  Set these in the host environment; the host passes its environment to adapter
230
233
  child processes.
231
234
 
232
235
  Inbound requires the app to use long-connection event subscription in the Feishu
233
- developer console and to subscribe `im.message.receive_v1`; the bot must already
234
- be in each allowlisted group. The adapter obtains the WebSocket URL from
236
+ developer console and to subscribe `im.message.receive_v1`. The bot must be in
237
+ each allowlisted group; private chat requires the app's bot DM read permission
238
+ (`im:message.p2p_msg:readonly` or `im:message.p2p_msg`). Add a server `inbound`
239
+ route for the exact source account and chat to relay it into ChatRoom. The
240
+ adapter obtains the WebSocket URL from
235
241
  `POST /callback/ws/endpoint`, pings, reassembles fragmented frames, and
236
- acknowledges only after the host commits the ingest. Only group `text` and `post`
237
- messages from human senders in an allowlisted chat are mapped. Bot/self senders,
238
- other chats, other event types, other apps, and unsupported message types are
242
+ acknowledges only after the host commits the ingest. Supported `text`, `post`,
243
+ `image`, and `file` messages must come from an allowed human sender and chat.
244
+ Bot/self senders, other chats, other event types, other apps, and unsupported message types are
239
245
  acknowledged without ingest. A long-connection start failure logs a warning,
240
246
  keeps the account started for outbound sends, and reports a sanitized
241
247
  `inbound failed: ...` in the account status; outbound forwarding keeps working.
@@ -339,4 +345,4 @@ same terminal result event and message.
339
345
  - no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
340
346
  - no attachments, no rule UI, no multi-tenant permission model, no exactly-once
341
347
  guarantee (inbound room notifications are idempotent per event and route, but
342
- a crash between the ACK and Feishu's next retry can still lose an event).
348
+ a crash between the ACK and Feishu's next retry can still lose an event).
@@ -67,10 +67,6 @@ export function applyReceipt(
67
67
 
68
68
  switch (receipt.state) {
69
69
  case "sent": {
70
- state.markDelivery(row.deliveryId, "sent", {
71
- providerMessage: providerMessage ?? null,
72
- lastError: null,
73
- });
74
70
  const event = state.getEvent(row.eventId);
75
71
  const echo = receipt.providerMessage?.nativeMessageId && receipt.providerMessage.endpoint
76
72
  ? {
@@ -1,4 +1,4 @@
1
- import type { AccountConfig, ChannelConfig, RuleTarget } from "./config.ts";
1
+ import type { AccountConfig, ChannelConfig } from "./config.ts";
2
2
  import { AdapterProcess, type SendReceipt } from "./adapter.ts";
3
3
  import { applyReceipt, notifyDeliveryResult, type DeliveryResultHandler } from "./delivery.ts";
4
4
  import { parseTarget, startFailureReason, toEndpoint, validateTargets } from "./host-helpers.ts";
@@ -8,7 +8,7 @@ import type { AdapterCapabilities, Endpoint, IngestEvent, MessageRef } from "./p
8
8
  import { matchRules, planPayload, sameEndpoint, targetKey } from "./rules.ts";
9
9
  import type { ChannelAccountRuntime } from "./stats.ts";
10
10
  import { sanitizeAccountError } from "./stats.ts";
11
- import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
11
+ import { openState, type ChannelState, type DeliveryRow, type PlannedDelivery } from "./state.ts";
12
12
 
13
13
  export type { IngestResult } from "./ingest-gate.ts";
14
14
 
@@ -213,12 +213,9 @@ export class ChannelHost {
213
213
  .map((account) => `${account.platform}/${account.id}`);
214
214
  const recovered = state.recoverInFlightDeliveries(idempotentKeys);
215
215
  if (recovered > 0) {
216
+ // Every started account already owns one delivery loop, so recovery only
217
+ // makes rows pending; scheduling again would create a second loop.
216
218
  log.warn(`recovered ${recovered} stale in-flight deliveries`);
217
- for (const account of this.#config.accounts) {
218
- if (!this.#disabled.has(account.id) && idempotentKeys.includes(`${account.platform}/${account.id}`)) {
219
- this.#schedule(account.id);
220
- }
221
- }
222
219
  }
223
220
 
224
221
  const usable = started.filter((accountId) => !this.#disabled.has(accountId));
@@ -264,7 +261,14 @@ export class ChannelHost {
264
261
  }
265
262
  }
266
263
 
267
- const result = state.commitIngest(event);
264
+ // The event and its frozen outbound plan commit together. Classification and
265
+ // planning run only for a new insert, on the stored event with its ingressSeq;
266
+ // the frozen decision also governs whether a consumer error rolls the event back.
267
+ let notificationOnly = false;
268
+ const { result, created } = state.commitIngestWithPlan(event, (storedEvent) => {
269
+ notificationOnly = this.#notificationOnly?.(storedEvent) ?? false;
270
+ return notificationOnly ? [] : this.#planDeliveries(storedEvent);
271
+ });
268
272
  if (result.duplicate) {
269
273
  log.info("duplicate ingest skipped", { event: result.existingEventId });
270
274
  return { duplicate: true, eventId: result.existingEventId };
@@ -279,7 +283,7 @@ export class ChannelHost {
279
283
  const message = error instanceof Error ? error.message : String(error);
280
284
  // An inbound notification owns the ACK: roll back and fail the ingest so
281
285
  // the provider retries. Other consumer failures stay contained as before.
282
- if (this.#notificationOnly?.(stored)) {
286
+ if (notificationOnly) {
283
287
  state.deleteIngestEvent(stored.eventId);
284
288
  log.error(`inbound commit rolled back: ${message}`, { event: stored.eventId });
285
289
  throw error;
@@ -288,58 +292,64 @@ export class ChannelHost {
288
292
  }
289
293
  }
290
294
 
291
- if (this.#notificationOnly?.(stored)) {
295
+ if (notificationOnly) {
292
296
  log.info("inbound notification only; outbound rules skipped", { event: stored.eventId });
293
297
  return { duplicate: false, eventId: stored.eventId };
294
298
  }
295
299
 
296
- if (stored.kind === "message.forward_requested") {
297
- const selected = stored.selectedMessage;
300
+ for (const delivery of created) {
301
+ const endpoint = parseTarget(delivery.target);
302
+ if (endpoint && this.#disabled.has(endpoint.accountId)) {
303
+ state.markDelivery(delivery.deliveryId, "paused", {
304
+ lastError: "account disabled until restart",
305
+ });
306
+ }
307
+ log.info(`delivery enqueued rule=${delivery.ruleId}@${delivery.ruleVersion}`, {
308
+ delivery: delivery.deliveryId,
309
+ event: stored.eventId,
310
+ });
311
+ }
312
+ return { duplicate: false, eventId: stored.eventId };
313
+ }
314
+
315
+ /** Freeze matching rules into delivery plans; runs inside the ingest transaction. */
316
+ #planDeliveries(event: IngestEvent): PlannedDelivery[] {
317
+ if (event.kind === "message.forward_requested") {
318
+ const selected = event.selectedMessage;
298
319
  const reason = !selected
299
320
  ? "selectedMessage is required"
300
- : !sameEndpoint(selected.endpoint, stored.source)
321
+ : !sameEndpoint(selected.endpoint, event.source)
301
322
  ? "selectedMessage is outside the source room"
302
323
  : undefined;
303
324
  if (reason) {
304
- log.warn(`forward rejected: ${reason}`, { event: stored.eventId });
305
- return { duplicate: false, eventId: stored.eventId };
325
+ log.warn(`forward rejected: ${reason}`, { event: event.eventId });
326
+ return [];
306
327
  }
307
328
  }
308
329
 
309
- const requestedTarget = stored.kind === "message.forward_requested" ? stored.requestedTarget : undefined;
310
- for (const rule of matchRules(this.#config, stored)) {
311
- const targets: RuleTarget[] = [];
312
- const payloads: string[] = [];
330
+ const requestedTarget = event.kind === "message.forward_requested" ? event.requestedTarget : undefined;
331
+ const planned: PlannedDelivery[] = [];
332
+ for (const rule of matchRules(this.#config, event)) {
313
333
  for (const target of rule.to) {
314
334
  const endpoint = toEndpoint(this.#config, rule.id, target);
315
335
  if (requestedTarget && !sameEndpoint(endpoint, requestedTarget)) continue;
316
- const plan = planPayload(rule, stored, endpoint);
336
+ const plan = planPayload(rule, event, endpoint);
317
337
  if ("dropped" in plan) {
318
338
  log.warn(
319
339
  `rule ${rule.id}@${rule.version} dropped delivery to ${targetKey(endpoint)}: ${plan.dropped}`,
320
- { event: stored.eventId },
340
+ { event: event.eventId },
321
341
  );
322
342
  continue;
323
343
  }
324
- targets.push(target);
325
- payloads.push(JSON.stringify(plan.payload));
326
- }
327
- if (targets.length === 0) continue;
328
- const created = state.enqueueDeliveries(stored.eventId, rule, targets, payloads);
329
- for (const delivery of created) {
330
- const endpoint = parseTarget(delivery.target);
331
- if (endpoint && this.#disabled.has(endpoint.accountId)) {
332
- state.markDelivery(delivery.deliveryId, "paused", {
333
- lastError: "account disabled until restart",
334
- });
335
- }
336
- log.info(`delivery enqueued rule=${rule.id}@${rule.version}`, {
337
- delivery: delivery.deliveryId,
338
- event: stored.eventId,
344
+ planned.push({
345
+ ruleId: rule.id,
346
+ ruleVersion: rule.version,
347
+ target: targetKey(endpoint),
348
+ payload: JSON.stringify(plan.payload),
339
349
  });
340
350
  }
341
351
  }
342
- return { duplicate: false, eventId: stored.eventId };
352
+ return planned;
343
353
  }
344
354
 
345
355
  async stop(options: { abortInFlight?: boolean } = {}): Promise<void> {
@@ -375,6 +385,7 @@ export class ChannelHost {
375
385
 
376
386
  #schedule(accountId: string): void {
377
387
  if (!this.#running || this.#disabled.has(accountId)) return;
388
+ if (this.#timers.has(accountId)) return;
378
389
  const timer = setTimeout(() => {
379
390
  this.#timers.delete(accountId);
380
391
  if (!this.#running) return;
@@ -13,10 +13,6 @@ export function matchInboundRoutes(config: ChannelConfig, event: IngestEvent): I
13
13
  );
14
14
  }
15
15
 
16
- /**
17
- * Room-notification text. The native user id is opaque but stable; the account
18
- * label shows which external bot and avoids exposing the chat id in room content.
19
- */
20
16
  export function platformLabel(platform: string): string {
21
17
  const value = platform.trim();
22
18
  return value ? value[0]!.toUpperCase() + value.slice(1) : "Channel";
@@ -27,9 +23,10 @@ export function inboundRoomText(event: IngestEvent, route: InboundRoute): string
27
23
  const attachments = event.content?.attachments ?? [];
28
24
  if (!text && attachments.length === 0) return undefined;
29
25
  const actor = event.actor.nativeUserId || "unknown";
26
+ const actorField = event.actor.identityNamespace === "open_id" ? "open_id" : "user_id";
30
27
  const messageID = event.message?.nativeMessageId ?? event.providerEventId ?? "unknown";
31
28
  const names = attachments.map((attachment) =>
32
29
  attachment.kind === "image" ? "[image]" : `[file ${attachment.name}]`).join(", ");
33
30
  const body = text ? (text.length > MAX_RELAY_TEXT ? `${text.slice(0, MAX_RELAY_TEXT)}…` : text) : names;
34
- return `[${platformLabel(event.source.platform)} ${route.from.account}] message_id=${messageID} chat_id=${event.source.roomId} sender=${actor}: ${body}`;
35
- }
31
+ return `[${platformLabel(event.source.platform)} ${route.from.account}] message_id=${messageID} room_id=${event.source.roomId} ${actorField}=${actor}: ${body}`;
32
+ }
@@ -20,6 +20,8 @@ type Reply = {
20
20
  changes?: number;
21
21
  lastInsertRowid?: number;
22
22
  error?: Record<string, unknown>;
23
+ // The worker's connection is gone; the next top-level call must reconnect.
24
+ broken?: true;
23
25
  };
24
26
 
25
27
  type ReadyMessage = { type: "ready" } | { type: "fatal"; error?: Record<string, unknown> };
@@ -41,11 +43,22 @@ function databaseError(error: Record<string, unknown> | undefined): Error {
41
43
  return result;
42
44
  }
43
45
 
46
+ // A lost transport is not a retryable SQL condition: immediate() retries busy
47
+ // errors, and replaying a statement with an unknown outcome is unsafe.
48
+ function lostError(error: unknown): Error {
49
+ const cause = error instanceof Error ? error : new Error(String(error));
50
+ return Object.assign(new Error(`PostgreSQL connection lost: ${cause.message}`, { cause }), {
51
+ code: "PG_BRIDGE_LOST",
52
+ });
53
+ }
54
+
44
55
  export class PgDatabase implements StateDatabase {
45
- readonly #worker: Worker;
46
- readonly #port: MessagePort;
56
+ readonly #connectionString: string;
47
57
  readonly #timeout: number;
48
58
  readonly #lockTimeout: number;
59
+ #worker: Worker | undefined;
60
+ #port: MessagePort | undefined;
61
+ #generation = 0;
49
62
  #nextID = 1;
50
63
  #depth = 0;
51
64
  #savepoints = 0;
@@ -54,39 +67,90 @@ export class PgDatabase implements StateDatabase {
54
67
 
55
68
  constructor(connectionString: string, options: { timeout?: number } = {}) {
56
69
  if (!connectionString) throw new Error("PostgreSQL connection string is empty");
70
+ this.#connectionString = connectionString;
57
71
  this.#timeout = options.timeout ?? 5_000;
58
72
  this.#lockTimeout = Math.max(1, this.#timeout - 1_000);
73
+ this.#connect();
74
+ }
75
+
76
+ // A worker owns one pg.Client. After a timeout or a lost connection the old
77
+ // worker is disposed instead of reused; the next independent call builds a
78
+ // fresh generation. Work that was already sent is never replayed.
79
+ #connect(): void {
80
+ // Generations hide events from a worker that was already discarded, so a
81
+ // late error or exit cannot mark the replacement connection dead.
82
+ const generation = ++this.#generation;
59
83
  const ready = new SharedArrayBuffer(4);
60
84
  const { port1, port2 } = new MessageChannel();
85
+ const worker = new Worker(workerURL());
86
+ worker.unref();
87
+ port1.unref();
88
+ // A dying worker must not surface as an uncaught 'error' event. Break the
89
+ // bridge so the next top-level call reconnects.
90
+ worker.on("error", (error: Error) => this.#lose(generation, error));
91
+ worker.on("exit", (code: number) => this.#lose(generation, new Error(`PostgreSQL worker exited with code ${code}`)));
92
+ this.#worker = worker;
61
93
  this.#port = port1;
62
- this.#worker = new Worker(workerURL());
63
- this.#worker.unref();
64
- this.#port.unref();
65
94
  try {
66
95
  // No workerData: some Bun versions break `pg` when a worker starts with
67
96
  // any workerData. The default worker channel carries one init message
68
97
  // and transfers the request port.
69
- this.#worker.postMessage({
98
+ worker.postMessage({
70
99
  type: "init",
71
- connectionString,
100
+ connectionString: this.#connectionString,
72
101
  ready,
73
102
  statementTimeout: Math.max(1, this.#timeout - 500),
74
103
  port: port2,
75
104
  }, [port2]);
76
105
  } catch (error) {
77
- void this.#worker.terminate();
78
- this.#port.close();
106
+ this.#dispose();
79
107
  throw error;
80
108
  }
81
109
  const status = Atomics.wait(new Int32Array(ready), 0, 0, this.#timeout);
82
110
  if (status === "timed-out") {
83
- void this.#worker.terminate();
111
+ this.#dispose();
84
112
  throw new Error(`PostgreSQL bridge did not become ready within ${this.#timeout}ms`);
85
113
  }
86
- const message = receiveMessageOnPort(this.#port)?.message as ReadyMessage | undefined;
87
- if (message?.type === "fatal") {
88
- void this.#worker.terminate();
89
- throw databaseError(message.error);
114
+ const message = receiveMessageOnPort(port1)?.message as ReadyMessage | undefined;
115
+ // Only an explicit "ready" makes the bridge healthy; a silent exit between
116
+ // signalReady and this read must not be reported as a usable connection.
117
+ if (message?.type !== "ready") {
118
+ this.#dispose();
119
+ throw message?.type === "fatal"
120
+ ? databaseError(message.error)
121
+ : new Error("PostgreSQL bridge closed before signaling ready");
122
+ }
123
+ this.#broken = undefined;
124
+ }
125
+
126
+ #dispose(): void {
127
+ const port = this.#port;
128
+ const worker = this.#worker;
129
+ this.#port = undefined;
130
+ this.#worker = undefined;
131
+ try { port?.close(); } catch { /* already closed */ }
132
+ void worker?.terminate();
133
+ }
134
+
135
+ #lose(generation: number, error: Error): void {
136
+ if (generation !== this.#generation || this.#broken || this.#closed) return;
137
+ this.#broken = lostError(error);
138
+ this.#dispose();
139
+ }
140
+
141
+ // Fails fast inside a transaction: the old transaction is already lost, so
142
+ // reopening here would run its remaining statements outside that transaction.
143
+ // A closed handle never reopens, even when it is also marked lost.
144
+ #ensureOpen(): void {
145
+ if (this.#closed) throw new Error("PostgreSQL database is closed");
146
+ if (!this.#broken) return;
147
+ if (this.#depth > 0) throw this.#broken;
148
+ this.#dispose();
149
+ try {
150
+ this.#connect();
151
+ } catch (error) {
152
+ this.#broken = lostError(error);
153
+ throw this.#broken;
90
154
  }
91
155
  }
92
156
 
@@ -116,37 +180,39 @@ export class PgDatabase implements StateDatabase {
116
180
  close(): void {
117
181
  if (this.#closed) return;
118
182
  this.#closed = true;
119
- const signal = new SharedArrayBuffer(4);
120
- try {
121
- this.#port.postMessage({ type: "close", signal });
122
- // Give client.end() time to flush before a caller opens the next
123
- // connection (migration and restart tests rely on it).
124
- Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
125
- } catch { /* worker already gone */ }
126
- this.#port.close();
127
- void this.#worker.terminate();
183
+ const port = this.#port;
184
+ if (port && !this.#broken) {
185
+ const signal = new SharedArrayBuffer(4);
186
+ try {
187
+ port.postMessage({ type: "close", signal });
188
+ // Give client.end() time to flush before a caller opens the next
189
+ // connection (migration and restart tests rely on it).
190
+ Atomics.wait(new Int32Array(signal), 0, 0, 2_000);
191
+ } catch { /* worker already gone */ }
192
+ }
193
+ this.#dispose();
128
194
  }
129
195
 
130
196
  #run<T>(fn: () => T, immediate: boolean): T {
197
+ // A new transaction may reconnect, but once its depth is pinned every
198
+ // BEGIN, lock, COMMIT and ROLLBACK runs against the same connection
199
+ // generation. A lost transaction therefore fails on the old bridge instead
200
+ // of continuing on a fresh one.
201
+ this.#ensureOpen();
131
202
  const nested = this.#depth > 0;
132
203
  const savepoint = `chat_room_savepoint_${this.#savepoints++}`;
133
- if (nested) {
134
- this.exec(`SAVEPOINT ${savepoint}`);
135
- } else {
136
- // Deferred reads need one stable snapshot; immediate writers are
137
- // serialized by the transaction-level advisory lock.
138
- this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
139
- if (immediate) {
140
- try {
204
+ this.#depth++;
205
+ try {
206
+ if (nested) {
207
+ this.exec(`SAVEPOINT ${savepoint}`);
208
+ } else {
209
+ // Deferred reads need one stable snapshot; immediate writers are
210
+ // serialized by the transaction-level advisory lock.
211
+ this.exec(immediate ? "BEGIN" : "BEGIN ISOLATION LEVEL REPEATABLE READ");
212
+ if (immediate) {
141
213
  this.exec(`SET LOCAL lock_timeout = '${this.#lockTimeout}ms'; SELECT pg_advisory_xact_lock(hashtext('channeld-state')); SET LOCAL lock_timeout = 0`);
142
- } catch (error) {
143
- try { this.exec("ROLLBACK"); } catch { /* keep the original error */ }
144
- throw error;
145
214
  }
146
215
  }
147
- }
148
- this.#depth++;
149
- try {
150
216
  const result = fn();
151
217
  this.exec(nested ? `RELEASE ${savepoint}` : "COMMIT");
152
218
  return result;
@@ -161,27 +227,53 @@ export class PgDatabase implements StateDatabase {
161
227
  }
162
228
 
163
229
  #request(mode: "all" | "get" | "run" | "exec", sql: string, params: SQLQueryBindings[]): Reply {
164
- if (this.#broken) throw this.#broken;
165
- if (this.#closed) throw new Error("PostgreSQL database is closed");
230
+ this.#ensureOpen();
231
+ const port = this.#port as MessagePort;
166
232
  const id = this.#nextID++;
167
233
  const signal = new SharedArrayBuffer(4);
168
- this.#port.postMessage({ id, mode, sql, params, signal });
234
+ try {
235
+ port.postMessage({ id, mode, sql, params, signal });
236
+ } catch (error) {
237
+ const failure = lostError(error);
238
+ this.#fail(failure);
239
+ throw this.#broken ?? failure;
240
+ }
169
241
  const status = Atomics.wait(new Int32Array(signal), 0, 0, this.#timeout);
170
242
  if (status === "timed-out") {
171
- // The worker may still be inside the query. Its connection and queue are
172
- // no longer trustworthy, so fail closed rather than desynchronize later calls.
173
- this.#broken = Object.assign(
174
- new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the database connection must be reopened`),
243
+ // The worker may still be inside the statement, so its outcome is unknown.
244
+ // Terminating the worker aborts its transaction; the statement is never
245
+ // replayed and a later independent call reconnects.
246
+ const error = Object.assign(
247
+ new Error(`PostgreSQL bridge timed out after ${this.#timeout}ms; the connection reopens on the next operation`),
175
248
  { code: "PG_BRIDGE_TIMEOUT" },
176
249
  );
177
- throw this.#broken;
250
+ this.#fail(error);
251
+ throw error;
178
252
  }
179
- const message = receiveMessageOnPort(this.#port)?.message as Reply | undefined;
253
+ const message = receiveMessageOnPort(port)?.message as Reply | undefined;
180
254
  if (!message || message.id !== id) {
181
- this.#broken = Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
182
- throw this.#broken;
255
+ const error = this.#broken ??
256
+ Object.assign(new Error("PostgreSQL bridge reply out of sequence"), { code: "PG_BRIDGE_SEQUENCE" });
257
+ this.#fail(error);
258
+ throw error;
259
+ }
260
+ if (!message.ok) {
261
+ const error = databaseError(message.error);
262
+ if (message.broken) {
263
+ // A normal SQL error keeps the connection; a lost one cannot be
264
+ // repaired in place, so close it and let the next call reconnect.
265
+ const lost = lostError(error);
266
+ this.#fail(lost);
267
+ throw lost;
268
+ }
269
+ throw error;
183
270
  }
184
- if (!message.ok) throw databaseError(message.error);
185
271
  return message;
186
272
  }
273
+
274
+ #fail(error: Error): void {
275
+ if (this.#broken) return;
276
+ this.#broken = error;
277
+ this.#dispose();
278
+ }
187
279
  }