Plugin runtime helpers
기준일: 2026-07-26
공식 기준: Plugin runtime helpers
Plugin runtime helpers 문서는 OpenClaw 공식 문서(plugins/sdk-runtime)를 한국어로 정리한 가이드입니다. api.runtime -- the injected runtime helpers available to plugins 명령·설정 키·코드 예시는 공식 문서를 그대로 보존하며, 해석과 절차 안내는 한국어로 제공합니다. 최종 동작은 설치된 CLI 버전과 공식 원문을 확인하세요.
핵심 요약
api.runtime -- the injected runtime helpers available to plugins
한국어 가이드 범위: plugins/sdk-runtime 경로의 설정·명령·제약·예시를 학습용으로 재구성합니다.
문서 구성
공식 문서의 주요 섹션은 다음과 같습니다.
- Config loading and writes
- Reusable runtime utilities
- Runtime namespaces
- Storing runtime references
- Other top-level api fields
- 관련 문서
상세 내용
본문
Reference for the api.runtime object injected into every plugin during registration. Use these helpers instead of importing host internals directly.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문과
--help를 확인하세요.
register(api) {
const runtime = api.runtime;
}
Config loading and writes
Prefer config that was already passed into the active call path, for example api.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.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문과
--help를 확인하세요.
주요 항목:
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.
Reusable runtime utilities
Use inbound botLoopProtection 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.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문과
--help를 확인하세요.
type ChannelBotLoopProtectionConfig = {
enabled?: boolean;
maxEventsPerWindow?: number;
windowSeconds?: number;
cooldownSeconds?: number;
};
return {
channel: "example",
routeSessionKey,
storePath,
ctxPayload,
recordInboundSession,
runDispatch,
botLoopProtection: {
scopeId: "account-1",
conversationId: "channel-1",
senderId: "bot-a",
receiverId: "bot-b",
config: channelConfig.botLoopProtection,
defaultsConfig: runtimeConfig.channels?.defaults?.botLoopProtection,
defaultEnabled: allowBotsMode !== "off",
},
};
Runtime namespaces
Agent identity, directories, and session management.
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문과
--help를 확인하세요.
주요 항목:
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.buildMentionRegexesmatchesMentionPatternsmatchesMentionWithExplicitimplicitMentionKindWhenresolveInboundMentionDecision
// Resolve the agent's working directory (agentId is required)
const agentDir = api.runtime.agent.resolveAgentDir(cfg, agentId);
// Resolve agent workspace
const workspaceDir = api.runtime.agent.resolveAgentWorkspaceDir(cfg, agentId);
// 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 result = await api.runtime.agent.runEmbeddedAgent({
sessionId: "my-plugin:task-1",
runId: crypto.randomUUID(),
workspaceDir: api.runtime.agent.resolveAgentWorkspaceDir(cfg, agentId),
prompt: "Summarize the latest changes",
timeoutMs: api.runtime.agent.resolveAgentTimeoutMs(cfg),
});
const entry = api.runtime.agent.session.getSessionEntry({ agentId, sessionKey });
for (const { sessionKey, entry } of api.runtime.agent.session.listSessionEntries({ agentId })) {
// Iterate session rows without depending on the legacy sessions.json shape.
}
await api.runtime.agent.session.patchSessionEntry({
agentId,
sessionKey,
update: (entry) => ({ thinkingLevel: "high" }),
});
const created = await api.runtime.agent.session.createSessionEntry({
cfg,
key: "agent:main:my-plugin:task-1",
initialEntry: {
agentHarnessId: "my-harness",
modelSelectionLocked: true,
pluginExtensions: { "my-plugin": { phase: "initializing" } },
},
afterCreate: async () => ({
pluginExtensions: { "my-plugin": { phase: "ready" } },
}),
});
const storePath = api.runtime.agent.session.resolveStorePath(cfg.session?.store, { agentId });
await api.runtime.agent.session.runWithWorkAdmission(
{ storePath, sessionKey },
async (signal) => {
// Create or update the session, then pass signal to the admitted agent run.
},
);
const model = api.runtime.agent.defaults.model; // e.g. "gpt-5.6-sol"
const provider = api.runtime.agent.defaults.provider; // e.g. "openai"
const result = await api.runtime.llm.complete({
messages: [{ role: "user", content: "Summarize this transcript." }],
purpose: "my-plugin.summary",
maxTokens: 512,
temperature: 0.2,
reasoning: "high",
});
Storing runtime references
Use createPluginRuntimeStore to store the runtime reference for use outside the register callback:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문과
--help를 확인하세요.
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",
});
export default defineChannelPluginEntry({
id: "my-plugin",
name: "My Plugin",
description: "Example",
plugin: myPlugin,
setRuntime: store.setRuntime,
});
export function getRuntime() {
return store.getRuntime(); // throws if not initialized
}
export function tryGetRuntime() {
return store.tryGetRuntime(); // returns null if not initialized
}
Other top-level api fields
Beyond api.runtime, the API object also provides:
위 내용은 공식 문서의 해당 섹션 요지입니다. 세부 플래그·기본값은 원문과
--help를 확인하세요.
관련 문서
주요 항목:
- Plugin internals — capability model and registry
- SDK entry points —
definePluginEntryoptions - SDK overview — subpath reference
실습 체크리스트
- 공식 문서와 로컬 버전을 대조합니다:
https://docs.openclaw.ai/plugins/sdk-runtime - 관련 CLI는
openclaw --help및 하위 명령--help로 옵션을 확인합니다. - 설정 변경 시
openclaw config/openclaw doctor로 유효성을 검사합니다. - Gateway·채널·플러그인 변경 후에는 필요 시 Gateway를 재시작합니다.
자주 쓰는 명령·설정 예시
register(api) {
const runtime = api.runtime;
}
type ChannelBotLoopProtectionConfig = {
enabled?: boolean;
maxEventsPerWindow?: number;
windowSeconds?: number;
cooldownSeconds?: number;
};
return {
channel: "example",
routeSessionKey,
storePath,
ctxPayload,
recordInboundSession,
runDispatch,
botLoopProtection: {
scopeId: "account-1",
conversationId: "channel-1",
senderId: "bot-a",
receiverId: "bot-b",
config: channelConfig.botLoopProtection,
defaultsConfig: runtimeConfig.channels?.defaults?.botLoopProtection,
defaultEnabled: allowBotsMode !== "off",
},
};
// Resolve the agent's working directory (agentId is required)
const agentDir = api.runtime.agent.resolveAgentDir(cfg, agentId);
// Resolve agent workspace
const workspaceDir = api.runtime.agent.resolveAgentWorkspaceDir(cfg, agentId);
// 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 result = await api.runtime.agent.runEmbeddedAgent({
sessionId: "my-plugin:task-1",
runId: crypto.randomUUID(),
workspaceDir: api.runtime.agent.resolveAgentWorkspaceDir(cfg, agentId),
prompt: "Summarize the latest changes",
timeoutMs: api.runtime.agent.resolveAgentTimeoutMs(cfg),
});
const entry = api.runtime.agent.session.getSessionEntry({ agentId, sessionKey });
for (const { sessionKey, entry } of api.runtime.agent.session.listSessionEntries({ agentId })) {
// Iterate session rows without depending on the legacy sessions.json shape.
}
await api.runtime.agent.session.patchSessionEntry({
agentId,
sessionKey,
update: (entry) => ({ thinkingLevel: "high" }),
});
const created = await api.runtime.agent.session.createSessionEntry({
cfg,
key: "agent:main:my-plugin:task-1",
initialEntry: {
agentHarnessId: "my-harness",
modelSelectionLocked: true,
pluginExtensions: { "my-plugin": { phase: "initializing" } },
},
afterCreate: async () => ({
pluginExtensions: { "my-plugin": { phase: "ready" } },
}),
});
const storePath = api.runtime.agent.session.resolveStorePath(cfg.session?.store, { agentId });
await api.runtime.agent.session.runWithWorkAdmission(
{ storePath, sessionKey },
async (signal) => {
// Create or update the session, then pass signal to the admitted agent run.
},
);
const model = api.runtime.agent.defaults.model; // e.g. "gpt-5.6-sol"
const provider = api.runtime.agent.defaults.provider; // e.g. "openai"
관련 링크
- 공식 원문: plugins/sdk-runtime
- OpenClaw 문서 홈
이 가이드는 공식 문서를 한국어 학습용으로 재구성한 것입니다. 옵션 기본값·플래그 이름은 설치 버전에 따라 달라질 수 있습니다.