@alexsun-top/opencode-chat-room 0.7.8 → 0.8.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 (67) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/LICENSE +21 -0
  3. package/README.md +45 -36
  4. package/README.zh-CN.md +50 -41
  5. package/dist/cli.js +2629 -350
  6. package/package.json +13 -3
  7. package/packages/chat-room-channeld/README.md +242 -0
  8. package/packages/chat-room-channeld/dist/feishu-adapter.js +499 -0
  9. package/packages/chat-room-channeld/dist/mock-adapter.js +295 -0
  10. package/packages/chat-room-channeld/src/adapter.ts +475 -0
  11. package/packages/chat-room-channeld/src/cli.ts +124 -0
  12. package/packages/chat-room-channeld/src/config.ts +207 -0
  13. package/packages/chat-room-channeld/src/delivery.ts +158 -0
  14. package/packages/chat-room-channeld/src/feishu-adapter.ts +473 -0
  15. package/packages/chat-room-channeld/src/framing.ts +128 -0
  16. package/packages/chat-room-channeld/src/host-helpers.ts +41 -0
  17. package/packages/chat-room-channeld/src/host.ts +509 -0
  18. package/packages/chat-room-channeld/src/ingest-gate.ts +108 -0
  19. package/packages/chat-room-channeld/src/log.ts +26 -0
  20. package/packages/chat-room-channeld/src/mock-adapter.ts +206 -0
  21. package/packages/chat-room-channeld/src/protocol.ts +75 -0
  22. package/packages/chat-room-channeld/src/published.ts +37 -0
  23. package/packages/chat-room-channeld/src/rules.ts +127 -0
  24. package/packages/chat-room-channeld/src/state.ts +485 -0
  25. package/packages/chat-room-channeld/src/stats.ts +167 -0
  26. package/plugin.ts +22 -5
  27. package/server/addressing-routes.ts +130 -0
  28. package/server/assets/NOTICE.txt +2 -2
  29. package/server/assets/SHIKI-LICENSE +22 -0
  30. package/server/assets/base.css +9 -1
  31. package/server/assets/chat/doc-preview.js +3 -4
  32. package/server/assets/chat/forward.js +69 -0
  33. package/server/assets/chat/index.js +2 -0
  34. package/server/assets/chat/locales/de.js +5 -0
  35. package/server/assets/chat/locales/es.js +5 -0
  36. package/server/assets/chat/locales/fr.js +5 -0
  37. package/server/assets/chat/locales/it.js +5 -0
  38. package/server/assets/chat/locales/ja.js +5 -0
  39. package/server/assets/chat/locales/ko.js +5 -0
  40. package/server/assets/chat/markdown-footnotes.js +115 -0
  41. package/server/assets/chat/markdown.js +24 -35
  42. package/server/assets/chat/palette.js +1 -1
  43. package/server/assets/chat/replies.js +7 -1
  44. package/server/assets/chat/shiki.js +87 -0
  45. package/server/assets/chat/side-pane.js +8 -1
  46. package/server/assets/chat/state.js +14 -1
  47. package/server/assets/chat/system-messages.js +2 -0
  48. package/server/assets/code-highlight.css +20 -31
  49. package/server/assets/conversation.css +3 -2
  50. package/server/assets/doc-preview.css +2 -1
  51. package/server/assets/responsive.css +5 -0
  52. package/server/assets/shiki.bundle.js +152 -0
  53. package/server/channels.ts +314 -0
  54. package/server/chat-server.ts +27 -4
  55. package/server/chat.html +10 -3
  56. package/server/sw.js +1 -2
  57. package/skills/chatroom/SKILL.md +1 -1
  58. package/src/center/center-client.ts +79 -1
  59. package/src/config/file-config.ts +34 -0
  60. package/src/runtime/v2-plugin.ts +8 -2
  61. package/src/runtime/watch.ts +3 -2
  62. package/src/state/sqlite-state.ts +42 -11
  63. package/src/state/store.ts +9 -3
  64. package/src/tui/http.mjs +16 -2
  65. package/src/tui/main.mjs +1 -1
  66. package/server/assets/HIGHLIGHT-LICENSE +0 -29
  67. package/server/assets/highlight-10.7.3.min.js +0 -1358
@@ -0,0 +1,475 @@
1
+ import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2
+ import { StringDecoder } from "node:string_decoder";
3
+ import type { AccountConfig } from "./config.ts";
4
+ import { AdapterGoneError, createFrameReader, writeFrame } from "./framing.ts";
5
+ import { log } from "./log.ts";
6
+ import {
7
+ EVENT_SCHEMA_VERSION,
8
+ MAX_FRAME_BYTES,
9
+ PROTOCOL_VERSION,
10
+ RPC_INTERNAL_ERROR,
11
+ RPC_METHOD_NOT_FOUND,
12
+ hostRequestId,
13
+ rpcError,
14
+ rpcRequest,
15
+ rpcResult,
16
+ type Endpoint,
17
+ type IngestEvent,
18
+ type JsonRpcId,
19
+ type MessageRef,
20
+ } from "./protocol.ts";
21
+
22
+ export type SendState = "sent" | "retryable" | "rate_limited" | "permanent" | "unsupported" | "unknown";
23
+
24
+ export interface SendReceipt {
25
+ state: SendState;
26
+ providerMessage?: MessageRef;
27
+ retryAfterMs?: number;
28
+ detail?: string;
29
+ }
30
+
31
+ export interface AdapterContext {
32
+ onIngest(event: IngestEvent): Promise<{ duplicate: boolean; eventId?: string }>;
33
+ onExit(code: number | null, signal: NodeJS.Signals | null): void;
34
+ onUnavailable?(reason: string): void;
35
+ }
36
+
37
+ export interface AdapterProcessOptions extends AdapterContext {
38
+ account: AccountConfig;
39
+ initializeTimeoutMs?: number;
40
+ sendTimeoutMs?: number;
41
+ }
42
+
43
+ interface PendingCall {
44
+ resolve(value: unknown): void;
45
+ reject(error: Error): void;
46
+ timer: ReturnType<typeof setTimeout>;
47
+ }
48
+
49
+ const SEND_STATES: readonly SendState[] = [
50
+ "sent",
51
+ "retryable",
52
+ "rate_limited",
53
+ "permanent",
54
+ "unsupported",
55
+ "unknown",
56
+ ];
57
+
58
+ const STDERR_TAIL_LIMIT = 4096;
59
+ const DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;
60
+ const DEFAULT_SEND_TIMEOUT_MS = 15_000;
61
+
62
+ export class AdapterProcess {
63
+ readonly #account: AccountConfig;
64
+ readonly #onIngest: AdapterContext["onIngest"];
65
+ readonly #onExit: AdapterContext["onExit"];
66
+ readonly #onUnavailable: AdapterContext["onUnavailable"];
67
+ readonly #initializeTimeoutMs: number;
68
+ readonly #sendTimeoutMs: number;
69
+ readonly #pending = new Map<string, PendingCall>();
70
+ readonly #stderrDecoder = new StringDecoder("utf8");
71
+ #child?: ChildProcessWithoutNullStreams;
72
+ #sequence = 0;
73
+ #stderrTail = "";
74
+ #started = false;
75
+ #stopping = false;
76
+ #gone = false;
77
+ #pollutionError?: Error;
78
+
79
+ constructor(options: AdapterProcessOptions) {
80
+ this.#account = options.account;
81
+ this.#onIngest = options.onIngest;
82
+ this.#onExit = options.onExit;
83
+ this.#onUnavailable = options.onUnavailable;
84
+ this.#initializeTimeoutMs = options.initializeTimeoutMs ?? DEFAULT_INITIALIZE_TIMEOUT_MS;
85
+ this.#sendTimeoutMs = options.sendTimeoutMs ?? DEFAULT_SEND_TIMEOUT_MS;
86
+ }
87
+
88
+ get accountId(): string {
89
+ return this.#account.id;
90
+ }
91
+
92
+ async start(): Promise<void> {
93
+ if (this.#child) throw new Error(`adapter ${this.#account.id} already started`);
94
+ const [command, ...args] = this.#account.adapter.command;
95
+ if (!command) throw new Error(`adapter ${this.#account.id} has an empty command`);
96
+ const child = spawn(command, args, {
97
+ stdio: ["pipe", "pipe", "pipe"],
98
+ env: {
99
+ ...process.env,
100
+ CHANNELD_ACCOUNT_ID: this.#account.id,
101
+ CHANNELD_PLATFORM: this.#account.platform,
102
+ },
103
+ });
104
+ this.#child = child;
105
+ this.#attach(child);
106
+
107
+ try {
108
+ await this.#call(
109
+ "initialize",
110
+ {
111
+ protocolVersions: [PROTOCOL_VERSION],
112
+ eventSchemas: [EVENT_SCHEMA_VERSION],
113
+ sessionEpoch: `${Date.now().toString(36)}-${process.pid}`,
114
+ platform: this.#account.platform,
115
+ accounts: [this.#account.id],
116
+ maxFrameBytes: MAX_FRAME_BYTES,
117
+ },
118
+ this.#initializeTimeoutMs,
119
+ );
120
+ await this.#call(
121
+ "start",
122
+ { accounts: [this.#account.id], cursors: {} },
123
+ this.#initializeTimeoutMs,
124
+ );
125
+ } catch (error) {
126
+ const tail = this.#stderrTail.trim();
127
+ const message = this.#pollutionError?.message
128
+ ?? (error instanceof Error ? error.message : String(error));
129
+ this.#stopping = true;
130
+ this.#killNow();
131
+ throw new Error(
132
+ `adapter ${this.#account.id} failed to start: ${message}${tail ? `\nstderr:\n${tail}` : ""}`,
133
+ );
134
+ }
135
+
136
+ this.#started = true;
137
+ log.info("adapter started", { account: this.#account.id });
138
+ }
139
+
140
+ /**
141
+ * Send one delivery. Platform outcomes are returned; protocol failures and
142
+ * timeouts become state "unknown" and never throw.
143
+ */
144
+ async send(
145
+ deliveryId: string,
146
+ attemptId: string,
147
+ idempotencyKey: string,
148
+ target: Endpoint,
149
+ payload: unknown,
150
+ ): Promise<SendReceipt> {
151
+ if (!this.#started || !this.#child) {
152
+ return { state: "unknown", detail: "adapter is not running" };
153
+ }
154
+ try {
155
+ const result = await this.#call(
156
+ "send",
157
+ { deliveryId, attemptId, idempotencyKey, target, payload },
158
+ this.#sendTimeoutMs,
159
+ );
160
+ const raw = (result ?? {}) as Partial<SendReceipt>;
161
+ if (!raw.state || !SEND_STATES.includes(raw.state)) {
162
+ return { state: "unknown", detail: `adapter returned invalid state: ${String(raw.state)}` };
163
+ }
164
+ return {
165
+ state: raw.state,
166
+ providerMessage: raw.providerMessage,
167
+ retryAfterMs: raw.retryAfterMs,
168
+ detail: raw.detail,
169
+ };
170
+ } catch (error) {
171
+ return { state: "unknown", detail: error instanceof Error ? error.message : String(error) };
172
+ }
173
+ }
174
+
175
+ async stop(): Promise<void> {
176
+ if (this.#stopping) return;
177
+ this.#stopping = true;
178
+ this.#started = false;
179
+ const child = this.#child;
180
+ this.#rejectPending(new AdapterGoneError(`adapter ${this.#account.id} stopped`));
181
+ if (!child) {
182
+ this.#cleanup();
183
+ return;
184
+ }
185
+ try {
186
+ try {
187
+ await this.#call("shutdown", {}, 1000);
188
+ } catch {
189
+ // Shutdown is best effort; the exit escalation below is authoritative.
190
+ }
191
+ try {
192
+ child.stdin.end();
193
+ } catch {
194
+ // stdin may already be closed.
195
+ }
196
+ if (await this.#waitForExit(2000)) return;
197
+ child.kill("SIGTERM");
198
+ if (await this.#waitForExit(1000)) return;
199
+ child.kill("SIGKILL");
200
+ await this.#waitForExit(1000);
201
+ } catch (error) {
202
+ try {
203
+ log.warn(
204
+ `adapter stop failed: ${error instanceof Error ? error.message : String(error)}`,
205
+ { account: this.#account.id },
206
+ );
207
+ } catch {
208
+ // Stop must never throw.
209
+ }
210
+ } finally {
211
+ this.#cleanup();
212
+ }
213
+ }
214
+
215
+ #attach(child: ChildProcessWithoutNullStreams): void {
216
+ child.stdin.on("error", (error: Error) => this.#handleStdioError("stdin", error));
217
+ child.stdout.on("error", (error: Error) => this.#handleStdioError("stdout", error));
218
+ child.stderr.on("error", (error: Error) => this.#handleStdioError("stderr", error));
219
+
220
+ const read = createFrameReader(
221
+ (message) => {
222
+ // Never await dispatch here: an ingest buffered behind a send must not
223
+ // block the send result frame that follows it in the same chunk.
224
+ void this.#dispatch(message).catch((error: unknown) => {
225
+ this.#markGone(
226
+ `adapter ${this.#account.id} dispatch failed: ${error instanceof Error ? error.message : String(error)}`,
227
+ );
228
+ });
229
+ },
230
+ (error) => this.#handleStdoutPollution(error),
231
+ );
232
+ child.stdout.on("data", (chunk: Buffer) => read(chunk));
233
+
234
+ child.stderr.on("data", (chunk: Buffer) => {
235
+ const text = this.#stderrDecoder.write(chunk);
236
+ this.#stderrTail = `${this.#stderrTail}${text}`.slice(-STDERR_TAIL_LIMIT);
237
+ for (const line of text.split("\n")) {
238
+ if (line.trim()) log.info(line, { account: this.#account.id });
239
+ }
240
+ });
241
+
242
+ child.on("error", (error) => {
243
+ this.#markGone(`adapter process error: ${error.message}`);
244
+ });
245
+
246
+ child.once("exit", (code, signal) => {
247
+ this.#detachStreams(child);
248
+ this.#child = undefined;
249
+ this.#rejectPending(new Error(`adapter exited (code=${code} signal=${signal})`));
250
+ if (!this.#stopping && !this.#gone && this.#started) {
251
+ log.error(`adapter exited code=${code ?? "null"} signal=${signal ?? "none"}`, {
252
+ account: this.#account.id,
253
+ });
254
+ this.#onExit(code, signal);
255
+ }
256
+ this.#started = false;
257
+ });
258
+ }
259
+
260
+ #handleStdioError(streamName: string, error: unknown): void {
261
+ const message = error instanceof Error ? error.message : String(error);
262
+ this.#markGone(`adapter ${this.#account.id} ${streamName} error: ${message}`);
263
+ }
264
+
265
+ async #dispatch(message: Record<string, unknown>): Promise<void> {
266
+ const id = message.id as JsonRpcId | undefined;
267
+ if (id !== undefined && typeof message.method === "string") {
268
+ await this.#handleRequest(id, message.method, message.params);
269
+ return;
270
+ }
271
+ if (id === undefined) {
272
+ log.warn("adapter frame has no id", { account: this.#account.id });
273
+ return;
274
+ }
275
+ const pending = this.#pending.get(String(id));
276
+ if (!pending) {
277
+ log.warn(`adapter response for unknown id ${String(id)}`, { account: this.#account.id });
278
+ return;
279
+ }
280
+ this.#pending.delete(String(id));
281
+ clearTimeout(pending.timer);
282
+ const rpcFailure = message.error as { message?: string } | undefined;
283
+ if (rpcFailure) {
284
+ pending.reject(new Error(rpcFailure.message ?? "adapter JSON-RPC error"));
285
+ return;
286
+ }
287
+ pending.resolve(message.result);
288
+ }
289
+
290
+ async #handleRequest(id: JsonRpcId, method: string, params: unknown): Promise<void> {
291
+ const child = this.#child;
292
+ if (!child) return;
293
+ try {
294
+ if (method === "ingest") {
295
+ const result = await this.#onIngest(params as IngestEvent);
296
+ await writeFrame(
297
+ child.stdin,
298
+ rpcResult(id, result.duplicate ? { duplicate: true } : { committed: true }),
299
+ );
300
+ } else if (method === "ping") {
301
+ await writeFrame(child.stdin, rpcResult(id, { pong: true }));
302
+ } else {
303
+ await writeFrame(
304
+ child.stdin,
305
+ rpcError(id, RPC_METHOD_NOT_FOUND, `method not found: ${method}`),
306
+ );
307
+ }
308
+ } catch (error) {
309
+ if (error instanceof AdapterGoneError) {
310
+ this.#markGone(error.message);
311
+ return;
312
+ }
313
+ const message = error instanceof Error ? error.message : String(error);
314
+ const code = (error as { code?: string } | null)?.code;
315
+ if (code !== "ingest_buffer_overflow") {
316
+ try {
317
+ log.error(`adapter request ${method} failed: ${message}`, { account: this.#account.id });
318
+ } catch {
319
+ // Keep the request path alive.
320
+ }
321
+ }
322
+ try {
323
+ await writeFrame(child.stdin, rpcError(id, RPC_INTERNAL_ERROR, message));
324
+ } catch (writeError) {
325
+ if (writeError instanceof AdapterGoneError) this.#markGone(writeError.message);
326
+ }
327
+ }
328
+ }
329
+
330
+ #handleStdoutPollution(error: Error): void {
331
+ if (this.#pollutionError) return;
332
+ const message = `adapter ${this.#account.id} wrote non-protocol output to stdout; adapter stdout may contain protocol frames only, logs must go to stderr`;
333
+ this.#pollutionError = new Error(message);
334
+ try {
335
+ log.error(message, { account: this.#account.id });
336
+ } catch {
337
+ // Keep the pollution error path alive if stderr is unavailable.
338
+ }
339
+ this.#markGone(message, false);
340
+ }
341
+
342
+ #markGone(reason: string, logReason = true): void {
343
+ if (this.#gone) return;
344
+ this.#gone = true;
345
+ this.#stopping = true;
346
+ this.#started = false;
347
+ if (logReason) {
348
+ try {
349
+ log.warn(reason, { account: this.#account.id });
350
+ } catch {
351
+ // Never throw from an adapter-gone path.
352
+ }
353
+ }
354
+ try {
355
+ this.#onUnavailable?.(reason);
356
+ } catch (error) {
357
+ try {
358
+ log.error(
359
+ `adapter unavailable handler failed: ${error instanceof Error ? error.message : String(error)}`,
360
+ { account: this.#account.id },
361
+ );
362
+ } catch {
363
+ // Ignore logging failures.
364
+ }
365
+ }
366
+ this.#rejectPending(new AdapterGoneError(reason));
367
+ try {
368
+ this.#child?.kill("SIGKILL");
369
+ } catch {
370
+ // The child may already be gone.
371
+ }
372
+ }
373
+
374
+ #call(method: string, params: unknown, timeoutMs: number): Promise<unknown> {
375
+ return new Promise((resolve, reject) => {
376
+ if (this.#gone) {
377
+ reject(new AdapterGoneError(`adapter ${this.#account.id} is gone`));
378
+ return;
379
+ }
380
+ if (this.#pollutionError) {
381
+ reject(this.#pollutionError);
382
+ return;
383
+ }
384
+ const child = this.#child;
385
+ if (!child || child.stdin.destroyed || child.stdin.writableEnded) {
386
+ const error = new AdapterGoneError(`adapter ${this.#account.id} is not running`);
387
+ reject(error);
388
+ if (!this.#stopping) this.#markGone(error.message);
389
+ return;
390
+ }
391
+ const id = hostRequestId(++this.#sequence);
392
+ const timer = setTimeout(() => {
393
+ this.#pending.delete(id);
394
+ reject(new Error(`${method} timed out after ${timeoutMs}ms`));
395
+ }, timeoutMs);
396
+ this.#pending.set(id, {
397
+ resolve: (value) => {
398
+ clearTimeout(timer);
399
+ resolve(value);
400
+ },
401
+ reject: (error) => {
402
+ clearTimeout(timer);
403
+ reject(error);
404
+ },
405
+ timer,
406
+ });
407
+
408
+ const failedWrite = (error: unknown): void => {
409
+ this.#pending.delete(id);
410
+ clearTimeout(timer);
411
+ reject(error instanceof Error ? error : new Error(String(error)));
412
+ if (error instanceof AdapterGoneError && !this.#stopping) this.#markGone(error.message);
413
+ };
414
+ try {
415
+ void writeFrame(child.stdin, rpcRequest(id, method, params)).catch(failedWrite);
416
+ } catch (error) {
417
+ failedWrite(error);
418
+ }
419
+ });
420
+ }
421
+
422
+ #waitForExit(ms: number): Promise<boolean> {
423
+ const child = this.#child;
424
+ if (!child || child.exitCode !== null || child.signalCode !== null) return Promise.resolve(true);
425
+ return new Promise((resolve) => {
426
+ const timer = setTimeout(() => {
427
+ child.off("exit", onExit);
428
+ resolve(false);
429
+ }, ms);
430
+ const onExit = (): void => {
431
+ clearTimeout(timer);
432
+ resolve(true);
433
+ };
434
+ child.once("exit", onExit);
435
+ });
436
+ }
437
+
438
+ #rejectPending(error: Error): void {
439
+ for (const [id, pending] of this.#pending) {
440
+ this.#pending.delete(id);
441
+ clearTimeout(pending.timer);
442
+ pending.reject(error);
443
+ }
444
+ }
445
+
446
+ #detachStreams(child: ChildProcessWithoutNullStreams): void {
447
+ for (const stream of [child.stdin, child.stdout, child.stderr] as NodeJS.EventEmitter[]) {
448
+ stream.removeAllListeners();
449
+ // Late pipe errors must never become an unhandled 'error' event.
450
+ stream.on("error", () => {});
451
+ }
452
+ child.removeAllListeners();
453
+ child.on("error", () => {});
454
+ }
455
+
456
+ #killNow(): void {
457
+ const child = this.#child;
458
+ this.#child = undefined;
459
+ this.#started = false;
460
+ this.#rejectPending(new Error("adapter failed to start"));
461
+ if (child) {
462
+ this.#detachStreams(child);
463
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
464
+ }
465
+ }
466
+
467
+ #cleanup(): void {
468
+ const child = this.#child;
469
+ this.#child = undefined;
470
+ this.#started = false;
471
+ this.#rejectPending(new Error("adapter stopped"));
472
+ if (!child) return;
473
+ this.#detachStreams(child);
474
+ }
475
+ }
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { loadConfig } from "./config.ts";
6
+ import { log } from "./log.ts";
7
+
8
+ function readVersion(): string {
9
+ const here = path.dirname(fileURLToPath(import.meta.url));
10
+ for (const candidate of ["../package.json", "../../package.json"]) {
11
+ try {
12
+ const parsed = JSON.parse(readFileSync(path.resolve(here, candidate), "utf8")) as {
13
+ version?: unknown;
14
+ };
15
+ if (typeof parsed.version === "string" && parsed.version) return parsed.version;
16
+ } catch {
17
+ // Try the next layout.
18
+ }
19
+ }
20
+ return "0.0.0";
21
+ }
22
+
23
+ const VERSION = readVersion();
24
+
25
+ const USAGE = `chat-room-channeld ${VERSION}
26
+
27
+ Relay chat-room events to external IM accounts through adapter child processes.
28
+
29
+ Usage:
30
+ chat-room-channeld --config <path> Run the relay host
31
+ chat-room-channeld run --config <path> Same as the default command
32
+ chat-room-channeld check --config <path> Validate a config file only
33
+ chat-room-channeld status --config <path> Print queue and integrity counts
34
+ chat-room-channeld mock Run the mock adapter on stdio
35
+ chat-room-channeld --version, -v Print the version
36
+ chat-room-channeld --help, -h Print this help
37
+ `;
38
+
39
+ class UsageError extends Error {}
40
+
41
+ type Command = "run" | "check" | "status" | "mock";
42
+
43
+ async function main(): Promise<void> {
44
+ const argv = process.argv.slice(2);
45
+ if (argv.includes("--version") || argv.includes("-v")) {
46
+ process.stdout.write(`chat-room-channeld ${VERSION}\n`);
47
+ return;
48
+ }
49
+ if (argv.includes("--help") || argv.includes("-h")) {
50
+ process.stdout.write(USAGE);
51
+ return;
52
+ }
53
+
54
+ const rest = [...argv];
55
+ let command: Command = "run";
56
+ const first = rest[0];
57
+ if (first === "run" || first === "check" || first === "status" || first === "mock") {
58
+ command = rest.shift() as Command;
59
+ }
60
+
61
+ let configPath: string | undefined;
62
+ while (rest.length > 0) {
63
+ const arg = rest.shift() as string;
64
+ if (arg === "--config") {
65
+ const value = rest.shift();
66
+ if (!value) throw new UsageError("--config requires a path");
67
+ configPath = value;
68
+ } else if (arg.startsWith("--config=")) {
69
+ configPath = arg.slice("--config=".length);
70
+ if (!configPath) throw new UsageError("--config requires a path");
71
+ } else {
72
+ throw new UsageError(`unknown argument: ${arg}`);
73
+ }
74
+ }
75
+
76
+ if (command === "mock") {
77
+ if (configPath) throw new UsageError("mock does not accept --config");
78
+ const { runMockAdapter } = await import("./mock-adapter.ts");
79
+ await runMockAdapter();
80
+ return;
81
+ }
82
+
83
+ if (!configPath) throw new UsageError(`${command} requires --config <path>`);
84
+ const config = loadConfig(configPath);
85
+ if (command === "check") {
86
+ process.stdout.write(`config ok: ${config.accounts.length} accounts, ${config.rules.length} rules\n`);
87
+ return;
88
+ }
89
+ if (command === "status") {
90
+ const { readChannelStats } = await import("./state.ts");
91
+ process.stdout.write(`${JSON.stringify(readChannelStats(config.stateFile), null, 2)}\n`);
92
+ return;
93
+ }
94
+
95
+ const { createHost } = await import("./host.ts");
96
+ const host = createHost(config);
97
+ let stopping = false;
98
+ const shutdown = (): void => {
99
+ if (stopping) return;
100
+ stopping = true;
101
+ void host.stop().then(() => {
102
+ log.info("shutdown complete");
103
+ process.exitCode = 0;
104
+ });
105
+ };
106
+ process.once("SIGINT", shutdown);
107
+ process.once("SIGTERM", shutdown);
108
+
109
+ try {
110
+ await host.start();
111
+ } catch (error) {
112
+ await host.stop();
113
+ throw error;
114
+ }
115
+ log.info(`relay running; state=${config.stateFile}`);
116
+ }
117
+
118
+ main().catch((error: unknown) => {
119
+ const message = error instanceof Error ? error.message : String(error);
120
+ const code = error instanceof UsageError ? 2 : 1;
121
+ process.stderr.write(`chat-room-channeld: ${message}\n`);
122
+ if (error instanceof UsageError) process.stderr.write(USAGE);
123
+ process.exitCode = code;
124
+ });