项目地址:OpenCode QQ Adapter

在 OpenCode QQ Adapter 这个项目中,我们使用 Plugin SDK 的方式,让插件作者可以基于这个项目开发自己的插件。下面简单整理一下 Node.js 插件 SDK 开发的一些内容。

1. SDK 相关概念

我们可以把 SDK 理解为核心代码 core 对外承诺的插件契约包:它包含 TypeScript 类型、manifest/API 常量、插件 context 的能力定义、测试 harness 等一系列核心组件。

对插件作者来说,SDK 是一个独立发布的 npm 包:插件只依赖它,不 import core 的 router、store 等内部实现。这样 core 重构目录、拆文件、换实现时,插件不需要跟着改。例如 OpenCode QQ Adapter 项目的依赖方向:

core(bridge / router / policy)
|
| implements
v
@opencode-qq/plugin-sdk
^ ^
| |
depends on | | depends on
| |
third-party plugin @opencode-qq/plugin-ui
third-party plugin ---X---> core
(禁止 import 内部实现)

“独立发布的包”不等于“独立于 core 的源码”。当前项目里,SDK 的源文件仍然在 core 的 src/plugins/sdk.ts,由 packages/plugin-sdk 编译成独立 package。之后会讲到这个设计。

2. SDK 的边界

那么什么东西应该放进 SDK、什么东西不应该呢?以我们这个 QQ Bot 项目为例,我们把插件需要使用或者知道的内容做成 SDK:

  • manifest 的类型与版本常量;
  • 插件生命周期(setup / start / stop);
  • context 上的能力:命令、hook、消息、会话、事件、后台 utility run、admin 路由等;
  • 插件配置的解析接口;
  • 测试 harness;
  • 插件 iframe UI 的通信协议类型。

而例如 SQLite 表管理、Router、Workspace 这些概念的具体实现,就不需要放在 SDK 中。可以用下面的话概括:如果这个类型的变化原因是“core 内部实现改了”,而不是“插件作者需要的能力变了”,它就不应该出现在 SDK 的公共签名里。

3. SDK 的一些设计

3.1 SDK 实现位置

SDK 有两种实现方式:

  1. SDK 自己作为单一事实源,core 依赖 SDK 开发。
  2. 将 SDK 放在 core 代码中,然后 tsconfig.json 通过 rootDir 把它编译到独立包。

这个项目采用了第二种:

{
"compilerOptions": {
"target": "ES2023",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "../../src/plugins",
"outDir": "dist",
"declaration": true,
"sourceMap": true
},
"include": [
"../../src/plugins/sdk.ts",
"../../src/plugins/storage.ts",
"../../src/plugins/testing.ts",
"../../src/plugins/ui-protocol.ts"
]
}

这样做的好处是:core 实现和 SDK 契约引用的是同一份类型,不会出现“SDK 里声明了一套,core 里又写了一套”的漂移。代价是 SDK 的构建依赖 core 仓库的目录结构,所以它更适合放在同一个 monorepo 里。

如果 SDK 要独立仓库,依赖方向就应该反过来:SDK 作为契约的唯一 source of truth,core 依赖 @opencode-qq/plugin-sdk,由 core 去实现 SDK 定义的接口。

3.2 SDK 契约

以我们的项目举例,sdk.ts 中声明了 manifest 的类型:

export const PLUGIN_API_VERSION = 2 as const;
export interface PluginManifest {
id: string;
name: string;
version: string;
apiVersion: typeof PLUGIN_API_VERSION;
description?: string;
capabilities?: PluginCapability[];
engines?: {
opencodeQq?: string;
};
ui?: {
root?: string;
entry?: string;
};
}
/** 宿主加载包时使用的扩展 manifest;`entry` 不属于公共运行时契约。 */
export interface PackageManifest extends PluginManifest {
entry?: string;
}
字段作用
id全局唯一,建议小写短横线;必须和 YAML 配置 key 一致,实例 dataDir 也使用这个 id
name展示名
version插件自身的 semver
apiVersion插件 API 的整数版本,当前为 2
engines.opencodeQq兼容的宿主版本范围
capabilities插件声明会使用哪些宿主能力
ui可选的 iframe 页面资源目录

entry 不属于公共的 PluginManifest,而是 PackageManifest / 宿主加载时使用的字段;SDK 消费者通常不需要关心它。

然后每个 Runtime Plugin 通常都在 package.json 中声明 manifest:

{
"name": "my-qq-plugin",
"version": "0.1.0",
"type": "module",
"exports": { ".": "./dist/index.js" },
"opencodeQq": {
"id": "my-plugin",
"name": "My plugin",
"version": "0.1.0",
"apiVersion": 2,
"capabilities": ["commands", "messages", "hooks", "admin"],
"engines": { "opencodeQq": ">=0.2.0 <0.3.0" },
"entry": "./dist/index.js",
"ui": { "root": "ui", "entry": "index.html" }
}
}

这样宿主、打包器和发布流程可以基于同一份 manifest 识别插件身份和入口;Node 仍然按 exports / entry 解析实际模块。

manifest 也可以由插件模块导出(export const manifest);如果 package.json.opencodeQq 和模块导出同时存在,宿主会要求两者的 id / version 一致。

4. SDK 契约与宿主加载流程

下面以 OpenCode QQ Adapter 的插件 SDK 为例,展示 SDK 契约怎么设计,以及宿主怎么加载和调用插件。

4.1 Context 类型定义

首先是 PluginContext,也就是 setup(ctx) 里的 ctx。它是 core 暴露给插件的受控能力集合:

export interface PluginContext<TOptions = Record<string, unknown>> {
manifest: Readonly<PluginManifest>;
config: TOptions;
dataDir: string;
logger: PluginLogger;
storage: PluginStorage;
commands: PluginCommands;
hooks: PluginHooks;
messages: PluginMessages;
sessions: PluginSessions;
events: PluginEvents;
agent: PluginAgent;
admin: PluginAdmin;
}

为什么要单独设计一个 PluginContext 呢?可以把它理解成开发者需要的、核心代码层暴露的受控能力集合。这个层实现了插件开发层所需能力与核心代码层具体实现的解耦:

core 内部实现
store / router / workspace / permission engine / agent loop
|
| 只挑出插件真正需要的能力
v
PluginContext(ctx)
commands / hooks / messages / sessions /
events / agent / admin / storage ...
|
v
third-party plugin

上面的 PluginContext 只是类型定义;能力的具体实现由下面的 namespace 拆分后逐层实现。

4.2 将能力层按 namespace 拆分

我们将 context 的能力进行分组:

ctx
├── commands
├── hooks
├── messages
├── sessions
├── events
├── agent
├── admin
└── storage

然后每个 namespace 提供如下的方法:

ctx.commands.register(...)
ctx.messages.sendImage(...)
ctx.sessions.setProject(...)
ctx.agent.complete(...)

可以把这个东西类比成目录树:

ctx/
├── commands/
│ ├── register
│ └── unregister
├── messages/
│ ├── reply
│ ├── send
│ ├── sendImage
│ └── sendFile
└── sessions/
├── get
├── setProject
└── reset

这些接口也在 sdk.ts 中被声明,例如 command namespace:

export interface PluginCommands {
register(command: PluginCommandDefinition): () => void;
unregister(name: string): void;
}

然后 core 的 PluginHost 在创建 context 时实现这些接口(SDK 只提供类型契约):

// src/plugins/host/context.ts(简化)
const commands = {
register(command) {
requireCapability(instance, "commands");
const names = validateCommand(command);
// 检查 core 保留命令
// 检查当前插件内重复
// 检查其他插件是否已经注册
const registered = { definition: command, names };
instance.commands.set(command.name, registered);
return () => {
if (instance.commands.get(command.name) === registered) {
instance.commands.delete(command.name);
}
};
},
unregister(name) {
// 按名字从 instance.commands 删除
},
};

前面的 manifest 校验和 namespace 也是一一对应的:

manifest 里的 capability对应的 ctx namespace主要方法
commandsctx.commandsregister / unregister
hooksctx.hooksregister
messagesctx.messagesreply / send / sendImage / sendFile
sessionsctx.sessionsget / setProject / reset
eventsctx.eventson
agentctx.agentcomplete
adminctx.adminroute / page

storage 不在 capability 表里,因为它不是需要声明的能力;它始终绑定到插件自己的 dataDir。

核心代码层在创建 context 实例时会检查 capability:

const commands = {
register(command) {
requireCapability(instance, "commands");
// 校验命令、检查重复、注册
},
};

所以如果 manifest 中只声明了:

"capabilities": ["hooks"]

但是代码里调用:

ctx.commands.register(...)

运行时就会报错:

plugin my-plugin must declare capability 'commands' in its manifest

这些能力怎么串起来,就是核心层要做的事情。下面完整讲一下加载流程。

4.3 核心层加载 SDK 的流程

假设我们写了下面的插件:

plugin/src/index.ts
import { definePlugin } from "@opencode-qq/plugin-sdk";
export default definePlugin({
setup(ctx) {
ctx.commands.register(...);
},
});

编译后会变成一个对象,它声明一个需要 ctx 的函数:

{
setup(ctx) { ... }
}

然后 Plugin 的 YAML 配置中会配置路径:

plugins:
my-plugin:
path: /home/me/plugins/my-plugin
# 或者
# plugins:
# my-plugin:
# package: my-plugin

核心层的 PluginLoader 不会直接 import() 用户代码,而是先经过 loadPluginModule():

PluginLoader.load()
-> loadPluginModule()
-> 解析 path / package
-> 读 package.json
-> 解析并校验 opencodeQq manifest
-> 校验 id / apiVersion / engines / entry
-> import(entry)
-> 检查 default export 有没有 setup()
-> parseOptions
-> createPluginContext
-> setup(context)
-> start(context)

实际 import 的代码大致如下:

const loaded = await loadPluginModule(spec, pluginId, coreVersion);
const definition = loaded.definition;
const context = createPluginContext(instance, options, services);
instance.context = context;
await definition.setup(context);
await definition.start?.(context);

Node 会:

  1. 读取插件入口文件;
  2. 在当前 bridge 进程里执行它;
  3. 返回模块的导出:
{
default: {
setup(ctx) { ... }
}
}

加载后核心层会检查默认导出,然后调用插件自己的 setup 方法:

const context = createPluginContext(instance, options, services);
instance.context = context;
await definition.setup(context);

插件系统的相关实现,会在下一篇博客中详细介绍。