@alexsun-top/chat-room-channeld 0.0.0-stage → 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 (68) hide show
  1. package/README.md +319 -2
  2. package/dist/adapter.d.ts +53 -0
  3. package/dist/adapter.js +578 -0
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +120 -0
  6. package/dist/config.d.ts +58 -0
  7. package/dist/config.js +198 -0
  8. package/dist/delivery.d.ts +14 -0
  9. package/dist/delivery.js +136 -0
  10. package/dist/framing.d.ts +22 -0
  11. package/dist/framing.js +120 -0
  12. package/dist/host-helpers.d.ts +6 -0
  13. package/dist/host-helpers.js +44 -0
  14. package/dist/host.d.ts +71 -0
  15. package/dist/host.js +554 -0
  16. package/dist/inbound.d.ts +10 -0
  17. package/dist/inbound.js +27 -0
  18. package/dist/ingest-gate.d.ts +20 -0
  19. package/dist/ingest-gate.js +84 -0
  20. package/dist/log.d.ts +11 -0
  21. package/dist/log.js +22 -0
  22. package/dist/mock-adapter.d.ts +1 -0
  23. package/dist/mock-adapter.js +163 -0
  24. package/dist/protocol.d.ts +127 -0
  25. package/dist/protocol.js +27 -0
  26. package/dist/published.d.ts +12 -0
  27. package/dist/published.js +22 -0
  28. package/dist/rules.d.ts +35 -0
  29. package/dist/rules.js +113 -0
  30. package/dist/state.d.ts +98 -0
  31. package/dist/state.js +296 -0
  32. package/dist/stats.d.ts +46 -0
  33. package/dist/stats.js +139 -0
  34. package/package.json +38 -4
  35. package/src/adapter.ts +647 -0
  36. package/src/cli.ts +124 -0
  37. package/src/config.ts +269 -0
  38. package/src/delivery.ts +163 -0
  39. package/src/framing.ts +128 -0
  40. package/src/host-helpers.ts +52 -0
  41. package/src/host.ts +642 -0
  42. package/src/inbound.ts +35 -0
  43. package/src/ingest-gate.ts +108 -0
  44. package/src/log.ts +26 -0
  45. package/src/mock-adapter.ts +206 -0
  46. package/src/protocol.ts +126 -0
  47. package/src/published.ts +37 -0
  48. package/src/rules.ts +132 -0
  49. package/src/state.ts +502 -0
  50. package/src/stats.ts +209 -0
  51. package/tests/abandon.test.ts +150 -0
  52. package/tests/account-runtime.test.ts +197 -0
  53. package/tests/adapter.test.ts +207 -0
  54. package/tests/cli.test.ts +224 -0
  55. package/tests/delivery-result.test.ts +334 -0
  56. package/tests/echo-race.test.ts +375 -0
  57. package/tests/framing.test.ts +47 -0
  58. package/tests/host.test.ts +509 -0
  59. package/tests/inbound.test.ts +61 -0
  60. package/tests/ingest-gate.test.ts +58 -0
  61. package/tests/published-result.test.ts +208 -0
  62. package/tests/reload-stop.test.ts +106 -0
  63. package/tests/rpc-id.test.ts +126 -0
  64. package/tests/rules.test.ts +91 -0
  65. package/tests/startup.test.ts +94 -0
  66. package/tests/state.test.ts +215 -0
  67. package/tests/status.test.ts +207 -0
  68. package/tsconfig.build.json +14 -0
package/README.md CHANGED
@@ -1,3 +1,320 @@
1
- # Temporary Holding Version
1
+ # chat-room-channeld
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Channel D relay core. One host process connects chat-room endpoints to external
4
+ IM endpoints through adapter child processes. Explicit rules turn a source-room
5
+ event into frozen deliveries for target accounts; each adapter owns one IM
6
+ account and speaks JSON-RPC over stdio.
7
+
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`.
13
+
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
+
18
+ ## Run from a checkout
19
+
20
+ ```sh
21
+ bun src/cli.ts --config channeld.yml
22
+ ```
23
+
24
+ Validate a config without touching the state file:
25
+
26
+ ```sh
27
+ bun src/cli.ts check --config channeld.yml
28
+ # config ok: 1 accounts, 1 rules
29
+ ```
30
+
31
+ Inspect queue and integrity counts without writing the state file:
32
+
33
+ ```sh
34
+ bun src/cli.ts status --config channeld.yml
35
+ ```
36
+
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.
42
+
43
+ Run the mock adapter on stdio (the host normally spawns it):
44
+
45
+ ```sh
46
+ bun src/cli.ts mock
47
+ ```
48
+
49
+ Requires Node.js 22.13 or newer (the state store uses `node:sqlite`).
50
+
51
+ Run the suite from a checkout:
52
+
53
+ ```sh
54
+ bun test tests/*.test.ts
55
+ ```
56
+
57
+ The standalone tarball, once published, includes `tests/` and a self-contained
58
+ `tsconfig.build.json`. To build and test from an installed tarball:
59
+
60
+ ```sh
61
+ cd node_modules/@alexsun-top/chat-room-channeld
62
+ npm install --include=dev
63
+ npm run build
64
+ bun test tests/*.test.ts
65
+ ```
66
+
67
+ Bun is still required for tests.
68
+
69
+ ## Config
70
+
71
+ ```yaml
72
+ stateFile: ./channeld.sqlite
73
+ accounts:
74
+ - id: im-a
75
+ platform: dingtalk
76
+ adapter: { command: ["node", "/opt/chatroom/dist/mock-adapter.js"], runtime: "node" }
77
+ rules:
78
+ - id: project-in
79
+ version: 1
80
+ from: { platform: chatroom, account: lab, room: translation, event: message.created }
81
+ transforms: [ { op: prefix-source }, { op: truncate, max: 2000 } ]
82
+ to: [ { platform: dingtalk, account: im-a, room: project } ]
83
+ onMissingParent: quote_or_unthreaded
84
+ onUnsupported: text_with_notice
85
+ ```
86
+
87
+ Transforms run in order and are limited to `prefix-source`, `trim`,
88
+ `truncate` (adds `…`), and `quote-preview`. Omitting `from.event` matches every
89
+ kind. Account ids, platforms, and room ids must match
90
+ `/^[A-Za-z0-9._-]+$/`; `/` is rejected so endpoint keys stay unambiguous.
91
+ Account ids and rule `(id, version)` pairs must be unique. Only the highest
92
+ configured version of each rule id is active: an explicit newer version
93
+ replaces the older definition.
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
+
129
+ ## Adapter protocol
130
+
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.**
137
+ An invalid stdout frame disables that account, stops its adapter, and leaves its
138
+ deliveries paused; other accounts keep running. Frames are JSON objects limited
139
+ to 1 MiB (`MAX_FRAME_BYTES`). Host request ids start with `host-`, adapter
140
+ request ids with `adapter-`.
141
+
142
+ Host to adapter: `initialize` (protocol/event versions, account, frame limit),
143
+ `start` (accounts, cursors), `send` (delivery id, attempt id, idempotency key,
144
+ target endpoint, frozen payload), `ping`, `shutdown`.
145
+
146
+ Adapter to host: `ingest` (an `IngestEvent`) answered with
147
+ `{committed:true}` or `{duplicate:true}`, and `ping`. Unknown methods get
148
+ JSON-RPC `-32601`.
149
+
150
+ A JSON-RPC `id` only correlates one request/response within a session; it is not
151
+ an idempotency key. Repeating an `id` with different `sourceDedupKey` values is
152
+ two distinct events; repeating the same `sourceDedupKey` is one event.
153
+
154
+ A `send` result is a receipt: `{state, providerMessage?, retryAfterMs?, detail?}`
155
+ where state is `sent`, `retryable`, `rate_limited`, `permanent`, `unsupported`,
156
+ or `unknown`. A request timeout maps to `unknown`; the host never throws for a
157
+ platform outcome.
158
+
159
+ Sends are serial per account. Inbound ingests are buffered behind an in-flight
160
+ send so provider echoes are matched before they can become new events; an
161
+ overflow (100 events) disables that account and is logged as an error. After an
162
+ overflow drain, every delivery for the disabled account is paused, and the
163
+ overflowed event is dropped.
164
+
165
+ When `CHANNELD_MOCK_EMIT=1`, the mock adapter emits one `message.created` event
166
+ from room `in` after starting, so the relay can be exercised end to end.
167
+ `CHANNELD_MOCK_ECHO=1` makes it emit a provider echo right after a `send` result;
168
+ `CHANNELD_MOCK_ECHO_DELAY_MS` delays that result to exercise buffered ingests.
169
+
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).
194
+
195
+ The adapter command is resolved from the host process working directory, so
196
+ use an absolute path unless the host starts in this package directory.
197
+
198
+ The child process reads:
199
+
200
+ - `FEISHU_APP_ID` (required)
201
+ - `FEISHU_APP_SECRET` (required)
202
+ - `FEISHU_BASE_URL` (optional, default `https://open.feishu.cn`)
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)
208
+
209
+ Set these in the host environment; the host passes its environment to adapter
210
+ child processes.
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
+
223
+ ```yaml
224
+ accounts:
225
+ - id: feishu-bot
226
+ platform: feishu
227
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"], runtime: "node" }
228
+ rules:
229
+ - id: to-feishu
230
+ version: 1
231
+ from: { platform: chatroom, account: lab, room: translation, event: message.created }
232
+ transforms: [ { op: prefix-source }, { op: truncate, max: 2000 } ]
233
+ to: [ { platform: feishu, account: feishu-bot, room: oc_xxx } ]
234
+ ```
235
+
236
+ The target room is the Feishu `chat_id`, so an endpoint
237
+ `feishu/<account>/<chat_id>` maps to one Feishu chat.
238
+
239
+ `initialize` fails when a credential is missing. `start` fetches a tenant access
240
+ token, so rejected credentials disable only this account. Tokens are cached and
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.
246
+
247
+ Send outcomes:
248
+
249
+ - `230020`, `99991400`, or HTTP 429: `rate_limited`; `Retry-After` accepts
250
+ seconds or an HTTP date and defaults to 1000 ms.
251
+ - `99991663`: force one token refresh and retry the send once, then `permanent`.
252
+ - HTTP 5xx, connection resets, and other fetch network errors: `retryable`.
253
+ - Request timeout or abort: `unknown`, never retried automatically.
254
+ - Other Feishu codes (for example `230002`): `permanent` with code and message.
255
+ - Malformed response: `unknown`.
256
+
257
+ The adapter never logs message text, credentials, tokens, uuids, or full
258
+ payloads. Provider message ids may be logged and returned in the receipt.
259
+
260
+ ## State
261
+
262
+ The SQLite state file has four tables:
263
+
264
+ - `channel_events`: committed ingest events, unique by dedup key.
265
+ - `channel_deliveries`: one frozen delivery per rule target, unique by
266
+ idempotency key (`trigger:rule:version:0:target`).
267
+ - `channel_receipts`: one observation per send attempt.
268
+ - `channel_echoes`: provider message ids that originated from this host, used to
269
+ skip echo ingests.
270
+
271
+ Delivery states: `pending → in_flight → sent`; `retryable` and `rate_limited`
272
+ retry only that account's queue with capped backoff (8 attempts, then
273
+ `exhausted`); `permanent` and `unsupported` are terminal; `unknown` leaves the
274
+ delivery in `unknown` and never retries automatically; `paused` keeps a disabled
275
+ account's rows out of every claim until the next host start. An adapter that
276
+ fails to start or writes non-protocol stdout disables only that account until
277
+ restart; its queued deliveries move to `paused` and return to `pending` when the
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
288
+ `all accounts disabled; host idle until restart` and stays alive; only a startup
289
+ with zero usable adapters fails. `onUnsupported: drop` skips empty renders; otherwise the
290
+ payload carries an `attachment/format unsupported` notice. Replies without a
291
+ target parent mapping are sent unthreaded with `degraded: "unthreaded"`, or
292
+ dropped when `onMissingParent: drop`.
293
+
294
+ ## Center delivery results (M2)
295
+
296
+ `HostDeps.onDeliveryResult(event, delivery, receipt)` fires once per delivery when
297
+ it reaches a terminal state: `sent`, `permanent`, `unsupported`, `exhausted`, or
298
+ `unknown`. `receipt` is present only when a receipt row exists for that attempt.
299
+ When an account is disabled or its adapter crashes, in-flight deliveries settle as
300
+ `unknown` and report with `receipt: undefined`; no receipt row is invented.
301
+ Retryable and rate-limited attempts never report, and a delivery reports at most
302
+ once.
303
+
304
+ Every terminal delivery also records exactly one `result.published` event in
305
+ `channel_events`. Its payload holds ids, delivery state, and target only — never
306
+ message text, error detail, or provider secrets — and `readChannelStats` reports
307
+ it as `publishedResults` while excluding it from source gaps. Rules never match or
308
+ forward `result.published`; the center writes the localized terminal system
309
+ message from that terminal result. Deliveries abandoned at startup because their
310
+ account is no longer configured are also reported as `unknown` and receive the
311
+ same terminal result event and message.
312
+
313
+ ## Non-goals (0.1 MVP)
314
+
315
+ - no config hot reload — rule changes require a restart (each delivery still freezes ruleId + ruleVersion + rendered payload);
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;
317
+ - no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
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).
@@ -0,0 +1,53 @@
1
+ import type { AccountConfig } from "./config.ts";
2
+ import { type Endpoint, type AdapterCapabilities, type IngestEvent, type MessageRef } from "./protocol.ts";
3
+ export type SendState = "sent" | "retryable" | "rate_limited" | "permanent" | "unsupported" | "unknown";
4
+ export interface SendReceipt {
5
+ state: SendState;
6
+ providerMessage?: MessageRef;
7
+ retryAfterMs?: number;
8
+ detail?: string;
9
+ }
10
+ export interface AdapterContext {
11
+ onIngest(event: IngestEvent): Promise<{
12
+ duplicate: boolean;
13
+ eventId?: string;
14
+ }>;
15
+ onExit(code: number | null, signal: NodeJS.Signals | null): void;
16
+ onUnavailable?(reason: string): void;
17
+ /** Optional adapter health, e.g. inbound long-connection readiness. */
18
+ onStatus?(status: {
19
+ inbound?: string;
20
+ detail?: string;
21
+ }): void;
22
+ }
23
+ export interface AdapterProcessOptions extends AdapterContext {
24
+ account: AccountConfig;
25
+ initializeTimeoutMs?: number;
26
+ sendTimeoutMs?: number;
27
+ }
28
+ /**
29
+ * Adapter children execute uploaded .ts plugins, so they get Node's full
30
+ * TypeScript transform; the server process itself stays strip-only.
31
+ */
32
+ export declare function adapterChildEnv(account: AccountConfig): NodeJS.ProcessEnv;
33
+ export declare class AdapterProcess {
34
+ #private;
35
+ constructor(options: AdapterProcessOptions);
36
+ get accountId(): string;
37
+ get capabilities(): AdapterCapabilities | undefined;
38
+ start(): Promise<void>;
39
+ /**
40
+ * Read-only handshake used when a plugin is uploaded: initialize only, then
41
+ * kill. It does not start the account and does not need credentials.
42
+ */
43
+ probe(): Promise<{
44
+ platform?: string;
45
+ capabilities?: AdapterCapabilities;
46
+ }>;
47
+ /**
48
+ * Send one delivery. Platform outcomes are returned; protocol failures and
49
+ * timeouts become state "unknown" and never throw.
50
+ */
51
+ send(deliveryId: string, attemptId: string, idempotencyKey: string, target: Endpoint, payload: unknown): Promise<SendReceipt>;
52
+ stop(): Promise<void>;
53
+ }