@alexsun-top/chat-room-channeld 0.0.0-stage → 0.0.0

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 +313 -2
  2. package/dist/adapter.d.ts +40 -0
  3. package/dist/adapter.js +473 -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 +104 -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 +636 -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 +129 -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,314 @@
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, ship as separate packages such as
10
+ `@alexsun-top/chat-room-adapter-feishu`; their inbound events can be relayed into one
11
+ chat-room as notifications and are never matched by outbound rules.
12
+
13
+ The core ships the source plus the mock adapter entry point. Use
14
+ `GET /channeld/status` on the ChatRoom server, or run the CLI from a checkout
15
+ with Bun.
16
+
17
+ ## Run from a checkout
18
+
19
+ ```sh
20
+ bun src/cli.ts --config channeld.yml
21
+ ```
22
+
23
+ Validate a config without touching the state file:
24
+
25
+ ```sh
26
+ bun src/cli.ts check --config channeld.yml
27
+ # config ok: 1 accounts, 1 rules
28
+ ```
29
+
30
+ Inspect queue and integrity counts without writing the state file:
31
+
32
+ ```sh
33
+ bun src/cli.ts status --config channeld.yml
34
+ ```
35
+
36
+ `status` prints counts and per-account runtime state: `started`, `failed`,
37
+ `disabled`, or `unknown` (no live host is attached to a CLI read), plus a short
38
+ sanitized `lastError` for failed/disabled accounts. It never prints message text,
39
+ rule ids, provider message ids, room ids, or credentials. A missing state file or
40
+ missing channel tables exit 1 with a clear error.
41
+
42
+ Run the mock adapter on stdio (the host normally spawns it):
43
+
44
+ ```sh
45
+ bun src/cli.ts mock
46
+ ```
47
+
48
+ Requires Node.js 22.13 or newer (the state store uses `node:sqlite`).
49
+
50
+ Run the suite from a checkout:
51
+
52
+ ```sh
53
+ bun test tests/*.test.ts
54
+ ```
55
+
56
+ The standalone tarball, once published, includes `tests/` and a self-contained
57
+ `tsconfig.build.json`. To build and test from an installed tarball:
58
+
59
+ ```sh
60
+ cd node_modules/@alexsun-top/chat-room-channeld
61
+ npm install --include=dev
62
+ npm run build
63
+ bun test tests/*.test.ts
64
+ ```
65
+
66
+ Bun is still required for tests.
67
+
68
+ ## Config
69
+
70
+ ```yaml
71
+ stateFile: ./channeld.sqlite
72
+ accounts:
73
+ - id: im-a
74
+ platform: dingtalk
75
+ adapter: { command: ["node", "/opt/chatroom/dist/mock-adapter.js"], runtime: "node" }
76
+ rules:
77
+ - id: project-in
78
+ version: 1
79
+ from: { platform: chatroom, account: lab, room: translation, event: message.created }
80
+ transforms: [ { op: prefix-source }, { op: truncate, max: 2000 } ]
81
+ to: [ { platform: dingtalk, account: im-a, room: project } ]
82
+ onMissingParent: quote_or_unthreaded
83
+ onUnsupported: text_with_notice
84
+ ```
85
+
86
+ Transforms run in order and are limited to `prefix-source`, `trim`,
87
+ `truncate` (adds `…`), and `quote-preview`. Omitting `from.event` matches every
88
+ kind. Account ids, platforms, and room ids must match
89
+ `/^[A-Za-z0-9._-]+$/`; `/` is rejected so endpoint keys stay unambiguous.
90
+ Account ids and rule `(id, version)` pairs must be unique. Only the highest
91
+ configured version of each rule id is active: an explicit newer version
92
+ replaces the older definition.
93
+
94
+ Each account may add an `env` map for secrets and per-platform settings. Keys
95
+ must match `/^[A-Za-z_][A-Za-z0-9_]*$/`, values are strings, and a map holds at
96
+ most 64 variables. The adapter child inherits the host environment, then receives
97
+ the account `env`, then the forced `CHANNELD_ACCOUNT_ID` and `CHANNELD_PLATFORM`
98
+ values; configuring either reserved key is rejected. Status output never includes
99
+ env values.
100
+
101
+ An optional top-level `inbound` array turns external events into room notifications
102
+ in the center. It is separate from `rules`: an inbound event is committed, written
103
+ to its target room once, and then skipped by every outbound rule, so it cannot
104
+ ping-pong back to the source.
105
+
106
+ ```yaml
107
+ inbound:
108
+ - from: { platform: feishu, account: feishu-main, room: oc_xxx }
109
+ to: { room: lab }
110
+ ```
111
+
112
+ `from.room` is the Feishu `chat_id`; `to.room` is the chat-room id. An omitted
113
+ `from.event` matches every kind. A source account must exist and its platform must
114
+ match. The center appends one system-style message, `[Feishu <account>] <open_id>:
115
+ <text>`, with a marker row in the room database; the marker and message share one
116
+ transaction, so a transport retry cannot duplicate it. If the room write fails, the
117
+ center rolls the channel event back and the adapter acknowledges failure, so Feishu
118
+ retries. A room that stays missing keeps failing until it is created.
119
+
120
+ ```yaml
121
+ accounts:
122
+ - id: feishu-main
123
+ platform: feishu
124
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.js"] }
125
+ env: { FEISHU_APP_ID: "cli_xxx", FEISHU_APP_SECRET: "xxx" }
126
+ ```
127
+
128
+ ## Adapter protocol
129
+
130
+ The host spawns each adapter with `CHANNELD_ACCOUNT_ID`,
131
+ `CHANNELD_PLATFORM`, and that account's configured `env`. Both directions use
132
+ newline-delimited JSON-RPC 2.0 on stdio. An `initialize` or `start` result may
133
+ include `platform`; when it differs from the configured account platform, that
134
+ adapter is stopped and only that account is marked `failed` (its queue pauses)
135
+ while the host and other accounts keep running. **stdout carries protocol frames only; all adapter logs go to stderr.**
136
+ An invalid stdout frame disables that account, stops its adapter, and leaves its
137
+ deliveries paused; other accounts keep running. Frames are JSON objects limited
138
+ to 1 MiB (`MAX_FRAME_BYTES`). Host request ids start with `host-`, adapter
139
+ request ids with `adapter-`.
140
+
141
+ Host to adapter: `initialize` (protocol/event versions, account, frame limit),
142
+ `start` (accounts, cursors), `send` (delivery id, attempt id, idempotency key,
143
+ target endpoint, frozen payload), `ping`, `shutdown`.
144
+
145
+ Adapter to host: `ingest` (an `IngestEvent`) answered with
146
+ `{committed:true}` or `{duplicate:true}`, and `ping`. Unknown methods get
147
+ JSON-RPC `-32601`.
148
+
149
+ A JSON-RPC `id` only correlates one request/response within a session; it is not
150
+ an idempotency key. Repeating an `id` with different `sourceDedupKey` values is
151
+ two distinct events; repeating the same `sourceDedupKey` is one event.
152
+
153
+ A `send` result is a receipt: `{state, providerMessage?, retryAfterMs?, detail?}`
154
+ where state is `sent`, `retryable`, `rate_limited`, `permanent`, `unsupported`,
155
+ or `unknown`. A request timeout maps to `unknown`; the host never throws for a
156
+ platform outcome.
157
+
158
+ Sends are serial per account. Inbound ingests are buffered behind an in-flight
159
+ send so provider echoes are matched before they can become new events; an
160
+ overflow (100 events) disables that account and is logged as an error. After an
161
+ overflow drain, every delivery for the disabled account is paused, and the
162
+ overflowed event is dropped.
163
+
164
+ When `CHANNELD_MOCK_EMIT=1`, the mock adapter emits one `message.created` event
165
+ from room `in` after starting, so the relay can be exercised end to end.
166
+ `CHANNELD_MOCK_ECHO=1` makes it emit a provider echo right after a `send` result;
167
+ `CHANNELD_MOCK_ECHO_DELAY_MS` delays that result to exercise buffered ingests.
168
+
169
+ ## Feishu adapter (separate package)
170
+
171
+ The Feishu adapter lives in `@alexsun-top/chat-room-adapter-feishu`; its bundle is
172
+ `plugins/feishu/dist/feishu-adapter.js`. Outbound it sends interactive
173
+ cards and can reply natively to a Feishu message; inbound it can receive group
174
+ messages over the event long connection. It speaks the same stdio JSON-RPC protocol
175
+ as the mock adapter and has no room or session concepts.
176
+
177
+ Cards default to card 1.0 with `lark_md`, which keeps the 0.8.0 payload stable.
178
+ Set `FEISHU_CARD_VERSION=2.0` to opt into card 2.0 (`schema: "2.0"` with a
179
+ `markdown` element), where headings, lists, and fenced code render as block
180
+ Markdown. Any other value fails `initialize`.
181
+
182
+ A payload `parent` with `endpoint.platform: "feishu"`, the same account, and a
183
+ non-empty `nativeMessageId` is sent with
184
+ `POST /open-apis/im/v1/messages/{parent_id}/reply`; the body has no `receive_id`.
185
+ Without a usable Feishu parent the send uses the normal chat endpoint. The center
186
+ fills that parent when a forwarded room reply's `answer_to` parent was already
187
+ delivered to the same target (`channel_echoes` keeps the provider native id).
188
+
189
+ The adapter command is resolved from the host process working directory, so
190
+ use an absolute path unless the host starts in this package directory.
191
+
192
+ The child process reads:
193
+
194
+ - `FEISHU_APP_ID` (required)
195
+ - `FEISHU_APP_SECRET` (required)
196
+ - `FEISHU_BASE_URL` (optional, default `https://open.feishu.cn`)
197
+ - `FEISHU_HTTP_TIMEOUT_MS` (optional, default `10000`)
198
+ - `FEISHU_CARD_VERSION` (optional, `1.0` default or `2.0`)
199
+ - `FEISHU_INBOUND` (optional, `1` enables the event long connection)
200
+ - `FEISHU_INBOUND_CHATS` (required with `FEISHU_INBOUND=1`; comma-separated
201
+ group `chat_id` allowlist)
202
+
203
+ Set these in the host environment; the host passes its environment to adapter
204
+ child processes.
205
+
206
+ Inbound requires the app to use long-connection event subscription in the Feishu
207
+ developer console and to subscribe `im.message.receive_v1`; the bot must already
208
+ be in each allowlisted group. The adapter obtains the WebSocket URL from
209
+ `POST /callback/ws/endpoint`, pings, reassembles fragmented frames, and
210
+ acknowledges only after the host commits the ingest. Only group `text` and `post`
211
+ messages from human senders in an allowlisted chat are mapped. Bot/self senders,
212
+ other chats, other event types, other apps, and unsupported message types are
213
+ acknowledged without ingest. A long-connection start failure logs a warning,
214
+ keeps the account started for outbound sends, and reports a sanitized
215
+ `inbound failed: ...` in the account status; outbound forwarding keeps working.
216
+
217
+ ```yaml
218
+ accounts:
219
+ - id: feishu-bot
220
+ platform: feishu
221
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.js"], runtime: "node" }
222
+ rules:
223
+ - id: to-feishu
224
+ version: 1
225
+ from: { platform: chatroom, account: lab, room: translation, event: message.created }
226
+ transforms: [ { op: prefix-source }, { op: truncate, max: 2000 } ]
227
+ to: [ { platform: feishu, account: feishu-bot, room: oc_xxx } ]
228
+ ```
229
+
230
+ The target room is the Feishu `chat_id`, so an endpoint
231
+ `feishu/<account>/<chat_id>` maps to one Feishu chat.
232
+
233
+ `initialize` fails when a credential is missing. `start` fetches a tenant access
234
+ token, so rejected credentials disable only this account. Tokens are cached and
235
+ refreshed when less than 30 minutes remain. A send posts an interactive card and
236
+ a `uuid` derived from the delivery idempotency key, so retrying the same delivery
237
+ cannot create a second message. Card 1.0 uses one `lark_md` element; card 2.0
238
+ uses one `markdown` element. A Feishu parent reference turns the send into a native
239
+ reply to that message.
240
+
241
+ Send outcomes:
242
+
243
+ - `230020`, `99991400`, or HTTP 429: `rate_limited`; `Retry-After` accepts
244
+ seconds or an HTTP date and defaults to 1000 ms.
245
+ - `99991663`: force one token refresh and retry the send once, then `permanent`.
246
+ - HTTP 5xx, connection resets, and other fetch network errors: `retryable`.
247
+ - Request timeout or abort: `unknown`, never retried automatically.
248
+ - Other Feishu codes (for example `230002`): `permanent` with code and message.
249
+ - Malformed response: `unknown`.
250
+
251
+ The adapter never logs message text, credentials, tokens, uuids, or full
252
+ payloads. Provider message ids may be logged and returned in the receipt.
253
+
254
+ ## State
255
+
256
+ The SQLite state file has four tables:
257
+
258
+ - `channel_events`: committed ingest events, unique by dedup key.
259
+ - `channel_deliveries`: one frozen delivery per rule target, unique by
260
+ idempotency key (`trigger:rule:version:0:target`).
261
+ - `channel_receipts`: one observation per send attempt.
262
+ - `channel_echoes`: provider message ids that originated from this host, used to
263
+ skip echo ingests.
264
+
265
+ Delivery states: `pending → in_flight → sent`; `retryable` and `rate_limited`
266
+ retry only that account's queue with capped backoff (8 attempts, then
267
+ `exhausted`); `permanent` and `unsupported` are terminal; `unknown` leaves the
268
+ delivery in `unknown` and never retries automatically; `paused` keeps a disabled
269
+ account's rows out of every claim until the next host start. An adapter that
270
+ fails to start or writes non-protocol stdout disables only that account until
271
+ restart; its queued deliveries move to `paused` and return to `pending` when the
272
+ host starts again. Inbound room notifications add one small
273
+ `channel_inbound_relays(event_id, room_id)` marker table to the room database;
274
+ it exists only to make the room append idempotent. Per-account `readChannelStats` states are `started` (adapter
275
+ running), `failed` (startup failure, including a platform mismatch), `disabled`
276
+ (disabled at runtime), or `unknown` without a live host. `lastError` is capped,
277
+ flattened to one line, and redacts credential-shaped `token=…`/`secret=…`
278
+ fragments. On disable or crash, in-flight deliveries move to `unknown`
279
+ with the reason; a deliberate host stop also settles remaining in-flight rows as
280
+ `unknown`, so a centered reload cannot auto-resend them. A host start resets
281
+ stale `in_flight` rows from a previous crash to `pending`. If every account becomes disabled at runtime, the host logs
282
+ `all accounts disabled; host idle until restart` and stays alive; only a startup
283
+ with zero usable adapters fails. `onUnsupported: drop` skips empty renders; otherwise the
284
+ payload carries an `attachment/format unsupported` notice. Replies without a
285
+ target parent mapping are sent unthreaded with `degraded: "unthreaded"`, or
286
+ dropped when `onMissingParent: drop`.
287
+
288
+ ## Center delivery results (M2)
289
+
290
+ `HostDeps.onDeliveryResult(event, delivery, receipt)` fires once per delivery when
291
+ it reaches a terminal state: `sent`, `permanent`, `unsupported`, `exhausted`, or
292
+ `unknown`. `receipt` is present only when a receipt row exists for that attempt.
293
+ When an account is disabled or its adapter crashes, in-flight deliveries settle as
294
+ `unknown` and report with `receipt: undefined`; no receipt row is invented.
295
+ Retryable and rate-limited attempts never report, and a delivery reports at most
296
+ once.
297
+
298
+ Every terminal delivery also records exactly one `result.published` event in
299
+ `channel_events`. Its payload holds ids, delivery state, and target only — never
300
+ message text, error detail, or provider secrets — and `readChannelStats` reports
301
+ it as `publishedResults` while excluding it from source gaps. Rules never match or
302
+ forward `result.published`; the center writes the localized terminal system
303
+ message from that terminal result. Deliveries abandoned at startup because their
304
+ account is no longer configured are also reported as `unknown` and receive the
305
+ same terminal result event and message.
306
+
307
+ ## Non-goals (0.1 MVP)
308
+
309
+ - no config hot reload — rule changes require a restart (each delivery still freezes ruleId + ruleVersion + rendered payload);
310
+ - no one-click manual resend command — `unknown` deliveries only guarantee no duplicate delivery row if resent (unique idempotency key); they are never auto-resent;
311
+ - no full backpressure (high-water marks, pausing ingress, disk quotas) — only per-account queue/process isolation and `rate_limited` backoff;
312
+ - no attachments, no rule UI, no multi-tenant permission model, no exactly-once
313
+ guarantee (inbound room notifications are idempotent per event and route, but
314
+ a crash between the ACK and Feishu's next retry can still lose an event).
@@ -0,0 +1,40 @@
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
+ export declare class AdapterProcess {
29
+ #private;
30
+ constructor(options: AdapterProcessOptions);
31
+ get accountId(): string;
32
+ get capabilities(): AdapterCapabilities | undefined;
33
+ start(): Promise<void>;
34
+ /**
35
+ * Send one delivery. Platform outcomes are returned; protocol failures and
36
+ * timeouts become state "unknown" and never throw.
37
+ */
38
+ send(deliveryId: string, attemptId: string, idempotencyKey: string, target: Endpoint, payload: unknown): Promise<SendReceipt>;
39
+ stop(): Promise<void>;
40
+ }