@theopenbee/channel-sdk 0.0.0-stage → 0.1.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.
package/README.md CHANGED
@@ -1,3 +1,59 @@
1
- # Temporary Holding Version
1
+ # @theopenbee/channel-sdk
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
+ Node.js SDK for building openbee channel plugins. It implements the stdio JSON-RPC protocol described in [`docs/channel-plugin-protocol.md`](https://github.com/theopenbee/openbee/blob/main/docs/channel-plugin-protocol.md), so a plugin only has to connect to its chat platform.
4
+
5
+ Requires Node.js 20 or newer.
6
+
7
+ ```sh
8
+ npm install @theopenbee/channel-sdk
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import { defineChannel, ConfigError } from "@theopenbee/channel-sdk";
15
+
16
+ defineChannel({
17
+ async start(ctx) {
18
+ if (!ctx.config.token) throw new ConfigError("token is required");
19
+ const client = await connect(ctx.config.token);
20
+ client.on("message", (m) =>
21
+ ctx.dispatch({ chat_id: m.channelId, sender_id: m.authorId, message_id: m.id, text: m.text }),
22
+ );
23
+ return { stop: () => client.close() };
24
+ },
25
+ async send(msg, ctx, signal) {
26
+ await deliver(msg, { signal });
27
+ },
28
+ });
29
+ ```
30
+
31
+ ## What the SDK handles
32
+
33
+ - Line-delimited JSON-RPC framing on stdin/stdout, request ids, `$/cancelRequest` (exposed as the `AbortSignal` passed to `send`).
34
+ - `initialize`: builds the context and calls `start`. Throwing `ConfigError` reports a config problem (`-32001`) and openbee will not restart the plugin; any other error exits the process so openbee restarts it.
35
+ - `shutdown` and stdin EOF: calls `stop` and exits. A plugin must never outlive openbee.
36
+ - `console.log`, `console.info` and `console.debug` are redirected to stderr so they cannot corrupt the protocol stream; stderr lines end up in the openbee log.
37
+ - Uncaught exceptions and unhandled rejections are written to stderr and exit with code 1.
38
+
39
+ ## Context
40
+
41
+ | Field | Description |
42
+ |---|---|
43
+ | `channelId` | Channel id from the manifest |
44
+ | `config` | Resolved config from `bee.platforms.<id>` (defaults applied, `enabled` and `bot_name` removed) |
45
+ | `botName` | The configured bot display name |
46
+ | `language` | openbee UI language (`en` or `zh`) |
47
+ | `dataDir` | Private writable directory for this plugin |
48
+ | `mediaDir` | Directory where inbound attachments must be stored |
49
+ | `dispatch(msg)` | Hand an inbound message to openbee |
50
+ | `saveMedia(data, ext)` | Write an attachment into `mediaDir` and return its path |
51
+ | `log.debug/info/warn/error(message, fields?)` | Structured logs in the openbee log |
52
+
53
+ ## Development
54
+
55
+ ```sh
56
+ pnpm install
57
+ pnpm build
58
+ pnpm test
59
+ ```
@@ -0,0 +1,11 @@
1
+ import type { ChannelDefinition } from "./types.js";
2
+ export * from "./types.js";
3
+ export { PROTOCOL_VERSION } from "./rpc.js";
4
+ export declare class ConfigError extends Error {
5
+ constructor(message: string);
6
+ }
7
+ export interface ChannelIO {
8
+ input: NodeJS.ReadableStream;
9
+ output: NodeJS.WritableStream;
10
+ }
11
+ export declare function defineChannel(def: ChannelDefinition, io?: ChannelIO): void;
package/dist/index.js ADDED
@@ -0,0 +1,158 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { writeFile } from "node:fs/promises";
3
+ import { join } from "node:path";
4
+ import { format } from "node:util";
5
+ import { CODE_CONFIG_INVALID, CODE_INTERNAL_ERROR, CODE_METHOD_NOT_FOUND, CODE_REQUEST_CANCELLED, CODE_REQUEST_FAILED, Peer, PROTOCOL_VERSION, } from "./rpc.js";
6
+ export * from "./types.js";
7
+ export { PROTOCOL_VERSION } from "./rpc.js";
8
+ export class ConfigError extends Error {
9
+ constructor(message) {
10
+ super(message);
11
+ this.name = "ConfigError";
12
+ }
13
+ }
14
+ function redirectConsole() {
15
+ const toStderr = (...args) => {
16
+ process.stderr.write(format(...args) + "\n");
17
+ };
18
+ console.log = toStderr;
19
+ console.info = toStderr;
20
+ console.debug = toStderr;
21
+ }
22
+ function installCrashHandlers() {
23
+ const crash = (err) => {
24
+ process.stderr.write(`fatal: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}\n`);
25
+ process.exit(1);
26
+ };
27
+ process.on("uncaughtException", crash);
28
+ process.on("unhandledRejection", crash);
29
+ }
30
+ function errorMessage(err) {
31
+ return err instanceof Error ? err.message : String(err);
32
+ }
33
+ export function defineChannel(def, io) {
34
+ const input = io?.input ?? process.stdin;
35
+ const output = io?.output ?? process.stdout;
36
+ if (output === process.stdout) {
37
+ redirectConsole();
38
+ installCrashHandlers();
39
+ }
40
+ const peer = new Peer(input, output);
41
+ const inflight = new Map();
42
+ let ctx;
43
+ let handle = undefined;
44
+ let stopping;
45
+ const stop = () => {
46
+ if (!stopping) {
47
+ stopping = (async () => {
48
+ for (const controller of inflight.values())
49
+ controller.abort();
50
+ try {
51
+ await handle?.stop?.();
52
+ }
53
+ catch (err) {
54
+ process.stderr.write(`stop failed: ${errorMessage(err)}\n`);
55
+ }
56
+ })();
57
+ }
58
+ return stopping;
59
+ };
60
+ const exit = (code) => {
61
+ output.write("", () => process.exit(code));
62
+ };
63
+ const log = (level) => (message, fields) => {
64
+ void peer.notify("log", fields ? { level, message, fields } : { level, message });
65
+ };
66
+ const buildContext = (p) => ({
67
+ channelId: p.channel_id,
68
+ config: p.config ?? {},
69
+ botName: p.bot_name ?? "",
70
+ language: p.language ?? "en",
71
+ dataDir: p.data_dir,
72
+ mediaDir: p.media_dir,
73
+ openbeeVersion: p.openbee_version ?? "",
74
+ dispatch: (message) => {
75
+ void peer.notify("inbound", message);
76
+ },
77
+ saveMedia: async (data, ext) => {
78
+ const suffix = ext ? (ext.startsWith(".") ? ext : "." + ext) : "";
79
+ const path = join(p.media_dir, `${Date.now()}-${randomBytes(4).toString("hex")}${suffix}`);
80
+ await writeFile(path, data);
81
+ return path;
82
+ },
83
+ log: { debug: log("debug"), info: log("info"), warn: log("warn"), error: log("error") },
84
+ });
85
+ const handleInitialize = async (id, params) => {
86
+ ctx = buildContext(params);
87
+ try {
88
+ handle = await def.start(ctx);
89
+ }
90
+ catch (err) {
91
+ if (err instanceof ConfigError) {
92
+ await peer.respondError(id, CODE_CONFIG_INVALID, err.message);
93
+ }
94
+ else {
95
+ await peer.respondError(id, CODE_INTERNAL_ERROR, errorMessage(err));
96
+ }
97
+ exit(1);
98
+ return;
99
+ }
100
+ await peer.respond(id, { protocol_version: PROTOCOL_VERSION });
101
+ };
102
+ const handleSend = async (id, params) => {
103
+ if (!ctx) {
104
+ await peer.respondError(id, CODE_REQUEST_FAILED, "channel is not initialized");
105
+ return;
106
+ }
107
+ const controller = new AbortController();
108
+ inflight.set(id, controller);
109
+ try {
110
+ const result = await def.send(params, ctx, controller.signal);
111
+ if (controller.signal.aborted) {
112
+ await peer.respondError(id, CODE_REQUEST_CANCELLED, "request cancelled");
113
+ }
114
+ else {
115
+ await peer.respond(id, result ?? {});
116
+ }
117
+ }
118
+ catch (err) {
119
+ const code = controller.signal.aborted ? CODE_REQUEST_CANCELLED : CODE_REQUEST_FAILED;
120
+ await peer.respondError(id, code, errorMessage(err));
121
+ }
122
+ finally {
123
+ inflight.delete(id);
124
+ }
125
+ };
126
+ const handleShutdown = async (id) => {
127
+ await stop();
128
+ await peer.respond(id, {});
129
+ exit(0);
130
+ };
131
+ const onMessage = (msg) => {
132
+ const { id, method, params } = msg;
133
+ if (method === "$/cancelRequest") {
134
+ const target = params?.id;
135
+ if (target !== undefined)
136
+ inflight.get(target)?.abort();
137
+ return;
138
+ }
139
+ if (id === undefined || id === null || !method)
140
+ return;
141
+ switch (method) {
142
+ case "initialize":
143
+ void handleInitialize(id, params);
144
+ return;
145
+ case "send":
146
+ void handleSend(id, params);
147
+ return;
148
+ case "shutdown":
149
+ void handleShutdown(id);
150
+ return;
151
+ default:
152
+ void peer.respondError(id, CODE_METHOD_NOT_FOUND, `method not found: ${method}`);
153
+ }
154
+ };
155
+ peer.listen(onMessage, () => {
156
+ void stop().then(() => exit(0));
157
+ });
158
+ }
package/dist/rpc.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ export declare const PROTOCOL_VERSION = 1;
2
+ export declare const CODE_CONFIG_INVALID = -32001;
3
+ export declare const CODE_METHOD_NOT_FOUND = -32601;
4
+ export declare const CODE_INTERNAL_ERROR = -32603;
5
+ export declare const CODE_REQUEST_FAILED = -32000;
6
+ export declare const CODE_REQUEST_CANCELLED = -32800;
7
+ export type MessageId = number | string;
8
+ export interface IncomingMessage {
9
+ id?: MessageId;
10
+ method?: string;
11
+ params?: unknown;
12
+ }
13
+ export declare class RpcError extends Error {
14
+ readonly code: number;
15
+ constructor(code: number, message: string);
16
+ }
17
+ export declare class Peer {
18
+ private readonly input;
19
+ private readonly output;
20
+ private queue;
21
+ constructor(input: NodeJS.ReadableStream, output: NodeJS.WritableStream);
22
+ listen(onMessage: (msg: IncomingMessage) => void, onClose: () => void): void;
23
+ notify(method: string, params?: unknown): Promise<void>;
24
+ respond(id: MessageId, result: unknown): Promise<void>;
25
+ respondError(id: MessageId, code: number, message: string): Promise<void>;
26
+ private write;
27
+ }
package/dist/rpc.js ADDED
@@ -0,0 +1,57 @@
1
+ import { createInterface } from "node:readline";
2
+ export const PROTOCOL_VERSION = 1;
3
+ export const CODE_CONFIG_INVALID = -32001;
4
+ export const CODE_METHOD_NOT_FOUND = -32601;
5
+ export const CODE_INTERNAL_ERROR = -32603;
6
+ export const CODE_REQUEST_FAILED = -32000;
7
+ export const CODE_REQUEST_CANCELLED = -32800;
8
+ export class RpcError extends Error {
9
+ code;
10
+ constructor(code, message) {
11
+ super(message);
12
+ this.code = code;
13
+ }
14
+ }
15
+ export class Peer {
16
+ input;
17
+ output;
18
+ queue = Promise.resolve();
19
+ constructor(input, output) {
20
+ this.input = input;
21
+ this.output = output;
22
+ }
23
+ listen(onMessage, onClose) {
24
+ const rl = createInterface({ input: this.input, crlfDelay: Infinity });
25
+ rl.on("line", (line) => {
26
+ const trimmed = line.trim();
27
+ if (!trimmed)
28
+ return;
29
+ let msg;
30
+ try {
31
+ msg = JSON.parse(trimmed);
32
+ }
33
+ catch {
34
+ return;
35
+ }
36
+ if (msg && typeof msg === "object")
37
+ onMessage(msg);
38
+ });
39
+ rl.on("close", onClose);
40
+ }
41
+ notify(method, params) {
42
+ return this.write({ jsonrpc: "2.0", method, params });
43
+ }
44
+ respond(id, result) {
45
+ return this.write({ jsonrpc: "2.0", id, result: result ?? {} });
46
+ }
47
+ respondError(id, code, message) {
48
+ return this.write({ jsonrpc: "2.0", id, error: { code, message } });
49
+ }
50
+ write(obj) {
51
+ const line = JSON.stringify(obj) + "\n";
52
+ this.queue = this.queue.then(() => new Promise((resolve) => {
53
+ this.output.write(line, () => resolve());
54
+ }));
55
+ return this.queue;
56
+ }
57
+ }
@@ -0,0 +1,72 @@
1
+ export type AttachmentType = "image" | "audio" | "video" | "document" | "sticker";
2
+ export interface Attachment {
3
+ type: AttachmentType;
4
+ path: string;
5
+ name?: string;
6
+ }
7
+ export interface InboundMessage {
8
+ chat_id: string;
9
+ sender_id: string;
10
+ session_scope?: string;
11
+ message_id?: string;
12
+ text?: string;
13
+ attachments?: Attachment[];
14
+ raw?: string;
15
+ context?: Record<string, unknown>;
16
+ time?: number;
17
+ }
18
+ export interface ReplyTo {
19
+ message_id?: string;
20
+ raw?: string;
21
+ }
22
+ export interface SendRequest {
23
+ session_key: string;
24
+ chat_id: string;
25
+ session_scope: string;
26
+ proactive: boolean;
27
+ reply_to?: ReplyTo;
28
+ content?: string;
29
+ media?: {
30
+ path: string;
31
+ name: string;
32
+ };
33
+ }
34
+ export interface SendResult {
35
+ platform_message_id?: string;
36
+ }
37
+ export interface InitializeParams {
38
+ protocol_version: number;
39
+ openbee_version: string;
40
+ channel_id: string;
41
+ language: string;
42
+ bot_name: string;
43
+ config: Record<string, unknown>;
44
+ data_dir: string;
45
+ media_dir: string;
46
+ }
47
+ export type LogFields = Record<string, unknown>;
48
+ export interface Logger {
49
+ debug(message: string, fields?: LogFields): void;
50
+ info(message: string, fields?: LogFields): void;
51
+ warn(message: string, fields?: LogFields): void;
52
+ error(message: string, fields?: LogFields): void;
53
+ }
54
+ export interface ChannelContext {
55
+ channelId: string;
56
+ config: Record<string, unknown>;
57
+ botName: string;
58
+ language: string;
59
+ dataDir: string;
60
+ mediaDir: string;
61
+ openbeeVersion: string;
62
+ dispatch(message: InboundMessage): void;
63
+ saveMedia(data: Uint8Array, ext: string): Promise<string>;
64
+ log: Logger;
65
+ }
66
+ export interface ChannelHandle {
67
+ stop?: () => void | Promise<void>;
68
+ }
69
+ export interface ChannelDefinition {
70
+ start(ctx: ChannelContext): Promise<ChannelHandle | void> | ChannelHandle | void;
71
+ send(message: SendRequest, ctx: ChannelContext, signal: AbortSignal): Promise<SendResult | void> | SendResult | void;
72
+ }
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@theopenbee/channel-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "SDK for building openbee channel plugins",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/theopenbee/channel-sdk.git"
9
+ },
10
+ "homepage": "https://github.com/theopenbee/channel-sdk#readme",
11
+ "bugs": {
12
+ "url": "https://github.com/theopenbee/channel-sdk/issues"
13
+ },
14
+ "type": "module",
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "engines": {
27
+ "node": ">=20"
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.json",
35
+ "test": "node --test test/*.test.mjs",
36
+ "prepack": "npm run build"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^22.10.0",
40
+ "typescript": "^5.7.0"
41
+ }
42
+ }