api.runtime object injected into every plugin during registration. Use these helpers instead of importing host internals directly.
Channel plugins
Step-by-step guide that uses these helpers in context for channel plugins.
Provider plugins
Step-by-step guide that uses these helpers in context for provider plugins.
api.runtime.version is the current OpenClaw product version, sourced from the shared version resolver so plugins see the same value the CLI reports.
Config loading and writes
Prefer config that was already passed into the active call path, for exampleapi.config during registration or a cfg argument on channel/provider callbacks. This keeps one process snapshot flowing through the work instead of reparsing config on hot paths.
Use api.runtime.config.current() only when a long-lived handler needs the current process snapshot and no config was passed to that function. The returned value is readonly; clone or use a mutation helper before editing.
Tool factories receive ctx.runtimeConfig plus ctx.getRuntimeConfig(). Use the getter inside a long-lived tool’s execute callback when config can change after the tool definition was created.
Persist changes with api.runtime.config.mutateConfigFile(...) or api.runtime.config.replaceConfigFile(...). Each write must choose an explicit afterWrite policy:
afterWrite: { mode: "auto" }lets the gateway reload planner decide.afterWrite: { mode: "restart", reason: "..." }forces a clean restart when the writer knows hot reload is unsafe.afterWrite: { mode: "none", reason: "..." }suppresses automatic reload/restart only when the caller owns the follow-up.
afterWrite plus a typed followUp summary so callers can log or test whether they requested a restart. The gateway still owns when that restart actually happens.
For direct SDK imports, prefer the focused config subpaths over the broad openclaw/plugin-sdk/config-runtime compatibility barrel: config-contracts for types, plugin-config-runtime for already-loaded config assertions and plugin entry lookup, runtime-config-snapshot for current process snapshots, and config-mutation for writes. Bundled plugin tests should mock these focused subpaths directly instead of mocking the broad compatibility barrel.
Internal OpenClaw runtime code follows the same direction: load config once at the CLI, gateway, or process boundary, then pass that value through. Successful mutation writes refresh the process runtime snapshot and advance its internal revision; long-lived caches should key off the runtime-owned cache key instead of serializing config locally. Long-lived runtime modules have a zero-tolerance scanner for ambient loadConfig() calls; use a passed cfg, a request context.getRuntimeConfig(), or getRuntimeConfig() at an explicit process boundary.
Provider and channel execution paths must use the active runtime config snapshot, not a file snapshot returned for config readback or editing. File snapshots preserve source values such as SecretRef markers for UI and writes; provider callbacks need the resolved runtime view. When a helper may be called with either the active source snapshot or the active runtime snapshot, route through selectApplicableRuntimeConfig() before reading credentials.
Reusable runtime utilities
Use inboundbotLoopProtection facts for bot-authored inbound messages. Core applies the shared in-memory sliding-window guard before session record and dispatch, without tying the policy to one channel. The guard tracks (scopeId, conversationId, participant pair) keys, counts both directions of a pair together, applies a cooldown once the window budget is exceeded, and prunes inactive entries opportunistically.
Channel plugins that expose this behavior to operators should prefer the shared channels.defaults.botLoopProtection shape for baseline budgets, then layer channel/provider-specific overrides on top. The shared config uses seconds because it is user-facing:
enabled semantics:
openclaw/plugin-sdk/pair-loop-guard-runtime directly only for custom
two-party event loops that do not go through the shared inbound reply runner.
Runtime namespaces
api.runtime.agent
api.runtime.agent
Agent identity, directories, and session management.Prefer
runEmbeddedAgent(...) is the neutral helper for starting a normal OpenClaw agent turn from plugin code. It uses the same provider/model resolution and agent-harness selection as channel-triggered replies.runEmbeddedPiAgent(...) remains as a deprecated compatibility alias for existing plugins. New code should use runEmbeddedAgent(...).resolveThinkingPolicy(...) returns the provider/model’s supported thinking levels and optional default. Provider plugins own the model-specific profile through their thinking hooks, so tool plugins should call this runtime helper instead of importing or duplicating provider lists.normalizeThinkingLevel(...) converts user text such as on, x-high, or extra high to the canonical stored level before checking it against the resolved policy.Session store helpers are under api.runtime.agent.session:getSessionEntry(...), listSessionEntries(...), patchSessionEntry(...), or upsertSessionEntry(...) for session workflows. These helpers address sessions by agent/session identity so plugins do not depend on the legacy sessions.json storage shape. Use preserveActivity: true for metadata-only patches that should not refresh session activity, and replaceEntry: true only when the callback returns a complete entry and deleted fields must stay deleted.Use runWithWorkAdmission(...) when a plugin starts work on a persisted session. The callback rejects archived or concurrently replaced sessions, keeps archive/reset/delete mutations coordinated through completion, and receives an AbortSignal that must be forwarded to the agent run.For transcript reads and writes, import openclaw/plugin-sdk/session-transcript-runtime and use resolveSessionTranscriptIdentity(...), resolveSessionTranscriptTarget(...), readSessionTranscriptEvents(...), appendSessionTranscriptMessageByIdentity(...), publishSessionTranscriptUpdateByIdentity(...), or withSessionTranscriptWriteLock(...) with { agentId, sessionKey, sessionId }. These APIs let plugins identify a transcript, read its events, append messages, publish updates, and run related operations under the same transcript write lock. Passing sessionFile, using resolveSessionTranscriptLegacyFileTarget(...), or importing low-level appendSessionTranscriptMessage(...) / emitSessionTranscriptUpdate(...) from openclaw/plugin-sdk/agent-harness-runtime is deprecated; those paths exist only for legacy code that already receives an active transcript artifact.resolveStorePath(...) and updateSessionStoreEntry(...) round out the session helpers: resolveStorePath resolves the session store path for a given scope, and updateSessionStoreEntry({ storePath, sessionKey, update }) patches one entry directly by store path when the caller already knows it.loadSessionStore(...), saveSessionStore(...), updateSessionStore(...), and resolveSessionFilePath(...) are deprecated compatibility helpers for plugins that still intentionally depend on the legacy whole-store or transcript-file shape. New plugin code must not use those helpers, and existing callers should migrate to entry helpers and transcript identity helpers.api.runtime.agent.defaults
api.runtime.agent.defaults
Default model and provider constants:
api.runtime.llm
api.runtime.llm
Run a host-owned text completion without importing provider internals or
duplicating OpenClaw model/auth/base URL preparation.The helper uses the same simple-completion preparation path as OpenClaw’s
built-in runtime and the host-owned runtime config snapshot. Context engines
receive a session-bound
llm.complete capability, so model calls use the
active session’s agent and do not silently fall back to the default agent. The
result includes provider/model/agent attribution plus normalized token,
cache, and estimated cost usage when available.api.runtime.subagent
api.runtime.subagent
Launch and manage background subagent runs.
deleteSession(...) can delete sessions created by the same plugin through api.runtime.subagent.run(...). Deleting arbitrary user or operator sessions still requires an admin-scoped Gateway request.api.runtime.nodes
api.runtime.nodes
List connected nodes and invoke a node-host command from Gateway-loaded plugin code or from plugin CLI commands. Use this when a plugin owns local work on a paired device, for example a browser or audio bridge on another Mac.Inside the Gateway this runtime is in-process. In plugin CLI commands it calls the configured Gateway over RPC, so commands such as
openclaw googlemeet recover-tab can inspect paired nodes from the terminal. Node commands still go through normal Gateway node pairing, command allowlists, plugin node-invoke policies, and node-local command handling.Plugins that expose dangerous node-host commands should register a node-invoke policy with api.registerNodeInvokePolicy(...). The policy runs in the Gateway after command allowlist checks and before the command is forwarded to the node, so direct node.invoke calls and higher-level plugin tools share the same enforcement path.api.runtime.tasks
api.runtime.tasks
Bind Task Flow and Task Run state to an existing OpenClaw session key or trusted tool context.Use
api.runtime.tasks.managedFlowsis mutation-capable: create, advance, and cancel Task Flows.api.runtime.tasks.flowsandapi.runtime.tasks.runsare read-only DTO views for listing and status lookups; both exposebindSession(...)/fromToolContext(...)plusget,list,findLatest, andresolve.api.runtime.tasks.flowis a deprecated alias formanagedFlows.
api.session.workflow.scheduleSessionTurn(...) for future
wakeups, then use managedFlows from the scheduled turn when that work
needs flow state, child tasks, waits, or cancellation.bindSession({ sessionKey, requesterOrigin }) when you already have a trusted OpenClaw session key from your own binding layer. Do not bind from raw user input.api.runtime.tts
api.runtime.tts
Text-to-speech synthesis.Uses core
messages.tts configuration and provider selection. Returns PCM audio buffer + sample rate. textToSpeechStream is also available for streaming synthesis.api.runtime.mediaUnderstanding
api.runtime.mediaUnderstanding
Image, audio, and video analysis.Returns
{ text: undefined } when no output is produced (e.g. skipped input).describeImageFileWithModel(...) describes an already-known image through a specific provider/model, bypassing the default active-model resolution that describeImageFile(...) uses.api.runtime.stt.transcribeAudioFile(...) remains as a compatibility alias for api.runtime.mediaUnderstanding.transcribeAudioFile(...).api.runtime.imageGeneration
api.runtime.imageGeneration
Image generation.
api.runtime.videoGeneration
api.runtime.videoGeneration
Video generation, mirroring the image generation shape.
api.runtime.musicGeneration
api.runtime.musicGeneration
Music generation, mirroring the image generation shape.
api.runtime.webSearch
api.runtime.webSearch
Web search.
api.runtime.media
api.runtime.media
Low-level media utilities.
api.runtime.config
api.runtime.config
Current runtime config snapshot and transactional config writes. Prefer
config that was already passed into the active call path; use
current() only when the handler needs the process snapshot directly.mutateConfigFile(...) and replaceConfigFile(...) return a followUp
value, for example { mode: "restart", requiresRestart: true, reason },
which records the writer intent without taking restart control away from the
gateway.api.runtime.system
api.runtime.system
System-level utilities.
runHeartbeatOnce(...) runs a single heartbeat cycle immediately, bypassing the normal coalesce timer. Pass { heartbeat: { target: "last" } } to force delivery to the last active channel instead of the default target: "none" suppression.runCommandWithTimeout(...) returns captured stdout and stderr, optional
truncation counts, code, signal, killed, termination, and
noOutputTimedOut. Timeout and no-output-timeout results report code: 124
when the child process does not provide a non-zero exit code. Non-timeout
signal exits can still return code: null, so use termination and
noOutputTimedOut to distinguish timeout reasons.api.runtime.events
api.runtime.events
Event subscriptions.
api.runtime.logging
api.runtime.logging
Logging.
api.runtime.modelAuth
api.runtime.modelAuth
Model and provider auth resolution.
api.runtime.state
api.runtime.state
State directory resolution and SQLite-backed keyed storage.Keyed stores survive restarts and are isolated by the runtime-bound plugin id. Use
registerIfAbsent(...) for atomic dedupe claims: it returns true when the key was missing or expired and registered, or false when a live value already exists without overwriting its value, creation time, or TTL. Limits: maxEntries per namespace, 50,000 live rows per plugin, JSON values under 64KB, and optional TTL expiry. By default, a write at either row limit sheds the oldest live rows from the namespace being written; sibling namespaces are not evicted for that write, and the write still fails if the namespace cannot free enough rows. Set overflowPolicy: "reject-new" for durable ownership records that must never be evicted: new keys fail at either limit, while existing keys remain updateable.openSyncKeyedStore<T>(...) returns the same store shape with synchronous methods (register, registerIfAbsent, lookup, consume, clear all return values directly instead of promises) for callers that cannot await.openChannelIngressQueue<TPayload>(...) opens a persisted ingress queue scoped to the calling plugin, for buffering inbound events that need at-least-once processing across restarts.api.runtime.channel
api.runtime.channel
Channel-specific runtime helpers (available when a channel plugin is loaded). Grouped by concern:
Use Available mention helpers:
| Group | Purpose |
|---|---|
text | Chunking (chunkText, chunkMarkdownText, resolveChunkMode), control-command detection, Markdown table conversion. |
reply | Buffered-block reply dispatch, envelope formatting, effective messages/human-delay config resolution. |
routing | buildAgentSessionKey, resolveAgentRoute. |
pairing | buildPairingReply, allowlist reads, pairing-request upserts. |
media | Remote media download/save (see below). |
activity | Record/read last channel activity. |
session | Session metadata from inbound events, last-route updates. |
mentions | Mention-policy helpers (see below). |
reactions | Ack-reaction handles for in-flight processing indicators. |
groups | Group policy and require-mention resolution. |
debounce | Inbound message debouncing. |
commands | Command authorization and text-command gating. |
outbound | Load a channel’s outbound adapter. |
inbound | Build inbound event context and run the shared inbound-event/reply kernel. |
threadBindings | Adjust idle-timeout/max-age for bound session threads. |
runtimeContexts | Register, read, and watch process-local per-channel/account/capability context. |
api.runtime.channel.media is the preferred surface for channel media downloads and storage:saveRemoteMedia(...) when a remote URL should become OpenClaw media. Use saveResponseMedia(...) when the plugin already fetched a Response with plugin-owned auth, redirect, or allowlist handling. Use readRemoteMediaBuffer(...) only when the plugin needs raw bytes for inspection, transforms, decryption, or reupload. fetchRemoteMedia(...) remains a deprecated compatibility alias for readRemoteMediaBuffer(...).api.runtime.channel.mentions is the shared inbound mention-policy surface for bundled channel plugins that use runtime injection:buildMentionRegexesmatchesMentionPatternsmatchesMentionWithExplicitimplicitMentionKindWhenresolveInboundMentionDecision
api.runtime.channel.mentions intentionally does not expose the older resolveMentionGating* compatibility helpers. Prefer the normalized { facts, policy } path.Several fields under reply, session, and inbound carry per-field @deprecated notes pointing at the current channel-turn kernel or channel-outbound adapters; check the inline JSDoc on the specific helper before building new code on it.Storing runtime references
UsecreatePluginRuntimeStore to store the runtime reference for use outside the register callback:
Prefer
pluginId for the runtime-store identity. The lower-level key form is for uncommon cases where one plugin intentionally needs more than one runtime slot.Other top-level api fields
Beyond api.runtime, the API object also provides:
Plugin id.
Plugin display name.
Current config snapshot (active in-memory runtime snapshot when available).
Plugin-specific config from
plugins.entries.<id>.config.Scoped logger (
debug, info, warn, error).Current load mode:
"full" (live activation), "discovery" / "tool-discovery" (read-only capability discovery), "setup-only" (lightweight setup entry), "setup-runtime" (setup flow that also needs the runtime channel entry), or "cli-metadata" (CLI command metadata collection).Resolve a path relative to the plugin root.
Related
- Plugin internals — capability model and registry
- SDK entry points —
definePluginEntryoptions - SDK overview — subpath reference