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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/README.md +18 -62
  3. package/README.zh-CN.md +25 -69
  4. package/dist/cli.js +1008 -274
  5. package/package.json +10 -7
  6. package/packages/chat-room-channeld/README.md +42 -15
  7. package/packages/chat-room-channeld/dist/mock-adapter.js +5 -5
  8. package/packages/chat-room-channeld/src/adapter.ts +150 -7
  9. package/packages/chat-room-channeld/src/cli.ts +72 -5
  10. package/packages/chat-room-channeld/src/host.ts +41 -11
  11. package/packages/chat-room-channeld/src/inbound.ts +13 -4
  12. package/packages/chat-room-channeld/src/pg/database.ts +187 -0
  13. package/packages/chat-room-channeld/src/pg/migrate.ts +150 -0
  14. package/packages/chat-room-channeld/src/pg/schema.ts +60 -0
  15. package/packages/chat-room-channeld/src/pg/sql.mjs +175 -0
  16. package/packages/chat-room-channeld/src/pg/sqlite.ts +100 -0
  17. package/packages/chat-room-channeld/src/pg/worker.mjs +133 -0
  18. package/packages/chat-room-channeld/src/protocol.ts +53 -1
  19. package/packages/chat-room-channeld/src/rules.ts +7 -2
  20. package/packages/chat-room-channeld/src/state.ts +73 -97
  21. package/packages/chat-room-channeld/src/stats.ts +140 -109
  22. package/plugin.ts +1 -1
  23. package/server/assets/base.css +11 -3
  24. package/server/assets/chat/admin-badge.js +32 -30
  25. package/server/assets/chat/admin.js +198 -163
  26. package/server/assets/chat/announcements.js +295 -210
  27. package/server/assets/chat/attachment-store.js +106 -75
  28. package/server/assets/chat/attachments.js +686 -441
  29. package/server/assets/chat/chat-background.js +206 -0
  30. package/server/assets/chat/clipboard.js +44 -25
  31. package/server/assets/chat/confirm-dialog.js +36 -34
  32. package/server/assets/chat/copy-action.js +40 -40
  33. package/server/assets/chat/create-room-dialog.js +50 -48
  34. package/server/assets/chat/diagram-viewer.js +293 -228
  35. package/server/assets/chat/doc-preview.js +510 -388
  36. package/server/assets/chat/editor.js +423 -335
  37. package/server/assets/chat/events.js +637 -502
  38. package/server/assets/chat/files.js +476 -426
  39. package/server/assets/chat/history-loader.js +79 -73
  40. package/server/assets/chat/icons.js +9 -11
  41. package/server/assets/chat/image-zoom.js +239 -169
  42. package/server/assets/chat/index.js +6 -5
  43. package/server/assets/chat/install-prompt.js +86 -66
  44. package/server/assets/chat/integration-account-schema.js +101 -0
  45. package/server/assets/chat/integration-editor.js +162 -153
  46. package/server/assets/chat/integration-values.js +109 -100
  47. package/server/assets/chat/integrations.js +696 -479
  48. package/server/assets/chat/join-requests.js +408 -358
  49. package/server/assets/chat/locales/de.js +193 -194
  50. package/server/assets/chat/locales/es.js +193 -194
  51. package/server/assets/chat/locales/fr.js +193 -194
  52. package/server/assets/chat/locales/index.js +1 -2
  53. package/server/assets/chat/locales/it.js +193 -194
  54. package/server/assets/chat/locales/ja.js +193 -193
  55. package/server/assets/chat/locales/ko.js +193 -193
  56. package/server/assets/chat/markdown-footnotes.js +134 -102
  57. package/server/assets/chat/markdown.js +553 -386
  58. package/server/assets/chat/members.js +236 -197
  59. package/server/assets/chat/mentions.js +157 -133
  60. package/server/assets/chat/message-cache.js +40 -33
  61. package/server/assets/chat/message-polling.js +280 -227
  62. package/server/assets/chat/message-window.js +74 -55
  63. package/server/assets/chat/messages.js +552 -479
  64. package/server/assets/chat/office-preview.js +46 -45
  65. package/server/assets/chat/palette.js +450 -412
  66. package/server/assets/chat/panels.js +94 -58
  67. package/server/assets/chat/pwa.js +144 -73
  68. package/server/assets/chat/questions.js +372 -302
  69. package/server/assets/chat/recall.js +320 -273
  70. package/server/assets/chat/receipts.js +149 -122
  71. package/server/assets/chat/reminders.js +331 -216
  72. package/server/assets/chat/replies.js +165 -136
  73. package/server/assets/chat/resource-format.js +59 -62
  74. package/server/assets/chat/room-list.js +58 -55
  75. package/server/assets/chat/room-watcher.js +72 -50
  76. package/server/assets/chat/rooms.js +623 -505
  77. package/server/assets/chat/search.js +136 -114
  78. package/server/assets/chat/settings.js +229 -140
  79. package/server/assets/chat/shiki.js +61 -62
  80. package/server/assets/chat/shortcuts.js +212 -190
  81. package/server/assets/chat/side-pane.js +166 -131
  82. package/server/assets/chat/state.js +851 -707
  83. package/server/assets/chat/system-events.js +55 -27
  84. package/server/assets/chat/system-messages.js +59 -49
  85. package/server/assets/chat/task-form.js +178 -182
  86. package/server/assets/chat/task-row.js +158 -155
  87. package/server/assets/chat/tasks.js +653 -593
  88. package/server/assets/chat/viewport.js +32 -29
  89. package/server/assets/chat/window-controls.js +37 -0
  90. package/server/assets/code-highlight.css +22 -6
  91. package/server/assets/conversation.css +65 -16
  92. package/server/assets/doc-preview.css +6 -1
  93. package/server/assets/files.css +3 -0
  94. package/server/assets/monaco/integration-rules.css +1 -1
  95. package/server/assets/monaco/integration-rules.js +841 -533
  96. package/server/assets/responsive.css +32 -2
  97. package/server/assets/settings.css +117 -13
  98. package/server/assets/window-controls.css +36 -0
  99. package/server/channel-attachments.ts +133 -0
  100. package/server/channel-integration.ts +79 -26
  101. package/server/channels.ts +15 -5
  102. package/server/chat-server.ts +9 -1
  103. package/server/chat.html +73 -38
  104. package/server/manifest.webmanifest +1 -0
  105. package/server/routes/pages.ts +7 -5
  106. package/server/sw.js +346 -267
  107. package/src/center/center-client.ts +1 -1
  108. package/src/state/pg-database.ts +5 -5
  109. package/src/state/pg-migrate.ts +7 -7
  110. package/src/state/pg-worker.mjs +2 -17
  111. package/src/state/sqlite-database.ts +14 -5
  112. package/src/state/sqlite-rooms.ts +130 -23
  113. package/src/state/sqlite-state-store.ts +6 -5
  114. package/src/state/sqlite.ts +3 -3
  115. package/src/web/integration-rules-editor.ts +141 -5
  116. package/src/web/integration-rules.ts +6 -2
  117. package/src/web/integration-schema.ts +7 -6
  118. package/packages/chat-room-channeld/dist/feishu-adapter.js +0 -1262
  119. package/packages/chat-room-channeld/src/feishu-adapter.ts +0 -303
  120. package/packages/chat-room-channeld/src/feishu-card.ts +0 -27
  121. package/packages/chat-room-channeld/src/feishu-inbound.ts +0 -158
  122. package/packages/chat-room-channeld/src/feishu-live.ts +0 -355
  123. package/packages/chat-room-channeld/src/feishu-send.ts +0 -342
  124. package/packages/chat-room-channeld/src/feishu-ws-frames.ts +0 -173
  125. package/server/assets/chat/forward.js +0 -69
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/opencode-chat-room",
3
- "version": "0.8.1",
3
+ "version": "0.8.3",
4
4
  "description": "A chat-room server, web client, terminal client, and OpenCode/Codex/dsh plugins.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,7 +28,6 @@
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",
@@ -38,6 +37,7 @@
38
37
  "server/routes",
39
38
  "server/app.ts",
40
39
  "server/channels.ts",
40
+ "server/channel-attachments.ts",
41
41
  "server/channel-settings.ts",
42
42
  "server/channel-integration.ts",
43
43
  "server/http-server.ts",
@@ -64,6 +64,8 @@
64
64
  "server/manifest.webmanifest",
65
65
  "server/sw.js",
66
66
  "server/assets",
67
+ "!server/assets/chat/**/*.ts",
68
+ "!server/chat-src",
67
69
  "CHANGELOG.md",
68
70
  "docs/administrator-rooms.md",
69
71
  "README.md",
@@ -74,17 +76,18 @@
74
76
  "registry": "https://registry.npmjs.org/"
75
77
  },
76
78
  "scripts": {
79
+ "build:web": "tsc -p tsconfig.web.json && tsc -p tsconfig.sw.json",
77
80
  "build:cli": "bun build cli.ts --target=node --packages external --outfile dist/cli.js >&2",
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",
79
- "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",
81
+ "build:channeld-mock": "bun run --cwd packages/chat-room-channeld build:mock",
82
+ "build:adapter-feishu": "bun scripts/build-feishu-adapter.ts",
80
83
  "build:monaco": "bun scripts/build-monaco.ts",
81
84
  "build:office": "bun scripts/build-office.ts",
82
- "prepack": "bun run build:cli && bun run build:channeld-mock && bun run build:channeld-feishu && bun scripts/build-monaco.ts --quiet && bun scripts/build-office.ts --quiet",
85
+ "prepack": "bun run build:web && bun run build:cli && bun run build:channeld-mock && bun scripts/build-monaco.ts --quiet && bun scripts/build-office.ts --quiet",
83
86
  "server": "node cli.ts",
84
87
  "server:bun": "bun cli.ts",
85
88
  "server:deno": "deno run --allow-env --allow-read --allow-write --allow-net cli.ts",
86
- "test": "for file in src/tests/*.test.ts server/*.test.ts; do bun test \"$file\" || exit; done && bun test src/tui/test --isolate",
87
- "typecheck": "tsc --noEmit"
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 test src/tui/test --isolate",
90
+ "typecheck": "bun run build:web && tsc --noEmit && bun scripts/check-web-types.ts"
88
91
  },
89
92
  "engines": {
90
93
  "node": ">=24.2.0"
@@ -5,16 +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 a Feishu adapter with opt-in inbound long-connection events. Inbound Feishu
10
- events can be relayed into one chat-room as notifications; they are never matched by
11
- outbound rules.
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`.
12
13
 
13
- This package is bundled inside `@alexsun-top/opencode-chat-room` 0.8.0 as
14
- source plus the Feishu and mock adapter entry points. Standalone npm
15
- publication, and the `npx @alexsun-top/chat-room-channeld` form, are planned
16
- for 0.8.x. In 0.8.0 use `GET /channeld/status` on the ChatRoom server, or run
17
- 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.
18
17
 
19
18
  ## Run from a checkout
20
19
 
@@ -47,6 +46,26 @@ Run the mock adapter on stdio (the host normally spawns it):
47
46
  bun src/cli.ts mock
48
47
  ```
49
48
 
49
+ ## PostgreSQL state
50
+
51
+ Set `CHAT_ROOM_DATABASE_URL` on the host process to use PostgreSQL instead of
52
+ the SQLite `stateFile`. One host process owns the database; the bridge
53
+ serializes writers with an advisory lock but multi-instance Channel D is not
54
+ supported. Unset the variable to roll back to SQLite.
55
+
56
+ Copy an existing SQLite store into an empty PostgreSQL database (stop the host
57
+ first; the SQLite file is never modified):
58
+
59
+ ```sh
60
+ bun src/cli.ts migrate --state ./channeld.sqlite --to-postgres postgresql://...
61
+ ```
62
+
63
+ Migration preserves event and delivery ids, `ingress_seq`, receipts, and echo
64
+ timestamps; legacy echoes that predate `created_at` are backfilled from SQLite
65
+ rowid order so historical echo selection stays stable. It refuses a target that
66
+ already has rows and verifies per-table row counts, maxima, and `ingress_seq`. Rollback is unsetting `CHAT_ROOM_DATABASE_URL`; rows written while
67
+ PostgreSQL was active are not copied back.
68
+
50
69
  Requires Node.js 22.13 or newer (the state store uses `node:sqlite`).
51
70
 
52
71
  Run the suite from a checkout:
@@ -65,7 +84,7 @@ npm run build
65
84
  bun test tests/*.test.ts
66
85
  ```
67
86
 
68
- Bun is still required for tests.
87
+ Bun is still required for the build script and tests.
69
88
 
70
89
  ## Config
71
90
 
@@ -123,7 +142,7 @@ retries. A room that stays missing keeps failing until it is created.
123
142
  accounts:
124
143
  - id: feishu-main
125
144
  platform: feishu
126
- adapter: { command: ["node", "/opt/chatroom/feishu-adapter.js"] }
145
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"] }
127
146
  env: { FEISHU_APP_ID: "cli_xxx", FEISHU_APP_SECRET: "xxx" }
128
147
  ```
129
148
 
@@ -170,7 +189,13 @@ from room `in` after starting, so the relay can be exercised end to end.
170
189
 
171
190
  ## Feishu adapter
172
191
 
173
- `dist/feishu-adapter.js` is a Feishu OpenAPI adapter. Outbound it sends interactive
192
+ The Feishu adapter is the generated typed single-file adapter
193
+ `plugins/feishu/dist/feishu-adapter.ts`, produced by concatenating the typed
194
+ source under `plugins/feishu/src` without a bundler so its TypeScript
195
+ annotations stay in the file. It is attached to the GitHub Release instead of being shipped inside the root
196
+ `@alexsun-top/opencode-chat-room` package and runs directly under Node 22.18+
197
+ through native type stripping (erasable syntax only: no `enum`, `namespace`, or
198
+ constructor parameter properties). Outbound it sends interactive
174
199
  cards and can reply natively to a Feishu message; inbound it can receive group
175
200
  messages over the event long connection. It speaks the same stdio JSON-RPC protocol
176
201
  as the mock adapter and has no room or session concepts.
@@ -219,7 +244,7 @@ keeps the account started for outbound sends, and reports a sanitized
219
244
  accounts:
220
245
  - id: feishu-bot
221
246
  platform: feishu
222
- adapter: { command: ["node", "/opt/chatroom/dist/feishu-adapter.js"], runtime: "node" }
247
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"], runtime: "node" }
223
248
  rules:
224
249
  - id: to-feishu
225
250
  version: 1
@@ -279,7 +304,9 @@ flattened to one line, and redacts credential-shaped `token=…`/`secret=…`
279
304
  fragments. On disable or crash, in-flight deliveries move to `unknown`
280
305
  with the reason; a deliberate host stop also settles remaining in-flight rows as
281
306
  `unknown`, so a centered reload cannot auto-resend them. A host start resets
282
- stale `in_flight` rows from a previous crash to `pending`. If every account becomes disabled at runtime, the host logs
307
+ stale `in_flight` rows from a previous crash to `pending` for adapters that
308
+ declare `send.idempotency = "persistent_delivery_key"`, and to `unknown` for
309
+ every other adapter. If every account becomes disabled at runtime, the host logs
283
310
  `all accounts disabled; host idle until restart` and stays alive; only a startup
284
311
  with zero usable adapters fails. `onUnsupported: drop` skips empty renders; otherwise the
285
312
  payload carries an `attachment/format unsupported` notice. Replies without a
@@ -308,7 +335,7 @@ same terminal result event and message.
308
335
  ## Non-goals (0.1 MVP)
309
336
 
310
337
  - no config hot reload — rule changes require a restart (each delivery still freezes ruleId + ruleVersion + rendered payload);
311
- - no one-click manual resend command — `unknown` deliveries only guarantee no duplicate delivery row if resent (unique idempotency key); they are never auto-resent;
338
+ - no automatic resend of `unknown` deliveries; `channeld retry --config <path> --delivery <id> --force` moves one `unknown` delivery back to `pending` and rejects every other state. It does not start the host. `--force` acknowledges that an adapter without durable idempotency resends from the first message part, so a duplicate is possible;
312
339
  - no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
313
340
  - no attachments, no rule UI, no multi-tenant permission model, no exactly-once
314
341
  guarantee (inbound room notifications are idempotent per event and route, but
@@ -1,11 +1,11 @@
1
- // packages/chat-room-channeld/src/mock-adapter.ts
1
+ // src/mock-adapter.ts
2
2
  import path from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
 
5
- // packages/chat-room-channeld/src/framing.ts
5
+ // src/framing.ts
6
6
  import { StringDecoder } from "node:string_decoder";
7
7
 
8
- // packages/chat-room-channeld/src/protocol.ts
8
+ // src/protocol.ts
9
9
  var PROTOCOL_VERSION = 1;
10
10
  var EVENT_SCHEMA_VERSION = 1;
11
11
  var MAX_FRAME_BYTES = 1048576;
@@ -25,7 +25,7 @@ function rpcError(id, code, message, data) {
25
25
  return { jsonrpc: "2.0", id, error };
26
26
  }
27
27
 
28
- // packages/chat-room-channeld/src/framing.ts
28
+ // src/framing.ts
29
29
  function parseFrame(line) {
30
30
  const text = line.trim();
31
31
  if (!text)
@@ -130,7 +130,7 @@ function writeFrame(stream, value) {
130
130
  });
131
131
  }
132
132
 
133
- // packages/chat-room-channeld/src/mock-adapter.ts
133
+ // src/mock-adapter.ts
134
134
  async function handleRequest(message, options, state) {
135
135
  const rawId = message.id;
136
136
  if (rawId === undefined) {
@@ -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,
@@ -61,6 +63,103 @@ const STDERR_TAIL_LIMIT = 4096;
61
63
  const DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;
62
64
  const DEFAULT_SEND_TIMEOUT_MS = 15_000;
63
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
+ const send = entry.send;
156
+ if (send && typeof send === "object") {
157
+ const value = (send as Record<string, unknown>).idempotency;
158
+ if (typeof value === "string" && value.trim()) capabilities.send = { idempotency: value.trim() };
159
+ }
160
+ return Object.keys(capabilities).length ? capabilities : undefined;
161
+ }
162
+
64
163
  export class AdapterProcess {
65
164
  readonly #account: AccountConfig;
66
165
  readonly #onIngest: AdapterContext["onIngest"];
@@ -78,6 +177,7 @@ export class AdapterProcess {
78
177
  #stopping = false;
79
178
  #gone = false;
80
179
  #pollutionError?: Error;
180
+ #capabilities?: AdapterCapabilities;
81
181
 
82
182
  constructor(options: AdapterProcessOptions) {
83
183
  this.#account = options.account;
@@ -93,19 +193,17 @@ export class AdapterProcess {
93
193
  return this.#account.id;
94
194
  }
95
195
 
196
+ get capabilities(): AdapterCapabilities | undefined {
197
+ return this.#capabilities;
198
+ }
199
+
96
200
  async start(): Promise<void> {
97
201
  if (this.#child) throw new Error(`adapter ${this.#account.id} already started`);
98
202
  const [command, ...args] = this.#account.adapter.command;
99
203
  if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
100
204
  const child = spawn(command, args, {
101
205
  stdio: ["pipe", "pipe", "pipe"],
102
- env: {
103
- ...process.env,
104
- ...this.#account.env,
105
- // Forced after account env: config validation also rejects these keys.
106
- CHANNELD_ACCOUNT_ID: this.#account.id,
107
- CHANNELD_PLATFORM: this.#account.platform,
108
- },
206
+ env: adapterChildEnv(this.#account),
109
207
  });
110
208
  this.#child = child;
111
209
  this.#attach(child);
@@ -124,6 +222,7 @@ export class AdapterProcess {
124
222
  this.#initializeTimeoutMs,
125
223
  );
126
224
  this.#assertReportedPlatform("initialize", initialized);
225
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
127
226
  const started = await this.#call(
128
227
  "start",
129
228
  { accounts: [this.#account.id], cursors: {} },
@@ -145,6 +244,50 @@ export class AdapterProcess {
145
244
  log.info("adapter started", { account: this.#account.id });
146
245
  }
147
246
 
247
+ /**
248
+ * Read-only handshake used when a plugin is uploaded: initialize only, then
249
+ * kill. It does not start the account and does not need credentials.
250
+ */
251
+ async probe(): Promise<{ platform?: string; capabilities?: AdapterCapabilities }> {
252
+ if (this.#child) throw new Error(`adapter ${this.#account.id} already started`);
253
+ const [command, ...args] = this.#account.adapter.command;
254
+ if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
255
+ const child = spawn(command, args, {
256
+ stdio: ["pipe", "pipe", "pipe"],
257
+ env: adapterChildEnv(this.#account),
258
+ });
259
+ this.#child = child;
260
+ this.#attach(child);
261
+ try {
262
+ const initialized = await this.#call(
263
+ "initialize",
264
+ {
265
+ protocolVersions: [PROTOCOL_VERSION],
266
+ eventSchemas: [EVENT_SCHEMA_VERSION],
267
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
268
+ platform: this.#account.platform,
269
+ accounts: [this.#account.id],
270
+ maxFrameBytes: MAX_FRAME_BYTES,
271
+ },
272
+ this.#initializeTimeoutMs,
273
+ );
274
+ const reported = initialized && typeof initialized === "object"
275
+ ? (initialized as { platform?: unknown }).platform
276
+ : undefined;
277
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
278
+ return {
279
+ ...(typeof reported === "string" && reported.trim() ? { platform: reported.trim() } : {}),
280
+ ...(this.#capabilities ? { capabilities: this.#capabilities } : {}),
281
+ };
282
+ } catch (error) {
283
+ const tail = this.#stderrTail.trim();
284
+ const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
285
+ throw new Error(`adapter probe failed: ${message}${tail ? `\nstderr:\n${tail}` : ""}`);
286
+ } finally {
287
+ await this.stop().catch(() => undefined);
288
+ }
289
+ }
290
+
148
291
  /**
149
292
  * Send one delivery. Platform outcomes are returned; protocol failures and
150
293
  * timeouts become state "unknown" and never throw.
@@ -3,6 +3,7 @@ import { readFileSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { loadConfig } from "./config.ts";
6
+ import { accountKey } from "./stats.ts";
6
7
  import { log } from "./log.ts";
7
8
 
8
9
  function readVersion(): string {
@@ -31,6 +32,10 @@ Usage:
31
32
  chat-room-channeld run --config <path> Same as the default command
32
33
  chat-room-channeld check --config <path> Validate a config file only
33
34
  chat-room-channeld status --config <path> Print queue and integrity counts
35
+ chat-room-channeld retry --config <path> --delivery <id> --force
36
+ Retry one unknown delivery; --force may duplicate
37
+ chat-room-channeld migrate --state <sqlite> --to-postgres <url>
38
+ Copy an existing SQLite store into PostgreSQL
34
39
  chat-room-channeld mock Run the mock adapter on stdio
35
40
  chat-room-channeld --version, -v Print the version
36
41
  chat-room-channeld --help, -h Print this help
@@ -38,7 +43,7 @@ Usage:
38
43
 
39
44
  class UsageError extends Error {}
40
45
 
41
- type Command = "run" | "check" | "status" | "mock";
46
+ type Command = "run" | "check" | "status" | "migrate" | "mock" | "retry";
42
47
 
43
48
  async function main(): Promise<void> {
44
49
  const argv = process.argv.slice(2);
@@ -54,11 +59,15 @@ async function main(): Promise<void> {
54
59
  const rest = [...argv];
55
60
  let command: Command = "run";
56
61
  const first = rest[0];
57
- if (first === "run" || first === "check" || first === "status" || first === "mock") {
62
+ if (first === "run" || first === "check" || first === "status" || first === "migrate" || first === "mock" || first === "retry") {
58
63
  command = rest.shift() as Command;
59
64
  }
60
65
 
61
66
  let configPath: string | undefined;
67
+ let statePath: string | undefined;
68
+ let toPostgres: string | undefined;
69
+ let deliveryId: string | undefined;
70
+ let forceRetry = false;
62
71
  while (rest.length > 0) {
63
72
  const arg = rest.shift() as string;
64
73
  if (arg === "--config") {
@@ -68,6 +77,29 @@ async function main(): Promise<void> {
68
77
  } else if (arg.startsWith("--config=")) {
69
78
  configPath = arg.slice("--config=".length);
70
79
  if (!configPath) throw new UsageError("--config requires a path");
80
+ } else if (arg === "--state") {
81
+ const value = rest.shift();
82
+ if (!value) throw new UsageError("--state requires a path");
83
+ statePath = value;
84
+ } else if (arg.startsWith("--state=")) {
85
+ statePath = arg.slice("--state=".length);
86
+ if (!statePath) throw new UsageError("--state requires a path");
87
+ } else if (arg === "--to-postgres") {
88
+ const value = rest.shift();
89
+ if (!value) throw new UsageError("--to-postgres requires a URL");
90
+ toPostgres = value;
91
+ } else if (arg.startsWith("--to-postgres=")) {
92
+ toPostgres = arg.slice("--to-postgres=".length);
93
+ if (!toPostgres) throw new UsageError("--to-postgres requires a URL");
94
+ } else if (arg === "--delivery") {
95
+ const value = rest.shift();
96
+ if (!value) throw new UsageError("--delivery requires an id");
97
+ deliveryId = value;
98
+ } else if (arg.startsWith("--delivery=")) {
99
+ deliveryId = arg.slice("--delivery=".length);
100
+ if (!deliveryId) throw new UsageError("--delivery requires an id");
101
+ } else if (arg === "--force") {
102
+ forceRetry = true;
71
103
  } else {
72
104
  throw new UsageError(`unknown argument: ${arg}`);
73
105
  }
@@ -80,6 +112,15 @@ async function main(): Promise<void> {
80
112
  return;
81
113
  }
82
114
 
115
+ if (command === "migrate") {
116
+ if (!toPostgres) throw new UsageError("migrate requires --to-postgres <url>");
117
+ if (!statePath) throw new UsageError("migrate requires --state <sqlite path>");
118
+ const { migrateToPostgres } = await import("./pg/migrate.ts");
119
+ const report = migrateToPostgres(statePath, toPostgres);
120
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
121
+ return;
122
+ }
123
+
83
124
  if (!configPath) throw new UsageError(`${command} requires --config <path>`);
84
125
  const config = loadConfig(configPath);
85
126
  if (command === "check") {
@@ -87,8 +128,34 @@ async function main(): Promise<void> {
87
128
  return;
88
129
  }
89
130
  if (command === "status") {
90
- const { readChannelStats } = await import("./state.ts");
91
- process.stdout.write(`${JSON.stringify(readChannelStats(config.stateFile), null, 2)}\n`);
131
+ const { readChannelStats, readChannelStatsFromPostgres } = await import("./state.ts");
132
+ const url = process.env.CHAT_ROOM_DATABASE_URL?.trim();
133
+ const stats = url ? readChannelStatsFromPostgres(url) : readChannelStats(config.stateFile);
134
+ process.stdout.write(`${JSON.stringify(stats, null, 2)}\n`);
135
+ return;
136
+ }
137
+ if (command === "retry") {
138
+ if (!deliveryId) throw new UsageError("retry requires --delivery <id>");
139
+ const { openState } = await import("./state.ts");
140
+ const state = openState(config.stateFile);
141
+ try {
142
+ const delivery = state.getDelivery(deliveryId);
143
+ if (!delivery) throw new UsageError(`delivery not found: ${deliveryId}`);
144
+ if (delivery.state !== "unknown") {
145
+ throw new UsageError(`delivery ${deliveryId} is ${delivery.state}; only unknown can be retried`);
146
+ }
147
+ const key = accountKey(delivery.target);
148
+ if (!config.accounts.some((account) => `${account.platform}/${account.id}` === key)) {
149
+ throw new UsageError(`account ${key} is not configured; add it back before retrying`);
150
+ }
151
+ if (!forceRetry) {
152
+ throw new UsageError("retry may resend from the first part and duplicate; pass --force");
153
+ }
154
+ state.markDelivery(deliveryId, "pending");
155
+ process.stdout.write(`${JSON.stringify({ deliveryId, state: "pending" })}\n`);
156
+ } finally {
157
+ state.close();
158
+ }
92
159
  return;
93
160
  }
94
161
 
@@ -112,7 +179,7 @@ async function main(): Promise<void> {
112
179
  await host.stop();
113
180
  throw error;
114
181
  }
115
- log.info(`relay running; state=${config.stateFile}`);
182
+ log.info(`relay running; state=${process.env.CHAT_ROOM_DATABASE_URL?.trim() ? "postgres" : config.stateFile}`);
116
183
  }
117
184
 
118
185
  main().catch((error: unknown) => {
@@ -4,7 +4,7 @@ import { applyReceipt, notifyDeliveryResult, type DeliveryResultHandler } from "
4
4
  import { parseTarget, startFailureReason, toEndpoint, validateTargets } from "./host-helpers.ts";
5
5
  import { IngestGate, type IngestResult } from "./ingest-gate.ts";
6
6
  import { log } from "./log.ts";
7
- import type { Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
7
+ import type { AdapterCapabilities, Endpoint, IngestEvent, MessageRef } from "./protocol.ts";
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";
@@ -13,6 +13,8 @@ import { openState, type ChannelState, type DeliveryRow } from "./state.ts";
13
13
  export type { IngestResult } from "./ingest-gate.ts";
14
14
 
15
15
  export interface AdapterHandle {
16
+ /** Optional platform facts declared by the adapter during initialize. */
17
+ readonly capabilities?: AdapterCapabilities;
16
18
  start(): Promise<void>;
17
19
  send(
18
20
  deliveryId: string,
@@ -49,6 +51,14 @@ export interface HostDeps {
49
51
  onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
50
52
  /** Events used as inbound room notifications must not match outbound rules. */
51
53
  notificationOnly?: (event: IngestEvent) => boolean;
54
+ /**
55
+ * Resolve a stored delivery payload into the adapter's wire form right before
56
+ * a send. The host calls cleanup after the attempt, whether it succeeded or not.
57
+ */
58
+ prepareSendPayload?: (payload: unknown, capabilities?: AdapterCapabilities) => Promise<{
59
+ payload: unknown;
60
+ cleanup?: () => Promise<void>;
61
+ }>;
52
62
  }
53
63
 
54
64
  function defaultSpawnAdapter(account: AccountConfig, context: SpawnAdapterContext): AdapterHandle {
@@ -64,6 +74,7 @@ export class ChannelHost {
64
74
  readonly #onDeliveryResult?: DeliveryResultHandler;
65
75
  readonly #onIngestCommitted?: (event: IngestEvent) => Promise<void> | void;
66
76
  readonly #notificationOnly?: (event: IngestEvent) => boolean;
77
+ readonly #prepareSendPayload?: HostDeps["prepareSendPayload"];
67
78
  readonly #adapters = new Map<string, AdapterHandle>();
68
79
  readonly #timers = new Map<string, ReturnType<typeof setTimeout>>();
69
80
  readonly #inFlight = new Map<string, Set<string>>();
@@ -90,6 +101,7 @@ export class ChannelHost {
90
101
  this.#onDeliveryResult = deps.onDeliveryResult;
91
102
  this.#onIngestCommitted = deps.onIngestCommitted;
92
103
  this.#notificationOnly = deps.notificationOnly;
104
+ this.#prepareSendPayload = deps.prepareSendPayload;
93
105
  }
94
106
 
95
107
  /** Account ids whose adapter failed to start or exited; their queues stay paused. */
@@ -133,8 +145,6 @@ export class ChannelHost {
133
145
  }
134
146
  const resumed = state.resumePausedDeliveries();
135
147
  if (resumed > 0) log.info(`resumed ${resumed} paused deliveries`);
136
- const recovered = state.recoverInFlightDeliveries();
137
- if (recovered > 0) log.warn(`recovered ${recovered} stale in-flight deliveries`);
138
148
 
139
149
  this.#running = true;
140
150
  this.#starting = true;
@@ -194,6 +204,23 @@ export class ChannelHost {
194
204
  }
195
205
  }
196
206
 
207
+ // Recovery runs after adapters initialize: an in-flight send whose adapter
208
+ // lacks durable idempotency cannot be replayed safely, so it becomes
209
+ // unknown instead of being retried as pending.
210
+ const idempotentKeys = this.#config.accounts
211
+ .filter((account) => !this.#disabled.has(account.id))
212
+ .filter((account) => this.#adapters.get(account.id)?.capabilities?.send?.idempotency === "persistent_delivery_key")
213
+ .map((account) => `${account.platform}/${account.id}`);
214
+ const recovered = state.recoverInFlightDeliveries(idempotentKeys);
215
+ if (recovered > 0) {
216
+ 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
+ }
223
+
197
224
  const usable = started.filter((accountId) => !this.#disabled.has(accountId));
198
225
  if (usable.length === 0) {
199
226
  this.#running = false;
@@ -251,7 +278,7 @@ export class ChannelHost {
251
278
  } catch (error) {
252
279
  const message = error instanceof Error ? error.message : String(error);
253
280
  // An inbound notification owns the ACK: roll back and fail the ingest so
254
- // Feishu retries. Other consumer failures stay contained as before.
281
+ // the provider retries. Other consumer failures stay contained as before.
255
282
  if (this.#notificationOnly?.(stored)) {
256
283
  state.deleteIngestEvent(stored.eventId);
257
284
  log.error(`inbound commit rolled back: ${message}`, { event: stored.eventId });
@@ -410,18 +437,21 @@ export class ChannelHost {
410
437
  this.#gate.begin(accountId);
411
438
  try {
412
439
  let receipt: SendReceipt;
440
+ let cleanup: (() => Promise<void>) | undefined;
413
441
  try {
414
- receipt = await adapter.send(
415
- row.deliveryId,
416
- attemptId,
417
- row.idempotencyKey,
418
- target,
419
- JSON.parse(row.payload) as unknown,
420
- );
442
+ const stored = JSON.parse(row.payload) as unknown;
443
+ if (this.#prepareSendPayload) {
444
+ const prepared = await this.#prepareSendPayload(stored, adapter.capabilities);
445
+ cleanup = prepared.cleanup;
446
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, prepared.payload);
447
+ } else {
448
+ receipt = await adapter.send(row.deliveryId, attemptId, row.idempotencyKey, target, stored);
449
+ }
421
450
  } catch (error) {
422
451
  receipt = { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
423
452
  } finally {
424
453
  inFlight.delete(row.deliveryId);
454
+ await cleanup?.().catch(() => undefined);
425
455
  }
426
456
  // A host stop wins over a late send result: reload must not auto-resend.
427
457
  if (this.#stopReason) receipt = { state: "unknown", detail: this.#stopReason };