概述

api.runtime 是注入到每个插件注册回调中的运行时对象。通过它调用核心辅助功能,而不是直接导入宿主内部模块。

核心 API

命名空间一览

命名空间用途
api.runtime.agentAgent 身份、目录、会话管理
api.runtime.agent.defaults默认模型和 Provider 常量
api.runtime.llm宿主拥有的文本补全(无需导入 Provider 内部)
api.runtime.subagent启动和管理后台子 Agent 运行
api.runtime.nodes列出已连接节点,调用节点宿主命令
api.runtime.tasks.managedFlows绑定 Task Flow 运行时,管理多步骤工作流状态
api.runtime.tts文本转语音合成
api.runtime.mediaUnderstanding图像/音频/视频分析
api.runtime.imageGeneration图像生成
api.runtime.webSearchWeb 搜索
api.runtime.media低级媒体工具(MIME 检测、QR 码等)
api.runtime.config当前运行时配置快照和事务性配置写入
api.runtime.system系统级工具(事件队列、心跳等)
api.runtime.events事件订阅
api.runtime.logging日志
api.runtime.modelAuth模型和 Provider 认证解析
api.runtime.state状态目录解析和 SQLite 键值存储
api.runtime.tools记忆工具工厂和 CLI
api.runtime.channelChannel 特定运行时辅助工具

配置读写规则

  • 优先使用已传入调用路径的配置(如 api.config 或 cfg 参数)
  • 长期处理器需要当前进程快照时使用 api.runtime.config.current()
  • 持久化变更用 mutateConfigFile(...) 或 replaceConfigFile(...),必须选择 afterWrite 策略:
    • { mode: "auto" } — 让 Gateway 重载规划器决定
    • { mode: "restart", reason: "..." } — 强制重启
    • { mode: "none", reason: "..." } — 调用方自行处理后续

使用示例

// Agent 运行时
const agentDir = api.runtime.agent.resolveAgentDir(cfg);
const result = await api.runtime.agent.runEmbeddedAgent({
  sessionId: "my-plugin:task-1",
  runId: crypto.randomUUID(),
  sessionFile: path.join(agentDir, "sessions", "task-1.jsonl"),
  workspaceDir: api.runtime.agent.resolveAgentWorkspaceDir(cfg),
  prompt: "Summarize the latest changes",
  timeoutMs: api.runtime.agent.resolveAgentTimeoutMs(cfg),
});
 
// 子 Agent
const { runId } = await api.runtime.subagent.run({
  sessionKey: "agent:main:subagent:search-helper",
  message: "Expand this query.",
  deliver: false,
});
const result = await api.runtime.subagent.waitForRun({ runId, timeoutMs: 30000 });
 
// 配置写入
await api.runtime.config.mutateConfigFile({
  afterWrite: { mode: "auto" },
  mutate(draft) { draft.plugins ??= {}; },
});

存储运行时引用

import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
 
const store = createPluginRuntimeStore<PluginRuntime>({
  pluginId: "my-plugin",
  errorMessage: "my-plugin runtime not initialized",
});
 
// 在入口点中接线
export default defineChannelPluginEntry({
  id: "my-plugin",
  plugin: myPlugin,
  setRuntime: store.setRuntime,
});
 
// 从其他文件访问
export function getRuntime() { return store.getRuntime(); }

相关页面

  • concepts/plugin-sdk-overview — 子路径参考
  • concepts/plugin-sdk-entrypoints — definePluginEntry 选项
  • concepts/plugin-architecture — 能力模型和注册表