@alexsun-top/chat-room-channeld 0.0.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.
package/README.md CHANGED
@@ -6,9 +6,10 @@ event into frozen deliveries for target accounts; each adapter owns one IM
6
6
  account and speaks JSON-RPC over stdio.
7
7
 
8
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.
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
14
  The core ships the source plus the mock adapter entry point. Use
14
15
  `GET /channeld/status` on the ChatRoom server, or run the CLI from a checkout
@@ -121,7 +122,7 @@ retries. A room that stays missing keeps failing until it is created.
121
122
  accounts:
122
123
  - id: feishu-main
123
124
  platform: feishu
124
- adapter: { command: ["node", "/opt/chatroom/feishu-adapter.js"] }
125
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"] }
125
126
  env: { FEISHU_APP_ID: "cli_xxx", FEISHU_APP_SECRET: "xxx" }
126
127
  ```
127
128
 
@@ -166,10 +167,15 @@ from room `in` after starting, so the relay can be exercised end to end.
166
167
  `CHANNELD_MOCK_ECHO=1` makes it emit a provider echo right after a `send` result;
167
168
  `CHANNELD_MOCK_ECHO_DELAY_MS` delays that result to exercise buffered ingests.
168
169
 
169
- ## Feishu adapter (separate package)
170
+ ## Feishu adapter
170
171
 
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
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
173
179
  cards and can reply natively to a Feishu message; inbound it can receive group
174
180
  messages over the event long connection. It speaks the same stdio JSON-RPC protocol
175
181
  as the mock adapter and has no room or session concepts.
@@ -218,7 +224,7 @@ keeps the account started for outbound sends, and reports a sanitized
218
224
  accounts:
219
225
  - id: feishu-bot
220
226
  platform: feishu
221
- adapter: { command: ["node", "/opt/chatroom/feishu-adapter.js"], runtime: "node" }
227
+ adapter: { command: ["node", "/opt/chatroom/feishu-adapter.ts"], runtime: "node" }
222
228
  rules:
223
229
  - id: to-feishu
224
230
  version: 1
package/dist/adapter.d.ts CHANGED
@@ -25,12 +25,25 @@ export interface AdapterProcessOptions extends AdapterContext {
25
25
  initializeTimeoutMs?: number;
26
26
  sendTimeoutMs?: number;
27
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;
28
33
  export declare class AdapterProcess {
29
34
  #private;
30
35
  constructor(options: AdapterProcessOptions);
31
36
  get accountId(): string;
32
37
  get capabilities(): AdapterCapabilities | undefined;
33
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
+ }>;
34
47
  /**
35
48
  * Send one delivery. Platform outcomes are returned; protocol failures and
36
49
  * timeouts become state "unknown" and never throw.
package/dist/adapter.js CHANGED
@@ -14,7 +14,67 @@ const SEND_STATES = [
14
14
  const STDERR_TAIL_LIMIT = 4096;
15
15
  const DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;
16
16
  const DEFAULT_SEND_TIMEOUT_MS = 15_000;
17
+ const ADAPTER_NODE_OPTIONS = [
18
+ "--experimental-transform-types",
19
+ "--disable-warning=ExperimentalWarning",
20
+ ];
21
+ /**
22
+ * Adapter children execute uploaded .ts plugins, so they get Node's full
23
+ * TypeScript transform; the server process itself stays strip-only.
24
+ */
25
+ export function adapterChildEnv(account) {
26
+ const env = { ...process.env, ...account.env };
27
+ let options = env.NODE_OPTIONS?.trim() ?? "";
28
+ for (const flag of ADAPTER_NODE_OPTIONS) {
29
+ if (!options.split(/\s+/).includes(flag))
30
+ options = options ? `${options} ${flag}` : flag;
31
+ }
32
+ env.NODE_OPTIONS = options;
33
+ // Forced after account env: config validation also rejects these keys.
34
+ env.CHANNELD_ACCOUNT_ID = account.id;
35
+ env.CHANNELD_PLATFORM = account.platform;
36
+ return env;
37
+ }
17
38
  /** Keep only well-formed adapter-declared facts; unknown fields are ignored. */
39
+ function readAccountFields(value) {
40
+ if (!Array.isArray(value))
41
+ return undefined;
42
+ const fields = [];
43
+ const seen = new Set();
44
+ for (const item of value) {
45
+ if (!item || typeof item !== "object")
46
+ continue;
47
+ const raw = item;
48
+ const key = typeof raw.key === "string" ? raw.key.trim() : "";
49
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) || seen.has(key))
50
+ continue;
51
+ const field = { key };
52
+ if (typeof raw.label === "string" && raw.label.trim())
53
+ field.label = raw.label.trim();
54
+ if (typeof raw.type === "string" && ["string", "secret", "boolean", "number", "select"].includes(raw.type)) {
55
+ field.type = raw.type;
56
+ }
57
+ if (raw.required === true)
58
+ field.required = true;
59
+ if (typeof raw.default === "string")
60
+ field.default = raw.default;
61
+ if (typeof raw.description === "string" && raw.description.trim())
62
+ field.description = raw.description.trim();
63
+ if (Array.isArray(raw.options)) {
64
+ const options = raw.options
65
+ .filter((option) => Boolean(option) && typeof option === "object")
66
+ .map((option) => typeof option.value === "string" && option.value
67
+ ? { value: option.value, ...(typeof option.label === "string" && option.label ? { label: option.label } : {}) }
68
+ : undefined)
69
+ .filter((option) => Boolean(option));
70
+ if (options.length)
71
+ field.options = options;
72
+ }
73
+ seen.add(key);
74
+ fields.push(field);
75
+ }
76
+ return fields.length ? fields : undefined;
77
+ }
18
78
  function readCapabilities(result, accountId) {
19
79
  if (!result || typeof result !== "object")
20
80
  return undefined;
@@ -45,6 +105,14 @@ function readCapabilities(result, accountId) {
45
105
  }
46
106
  }
47
107
  }
108
+ const account = entry.account;
109
+ if (account && typeof account === "object") {
110
+ const value = account;
111
+ const schema = readAccountFields(value.schema);
112
+ const env = readAccountFields(value.env);
113
+ if (schema || env)
114
+ capabilities.account = { ...(schema ? { schema } : {}), ...(env ? { env } : {}) };
115
+ }
48
116
  return Object.keys(capabilities).length ? capabilities : undefined;
49
117
  }
50
118
  export class AdapterProcess {
@@ -88,13 +156,7 @@ export class AdapterProcess {
88
156
  throw new Error(`adapter ${this.#account.id} has an empty command`);
89
157
  const child = spawn(command, args, {
90
158
  stdio: ["pipe", "pipe", "pipe"],
91
- env: {
92
- ...process.env,
93
- ...this.#account.env,
94
- // Forced after account env: config validation also rejects these keys.
95
- CHANNELD_ACCOUNT_ID: this.#account.id,
96
- CHANNELD_PLATFORM: this.#account.platform,
97
- },
159
+ env: adapterChildEnv(this.#account),
98
160
  });
99
161
  this.#child = child;
100
162
  this.#attach(child);
@@ -123,6 +185,49 @@ export class AdapterProcess {
123
185
  this.#started = true;
124
186
  log.info("adapter started", { account: this.#account.id });
125
187
  }
188
+ /**
189
+ * Read-only handshake used when a plugin is uploaded: initialize only, then
190
+ * kill. It does not start the account and does not need credentials.
191
+ */
192
+ async probe() {
193
+ if (this.#child)
194
+ throw new Error(`adapter ${this.#account.id} already started`);
195
+ const [command, ...args] = this.#account.adapter.command;
196
+ if (!command)
197
+ throw new Error(`adapter ${this.#account.id} has an empty command`);
198
+ const child = spawn(command, args, {
199
+ stdio: ["pipe", "pipe", "pipe"],
200
+ env: adapterChildEnv(this.#account),
201
+ });
202
+ this.#child = child;
203
+ this.#attach(child);
204
+ try {
205
+ const initialized = await this.#call("initialize", {
206
+ protocolVersions: [PROTOCOL_VERSION],
207
+ eventSchemas: [EVENT_SCHEMA_VERSION],
208
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
209
+ platform: this.#account.platform,
210
+ accounts: [this.#account.id],
211
+ maxFrameBytes: MAX_FRAME_BYTES,
212
+ }, this.#initializeTimeoutMs);
213
+ const reported = initialized && typeof initialized === "object"
214
+ ? initialized.platform
215
+ : undefined;
216
+ this.#capabilities = readCapabilities(initialized, this.#account.id);
217
+ return {
218
+ ...(typeof reported === "string" && reported.trim() ? { platform: reported.trim() } : {}),
219
+ ...(this.#capabilities ? { capabilities: this.#capabilities } : {}),
220
+ };
221
+ }
222
+ catch (error) {
223
+ const tail = this.#stderrTail.trim();
224
+ const message = this.#pollutionError?.message ?? (error instanceof Error ? error.message : String(error));
225
+ throw new Error(`adapter probe failed: ${message}${tail ? `\nstderr:\n${tail}` : ""}`);
226
+ }
227
+ finally {
228
+ await this.stop().catch(() => undefined);
229
+ }
230
+ }
126
231
  /**
127
232
  * Send one delivery. Platform outcomes are returned; protocol failures and
128
233
  * timeouts become state "unknown" and never throw.
@@ -38,10 +38,33 @@ export type AttachmentCapabilities = {
38
38
  imageMaxBytes?: number;
39
39
  fileMaxBytes?: number;
40
40
  };
41
+ /**
42
+ * One account setting declared by an adapter. `key` is the env variable the
43
+ * adapter process reads; the UI renders the field and stores its value there.
44
+ */
45
+ export type AccountField = {
46
+ key: string;
47
+ label?: string;
48
+ type?: "string" | "secret" | "boolean" | "number" | "select";
49
+ required?: boolean;
50
+ default?: string;
51
+ description?: string;
52
+ options?: Array<{
53
+ value: string;
54
+ label?: string;
55
+ }>;
56
+ };
57
+ export type AccountCapabilities = {
58
+ /** Primary form fields, in display order. */
59
+ schema?: AccountField[];
60
+ /** Advanced env declarations; keys not covered here stay free-form. */
61
+ env?: AccountField[];
62
+ };
41
63
  /** Adapter-declared platform facts the generic host must not hardcode. */
42
64
  export type AdapterCapabilities = {
43
65
  displayName?: string;
44
66
  attachments?: AttachmentCapabilities;
67
+ account?: AccountCapabilities;
45
68
  };
46
69
  export interface IngestEvent {
47
70
  schemaVersion: number;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexsun-top/chat-room-channeld",
3
- "version": "0.0.0",
3
+ "version": "0.8.2",
4
4
  "description": "Channel D relay core: a host that relays chat-room events to external IM accounts through adapter child processes.",
5
5
  "type": "module",
6
6
  "repository": {
package/src/adapter.ts CHANGED
@@ -63,6 +63,28 @@ const STDERR_TAIL_LIMIT = 4096;
63
63
  const DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;
64
64
  const DEFAULT_SEND_TIMEOUT_MS = 15_000;
65
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
+
66
88
  /** Keep only well-formed adapter-declared facts; unknown fields are ignored. */
67
89
  function readAccountFields(value: unknown): AccountField[] | undefined {
68
90
  if (!Array.isArray(value)) return undefined;
@@ -176,13 +198,7 @@ export class AdapterProcess {
176
198
  if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
177
199
  const child = spawn(command, args, {
178
200
  stdio: ["pipe", "pipe", "pipe"],
179
- env: {
180
- ...process.env,
181
- ...this.#account.env,
182
- // Forced after account env: config validation also rejects these keys.
183
- CHANNELD_ACCOUNT_ID: this.#account.id,
184
- CHANNELD_PLATFORM: this.#account.platform,
185
- },
201
+ env: adapterChildEnv(this.#account),
186
202
  });
187
203
  this.#child = child;
188
204
  this.#attach(child);
@@ -233,12 +249,7 @@ export class AdapterProcess {
233
249
  if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
234
250
  const child = spawn(command, args, {
235
251
  stdio: ["pipe", "pipe", "pipe"],
236
- env: {
237
- ...process.env,
238
- ...this.#account.env,
239
- CHANNELD_ACCOUNT_ID: this.#account.id,
240
- CHANNELD_PLATFORM: this.#account.platform,
241
- },
252
+ env: adapterChildEnv(this.#account),
242
253
  });
243
254
  this.#child = child;
244
255
  this.#attach(child);
@@ -3,7 +3,7 @@ import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3
3
  import { tmpdir } from "node:os";
4
4
  import path from "node:path";
5
5
  import { PassThrough } from "node:stream";
6
- import { AdapterProcess } from "../src/adapter.ts";
6
+ import { AdapterProcess, adapterChildEnv } from "../src/adapter.ts";
7
7
  import type { AccountConfig } from "../src/config.ts";
8
8
  import { AdapterGoneError, writeFrame } from "../src/framing.ts";
9
9
 
@@ -127,3 +127,81 @@ describe("adapter probe", () => {
127
127
  expect(existsSync(marker)).toBe(false);
128
128
  });
129
129
  });
130
+
131
+ const ENUM_ADAPTER = `
132
+ enum Mode { Ready = "ready" }
133
+ let buffer = "";
134
+ process.stdin.on("data", (chunk) => {
135
+ buffer += chunk.toString("utf8");
136
+ let newline = buffer.indexOf("\\n");
137
+ while (newline !== -1) {
138
+ const request = JSON.parse(buffer.slice(0, newline));
139
+ buffer = buffer.slice(newline + 1);
140
+ const mode: Mode = Mode.Ready;
141
+ process.stdout.write(JSON.stringify({
142
+ jsonrpc: "2.0", id: request.id,
143
+ result: request.method === "initialize"
144
+ ? {
145
+ version: 1, eventSchema: 1, platform: "enum-platform", maxFrameBytes: 1048576,
146
+ accounts: { [process.env.CHANNELD_ACCOUNT_ID]: { displayName: "Enum " + mode } },
147
+ }
148
+ : { ready: true },
149
+ }) + "\\n");
150
+ newline = buffer.indexOf("\\n");
151
+ }
152
+ });
153
+ setInterval(() => {}, 1000);
154
+ `;
155
+
156
+ describe("adapter TypeScript transform", () => {
157
+ const node = Bun.which("node");
158
+
159
+ test("a .ts adapter with enum starts and probes", async () => {
160
+ if (!node) throw new Error("node is required to run the adapter TypeScript test");
161
+ const root = tempDir();
162
+ const script = path.join(root, "enum-adapter.ts");
163
+ writeFileSync(script, ENUM_ADAPTER);
164
+ const account = (id: string): AccountConfig => ({
165
+ id,
166
+ platform: "enum-platform",
167
+ adapter: { command: [node, script] },
168
+ });
169
+ const serverOptions = process.env.NODE_OPTIONS;
170
+
171
+ const probed = await new AdapterProcess({
172
+ account: account("enum-probe"),
173
+ onIngest: async () => ({ duplicate: false }),
174
+ onExit: () => {},
175
+ initializeTimeoutMs: 2000,
176
+ }).probe();
177
+ expect(probed.platform).toBe("enum-platform");
178
+ expect(probed.capabilities?.displayName).toBe("Enum ready");
179
+
180
+ const adapter = new AdapterProcess({
181
+ account: account("enum-start"),
182
+ onIngest: async () => ({ duplicate: false }),
183
+ onExit: () => {},
184
+ initializeTimeoutMs: 2000,
185
+ });
186
+ await adapter.start();
187
+ expect(adapter.capabilities?.displayName).toBe("Enum ready");
188
+ await adapter.stop();
189
+ expect(process.env.NODE_OPTIONS).toBe(serverOptions);
190
+ });
191
+
192
+ test("adapter child env appends transform flags without duplicates", () => {
193
+ const previous = process.env.NODE_OPTIONS;
194
+ process.env.NODE_OPTIONS = "--max-old-space-size=256 --experimental-transform-types";
195
+ try {
196
+ const env = adapterChildEnv({ id: "acct", platform: "mock", adapter: { command: ["unused"] } });
197
+ expect(env.NODE_OPTIONS).toBe(
198
+ "--max-old-space-size=256 --experimental-transform-types --disable-warning=ExperimentalWarning",
199
+ );
200
+ expect(env.CHANNELD_ACCOUNT_ID).toBe("acct");
201
+ expect(process.env.NODE_OPTIONS).toBe("--max-old-space-size=256 --experimental-transform-types");
202
+ } finally {
203
+ if (previous === undefined) delete process.env.NODE_OPTIONS;
204
+ else process.env.NODE_OPTIONS = previous;
205
+ }
206
+ });
207
+ });