Chuyển đến nội dung chính

Documentation Index

Fetch the complete documentation index at: https://docs.openclaw.ai/llms.txt

Use this file to discover all available pages before exploring further.

Tài liệu tham khảo cho đối tượng api.runtime được chèn vào mọi Plugin trong quá trình đăng ký. Dùng các helper này thay vì nhập trực tiếp phần nội bộ của host.

Channel plugins

Hướng dẫn từng bước sử dụng các helper này trong ngữ cảnh cho Plugin kênh.

Provider plugins

Hướng dẫn từng bước sử dụng các helper này trong ngữ cảnh cho Plugin nhà cung cấp.
register(api) {
  const runtime = api.runtime;
}

Tải và ghi cấu hình

Ưu tiên cấu hình đã được truyền vào luồng gọi đang hoạt động, ví dụ api.config trong quá trình đăng ký hoặc đối số cfg trên callback kênh/nhà cung cấp. Cách này giữ một snapshot tiến trình duy nhất chảy xuyên suốt công việc thay vì phân tích lại cấu hình trên các hot path. Chỉ dùng api.runtime.config.current() khi một handler tồn tại lâu cần snapshot tiến trình hiện tại và không có cấu hình nào được truyền vào hàm đó. Giá trị trả về là readonly; hãy clone hoặc dùng helper mutation trước khi chỉnh sửa. Factory công cụ nhận ctx.runtimeConfig cùng với ctx.getRuntimeConfig(). Dùng getter bên trong callback execute của công cụ tồn tại lâu khi cấu hình có thể thay đổi sau khi định nghĩa công cụ đã được tạo. Lưu thay đổi bằng api.runtime.config.mutateConfigFile(...) hoặc api.runtime.config.replaceConfigFile(...). Mỗi lần ghi phải chọn một chính sách afterWrite rõ ràng:
  • afterWrite: { mode: "auto" } để trình quyết định tải lại của Gateway quyết định.
  • afterWrite: { mode: "restart", reason: "..." } buộc khởi động lại sạch khi bên ghi biết hot reload không an toàn.
  • afterWrite: { mode: "none", reason: "..." } chỉ chặn tự động tải lại/khởi động lại khi bên gọi sở hữu bước theo dõi tiếp theo.
Các helper mutation trả về afterWrite cùng một bản tóm tắt followUp có kiểu để bên gọi có thể ghi log hoặc kiểm thử liệu họ đã yêu cầu khởi động lại hay chưa. Gateway vẫn sở hữu thời điểm việc khởi động lại đó thực sự diễn ra. api.runtime.config.loadConfig()api.runtime.config.writeConfigFile(...) là các helper tương thích đã ngừng khuyến nghị dưới runtime-config-load-write. Chúng cảnh báo một lần tại runtime và vẫn có sẵn cho các Plugin bên ngoài cũ trong thời gian chuyển đổi. Các Plugin được đóng gói không được dùng chúng; lớp bảo vệ ranh giới cấu hình sẽ lỗi nếu mã Plugin gọi chúng hoặc nhập các helper đó từ các đường dẫn con của SDK Plugin. Đối với các import SDK trực tiếp, dùng các đường dẫn con cấu hình tập trung thay vì barrel tương thích rộng openclaw/plugin-sdk/config-runtime: config-types cho type, plugin-config-runtime cho assertion cấu hình đã tải và tra cứu entry Plugin, runtime-config-snapshot cho snapshot tiến trình hiện tại, và config-mutation cho thao tác ghi. Kiểm thử Plugin được đóng gói nên mock trực tiếp các đường dẫn con tập trung này thay vì mock barrel tương thích rộng. Mã runtime nội bộ của OpenClaw đi theo cùng hướng: tải cấu hình một lần tại ranh giới CLI, Gateway, hoặc tiến trình, rồi truyền giá trị đó xuyên suốt. Các lần ghi mutation thành công làm mới snapshot runtime của tiến trình và tăng revision nội bộ của nó; các cache tồn tại lâu nên dựa vào khóa cache do runtime sở hữu thay vì tự serialize cấu hình cục bộ. Các module runtime tồn tại lâu có bộ quét không khoan nhượng đối với các lệnh gọi loadConfig() xung quanh; hãy dùng một cfg được truyền vào, context.getRuntimeConfig() của request, hoặc getRuntimeConfig() tại một ranh giới tiến trình rõ ràng. Các đường dẫn thực thi nhà cung cấp và kênh phải dùng snapshot cấu hình runtime đang hoạt động, không phải snapshot tệp được trả về để đọc lại hoặc chỉnh sửa cấu hình. Snapshot tệp giữ nguyên các giá trị nguồn như marker SecretRef cho UI và thao tác ghi; callback nhà cung cấp cần chế độ xem runtime đã được phân giải. Khi một helper có thể được gọi với snapshot nguồn đang hoạt động hoặc snapshot runtime đang hoạt động, hãy đi qua selectApplicableRuntimeConfig() trước khi đọc thông tin đăng nhập.

Namespace runtime

Danh tính agent, thư mục, và quản lý phiên.
// Resolve the agent's working directory
const agentDir = api.runtime.agent.resolveAgentDir(cfg);

// Resolve agent workspace
const workspaceDir = api.runtime.agent.resolveAgentWorkspaceDir(cfg);

// Get agent identity
const identity = api.runtime.agent.resolveAgentIdentity(cfg);

// Get default thinking level
const thinking = api.runtime.agent.resolveThinkingDefault({
  cfg,
  provider,
  model,
});

// Validate a user-provided thinking level against the active provider profile
const policy = api.runtime.agent.resolveThinkingPolicy({ provider, model });
const level = api.runtime.agent.normalizeThinkingLevel("extra high");
if (level && policy.levels.some((entry) => entry.id === level)) {
  // pass level to an embedded run
}

// Get agent timeout
const timeoutMs = api.runtime.agent.resolveAgentTimeoutMs(cfg);

// Ensure workspace exists
await api.runtime.agent.ensureAgentWorkspace(cfg);

// Run an embedded agent turn
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", "my-plugin-task-1.jsonl"),
  workspaceDir: api.runtime.agent.resolveAgentWorkspaceDir(cfg),
  prompt: "Summarize the latest changes",
  timeoutMs: api.runtime.agent.resolveAgentTimeoutMs(cfg),
});
runEmbeddedAgent(...) là helper trung lập để bắt đầu một lượt agent OpenClaw thông thường từ mã Plugin. Nó dùng cùng cơ chế phân giải nhà cung cấp/model và lựa chọn agent-harness như các phản hồi được kích hoạt từ kênh.runEmbeddedPiAgent(...) vẫn là alias tương thích.resolveThinkingPolicy(...) trả về các mức suy nghĩ được hỗ trợ của nhà cung cấp/model và giá trị mặc định tùy chọn. Plugin nhà cung cấp sở hữu hồ sơ theo model thông qua các hook suy nghĩ của chúng, nên Plugin công cụ nên gọi helper runtime này thay vì nhập hoặc nhân đôi danh sách nhà cung cấp.normalizeThinkingLevel(...) chuyển đổi văn bản người dùng như on, x-high, hoặc extra high thành mức lưu trữ chuẩn trước khi kiểm tra nó với chính sách đã phân giải.Helper kho phiên nằm dưới api.runtime.agent.session:
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);
Hằng số model và nhà cung cấp mặc định:
const model = api.runtime.agent.defaults.model; // e.g. "anthropic/claude-sonnet-4-6"
const provider = api.runtime.agent.defaults.provider; // e.g. "anthropic"
Khởi chạy và quản lý các lần chạy subagent nền.
// Start a subagent run
const { runId } = await api.runtime.subagent.run({
  sessionKey: "agent:main:subagent:search-helper",
  message: "Expand this query into focused follow-up searches.",
  provider: "openai", // optional override
  model: "gpt-4.1-mini", // optional override
  deliver: false,
});

// Wait for completion
const result = await api.runtime.subagent.waitForRun({ runId, timeoutMs: 30000 });

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

// Delete a session
await api.runtime.subagent.deleteSession({
  sessionKey: "agent:main:subagent:search-helper",
});
Ghi đè model (provider/model) yêu cầu operator bật tùy chọn qua plugins.entries.<id>.subagent.allowModelOverride: true trong cấu hình. Plugin không đáng tin cậy vẫn có thể chạy subagent, nhưng các yêu cầu ghi đè sẽ bị từ chối.
deleteSession(...) có thể xóa các phiên được tạo bởi cùng Plugin thông qua api.runtime.subagent.run(...). Việc xóa phiên tùy ý của người dùng hoặc operator vẫn cần một request Gateway có phạm vi admin.
Liệt kê các node đã kết nối và gọi một lệnh do node-host cung cấp từ mã Plugin được Gateway tải hoặc từ lệnh CLI của Plugin. Dùng mục này khi Plugin sở hữu công việc cục bộ trên thiết bị đã ghép cặp, ví dụ một cầu nối trình duyệt hoặc âm thanh trên một máy Mac khác.
const { nodes } = await api.runtime.nodes.list({ connected: true });

const result = await api.runtime.nodes.invoke({
  nodeId: "mac-studio",
  command: "my-plugin.command",
  params: { action: "start" },
  timeoutMs: 30000,
});
Bên trong Gateway, runtime này chạy trong cùng tiến trình. Trong các lệnh CLI của Plugin, nó gọi Gateway đã cấu hình qua RPC, nên các lệnh như openclaw googlemeet recover-tab có thể kiểm tra các node đã ghép cặp từ terminal. Lệnh node vẫn đi qua quy trình ghép cặp node Gateway thông thường, allowlist lệnh, và xử lý lệnh cục bộ trên node.
Liên kết một runtime Task Flow với khóa phiên OpenClaw hiện có hoặc ngữ cảnh công cụ đáng tin cậy, sau đó tạo và quản lý Task Flow mà không cần truyền owner trong mỗi lần gọi.
const taskFlow = api.runtime.tasks.managedFlows.fromToolContext(ctx);

const created = taskFlow.createManaged({
  controllerId: "my-plugin/review-batch",
  goal: "Review new pull requests",
});

const child = taskFlow.runTask({
  flowId: created.flowId,
  runtime: "acp",
  childSessionKey: "agent:main:subagent:reviewer",
  task: "Review 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" },
});
Dùng bindSession({ sessionKey, requesterOrigin }) khi bạn đã có một khóa phiên OpenClaw đáng tin cậy từ lớp binding của riêng bạn. Không bind từ dữ liệu nhập thô của người dùng.
Tổng hợp văn bản thành giọng nói.
// Standard TTS
const clip = await api.runtime.tts.textToSpeech({
  text: "Hello from OpenClaw",
  cfg: api.config,
});

// Telephony-optimized TTS
const telephonyClip = await api.runtime.tts.textToSpeechTelephony({
  text: "Hello from OpenClaw",
  cfg: api.config,
});

// List available voices
const voices = await api.runtime.tts.listVoices({
  provider: "elevenlabs",
  cfg: api.config,
});
Dùng cấu hình messages.tts lõi và lựa chọn nhà cung cấp. Trả về bộ đệm âm thanh PCM + tần số lấy mẫu.
Phân tích hình ảnh, âm thanh, và video.
// Describe an image
const image = await api.runtime.mediaUnderstanding.describeImageFile({
  filePath: "/tmp/inbound-photo.jpg",
  cfg: api.config,
  agentDir: "/tmp/agent",
});

// Transcribe audio
const { text } = await api.runtime.mediaUnderstanding.transcribeAudioFile({
  filePath: "/tmp/inbound-audio.ogg",
  cfg: api.config,
  mime: "audio/ogg", // optional, for when MIME cannot be inferred
});

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

// Generic file analysis
const result = await api.runtime.mediaUnderstanding.runFile({
  filePath: "/tmp/inbound-file.pdf",
  cfg: api.config,
});
Trả về { text: undefined } khi không có đầu ra nào được tạo ra (ví dụ: dữ liệu nhập bị bỏ qua).
api.runtime.stt.transcribeAudioFile(...) vẫn là bí danh tương thích cho api.runtime.mediaUnderstanding.transcribeAudioFile(...).
Tạo hình ảnh.
const result = await api.runtime.imageGeneration.generate({
  prompt: "A robot painting a sunset",
  cfg: api.config,
});

const providers = api.runtime.imageGeneration.listProviders({ cfg: api.config });
Tìm kiếm trên web.
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 },
});
Tiện ích media cấp thấp.
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 });
const terminalQr = await api.runtime.media.renderQrTerminal("https://openclaw.ai");
const pngQr = await api.runtime.media.renderQrPngBase64("https://openclaw.ai", {
  scale: 6, // 1-12
  marginModules: 4, // 0-16
});
const pngQrDataUrl = await api.runtime.media.renderQrPngDataUrl("https://openclaw.ai");
const tmpRoot = resolvePreferredOpenClawTmpDir();
const pngQrFile = await api.runtime.media.writeQrPngTempFile("https://openclaw.ai", {
  tmpRoot,
  dirPrefix: "my-plugin-qr-",
  fileName: "qr.png",
});
Ảnh chụp cấu hình runtime hiện tại và các thao tác ghi cấu hình theo giao dịch. Ưu tiên cấu hình đã được truyền vào đường dẫn lệnh gọi đang hoạt động; chỉ dùng current() khi handler cần trực tiếp ảnh chụp tiến trình.
const cfg = api.runtime.config.current();
await api.runtime.config.mutateConfigFile({
  afterWrite: { mode: "auto" },
  mutate(draft) {
    draft.plugins ??= {};
  },
});
mutateConfigFile(...)replaceConfigFile(...) trả về giá trị followUp, ví dụ { mode: "restart", requiresRestart: true, reason }, ghi lại ý định của trình ghi mà không lấy quyền điều khiển khởi động lại khỏi gateway.
Tiện ích cấp hệ thống.
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);
Đăng ký nhận sự kiện.
api.runtime.events.onAgentEvent((event) => {
  /* ... */
});
api.runtime.events.onSessionTranscriptUpdate((update) => {
  /* ... */
});
Ghi log.
const verbose = api.runtime.logging.shouldLogVerbose();
const childLogger = api.runtime.logging.getChildLogger({ plugin: "my-plugin" }, { level: "debug" });
Phân giải xác thực model và provider.
const auth = await api.runtime.modelAuth.getApiKeyForModel({ model, cfg });
const providerAuth = await api.runtime.modelAuth.resolveApiKeyForProvider({
  provider: "openai",
  cfg,
});
Phân giải thư mục trạng thái và lưu trữ khóa-giá trị dựa trên SQLite.
const stateDir = api.runtime.state.resolveStateDir(process.env);
const store = api.runtime.state.openKeyedStore<MyRecord>({
  namespace: "my-feature",
  maxEntries: 200,
  defaultTtlMs: 15 * 60_000,
});

await store.register("key-1", { value: "hello" });
const value = await store.lookup("key-1");
await store.consume("key-1");
await store.clear();
Kho khóa-giá trị tồn tại qua các lần khởi động lại và được cô lập theo id plugin gắn với runtime. Giới hạn: maxEntries cho mỗi namespace, 1.000 hàng đang hoạt động cho mỗi plugin, giá trị JSON dưới 64KB, và tùy chọn hết hạn TTL.
Chỉ các plugin đóng gói sẵn trong bản phát hành này.
Factory công cụ bộ nhớ và CLI.
const getTool = api.runtime.tools.createMemoryGetTool(/* ... */);
const searchTool = api.runtime.tools.createMemorySearchTool(/* ... */);
api.runtime.tools.registerMemoryCli(/* ... */);
Helper runtime dành riêng cho kênh (có sẵn khi một plugin kênh được tải).api.runtime.channel.mentions là bề mặt chính sách nhắc đến đầu vào dùng chung cho các plugin kênh đóng gói sẵn sử dụng tiêm runtime:
const mentionMatch = api.runtime.channel.mentions.matchesMentionWithExplicit(text, {
  mentionRegexes,
  mentionPatterns,
});

const decision = api.runtime.channel.mentions.resolveInboundMentionDecision({
  facts: {
    canDetectMention: true,
    wasMentioned: mentionMatch.matched,
    implicitMentionKinds: api.runtime.channel.mentions.implicitMentionKindWhen(
      "reply_to_bot",
      isReplyToBot,
    ),
  },
  policy: {
    isGroup,
    requireMention,
    allowTextCommands,
    hasControlCommand,
    commandAuthorized,
  },
});
Các helper nhắc đến có sẵn:
  • buildMentionRegexes
  • matchesMentionPatterns
  • matchesMentionWithExplicit
  • implicitMentionKindWhen
  • resolveInboundMentionDecision
api.runtime.channel.mentions cố ý không phơi bày các helper tương thích resolveMentionGating* cũ hơn. Ưu tiên đường dẫn { facts, policy } đã chuẩn hóa.

Lưu trữ tham chiếu runtime

Dùng createPluginRuntimeStore để lưu trữ tham chiếu runtime cho việc sử dụng bên ngoài callback register:
1

Tạo store

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

const store = createPluginRuntimeStore<PluginRuntime>({
  pluginId: "my-plugin",
  errorMessage: "my-plugin runtime not initialized",
});
2

Nối vào điểm vào

export default defineChannelPluginEntry({
  id: "my-plugin",
  name: "My Plugin",
  description: "Example",
  plugin: myPlugin,
  setRuntime: store.setRuntime,
});
3

Truy cập từ các tệp khác

export function getRuntime() {
  return store.getRuntime(); // throws if not initialized
}

export function tryGetRuntime() {
  return store.tryGetRuntime(); // returns null if not initialized
}
Ưu tiên pluginId cho danh tính runtime-store. Dạng key cấp thấp hơn dành cho những trường hợp không phổ biến khi một plugin cố ý cần nhiều hơn một slot runtime.

Các trường api cấp cao nhất khác

Ngoài api.runtime, đối tượng API cũng cung cấp:
api.id
string
Id plugin.
api.name
string
Tên hiển thị của plugin.
api.config
OpenClawConfig
Ảnh chụp cấu hình hiện tại (ảnh chụp runtime trong bộ nhớ đang hoạt động khi có sẵn).
api.pluginConfig
Record<string, unknown>
Cấu hình dành riêng cho plugin từ plugins.entries.<id>.config.
api.logger
PluginLogger
Logger theo phạm vi (debug, info, warn, error).
api.registrationMode
PluginRegistrationMode
Chế độ tải hiện tại; "setup-runtime" là khoảng thời gian khởi động/thiết lập nhẹ trước entry đầy đủ.
api.resolvePath(input)
(string) => string
Phân giải một đường dẫn tương đối với gốc plugin.

Liên quan