@theopenbee/channel-sdk 0.0.0-stage → 0.2.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TENGYONGZHI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
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
+ | `migrateChat(fromChatId, toChatId)` | Tell openbee a chat got a new id, so pending and running tasks follow it |
51
+ | `saveMedia(data, ext)` | Write an attachment into `mediaDir` and return its path |
52
+ | `log.debug/info/warn/error(message, fields?)` | Structured logs in the openbee log |
53
+
54
+ ## Development
55
+
56
+ ```sh
57
+ npm install
58
+ npm test
59
+ ```
60
+
61
+ `npm install` also builds `dist/`; run `npm run build` after changing `src/`.
@@ -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,161 @@
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
+ migrateChat: (fromChatId, toChatId) => {
78
+ void peer.notify("migrate_chat", { from_chat_id: fromChatId, to_chat_id: toChatId });
79
+ },
80
+ saveMedia: async (data, ext) => {
81
+ const suffix = ext ? (ext.startsWith(".") ? ext : "." + ext) : "";
82
+ const path = join(p.media_dir, `${Date.now()}-${randomBytes(4).toString("hex")}${suffix}`);
83
+ await writeFile(path, data);
84
+ return path;
85
+ },
86
+ log: { debug: log("debug"), info: log("info"), warn: log("warn"), error: log("error") },
87
+ });
88
+ const handleInitialize = async (id, params) => {
89
+ ctx = buildContext(params);
90
+ try {
91
+ handle = await def.start(ctx);
92
+ }
93
+ catch (err) {
94
+ if (err instanceof ConfigError) {
95
+ await peer.respondError(id, CODE_CONFIG_INVALID, err.message);
96
+ }
97
+ else {
98
+ await peer.respondError(id, CODE_INTERNAL_ERROR, errorMessage(err));
99
+ }
100
+ exit(1);
101
+ return;
102
+ }
103
+ await peer.respond(id, { protocol_version: PROTOCOL_VERSION });
104
+ };
105
+ const handleSend = async (id, params) => {
106
+ if (!ctx) {
107
+ await peer.respondError(id, CODE_REQUEST_FAILED, "channel is not initialized");
108
+ return;
109
+ }
110
+ const controller = new AbortController();
111
+ inflight.set(id, controller);
112
+ try {
113
+ const result = await def.send(params, ctx, controller.signal);
114
+ if (controller.signal.aborted) {
115
+ await peer.respondError(id, CODE_REQUEST_CANCELLED, "request cancelled");
116
+ }
117
+ else {
118
+ await peer.respond(id, result ?? {});
119
+ }
120
+ }
121
+ catch (err) {
122
+ const code = controller.signal.aborted ? CODE_REQUEST_CANCELLED : CODE_REQUEST_FAILED;
123
+ await peer.respondError(id, code, errorMessage(err));
124
+ }
125
+ finally {
126
+ inflight.delete(id);
127
+ }
128
+ };
129
+ const handleShutdown = async (id) => {
130
+ await stop();
131
+ await peer.respond(id, {});
132
+ exit(0);
133
+ };
134
+ const onMessage = (msg) => {
135
+ const { id, method, params } = msg;
136
+ if (method === "$/cancelRequest") {
137
+ const target = params?.id;
138
+ if (target !== undefined)
139
+ inflight.get(target)?.abort();
140
+ return;
141
+ }
142
+ if (id === undefined || id === null || !method)
143
+ return;
144
+ switch (method) {
145
+ case "initialize":
146
+ void handleInitialize(id, params);
147
+ return;
148
+ case "send":
149
+ void handleSend(id, params);
150
+ return;
151
+ case "shutdown":
152
+ void handleShutdown(id);
153
+ return;
154
+ default:
155
+ void peer.respondError(id, CODE_METHOD_NOT_FOUND, `method not found: ${method}`);
156
+ }
157
+ };
158
+ peer.listen(onMessage, () => {
159
+ void stop().then(() => exit(0));
160
+ });
161
+ }
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,73 @@
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
+ migrateChat(fromChatId: string, toChatId: string): void;
64
+ saveMedia(data: Uint8Array, ext: string): Promise<string>;
65
+ log: Logger;
66
+ }
67
+ export interface ChannelHandle {
68
+ stop?: () => void | Promise<void>;
69
+ }
70
+ export interface ChannelDefinition {
71
+ start(ctx: ChannelContext): Promise<ChannelHandle | void> | ChannelHandle | void;
72
+ send(message: SendRequest, ctx: ChannelContext, signal: AbortSignal): Promise<SendResult | void> | SendResult | void;
73
+ }
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.2.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
+ "prepare": "npm run build"
37
+ },
38
+ "devDependencies": {
39
+ "@types/node": "^22.10.0",
40
+ "typescript": "^5.7.0"
41
+ }
42
+ }