@alexsun-top/opencode-chat-room 0.8.0 → 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 (176) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE +2 -2
  3. package/README.md +40 -8
  4. package/README.zh-CN.md +40 -8
  5. package/cli.ts +27 -1
  6. package/dist/cli.js +5406 -3088
  7. package/package.json +25 -5
  8. package/packages/chat-room-channeld/README.md +111 -33
  9. package/packages/chat-room-channeld/src/adapter.ts +179 -7
  10. package/packages/chat-room-channeld/src/config.ts +63 -1
  11. package/packages/chat-room-channeld/src/delivery.ts +6 -1
  12. package/packages/chat-room-channeld/src/host-helpers.ts +11 -0
  13. package/packages/chat-room-channeld/src/host.ts +142 -9
  14. package/packages/chat-room-channeld/src/inbound.ts +35 -0
  15. package/packages/chat-room-channeld/src/protocol.ts +52 -1
  16. package/packages/chat-room-channeld/src/rules.ts +7 -2
  17. package/packages/chat-room-channeld/src/state.ts +17 -0
  18. package/packages/chat-room-channeld/src/stats.ts +43 -1
  19. package/plugin.ts +1 -1
  20. package/server/admin-state.ts +13 -13
  21. package/server/app.ts +95 -0
  22. package/server/assets/NOTICE.txt +2 -1
  23. package/server/assets/base.css +21 -9
  24. package/server/assets/chat/admin.js +0 -2
  25. package/server/assets/chat/announcements.js +69 -8
  26. package/server/assets/chat/chat-background.js +177 -0
  27. package/server/assets/chat/confirm-dialog.js +0 -1
  28. package/server/assets/chat/create-room-dialog.js +0 -1
  29. package/server/assets/chat/diagram-viewer.js +7 -1
  30. package/server/assets/chat/doc-preview.js +251 -46
  31. package/server/assets/chat/events.js +16 -5
  32. package/server/assets/chat/files.js +53 -7
  33. package/server/assets/chat/image-zoom.js +8 -1
  34. package/server/assets/chat/index.js +6 -2
  35. package/server/assets/chat/integration-account-schema.js +99 -0
  36. package/server/assets/chat/integration-editor.js +163 -0
  37. package/server/assets/chat/integration-values.js +124 -0
  38. package/server/assets/chat/integrations.js +648 -0
  39. package/server/assets/chat/locales/de.js +40 -4
  40. package/server/assets/chat/locales/es.js +40 -4
  41. package/server/assets/chat/locales/fr.js +40 -4
  42. package/server/assets/chat/locales/it.js +40 -4
  43. package/server/assets/chat/locales/ja.js +40 -4
  44. package/server/assets/chat/locales/ko.js +40 -4
  45. package/server/assets/chat/markdown-footnotes.js +1 -1
  46. package/server/assets/chat/markdown.js +45 -8
  47. package/server/assets/chat/messages.js +6 -5
  48. package/server/assets/chat/office-preview.js +69 -0
  49. package/server/assets/chat/palette.js +6 -1
  50. package/server/assets/chat/panels.js +56 -0
  51. package/server/assets/chat/recall.js +58 -7
  52. package/server/assets/chat/receipts.js +17 -6
  53. package/server/assets/chat/reminders.js +68 -9
  54. package/server/assets/chat/replies.js +0 -6
  55. package/server/assets/chat/resource-format.js +11 -0
  56. package/server/assets/chat/rooms.js +1 -6
  57. package/server/assets/chat/settings.js +98 -4
  58. package/server/assets/chat/shortcuts.js +0 -3
  59. package/server/assets/chat/side-pane.js +34 -10
  60. package/server/assets/chat/state.js +125 -12
  61. package/server/assets/chat/system-events.js +58 -0
  62. package/server/assets/chat/system-messages.js +32 -14
  63. package/server/assets/chat/task-row.js +0 -6
  64. package/server/assets/chat/tasks.js +119 -37
  65. package/server/assets/chat/window-controls.js +37 -0
  66. package/server/assets/code-highlight.css +71 -32
  67. package/server/assets/conversation.css +174 -31
  68. package/server/assets/doc-preview.css +40 -3
  69. package/server/assets/files.css +8 -0
  70. package/server/assets/fluent-icons.svg +2 -0
  71. package/server/assets/monaco/LICENSE +21 -0
  72. package/server/assets/monaco/ThirdPartyNotices.txt +448 -0
  73. package/server/assets/monaco/codicon-jdswhhtn.ttf +0 -0
  74. package/server/assets/monaco/editor.worker.js +45 -0
  75. package/server/assets/monaco/integration-rules.css +1 -0
  76. package/server/assets/monaco/integration-rules.js +1605 -0
  77. package/server/assets/monaco/json.worker.js +77 -0
  78. package/server/assets/office/THIRD-PARTY-NOTICES.txt +11 -0
  79. package/server/assets/office/docx.bundle.js +33 -0
  80. package/server/assets/office/licenses/docx-preview-LICENSE.txt +201 -0
  81. package/server/assets/office/licenses/echarts-LICENSE.txt +222 -0
  82. package/server/assets/office/licenses/jszip-LICENSE.txt +651 -0
  83. package/server/assets/office/licenses/lodash-LICENSE.txt +47 -0
  84. package/server/assets/office/licenses/pptx-preview-LICENSE.txt +8 -0
  85. package/server/assets/office/licenses/tslib-LICENSE.txt +12 -0
  86. package/server/assets/office/licenses/uuid-LICENSE.txt +9 -0
  87. package/server/assets/office/licenses/xlsx-LICENSE.txt +201 -0
  88. package/server/assets/office/licenses/zrender-LICENSE.txt +29 -0
  89. package/server/assets/office/pptx.bundle.js +104 -0
  90. package/server/assets/office/xlsx.bundle.js +141 -0
  91. package/server/assets/recall.css +5 -4
  92. package/server/assets/responsive.css +80 -11
  93. package/server/assets/settings.css +185 -9
  94. package/server/assets/tasks.css +57 -7
  95. package/server/assets/window-controls.css +36 -0
  96. package/server/channel-attachments.ts +133 -0
  97. package/server/channel-integration.ts +572 -0
  98. package/server/channel-settings.ts +77 -0
  99. package/server/channels.ts +274 -21
  100. package/server/chat-server.ts +32 -580
  101. package/server/chat.html +234 -34
  102. package/server/http-server.ts +3 -182
  103. package/server/manifest.webmanifest +1 -0
  104. package/server/resource-routes.ts +16 -16
  105. package/server/routes/inbox.ts +100 -0
  106. package/server/routes/pages.ts +83 -0
  107. package/server/routes/questions.ts +39 -0
  108. package/server/routes/room-actions.ts +162 -0
  109. package/server/routes/rooms.ts +160 -0
  110. package/server/startup.ts +84 -0
  111. package/server/sw.js +5 -0
  112. package/server/task-routes.ts +1 -1
  113. package/src/center/center-client.ts +3 -11
  114. package/src/config/file-config.ts +7 -54
  115. package/src/platform/http-server.ts +182 -0
  116. package/src/protocol/addressing.ts +21 -0
  117. package/src/protocol/config.ts +58 -0
  118. package/src/protocol/room.ts +51 -0
  119. package/src/rooms/resources.ts +26 -16
  120. package/src/rooms/room-service.ts +2 -48
  121. package/src/rooms/storage.ts +329 -0
  122. package/src/rooms/tasks.ts +21 -5
  123. package/src/runtime/watch.ts +1 -1
  124. package/src/state/pg-database.ts +183 -0
  125. package/src/state/pg-migrate.ts +175 -0
  126. package/src/state/pg-sql.mjs +175 -0
  127. package/src/state/pg-worker.mjs +133 -0
  128. package/src/state/sqlite-announcements.ts +25 -0
  129. package/src/state/sqlite-database.ts +130 -0
  130. package/src/state/sqlite-legacy.ts +90 -0
  131. package/src/state/sqlite-members.ts +155 -0
  132. package/src/state/sqlite-messages.ts +288 -0
  133. package/src/state/sqlite-resources.ts +39 -0
  134. package/src/state/sqlite-rooms.ts +194 -0
  135. package/src/state/sqlite-schema.ts +80 -0
  136. package/src/state/sqlite-state-store.ts +34 -0
  137. package/src/state/sqlite-state.ts +15 -897
  138. package/src/state/sqlite-tasks.ts +65 -0
  139. package/src/state/sqlite-transaction.ts +13 -0
  140. package/src/state/sqlite.ts +21 -1
  141. package/src/state/store.ts +5 -1
  142. package/src/tui/app.mjs +32 -19
  143. package/src/tui/config.mjs +12 -4
  144. package/src/tui/i18n.mjs +38 -0
  145. package/src/tui/info-app.mjs +50 -51
  146. package/src/tui/info-content.mjs +79 -44
  147. package/src/tui/join-app.mjs +9 -9
  148. package/src/tui/locales/en.mjs +349 -0
  149. package/src/tui/locales/zh-CN.mjs +349 -0
  150. package/src/tui/main.mjs +85 -37
  151. package/src/tui/markdown.mjs +3 -2
  152. package/src/tui/mentions.mjs +3 -1
  153. package/src/tui/message-app.mjs +22 -21
  154. package/src/tui/message-view.mjs +2 -1
  155. package/src/tui/palette-app.mjs +9 -8
  156. package/src/tui/palette.mjs +30 -24
  157. package/src/tui/prefs.mjs +92 -0
  158. package/src/tui/reminder-app.mjs +18 -17
  159. package/src/tui/room-settings-app.mjs +30 -28
  160. package/src/tui/settings-app.mjs +153 -0
  161. package/src/tui/ui-content.mjs +65 -86
  162. package/src/tui/ui-help.mjs +73 -0
  163. package/src/tui/ui-overlay-view.mjs +23 -7
  164. package/src/tui/ui-suggest.mjs +6 -5
  165. package/src/tui/ui-theme.mjs +37 -33
  166. package/src/tui/ui-view.mjs +22 -7
  167. package/src/tui/ui.mjs +15 -3
  168. package/src/web/editor.worker.ts +1 -0
  169. package/src/web/integration-rules-editor.ts +573 -0
  170. package/src/web/integration-rules.ts +26 -0
  171. package/src/web/integration-schema.ts +229 -0
  172. package/src/web/json.worker.ts +1 -0
  173. package/src/web/office-viewer.ts +221 -0
  174. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -499
  175. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -473
  176. package/server/assets/chat/forward.js +0 -69
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,13 +28,18 @@
28
28
  "src",
29
29
  "packages/chat-room-channeld/src",
30
30
  "packages/chat-room-channeld/dist/mock-adapter.js",
31
- "packages/chat-room-channeld/dist/feishu-adapter.js",
32
31
  "!src/tests",
33
32
  "!src/**/*.test.*",
34
33
  "!src/tui/test",
35
34
  "skills/chatroom/SKILL.md",
36
35
  "server/chat-server.ts",
36
+ "server/startup.ts",
37
+ "server/routes",
38
+ "server/app.ts",
37
39
  "server/channels.ts",
40
+ "server/channel-attachments.ts",
41
+ "server/channel-settings.ts",
42
+ "server/channel-integration.ts",
38
43
  "server/http-server.ts",
39
44
  "server/json-body.ts",
40
45
  "server/inbox.ts",
@@ -71,8 +76,10 @@
71
76
  "scripts": {
72
77
  "build:cli": "bun build cli.ts --target=node --packages external --outfile dist/cli.js >&2",
73
78
  "build:channeld-mock": "bun build packages/chat-room-channeld/src/mock-adapter.ts --target=node --packages external --outfile packages/chat-room-channeld/dist/mock-adapter.js >&2",
74
- "build:channeld-feishu": "bun build packages/chat-room-channeld/src/feishu-adapter.ts --target=node --packages external --outfile packages/chat-room-channeld/dist/feishu-adapter.js >&2",
75
- "prepack": "bun run build:cli && bun run build:channeld-mock && bun run build:channeld-feishu",
79
+ "build:adapter-feishu": "bun scripts/build-feishu-adapter.ts",
80
+ "build:monaco": "bun scripts/build-monaco.ts",
81
+ "build:office": "bun scripts/build-office.ts",
82
+ "prepack": "bun run build:cli && bun run build:channeld-mock && bun scripts/build-monaco.ts --quiet && bun scripts/build-office.ts --quiet",
76
83
  "server": "node cli.ts",
77
84
  "server:bun": "bun cli.ts",
78
85
  "server:deno": "deno run --allow-env --allow-read --allow-write --allow-net cli.ts",
@@ -85,18 +92,31 @@
85
92
  "devDependencies": {
86
93
  "@opencode/plugin": "2.0.29",
87
94
  "@types/bun": "latest",
95
+ "@types/pg": "^8.23.1",
96
+ "docx-preview": "0.4.1",
97
+ "jszip": "3.10.2",
98
+ "monaco-editor": "0.58.0",
88
99
  "playwright": "1.64.1",
89
- "shiki": "4.6.0"
100
+ "pptx-preview": "1.0.7",
101
+ "shiki": "4.6.0",
102
+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz"
90
103
  },
91
104
  "peerDependencies": {
92
105
  "typescript": "^5"
93
106
  },
94
107
  "dependencies": {
108
+ "@aws-sdk/client-s3": "^3.1178.0",
95
109
  "@opencode-ai/plugin": "^1.18.29",
96
110
  "@opencode/client": "2.0.32",
97
111
  "@opentui/core": "0.2.16",
98
112
  "croner": "11.0.0",
113
+ "pg": "^8.23.1",
99
114
  "yaml": "^2.9.0",
100
115
  "zod": "4.1.8"
116
+ },
117
+ "overrides": {
118
+ "echarts": "6.1.0",
119
+ "lodash": "4.18.1",
120
+ "uuid": "11.1.1"
101
121
  }
102
122
  }
@@ -5,15 +5,15 @@ IM endpoints through adapter child processes. Explicit rules turn a source-room
5
5
  event into frozen deliveries for target accounts; each adapter owns one IM
6
6
  account and speaks JSON-RPC over stdio.
7
7
 
8
- This is the 0.1 MVP: static rules, text messages, outbound adapters with text and Markdown cards, a mock
9
- adapter, and an outbound Feishu adapter. Inbound Feishu events are not
10
- implemented yet.
8
+ This package is published as `@alexsun-top/chat-room-channeld`. Platform
9
+ adapters, including Feishu, are single files under the top-level
10
+ `plugins/` directory, not separate npm packages; their inbound events can be
11
+ relayed into one chat-room as notifications and are never matched by outbound
12
+ rules. The core launches any adapter through the account's `adapter.command`.
11
13
 
12
- This package is bundled inside `@alexsun-top/opencode-chat-room` 0.8.0 as
13
- source plus the Feishu and mock adapter entry points. Standalone npm
14
- publication, and the `npx @alexsun-top/chat-room-channeld` form, are planned
15
- for 0.8.x. In 0.8.0 use `GET /channeld/status` on the ChatRoom server, or run
16
- the CLI from a checkout with Bun.
14
+ The core ships the source plus the mock adapter entry point. Use
15
+ `GET /channeld/status` on the ChatRoom server, or run the CLI from a checkout
16
+ with Bun.
17
17
 
18
18
  ## Run from a checkout
19
19
 
@@ -34,10 +34,11 @@ Inspect queue and integrity counts without writing the state file:
34
34
  bun src/cli.ts status --config channeld.yml
35
35
  ```
36
36
 
37
- `status` prints counts only: queue depth, oldest backlog, unknown, retryable and
38
- rate-limited deliveries, and source/integrity gaps. It never prints message text,
39
- rule ids, error details, provider message ids, room ids, or credentials. A missing
40
- state file or missing channel tables exit 1 with a clear error.
37
+ `status` prints counts and per-account runtime state: `started`, `failed`,
38
+ `disabled`, or `unknown` (no live host is attached to a CLI read), plus a short
39
+ sanitized `lastError` for failed/disabled accounts. It never prints message text,
40
+ rule ids, provider message ids, room ids, or credentials. A missing state file or
41
+ missing channel tables exit 1 with a clear error.
41
42
 
42
43
  Run the mock adapter on stdio (the host normally spawns it):
43
44
 
@@ -91,11 +92,48 @@ Account ids and rule `(id, version)` pairs must be unique. Only the highest
91
92
  configured version of each rule id is active: an explicit newer version
92
93
  replaces the older definition.
93
94
 
95
+ Each account may add an `env` map for secrets and per-platform settings. Keys
96
+ must match `/^[A-Za-z_][A-Za-z0-9_]*$/`, values are strings, and a map holds at
97
+ most 64 variables. The adapter child inherits the host environment, then receives
98
+ the account `env`, then the forced `CHANNELD_ACCOUNT_ID` and `CHANNELD_PLATFORM`
99
+ values; configuring either reserved key is rejected. Status output never includes
100
+ env values.
101
+
102
+ An optional top-level `inbound` array turns external events into room notifications
103
+ in the center. It is separate from `rules`: an inbound event is committed, written
104
+ to its target room once, and then skipped by every outbound rule, so it cannot
105
+ ping-pong back to the source.
106
+
107
+ ```yaml
108
+ inbound:
109
+ - from: { platform: feishu, account: feishu-main, room: oc_xxx }
110
+ to: { room: lab }
111
+ ```
112
+
113
+ `from.room` is the Feishu `chat_id`; `to.room` is the chat-room id. An omitted
114
+ `from.event` matches every kind. A source account must exist and its platform must
115
+ match. The center appends one system-style message, `[Feishu <account>] <open_id>:
116
+ <text>`, with a marker row in the room database; the marker and message share one
117
+ transaction, so a transport retry cannot duplicate it. If the room write fails, the
118
+ center rolls the channel event back and the adapter acknowledges failure, so Feishu
119
+ retries. A room that stays missing keeps failing until it is created.
120
+
121
+ ```yaml
122
+ accounts:
123
+ - id: feishu-main
124
+ platform: feishu
125
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"] }
126
+ env: { FEISHU_APP_ID: "cli_xxx", FEISHU_APP_SECRET: "xxx" }
127
+ ```
128
+
94
129
  ## Adapter protocol
95
130
 
96
- The host spawns each adapter with `CHANNELD_ACCOUNT_ID` and
97
- `CHANNELD_PLATFORM`. Both directions use newline-delimited JSON-RPC 2.0 on
98
- stdio. **stdout carries protocol frames only; all adapter logs go to stderr.**
131
+ The host spawns each adapter with `CHANNELD_ACCOUNT_ID`,
132
+ `CHANNELD_PLATFORM`, and that account's configured `env`. Both directions use
133
+ newline-delimited JSON-RPC 2.0 on stdio. An `initialize` or `start` result may
134
+ include `platform`; when it differs from the configured account platform, that
135
+ adapter is stopped and only that account is marked `failed` (its queue pauses)
136
+ while the host and other accounts keep running. **stdout carries protocol frames only; all adapter logs go to stderr.**
99
137
  An invalid stdout frame disables that account, stops its adapter, and leaves its
100
138
  deliveries paused; other accounts keep running. Frames are JSON objects limited
101
139
  to 1 MiB (`MAX_FRAME_BYTES`). Host request ids start with `host-`, adapter
@@ -129,13 +167,30 @@ from room `in` after starting, so the relay can be exercised end to end.
129
167
  `CHANNELD_MOCK_ECHO=1` makes it emit a provider echo right after a `send` result;
130
168
  `CHANNELD_MOCK_ECHO_DELAY_MS` delays that result to exercise buffered ingests.
131
169
 
132
- ## Feishu outbound adapter
133
-
134
- `dist/feishu-adapter.js` is an outbound-only adapter for Feishu OpenAPI
135
- messages. It sends interactive cards using `lark_md` inline formatting and
136
- declares `reply: "none"`; native Feishu reply/quote requires a Feishu parent
137
- message and is deferred with inbound support. It speaks the same stdio JSON-RPC protocol as the mock adapter and
138
- has no room or session concepts. Inbound Feishu events are planned for 0.8.x.
170
+ ## Feishu adapter
171
+
172
+ The Feishu adapter is the generated typed single-file adapter
173
+ `plugins/feishu/dist/feishu-adapter.ts`, produced by concatenating the typed
174
+ source under `plugins/feishu/src` without a bundler so its TypeScript
175
+ annotations stay in the file. It is attached to the GitHub Release instead of being shipped inside the root
176
+ `@alexsun-top/opencode-chat-room` package and runs directly under Node 22.18+
177
+ through native type stripping (erasable syntax only: no `enum`, `namespace`, or
178
+ constructor parameter properties). Outbound it sends interactive
179
+ cards and can reply natively to a Feishu message; inbound it can receive group
180
+ messages over the event long connection. It speaks the same stdio JSON-RPC protocol
181
+ as the mock adapter and has no room or session concepts.
182
+
183
+ Cards default to card 1.0 with `lark_md`, which keeps the 0.8.0 payload stable.
184
+ Set `FEISHU_CARD_VERSION=2.0` to opt into card 2.0 (`schema: "2.0"` with a
185
+ `markdown` element), where headings, lists, and fenced code render as block
186
+ Markdown. Any other value fails `initialize`.
187
+
188
+ A payload `parent` with `endpoint.platform: "feishu"`, the same account, and a
189
+ non-empty `nativeMessageId` is sent with
190
+ `POST /open-apis/im/v1/messages/{parent_id}/reply`; the body has no `receive_id`.
191
+ Without a usable Feishu parent the send uses the normal chat endpoint. The center
192
+ fills that parent when a forwarded room reply's `answer_to` parent was already
193
+ delivered to the same target (`channel_echoes` keeps the provider native id).
139
194
 
140
195
  The adapter command is resolved from the host process working directory, so
141
196
  use an absolute path unless the host starts in this package directory.
@@ -146,15 +201,30 @@ The child process reads:
146
201
  - `FEISHU_APP_SECRET` (required)
147
202
  - `FEISHU_BASE_URL` (optional, default `https://open.feishu.cn`)
148
203
  - `FEISHU_HTTP_TIMEOUT_MS` (optional, default `10000`)
204
+ - `FEISHU_CARD_VERSION` (optional, `1.0` default or `2.0`)
205
+ - `FEISHU_INBOUND` (optional, `1` enables the event long connection)
206
+ - `FEISHU_INBOUND_CHATS` (required with `FEISHU_INBOUND=1`; comma-separated
207
+ group `chat_id` allowlist)
149
208
 
150
209
  Set these in the host environment; the host passes its environment to adapter
151
210
  child processes.
152
211
 
212
+ Inbound requires the app to use long-connection event subscription in the Feishu
213
+ developer console and to subscribe `im.message.receive_v1`; the bot must already
214
+ be in each allowlisted group. The adapter obtains the WebSocket URL from
215
+ `POST /callback/ws/endpoint`, pings, reassembles fragmented frames, and
216
+ acknowledges only after the host commits the ingest. Only group `text` and `post`
217
+ messages from human senders in an allowlisted chat are mapped. Bot/self senders,
218
+ other chats, other event types, other apps, and unsupported message types are
219
+ acknowledged without ingest. A long-connection start failure logs a warning,
220
+ keeps the account started for outbound sends, and reports a sanitized
221
+ `inbound failed: ...` in the account status; outbound forwarding keeps working.
222
+
153
223
  ```yaml
154
224
  accounts:
155
225
  - id: feishu-bot
156
226
  platform: feishu
157
- adapter: { command: ["node", "/opt/chatroom/dist/feishu-adapter.js"], runtime: "node" }
227
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"], runtime: "node" }
158
228
  rules:
159
229
  - id: to-feishu
160
230
  version: 1
@@ -168,10 +238,11 @@ The target room is the Feishu `chat_id`, so an endpoint
168
238
 
169
239
  `initialize` fails when a credential is missing. `start` fetches a tenant access
170
240
  token, so rejected credentials disable only this account. Tokens are cached and
171
- refreshed when less than 30 minutes remain. A send posts an interactive
172
- Markdown card (`msg_type: "interactive"` with a `lark_md` element) and a `uuid`
173
- derived from the delivery idempotency key, so retrying the same delivery cannot
174
- create a second message.
241
+ refreshed when less than 30 minutes remain. A send posts an interactive card and
242
+ a `uuid` derived from the delivery idempotency key, so retrying the same delivery
243
+ cannot create a second message. Card 1.0 uses one `lark_md` element; card 2.0
244
+ uses one `markdown` element. A Feishu parent reference turns the send into a native
245
+ reply to that message.
175
246
 
176
247
  Send outcomes:
177
248
 
@@ -204,9 +275,16 @@ delivery in `unknown` and never retries automatically; `paused` keeps a disabled
204
275
  account's rows out of every claim until the next host start. An adapter that
205
276
  fails to start or writes non-protocol stdout disables only that account until
206
277
  restart; its queued deliveries move to `paused` and return to `pending` when the
207
- host starts again. On disable or crash, in-flight deliveries move to `unknown`
208
- with the reason; a host start resets stale `in_flight` rows from a previous
209
- crash to `pending`. If every account becomes disabled at runtime, the host logs
278
+ host starts again. Inbound room notifications add one small
279
+ `channel_inbound_relays(event_id, room_id)` marker table to the room database;
280
+ it exists only to make the room append idempotent. Per-account `readChannelStats` states are `started` (adapter
281
+ running), `failed` (startup failure, including a platform mismatch), `disabled`
282
+ (disabled at runtime), or `unknown` without a live host. `lastError` is capped,
283
+ flattened to one line, and redacts credential-shaped `token=…`/`secret=…`
284
+ fragments. On disable or crash, in-flight deliveries move to `unknown`
285
+ with the reason; a deliberate host stop also settles remaining in-flight rows as
286
+ `unknown`, so a centered reload cannot auto-resend them. A host start resets
287
+ stale `in_flight` rows from a previous crash to `pending`. If every account becomes disabled at runtime, the host logs
210
288
  `all accounts disabled; host idle until restart` and stays alive; only a startup
211
289
  with zero usable adapters fails. `onUnsupported: drop` skips empty renders; otherwise the
212
290
  payload carries an `attachment/format unsupported` notice. Replies without a
@@ -237,6 +315,6 @@ same terminal result event and message.
237
315
  - no config hot reload — rule changes require a restart (each delivery still freezes ruleId + ruleVersion + rendered payload);
238
316
  - no one-click manual resend command — `unknown` deliveries only guarantee no duplicate delivery row if resent (unique idempotency key); they are never auto-resent;
239
317
  - no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
240
- - no attachments, no rule UI, no multi-tenant permission model, no inbound
241
- Feishu events (the Feishu adapter is outbound only), no exactly-once
242
- guarantee.
318
+ - no attachments, no rule UI, no multi-tenant permission model, no exactly-once
319
+ guarantee (inbound room notifications are idempotent per event and route, but
320
+ a crash between the ACK and Feishu's next retry can still lose an event).
@@ -14,6 +14,8 @@ import {
14
14
  rpcRequest,
15
15
  rpcResult,
16
16
  type Endpoint,
17
+ type AccountField,
18
+ type AdapterCapabilities,
17
19
  type IngestEvent,
18
20
  type JsonRpcId,
19
21
  type MessageRef,
@@ -32,6 +34,8 @@ export interface AdapterContext {
32
34
  onIngest(event: IngestEvent): Promise<{ duplicate: boolean; eventId?: string }>;
33
35
  onExit(code: number | null, signal: NodeJS.Signals | null): void;
34
36
  onUnavailable?(reason: string): void;
37
+ /** Optional adapter health, e.g. inbound long-connection readiness. */
38
+ onStatus?(status: { inbound?: string; detail?: string }): void;
35
39
  }
36
40
 
37
41
  export interface AdapterProcessOptions extends AdapterContext {
@@ -59,11 +63,104 @@ const STDERR_TAIL_LIMIT = 4096;
59
63
  const DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;
60
64
  const DEFAULT_SEND_TIMEOUT_MS = 15_000;
61
65
 
66
+ const ADAPTER_NODE_OPTIONS = [
67
+ "--experimental-transform-types",
68
+ "--disable-warning=ExperimentalWarning",
69
+ ] as const;
70
+
71
+ /**
72
+ * Adapter children execute uploaded .ts plugins, so they get Node's full
73
+ * TypeScript transform; the server process itself stays strip-only.
74
+ */
75
+ export function adapterChildEnv(account: AccountConfig): NodeJS.ProcessEnv {
76
+ const env = { ...process.env, ...account.env };
77
+ let options = env.NODE_OPTIONS?.trim() ?? "";
78
+ for (const flag of ADAPTER_NODE_OPTIONS) {
79
+ if (!options.split(/\s+/).includes(flag)) options = options ? `${options} ${flag}` : flag;
80
+ }
81
+ env.NODE_OPTIONS = options;
82
+ // Forced after account env: config validation also rejects these keys.
83
+ env.CHANNELD_ACCOUNT_ID = account.id;
84
+ env.CHANNELD_PLATFORM = account.platform;
85
+ return env;
86
+ }
87
+
88
+ /** Keep only well-formed adapter-declared facts; unknown fields are ignored. */
89
+ function readAccountFields(value: unknown): AccountField[] | undefined {
90
+ if (!Array.isArray(value)) return undefined;
91
+ const fields: AccountField[] = [];
92
+ const seen = new Set<string>();
93
+ for (const item of value) {
94
+ if (!item || typeof item !== "object") continue;
95
+ const raw = item as Record<string, unknown>;
96
+ const key = typeof raw.key === "string" ? raw.key.trim() : "";
97
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || seen.has(key)) continue;
98
+ const field: AccountField = { key };
99
+ if (typeof raw.label === "string" && raw.label.trim()) field.label = raw.label.trim();
100
+ if (typeof raw.type === "string" && ["string", "secret", "boolean", "number", "select"].includes(raw.type)) {
101
+ field.type = raw.type as AccountField["type"];
102
+ }
103
+ if (raw.required === true) field.required = true;
104
+ if (typeof raw.default === "string") field.default = raw.default;
105
+ if (typeof raw.description === "string" && raw.description.trim()) field.description = raw.description.trim();
106
+ if (Array.isArray(raw.options)) {
107
+ const options = raw.options
108
+ .filter((option): option is Record<string, unknown> => Boolean(option) && typeof option === "object")
109
+ .map((option) => typeof option.value === "string" && option.value
110
+ ? { value: option.value, ...(typeof option.label === "string" && option.label ? { label: option.label } : {}) }
111
+ : undefined)
112
+ .filter((option): option is { value: string; label?: string } => Boolean(option));
113
+ if (options.length) field.options = options;
114
+ }
115
+ seen.add(key);
116
+ fields.push(field);
117
+ }
118
+ return fields.length ? fields : undefined;
119
+ }
120
+
121
+ function readCapabilities(result: unknown, accountId: string): AdapterCapabilities | undefined {
122
+ if (!result || typeof result !== "object") return undefined;
123
+ const accounts = (result as { accounts?: unknown }).accounts;
124
+ if (!accounts || typeof accounts !== "object") return undefined;
125
+ const raw = (accounts as Record<string, unknown>)[accountId];
126
+ if (!raw || typeof raw !== "object") return undefined;
127
+ const entry = raw as Record<string, unknown>;
128
+ const capabilities: AdapterCapabilities = {};
129
+ if (typeof entry.displayName === "string" && entry.displayName.trim()) {
130
+ capabilities.displayName = entry.displayName.trim();
131
+ }
132
+ const attachment = entry.attachments;
133
+ if (attachment && typeof attachment === "object") {
134
+ const value = attachment as Record<string, unknown>;
135
+ const kinds = Array.isArray(value.kinds)
136
+ ? value.kinds.filter((kind): kind is "image" | "file" => kind === "image" || kind === "file")
137
+ : [];
138
+ if (kinds.length) {
139
+ capabilities.attachments = { kinds };
140
+ if (Number.isSafeInteger(value.imageMaxBytes) && (value.imageMaxBytes as number) > 0) {
141
+ capabilities.attachments.imageMaxBytes = value.imageMaxBytes as number;
142
+ }
143
+ if (Number.isSafeInteger(value.fileMaxBytes) && (value.fileMaxBytes as number) > 0) {
144
+ capabilities.attachments.fileMaxBytes = value.fileMaxBytes as number;
145
+ }
146
+ }
147
+ }
148
+ const account = entry.account;
149
+ if (account && typeof account === "object") {
150
+ const value = account as Record<string, unknown>;
151
+ const schema = readAccountFields(value.schema);
152
+ const env = readAccountFields(value.env);
153
+ if (schema || env) capabilities.account = { ...(schema ? { schema } : {}), ...(env ? { env } : {}) };
154
+ }
155
+ return Object.keys(capabilities).length ? capabilities : undefined;
156
+ }
157
+
62
158
  export class AdapterProcess {
63
159
  readonly #account: AccountConfig;
64
160
  readonly #onIngest: AdapterContext["onIngest"];
65
161
  readonly #onExit: AdapterContext["onExit"];
66
162
  readonly #onUnavailable: AdapterContext["onUnavailable"];
163
+ readonly #onStatus: AdapterContext["onStatus"];
67
164
  readonly #initializeTimeoutMs: number;
68
165
  readonly #sendTimeoutMs: number;
69
166
  readonly #pending = new Map<string, PendingCall>();
@@ -75,12 +172,14 @@ export class AdapterProcess {
75
172
  #stopping = false;
76
173
  #gone = false;
77
174
  #pollutionError?: Error;
175
+ #capabilities?: AdapterCapabilities;
78
176
 
79
177
  constructor(options: AdapterProcessOptions) {
80
178
  this.#account = options.account;
81
179
  this.#onIngest = options.onIngest;
82
180
  this.#onExit = options.onExit;
83
181
  this.#onUnavailable = options.onUnavailable;
182
+ this.#onStatus = options.onStatus;
84
183
  this.#initializeTimeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;
85
184
  this.#sendTimeoutMs = options.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
86
185
  }
@@ -89,23 +188,23 @@ export class AdapterProcess {
89
188
  return this.#account.id;
90
189
  }
91
190
 
191
+ get capabilities(): AdapterCapabilities | undefined {
192
+ return this.#capabilities;
193
+ }
194
+
92
195
  async start(): Promise<void> {
93
196
  if (this.#child) throw new Error(`adapter ${this.#account.id} already started`);
94
197
  const [command, ...args] = this.#account.adapter.command;
95
198
  if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
96
199
  const child = spawn(command, args, {
97
200
  stdio: ["pipe", "pipe", "pipe"],
98
- env: {
99
- ...process.env,
100
- CHANNELD_ACCOUNT_ID: this.#account.id,
101
- CHANNELD_PLATFORM: this.#account.platform,
102
- },
201
+ env: adapterChildEnv(this.#account),
103
202
  });
104
203
  this.#child = child;
105
204
  this.#attach(child);
106
205
 
107
206
  try {
108
- await this.#call(
207
+ const initialized = await this.#call(
109
208
  "initialize",
110
209
  {
111
210
  protocolVersions: [PROTOCOL_VERSION],
@@ -117,11 +216,14 @@ export class AdapterProcess {
117
216
  },
118
217
  this.#initializeTimeoutMs,
119
218
  );
120
- await this.#call(
219
+ this.#assertReportedPlatform("initialize", initialized);
220
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
221
+ const started = await this.#call(
121
222
  "start",
122
223
  { accounts: [this.#account.id], cursors: {} },
123
224
  this.#initializeTimeoutMs,
124
225
  );
226
+ this.#assertReportedPlatform("start", started);
125
227
  } catch (error) {
126
228
  const tail = this.#stderrTail.trim();
127
229
  const message = this.#pollutionError?.message
@@ -137,6 +239,50 @@ export class AdapterProcess {
137
239
  log.info("adapter started", { account: this.#account.id });
138
240
  }
139
241
 
242
+ /**
243
+ * Read-only handshake used when a plugin is uploaded: initialize only, then
244
+ * kill. It does not start the account and does not need credentials.
245
+ */
246
+ async probe(): Promise<{ platform?: string; capabilities?: AdapterCapabilities }> {
247
+ if (this.#child) throw new Error(`adapter ${this.#account.id} already started`);
248
+ const [command, ...args] = this.#account.adapter.command;
249
+ if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
250
+ const child = spawn(command, args, {
251
+ stdio: ["pipe", "pipe", "pipe"],
252
+ env: adapterChildEnv(this.#account),
253
+ });
254
+ this.#child = child;
255
+ this.#attach(child);
256
+ try {
257
+ const initialized = await this.#call(
258
+ "initialize",
259
+ {
260
+ protocolVersions: [PROTOCOL_VERSION],
261
+ eventSchemas: [EVENT_SCHEMA_VERSION],
262
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
263
+ platform: this.#account.platform,
264
+ accounts: [this.#account.id],
265
+ maxFrameBytes: MAX_FRAME_BYTES,
266
+ },
267
+ this.#initializeTimeoutMs,
268
+ );
269
+ const reported = initialized && typeof initialized === "object"
270
+ ? (initialized as { platform?: unknown }).platform
271
+ : undefined;
272
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
273
+ return {
274
+ ...(typeof reported === "string" && reported.trim() ? { platform: reported.trim() } : {}),
275
+ ...(this.#capabilities ? { capabilities: this.#capabilities } : {}),
276
+ };
277
+ } catch (error) {
278
+ const tail = this.#stderrTail.trim();
279
+ const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
280
+ throw new Error(`adapter probe failed: ${message}${tail ? `\nstderr:\n${tail}` : ""}`);
281
+ } finally {
282
+ await this.stop().catch(() => undefined);
283
+ }
284
+ }
285
+
140
286
  /**
141
287
  * Send one delivery. Platform outcomes are returned; protocol failures and
142
288
  * timeouts become state "unknown" and never throw.
@@ -212,6 +358,21 @@ export class AdapterProcess {
212
358
  }
213
359
  }
214
360
 
361
+ /** A result may declare its platform; a mismatch makes this account unusable. */
362
+ #assertReportedPlatform(method: string, result: unknown): void {
363
+ if (!result || typeof result !== "object") return;
364
+ const reported = (result as { platform?: unknown }).platform;
365
+ if (reported === undefined) return;
366
+ if (typeof reported !== "string" || !reported.trim()) {
367
+ throw new Error(`${method} returned an invalid platform`);
368
+ }
369
+ if (reported !== this.#account.platform) {
370
+ throw new Error(
371
+ `${method} reported platform "${reported}" but account ${this.#account.id} is configured for "${this.#account.platform}"`,
372
+ );
373
+ }
374
+ }
375
+
215
376
  #attach(child: ChildProcessWithoutNullStreams): void {
216
377
  child.stdin.on("error", (error: Error) => this.#handleStdioError("stdin", error));
217
378
  child.stdout.on("error", (error: Error) => this.#handleStdioError("stdout", error));
@@ -297,6 +458,17 @@ export class AdapterProcess {
297
458
  child.stdin,
298
459
  rpcResult(id, result.duplicate ? { duplicate: true } : { committed: true }),
299
460
  );
461
+ } else if (method === "status") {
462
+ const input = (params ?? {}) as { inbound?: unknown; detail?: unknown };
463
+ try {
464
+ this.#onStatus?.({
465
+ inbound: typeof input.inbound === "string" ? input.inbound : undefined,
466
+ detail: typeof input.detail === "string" ? input.detail : undefined,
467
+ });
468
+ } catch {
469
+ // Status is advisory; a consumer failure must not break the adapter.
470
+ }
471
+ await writeFrame(child.stdin, rpcResult(id, { ok: true }));
300
472
  } else if (method === "ping") {
301
473
  await writeFrame(child.stdin, rpcResult(id, { pong: true }));
302
474
  } else {
@@ -31,12 +31,22 @@ export interface AccountConfig {
31
31
  id: string;
32
32
  platform: string;
33
33
  adapter: { command: string[]; runtime?: string };
34
+ /** Extra environment variables passed only to this account's adapter process. */
35
+ env?: Record<string, string>;
36
+ }
37
+
38
+ /** A center-only route: an inbound IM event becomes a room notification. */
39
+ export interface InboundRoute {
40
+ from: RuleSource;
41
+ to: { room: string };
34
42
  }
35
43
 
36
44
  export interface ChannelConfig {
37
45
  stateFile: string;
38
46
  accounts: AccountConfig[];
39
47
  rules: RuleConfig[];
48
+ /** Room notifications for inbound events; never matched by outbound rules. */
49
+ inbound: InboundRoute[];
40
50
  }
41
51
 
42
52
  type RecordValue = Record<string, unknown>;
@@ -49,6 +59,11 @@ function record(value: unknown, where: string): RecordValue {
49
59
  }
50
60
 
51
61
  const IDENTIFIER = /^[A-Za-z0-9._-]+$/;
62
+ const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
63
+ const MAX_ACCOUNT_ENV = 64;
64
+ const MAX_ENV_VALUE = 8192;
65
+ // The host writes these two after the account env, so a config must not claim them.
66
+ const RESERVED_ENV = new Set(["CHANNELD_ACCOUNT_ID", "CHANNELD_PLATFORM"]);
52
67
 
53
68
  function stringValue(value: unknown, where: string): string {
54
69
  if (typeof value !== "string" || !value.trim()) {
@@ -108,6 +123,34 @@ function parseTransform(value: unknown, where: string): Transform {
108
123
  }
109
124
  }
110
125
 
126
+ function parseAccountEnv(value: unknown, where: string): Record<string, string> | undefined {
127
+ if (value === undefined) return undefined;
128
+ const raw = record(value, where);
129
+ const entries = Object.entries(raw);
130
+ if (entries.length > MAX_ACCOUNT_ENV) {
131
+ throw new ConfigError(`config: ${where} must contain at most ${MAX_ACCOUNT_ENV} variables`);
132
+ }
133
+ const env: Array<[string, string]> = [];
134
+ for (const [key, item] of entries) {
135
+ if (!ENV_KEY.test(key)) {
136
+ throw new ConfigError(
137
+ `config: ${where}.${key} must match /^[A-Za-z_][A-Za-z0-9_]*$/ (letters, digits, underscore; cannot start with a digit)`,
138
+ );
139
+ }
140
+ if (RESERVED_ENV.has(key)) {
141
+ throw new ConfigError(`config: ${where}.${key} is reserved by the channeld protocol`);
142
+ }
143
+ if (typeof item !== "string") {
144
+ throw new ConfigError(`config: ${where}.${key} must be a string`);
145
+ }
146
+ if (item.length > MAX_ENV_VALUE) {
147
+ throw new ConfigError(`config: ${where}.${key} must be at most ${MAX_ENV_VALUE} characters`);
148
+ }
149
+ env.push([key, item]);
150
+ }
151
+ return Object.fromEntries(env);
152
+ }
153
+
111
154
  function parseAccount(value: unknown, where: string): AccountConfig {
112
155
  const raw = record(value, where);
113
156
  const adapter = record(raw.adapter, `${where}.adapter`);
@@ -118,6 +161,20 @@ function parseAccount(value: unknown, where: string): AccountConfig {
118
161
  id: identifierValue(raw.id, `${where}.id`),
119
162
  platform: identifierValue(raw.platform, `${where}.platform`),
120
163
  adapter: { command, runtime: optionalString(adapter.runtime, `${where}.adapter.runtime`) },
164
+ env: parseAccountEnv(raw.env, `${where}.env`),
165
+ };
166
+ }
167
+
168
+ function parseInbound(value: unknown, where: string): InboundRoute {
169
+ const raw = record(value, where);
170
+ const from = record(raw.from, `${where}.from`);
171
+ const to = record(raw.to, `${where}.to`);
172
+ return {
173
+ from: {
174
+ ...parseTarget({ platform: from.platform, account: from.account, room: from.room }, `${where}.from`),
175
+ event: optionalString(from.event, `${where}.from.event`),
176
+ },
177
+ to: { room: stringValue(to.room, `${where}.to.room`) },
121
178
  };
122
179
  }
123
180
 
@@ -170,6 +227,11 @@ export function parseConfig(value: unknown): ChannelConfig {
170
227
  const rules = raw.rules === undefined
171
228
  ? []
172
229
  : arrayValueAllowEmpty(raw.rules, "rules").map((item, index) => parseRule(item, `rules[${index}]`));
230
+ const inbound = raw.inbound === undefined
231
+ ? []
232
+ : arrayValueAllowEmpty(raw.inbound, "inbound").map((item, index) =>
233
+ parseInbound(item, `inbound[${index}]`),
234
+ );
173
235
 
174
236
  const accountIds = new Set<string>();
175
237
  for (const account of accounts) {
@@ -182,7 +244,7 @@ export function parseConfig(value: unknown): ChannelConfig {
182
244
  if (ruleKeys.has(key)) throw new ConfigError(`config: duplicate rule "${rule.id}" version ${rule.version}`);
183
245
  ruleKeys.add(key);
184
246
  }
185
- return { stateFile, accounts, rules };
247
+ return { stateFile, accounts, rules, inbound };
186
248
  }
187
249
 
188
250
  /** Load a config file. YAML parsing also accepts JSON documents. */