Skip to content

本页是 OpenClaw 插件 api.runtime 对象的完整命名空间参考。每个插件注册回调都能通过 api.runtime 调用 core 提供的能力,包括:启动嵌入式 agent(agent)、管理后台任务(subagenttaskFlow)、文字转语音(tts)、图像/音频/视频分析(mediaUnderstanding)、图像生成(imageGeneration)、网页搜索(webSearch)、媒体处理(media)、配置读写(config)、系统事件(system/events)和状态目录(state)。

OpenClaw 插件运行时辅助工具

api.runtime 是注入到每个插件注册回调中的 runtime 对象,用它替代直接导入 host 内部模块。

需要实操指导? 参考渠道插件开发Provider 插件开发,了解这些 helper 在实际插件中的使用方式。

typescript
register(api) {
  const runtime = api.runtime;
}

Runtime 命名空间

api.runtime.agent

Agent 身份、目录和 session 管理。

typescript
// 解析 agent 工作目录
const agentDir = api.runtime.agent.resolveAgentDir(cfg);

// 解析 agent 工作区
const workspaceDir = api.runtime.agent.resolveAgentWorkspaceDir(cfg);

// 获取 agent 身份
const identity = api.runtime.agent.resolveAgentIdentity(cfg);

// 获取默认思考级别
const thinking = api.runtime.agent.resolveThinkingDefault(cfg, provider, model);

// 获取 agent 超时
const timeoutMs = api.runtime.agent.resolveAgentTimeoutMs(cfg);

// 确保工作区存在
await api.runtime.agent.ensureAgentWorkspace(cfg);

// 运行嵌入式 Pi Agent
const result = await api.runtime.agent.runEmbeddedPiAgent({
  sessionId: "my-plugin:task-1",
  runId: crypto.randomUUID(),
  sessionFile: path.join(agentDir, "sessions", "my-plugin-task-1.jsonl"),
  workspaceDir: api.runtime.agent.resolveAgentWorkspaceDir(cfg),
  prompt: "总结最新的变更",
  timeoutMs: api.runtime.agent.resolveAgentTimeoutMs(cfg),
});

Session store helperapi.runtime.agent.session 下:

typescript
const storePath = api.runtime.agent.session.resolveStorePath(cfg);
const store = api.runtime.agent.session.loadSessionStore(cfg);
await api.runtime.agent.session.saveSessionStore(cfg, store);
const filePath = api.runtime.agent.session.resolveSessionFilePath(cfg, sessionId);

api.runtime.agent.defaults

默认模型和 Provider 常量:

typescript
const model = api.runtime.agent.defaults.model;     // 如 "anthropic/claude-sonnet-4-6"
const provider = api.runtime.agent.defaults.provider; // 如 "anthropic"

api.runtime.subagent

启动和管理后台 subagent 运行。

typescript
// 启动 subagent
const { runId } = await api.runtime.subagent.run({
  sessionKey: "agent:main:subagent:search-helper",
  message: "将这个查询扩展为几个有针对性的后续搜索。",
  provider: "openai",   // 可选覆盖
  model: "gpt-4.1-mini", // 可选覆盖
  deliver: false,
});

// 等待完成
const result = await api.runtime.subagent.waitForRun({ runId, timeoutMs: 30000 });

// 读取 session 消息
const { messages } = await api.runtime.subagent.getSessionMessages({
  sessionKey: "agent:main:subagent:search-helper",
  limit: 10,
});

// 删除 session
await api.runtime.subagent.deleteSession({
  sessionKey: "agent:main:subagent:search-helper",
});

注意: 模型覆盖(provider/model)需要运营者在配置中开启 plugins.entries.<id>.subagent.allowModelOverride: true。未经授权的插件仍可运行 subagent,但覆盖请求会被拒绝。

api.runtime.taskFlow

将 Task Flow runtime 绑定到已有 OpenClaw session key 或受信任工具上下文,然后无需在每次调用时传入 owner 就能创建和管理 Task Flow。

typescript
const taskFlow = api.runtime.taskFlow.fromToolContext(ctx);

const created = taskFlow.createManaged({
  controllerId: "my-plugin/review-batch",
  goal: "审查新的 Pull Request",
});

const child = taskFlow.runTask({
  flowId: created.flowId,
  runtime: "acp",
  childSessionKey: "agent:main:subagent:reviewer",
  task: "审查 PR #123",
  status: "running",
  startedAt: Date.now(),
});

const waiting = taskFlow.setWaiting({
  flowId: created.flowId,
  expectedRevision: created.revision,
  currentStep: "await-human-reply",
  waitJson: { kind: "reply", channel: "telegram" },
});

使用 bindSession({ sessionKey, requesterOrigin }) 当你已有来自自己绑定层的受信任 OpenClaw session key 时。不要直接从原始用户输入绑定。

api.runtime.tts

文字转语音合成。

typescript
// 标准 TTS
const clip = await api.runtime.tts.textToSpeech({
  text: "来自 OpenClaw 的问候",
  cfg: api.config,
});

// 电话优化 TTS
const telephonyClip = await api.runtime.tts.textToSpeechTelephony({
  text: "来自 OpenClaw 的问候",
  cfg: api.config,
});

// 列出可用声音
const voices = await api.runtime.tts.listVoices({
  provider: "elevenlabs",
  cfg: api.config,
});

使用核心 messages.tts 配置和 Provider 选择。返回 PCM 音频 buffer + 采样率。

api.runtime.mediaUnderstanding

图像、音频和视频分析。

typescript
// 描述图像
const image = await api.runtime.mediaUnderstanding.describeImageFile({
  filePath: "/tmp/inbound-photo.jpg",
  cfg: api.config,
  agentDir: "/tmp/agent",
});

// 转录音频
const { text } = await api.runtime.mediaUnderstanding.transcribeAudioFile({
  filePath: "/tmp/inbound-audio.ogg",
  cfg: api.config,
  mime: "audio/ogg", // 可选,当 MIME 无法推断时使用
});

// 描述视频
const video = await api.runtime.mediaUnderstanding.describeVideoFile({
  filePath: "/tmp/inbound-video.mp4",
  cfg: api.config,
});

// 通用文件分析
const result = await api.runtime.mediaUnderstanding.runFile({
  filePath: "/tmp/inbound-file.pdf",
  cfg: api.config,
});

无输出时返回 { text: undefined }(如跳过的输入)。

api.runtime.stt.transcribeAudioFile(...) 仍作为 api.runtime.mediaUnderstanding.transcribeAudioFile(...) 的兼容别名存在。

api.runtime.imageGeneration

图像生成。

typescript
const result = await api.runtime.imageGeneration.generate({
  prompt: "一个机器人在画日落",
  cfg: api.config,
});

const providers = api.runtime.imageGeneration.listProviders({ cfg: api.config });

api.runtime.webSearch

网页搜索。

typescript
const providers = api.runtime.webSearch.listProviders({ config: api.config });

const result = await api.runtime.webSearch.search({
  config: api.config,
  args: { query: "OpenClaw plugin SDK", count: 5 },
});

api.runtime.media

低级媒体工具。

typescript
const webMedia = await api.runtime.media.loadWebMedia(url);
const mime = await api.runtime.media.detectMime(buffer);
const kind = api.runtime.media.mediaKindFromMime("image/jpeg"); // "image"
const isVoice = api.runtime.media.isVoiceCompatibleAudio(filePath);
const metadata = await api.runtime.media.getImageMetadata(filePath);
const resized = await api.runtime.media.resizeToJpeg(buffer, { maxWidth: 800 });

api.runtime.config

配置加载和写入。

typescript
const cfg = await api.runtime.config.loadConfig();
await api.runtime.config.writeConfigFile(cfg);

api.runtime.system

系统级工具。

typescript
await api.runtime.system.enqueueSystemEvent(event);
api.runtime.system.requestHeartbeatNow();
const output = await api.runtime.system.runCommandWithTimeout(cmd, args, opts);
const hint = api.runtime.system.formatNativeDependencyHint(pkg);

api.runtime.events

事件订阅。

typescript
api.runtime.events.onAgentEvent((event) => {
  /* ... */
});
api.runtime.events.onSessionTranscriptUpdate((update) => {
  /* ... */
});

api.runtime.logging

日志记录。

typescript
const verbose = api.runtime.logging.shouldLogVerbose();
const childLogger = api.runtime.logging.getChildLogger(
  { plugin: "my-plugin" },
  { level: "debug" }
);

api.runtime.modelAuth

模型和 Provider 认证解析。

typescript
const auth = await api.runtime.modelAuth.getApiKeyForModel({ model, cfg });
const providerAuth = await api.runtime.modelAuth.resolveApiKeyForProvider({
  provider: "openai",
  cfg,
});

api.runtime.state

状态目录解析。

typescript
const stateDir = api.runtime.state.resolveStateDir();

api.runtime.tools

内存工具工厂和 CLI。

typescript
const getTool = api.runtime.tools.createMemoryGetTool(/* ... */);
const searchTool = api.runtime.tools.createMemorySearchTool(/* ... */);
api.runtime.tools.registerMemoryCli(/* ... */);

api.runtime.channel

渠道特定的 runtime helper(渠道插件加载时可用)。

存储 Runtime 引用

使用 createPluginRuntimeStore 将 runtime 引用存储起来,以便在 register 回调之外使用:

typescript
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
import type { PluginRuntime } from "openclaw/plugin-sdk/runtime-store";

const store = createPluginRuntimeStore<PluginRuntime>("my-plugin runtime not initialized");

// 在入口文件中
export default defineChannelPluginEntry({
  id: "my-plugin",
  name: "My Plugin",
  description: "示例",
  plugin: myPlugin,
  setRuntime: store.setRuntime,
});

// 在其他文件中
export function getRuntime() {
  return store.getRuntime(); // 未初始化时抛出异常
}

export function tryGetRuntime() {
  return store.tryGetRuntime(); // 未初始化时返回 null
}

其他顶级 api 字段

api.runtime 外,API 对象还提供:

字段类型说明
api.idstring插件 id
api.namestring插件显示名称
api.configOpenClawConfig当前配置快照(runtime 可用时为内存中的活跃快照)
api.pluginConfigRecord<string, unknown>来自 plugins.entries.<id>.config 的插件专属配置
api.loggerPluginLogger作用域日志器(debug/info/warn/error
api.registrationModePluginRegistrationMode当前加载模式;"setup-runtime" 是轻量预完整入口启动/setup 窗口
api.resolvePath(input)(string) => string解析相对于插件根的路径

相关文档

常见问题

Q: 如何在 register 回调之外的模块中访问 runtime?

A: 用 createPluginRuntimeStore 存储引用(见上方"存储 Runtime 引用"章节)。调用 store.setRuntime 即可在入口的 setRuntime 钩子中初始化,之后在任意模块中 getRuntime() 获取。tryGetRuntime() 在未初始化时返回 null 而不是抛出异常,适合在插件未完全启动时的防御性访问。

Q: api.runtime.subagent.run 的模型覆盖为什么被拒绝?

A: 模型覆盖需要运营者在配置中显式开启 plugins.entries.<id>.subagent.allowModelOverride: true。这是安全机制,防止不受信任的插件借助 subagent 绕过模型选择策略。如果你是自己开发且信任的插件,联系运营者在配置里开启这个开关。

Q: api.runtime.tts 用的是哪个 TTS Provider?

A: api.runtime.tts 使用核心 messages.tts 配置中声明的 Provider,优先级和用户手动调用 TTS 完全一致。如果需要在插件中强制指定某个 Provider,可以传 provider 参数;若省略,则回退到配置默认值。