Plugin SDK API 参考
OpenClaw Plugin SDK 提供了丰富的 API 用于构建插件。本文档涵盖核心 API、类型定义和常用工具函数。
核心导入
主要 SDK 模块
import type {
OpenClawPluginApi,
OpenClawPluginConfigSchema,
PluginLogger,
PluginRuntime,
} from "openclaw/plugin-sdk";
核心工具
import {
emptyPluginConfigSchema,
buildOauthProviderAuthResult,
approveDevicePairing,
listDevicePairing,
rejectDevicePairing,
} from "openclaw/plugin-sdk/core";
OpenClawPluginApi
插件的主要入口点,在 register 函数中接收:
export default function (api: OpenClawPluginApi) {
// 使用 api 注册功能
}
该插件的配置(来自 plugins.entries.<id>.config)
注册 AI 代理可调用的工具:
api.registerTool(
{
name: "my_tool",
description: "执行某项操作",
parameters: Type.Object({
input: Type.String(),
}),
async execute(_id, params) {
return { content: [{ type: "text", text: params.input }] };
},
},
{ optional: true }, // 可选:需要用户选择加入
);
tool
AnyAgentTool | OpenClawPluginToolFactory
工具定义或工具工厂函数
opts
OpenClawPluginToolOptions
工具选项:
optional: 是否需要显式启用
name: 覆盖工具名称
names: 注册多个别名
查看完整指南: 插件代理工具
registerHook
注册生命周期事件钩子:
api.registerHook(
"before_agent_start",
async (event, ctx) => {
console.log("Agent starting:", ctx.agentId);
return { prependContext: "额外的上下文" };
},
{ priority: 10 }
);
要监听的事件名称,支持:
before_model_resolve
before_prompt_build
before_agent_start
llm_input
llm_output
agent_end
before_compaction
after_compaction
before_reset
message_received
message_sending
message_sent
before_tool_call
after_tool_call
session_start
session_end
gateway_start
gateway_stop
opts
OpenClawPluginHookOptions
钩子选项:
entry: 钩子条目
name: 钩子名称
description: 钩子描述
register: 是否注册
priority: 执行优先级(数字越大越先执行)
registerHttpRoute
注册 HTTP 路由处理器:
api.registerHttpRoute({
path: "/webhook/custom",
handler: async (req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify({ status: "ok" }));
return true; // 表示已处理
},
auth: "plugin",
match: "exact",
});
HTTP 路径(例如 /webhook/custom)
params.handler
OpenClawPluginHttpRouteHandler
路由处理函数
认证策略:
gateway: 使用网关的认证
plugin: 插件自行处理认证
params.match
'exact' | 'prefix'
default:"exact"
匹配模式:
exact: 精确匹配路径
prefix: 前缀匹配
registerChannel
注册消息平台插件:
api.registerChannel({
plugin: {
id: "matrix",
label: "Matrix",
// ...平台实现
},
dock: channelDock, // 可选:平台控制器
});
registerGatewayMethod
注册网关 RPC 方法:
api.registerGatewayMethod(
"voicecall.initiate",
async ({ params, respond }) => {
const { to, message } = params;
// 处理逻辑
respond(true, { callId: "abc123" });
}
);
registerCli
注册 CLI 命令:
api.registerCli(
({ program, config }) => {
program
.command("voicecall")
.description("语音通话管理")
.action(async () => {
console.log("语音通话命令");
});
},
{ commands: ["voicecall"] }
);
registerService
注册后台服务:
api.registerService({
id: "my-service",
async start(ctx) {
console.log("服务启动:", ctx.stateDir);
// 启动长期运行的服务
},
async stop(ctx) {
console.log("服务停止");
// 清理资源
},
});
registerCommand
注册自定义命令(绕过 LLM):
api.registerCommand({
name: "tts",
description: "切换 TTS 开关",
acceptsArgs: true,
requireAuth: true,
async handler(ctx) {
// 处理 /tts 命令
return { text: "TTS 已切换" };
},
});
registerProvider
注册 AI 模型提供商:
api.registerProvider({
id: "custom-provider",
label: "Custom Provider",
auth: [
{
id: "api-key",
label: "API Key",
kind: "api_key",
async run(ctx) {
// OAuth 或 API key 流程
return { profiles: [], configPatch: {} };
},
},
],
});
resolvePath
解析相对于插件目录的路径:
const configPath = api.resolvePath("./config.json");
注册生命周期钩子(简化语法):
api.on(
"before_agent_start",
async (event, ctx) => {
// 处理事件
},
{ priority: 10 }
);
配置模式
空配置模式
对于无配置的插件:
import { emptyPluginConfigSchema } from "openclaw/plugin-sdk/core";
export default {
id: "simple-plugin",
configSchema: emptyPluginConfigSchema,
register(api) {
// ...
},
};
Zod 配置模式
使用 Zod 验证配置:
import { z } from "zod";
const ConfigSchema = z.object({
apiKey: z.string(),
enabled: z.boolean().default(true),
timeout: z.number().min(1000).max(60000).default(5000),
});
const configSchema = {
parse(value: unknown) {
return ConfigSchema.parse(value);
},
safeParse(value: unknown) {
return ConfigSchema.safeParse(value);
},
uiHints: {
apiKey: { label: "API Key", sensitive: true },
enabled: { label: "启用" },
timeout: { label: "超时(毫秒)", advanced: true },
},
};
JSON Schema
直接使用 JSON Schema:
const configSchema = {
jsonSchema: {
type: "object",
additionalProperties: false,
properties: {
apiKey: { type: "string" },
enabled: { type: "boolean" },
},
required: ["apiKey"],
},
};
TypeBox Schema
推荐用于工具参数定义:
import { Type } from "@sinclair/typebox";
const ToolParams = Type.Object({
action: Type.Union([
Type.Literal("start"),
Type.Literal("stop"),
Type.Literal("status"),
]),
target: Type.Optional(Type.String({ description: "目标标识符" })),
});
Logger API
api.logger.debug("调试信息"); // 仅在 debug 模式下
api.logger.info("普通信息");
api.logger.warn("警告信息");
api.logger.error("错误信息");
PluginRuntime
运行时服务访问:
// TTS 服务
const audio = await api.runtime.tts.synthesize({
text: "你好,世界",
provider: "openai",
voice: "alloy",
});
常用工具函数
设备配对
import {
approveDevicePairing,
listDevicePairing,
rejectDevicePairing,
} from "openclaw/plugin-sdk/core";
// 列出待审批的配对请求
const pairings = await listDevicePairing(config);
// 批准配对
await approveDevicePairing(config, pairingId);
// 拒绝配对
await rejectDevicePairing(config, pairingId);
运行插件命令
import {
runPluginCommandWithTimeout,
type PluginCommandRunResult,
} from "openclaw/plugin-sdk/core";
const result: PluginCommandRunResult = await runPluginCommandWithTimeout({
command: "ffmpeg",
args: ["-i", "input.mp4", "output.mp3"],
timeoutMs: 30000,
});
网关绑定 URL
import { resolveGatewayBindUrl } from "openclaw/plugin-sdk/core";
const bindUrl = await resolveGatewayBindUrl({
bind: "loopback",
port: 18789,
});
console.log(bindUrl.url); // http://127.0.0.1:18789
平台特定 SDK
每个消息平台都有专门的 SDK 模块:
Telegram SDK
import {
listTelegramAccountIds,
resolveTelegramAccount,
normalizeTelegramMessagingTarget,
} from "openclaw/plugin-sdk/telegram";
Discord SDK
import {
listDiscordAccountIds,
resolveDiscordAccount,
normalizeDiscordMessagingTarget,
} from "openclaw/plugin-sdk/discord";
Slack SDK
import {
listSlackAccountIds,
resolveSlackAccount,
normalizeSlackMessagingTarget,
} from "openclaw/plugin-sdk/slack";
查看完整列表: package.json 的 exports 字段。
类型定义
type AnyAgentTool = {
name: string;
label?: string;
description: string;
parameters: TypeBoxSchema | Record<string, unknown>;
execute: (
toolCallId: string,
params: Record<string, unknown>,
ctx: OpenClawPluginToolContext
) => Promise<ToolResult> | ToolResult;
};
OpenClawPluginToolContext
type OpenClawPluginToolContext = {
config?: OpenClawConfig;
workspaceDir?: string;
agentDir?: string;
agentId?: string;
sessionKey?: string;
sessionId?: string;
messageChannel?: string;
agentAccountId?: string;
requesterSenderId?: string;
senderIsOwner?: boolean;
sandboxed?: boolean;
};
示例:完整插件
import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
import { Type } from "@sinclair/typebox";
import { z } from "zod";
const ConfigSchema = z.object({
enabled: z.boolean().default(true),
apiKey: z.string().optional(),
});
const configSchema = {
parse(value: unknown) {
return ConfigSchema.parse(value);
},
uiHints: {
enabled: { label: "启用插件" },
apiKey: { label: "API Key", sensitive: true },
},
};
export default {
id: "example-plugin",
name: "Example Plugin",
version: "1.0.0",
configSchema,
register(api: OpenClawPluginApi) {
const config = configSchema.parse(api.pluginConfig);
// 注册工具
api.registerTool({
name: "example_tool",
description: "示例工具",
parameters: Type.Object({
input: Type.String({ description: "输入文本" }),
}),
async execute(_id, params) {
return {
content: [
{
type: "text",
text: `处理结果: ${params.input}`,
},
],
};
},
});
// 注册钩子
api.on("before_agent_start", async (event, ctx) => {
api.logger.info(`Agent ${ctx.agentId} 启动中`);
});
// 注册服务
api.registerService({
id: "example-service",
async start() {
api.logger.info("服务已启动");
},
async stop() {
api.logger.info("服务已停止");
},
});
// 注册 HTTP 路由
api.registerHttpRoute({
path: "/example/webhook",
handler: async (req, res) => {
res.writeHead(200);
res.end("OK");
return true;
},
auth: "plugin",
});
},
};
下一步