mirror of
https://github.com/hansjone/oclaw.git
synced 2026-10-09 16:30:47 +08:00
重构主控编排与运行时预热链路,统一工作区提示词/专家调度协议并补齐 wiki 记忆注入与写回闭环。
同时收敛启动与运维脚本默认行为(含 wiki worker)、更新 Admin 可观测性与相关测试,降低首轮时延并提高运行稳定性。 Made-with: Cursor
This commit is contained in:
parent
4a23b715a2
commit
dbbe3add6a
14438 changed files with 2693620 additions and 2546 deletions
10
openclaw/docs/plugins/agent-tools.md
Normal file
10
openclaw/docs/plugins/agent-tools.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
summary: "Redirects to Building Plugins (registering tools section)"
|
||||
read_when:
|
||||
- Legacy link to agent-tools
|
||||
title: "Registering Tools"
|
||||
---
|
||||
|
||||
# Registering Tools in Plugins
|
||||
|
||||
This page has moved. See [Building Plugins: Registering agent tools](/plugins/building-plugins#registering-agent-tools).
|
||||
1675
openclaw/docs/plugins/architecture.md
Normal file
1675
openclaw/docs/plugins/architecture.md
Normal file
File diff suppressed because it is too large
Load diff
10
openclaw/docs/plugins/building-extensions.md
Normal file
10
openclaw/docs/plugins/building-extensions.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
title: "Building Plugins (redirect)"
|
||||
summary: "Redirects to the current Building Plugins guide"
|
||||
read_when:
|
||||
- Legacy link to building-extensions
|
||||
---
|
||||
|
||||
# Building Plugins
|
||||
|
||||
This page has moved to [Building Plugins](/plugins/building-plugins).
|
||||
320
openclaw/docs/plugins/building-plugins.md
Normal file
320
openclaw/docs/plugins/building-plugins.md
Normal file
|
|
@ -0,0 +1,320 @@
|
|||
---
|
||||
title: "Building Plugins"
|
||||
sidebarTitle: "Getting Started"
|
||||
summary: "Create your first OpenClaw plugin in minutes"
|
||||
read_when:
|
||||
- You want to create a new OpenClaw plugin
|
||||
- You need a quick-start for plugin development
|
||||
- You are adding a new channel, provider, tool, or other capability to OpenClaw
|
||||
---
|
||||
|
||||
# Building Plugins
|
||||
|
||||
Plugins extend OpenClaw with new capabilities: channels, model providers,
|
||||
speech, realtime transcription, realtime voice, media understanding, image
|
||||
generation, video generation, web fetch, web search, agent tools, or any
|
||||
combination.
|
||||
|
||||
You do not need to add your plugin to the OpenClaw repository. Publish to
|
||||
[ClawHub](/tools/clawhub) or npm and users install with
|
||||
`openclaw plugins install <package-name>`. OpenClaw tries ClawHub first and
|
||||
falls back to npm automatically.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Node >= 22 and a package manager (npm or pnpm)
|
||||
- Familiarity with TypeScript (ESM)
|
||||
- For in-repo plugins: repository cloned and `pnpm install` done
|
||||
|
||||
## What kind of plugin?
|
||||
|
||||
<CardGroup cols={3}>
|
||||
<Card title="Channel plugin" icon="messages-square" href="/plugins/sdk-channel-plugins">
|
||||
Connect OpenClaw to a messaging platform (Discord, IRC, etc.)
|
||||
</Card>
|
||||
<Card title="Provider plugin" icon="cpu" href="/plugins/sdk-provider-plugins">
|
||||
Add a model provider (LLM, proxy, or custom endpoint)
|
||||
</Card>
|
||||
<Card title="Tool / hook plugin" icon="wrench">
|
||||
Register agent tools, event hooks, or services — continue below
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
If a channel plugin is optional and may not be installed when onboarding/setup
|
||||
runs, use `createOptionalChannelSetupSurface(...)` from
|
||||
`openclaw/plugin-sdk/channel-setup`. It produces a setup adapter + wizard pair
|
||||
that advertises the install requirement and fails closed on real config writes
|
||||
until the plugin is installed.
|
||||
|
||||
## Quick start: tool plugin
|
||||
|
||||
This walkthrough creates a minimal plugin that registers an agent tool. Channel
|
||||
and provider plugins have dedicated guides linked above.
|
||||
|
||||
<Steps>
|
||||
<Step title="Create the package and manifest">
|
||||
<CodeGroup>
|
||||
```json package.json
|
||||
{
|
||||
"name": "@myorg/openclaw-my-plugin",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.3.24-beta.2",
|
||||
"minGatewayVersion": "2026.3.24-beta.2"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.3.24-beta.2",
|
||||
"pluginSdkVersion": "2026.3.24-beta.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json openclaw.plugin.json
|
||||
{
|
||||
"id": "my-plugin",
|
||||
"name": "My Plugin",
|
||||
"description": "Adds a custom tool to OpenClaw",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
Every plugin needs a manifest, even with no config. See
|
||||
[Manifest](/plugins/manifest) for the full schema. The canonical ClawHub
|
||||
publish snippets live in `docs/snippets/plugin-publish/`.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Write the entry point">
|
||||
|
||||
```typescript
|
||||
// index.ts
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { Type } from "@sinclair/typebox";
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "my-plugin",
|
||||
name: "My Plugin",
|
||||
description: "Adds a custom tool to OpenClaw",
|
||||
register(api) {
|
||||
api.registerTool({
|
||||
name: "my_tool",
|
||||
description: "Do a thing",
|
||||
parameters: Type.Object({ input: Type.String() }),
|
||||
async execute(_id, params) {
|
||||
return { content: [{ type: "text", text: `Got: ${params.input}` }] };
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
`definePluginEntry` is for non-channel plugins. For channels, use
|
||||
`defineChannelPluginEntry` — see [Channel Plugins](/plugins/sdk-channel-plugins).
|
||||
For full entry point options, see [Entry Points](/plugins/sdk-entrypoints).
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Test and publish">
|
||||
|
||||
**External plugins:** validate and publish with ClawHub, then install:
|
||||
|
||||
```bash
|
||||
clawhub package publish your-org/your-plugin --dry-run
|
||||
clawhub package publish your-org/your-plugin
|
||||
openclaw plugins install clawhub:@myorg/openclaw-my-plugin
|
||||
```
|
||||
|
||||
OpenClaw also checks ClawHub before npm for bare package specs like
|
||||
`@myorg/openclaw-my-plugin`.
|
||||
|
||||
**In-repo plugins:** place under the bundled plugin workspace tree — automatically discovered.
|
||||
|
||||
```bash
|
||||
pnpm test -- <bundled-plugin-root>/my-plugin/
|
||||
```
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Plugin capabilities
|
||||
|
||||
A single plugin can register any number of capabilities via the `api` object:
|
||||
|
||||
| Capability | Registration method | Detailed guide |
|
||||
| ---------------------- | ------------------------------------------------ | ------------------------------------------------------------------------------- |
|
||||
| Text inference (LLM) | `api.registerProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins) |
|
||||
| CLI inference backend | `api.registerCliBackend(...)` | [CLI Backends](/gateway/cli-backends) |
|
||||
| Channel / messaging | `api.registerChannel(...)` | [Channel Plugins](/plugins/sdk-channel-plugins) |
|
||||
| Speech (TTS/STT) | `api.registerSpeechProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Realtime transcription | `api.registerRealtimeTranscriptionProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Realtime voice | `api.registerRealtimeVoiceProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Media understanding | `api.registerMediaUnderstandingProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Image generation | `api.registerImageGenerationProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Music generation | `api.registerMusicGenerationProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Video generation | `api.registerVideoGenerationProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Web fetch | `api.registerWebFetchProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Web search | `api.registerWebSearchProvider(...)` | [Provider Plugins](/plugins/sdk-provider-plugins#step-5-add-extra-capabilities) |
|
||||
| Agent tools | `api.registerTool(...)` | Below |
|
||||
| Custom commands | `api.registerCommand(...)` | [Entry Points](/plugins/sdk-entrypoints) |
|
||||
| Event hooks | `api.registerHook(...)` | [Entry Points](/plugins/sdk-entrypoints) |
|
||||
| HTTP routes | `api.registerHttpRoute(...)` | [Internals](/plugins/architecture#gateway-http-routes) |
|
||||
| CLI subcommands | `api.registerCli(...)` | [Entry Points](/plugins/sdk-entrypoints) |
|
||||
|
||||
For the full registration API, see [SDK Overview](/plugins/sdk-overview#registration-api).
|
||||
|
||||
If your plugin registers custom gateway RPC methods, keep them on a
|
||||
plugin-specific prefix. Core admin namespaces (`config.*`,
|
||||
`exec.approvals.*`, `wizard.*`, `update.*`) stay reserved and always resolve to
|
||||
`operator.admin`, even if a plugin asks for a narrower scope.
|
||||
|
||||
Hook guard semantics to keep in mind:
|
||||
|
||||
- `before_tool_call`: `{ block: true }` is terminal and stops lower-priority handlers.
|
||||
- `before_tool_call`: `{ block: false }` is treated as no decision.
|
||||
- `before_tool_call`: `{ requireApproval: true }` pauses agent execution and prompts the user for approval via the exec approval overlay, Telegram buttons, Discord interactions, or the `/approve` command on any channel.
|
||||
- `before_install`: `{ block: true }` is terminal and stops lower-priority handlers.
|
||||
- `before_install`: `{ block: false }` is treated as no decision.
|
||||
- `message_sending`: `{ cancel: true }` is terminal and stops lower-priority handlers.
|
||||
- `message_sending`: `{ cancel: false }` is treated as no decision.
|
||||
|
||||
The `/approve` command handles both exec and plugin approvals with bounded fallback: when an exec approval id is not found, OpenClaw retries the same id through plugin approvals. Plugin approval forwarding can be configured independently via `approvals.plugin` in config.
|
||||
|
||||
If custom approval plumbing needs to detect that same bounded fallback case,
|
||||
prefer `isApprovalNotFoundError` from `openclaw/plugin-sdk/error-runtime`
|
||||
instead of matching approval-expiry strings manually.
|
||||
|
||||
See [SDK Overview hook decision semantics](/plugins/sdk-overview#hook-decision-semantics) for details.
|
||||
|
||||
## Registering agent tools
|
||||
|
||||
Tools are typed functions the LLM can call. They can be required (always
|
||||
available) or optional (user opt-in):
|
||||
|
||||
```typescript
|
||||
register(api) {
|
||||
// Required tool — always available
|
||||
api.registerTool({
|
||||
name: "my_tool",
|
||||
description: "Do a thing",
|
||||
parameters: Type.Object({ input: Type.String() }),
|
||||
async execute(_id, params) {
|
||||
return { content: [{ type: "text", text: params.input }] };
|
||||
},
|
||||
});
|
||||
|
||||
// Optional tool — user must add to allowlist
|
||||
api.registerTool(
|
||||
{
|
||||
name: "workflow_tool",
|
||||
description: "Run a workflow",
|
||||
parameters: Type.Object({ pipeline: Type.String() }),
|
||||
async execute(_id, params) {
|
||||
return { content: [{ type: "text", text: params.pipeline }] };
|
||||
},
|
||||
},
|
||||
{ optional: true },
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Users enable optional tools in config:
|
||||
|
||||
```json5
|
||||
{
|
||||
tools: { allow: ["workflow_tool"] },
|
||||
}
|
||||
```
|
||||
|
||||
- Tool names must not clash with core tools (conflicts are skipped)
|
||||
- Use `optional: true` for tools with side effects or extra binary requirements
|
||||
- Users can enable all tools from a plugin by adding the plugin id to `tools.allow`
|
||||
|
||||
## Import conventions
|
||||
|
||||
Always import from focused `openclaw/plugin-sdk/<subpath>` paths:
|
||||
|
||||
```typescript
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
|
||||
|
||||
// Wrong: monolithic root (deprecated, will be removed)
|
||||
import { ... } from "openclaw/plugin-sdk";
|
||||
```
|
||||
|
||||
For the full subpath reference, see [SDK Overview](/plugins/sdk-overview).
|
||||
|
||||
Within your plugin, use local barrel files (`api.ts`, `runtime-api.ts`) for
|
||||
internal imports — never import your own plugin through its SDK path.
|
||||
|
||||
For provider plugins, keep provider-specific helpers in those package-root
|
||||
barrels unless the seam is truly generic. Current bundled examples:
|
||||
|
||||
- Anthropic: Claude stream wrappers and `service_tier` / beta helpers
|
||||
- OpenAI: provider builders, default-model helpers, realtime providers
|
||||
- OpenRouter: provider builder plus onboarding/config helpers
|
||||
|
||||
If a helper is only useful inside one bundled provider package, keep it on that
|
||||
package-root seam instead of promoting it into `openclaw/plugin-sdk/*`.
|
||||
|
||||
Some generated `openclaw/plugin-sdk/<bundled-id>` helper seams still exist for
|
||||
bundled-plugin maintenance and compatibility, for example
|
||||
`plugin-sdk/feishu-setup` or `plugin-sdk/zalo-setup`. Treat those as reserved
|
||||
surfaces, not as the default pattern for new third-party plugins.
|
||||
|
||||
## Pre-submission checklist
|
||||
|
||||
<Check>**package.json** has correct `openclaw` metadata</Check>
|
||||
<Check>**openclaw.plugin.json** manifest is present and valid</Check>
|
||||
<Check>Entry point uses `defineChannelPluginEntry` or `definePluginEntry`</Check>
|
||||
<Check>All imports use focused `plugin-sdk/<subpath>` paths</Check>
|
||||
<Check>Internal imports use local modules, not SDK self-imports</Check>
|
||||
<Check>Tests pass (`pnpm test -- <bundled-plugin-root>/my-plugin/`)</Check>
|
||||
<Check>`pnpm check` passes (in-repo plugins)</Check>
|
||||
|
||||
## Beta Release Testing
|
||||
|
||||
1. Watch for GitHub release tags on [openclaw/openclaw](https://github.com/openclaw/openclaw/releases) and subscribe via `Watch` > `Releases`. Beta tags look like `v2026.3.N-beta.1`. You can also turn on notifications for the official OpenClaw X account [@openclaw](https://x.com/openclaw) for release announcements.
|
||||
2. Test your plugin against the beta tag as soon as it appears. The window before stable is typically only a few hours.
|
||||
3. Post in your plugin's thread in the `plugin-forum` Discord channel after testing with either `all good` or what broke. If you do not have a thread yet, create one.
|
||||
4. If something breaks, open or update an issue titled `Beta blocker: <plugin-name> - <summary>` and apply the `beta-blocker` label. Put the issue link in your thread.
|
||||
5. Open a PR to `main` titled `fix(<plugin-id>): beta blocker - <summary>` and link the issue in both the PR and your Discord thread. Contributors cannot label PRs, so the title is the PR-side signal for maintainers and automation. Blockers with a PR get merged; blockers without one might ship anyway. Maintainers watch these threads during beta testing.
|
||||
6. Silence means green. If you miss the window, your fix likely lands in the next cycle.
|
||||
|
||||
## Next steps
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Channel Plugins" icon="messages-square" href="/plugins/sdk-channel-plugins">
|
||||
Build a messaging channel plugin
|
||||
</Card>
|
||||
<Card title="Provider Plugins" icon="cpu" href="/plugins/sdk-provider-plugins">
|
||||
Build a model provider plugin
|
||||
</Card>
|
||||
<Card title="SDK Overview" icon="book-open" href="/plugins/sdk-overview">
|
||||
Import map and registration API reference
|
||||
</Card>
|
||||
<Card title="Runtime Helpers" icon="settings" href="/plugins/sdk-runtime">
|
||||
TTS, search, subagent via api.runtime
|
||||
</Card>
|
||||
<Card title="Testing" icon="test-tubes" href="/plugins/sdk-testing">
|
||||
Test utilities and patterns
|
||||
</Card>
|
||||
<Card title="Plugin Manifest" icon="file-json" href="/plugins/manifest">
|
||||
Full manifest schema reference
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
## Related
|
||||
|
||||
- [Plugin Architecture](/plugins/architecture) — internal architecture deep dive
|
||||
- [SDK Overview](/plugins/sdk-overview) — Plugin SDK reference
|
||||
- [Manifest](/plugins/manifest) — plugin manifest format
|
||||
- [Channel Plugins](/plugins/sdk-channel-plugins) — building channel plugins
|
||||
- [Provider Plugins](/plugins/sdk-provider-plugins) — building provider plugins
|
||||
292
openclaw/docs/plugins/bundles.md
Normal file
292
openclaw/docs/plugins/bundles.md
Normal file
|
|
@ -0,0 +1,292 @@
|
|||
---
|
||||
summary: "Install and use Codex, Claude, and Cursor bundles as OpenClaw plugins"
|
||||
read_when:
|
||||
- You want to install a Codex, Claude, or Cursor-compatible bundle
|
||||
- You need to understand how OpenClaw maps bundle content into native features
|
||||
- You are debugging bundle detection or missing capabilities
|
||||
title: "Plugin Bundles"
|
||||
---
|
||||
|
||||
# Plugin Bundles
|
||||
|
||||
OpenClaw can install plugins from three external ecosystems: **Codex**, **Claude**,
|
||||
and **Cursor**. These are called **bundles** — content and metadata packs that
|
||||
OpenClaw maps into native features like skills, hooks, and MCP tools.
|
||||
|
||||
<Info>
|
||||
Bundles are **not** the same as native OpenClaw plugins. Native plugins run
|
||||
in-process and can register any capability. Bundles are content packs with
|
||||
selective feature mapping and a narrower trust boundary.
|
||||
</Info>
|
||||
|
||||
## Why bundles exist
|
||||
|
||||
Many useful plugins are published in Codex, Claude, or Cursor format. Instead
|
||||
of requiring authors to rewrite them as native OpenClaw plugins, OpenClaw
|
||||
detects these formats and maps their supported content into the native feature
|
||||
set. This means you can install a Claude command pack or a Codex skill bundle
|
||||
and use it immediately.
|
||||
|
||||
## Install a bundle
|
||||
|
||||
<Steps>
|
||||
<Step title="Install from a directory, archive, or marketplace">
|
||||
```bash
|
||||
# Local directory
|
||||
openclaw plugins install ./my-bundle
|
||||
|
||||
# Archive
|
||||
openclaw plugins install ./my-bundle.tgz
|
||||
|
||||
# Claude marketplace
|
||||
openclaw plugins marketplace list <marketplace-name>
|
||||
openclaw plugins install <plugin-name>@<marketplace-name>
|
||||
```
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Verify detection">
|
||||
```bash
|
||||
openclaw plugins list
|
||||
openclaw plugins inspect <id>
|
||||
```
|
||||
|
||||
Bundles show as `Format: bundle` with a subtype of `codex`, `claude`, or `cursor`.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Restart and use">
|
||||
```bash
|
||||
openclaw gateway restart
|
||||
```
|
||||
|
||||
Mapped features (skills, hooks, MCP tools, LSP defaults) are available in the next session.
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## What OpenClaw maps from bundles
|
||||
|
||||
Not every bundle feature runs in OpenClaw today. Here is what works and what
|
||||
is detected but not yet wired.
|
||||
|
||||
### Supported now
|
||||
|
||||
| Feature | How it maps | Applies to |
|
||||
| ------------- | ------------------------------------------------------------------------------------------- | -------------- |
|
||||
| Skill content | Bundle skill roots load as normal OpenClaw skills | All formats |
|
||||
| Commands | `commands/` and `.cursor/commands/` treated as skill roots | Claude, Cursor |
|
||||
| Hook packs | OpenClaw-style `HOOK.md` + `handler.ts` layouts | Codex |
|
||||
| MCP tools | Bundle MCP config merged into embedded Pi settings; supported stdio and HTTP servers loaded | All formats |
|
||||
| LSP servers | Claude `.lsp.json` and manifest-declared `lspServers` merged into embedded Pi LSP defaults | Claude |
|
||||
| Settings | Claude `settings.json` imported as embedded Pi defaults | Claude |
|
||||
|
||||
#### Skill content
|
||||
|
||||
- bundle skill roots load as normal OpenClaw skill roots
|
||||
- Claude `commands` roots are treated as additional skill roots
|
||||
- Cursor `.cursor/commands` roots are treated as additional skill roots
|
||||
|
||||
This means Claude markdown command files work through the normal OpenClaw skill
|
||||
loader. Cursor command markdown works through the same path.
|
||||
|
||||
#### Hook packs
|
||||
|
||||
- bundle hook roots work **only** when they use the normal OpenClaw hook-pack
|
||||
layout. Today this is primarily the Codex-compatible case:
|
||||
- `HOOK.md`
|
||||
- `handler.ts` or `handler.js`
|
||||
|
||||
#### MCP for Pi
|
||||
|
||||
- enabled bundles can contribute MCP server config
|
||||
- OpenClaw merges bundle MCP config into the effective embedded Pi settings as
|
||||
`mcpServers`
|
||||
- OpenClaw exposes supported bundle MCP tools during embedded Pi agent turns by
|
||||
launching stdio servers or connecting to HTTP servers
|
||||
- project-local Pi settings still apply after bundle defaults, so workspace
|
||||
settings can override bundle MCP entries when needed
|
||||
- bundle MCP tool catalogs are sorted deterministically before registration, so
|
||||
upstream `listTools()` order changes do not thrash prompt-cache tool blocks
|
||||
|
||||
##### Transports
|
||||
|
||||
MCP servers can use stdio or HTTP transport:
|
||||
|
||||
**Stdio** launches a child process:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"my-server": {
|
||||
"command": "node",
|
||||
"args": ["server.js"],
|
||||
"env": { "PORT": "3000" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**HTTP** connects to a running MCP server over `sse` by default, or `streamable-http` when requested:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"servers": {
|
||||
"my-server": {
|
||||
"url": "http://localhost:3100/mcp",
|
||||
"transport": "streamable-http",
|
||||
"headers": {
|
||||
"Authorization": "Bearer ${MY_SECRET_TOKEN}"
|
||||
},
|
||||
"connectionTimeoutMs": 30000
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- `transport` may be set to `"streamable-http"` or `"sse"`; when omitted, OpenClaw uses `sse`
|
||||
- only `http:` and `https:` URL schemes are allowed
|
||||
- `headers` values support `${ENV_VAR}` interpolation
|
||||
- a server entry with both `command` and `url` is rejected
|
||||
- URL credentials (userinfo and query params) are redacted from tool
|
||||
descriptions and logs
|
||||
- `connectionTimeoutMs` overrides the default 30-second connection timeout for
|
||||
both stdio and HTTP transports
|
||||
|
||||
##### Tool naming
|
||||
|
||||
OpenClaw registers bundle MCP tools with provider-safe names in the form
|
||||
`serverName__toolName`. For example, a server keyed `"vigil-harbor"` exposing a
|
||||
`memory_search` tool registers as `vigil-harbor__memory_search`.
|
||||
|
||||
- characters outside `A-Za-z0-9_-` are replaced with `-`
|
||||
- server prefixes are capped at 30 characters
|
||||
- full tool names are capped at 64 characters
|
||||
- empty server names fall back to `mcp`
|
||||
- colliding sanitized names are disambiguated with numeric suffixes
|
||||
- final exposed tool order is deterministic by safe name to keep repeated Pi
|
||||
turns cache-stable
|
||||
|
||||
#### Embedded Pi settings
|
||||
|
||||
- Claude `settings.json` is imported as default embedded Pi settings when the
|
||||
bundle is enabled
|
||||
- OpenClaw sanitizes shell override keys before applying them
|
||||
|
||||
Sanitized keys:
|
||||
|
||||
- `shellPath`
|
||||
- `shellCommandPrefix`
|
||||
|
||||
#### Embedded Pi LSP
|
||||
|
||||
- enabled Claude bundles can contribute LSP server config
|
||||
- OpenClaw loads `.lsp.json` plus any manifest-declared `lspServers` paths
|
||||
- bundle LSP config is merged into the effective embedded Pi LSP defaults
|
||||
- only supported stdio-backed LSP servers are runnable today; unsupported
|
||||
transports still show up in `openclaw plugins inspect <id>`
|
||||
|
||||
### Detected but not executed
|
||||
|
||||
These are recognized and shown in diagnostics, but OpenClaw does not run them:
|
||||
|
||||
- Claude `agents`, `hooks.json` automation, `outputStyles`
|
||||
- Cursor `.cursor/agents`, `.cursor/hooks.json`, `.cursor/rules`
|
||||
- Codex inline/app metadata beyond capability reporting
|
||||
|
||||
## Bundle formats
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Codex bundles">
|
||||
Markers: `.codex-plugin/plugin.json`
|
||||
|
||||
Optional content: `skills/`, `hooks/`, `.mcp.json`, `.app.json`
|
||||
|
||||
Codex bundles fit OpenClaw best when they use skill roots and OpenClaw-style
|
||||
hook-pack directories (`HOOK.md` + `handler.ts`).
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Claude bundles">
|
||||
Two detection modes:
|
||||
|
||||
- **Manifest-based:** `.claude-plugin/plugin.json`
|
||||
- **Manifestless:** default Claude layout (`skills/`, `commands/`, `agents/`, `hooks/`, `.mcp.json`, `.lsp.json`, `settings.json`)
|
||||
|
||||
Claude-specific behavior:
|
||||
|
||||
- `commands/` is treated as skill content
|
||||
- `settings.json` is imported into embedded Pi settings (shell override keys are sanitized)
|
||||
- `.mcp.json` exposes supported stdio tools to embedded Pi
|
||||
- `.lsp.json` plus manifest-declared `lspServers` paths load into embedded Pi LSP defaults
|
||||
- `hooks/hooks.json` is detected but not executed
|
||||
- Custom component paths in the manifest are additive (they extend defaults, not replace them)
|
||||
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Cursor bundles">
|
||||
Markers: `.cursor-plugin/plugin.json`
|
||||
|
||||
Optional content: `skills/`, `.cursor/commands/`, `.cursor/agents/`, `.cursor/rules/`, `.cursor/hooks.json`, `.mcp.json`
|
||||
|
||||
- `.cursor/commands/` is treated as skill content
|
||||
- `.cursor/rules/`, `.cursor/agents/`, and `.cursor/hooks.json` are detect-only
|
||||
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Detection precedence
|
||||
|
||||
OpenClaw checks for native plugin format first:
|
||||
|
||||
1. `openclaw.plugin.json` or valid `package.json` with `openclaw.extensions` — treated as **native plugin**
|
||||
2. Bundle markers (`.codex-plugin/`, `.claude-plugin/`, or default Claude/Cursor layout) — treated as **bundle**
|
||||
|
||||
If a directory contains both, OpenClaw uses the native path. This prevents
|
||||
dual-format packages from being partially installed as bundles.
|
||||
|
||||
## Security
|
||||
|
||||
Bundles have a narrower trust boundary than native plugins:
|
||||
|
||||
- OpenClaw does **not** load arbitrary bundle runtime modules in-process
|
||||
- Skills and hook-pack paths must stay inside the plugin root (boundary-checked)
|
||||
- Settings files are read with the same boundary checks
|
||||
- Supported stdio MCP servers may be launched as subprocesses
|
||||
|
||||
This makes bundles safer by default, but you should still treat third-party
|
||||
bundles as trusted content for the features they do expose.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Bundle is detected but capabilities do not run">
|
||||
Run `openclaw plugins inspect <id>`. If a capability is listed but marked as
|
||||
not wired, that is a product limit — not a broken install.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Claude command files do not appear">
|
||||
Make sure the bundle is enabled and the markdown files are inside a detected
|
||||
`commands/` or `skills/` root.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Claude settings do not apply">
|
||||
Only embedded Pi settings from `settings.json` are supported. OpenClaw does
|
||||
not treat bundle settings as raw config patches.
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Claude hooks do not execute">
|
||||
`hooks/hooks.json` is detect-only. If you need runnable hooks, use the
|
||||
OpenClaw hook-pack layout or ship a native plugin.
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Related
|
||||
|
||||
- [Install and Configure Plugins](/tools/plugin)
|
||||
- [Building Plugins](/plugins/building-plugins) — create a native plugin
|
||||
- [Plugin Manifest](/plugins/manifest) — native manifest schema
|
||||
489
openclaw/docs/plugins/codex-harness.md
Normal file
489
openclaw/docs/plugins/codex-harness.md
Normal file
|
|
@ -0,0 +1,489 @@
|
|||
---
|
||||
title: "Codex Harness"
|
||||
summary: "Run OpenClaw embedded agent turns through the bundled Codex app-server harness"
|
||||
read_when:
|
||||
- You want to use the bundled Codex app-server harness
|
||||
- You need Codex model refs and config examples
|
||||
- You want to disable PI fallback for Codex-only deployments
|
||||
---
|
||||
|
||||
# Codex Harness
|
||||
|
||||
The bundled `codex` plugin lets OpenClaw run embedded agent turns through the
|
||||
Codex app-server instead of the built-in PI harness.
|
||||
|
||||
Use this when you want Codex to own the low-level agent session: model
|
||||
discovery, native thread resume, native compaction, and app-server execution.
|
||||
OpenClaw still owns chat channels, session files, model selection, tools,
|
||||
approvals, media delivery, and the visible transcript mirror.
|
||||
|
||||
The harness is off by default. It is selected only when the `codex` plugin is
|
||||
enabled and the resolved model is a `codex/*` model, or when you explicitly
|
||||
force `embeddedHarness.runtime: "codex"` or `OPENCLAW_AGENT_RUNTIME=codex`.
|
||||
If you never configure `codex/*`, existing PI, OpenAI, Anthropic, Gemini, local,
|
||||
and custom-provider runs keep their current behavior.
|
||||
|
||||
## Pick the right model prefix
|
||||
|
||||
OpenClaw has separate routes for OpenAI and Codex-shaped access:
|
||||
|
||||
| Model ref | Runtime path | Use when |
|
||||
| ---------------------- | -------------------------------------------- | ----------------------------------------------------------------------- |
|
||||
| `openai/gpt-5.4` | OpenAI provider through OpenClaw/PI plumbing | You want direct OpenAI Platform API access with `OPENAI_API_KEY`. |
|
||||
| `openai-codex/gpt-5.4` | OpenAI Codex OAuth provider through PI | You want ChatGPT/Codex OAuth without the Codex app-server harness. |
|
||||
| `codex/gpt-5.4` | Bundled Codex provider plus Codex harness | You want native Codex app-server execution for the embedded agent turn. |
|
||||
|
||||
The Codex harness only claims `codex/*` model refs. Existing `openai/*`,
|
||||
`openai-codex/*`, Anthropic, Gemini, xAI, local, and custom provider refs keep
|
||||
their normal paths.
|
||||
|
||||
## Requirements
|
||||
|
||||
- OpenClaw with the bundled `codex` plugin available.
|
||||
- Codex app-server `0.118.0` or newer.
|
||||
- Codex auth available to the app-server process.
|
||||
|
||||
The plugin blocks older or unversioned app-server handshakes. That keeps
|
||||
OpenClaw on the protocol surface it has been tested against.
|
||||
|
||||
For live and Docker smoke tests, auth usually comes from `OPENAI_API_KEY`, plus
|
||||
optional Codex CLI files such as `~/.codex/auth.json` and
|
||||
`~/.codex/config.toml`. Use the same auth material your local Codex app-server
|
||||
uses.
|
||||
|
||||
## Minimal config
|
||||
|
||||
Use `codex/gpt-5.4`, enable the bundled plugin, and force the `codex` harness:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
agents: {
|
||||
defaults: {
|
||||
model: "codex/gpt-5.4",
|
||||
embeddedHarness: {
|
||||
runtime: "codex",
|
||||
fallback: "none",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
If your config uses `plugins.allow`, include `codex` there too:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
allow: ["codex"],
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Setting `agents.defaults.model` or an agent model to `codex/<model>` also
|
||||
auto-enables the bundled `codex` plugin. The explicit plugin entry is still
|
||||
useful in shared configs because it makes the deployment intent obvious.
|
||||
|
||||
## Add Codex without replacing other models
|
||||
|
||||
Keep `runtime: "auto"` when you want Codex for `codex/*` models and PI for
|
||||
everything else:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
agents: {
|
||||
defaults: {
|
||||
model: {
|
||||
primary: "codex/gpt-5.4",
|
||||
fallbacks: ["openai/gpt-5.4", "anthropic/claude-opus-4-6"],
|
||||
},
|
||||
models: {
|
||||
"codex/gpt-5.4": { alias: "codex" },
|
||||
"codex/gpt-5.4-mini": { alias: "codex-mini" },
|
||||
"openai/gpt-5.4": { alias: "gpt" },
|
||||
"anthropic/claude-opus-4-6": { alias: "opus" },
|
||||
},
|
||||
embeddedHarness: {
|
||||
runtime: "auto",
|
||||
fallback: "pi",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
With this shape:
|
||||
|
||||
- `/model codex` or `/model codex/gpt-5.4` uses the Codex app-server harness.
|
||||
- `/model gpt` or `/model openai/gpt-5.4` uses the OpenAI provider path.
|
||||
- `/model opus` uses the Anthropic provider path.
|
||||
- If a non-Codex model is selected, PI remains the compatibility harness.
|
||||
|
||||
## Codex-only deployments
|
||||
|
||||
Disable PI fallback when you need to prove that every embedded agent turn uses
|
||||
the Codex harness:
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
model: "codex/gpt-5.4",
|
||||
embeddedHarness: {
|
||||
runtime: "codex",
|
||||
fallback: "none",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Environment override:
|
||||
|
||||
```bash
|
||||
OPENCLAW_AGENT_RUNTIME=codex \
|
||||
OPENCLAW_AGENT_HARNESS_FALLBACK=none \
|
||||
openclaw gateway run
|
||||
```
|
||||
|
||||
With fallback disabled, OpenClaw fails early if the Codex plugin is disabled,
|
||||
the requested model is not a `codex/*` ref, the app-server is too old, or the
|
||||
app-server cannot start.
|
||||
|
||||
## Per-agent Codex
|
||||
|
||||
You can make one agent Codex-only while the default agent keeps normal
|
||||
auto-selection:
|
||||
|
||||
```json5
|
||||
{
|
||||
agents: {
|
||||
defaults: {
|
||||
embeddedHarness: {
|
||||
runtime: "auto",
|
||||
fallback: "pi",
|
||||
},
|
||||
},
|
||||
list: [
|
||||
{
|
||||
id: "main",
|
||||
default: true,
|
||||
model: "anthropic/claude-opus-4-6",
|
||||
},
|
||||
{
|
||||
id: "codex",
|
||||
name: "Codex",
|
||||
model: "codex/gpt-5.4",
|
||||
embeddedHarness: {
|
||||
runtime: "codex",
|
||||
fallback: "none",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Use normal session commands to switch agents and models. `/new` creates a fresh
|
||||
OpenClaw session and the Codex harness creates or resumes its sidecar app-server
|
||||
thread as needed. `/reset` clears the OpenClaw session binding for that thread.
|
||||
|
||||
## Model discovery
|
||||
|
||||
By default, the Codex plugin asks the app-server for available models. If
|
||||
discovery fails or times out, it uses the bundled fallback catalog:
|
||||
|
||||
- `codex/gpt-5.4`
|
||||
- `codex/gpt-5.4-mini`
|
||||
- `codex/gpt-5.2`
|
||||
|
||||
You can tune discovery under `plugins.entries.codex.config.discovery`:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
config: {
|
||||
discovery: {
|
||||
enabled: true,
|
||||
timeoutMs: 2500,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Disable discovery when you want startup to avoid probing Codex and stick to the
|
||||
fallback catalog:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
config: {
|
||||
discovery: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## App-server connection and policy
|
||||
|
||||
By default, the plugin starts Codex locally with:
|
||||
|
||||
```bash
|
||||
codex app-server --listen stdio://
|
||||
```
|
||||
|
||||
You can keep that default and only tune Codex native policy:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
config: {
|
||||
appServer: {
|
||||
approvalPolicy: "on-request",
|
||||
sandbox: "workspace-write",
|
||||
serviceTier: "priority",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
For an already-running app-server, use WebSocket transport:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
config: {
|
||||
appServer: {
|
||||
transport: "websocket",
|
||||
url: "ws://127.0.0.1:39175",
|
||||
authToken: "${CODEX_APP_SERVER_TOKEN}",
|
||||
requestTimeoutMs: 60000,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Supported `appServer` fields:
|
||||
|
||||
| Field | Default | Meaning |
|
||||
| ------------------- | ---------------------------------------- | ------------------------------------------------------------------------ |
|
||||
| `transport` | `"stdio"` | `"stdio"` spawns Codex; `"websocket"` connects to `url`. |
|
||||
| `command` | `"codex"` | Executable for stdio transport. |
|
||||
| `args` | `["app-server", "--listen", "stdio://"]` | Arguments for stdio transport. |
|
||||
| `url` | unset | WebSocket app-server URL. |
|
||||
| `authToken` | unset | Bearer token for WebSocket transport. |
|
||||
| `headers` | `{}` | Extra WebSocket headers. |
|
||||
| `requestTimeoutMs` | `60000` | Timeout for app-server control-plane calls. |
|
||||
| `approvalPolicy` | `"never"` | Native Codex approval policy sent to thread start/resume/turn. |
|
||||
| `sandbox` | `"workspace-write"` | Native Codex sandbox mode sent to thread start/resume. |
|
||||
| `approvalsReviewer` | `"user"` | Use `"guardian_subagent"` to let Codex guardian review native approvals. |
|
||||
| `serviceTier` | unset | Optional Codex service tier, for example `"priority"`. |
|
||||
|
||||
The older environment variables still work as fallbacks for local testing when
|
||||
the matching config field is unset:
|
||||
|
||||
- `OPENCLAW_CODEX_APP_SERVER_BIN`
|
||||
- `OPENCLAW_CODEX_APP_SERVER_ARGS`
|
||||
- `OPENCLAW_CODEX_APP_SERVER_APPROVAL_POLICY`
|
||||
- `OPENCLAW_CODEX_APP_SERVER_SANDBOX`
|
||||
- `OPENCLAW_CODEX_APP_SERVER_GUARDIAN=1`
|
||||
|
||||
Config is preferred for repeatable deployments.
|
||||
|
||||
## Common recipes
|
||||
|
||||
Local Codex with default stdio transport:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Codex-only harness validation, with PI fallback disabled:
|
||||
|
||||
```json5
|
||||
{
|
||||
embeddedHarness: {
|
||||
fallback: "none",
|
||||
},
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Guardian-reviewed Codex approvals:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
config: {
|
||||
appServer: {
|
||||
approvalPolicy: "on-request",
|
||||
approvalsReviewer: "guardian_subagent",
|
||||
sandbox: "workspace-write",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Remote app-server with explicit headers:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
codex: {
|
||||
enabled: true,
|
||||
config: {
|
||||
appServer: {
|
||||
transport: "websocket",
|
||||
url: "ws://gateway-host:39175",
|
||||
headers: {
|
||||
"X-OpenClaw-Agent": "main",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Model switching stays OpenClaw-controlled. When an OpenClaw session is attached
|
||||
to an existing Codex thread, the next turn sends the currently selected
|
||||
`codex/*` model, provider, approval policy, sandbox, and service tier to
|
||||
app-server again. Switching from `codex/gpt-5.4` to `codex/gpt-5.2` keeps the
|
||||
thread binding but asks Codex to continue with the newly selected model.
|
||||
|
||||
## Codex command
|
||||
|
||||
The bundled plugin registers `/codex` as an authorized slash command. It is
|
||||
generic and works on any channel that supports OpenClaw text commands.
|
||||
|
||||
Common forms:
|
||||
|
||||
- `/codex status` shows live app-server connectivity, models, account, rate limits, MCP servers, and skills.
|
||||
- `/codex models` lists live Codex app-server models.
|
||||
- `/codex threads [filter]` lists recent Codex threads.
|
||||
- `/codex resume <thread-id>` attaches the current OpenClaw session to an existing Codex thread.
|
||||
- `/codex compact` asks Codex app-server to compact the attached thread.
|
||||
- `/codex review` starts Codex native review for the attached thread.
|
||||
- `/codex account` shows account and rate-limit status.
|
||||
- `/codex mcp` lists Codex app-server MCP server status.
|
||||
- `/codex skills` lists Codex app-server skills.
|
||||
|
||||
`/codex resume` writes the same sidecar binding file that the harness uses for
|
||||
normal turns. On the next message, OpenClaw resumes that Codex thread, passes the
|
||||
currently selected OpenClaw `codex/*` model into app-server, and keeps extended
|
||||
history enabled.
|
||||
|
||||
The command surface requires Codex app-server `0.118.0` or newer. Individual
|
||||
control methods are reported as `unsupported by this Codex app-server` if a
|
||||
future or custom app-server does not expose that JSON-RPC method.
|
||||
|
||||
## Tools, media, and compaction
|
||||
|
||||
The Codex harness changes the low-level embedded agent executor only.
|
||||
|
||||
OpenClaw still builds the tool list and receives dynamic tool results from the
|
||||
harness. Text, images, video, music, TTS, approvals, and messaging-tool output
|
||||
continue through the normal OpenClaw delivery path.
|
||||
|
||||
When the selected model uses the Codex harness, native thread compaction is
|
||||
delegated to Codex app-server. OpenClaw keeps a transcript mirror for channel
|
||||
history, search, `/new`, `/reset`, and future model or harness switching. The
|
||||
mirror includes the user prompt, final assistant text, and lightweight Codex
|
||||
reasoning or plan records when the app-server emits them.
|
||||
|
||||
Media generation does not require PI. Image, video, music, PDF, TTS, and media
|
||||
understanding continue to use the matching provider/model settings such as
|
||||
`agents.defaults.imageGenerationModel`, `videoGenerationModel`, `pdfModel`, and
|
||||
`messages.tts`.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**Codex does not appear in `/model`:** enable `plugins.entries.codex.enabled`,
|
||||
set a `codex/*` model ref, or check whether `plugins.allow` excludes `codex`.
|
||||
|
||||
**OpenClaw falls back to PI:** set `embeddedHarness.fallback: "none"` or
|
||||
`OPENCLAW_AGENT_HARNESS_FALLBACK=none` while testing.
|
||||
|
||||
**The app-server is rejected:** upgrade Codex so the app-server handshake
|
||||
reports version `0.118.0` or newer.
|
||||
|
||||
**Model discovery is slow:** lower `plugins.entries.codex.config.discovery.timeoutMs`
|
||||
or disable discovery.
|
||||
|
||||
**WebSocket transport fails immediately:** check `appServer.url`, `authToken`,
|
||||
and that the remote app-server speaks the same Codex app-server protocol version.
|
||||
|
||||
**A non-Codex model uses PI:** that is expected. The Codex harness only claims
|
||||
`codex/*` model refs.
|
||||
|
||||
## Related
|
||||
|
||||
- [Agent Harness Plugins](/plugins/sdk-agent-harness)
|
||||
- [Model Providers](/concepts/model-providers)
|
||||
- [Configuration Reference](/gateway/configuration-reference)
|
||||
- [Testing](/help/testing#live-codex-app-server-harness-smoke)
|
||||
149
openclaw/docs/plugins/community.md
Normal file
149
openclaw/docs/plugins/community.md
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
---
|
||||
summary: "Community-maintained OpenClaw plugins: browse, install, and submit your own"
|
||||
read_when:
|
||||
- You want to find third-party OpenClaw plugins
|
||||
- You want to publish or list your own plugin
|
||||
title: "Community Plugins"
|
||||
---
|
||||
|
||||
# Community Plugins
|
||||
|
||||
Community plugins are third-party packages that extend OpenClaw with new
|
||||
channels, tools, providers, or other capabilities. They are built and maintained
|
||||
by the community, published on [ClawHub](/tools/clawhub) or npm, and
|
||||
installable with a single command.
|
||||
|
||||
ClawHub is the canonical discovery surface for community plugins. Do not open
|
||||
docs-only PRs just to add your plugin here for discoverability; publish it on
|
||||
ClawHub instead.
|
||||
|
||||
```bash
|
||||
openclaw plugins install <package-name>
|
||||
```
|
||||
|
||||
OpenClaw checks ClawHub first and falls back to npm automatically.
|
||||
|
||||
## Listed plugins
|
||||
|
||||
### Codex App Server Bridge
|
||||
|
||||
Independent OpenClaw bridge for Codex App Server conversations. Bind a chat to
|
||||
a Codex thread, talk to it with plain text, and control it with chat-native
|
||||
commands for resume, planning, review, model selection, compaction, and more.
|
||||
|
||||
- **npm:** `openclaw-codex-app-server`
|
||||
- **repo:** [github.com/pwrdrvr/openclaw-codex-app-server](https://github.com/pwrdrvr/openclaw-codex-app-server)
|
||||
|
||||
```bash
|
||||
openclaw plugins install openclaw-codex-app-server
|
||||
```
|
||||
|
||||
### DingTalk
|
||||
|
||||
Enterprise robot integration using Stream mode. Supports text, images, and
|
||||
file messages via any DingTalk client.
|
||||
|
||||
- **npm:** `@largezhou/ddingtalk`
|
||||
- **repo:** [github.com/largezhou/openclaw-dingtalk](https://github.com/largezhou/openclaw-dingtalk)
|
||||
|
||||
```bash
|
||||
openclaw plugins install @largezhou/ddingtalk
|
||||
```
|
||||
|
||||
### Lossless Claw (LCM)
|
||||
|
||||
Lossless Context Management plugin for OpenClaw. DAG-based conversation
|
||||
summarization with incremental compaction — preserves full context fidelity
|
||||
while reducing token usage.
|
||||
|
||||
- **npm:** `@martian-engineering/lossless-claw`
|
||||
- **repo:** [github.com/Martian-Engineering/lossless-claw](https://github.com/Martian-Engineering/lossless-claw)
|
||||
|
||||
```bash
|
||||
openclaw plugins install @martian-engineering/lossless-claw
|
||||
```
|
||||
|
||||
### Opik
|
||||
|
||||
Official plugin that exports agent traces to Opik. Monitor agent behavior,
|
||||
cost, tokens, errors, and more.
|
||||
|
||||
- **npm:** `@opik/opik-openclaw`
|
||||
- **repo:** [github.com/comet-ml/opik-openclaw](https://github.com/comet-ml/opik-openclaw)
|
||||
|
||||
```bash
|
||||
openclaw plugins install @opik/opik-openclaw
|
||||
```
|
||||
|
||||
### QQbot
|
||||
|
||||
Connect OpenClaw to QQ via the QQ Bot API. Supports private chats, group
|
||||
mentions, channel messages, and rich media including voice, images, videos,
|
||||
and files.
|
||||
|
||||
- **npm:** `@tencent-connect/openclaw-qqbot`
|
||||
- **repo:** [github.com/tencent-connect/openclaw-qqbot](https://github.com/tencent-connect/openclaw-qqbot)
|
||||
|
||||
```bash
|
||||
openclaw plugins install @tencent-connect/openclaw-qqbot
|
||||
```
|
||||
|
||||
### wecom
|
||||
|
||||
WeCom channel plugin for OpenClaw by the Tencent WeCom team. Powered by
|
||||
WeCom Bot WebSocket persistent connections, it supports direct messages & group
|
||||
chats, streaming replies, proactive messaging, image/file processing, Markdown
|
||||
formatting, built-in access control, and document/meeting/messaging skills.
|
||||
|
||||
- **npm:** `@wecom/wecom-openclaw-plugin`
|
||||
- **repo:** [github.com/WecomTeam/wecom-openclaw-plugin](https://github.com/WecomTeam/wecom-openclaw-plugin)
|
||||
|
||||
```bash
|
||||
openclaw plugins install @wecom/wecom-openclaw-plugin
|
||||
```
|
||||
|
||||
## Submit your plugin
|
||||
|
||||
We welcome community plugins that are useful, documented, and safe to operate.
|
||||
|
||||
<Steps>
|
||||
<Step title="Publish to ClawHub or npm">
|
||||
Your plugin must be installable via `openclaw plugins install \<package-name\>`.
|
||||
Publish to [ClawHub](/tools/clawhub) (preferred) or npm.
|
||||
See [Building Plugins](/plugins/building-plugins) for the full guide.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Host on GitHub">
|
||||
Source code must be in a public repository with setup docs and an issue
|
||||
tracker.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Use docs PRs only for source-doc changes">
|
||||
You do not need a docs PR just to make your plugin discoverable. Publish it
|
||||
on ClawHub instead.
|
||||
|
||||
Open a docs PR only when OpenClaw's source docs need an actual content
|
||||
change, such as correcting install guidance or adding cross-repo
|
||||
documentation that belongs in the main docs set.
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Quality bar
|
||||
|
||||
| Requirement | Why |
|
||||
| --------------------------- | --------------------------------------------- |
|
||||
| Published on ClawHub or npm | Users need `openclaw plugins install` to work |
|
||||
| Public GitHub repo | Source review, issue tracking, transparency |
|
||||
| Setup and usage docs | Users need to know how to configure it |
|
||||
| Active maintenance | Recent updates or responsive issue handling |
|
||||
|
||||
Low-effort wrappers, unclear ownership, or unmaintained packages may be declined.
|
||||
|
||||
## Related
|
||||
|
||||
- [Install and Configure Plugins](/tools/plugin) — how to install any plugin
|
||||
- [Building Plugins](/plugins/building-plugins) — create your own
|
||||
- [Plugin Manifest](/plugins/manifest) — manifest schema
|
||||
645
openclaw/docs/plugins/manifest.md
Normal file
645
openclaw/docs/plugins/manifest.md
Normal file
|
|
@ -0,0 +1,645 @@
|
|||
---
|
||||
summary: "Plugin manifest + JSON schema requirements (strict config validation)"
|
||||
read_when:
|
||||
- You are building an OpenClaw plugin
|
||||
- You need to ship a plugin config schema or debug plugin validation errors
|
||||
title: "Plugin Manifest"
|
||||
---
|
||||
|
||||
# Plugin manifest (openclaw.plugin.json)
|
||||
|
||||
This page is for the **native OpenClaw plugin manifest** only.
|
||||
|
||||
For compatible bundle layouts, see [Plugin bundles](/plugins/bundles).
|
||||
|
||||
Compatible bundle formats use different manifest files:
|
||||
|
||||
- Codex bundle: `.codex-plugin/plugin.json`
|
||||
- Claude bundle: `.claude-plugin/plugin.json` or the default Claude component
|
||||
layout without a manifest
|
||||
- Cursor bundle: `.cursor-plugin/plugin.json`
|
||||
|
||||
OpenClaw auto-detects those bundle layouts too, but they are not validated
|
||||
against the `openclaw.plugin.json` schema described here.
|
||||
|
||||
For compatible bundles, OpenClaw currently reads bundle metadata plus declared
|
||||
skill roots, Claude command roots, Claude bundle `settings.json` defaults,
|
||||
Claude bundle LSP defaults, and supported hook packs when the layout matches
|
||||
OpenClaw runtime expectations.
|
||||
|
||||
Every native OpenClaw plugin **must** ship a `openclaw.plugin.json` file in the
|
||||
**plugin root**. OpenClaw uses this manifest to validate configuration
|
||||
**without executing plugin code**. Missing or invalid manifests are treated as
|
||||
plugin errors and block config validation.
|
||||
|
||||
See the full plugin system guide: [Plugins](/tools/plugin).
|
||||
For the native capability model and current external-compatibility guidance:
|
||||
[Capability model](/plugins/architecture#public-capability-model).
|
||||
|
||||
## What this file does
|
||||
|
||||
`openclaw.plugin.json` is the metadata OpenClaw reads before it loads your
|
||||
plugin code.
|
||||
|
||||
Use it for:
|
||||
|
||||
- plugin identity
|
||||
- config validation
|
||||
- auth and onboarding metadata that should be available without booting plugin
|
||||
runtime
|
||||
- cheap activation hints that control-plane surfaces can inspect before runtime
|
||||
loads
|
||||
- cheap setup descriptors that setup/onboarding surfaces can inspect before
|
||||
runtime loads
|
||||
- alias and auto-enable metadata that should resolve before plugin runtime loads
|
||||
- shorthand model-family ownership metadata that should auto-activate the
|
||||
plugin before runtime loads
|
||||
- static capability ownership snapshots used for bundled compat wiring and
|
||||
contract coverage
|
||||
- cheap QA runner metadata that the shared `openclaw qa` host can inspect
|
||||
before plugin runtime loads
|
||||
- channel-specific config metadata that should merge into catalog and validation
|
||||
surfaces without loading runtime
|
||||
- config UI hints
|
||||
|
||||
Do not use it for:
|
||||
|
||||
- registering runtime behavior
|
||||
- declaring code entrypoints
|
||||
- npm install metadata
|
||||
|
||||
Those belong in your plugin code and `package.json`.
|
||||
|
||||
## Minimal example
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "voice-call",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Rich example
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "openrouter",
|
||||
"name": "OpenRouter",
|
||||
"description": "OpenRouter provider plugin",
|
||||
"version": "1.0.0",
|
||||
"providers": ["openrouter"],
|
||||
"modelSupport": {
|
||||
"modelPrefixes": ["router-"]
|
||||
},
|
||||
"providerEndpoints": [
|
||||
{
|
||||
"endpointClass": "xai-native",
|
||||
"hosts": ["api.x.ai"]
|
||||
}
|
||||
],
|
||||
"cliBackends": ["openrouter-cli"],
|
||||
"syntheticAuthRefs": ["openrouter-cli"],
|
||||
"providerAuthEnvVars": {
|
||||
"openrouter": ["OPENROUTER_API_KEY"]
|
||||
},
|
||||
"providerAuthAliases": {
|
||||
"openrouter-coding": "openrouter"
|
||||
},
|
||||
"channelEnvVars": {
|
||||
"openrouter-chatops": ["OPENROUTER_CHATOPS_TOKEN"]
|
||||
},
|
||||
"providerAuthChoices": [
|
||||
{
|
||||
"provider": "openrouter",
|
||||
"method": "api-key",
|
||||
"choiceId": "openrouter-api-key",
|
||||
"choiceLabel": "OpenRouter API key",
|
||||
"groupId": "openrouter",
|
||||
"groupLabel": "OpenRouter",
|
||||
"optionKey": "openrouterApiKey",
|
||||
"cliFlag": "--openrouter-api-key",
|
||||
"cliOption": "--openrouter-api-key <key>",
|
||||
"cliDescription": "OpenRouter API key",
|
||||
"onboardingScopes": ["text-inference"]
|
||||
}
|
||||
],
|
||||
"uiHints": {
|
||||
"apiKey": {
|
||||
"label": "API key",
|
||||
"placeholder": "sk-or-v1-...",
|
||||
"sensitive": true
|
||||
}
|
||||
},
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"apiKey": {
|
||||
"type": "string"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Top-level field reference
|
||||
|
||||
| Field | Required | Type | What it means |
|
||||
| ----------------------------------- | -------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| `id` | Yes | `string` | Canonical plugin id. This is the id used in `plugins.entries.<id>`. |
|
||||
| `configSchema` | Yes | `object` | Inline JSON Schema for this plugin's config. |
|
||||
| `enabledByDefault` | No | `true` | Marks a bundled plugin as enabled by default. Omit it, or set any non-`true` value, to leave the plugin disabled by default. |
|
||||
| `legacyPluginIds` | No | `string[]` | Legacy ids that normalize to this canonical plugin id. |
|
||||
| `autoEnableWhenConfiguredProviders` | No | `string[]` | Provider ids that should auto-enable this plugin when auth, config, or model refs mention them. |
|
||||
| `kind` | No | `"memory"` \| `"context-engine"` | Declares an exclusive plugin kind used by `plugins.slots.*`. |
|
||||
| `channels` | No | `string[]` | Channel ids owned by this plugin. Used for discovery and config validation. |
|
||||
| `providers` | No | `string[]` | Provider ids owned by this plugin. |
|
||||
| `modelSupport` | No | `object` | Manifest-owned shorthand model-family metadata used to auto-load the plugin before runtime. |
|
||||
| `providerEndpoints` | No | `object[]` | Manifest-owned endpoint host/baseUrl metadata for provider routes that core must classify before provider runtime loads. |
|
||||
| `cliBackends` | No | `string[]` | CLI inference backend ids owned by this plugin. Used for startup auto-activation from explicit config refs. |
|
||||
| `syntheticAuthRefs` | No | `string[]` | Provider or CLI backend refs whose plugin-owned synthetic auth hook should be probed during cold model discovery before runtime loads. |
|
||||
| `nonSecretAuthMarkers` | No | `string[]` | Bundled-plugin-owned placeholder API key values that represent non-secret local, OAuth, or ambient credential state. |
|
||||
| `commandAliases` | No | `object[]` | Command names owned by this plugin that should produce plugin-aware config and CLI diagnostics before runtime loads. |
|
||||
| `providerAuthEnvVars` | No | `Record<string, string[]>` | Cheap provider-auth env metadata that OpenClaw can inspect without loading plugin code. |
|
||||
| `providerAuthAliases` | No | `Record<string, string>` | Provider ids that should reuse another provider id for auth lookup, for example a coding provider that shares the base provider API key and auth profiles. |
|
||||
| `channelEnvVars` | No | `Record<string, string[]>` | Cheap channel env metadata that OpenClaw can inspect without loading plugin code. Use this for env-driven channel setup or auth surfaces that generic startup/config helpers should see. |
|
||||
| `providerAuthChoices` | No | `object[]` | Cheap auth-choice metadata for onboarding pickers, preferred-provider resolution, and simple CLI flag wiring. |
|
||||
| `activation` | No | `object` | Cheap activation hints for provider, command, channel, route, and capability-triggered loading. Metadata only; plugin runtime still owns actual behavior. |
|
||||
| `setup` | No | `object` | Cheap setup/onboarding descriptors that discovery and setup surfaces can inspect without loading plugin runtime. |
|
||||
| `qaRunners` | No | `object[]` | Cheap QA runner descriptors used by the shared `openclaw qa` host before plugin runtime loads. |
|
||||
| `contracts` | No | `object` | Static bundled capability snapshot for speech, realtime transcription, realtime voice, media-understanding, image-generation, music-generation, video-generation, web-fetch, web search, and tool ownership. |
|
||||
| `channelConfigs` | No | `Record<string, object>` | Manifest-owned channel config metadata merged into discovery and validation surfaces before runtime loads. |
|
||||
| `skills` | No | `string[]` | Skill directories to load, relative to the plugin root. |
|
||||
| `name` | No | `string` | Human-readable plugin name. |
|
||||
| `description` | No | `string` | Short summary shown in plugin surfaces. |
|
||||
| `version` | No | `string` | Informational plugin version. |
|
||||
| `uiHints` | No | `Record<string, object>` | UI labels, placeholders, and sensitivity hints for config fields. |
|
||||
|
||||
## providerAuthChoices reference
|
||||
|
||||
Each `providerAuthChoices` entry describes one onboarding or auth choice.
|
||||
OpenClaw reads this before provider runtime loads.
|
||||
|
||||
| Field | Required | Type | What it means |
|
||||
| --------------------- | -------- | ----------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `provider` | Yes | `string` | Provider id this choice belongs to. |
|
||||
| `method` | Yes | `string` | Auth method id to dispatch to. |
|
||||
| `choiceId` | Yes | `string` | Stable auth-choice id used by onboarding and CLI flows. |
|
||||
| `choiceLabel` | No | `string` | User-facing label. If omitted, OpenClaw falls back to `choiceId`. |
|
||||
| `choiceHint` | No | `string` | Short helper text for the picker. |
|
||||
| `assistantPriority` | No | `number` | Lower values sort earlier in assistant-driven interactive pickers. |
|
||||
| `assistantVisibility` | No | `"visible"` \| `"manual-only"` | Hide the choice from assistant pickers while still allowing manual CLI selection. |
|
||||
| `deprecatedChoiceIds` | No | `string[]` | Legacy choice ids that should redirect users to this replacement choice. |
|
||||
| `groupId` | No | `string` | Optional group id for grouping related choices. |
|
||||
| `groupLabel` | No | `string` | User-facing label for that group. |
|
||||
| `groupHint` | No | `string` | Short helper text for the group. |
|
||||
| `optionKey` | No | `string` | Internal option key for simple one-flag auth flows. |
|
||||
| `cliFlag` | No | `string` | CLI flag name, such as `--openrouter-api-key`. |
|
||||
| `cliOption` | No | `string` | Full CLI option shape, such as `--openrouter-api-key <key>`. |
|
||||
| `cliDescription` | No | `string` | Description used in CLI help. |
|
||||
| `onboardingScopes` | No | `Array<"text-inference" \| "image-generation">` | Which onboarding surfaces this choice should appear in. If omitted, it defaults to `["text-inference"]`. |
|
||||
|
||||
## commandAliases reference
|
||||
|
||||
Use `commandAliases` when a plugin owns a runtime command name that users may
|
||||
mistakenly put in `plugins.allow` or try to run as a root CLI command. OpenClaw
|
||||
uses this metadata for diagnostics without importing plugin runtime code.
|
||||
|
||||
```json
|
||||
{
|
||||
"commandAliases": [
|
||||
{
|
||||
"name": "dreaming",
|
||||
"kind": "runtime-slash",
|
||||
"cliCommand": "memory"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | Type | What it means |
|
||||
| ------------ | -------- | ----------------- | ----------------------------------------------------------------------- |
|
||||
| `name` | Yes | `string` | Command name that belongs to this plugin. |
|
||||
| `kind` | No | `"runtime-slash"` | Marks the alias as a chat slash command rather than a root CLI command. |
|
||||
| `cliCommand` | No | `string` | Related root CLI command to suggest for CLI operations, if one exists. |
|
||||
|
||||
## activation reference
|
||||
|
||||
Use `activation` when the plugin can cheaply declare which control-plane events
|
||||
should activate it later.
|
||||
|
||||
## qaRunners reference
|
||||
|
||||
Use `qaRunners` when a plugin contributes one or more transport runners beneath
|
||||
the shared `openclaw qa` root. Keep this metadata cheap and static; the plugin
|
||||
runtime still owns actual CLI registration through a lightweight
|
||||
`runtime-api.ts` surface that exports `qaRunnerCliRegistrations`.
|
||||
|
||||
```json
|
||||
{
|
||||
"qaRunners": [
|
||||
{
|
||||
"commandName": "matrix",
|
||||
"description": "Run the Docker-backed Matrix live QA lane against a disposable homeserver"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | Type | What it means |
|
||||
| ------------- | -------- | -------- | ------------------------------------------------------------------ |
|
||||
| `commandName` | Yes | `string` | Subcommand mounted beneath `openclaw qa`, for example `matrix`. |
|
||||
| `description` | No | `string` | Fallback help text used when the shared host needs a stub command. |
|
||||
|
||||
This block is metadata only. It does not register runtime behavior, and it does
|
||||
not replace `register(...)`, `setupEntry`, or other runtime/plugin entrypoints.
|
||||
Current consumers use it as a narrowing hint before broader plugin loading, so
|
||||
missing activation metadata usually only costs performance; it should not
|
||||
change correctness while legacy manifest ownership fallbacks still exist.
|
||||
|
||||
```json
|
||||
{
|
||||
"activation": {
|
||||
"onProviders": ["openai"],
|
||||
"onCommands": ["models"],
|
||||
"onChannels": ["web"],
|
||||
"onRoutes": ["gateway-webhook"],
|
||||
"onCapabilities": ["provider", "tool"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Required | Type | What it means |
|
||||
| ---------------- | -------- | ---------------------------------------------------- | ----------------------------------------------------------------- |
|
||||
| `onProviders` | No | `string[]` | Provider ids that should activate this plugin when requested. |
|
||||
| `onCommands` | No | `string[]` | Command ids that should activate this plugin. |
|
||||
| `onChannels` | No | `string[]` | Channel ids that should activate this plugin. |
|
||||
| `onRoutes` | No | `string[]` | Route kinds that should activate this plugin. |
|
||||
| `onCapabilities` | No | `Array<"provider" \| "channel" \| "tool" \| "hook">` | Broad capability hints used by control-plane activation planning. |
|
||||
|
||||
Current live consumers:
|
||||
|
||||
- command-triggered CLI planning falls back to legacy
|
||||
`commandAliases[].cliCommand` or `commandAliases[].name`
|
||||
- channel-triggered setup/channel planning falls back to legacy `channels[]`
|
||||
ownership when explicit channel activation metadata is missing
|
||||
- provider-triggered setup/runtime planning falls back to legacy
|
||||
`providers[]` and top-level `cliBackends[]` ownership when explicit provider
|
||||
activation metadata is missing
|
||||
|
||||
## setup reference
|
||||
|
||||
Use `setup` when setup and onboarding surfaces need cheap plugin-owned metadata
|
||||
before runtime loads.
|
||||
|
||||
```json
|
||||
{
|
||||
"setup": {
|
||||
"providers": [
|
||||
{
|
||||
"id": "openai",
|
||||
"authMethods": ["api-key"],
|
||||
"envVars": ["OPENAI_API_KEY"]
|
||||
}
|
||||
],
|
||||
"cliBackends": ["openai-cli"],
|
||||
"configMigrations": ["legacy-openai-auth"],
|
||||
"requiresRuntime": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Top-level `cliBackends` stays valid and continues to describe CLI inference
|
||||
backends. `setup.cliBackends` is the setup-specific descriptor surface for
|
||||
control-plane/setup flows that should stay metadata-only.
|
||||
|
||||
When present, `setup.providers` and `setup.cliBackends` are the preferred
|
||||
descriptor-first lookup surface for setup discovery. If the descriptor only
|
||||
narrows the candidate plugin and setup still needs richer setup-time runtime
|
||||
hooks, set `requiresRuntime: true` and keep `setup-api` in place as the
|
||||
fallback execution path.
|
||||
|
||||
Because setup lookup can execute plugin-owned `setup-api` code, normalized
|
||||
`setup.providers[].id` and `setup.cliBackends[]` values must stay unique across
|
||||
discovered plugins. Ambiguous ownership fails closed instead of picking a
|
||||
winner from discovery order.
|
||||
|
||||
### setup.providers reference
|
||||
|
||||
| Field | Required | Type | What it means |
|
||||
| ------------- | -------- | ---------- | ------------------------------------------------------------------------------------ |
|
||||
| `id` | Yes | `string` | Provider id exposed during setup or onboarding. Keep normalized ids globally unique. |
|
||||
| `authMethods` | No | `string[]` | Setup/auth method ids this provider supports without loading full runtime. |
|
||||
| `envVars` | No | `string[]` | Env vars that generic setup/status surfaces can check before plugin runtime loads. |
|
||||
|
||||
### setup fields
|
||||
|
||||
| Field | Required | Type | What it means |
|
||||
| ------------------ | -------- | ---------- | --------------------------------------------------------------------------------------------------- |
|
||||
| `providers` | No | `object[]` | Provider setup descriptors exposed during setup and onboarding. |
|
||||
| `cliBackends` | No | `string[]` | Setup-time backend ids used for descriptor-first setup lookup. Keep normalized ids globally unique. |
|
||||
| `configMigrations` | No | `string[]` | Config migration ids owned by this plugin's setup surface. |
|
||||
| `requiresRuntime` | No | `boolean` | Whether setup still needs `setup-api` execution after descriptor lookup. |
|
||||
|
||||
## uiHints reference
|
||||
|
||||
`uiHints` is a map from config field names to small rendering hints.
|
||||
|
||||
```json
|
||||
{
|
||||
"uiHints": {
|
||||
"apiKey": {
|
||||
"label": "API key",
|
||||
"help": "Used for OpenRouter requests",
|
||||
"placeholder": "sk-or-v1-...",
|
||||
"sensitive": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each field hint can include:
|
||||
|
||||
| Field | Type | What it means |
|
||||
| ------------- | ---------- | --------------------------------------- |
|
||||
| `label` | `string` | User-facing field label. |
|
||||
| `help` | `string` | Short helper text. |
|
||||
| `tags` | `string[]` | Optional UI tags. |
|
||||
| `advanced` | `boolean` | Marks the field as advanced. |
|
||||
| `sensitive` | `boolean` | Marks the field as secret or sensitive. |
|
||||
| `placeholder` | `string` | Placeholder text for form inputs. |
|
||||
|
||||
## contracts reference
|
||||
|
||||
Use `contracts` only for static capability ownership metadata that OpenClaw can
|
||||
read without importing the plugin runtime.
|
||||
|
||||
```json
|
||||
{
|
||||
"contracts": {
|
||||
"speechProviders": ["openai"],
|
||||
"realtimeTranscriptionProviders": ["openai"],
|
||||
"realtimeVoiceProviders": ["openai"],
|
||||
"mediaUnderstandingProviders": ["openai", "openai-codex"],
|
||||
"imageGenerationProviders": ["openai"],
|
||||
"videoGenerationProviders": ["qwen"],
|
||||
"webFetchProviders": ["firecrawl"],
|
||||
"webSearchProviders": ["gemini"],
|
||||
"tools": ["firecrawl_search", "firecrawl_scrape"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each list is optional:
|
||||
|
||||
| Field | Type | What it means |
|
||||
| -------------------------------- | ---------- | -------------------------------------------------------------- |
|
||||
| `speechProviders` | `string[]` | Speech provider ids this plugin owns. |
|
||||
| `realtimeTranscriptionProviders` | `string[]` | Realtime-transcription provider ids this plugin owns. |
|
||||
| `realtimeVoiceProviders` | `string[]` | Realtime-voice provider ids this plugin owns. |
|
||||
| `mediaUnderstandingProviders` | `string[]` | Media-understanding provider ids this plugin owns. |
|
||||
| `imageGenerationProviders` | `string[]` | Image-generation provider ids this plugin owns. |
|
||||
| `videoGenerationProviders` | `string[]` | Video-generation provider ids this plugin owns. |
|
||||
| `webFetchProviders` | `string[]` | Web-fetch provider ids this plugin owns. |
|
||||
| `webSearchProviders` | `string[]` | Web-search provider ids this plugin owns. |
|
||||
| `tools` | `string[]` | Agent tool names this plugin owns for bundled contract checks. |
|
||||
|
||||
## channelConfigs reference
|
||||
|
||||
Use `channelConfigs` when a channel plugin needs cheap config metadata before
|
||||
runtime loads.
|
||||
|
||||
```json
|
||||
{
|
||||
"channelConfigs": {
|
||||
"matrix": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"homeserverUrl": { "type": "string" }
|
||||
}
|
||||
},
|
||||
"uiHints": {
|
||||
"homeserverUrl": {
|
||||
"label": "Homeserver URL",
|
||||
"placeholder": "https://matrix.example.com"
|
||||
}
|
||||
},
|
||||
"label": "Matrix",
|
||||
"description": "Matrix homeserver connection",
|
||||
"preferOver": ["matrix-legacy"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each channel entry can include:
|
||||
|
||||
| Field | Type | What it means |
|
||||
| ------------- | ------------------------ | ----------------------------------------------------------------------------------------- |
|
||||
| `schema` | `object` | JSON Schema for `channels.<id>`. Required for each declared channel config entry. |
|
||||
| `uiHints` | `Record<string, object>` | Optional UI labels/placeholders/sensitive hints for that channel config section. |
|
||||
| `label` | `string` | Channel label merged into picker and inspect surfaces when runtime metadata is not ready. |
|
||||
| `description` | `string` | Short channel description for inspect and catalog surfaces. |
|
||||
| `preferOver` | `string[]` | Legacy or lower-priority plugin ids this channel should outrank in selection surfaces. |
|
||||
|
||||
## modelSupport reference
|
||||
|
||||
Use `modelSupport` when OpenClaw should infer your provider plugin from
|
||||
shorthand model ids like `gpt-5.4` or `claude-sonnet-4.6` before plugin runtime
|
||||
loads.
|
||||
|
||||
```json
|
||||
{
|
||||
"modelSupport": {
|
||||
"modelPrefixes": ["gpt-", "o1", "o3", "o4"],
|
||||
"modelPatterns": ["^computer-use-preview"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
OpenClaw applies this precedence:
|
||||
|
||||
- explicit `provider/model` refs use the owning `providers` manifest metadata
|
||||
- `modelPatterns` beat `modelPrefixes`
|
||||
- if one non-bundled plugin and one bundled plugin both match, the non-bundled
|
||||
plugin wins
|
||||
- remaining ambiguity is ignored until the user or config specifies a provider
|
||||
|
||||
Fields:
|
||||
|
||||
| Field | Type | What it means |
|
||||
| --------------- | ---------- | ------------------------------------------------------------------------------- |
|
||||
| `modelPrefixes` | `string[]` | Prefixes matched with `startsWith` against shorthand model ids. |
|
||||
| `modelPatterns` | `string[]` | Regex sources matched against shorthand model ids after profile suffix removal. |
|
||||
|
||||
Legacy top-level capability keys are deprecated. Use `openclaw doctor --fix` to
|
||||
move `speechProviders`, `realtimeTranscriptionProviders`,
|
||||
`realtimeVoiceProviders`, `mediaUnderstandingProviders`,
|
||||
`imageGenerationProviders`, `videoGenerationProviders`,
|
||||
`webFetchProviders`, and `webSearchProviders` under `contracts`; normal
|
||||
manifest loading no longer treats those top-level fields as capability
|
||||
ownership.
|
||||
|
||||
## Manifest versus package.json
|
||||
|
||||
The two files serve different jobs:
|
||||
|
||||
| File | Use it for |
|
||||
| ---------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `openclaw.plugin.json` | Discovery, config validation, auth-choice metadata, and UI hints that must exist before plugin code runs |
|
||||
| `package.json` | npm metadata, dependency installation, and the `openclaw` block used for entrypoints, install gating, setup, or catalog metadata |
|
||||
|
||||
If you are unsure where a piece of metadata belongs, use this rule:
|
||||
|
||||
- if OpenClaw must know it before loading plugin code, put it in `openclaw.plugin.json`
|
||||
- if it is about packaging, entry files, or npm install behavior, put it in `package.json`
|
||||
|
||||
### package.json fields that affect discovery
|
||||
|
||||
Some pre-runtime plugin metadata intentionally lives in `package.json` under the
|
||||
`openclaw` block instead of `openclaw.plugin.json`.
|
||||
|
||||
Important examples:
|
||||
|
||||
| Field | What it means |
|
||||
| ----------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `openclaw.extensions` | Declares native plugin entrypoints. |
|
||||
| `openclaw.setupEntry` | Lightweight setup-only entrypoint used during onboarding and deferred channel startup. |
|
||||
| `openclaw.channel` | Cheap channel catalog metadata like labels, docs paths, aliases, and selection copy. |
|
||||
| `openclaw.channel.configuredState` | Lightweight configured-state checker metadata that can answer "does env-only setup already exist?" without loading the full channel runtime. |
|
||||
| `openclaw.channel.persistedAuthState` | Lightweight persisted-auth checker metadata that can answer "is anything already signed in?" without loading the full channel runtime. |
|
||||
| `openclaw.install.npmSpec` / `openclaw.install.localPath` | Install/update hints for bundled and externally published plugins. |
|
||||
| `openclaw.install.defaultChoice` | Preferred install path when multiple install sources are available. |
|
||||
| `openclaw.install.minHostVersion` | Minimum supported OpenClaw host version, using a semver floor like `>=2026.3.22`. |
|
||||
| `openclaw.install.allowInvalidConfigRecovery` | Allows a narrow bundled-plugin reinstall recovery path when config is invalid. |
|
||||
| `openclaw.startup.deferConfiguredChannelFullLoadUntilAfterListen` | Lets setup-only channel surfaces load before the full channel plugin during startup. |
|
||||
|
||||
`openclaw.install.minHostVersion` is enforced during install and manifest
|
||||
registry loading. Invalid values are rejected; newer-but-valid values skip the
|
||||
plugin on older hosts.
|
||||
|
||||
`openclaw.install.allowInvalidConfigRecovery` is intentionally narrow. It does
|
||||
not make arbitrary broken configs installable. Today it only allows install
|
||||
flows to recover from specific stale bundled-plugin upgrade failures, such as a
|
||||
missing bundled plugin path or a stale `channels.<id>` entry for that same
|
||||
bundled plugin. Unrelated config errors still block install and send operators
|
||||
to `openclaw doctor --fix`.
|
||||
|
||||
`openclaw.channel.persistedAuthState` is package metadata for a tiny checker
|
||||
module:
|
||||
|
||||
```json
|
||||
{
|
||||
"openclaw": {
|
||||
"channel": {
|
||||
"id": "whatsapp",
|
||||
"persistedAuthState": {
|
||||
"specifier": "./auth-presence",
|
||||
"exportName": "hasAnyWhatsAppAuth"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use it when setup, doctor, or configured-state flows need a cheap yes/no auth
|
||||
probe before the full channel plugin loads. The target export should be a small
|
||||
function that reads persisted state only; do not route it through the full
|
||||
channel runtime barrel.
|
||||
|
||||
`openclaw.channel.configuredState` follows the same shape for cheap env-only
|
||||
configured checks:
|
||||
|
||||
```json
|
||||
{
|
||||
"openclaw": {
|
||||
"channel": {
|
||||
"id": "telegram",
|
||||
"configuredState": {
|
||||
"specifier": "./configured-state",
|
||||
"exportName": "hasTelegramConfiguredState"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Use it when a channel can answer configured-state from env or other tiny
|
||||
non-runtime inputs. If the check needs full config resolution or the real
|
||||
channel runtime, keep that logic in the plugin `config.hasConfiguredState`
|
||||
hook instead.
|
||||
|
||||
## JSON Schema requirements
|
||||
|
||||
- **Every plugin must ship a JSON Schema**, even if it accepts no config.
|
||||
- An empty schema is acceptable (for example, `{ "type": "object", "additionalProperties": false }`).
|
||||
- Schemas are validated at config read/write time, not at runtime.
|
||||
|
||||
## Validation behavior
|
||||
|
||||
- Unknown `channels.*` keys are **errors**, unless the channel id is declared by
|
||||
a plugin manifest.
|
||||
- `plugins.entries.<id>`, `plugins.allow`, `plugins.deny`, and `plugins.slots.*`
|
||||
must reference **discoverable** plugin ids. Unknown ids are **errors**.
|
||||
- If a plugin is installed but has a broken or missing manifest or schema,
|
||||
validation fails and Doctor reports the plugin error.
|
||||
- If plugin config exists but the plugin is **disabled**, the config is kept and
|
||||
a **warning** is surfaced in Doctor + logs.
|
||||
|
||||
See [Configuration reference](/gateway/configuration) for the full `plugins.*` schema.
|
||||
|
||||
## Notes
|
||||
|
||||
- The manifest is **required for native OpenClaw plugins**, including local filesystem loads.
|
||||
- Runtime still loads the plugin module separately; the manifest is only for
|
||||
discovery + validation.
|
||||
- Native manifests are parsed with JSON5, so comments, trailing commas, and
|
||||
unquoted keys are accepted as long as the final value is still an object.
|
||||
- Only documented manifest fields are read by the manifest loader. Avoid adding
|
||||
custom top-level keys here.
|
||||
- `providerAuthEnvVars` is the cheap metadata path for auth probes, env-marker
|
||||
validation, and similar provider-auth surfaces that should not boot plugin
|
||||
runtime just to inspect env names.
|
||||
- `providerAuthAliases` lets provider variants reuse another provider's auth
|
||||
env vars, auth profiles, config-backed auth, and API-key onboarding choice
|
||||
without hardcoding that relationship in core.
|
||||
- `providerEndpoints` lets provider plugins own simple endpoint host/baseUrl
|
||||
matching metadata. Use it only for endpoint classes core already supports;
|
||||
the plugin still owns runtime behavior.
|
||||
- `syntheticAuthRefs` is the cheap metadata path for provider-owned synthetic
|
||||
auth hooks that must be visible to cold model discovery before the runtime
|
||||
registry exists. Only list refs whose runtime provider or CLI backend actually
|
||||
implements `resolveSyntheticAuth`.
|
||||
- `nonSecretAuthMarkers` is the cheap metadata path for bundled plugin-owned
|
||||
placeholder API keys such as local, OAuth, or ambient credential markers.
|
||||
Core treats these as non-secrets for auth display and secret audits without
|
||||
hardcoding the owning provider.
|
||||
- `channelEnvVars` is the cheap metadata path for shell-env fallback, setup
|
||||
prompts, and similar channel surfaces that should not boot plugin runtime
|
||||
just to inspect env names.
|
||||
- `providerAuthChoices` is the cheap metadata path for auth-choice pickers,
|
||||
`--auth-choice` resolution, preferred-provider mapping, and simple onboarding
|
||||
CLI flag registration before provider runtime loads. For runtime wizard
|
||||
metadata that requires provider code, see
|
||||
[Provider runtime hooks](/plugins/architecture#provider-runtime-hooks).
|
||||
- Exclusive plugin kinds are selected through `plugins.slots.*`.
|
||||
- `kind: "memory"` is selected by `plugins.slots.memory`.
|
||||
- `kind: "context-engine"` is selected by `plugins.slots.contextEngine`
|
||||
(default: built-in `legacy`).
|
||||
- `channels`, `providers`, `cliBackends`, and `skills` can be omitted when a
|
||||
plugin does not need them.
|
||||
- If your plugin depends on native modules, document the build steps and any
|
||||
package-manager allowlist requirements (for example, pnpm `allow-build-scripts`
|
||||
- `pnpm rebuild <package>`).
|
||||
|
||||
## Related
|
||||
|
||||
- [Building Plugins](/plugins/building-plugins) — getting started with plugins
|
||||
- [Plugin Architecture](/plugins/architecture) — internal architecture
|
||||
- [SDK Overview](/plugins/sdk-overview) — Plugin SDK reference
|
||||
420
openclaw/docs/plugins/memory-wiki.md
Normal file
420
openclaw/docs/plugins/memory-wiki.md
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
---
|
||||
summary: "memory-wiki: compiled knowledge vault with provenance, claims, dashboards, and bridge mode"
|
||||
read_when:
|
||||
- You want persistent knowledge beyond plain MEMORY.md notes
|
||||
- You are configuring the bundled memory-wiki plugin
|
||||
- You want to understand wiki_search, wiki_get, or bridge mode
|
||||
title: "Memory Wiki"
|
||||
---
|
||||
|
||||
# Memory Wiki
|
||||
|
||||
`memory-wiki` is a bundled plugin that turns durable memory into a compiled
|
||||
knowledge vault.
|
||||
|
||||
It does **not** replace the active memory plugin. The active memory plugin still
|
||||
owns recall, promotion, indexing, and dreaming. `memory-wiki` sits beside it
|
||||
and compiles durable knowledge into a navigable wiki with deterministic pages,
|
||||
structured claims, provenance, dashboards, and machine-readable digests.
|
||||
|
||||
Use it when you want memory to behave more like a maintained knowledge layer and
|
||||
less like a pile of Markdown files.
|
||||
|
||||
## What it adds
|
||||
|
||||
- A dedicated wiki vault with deterministic page layout
|
||||
- Structured claim and evidence metadata, not just prose
|
||||
- Page-level provenance, confidence, contradictions, and open questions
|
||||
- Compiled digests for agent/runtime consumers
|
||||
- Wiki-native search/get/apply/lint tools
|
||||
- Optional bridge mode that imports public artifacts from the active memory plugin
|
||||
- Optional Obsidian-friendly render mode and CLI integration
|
||||
|
||||
## How it fits with memory
|
||||
|
||||
Think of the split like this:
|
||||
|
||||
| Layer | Owns |
|
||||
| ------------------------------------------------------- | ------------------------------------------------------------------------------------------ |
|
||||
| Active memory plugin (`memory-core`, QMD, Honcho, etc.) | Recall, semantic search, promotion, dreaming, memory runtime |
|
||||
| `memory-wiki` | Compiled wiki pages, provenance-rich syntheses, dashboards, wiki-specific search/get/apply |
|
||||
|
||||
If the active memory plugin exposes shared recall artifacts, OpenClaw can search
|
||||
both layers in one pass with `memory_search corpus=all`.
|
||||
|
||||
When you need wiki-specific ranking, provenance, or direct page access, use the
|
||||
wiki-native tools instead.
|
||||
|
||||
## Recommended hybrid pattern
|
||||
|
||||
A strong default for local-first setups is:
|
||||
|
||||
- QMD as the active memory backend for recall and broad semantic search
|
||||
- `memory-wiki` in `bridge` mode for durable synthesized knowledge pages
|
||||
|
||||
That split works well because each layer stays focused:
|
||||
|
||||
- QMD keeps raw notes, session exports, and extra collections searchable
|
||||
- `memory-wiki` compiles stable entities, claims, dashboards, and source pages
|
||||
|
||||
Practical rule:
|
||||
|
||||
- use `memory_search` when you want one broad recall pass across memory
|
||||
- use `wiki_search` and `wiki_get` when you want provenance-aware wiki results
|
||||
- use `memory_search corpus=all` when you want shared search to span both layers
|
||||
|
||||
If bridge mode reports zero exported artifacts, the active memory plugin is not
|
||||
currently exposing public bridge inputs yet. Run `openclaw wiki doctor` first,
|
||||
then confirm the active memory plugin supports public artifacts.
|
||||
|
||||
## Vault modes
|
||||
|
||||
`memory-wiki` supports three vault modes:
|
||||
|
||||
### `isolated`
|
||||
|
||||
Own vault, own sources, no dependency on `memory-core`.
|
||||
|
||||
Use this when you want the wiki to be its own curated knowledge store.
|
||||
|
||||
### `bridge`
|
||||
|
||||
Reads public memory artifacts and memory events from the active memory plugin
|
||||
through public plugin SDK seams.
|
||||
|
||||
Use this when you want the wiki to compile and organize the memory plugin's
|
||||
exported artifacts without reaching into private plugin internals.
|
||||
|
||||
Bridge mode can index:
|
||||
|
||||
- exported memory artifacts
|
||||
- dream reports
|
||||
- daily notes
|
||||
- memory root files
|
||||
- memory event logs
|
||||
|
||||
### `unsafe-local`
|
||||
|
||||
Explicit same-machine escape hatch for local private paths.
|
||||
|
||||
This mode is intentionally experimental and non-portable. Use it only when you
|
||||
understand the trust boundary and specifically need local filesystem access that
|
||||
bridge mode cannot provide.
|
||||
|
||||
## Vault layout
|
||||
|
||||
The plugin initializes a vault like this:
|
||||
|
||||
```text
|
||||
<vault>/
|
||||
AGENTS.md
|
||||
WIKI.md
|
||||
index.md
|
||||
inbox.md
|
||||
entities/
|
||||
concepts/
|
||||
syntheses/
|
||||
sources/
|
||||
reports/
|
||||
_attachments/
|
||||
_views/
|
||||
.openclaw-wiki/
|
||||
```
|
||||
|
||||
Managed content stays inside generated blocks. Human note blocks are preserved.
|
||||
|
||||
The main page groups are:
|
||||
|
||||
- `sources/` for imported raw material and bridge-backed pages
|
||||
- `entities/` for durable things, people, systems, projects, and objects
|
||||
- `concepts/` for ideas, abstractions, patterns, and policies
|
||||
- `syntheses/` for compiled summaries and maintained rollups
|
||||
- `reports/` for generated dashboards
|
||||
|
||||
## Structured claims and evidence
|
||||
|
||||
Pages can carry structured `claims` frontmatter, not just freeform text.
|
||||
|
||||
Each claim can include:
|
||||
|
||||
- `id`
|
||||
- `text`
|
||||
- `status`
|
||||
- `confidence`
|
||||
- `evidence[]`
|
||||
- `updatedAt`
|
||||
|
||||
Evidence entries can include:
|
||||
|
||||
- `sourceId`
|
||||
- `path`
|
||||
- `lines`
|
||||
- `weight`
|
||||
- `note`
|
||||
- `updatedAt`
|
||||
|
||||
This is what makes the wiki act more like a belief layer than a passive note
|
||||
dump. Claims can be tracked, scored, contested, and resolved back to sources.
|
||||
|
||||
## Compile pipeline
|
||||
|
||||
The compile step reads wiki pages, normalizes summaries, and emits stable
|
||||
machine-facing artifacts under:
|
||||
|
||||
- `.openclaw-wiki/cache/agent-digest.json`
|
||||
- `.openclaw-wiki/cache/claims.jsonl`
|
||||
|
||||
These digests exist so agents and runtime code do not have to scrape Markdown
|
||||
pages.
|
||||
|
||||
Compiled output also powers:
|
||||
|
||||
- first-pass wiki indexing for search/get flows
|
||||
- claim-id lookup back to owning pages
|
||||
- compact prompt supplements
|
||||
- report/dashboard generation
|
||||
|
||||
## Dashboards and health reports
|
||||
|
||||
When `render.createDashboards` is enabled, compile maintains dashboards under
|
||||
`reports/`.
|
||||
|
||||
Built-in reports include:
|
||||
|
||||
- `reports/open-questions.md`
|
||||
- `reports/contradictions.md`
|
||||
- `reports/low-confidence.md`
|
||||
- `reports/claim-health.md`
|
||||
- `reports/stale-pages.md`
|
||||
|
||||
These reports track things like:
|
||||
|
||||
- contradiction note clusters
|
||||
- competing claim clusters
|
||||
- claims missing structured evidence
|
||||
- low-confidence pages and claims
|
||||
- stale or unknown freshness
|
||||
- pages with unresolved questions
|
||||
|
||||
## Search and retrieval
|
||||
|
||||
`memory-wiki` supports two search backends:
|
||||
|
||||
- `shared`: use the shared memory search flow when available
|
||||
- `local`: search the wiki locally
|
||||
|
||||
It also supports three corpora:
|
||||
|
||||
- `wiki`
|
||||
- `memory`
|
||||
- `all`
|
||||
|
||||
Important behavior:
|
||||
|
||||
- `wiki_search` and `wiki_get` use compiled digests as a first pass when possible
|
||||
- claim ids can resolve back to the owning page
|
||||
- contested/stale/fresh claims influence ranking
|
||||
- provenance labels can survive into results
|
||||
|
||||
Practical rule:
|
||||
|
||||
- use `memory_search corpus=all` for one broad recall pass
|
||||
- use `wiki_search` + `wiki_get` when you care about wiki-specific ranking,
|
||||
provenance, or page-level belief structure
|
||||
|
||||
## Agent tools
|
||||
|
||||
The plugin registers these tools:
|
||||
|
||||
- `wiki_status`
|
||||
- `wiki_search`
|
||||
- `wiki_get`
|
||||
- `wiki_apply`
|
||||
- `wiki_lint`
|
||||
|
||||
What they do:
|
||||
|
||||
- `wiki_status`: current vault mode, health, Obsidian CLI availability
|
||||
- `wiki_search`: search wiki pages and, when configured, shared memory corpora
|
||||
- `wiki_get`: read a wiki page by id/path or fall back to shared memory corpus
|
||||
- `wiki_apply`: narrow synthesis/metadata mutations without freeform page surgery
|
||||
- `wiki_lint`: structural checks, provenance gaps, contradictions, open questions
|
||||
|
||||
The plugin also registers a non-exclusive memory corpus supplement, so shared
|
||||
`memory_search` and `memory_get` can reach the wiki when the active memory
|
||||
plugin supports corpus selection.
|
||||
|
||||
## Prompt and context behavior
|
||||
|
||||
When `context.includeCompiledDigestPrompt` is enabled, memory prompt sections
|
||||
append a compact compiled snapshot from `agent-digest.json`.
|
||||
|
||||
That snapshot is intentionally small and high-signal:
|
||||
|
||||
- top pages only
|
||||
- top claims only
|
||||
- contradiction count
|
||||
- question count
|
||||
- confidence/freshness qualifiers
|
||||
|
||||
This is opt-in because it changes prompt shape and is mainly useful for context
|
||||
engines or legacy prompt assembly that explicitly consume memory supplements.
|
||||
|
||||
## Configuration
|
||||
|
||||
Put config under `plugins.entries.memory-wiki.config`:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"memory-wiki": {
|
||||
enabled: true,
|
||||
config: {
|
||||
vaultMode: "isolated",
|
||||
vault: {
|
||||
path: "~/.openclaw/wiki/main",
|
||||
renderMode: "obsidian",
|
||||
},
|
||||
obsidian: {
|
||||
enabled: true,
|
||||
useOfficialCli: true,
|
||||
vaultName: "OpenClaw Wiki",
|
||||
openAfterWrites: false,
|
||||
},
|
||||
bridge: {
|
||||
enabled: false,
|
||||
readMemoryArtifacts: true,
|
||||
indexDreamReports: true,
|
||||
indexDailyNotes: true,
|
||||
indexMemoryRoot: true,
|
||||
followMemoryEvents: true,
|
||||
},
|
||||
ingest: {
|
||||
autoCompile: true,
|
||||
maxConcurrentJobs: 1,
|
||||
allowUrlIngest: true,
|
||||
},
|
||||
search: {
|
||||
backend: "shared",
|
||||
corpus: "wiki",
|
||||
},
|
||||
context: {
|
||||
includeCompiledDigestPrompt: false,
|
||||
},
|
||||
render: {
|
||||
preserveHumanBlocks: true,
|
||||
createBacklinks: true,
|
||||
createDashboards: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Key toggles:
|
||||
|
||||
- `vaultMode`: `isolated`, `bridge`, `unsafe-local`
|
||||
- `vault.renderMode`: `native` or `obsidian`
|
||||
- `bridge.readMemoryArtifacts`: import active memory plugin public artifacts
|
||||
- `bridge.followMemoryEvents`: include event logs in bridge mode
|
||||
- `search.backend`: `shared` or `local`
|
||||
- `search.corpus`: `wiki`, `memory`, or `all`
|
||||
- `context.includeCompiledDigestPrompt`: append compact digest snapshot to memory prompt sections
|
||||
- `render.createBacklinks`: generate deterministic related blocks
|
||||
- `render.createDashboards`: generate dashboard pages
|
||||
|
||||
### Example: QMD + bridge mode
|
||||
|
||||
Use this when you want QMD for recall and `memory-wiki` for a maintained
|
||||
knowledge layer:
|
||||
|
||||
```json5
|
||||
{
|
||||
memory: {
|
||||
backend: "qmd",
|
||||
"memory-wiki": {
|
||||
enabled: true,
|
||||
config: {
|
||||
vaultMode: "bridge",
|
||||
bridge: {
|
||||
enabled: true,
|
||||
readMemoryArtifacts: true,
|
||||
indexDreamReports: true,
|
||||
indexDailyNotes: true,
|
||||
indexMemoryRoot: true,
|
||||
followMemoryEvents: true,
|
||||
},
|
||||
search: {
|
||||
backend: "shared",
|
||||
corpus: "all",
|
||||
},
|
||||
context: {
|
||||
includeCompiledDigestPrompt: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
This keeps:
|
||||
|
||||
- QMD in charge of active memory recall
|
||||
- `memory-wiki` focused on compiled pages and dashboards
|
||||
- prompt shape unchanged until you intentionally enable compiled digest prompts
|
||||
|
||||
## CLI
|
||||
|
||||
`memory-wiki` also exposes a top-level CLI surface:
|
||||
|
||||
```bash
|
||||
openclaw wiki status
|
||||
openclaw wiki doctor
|
||||
openclaw wiki init
|
||||
openclaw wiki ingest ./notes/alpha.md
|
||||
openclaw wiki compile
|
||||
openclaw wiki lint
|
||||
openclaw wiki search "alpha"
|
||||
openclaw wiki get entity.alpha
|
||||
openclaw wiki apply synthesis "Alpha Summary" --body "..." --source-id source.alpha
|
||||
openclaw wiki bridge import
|
||||
openclaw wiki obsidian status
|
||||
```
|
||||
|
||||
See [CLI: wiki](/cli/wiki) for the full command reference.
|
||||
|
||||
## Obsidian support
|
||||
|
||||
When `vault.renderMode` is `obsidian`, the plugin writes Obsidian-friendly
|
||||
Markdown and can optionally use the official `obsidian` CLI.
|
||||
|
||||
Supported workflows include:
|
||||
|
||||
- status probing
|
||||
- vault search
|
||||
- opening a page
|
||||
- invoking an Obsidian command
|
||||
- jumping to the daily note
|
||||
|
||||
This is optional. The wiki still works in native mode without Obsidian.
|
||||
|
||||
## Recommended workflow
|
||||
|
||||
1. Keep your active memory plugin for recall/promotion/dreaming.
|
||||
2. Enable `memory-wiki`.
|
||||
3. Start with `isolated` mode unless you explicitly want bridge mode.
|
||||
4. Use `wiki_search` / `wiki_get` when provenance matters.
|
||||
5. Use `wiki_apply` for narrow syntheses or metadata updates.
|
||||
6. Run `wiki_lint` after meaningful changes.
|
||||
7. Turn on dashboards if you want stale/contradiction visibility.
|
||||
|
||||
## Related docs
|
||||
|
||||
- [Memory Overview](/concepts/memory)
|
||||
- [CLI: memory](/cli/memory)
|
||||
- [CLI: wiki](/cli/wiki)
|
||||
- [Plugin SDK overview](/plugins/sdk-overview)
|
||||
283
openclaw/docs/plugins/sdk-agent-harness.md
Normal file
283
openclaw/docs/plugins/sdk-agent-harness.md
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
---
|
||||
title: "Agent Harness Plugins"
|
||||
sidebarTitle: "Agent Harness"
|
||||
summary: "Experimental SDK surface for plugins that replace the low level embedded agent executor"
|
||||
read_when:
|
||||
- You are changing the embedded agent runtime or harness registry
|
||||
- You are registering an agent harness from a bundled or trusted plugin
|
||||
- You need to understand how the Codex plugin relates to model providers
|
||||
---
|
||||
|
||||
# Agent Harness Plugins
|
||||
|
||||
An **agent harness** is the low level executor for one prepared OpenClaw agent
|
||||
turn. It is not a model provider, not a channel, and not a tool registry.
|
||||
|
||||
Use this surface only for bundled or trusted native plugins. The contract is
|
||||
still experimental because the parameter types intentionally mirror the current
|
||||
embedded runner.
|
||||
|
||||
## When to use a harness
|
||||
|
||||
Register an agent harness when a model family has its own native session
|
||||
runtime and the normal OpenClaw provider transport is the wrong abstraction.
|
||||
|
||||
Examples:
|
||||
|
||||
- a native coding-agent server that owns threads and compaction
|
||||
- a local CLI or daemon that must stream native plan/reasoning/tool events
|
||||
- a model runtime that needs its own resume id in addition to the OpenClaw
|
||||
session transcript
|
||||
|
||||
Do **not** register a harness just to add a new LLM API. For normal HTTP or
|
||||
WebSocket model APIs, build a [provider plugin](/plugins/sdk-provider-plugins).
|
||||
|
||||
## What core still owns
|
||||
|
||||
Before a harness is selected, OpenClaw has already resolved:
|
||||
|
||||
- provider and model
|
||||
- runtime auth state
|
||||
- thinking level and context budget
|
||||
- the OpenClaw transcript/session file
|
||||
- workspace, sandbox, and tool policy
|
||||
- channel reply callbacks and streaming callbacks
|
||||
- model fallback and live model switching policy
|
||||
|
||||
That split is intentional. A harness runs a prepared attempt; it does not pick
|
||||
providers, replace channel delivery, or silently switch models.
|
||||
|
||||
## Register a harness
|
||||
|
||||
**Import:** `openclaw/plugin-sdk/agent-harness`
|
||||
|
||||
```typescript
|
||||
import type { AgentHarness } from "openclaw/plugin-sdk/agent-harness";
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
|
||||
const myHarness: AgentHarness = {
|
||||
id: "my-harness",
|
||||
label: "My native agent harness",
|
||||
|
||||
supports(ctx) {
|
||||
return ctx.provider === "my-provider"
|
||||
? { supported: true, priority: 100 }
|
||||
: { supported: false };
|
||||
},
|
||||
|
||||
async runAttempt(params) {
|
||||
// Start or resume your native thread.
|
||||
// Use params.prompt, params.tools, params.images, params.onPartialReply,
|
||||
// params.onAgentEvent, and the other prepared attempt fields.
|
||||
return await runMyNativeTurn(params);
|
||||
},
|
||||
};
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "my-native-agent",
|
||||
name: "My Native Agent",
|
||||
description: "Runs selected models through a native agent daemon.",
|
||||
register(api) {
|
||||
api.registerAgentHarness(myHarness);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Selection policy
|
||||
|
||||
OpenClaw chooses a harness after provider/model resolution:
|
||||
|
||||
1. `OPENCLAW_AGENT_RUNTIME=<id>` forces a registered harness with that id.
|
||||
2. `OPENCLAW_AGENT_RUNTIME=pi` forces the built-in PI harness.
|
||||
3. `OPENCLAW_AGENT_RUNTIME=auto` asks registered harnesses if they support the
|
||||
resolved provider/model.
|
||||
4. If no registered harness matches, OpenClaw uses PI unless PI fallback is
|
||||
disabled.
|
||||
|
||||
Forced plugin harness failures surface as run failures. In `auto` mode,
|
||||
OpenClaw may fall back to PI when the selected plugin harness fails before a
|
||||
turn has produced side effects. Set `OPENCLAW_AGENT_HARNESS_FALLBACK=none` or
|
||||
`embeddedHarness.fallback: "none"` to make that fallback a hard failure instead.
|
||||
|
||||
The bundled Codex plugin registers `codex` as its harness id. Core treats that
|
||||
as an ordinary plugin harness id; Codex-specific aliases belong in the plugin
|
||||
or operator config, not in the shared runtime selector.
|
||||
|
||||
## Provider plus harness pairing
|
||||
|
||||
Most harnesses should also register a provider. The provider makes model refs,
|
||||
auth status, model metadata, and `/model` selection visible to the rest of
|
||||
OpenClaw. The harness then claims that provider in `supports(...)`.
|
||||
|
||||
The bundled Codex plugin follows this pattern:
|
||||
|
||||
- provider id: `codex`
|
||||
- user model refs: `codex/gpt-5.4`, `codex/gpt-5.2`, or another model returned
|
||||
by the Codex app server
|
||||
- harness id: `codex`
|
||||
- auth: synthetic provider availability, because the Codex harness owns the
|
||||
native Codex login/session
|
||||
- app-server request: OpenClaw sends the bare model id to Codex and lets the
|
||||
harness talk to the native app-server protocol
|
||||
|
||||
The Codex plugin is additive. Plain `openai/gpt-*` refs remain OpenAI provider
|
||||
refs and continue to use the normal OpenClaw provider path. Select `codex/gpt-*`
|
||||
when you want Codex-managed auth, Codex model discovery, native threads, and
|
||||
Codex app-server execution. `/model` can switch among the Codex models returned
|
||||
by the Codex app server without requiring OpenAI provider credentials.
|
||||
|
||||
For operator setup, model prefix examples, and Codex-only configs, see
|
||||
[Codex Harness](/plugins/codex-harness).
|
||||
|
||||
OpenClaw requires Codex app-server `0.118.0` or newer. The Codex plugin checks
|
||||
the app-server initialize handshake and blocks older or unversioned servers so
|
||||
OpenClaw only runs against the protocol surface it has been tested with.
|
||||
|
||||
### Native Codex harness mode
|
||||
|
||||
The bundled `codex` harness is the native Codex mode for embedded OpenClaw
|
||||
agent turns. Enable the bundled `codex` plugin first, and include `codex` in
|
||||
`plugins.allow` if your config uses a restrictive allowlist. It is different
|
||||
from `openai-codex/*`:
|
||||
|
||||
- `openai-codex/*` uses ChatGPT/Codex OAuth through the normal OpenClaw provider
|
||||
path.
|
||||
- `codex/*` uses the bundled Codex provider and routes the turn through Codex
|
||||
app-server.
|
||||
|
||||
When this mode runs, Codex owns the native thread id, resume behavior,
|
||||
compaction, and app-server execution. OpenClaw still owns the chat channel,
|
||||
visible transcript mirror, tool policy, approvals, media delivery, and session
|
||||
selection. Use `embeddedHarness.runtime: "codex"` with
|
||||
`embeddedHarness.fallback: "none"` when you need to prove that the Codex
|
||||
app-server path is used and PI fallback is not hiding a broken native harness.
|
||||
|
||||
## Disable PI fallback
|
||||
|
||||
By default, OpenClaw runs embedded agents with `agents.defaults.embeddedHarness`
|
||||
set to `{ runtime: "auto", fallback: "pi" }`. In `auto` mode, registered plugin
|
||||
harnesses can claim a provider/model pair. If none match, or if an auto-selected
|
||||
plugin harness fails before producing output, OpenClaw falls back to PI.
|
||||
|
||||
Set `fallback: "none"` when you need to prove that a plugin harness is the only
|
||||
runtime being exercised. This disables automatic PI fallback; it does not block
|
||||
an explicit `runtime: "pi"` or `OPENCLAW_AGENT_RUNTIME=pi`.
|
||||
|
||||
For Codex-only embedded runs:
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"model": "codex/gpt-5.4",
|
||||
"embeddedHarness": {
|
||||
"runtime": "codex",
|
||||
"fallback": "none"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you want any registered plugin harness to claim matching models but never
|
||||
want OpenClaw to silently fall back to PI, keep `runtime: "auto"` and disable
|
||||
the fallback:
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"embeddedHarness": {
|
||||
"runtime": "auto",
|
||||
"fallback": "none"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Per-agent overrides use the same shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"embeddedHarness": {
|
||||
"runtime": "auto",
|
||||
"fallback": "pi"
|
||||
}
|
||||
},
|
||||
"list": [
|
||||
{
|
||||
"id": "codex-only",
|
||||
"model": "codex/gpt-5.4",
|
||||
"embeddedHarness": {
|
||||
"runtime": "codex",
|
||||
"fallback": "none"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`OPENCLAW_AGENT_RUNTIME` still overrides the configured runtime. Use
|
||||
`OPENCLAW_AGENT_HARNESS_FALLBACK=none` to disable PI fallback from the
|
||||
environment.
|
||||
|
||||
```bash
|
||||
OPENCLAW_AGENT_RUNTIME=codex \
|
||||
OPENCLAW_AGENT_HARNESS_FALLBACK=none \
|
||||
openclaw gateway run
|
||||
```
|
||||
|
||||
With fallback disabled, a session fails early when the requested harness is not
|
||||
registered, does not support the resolved provider/model, or fails before
|
||||
producing turn side effects. That is intentional for Codex-only deployments and
|
||||
for live tests that must prove the Codex app-server path is actually in use.
|
||||
|
||||
This setting only controls the embedded agent harness. It does not disable
|
||||
image, video, music, TTS, PDF, or other provider-specific model routing.
|
||||
|
||||
## Native sessions and transcript mirror
|
||||
|
||||
A harness may keep a native session id, thread id, or daemon-side resume token.
|
||||
Keep that binding explicitly associated with the OpenClaw session, and keep
|
||||
mirroring user-visible assistant/tool output into the OpenClaw transcript.
|
||||
|
||||
The OpenClaw transcript remains the compatibility layer for:
|
||||
|
||||
- channel-visible session history
|
||||
- transcript search and indexing
|
||||
- switching back to the built-in PI harness on a later turn
|
||||
- generic `/new`, `/reset`, and session deletion behavior
|
||||
|
||||
If your harness stores a sidecar binding, implement `reset(...)` so OpenClaw can
|
||||
clear it when the owning OpenClaw session is reset.
|
||||
|
||||
## Tool and media results
|
||||
|
||||
Core constructs the OpenClaw tool list and passes it into the prepared attempt.
|
||||
When a harness executes a dynamic tool call, return the tool result back through
|
||||
the harness result shape instead of sending channel media yourself.
|
||||
|
||||
This keeps text, image, video, music, TTS, approval, and messaging-tool outputs
|
||||
on the same delivery path as PI-backed runs.
|
||||
|
||||
## Current limitations
|
||||
|
||||
- The public import path is generic, but some attempt/result type aliases still
|
||||
carry `Pi` names for compatibility.
|
||||
- Third-party harness installation is experimental. Prefer provider plugins
|
||||
until you need a native session runtime.
|
||||
- Harness switching is supported across turns. Do not switch harnesses in the
|
||||
middle of a turn after native tools, approvals, assistant text, or message
|
||||
sends have started.
|
||||
|
||||
## Related
|
||||
|
||||
- [SDK Overview](/plugins/sdk-overview)
|
||||
- [Runtime Helpers](/plugins/sdk-runtime)
|
||||
- [Provider Plugins](/plugins/sdk-provider-plugins)
|
||||
- [Codex Harness](/plugins/codex-harness)
|
||||
- [Model Providers](/concepts/model-providers)
|
||||
635
openclaw/docs/plugins/sdk-channel-plugins.md
Normal file
635
openclaw/docs/plugins/sdk-channel-plugins.md
Normal file
|
|
@ -0,0 +1,635 @@
|
|||
---
|
||||
title: "Building Channel Plugins"
|
||||
sidebarTitle: "Channel Plugins"
|
||||
summary: "Step-by-step guide to building a messaging channel plugin for OpenClaw"
|
||||
read_when:
|
||||
- You are building a new messaging channel plugin
|
||||
- You want to connect OpenClaw to a messaging platform
|
||||
- You need to understand the ChannelPlugin adapter surface
|
||||
---
|
||||
|
||||
# Building Channel Plugins
|
||||
|
||||
This guide walks through building a channel plugin that connects OpenClaw to a
|
||||
messaging platform. By the end you will have a working channel with DM security,
|
||||
pairing, reply threading, and outbound messaging.
|
||||
|
||||
<Info>
|
||||
If you have not built any OpenClaw plugin before, read
|
||||
[Getting Started](/plugins/building-plugins) first for the basic package
|
||||
structure and manifest setup.
|
||||
</Info>
|
||||
|
||||
## How channel plugins work
|
||||
|
||||
Channel plugins do not need their own send/edit/react tools. OpenClaw keeps one
|
||||
shared `message` tool in core. Your plugin owns:
|
||||
|
||||
- **Config** — account resolution and setup wizard
|
||||
- **Security** — DM policy and allowlists
|
||||
- **Pairing** — DM approval flow
|
||||
- **Session grammar** — how provider-specific conversation ids map to base chats, thread ids, and parent fallbacks
|
||||
- **Outbound** — sending text, media, and polls to the platform
|
||||
- **Threading** — how replies are threaded
|
||||
|
||||
Core owns the shared message tool, prompt wiring, the outer session-key shape,
|
||||
generic `:thread:` bookkeeping, and dispatch.
|
||||
|
||||
If your channel adds message-tool params that carry media sources, expose those
|
||||
param names through `describeMessageTool(...).mediaSourceParams`. Core uses
|
||||
that explicit list for sandbox path normalization and outbound media-access
|
||||
policy, so plugins do not need shared-core special cases for provider-specific
|
||||
avatar, attachment, or cover-image params.
|
||||
Prefer returning an action-keyed map such as
|
||||
`{ "set-profile": ["avatarUrl", "avatarPath"] }` so unrelated actions do not
|
||||
inherit another action's media args. A flat array still works for params that
|
||||
are intentionally shared across every exposed action.
|
||||
|
||||
If your platform stores extra scope inside conversation ids, keep that parsing
|
||||
in the plugin with `messaging.resolveSessionConversation(...)`. That is the
|
||||
canonical hook for mapping `rawId` to the base conversation id, optional thread
|
||||
id, explicit `baseConversationId`, and any `parentConversationCandidates`.
|
||||
When you return `parentConversationCandidates`, keep them ordered from the
|
||||
narrowest parent to the broadest/base conversation.
|
||||
|
||||
Bundled plugins that need the same parsing before the channel registry boots
|
||||
can also expose a top-level `session-key-api.ts` file with a matching
|
||||
`resolveSessionConversation(...)` export. Core uses that bootstrap-safe surface
|
||||
only when the runtime plugin registry is not available yet.
|
||||
|
||||
`messaging.resolveParentConversationCandidates(...)` remains available as a
|
||||
legacy compatibility fallback when a plugin only needs parent fallbacks on top
|
||||
of the generic/raw id. If both hooks exist, core uses
|
||||
`resolveSessionConversation(...).parentConversationCandidates` first and only
|
||||
falls back to `resolveParentConversationCandidates(...)` when the canonical hook
|
||||
omits them.
|
||||
|
||||
## Approvals and channel capabilities
|
||||
|
||||
Most channel plugins do not need approval-specific code.
|
||||
|
||||
- Core owns same-chat `/approve`, shared approval button payloads, and generic fallback delivery.
|
||||
- Prefer one `approvalCapability` object on the channel plugin when the channel needs approval-specific behavior.
|
||||
- `ChannelPlugin.approvals` is removed. Put approval delivery/native/render/auth facts on `approvalCapability`.
|
||||
- `plugin.auth` is login/logout only; core no longer reads approval auth hooks from that object.
|
||||
- `approvalCapability.authorizeActorAction` and `approvalCapability.getActionAvailabilityState` are the canonical approval-auth seam.
|
||||
- Use `approvalCapability.getActionAvailabilityState` for same-chat approval auth availability.
|
||||
- If your channel exposes native exec approvals, use `approvalCapability.getExecInitiatingSurfaceState` for the initiating-surface/native-client state when it differs from same-chat approval auth. Core uses that exec-specific hook to distinguish `enabled` vs `disabled`, decide whether the initiating channel supports native exec approvals, and include the channel in native-client fallback guidance. `createApproverRestrictedNativeApprovalCapability(...)` fills this in for the common case.
|
||||
- Use `outbound.shouldSuppressLocalPayloadPrompt` or `outbound.beforeDeliverPayload` for channel-specific payload lifecycle behavior such as hiding duplicate local approval prompts or sending typing indicators before delivery.
|
||||
- Use `approvalCapability.delivery` only for native approval routing or fallback suppression.
|
||||
- Use `approvalCapability.nativeRuntime` for channel-owned native approval facts. Keep it lazy on hot channel entrypoints with `createLazyChannelApprovalNativeRuntimeAdapter(...)`, which can import your runtime module on demand while still letting core assemble the approval lifecycle.
|
||||
- Use `approvalCapability.render` only when a channel truly needs custom approval payloads instead of the shared renderer.
|
||||
- Use `approvalCapability.describeExecApprovalSetup` when the channel wants the disabled-path reply to explain the exact config knobs needed to enable native exec approvals. The hook receives `{ channel, channelLabel, accountId }`; named-account channels should render account-scoped paths such as `channels.<channel>.accounts.<id>.execApprovals.*` instead of top-level defaults.
|
||||
- If a channel can infer stable owner-like DM identities from existing config, use `createResolvedApproverActionAuthAdapter` from `openclaw/plugin-sdk/approval-runtime` to restrict same-chat `/approve` without adding approval-specific core logic.
|
||||
- If a channel needs native approval delivery, keep channel code focused on target normalization plus transport/presentation facts. Use `createChannelExecApprovalProfile`, `createChannelNativeOriginTargetResolver`, `createChannelApproverDmTargetResolver`, and `createApproverRestrictedNativeApprovalCapability` from `openclaw/plugin-sdk/approval-runtime`. Put the channel-specific facts behind `approvalCapability.nativeRuntime`, ideally via `createChannelApprovalNativeRuntimeAdapter(...)` or `createLazyChannelApprovalNativeRuntimeAdapter(...)`, so core can assemble the handler and own request filtering, routing, dedupe, expiry, gateway subscription, and routed-elsewhere notices. `nativeRuntime` is split into a few smaller seams:
|
||||
- `availability` — whether the account is configured and whether a request should be handled
|
||||
- `presentation` — map the shared approval view model into pending/resolved/expired native payloads or final actions
|
||||
- `transport` — prepare targets plus send/update/delete native approval messages
|
||||
- `interactions` — optional bind/unbind/clear-action hooks for native buttons or reactions
|
||||
- `observe` — optional delivery diagnostics hooks
|
||||
- If the channel needs runtime-owned objects such as a client, token, Bolt app, or webhook receiver, register them through `openclaw/plugin-sdk/channel-runtime-context`. The generic runtime-context registry lets core bootstrap capability-driven handlers from channel startup state without adding approval-specific wrapper glue.
|
||||
- Reach for the lower-level `createChannelApprovalHandler` or `createChannelNativeApprovalRuntime` only when the capability-driven seam is not expressive enough yet.
|
||||
- Native approval channels must route both `accountId` and `approvalKind` through those helpers. `accountId` keeps multi-account approval policy scoped to the right bot account, and `approvalKind` keeps exec vs plugin approval behavior available to the channel without hardcoded branches in core.
|
||||
- Core now owns approval reroute notices too. Channel plugins should not send their own "approval went to DMs / another channel" follow-up messages from `createChannelNativeApprovalRuntime`; instead, expose accurate origin + approver-DM routing through the shared approval capability helpers and let core aggregate actual deliveries before posting any notice back to the initiating chat.
|
||||
- Preserve the delivered approval id kind end-to-end. Native clients should not
|
||||
guess or rewrite exec vs plugin approval routing from channel-local state.
|
||||
- Different approval kinds can intentionally expose different native surfaces.
|
||||
Current bundled examples:
|
||||
- Slack keeps native approval routing available for both exec and plugin ids.
|
||||
- Matrix keeps the same native DM/channel routing and reaction UX for exec
|
||||
and plugin approvals, while still letting auth differ by approval kind.
|
||||
- `createApproverRestrictedNativeApprovalAdapter` still exists as a compatibility wrapper, but new code should prefer the capability builder and expose `approvalCapability` on the plugin.
|
||||
|
||||
For hot channel entrypoints, prefer the narrower runtime subpaths when you only
|
||||
need one part of that family:
|
||||
|
||||
- `openclaw/plugin-sdk/approval-auth-runtime`
|
||||
- `openclaw/plugin-sdk/approval-client-runtime`
|
||||
- `openclaw/plugin-sdk/approval-delivery-runtime`
|
||||
- `openclaw/plugin-sdk/approval-gateway-runtime`
|
||||
- `openclaw/plugin-sdk/approval-handler-adapter-runtime`
|
||||
- `openclaw/plugin-sdk/approval-handler-runtime`
|
||||
- `openclaw/plugin-sdk/approval-native-runtime`
|
||||
- `openclaw/plugin-sdk/approval-reply-runtime`
|
||||
- `openclaw/plugin-sdk/channel-runtime-context`
|
||||
|
||||
Likewise, prefer `openclaw/plugin-sdk/setup-runtime`,
|
||||
`openclaw/plugin-sdk/setup-adapter-runtime`,
|
||||
`openclaw/plugin-sdk/reply-runtime`,
|
||||
`openclaw/plugin-sdk/reply-dispatch-runtime`,
|
||||
`openclaw/plugin-sdk/reply-reference`, and
|
||||
`openclaw/plugin-sdk/reply-chunking` when you do not need the broader umbrella
|
||||
surface.
|
||||
|
||||
For setup specifically:
|
||||
|
||||
- `openclaw/plugin-sdk/setup-runtime` covers the runtime-safe setup helpers:
|
||||
import-safe setup patch adapters (`createPatchedAccountSetupAdapter`,
|
||||
`createEnvPatchedAccountSetupAdapter`,
|
||||
`createSetupInputPresenceValidator`), lookup-note output,
|
||||
`promptResolvedAllowFrom`, `splitSetupEntries`, and the delegated
|
||||
setup-proxy builders
|
||||
- `openclaw/plugin-sdk/setup-adapter-runtime` is the narrow env-aware adapter
|
||||
seam for `createEnvPatchedAccountSetupAdapter`
|
||||
- `openclaw/plugin-sdk/channel-setup` covers the optional-install setup
|
||||
builders plus a few setup-safe primitives:
|
||||
`createOptionalChannelSetupSurface`, `createOptionalChannelSetupAdapter`,
|
||||
|
||||
If your channel supports env-driven setup or auth and generic startup/config
|
||||
flows should know those env names before runtime loads, declare them in the
|
||||
plugin manifest with `channelEnvVars`. Keep channel runtime `envVars` or local
|
||||
constants for operator-facing copy only.
|
||||
`createOptionalChannelSetupWizard`, `DEFAULT_ACCOUNT_ID`,
|
||||
`createTopLevelChannelDmPolicy`, `setSetupChannelEnabled`, and
|
||||
`splitSetupEntries`
|
||||
|
||||
- use the broader `openclaw/plugin-sdk/setup` seam only when you also need the
|
||||
heavier shared setup/config helpers such as
|
||||
`moveSingleAccountChannelSectionToDefaultAccount(...)`
|
||||
|
||||
If your channel only wants to advertise "install this plugin first" in setup
|
||||
surfaces, prefer `createOptionalChannelSetupSurface(...)`. The generated
|
||||
adapter/wizard fail closed on config writes and finalization, and they reuse
|
||||
the same install-required message across validation, finalize, and docs-link
|
||||
copy.
|
||||
|
||||
For other hot channel paths, prefer the narrow helpers over broader legacy
|
||||
surfaces:
|
||||
|
||||
- `openclaw/plugin-sdk/account-core`,
|
||||
`openclaw/plugin-sdk/account-id`,
|
||||
`openclaw/plugin-sdk/account-resolution`, and
|
||||
`openclaw/plugin-sdk/account-helpers` for multi-account config and
|
||||
default-account fallback
|
||||
- `openclaw/plugin-sdk/inbound-envelope` and
|
||||
`openclaw/plugin-sdk/inbound-reply-dispatch` for inbound route/envelope and
|
||||
record-and-dispatch wiring
|
||||
- `openclaw/plugin-sdk/messaging-targets` for target parsing/matching
|
||||
- `openclaw/plugin-sdk/outbound-media` and
|
||||
`openclaw/plugin-sdk/outbound-runtime` for media loading plus outbound
|
||||
identity/send delegates
|
||||
- `openclaw/plugin-sdk/thread-bindings-runtime` for thread-binding lifecycle
|
||||
and adapter registration
|
||||
- `openclaw/plugin-sdk/agent-media-payload` only when a legacy agent/media
|
||||
payload field layout is still required
|
||||
- `openclaw/plugin-sdk/telegram-command-config` for Telegram custom-command
|
||||
normalization, duplicate/conflict validation, and a fallback-stable command
|
||||
config contract
|
||||
|
||||
Auth-only channels can usually stop at the default path: core handles approvals and the plugin just exposes outbound/auth capabilities. Native approval channels such as Matrix, Slack, Telegram, and custom chat transports should use the shared native helpers instead of rolling their own approval lifecycle.
|
||||
|
||||
## Inbound mention policy
|
||||
|
||||
Keep inbound mention handling split in two layers:
|
||||
|
||||
- plugin-owned evidence gathering
|
||||
- shared policy evaluation
|
||||
|
||||
Use `openclaw/plugin-sdk/channel-mention-gating` for mention-policy decisions.
|
||||
Use `openclaw/plugin-sdk/channel-inbound` only when you need the broader inbound
|
||||
helper barrel.
|
||||
|
||||
Good fit for plugin-local logic:
|
||||
|
||||
- reply-to-bot detection
|
||||
- quoted-bot detection
|
||||
- thread-participation checks
|
||||
- service/system-message exclusions
|
||||
- platform-native caches needed to prove bot participation
|
||||
|
||||
Good fit for the shared helper:
|
||||
|
||||
- `requireMention`
|
||||
- explicit mention result
|
||||
- implicit mention allowlist
|
||||
- command bypass
|
||||
- final skip decision
|
||||
|
||||
Preferred flow:
|
||||
|
||||
1. Compute local mention facts.
|
||||
2. Pass those facts into `resolveInboundMentionDecision({ facts, policy })`.
|
||||
3. Use `decision.effectiveWasMentioned`, `decision.shouldBypassMention`, and `decision.shouldSkip` in your inbound gate.
|
||||
|
||||
```typescript
|
||||
import {
|
||||
implicitMentionKindWhen,
|
||||
matchesMentionWithExplicit,
|
||||
resolveInboundMentionDecision,
|
||||
} from "openclaw/plugin-sdk/channel-inbound";
|
||||
|
||||
const mentionMatch = matchesMentionWithExplicit(text, {
|
||||
mentionRegexes,
|
||||
mentionPatterns,
|
||||
});
|
||||
|
||||
const facts = {
|
||||
canDetectMention: true,
|
||||
wasMentioned: mentionMatch.matched,
|
||||
hasAnyMention: mentionMatch.hasExplicitMention,
|
||||
implicitMentionKinds: [
|
||||
...implicitMentionKindWhen("reply_to_bot", isReplyToBot),
|
||||
...implicitMentionKindWhen("quoted_bot", isQuoteOfBot),
|
||||
],
|
||||
};
|
||||
|
||||
const decision = resolveInboundMentionDecision({
|
||||
facts,
|
||||
policy: {
|
||||
isGroup,
|
||||
requireMention,
|
||||
allowedImplicitMentionKinds: requireExplicitMention ? [] : ["reply_to_bot", "quoted_bot"],
|
||||
allowTextCommands,
|
||||
hasControlCommand,
|
||||
commandAuthorized,
|
||||
},
|
||||
});
|
||||
|
||||
if (decision.shouldSkip) return;
|
||||
```
|
||||
|
||||
`api.runtime.channel.mentions` exposes the same shared mention helpers for
|
||||
bundled channel plugins that already depend on runtime injection:
|
||||
|
||||
- `buildMentionRegexes`
|
||||
- `matchesMentionPatterns`
|
||||
- `matchesMentionWithExplicit`
|
||||
- `implicitMentionKindWhen`
|
||||
- `resolveInboundMentionDecision`
|
||||
|
||||
If you only need `implicitMentionKindWhen` and
|
||||
`resolveInboundMentionDecision`, import from
|
||||
`openclaw/plugin-sdk/channel-mention-gating` to avoid loading unrelated inbound
|
||||
runtime helpers.
|
||||
|
||||
The older `resolveMentionGating*` helpers remain on
|
||||
`openclaw/plugin-sdk/channel-inbound` as compatibility exports only. New code
|
||||
should use `resolveInboundMentionDecision({ facts, policy })`.
|
||||
|
||||
## Walkthrough
|
||||
|
||||
<Steps>
|
||||
<a id="step-1-package-and-manifest"></a>
|
||||
<Step title="Package and manifest">
|
||||
Create the standard plugin files. The `channel` field in `package.json` is
|
||||
what makes this a channel plugin. For the full package-metadata surface,
|
||||
see [Plugin Setup and Config](/plugins/sdk-setup#openclaw-channel):
|
||||
|
||||
<CodeGroup>
|
||||
```json package.json
|
||||
{
|
||||
"name": "@myorg/openclaw-acme-chat",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"setupEntry": "./setup-entry.ts",
|
||||
"channel": {
|
||||
"id": "acme-chat",
|
||||
"label": "Acme Chat",
|
||||
"blurb": "Connect OpenClaw to Acme Chat."
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json openclaw.plugin.json
|
||||
{
|
||||
"id": "acme-chat",
|
||||
"kind": "channel",
|
||||
"channels": ["acme-chat"],
|
||||
"name": "Acme Chat",
|
||||
"description": "Acme Chat channel plugin",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"acme-chat": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"token": { "type": "string" },
|
||||
"allowFrom": {
|
||||
"type": "array",
|
||||
"items": { "type": "string" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Build the channel plugin object">
|
||||
The `ChannelPlugin` interface has many optional adapter surfaces. Start with
|
||||
the minimum — `id` and `setup` — and add adapters as you need them.
|
||||
|
||||
Create `src/channel.ts`:
|
||||
|
||||
```typescript src/channel.ts
|
||||
import {
|
||||
createChatChannelPlugin,
|
||||
createChannelPluginBase,
|
||||
} from "openclaw/plugin-sdk/channel-core";
|
||||
import type { OpenClawConfig } from "openclaw/plugin-sdk/channel-core";
|
||||
import { acmeChatApi } from "./client.js"; // your platform API client
|
||||
|
||||
type ResolvedAccount = {
|
||||
accountId: string | null;
|
||||
token: string;
|
||||
allowFrom: string[];
|
||||
dmPolicy: string | undefined;
|
||||
};
|
||||
|
||||
function resolveAccount(
|
||||
cfg: OpenClawConfig,
|
||||
accountId?: string | null,
|
||||
): ResolvedAccount {
|
||||
const section = (cfg.channels as Record<string, any>)?.["acme-chat"];
|
||||
const token = section?.token;
|
||||
if (!token) throw new Error("acme-chat: token is required");
|
||||
return {
|
||||
accountId: accountId ?? null,
|
||||
token,
|
||||
allowFrom: section?.allowFrom ?? [],
|
||||
dmPolicy: section?.dmSecurity,
|
||||
};
|
||||
}
|
||||
|
||||
export const acmeChatPlugin = createChatChannelPlugin<ResolvedAccount>({
|
||||
base: createChannelPluginBase({
|
||||
id: "acme-chat",
|
||||
setup: {
|
||||
resolveAccount,
|
||||
inspectAccount(cfg, accountId) {
|
||||
const section =
|
||||
(cfg.channels as Record<string, any>)?.["acme-chat"];
|
||||
return {
|
||||
enabled: Boolean(section?.token),
|
||||
configured: Boolean(section?.token),
|
||||
tokenStatus: section?.token ? "available" : "missing",
|
||||
};
|
||||
},
|
||||
},
|
||||
}),
|
||||
|
||||
// DM security: who can message the bot
|
||||
security: {
|
||||
dm: {
|
||||
channelKey: "acme-chat",
|
||||
resolvePolicy: (account) => account.dmPolicy,
|
||||
resolveAllowFrom: (account) => account.allowFrom,
|
||||
defaultPolicy: "allowlist",
|
||||
},
|
||||
},
|
||||
|
||||
// Pairing: approval flow for new DM contacts
|
||||
pairing: {
|
||||
text: {
|
||||
idLabel: "Acme Chat username",
|
||||
message: "Send this code to verify your identity:",
|
||||
notify: async ({ target, code }) => {
|
||||
await acmeChatApi.sendDm(target, `Pairing code: ${code}`);
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
// Threading: how replies are delivered
|
||||
threading: { topLevelReplyToMode: "reply" },
|
||||
|
||||
// Outbound: send messages to the platform
|
||||
outbound: {
|
||||
attachedResults: {
|
||||
sendText: async (params) => {
|
||||
const result = await acmeChatApi.sendMessage(
|
||||
params.to,
|
||||
params.text,
|
||||
);
|
||||
return { messageId: result.id };
|
||||
},
|
||||
},
|
||||
base: {
|
||||
sendMedia: async (params) => {
|
||||
await acmeChatApi.sendFile(params.to, params.filePath);
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
<Accordion title="What createChatChannelPlugin does for you">
|
||||
Instead of implementing low-level adapter interfaces manually, you pass
|
||||
declarative options and the builder composes them:
|
||||
|
||||
| Option | What it wires |
|
||||
| --- | --- |
|
||||
| `security.dm` | Scoped DM security resolver from config fields |
|
||||
| `pairing.text` | Text-based DM pairing flow with code exchange |
|
||||
| `threading` | Reply-to-mode resolver (fixed, account-scoped, or custom) |
|
||||
| `outbound.attachedResults` | Send functions that return result metadata (message IDs) |
|
||||
|
||||
You can also pass raw adapter objects instead of the declarative options
|
||||
if you need full control.
|
||||
</Accordion>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Wire the entry point">
|
||||
Create `index.ts`:
|
||||
|
||||
```typescript index.ts
|
||||
import { defineChannelPluginEntry } from "openclaw/plugin-sdk/channel-core";
|
||||
import { acmeChatPlugin } from "./src/channel.js";
|
||||
|
||||
export default defineChannelPluginEntry({
|
||||
id: "acme-chat",
|
||||
name: "Acme Chat",
|
||||
description: "Acme Chat channel plugin",
|
||||
plugin: acmeChatPlugin,
|
||||
registerCliMetadata(api) {
|
||||
api.registerCli(
|
||||
({ program }) => {
|
||||
program
|
||||
.command("acme-chat")
|
||||
.description("Acme Chat management");
|
||||
},
|
||||
{
|
||||
descriptors: [
|
||||
{
|
||||
name: "acme-chat",
|
||||
description: "Acme Chat management",
|
||||
hasSubcommands: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
},
|
||||
registerFull(api) {
|
||||
api.registerGatewayMethod(/* ... */);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Put channel-owned CLI descriptors in `registerCliMetadata(...)` so OpenClaw
|
||||
can show them in root help without activating the full channel runtime,
|
||||
while normal full loads still pick up the same descriptors for real command
|
||||
registration. Keep `registerFull(...)` for runtime-only work.
|
||||
If `registerFull(...)` registers gateway RPC methods, use a
|
||||
plugin-specific prefix. Core admin namespaces (`config.*`,
|
||||
`exec.approvals.*`, `wizard.*`, `update.*`) stay reserved and always
|
||||
resolve to `operator.admin`.
|
||||
`defineChannelPluginEntry` handles the registration-mode split automatically. See
|
||||
[Entry Points](/plugins/sdk-entrypoints#definechannelpluginentry) for all
|
||||
options.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Add a setup entry">
|
||||
Create `setup-entry.ts` for lightweight loading during onboarding:
|
||||
|
||||
```typescript setup-entry.ts
|
||||
import { defineSetupPluginEntry } from "openclaw/plugin-sdk/channel-core";
|
||||
import { acmeChatPlugin } from "./src/channel.js";
|
||||
|
||||
export default defineSetupPluginEntry(acmeChatPlugin);
|
||||
```
|
||||
|
||||
OpenClaw loads this instead of the full entry when the channel is disabled
|
||||
or unconfigured. It avoids pulling in heavy runtime code during setup flows.
|
||||
See [Setup and Config](/plugins/sdk-setup#setup-entry) for details.
|
||||
|
||||
Bundled workspace channels that split setup-safe exports into sidecar
|
||||
modules can use `defineBundledChannelSetupEntry(...)` from
|
||||
`openclaw/plugin-sdk/channel-entry-contract` when they also need an
|
||||
explicit setup-time runtime setter.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Handle inbound messages">
|
||||
Your plugin needs to receive messages from the platform and forward them to
|
||||
OpenClaw. The typical pattern is a webhook that verifies the request and
|
||||
dispatches it through your channel's inbound handler:
|
||||
|
||||
```typescript
|
||||
registerFull(api) {
|
||||
api.registerHttpRoute({
|
||||
path: "/acme-chat/webhook",
|
||||
auth: "plugin", // plugin-managed auth (verify signatures yourself)
|
||||
handler: async (req, res) => {
|
||||
const event = parseWebhookPayload(req);
|
||||
|
||||
// Your inbound handler dispatches the message to OpenClaw.
|
||||
// The exact wiring depends on your platform SDK —
|
||||
// see a real example in the bundled Microsoft Teams or Google Chat plugin package.
|
||||
await handleAcmeChatInbound(api, event);
|
||||
|
||||
res.statusCode = 200;
|
||||
res.end("ok");
|
||||
return true;
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
<Note>
|
||||
Inbound message handling is channel-specific. Each channel plugin owns
|
||||
its own inbound pipeline. Look at bundled channel plugins
|
||||
(for example the Microsoft Teams or Google Chat plugin package) for real patterns.
|
||||
</Note>
|
||||
|
||||
</Step>
|
||||
|
||||
<a id="step-6-test"></a>
|
||||
<Step title="Test">
|
||||
Write colocated tests in `src/channel.test.ts`:
|
||||
|
||||
```typescript src/channel.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { acmeChatPlugin } from "./channel.js";
|
||||
|
||||
describe("acme-chat plugin", () => {
|
||||
it("resolves account from config", () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
"acme-chat": { token: "test-token", allowFrom: ["user1"] },
|
||||
},
|
||||
} as any;
|
||||
const account = acmeChatPlugin.setup!.resolveAccount(cfg, undefined);
|
||||
expect(account.token).toBe("test-token");
|
||||
});
|
||||
|
||||
it("inspects account without materializing secrets", () => {
|
||||
const cfg = {
|
||||
channels: { "acme-chat": { token: "test-token" } },
|
||||
} as any;
|
||||
const result = acmeChatPlugin.setup!.inspectAccount!(cfg, undefined);
|
||||
expect(result.configured).toBe(true);
|
||||
expect(result.tokenStatus).toBe("available");
|
||||
});
|
||||
|
||||
it("reports missing config", () => {
|
||||
const cfg = { channels: {} } as any;
|
||||
const result = acmeChatPlugin.setup!.inspectAccount!(cfg, undefined);
|
||||
expect(result.configured).toBe(false);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
```bash
|
||||
pnpm test -- <bundled-plugin-root>/acme-chat/
|
||||
```
|
||||
|
||||
For shared test helpers, see [Testing](/plugins/sdk-testing).
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## File structure
|
||||
|
||||
```
|
||||
<bundled-plugin-root>/acme-chat/
|
||||
├── package.json # openclaw.channel metadata
|
||||
├── openclaw.plugin.json # Manifest with config schema
|
||||
├── index.ts # defineChannelPluginEntry
|
||||
├── setup-entry.ts # defineSetupPluginEntry
|
||||
├── api.ts # Public exports (optional)
|
||||
├── runtime-api.ts # Internal runtime exports (optional)
|
||||
└── src/
|
||||
├── channel.ts # ChannelPlugin via createChatChannelPlugin
|
||||
├── channel.test.ts # Tests
|
||||
├── client.ts # Platform API client
|
||||
└── runtime.ts # Runtime store (if needed)
|
||||
```
|
||||
|
||||
## Advanced topics
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Threading options" icon="git-branch" href="/plugins/sdk-entrypoints#registration-mode">
|
||||
Fixed, account-scoped, or custom reply modes
|
||||
</Card>
|
||||
<Card title="Message tool integration" icon="puzzle" href="/plugins/architecture#channel-plugins-and-the-shared-message-tool">
|
||||
describeMessageTool and action discovery
|
||||
</Card>
|
||||
<Card title="Target resolution" icon="crosshair" href="/plugins/architecture#channel-target-resolution">
|
||||
inferTargetChatType, looksLikeId, resolveTarget
|
||||
</Card>
|
||||
<Card title="Runtime helpers" icon="settings" href="/plugins/sdk-runtime">
|
||||
TTS, STT, media, subagent via api.runtime
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
<Note>
|
||||
Some bundled helper seams still exist for bundled-plugin maintenance and
|
||||
compatibility. They are not the recommended pattern for new channel plugins;
|
||||
prefer the generic channel/setup/reply/runtime subpaths from the common SDK
|
||||
surface unless you are maintaining that bundled plugin family directly.
|
||||
</Note>
|
||||
|
||||
## Next steps
|
||||
|
||||
- [Provider Plugins](/plugins/sdk-provider-plugins) — if your plugin also provides models
|
||||
- [SDK Overview](/plugins/sdk-overview) — full subpath import reference
|
||||
- [SDK Testing](/plugins/sdk-testing) — test utilities and contract tests
|
||||
- [Plugin Manifest](/plugins/manifest) — full manifest schema
|
||||
235
openclaw/docs/plugins/sdk-entrypoints.md
Normal file
235
openclaw/docs/plugins/sdk-entrypoints.md
Normal file
|
|
@ -0,0 +1,235 @@
|
|||
---
|
||||
title: "Plugin Entry Points"
|
||||
sidebarTitle: "Entry Points"
|
||||
summary: "Reference for definePluginEntry, defineChannelPluginEntry, and defineSetupPluginEntry"
|
||||
read_when:
|
||||
- You need the exact type signature of definePluginEntry or defineChannelPluginEntry
|
||||
- You want to understand registration mode (full vs setup vs CLI metadata)
|
||||
- You are looking up entry point options
|
||||
---
|
||||
|
||||
# Plugin Entry Points
|
||||
|
||||
Every plugin exports a default entry object. The SDK provides three helpers for
|
||||
creating them.
|
||||
|
||||
<Tip>
|
||||
**Looking for a walkthrough?** See [Channel Plugins](/plugins/sdk-channel-plugins)
|
||||
or [Provider Plugins](/plugins/sdk-provider-plugins) for step-by-step guides.
|
||||
</Tip>
|
||||
|
||||
## `definePluginEntry`
|
||||
|
||||
**Import:** `openclaw/plugin-sdk/plugin-entry`
|
||||
|
||||
For provider plugins, tool plugins, hook plugins, and anything that is **not**
|
||||
a messaging channel.
|
||||
|
||||
```typescript
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "my-plugin",
|
||||
name: "My Plugin",
|
||||
description: "Short summary",
|
||||
register(api) {
|
||||
api.registerProvider({
|
||||
/* ... */
|
||||
});
|
||||
api.registerTool({
|
||||
/* ... */
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
| Field | Type | Required | Default |
|
||||
| -------------- | ---------------------------------------------------------------- | -------- | ------------------- |
|
||||
| `id` | `string` | Yes | — |
|
||||
| `name` | `string` | Yes | — |
|
||||
| `description` | `string` | Yes | — |
|
||||
| `kind` | `string` | No | — |
|
||||
| `configSchema` | `OpenClawPluginConfigSchema \| () => OpenClawPluginConfigSchema` | No | Empty object schema |
|
||||
| `register` | `(api: OpenClawPluginApi) => void` | Yes | — |
|
||||
|
||||
- `id` must match your `openclaw.plugin.json` manifest.
|
||||
- `kind` is for exclusive slots: `"memory"` or `"context-engine"`.
|
||||
- `configSchema` can be a function for lazy evaluation.
|
||||
- OpenClaw resolves and memoizes that schema on first access, so expensive schema
|
||||
builders only run once.
|
||||
|
||||
## `defineChannelPluginEntry`
|
||||
|
||||
**Import:** `openclaw/plugin-sdk/channel-core`
|
||||
|
||||
Wraps `definePluginEntry` with channel-specific wiring. Automatically calls
|
||||
`api.registerChannel({ plugin })`, exposes an optional root-help CLI metadata
|
||||
seam, and gates `registerFull` on registration mode.
|
||||
|
||||
```typescript
|
||||
import { defineChannelPluginEntry } from "openclaw/plugin-sdk/channel-core";
|
||||
|
||||
export default defineChannelPluginEntry({
|
||||
id: "my-channel",
|
||||
name: "My Channel",
|
||||
description: "Short summary",
|
||||
plugin: myChannelPlugin,
|
||||
setRuntime: setMyRuntime,
|
||||
registerCliMetadata(api) {
|
||||
api.registerCli(/* ... */);
|
||||
},
|
||||
registerFull(api) {
|
||||
api.registerGatewayMethod(/* ... */);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
| Field | Type | Required | Default |
|
||||
| --------------------- | ---------------------------------------------------------------- | -------- | ------------------- |
|
||||
| `id` | `string` | Yes | — |
|
||||
| `name` | `string` | Yes | — |
|
||||
| `description` | `string` | Yes | — |
|
||||
| `plugin` | `ChannelPlugin` | Yes | — |
|
||||
| `configSchema` | `OpenClawPluginConfigSchema \| () => OpenClawPluginConfigSchema` | No | Empty object schema |
|
||||
| `setRuntime` | `(runtime: PluginRuntime) => void` | No | — |
|
||||
| `registerCliMetadata` | `(api: OpenClawPluginApi) => void` | No | — |
|
||||
| `registerFull` | `(api: OpenClawPluginApi) => void` | No | — |
|
||||
|
||||
- `setRuntime` is called during registration so you can store the runtime reference
|
||||
(typically via `createPluginRuntimeStore`). It is skipped during CLI metadata
|
||||
capture.
|
||||
- `registerCliMetadata` runs during both `api.registrationMode === "cli-metadata"`
|
||||
and `api.registrationMode === "full"`.
|
||||
Use it as the canonical place for channel-owned CLI descriptors so root help
|
||||
stays non-activating while normal CLI command registration remains compatible
|
||||
with full plugin loads.
|
||||
- `registerFull` only runs when `api.registrationMode === "full"`. It is skipped
|
||||
during setup-only loading.
|
||||
- Like `definePluginEntry`, `configSchema` can be a lazy factory and OpenClaw
|
||||
memoizes the resolved schema on first access.
|
||||
- For plugin-owned root CLI commands, prefer `api.registerCli(..., { descriptors: [...] })`
|
||||
when you want the command to stay lazy-loaded without disappearing from the
|
||||
root CLI parse tree. For channel plugins, prefer registering those descriptors
|
||||
from `registerCliMetadata(...)` and keep `registerFull(...)` focused on runtime-only work.
|
||||
- If `registerFull(...)` also registers gateway RPC methods, keep them on a
|
||||
plugin-specific prefix. Reserved core admin namespaces (`config.*`,
|
||||
`exec.approvals.*`, `wizard.*`, `update.*`) are always coerced to
|
||||
`operator.admin`.
|
||||
|
||||
## `defineSetupPluginEntry`
|
||||
|
||||
**Import:** `openclaw/plugin-sdk/channel-core`
|
||||
|
||||
For the lightweight `setup-entry.ts` file. Returns just `{ plugin }` with no
|
||||
runtime or CLI wiring.
|
||||
|
||||
```typescript
|
||||
import { defineSetupPluginEntry } from "openclaw/plugin-sdk/channel-core";
|
||||
|
||||
export default defineSetupPluginEntry(myChannelPlugin);
|
||||
```
|
||||
|
||||
OpenClaw loads this instead of the full entry when a channel is disabled,
|
||||
unconfigured, or when deferred loading is enabled. See
|
||||
[Setup and Config](/plugins/sdk-setup#setup-entry) for when this matters.
|
||||
|
||||
In practice, pair `defineSetupPluginEntry(...)` with the narrow setup helper
|
||||
families:
|
||||
|
||||
- `openclaw/plugin-sdk/setup-runtime` for runtime-safe setup helpers such as
|
||||
import-safe setup patch adapters, lookup-note output,
|
||||
`promptResolvedAllowFrom`, `splitSetupEntries`, and delegated setup proxies
|
||||
- `openclaw/plugin-sdk/channel-setup` for optional-install setup surfaces
|
||||
- `openclaw/plugin-sdk/setup-tools` for setup/install CLI/archive/docs helpers
|
||||
|
||||
Keep heavy SDKs, CLI registration, and long-lived runtime services in the full
|
||||
entry.
|
||||
|
||||
Bundled workspace channels that split setup and runtime surfaces can use
|
||||
`defineBundledChannelSetupEntry(...)` from
|
||||
`openclaw/plugin-sdk/channel-entry-contract` instead. That contract lets the
|
||||
setup entry keep setup-safe plugin/secrets exports while still exposing a
|
||||
runtime setter:
|
||||
|
||||
```typescript
|
||||
import { defineBundledChannelSetupEntry } from "openclaw/plugin-sdk/channel-entry-contract";
|
||||
|
||||
export default defineBundledChannelSetupEntry({
|
||||
importMetaUrl: import.meta.url,
|
||||
plugin: {
|
||||
specifier: "./channel-plugin-api.js",
|
||||
exportName: "myChannelPlugin",
|
||||
},
|
||||
runtime: {
|
||||
specifier: "./runtime-api.js",
|
||||
exportName: "setMyChannelRuntime",
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Use that bundled contract only when setup flows truly need a lightweight runtime
|
||||
setter before the full channel entry loads.
|
||||
|
||||
## Registration mode
|
||||
|
||||
`api.registrationMode` tells your plugin how it was loaded:
|
||||
|
||||
| Mode | When | What to register |
|
||||
| ----------------- | --------------------------------- | ----------------------------------------------------------------------------------------- |
|
||||
| `"full"` | Normal gateway startup | Everything |
|
||||
| `"setup-only"` | Disabled/unconfigured channel | Channel registration only |
|
||||
| `"setup-runtime"` | Setup flow with runtime available | Channel registration plus only the lightweight runtime needed before the full entry loads |
|
||||
| `"cli-metadata"` | Root help / CLI metadata capture | CLI descriptors only |
|
||||
|
||||
`defineChannelPluginEntry` handles this split automatically. If you use
|
||||
`definePluginEntry` directly for a channel, check mode yourself:
|
||||
|
||||
```typescript
|
||||
register(api) {
|
||||
if (api.registrationMode === "cli-metadata" || api.registrationMode === "full") {
|
||||
api.registerCli(/* ... */);
|
||||
if (api.registrationMode === "cli-metadata") return;
|
||||
}
|
||||
|
||||
api.registerChannel({ plugin: myPlugin });
|
||||
if (api.registrationMode !== "full") return;
|
||||
|
||||
// Heavy runtime-only registrations
|
||||
api.registerService(/* ... */);
|
||||
}
|
||||
```
|
||||
|
||||
Treat `"setup-runtime"` as the window where setup-only startup surfaces must
|
||||
exist without re-entering the full bundled channel runtime. Good fits are
|
||||
channel registration, setup-safe HTTP routes, setup-safe gateway methods, and
|
||||
delegated setup helpers. Heavy background services, CLI registrars, and
|
||||
provider/client SDK bootstraps still belong in `"full"`.
|
||||
|
||||
For CLI registrars specifically:
|
||||
|
||||
- use `descriptors` when the registrar owns one or more root commands and you
|
||||
want OpenClaw to lazy-load the real CLI module on first invocation
|
||||
- make sure those descriptors cover every top-level command root exposed by the
|
||||
registrar
|
||||
- use `commands` alone only for eager compatibility paths
|
||||
|
||||
## Plugin shapes
|
||||
|
||||
OpenClaw classifies loaded plugins by their registration behavior:
|
||||
|
||||
| Shape | Description |
|
||||
| --------------------- | -------------------------------------------------- |
|
||||
| **plain-capability** | One capability type (e.g. provider-only) |
|
||||
| **hybrid-capability** | Multiple capability types (e.g. provider + speech) |
|
||||
| **hook-only** | Only hooks, no capabilities |
|
||||
| **non-capability** | Tools/commands/services but no capabilities |
|
||||
|
||||
Use `openclaw plugins inspect <id>` to see a plugin's shape.
|
||||
|
||||
## Related
|
||||
|
||||
- [SDK Overview](/plugins/sdk-overview) — registration API and subpath reference
|
||||
- [Runtime Helpers](/plugins/sdk-runtime) — `api.runtime` and `createPluginRuntimeStore`
|
||||
- [Setup and Config](/plugins/sdk-setup) — manifest, setup entry, deferred loading
|
||||
- [Channel Plugins](/plugins/sdk-channel-plugins) — building the `ChannelPlugin` object
|
||||
- [Provider Plugins](/plugins/sdk-provider-plugins) — provider registration and hooks
|
||||
404
openclaw/docs/plugins/sdk-migration.md
Normal file
404
openclaw/docs/plugins/sdk-migration.md
Normal file
|
|
@ -0,0 +1,404 @@
|
|||
---
|
||||
title: "Plugin SDK Migration"
|
||||
sidebarTitle: "Migrate to SDK"
|
||||
summary: "Migrate from the legacy backwards-compatibility layer to the modern plugin SDK"
|
||||
read_when:
|
||||
- You see the OPENCLAW_PLUGIN_SDK_COMPAT_DEPRECATED warning
|
||||
- You see the OPENCLAW_EXTENSION_API_DEPRECATED warning
|
||||
- You are updating a plugin to the modern plugin architecture
|
||||
- You maintain an external OpenClaw plugin
|
||||
---
|
||||
|
||||
# Plugin SDK Migration
|
||||
|
||||
OpenClaw has moved from a broad backwards-compatibility layer to a modern plugin
|
||||
architecture with focused, documented imports. If your plugin was built before
|
||||
the new architecture, this guide helps you migrate.
|
||||
|
||||
## What is changing
|
||||
|
||||
The old plugin system provided two wide-open surfaces that let plugins import
|
||||
anything they needed from a single entry point:
|
||||
|
||||
- **`openclaw/plugin-sdk/compat`** — a single import that re-exported dozens of
|
||||
helpers. It was introduced to keep older hook-based plugins working while the
|
||||
new plugin architecture was being built.
|
||||
- **`openclaw/extension-api`** — a bridge that gave plugins direct access to
|
||||
host-side helpers like the embedded agent runner.
|
||||
|
||||
Both surfaces are now **deprecated**. They still work at runtime, but new
|
||||
plugins must not use them, and existing plugins should migrate before the next
|
||||
major release removes them.
|
||||
|
||||
<Warning>
|
||||
The backwards-compatibility layer will be removed in a future major release.
|
||||
Plugins that still import from these surfaces will break when that happens.
|
||||
</Warning>
|
||||
|
||||
## Why this changed
|
||||
|
||||
The old approach caused problems:
|
||||
|
||||
- **Slow startup** — importing one helper loaded dozens of unrelated modules
|
||||
- **Circular dependencies** — broad re-exports made it easy to create import cycles
|
||||
- **Unclear API surface** — no way to tell which exports were stable vs internal
|
||||
|
||||
The modern plugin SDK fixes this: each import path (`openclaw/plugin-sdk/\<subpath\>`)
|
||||
is a small, self-contained module with a clear purpose and documented contract.
|
||||
|
||||
Legacy provider convenience seams for bundled channels are also gone. Imports
|
||||
such as `openclaw/plugin-sdk/slack`, `openclaw/plugin-sdk/discord`,
|
||||
`openclaw/plugin-sdk/signal`, `openclaw/plugin-sdk/whatsapp`,
|
||||
channel-branded helper seams, and
|
||||
`openclaw/plugin-sdk/telegram-core` were private mono-repo shortcuts, not
|
||||
stable plugin contracts. Use narrow generic SDK subpaths instead. Inside the
|
||||
bundled plugin workspace, keep provider-owned helpers in that plugin's own
|
||||
`api.ts` or `runtime-api.ts`.
|
||||
|
||||
Current bundled provider examples:
|
||||
|
||||
- Anthropic keeps Claude-specific stream helpers in its own `api.ts` /
|
||||
`contract-api.ts` seam
|
||||
- OpenAI keeps provider builders, default-model helpers, and realtime provider
|
||||
builders in its own `api.ts`
|
||||
- OpenRouter keeps provider builder and onboarding/config helpers in its own
|
||||
`api.ts`
|
||||
|
||||
## How to migrate
|
||||
|
||||
<Steps>
|
||||
<Step title="Migrate approval-native handlers to capability facts">
|
||||
Approval-capable channel plugins now expose native approval behavior through
|
||||
`approvalCapability.nativeRuntime` plus the shared runtime-context registry.
|
||||
|
||||
Key changes:
|
||||
|
||||
- Replace `approvalCapability.handler.loadRuntime(...)` with
|
||||
`approvalCapability.nativeRuntime`
|
||||
- Move approval-specific auth/delivery off legacy `plugin.auth` /
|
||||
`plugin.approvals` wiring and onto `approvalCapability`
|
||||
- `ChannelPlugin.approvals` has been removed from the public channel-plugin
|
||||
contract; move delivery/native/render fields onto `approvalCapability`
|
||||
- `plugin.auth` remains for channel login/logout flows only; approval auth
|
||||
hooks there are no longer read by core
|
||||
- Register channel-owned runtime objects such as clients, tokens, or Bolt
|
||||
apps through `openclaw/plugin-sdk/channel-runtime-context`
|
||||
- Do not send plugin-owned reroute notices from native approval handlers;
|
||||
core now owns routed-elsewhere notices from actual delivery results
|
||||
- When passing `channelRuntime` into `createChannelManager(...)`, provide a
|
||||
real `createPluginRuntime().channel` surface. Partial stubs are rejected.
|
||||
|
||||
See `/plugins/sdk-channel-plugins` for the current approval capability
|
||||
layout.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Audit Windows wrapper fallback behavior">
|
||||
If your plugin uses `openclaw/plugin-sdk/windows-spawn`, unresolved Windows
|
||||
`.cmd`/`.bat` wrappers now fail closed unless you explicitly pass
|
||||
`allowShellFallback: true`.
|
||||
|
||||
```typescript
|
||||
// Before
|
||||
const program = applyWindowsSpawnProgramPolicy({ candidate });
|
||||
|
||||
// After
|
||||
const program = applyWindowsSpawnProgramPolicy({
|
||||
candidate,
|
||||
// Only set this for trusted compatibility callers that intentionally
|
||||
// accept shell-mediated fallback.
|
||||
allowShellFallback: true,
|
||||
});
|
||||
```
|
||||
|
||||
If your caller does not intentionally rely on shell fallback, do not set
|
||||
`allowShellFallback` and handle the thrown error instead.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Find deprecated imports">
|
||||
Search your plugin for imports from either deprecated surface:
|
||||
|
||||
```bash
|
||||
grep -r "plugin-sdk/compat" my-plugin/
|
||||
grep -r "openclaw/extension-api" my-plugin/
|
||||
```
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Replace with focused imports">
|
||||
Each export from the old surface maps to a specific modern import path:
|
||||
|
||||
```typescript
|
||||
// Before (deprecated backwards-compatibility layer)
|
||||
import {
|
||||
createChannelReplyPipeline,
|
||||
createPluginRuntimeStore,
|
||||
resolveControlCommandGate,
|
||||
} from "openclaw/plugin-sdk/compat";
|
||||
|
||||
// After (modern focused imports)
|
||||
import { createChannelReplyPipeline } from "openclaw/plugin-sdk/channel-reply-pipeline";
|
||||
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
|
||||
import { resolveControlCommandGate } from "openclaw/plugin-sdk/command-auth";
|
||||
```
|
||||
|
||||
For host-side helpers, use the injected plugin runtime instead of importing
|
||||
directly:
|
||||
|
||||
```typescript
|
||||
// Before (deprecated extension-api bridge)
|
||||
import { runEmbeddedPiAgent } from "openclaw/extension-api";
|
||||
const result = await runEmbeddedPiAgent({ sessionId, prompt });
|
||||
|
||||
// After (injected runtime)
|
||||
const result = await api.runtime.agent.runEmbeddedPiAgent({ sessionId, prompt });
|
||||
```
|
||||
|
||||
The same pattern applies to other legacy bridge helpers:
|
||||
|
||||
| Old import | Modern equivalent |
|
||||
| --- | --- |
|
||||
| `resolveAgentDir` | `api.runtime.agent.resolveAgentDir` |
|
||||
| `resolveAgentWorkspaceDir` | `api.runtime.agent.resolveAgentWorkspaceDir` |
|
||||
| `resolveAgentIdentity` | `api.runtime.agent.resolveAgentIdentity` |
|
||||
| `resolveThinkingDefault` | `api.runtime.agent.resolveThinkingDefault` |
|
||||
| `resolveAgentTimeoutMs` | `api.runtime.agent.resolveAgentTimeoutMs` |
|
||||
| `ensureAgentWorkspace` | `api.runtime.agent.ensureAgentWorkspace` |
|
||||
| session store helpers | `api.runtime.agent.session.*` |
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Build and test">
|
||||
```bash
|
||||
pnpm build
|
||||
pnpm test -- my-plugin/
|
||||
```
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Import path reference
|
||||
|
||||
<Accordion title="Common import path table">
|
||||
| Import path | Purpose | Key exports |
|
||||
| --- | --- | --- |
|
||||
| `plugin-sdk/plugin-entry` | Canonical plugin entry helper | `definePluginEntry` |
|
||||
| `plugin-sdk/core` | Legacy umbrella re-export for channel entry definitions/builders | `defineChannelPluginEntry`, `createChatChannelPlugin` |
|
||||
| `plugin-sdk/config-schema` | Root config schema export | `OpenClawSchema` |
|
||||
| `plugin-sdk/provider-entry` | Single-provider entry helper | `defineSingleProviderPluginEntry` |
|
||||
| `plugin-sdk/channel-core` | Focused channel entry definitions and builders | `defineChannelPluginEntry`, `defineSetupPluginEntry`, `createChatChannelPlugin`, `createChannelPluginBase` |
|
||||
| `plugin-sdk/setup` | Shared setup wizard helpers | Allowlist prompts, setup status builders |
|
||||
| `plugin-sdk/setup-runtime` | Setup-time runtime helpers | Import-safe setup patch adapters, lookup-note helpers, `promptResolvedAllowFrom`, `splitSetupEntries`, delegated setup proxies |
|
||||
| `plugin-sdk/setup-adapter-runtime` | Setup adapter helpers | `createEnvPatchedAccountSetupAdapter` |
|
||||
| `plugin-sdk/setup-tools` | Setup tooling helpers | `formatCliCommand`, `detectBinary`, `extractArchive`, `resolveBrewExecutable`, `formatDocsLink`, `CONFIG_DIR` |
|
||||
| `plugin-sdk/account-core` | Multi-account helpers | Account list/config/action-gate helpers |
|
||||
| `plugin-sdk/account-id` | Account-id helpers | `DEFAULT_ACCOUNT_ID`, account-id normalization |
|
||||
| `plugin-sdk/account-resolution` | Account lookup helpers | Account lookup + default-fallback helpers |
|
||||
| `plugin-sdk/account-helpers` | Narrow account helpers | Account list/account-action helpers |
|
||||
| `plugin-sdk/channel-setup` | Setup wizard adapters | `createOptionalChannelSetupSurface`, `createOptionalChannelSetupAdapter`, `createOptionalChannelSetupWizard`, plus `DEFAULT_ACCOUNT_ID`, `createTopLevelChannelDmPolicy`, `setSetupChannelEnabled`, `splitSetupEntries` |
|
||||
| `plugin-sdk/channel-pairing` | DM pairing primitives | `createChannelPairingController` |
|
||||
| `plugin-sdk/channel-reply-pipeline` | Reply prefix + typing wiring | `createChannelReplyPipeline` |
|
||||
| `plugin-sdk/channel-config-helpers` | Config adapter factories | `createHybridChannelConfigAdapter` |
|
||||
| `plugin-sdk/channel-config-schema` | Config schema builders | Channel config schema types |
|
||||
| `plugin-sdk/telegram-command-config` | Telegram command config helpers | Command-name normalization, description trimming, duplicate/conflict validation |
|
||||
| `plugin-sdk/channel-policy` | Group/DM policy resolution | `resolveChannelGroupRequireMention` |
|
||||
| `plugin-sdk/channel-lifecycle` | Account status tracking | `createAccountStatusSink` |
|
||||
| `plugin-sdk/inbound-envelope` | Inbound envelope helpers | Shared route + envelope builder helpers |
|
||||
| `plugin-sdk/inbound-reply-dispatch` | Inbound reply helpers | Shared record-and-dispatch helpers |
|
||||
| `plugin-sdk/messaging-targets` | Messaging target parsing | Target parsing/matching helpers |
|
||||
| `plugin-sdk/outbound-media` | Outbound media helpers | Shared outbound media loading |
|
||||
| `plugin-sdk/outbound-runtime` | Outbound runtime helpers | Outbound identity/send delegate helpers |
|
||||
| `plugin-sdk/thread-bindings-runtime` | Thread-binding helpers | Thread-binding lifecycle and adapter helpers |
|
||||
| `plugin-sdk/agent-media-payload` | Legacy media payload helpers | Agent media payload builder for legacy field layouts |
|
||||
| `plugin-sdk/channel-runtime` | Deprecated compatibility shim | Legacy channel runtime utilities only |
|
||||
| `plugin-sdk/channel-send-result` | Send result types | Reply result types |
|
||||
| `plugin-sdk/runtime-store` | Persistent plugin storage | `createPluginRuntimeStore` |
|
||||
| `plugin-sdk/runtime` | Broad runtime helpers | Runtime/logging/backup/plugin-install helpers |
|
||||
| `plugin-sdk/runtime-env` | Narrow runtime env helpers | Logger/runtime env, timeout, retry, and backoff helpers |
|
||||
| `plugin-sdk/plugin-runtime` | Shared plugin runtime helpers | Plugin commands/hooks/http/interactive helpers |
|
||||
| `plugin-sdk/hook-runtime` | Hook pipeline helpers | Shared webhook/internal hook pipeline helpers |
|
||||
| `plugin-sdk/lazy-runtime` | Lazy runtime helpers | `createLazyRuntimeModule`, `createLazyRuntimeMethod`, `createLazyRuntimeMethodBinder`, `createLazyRuntimeNamedExport`, `createLazyRuntimeSurface` |
|
||||
| `plugin-sdk/process-runtime` | Process helpers | Shared exec helpers |
|
||||
| `plugin-sdk/cli-runtime` | CLI runtime helpers | Command formatting, waits, version helpers |
|
||||
| `plugin-sdk/gateway-runtime` | Gateway helpers | Gateway client and channel-status patch helpers |
|
||||
| `plugin-sdk/config-runtime` | Config helpers | Config load/write helpers |
|
||||
| `plugin-sdk/telegram-command-config` | Telegram command helpers | Fallback-stable Telegram command validation helpers when the bundled Telegram contract surface is unavailable |
|
||||
| `plugin-sdk/approval-runtime` | Approval prompt helpers | Exec/plugin approval payload, approval capability/profile helpers, native approval routing/runtime helpers |
|
||||
| `plugin-sdk/approval-auth-runtime` | Approval auth helpers | Approver resolution, same-chat action auth |
|
||||
| `plugin-sdk/approval-client-runtime` | Approval client helpers | Native exec approval profile/filter helpers |
|
||||
| `plugin-sdk/approval-delivery-runtime` | Approval delivery helpers | Native approval capability/delivery adapters |
|
||||
| `plugin-sdk/approval-gateway-runtime` | Approval gateway helpers | Shared approval gateway-resolution helper |
|
||||
| `plugin-sdk/approval-handler-adapter-runtime` | Approval adapter helpers | Lightweight native approval adapter loading helpers for hot channel entrypoints |
|
||||
| `plugin-sdk/approval-handler-runtime` | Approval handler helpers | Broader approval handler runtime helpers; prefer the narrower adapter/gateway seams when they are enough |
|
||||
| `plugin-sdk/approval-native-runtime` | Approval target helpers | Native approval target/account binding helpers |
|
||||
| `plugin-sdk/approval-reply-runtime` | Approval reply helpers | Exec/plugin approval reply payload helpers |
|
||||
| `plugin-sdk/channel-runtime-context` | Channel runtime-context helpers | Generic channel runtime-context register/get/watch helpers |
|
||||
| `plugin-sdk/security-runtime` | Security helpers | Shared trust, DM gating, external-content, and secret-collection helpers |
|
||||
| `plugin-sdk/ssrf-policy` | SSRF policy helpers | Host allowlist and private-network policy helpers |
|
||||
| `plugin-sdk/ssrf-runtime` | SSRF runtime helpers | Pinned-dispatcher, guarded fetch, SSRF policy helpers |
|
||||
| `plugin-sdk/collection-runtime` | Bounded cache helpers | `pruneMapToMaxSize` |
|
||||
| `plugin-sdk/diagnostic-runtime` | Diagnostic gating helpers | `isDiagnosticFlagEnabled`, `isDiagnosticsEnabled` |
|
||||
| `plugin-sdk/error-runtime` | Error formatting helpers | `formatUncaughtError`, `isApprovalNotFoundError`, error graph helpers |
|
||||
| `plugin-sdk/fetch-runtime` | Wrapped fetch/proxy helpers | `resolveFetch`, proxy helpers |
|
||||
| `plugin-sdk/host-runtime` | Host normalization helpers | `normalizeHostname`, `normalizeScpRemoteHost` |
|
||||
| `plugin-sdk/retry-runtime` | Retry helpers | `RetryConfig`, `retryAsync`, policy runners |
|
||||
| `plugin-sdk/allow-from` | Allowlist formatting | `formatAllowFromLowercase` |
|
||||
| `plugin-sdk/allowlist-resolution` | Allowlist input mapping | `mapAllowlistResolutionInputs` |
|
||||
| `plugin-sdk/command-auth` | Command gating and command-surface helpers | `resolveControlCommandGate`, sender-authorization helpers, command registry helpers |
|
||||
| `plugin-sdk/command-status` | Command status/help renderers | `buildCommandsMessage`, `buildCommandsMessagePaginated`, `buildHelpMessage` |
|
||||
| `plugin-sdk/secret-input` | Secret input parsing | Secret input helpers |
|
||||
| `plugin-sdk/webhook-ingress` | Webhook request helpers | Webhook target utilities |
|
||||
| `plugin-sdk/webhook-request-guards` | Webhook body guard helpers | Request body read/limit helpers |
|
||||
| `plugin-sdk/reply-runtime` | Shared reply runtime | Inbound dispatch, heartbeat, reply planner, chunking |
|
||||
| `plugin-sdk/reply-dispatch-runtime` | Narrow reply dispatch helpers | Finalize + provider dispatch helpers |
|
||||
| `plugin-sdk/reply-history` | Reply-history helpers | `buildHistoryContext`, `buildPendingHistoryContextFromMap`, `recordPendingHistoryEntry`, `clearHistoryEntriesIfEnabled` |
|
||||
| `plugin-sdk/reply-reference` | Reply reference planning | `createReplyReferencePlanner` |
|
||||
| `plugin-sdk/reply-chunking` | Reply chunk helpers | Text/markdown chunking helpers |
|
||||
| `plugin-sdk/session-store-runtime` | Session store helpers | Store path + updated-at helpers |
|
||||
| `plugin-sdk/state-paths` | State path helpers | State and OAuth dir helpers |
|
||||
| `plugin-sdk/routing` | Routing/session-key helpers | `resolveAgentRoute`, `buildAgentSessionKey`, `resolveDefaultAgentBoundAccountId`, session-key normalization helpers |
|
||||
| `plugin-sdk/status-helpers` | Channel status helpers | Channel/account status summary builders, runtime-state defaults, issue metadata helpers |
|
||||
| `plugin-sdk/target-resolver-runtime` | Target resolver helpers | Shared target resolver helpers |
|
||||
| `plugin-sdk/string-normalization-runtime` | String normalization helpers | Slug/string normalization helpers |
|
||||
| `plugin-sdk/request-url` | Request URL helpers | Extract string URLs from request-like inputs |
|
||||
| `plugin-sdk/run-command` | Timed command helpers | Timed command runner with normalized stdout/stderr |
|
||||
| `plugin-sdk/param-readers` | Param readers | Common tool/CLI param readers |
|
||||
| `plugin-sdk/tool-payload` | Tool payload extraction | Extract normalized payloads from tool result objects |
|
||||
| `plugin-sdk/tool-send` | Tool send extraction | Extract canonical send target fields from tool args |
|
||||
| `plugin-sdk/temp-path` | Temp path helpers | Shared temp-download path helpers |
|
||||
| `plugin-sdk/logging-core` | Logging helpers | Subsystem logger and redaction helpers |
|
||||
| `plugin-sdk/markdown-table-runtime` | Markdown-table helpers | Markdown table mode helpers |
|
||||
| `plugin-sdk/reply-payload` | Message reply types | Reply payload types |
|
||||
| `plugin-sdk/provider-setup` | Curated local/self-hosted provider setup helpers | Self-hosted provider discovery/config helpers |
|
||||
| `plugin-sdk/self-hosted-provider-setup` | Focused OpenAI-compatible self-hosted provider setup helpers | Same self-hosted provider discovery/config helpers |
|
||||
| `plugin-sdk/provider-auth-runtime` | Provider runtime auth helpers | Runtime API-key resolution helpers |
|
||||
| `plugin-sdk/provider-auth-api-key` | Provider API-key setup helpers | API-key onboarding/profile-write helpers |
|
||||
| `plugin-sdk/provider-auth-result` | Provider auth-result helpers | Standard OAuth auth-result builder |
|
||||
| `plugin-sdk/provider-auth-login` | Provider interactive login helpers | Shared interactive login helpers |
|
||||
| `plugin-sdk/provider-env-vars` | Provider env-var helpers | Provider auth env-var lookup helpers |
|
||||
| `plugin-sdk/provider-model-shared` | Shared provider model/replay helpers | `ProviderReplayFamily`, `buildProviderReplayFamilyHooks`, `normalizeModelCompat`, shared replay-policy builders, provider-endpoint helpers, and model-id normalization helpers |
|
||||
| `plugin-sdk/provider-catalog-shared` | Shared provider catalog helpers | `findCatalogTemplate`, `buildSingleProviderApiKeyCatalog`, `supportsNativeStreamingUsageCompat`, `applyProviderNativeStreamingUsageCompat` |
|
||||
| `plugin-sdk/provider-onboard` | Provider onboarding patches | Onboarding config helpers |
|
||||
| `plugin-sdk/provider-http` | Provider HTTP helpers | Generic provider HTTP/endpoint capability helpers |
|
||||
| `plugin-sdk/provider-web-fetch` | Provider web-fetch helpers | Web-fetch provider registration/cache helpers |
|
||||
| `plugin-sdk/provider-web-search-config-contract` | Provider web-search config helpers | Narrow web-search config/credential helpers for providers that do not need plugin-enable wiring |
|
||||
| `plugin-sdk/provider-web-search-contract` | Provider web-search contract helpers | Narrow web-search config/credential contract helpers such as `createWebSearchProviderContractFields`, `enablePluginInConfig`, `resolveProviderWebSearchPluginConfig`, and scoped credential setters/getters |
|
||||
| `plugin-sdk/provider-web-search` | Provider web-search helpers | Web-search provider registration/cache/runtime helpers |
|
||||
| `plugin-sdk/provider-tools` | Provider tool/schema compat helpers | `ProviderToolCompatFamily`, `buildProviderToolCompatFamilyHooks`, Gemini schema cleanup + diagnostics, and xAI compat helpers such as `resolveXaiModelCompatPatch` / `applyXaiModelCompat` |
|
||||
| `plugin-sdk/provider-usage` | Provider usage helpers | `fetchClaudeUsage`, `fetchGeminiUsage`, `fetchGithubCopilotUsage`, and other provider usage helpers |
|
||||
| `plugin-sdk/provider-stream` | Provider stream wrapper helpers | `ProviderStreamFamily`, `buildProviderStreamFamilyHooks`, `composeProviderStreamWrappers`, stream wrapper types, and shared Anthropic/Bedrock/Google/Kilocode/Moonshot/OpenAI/OpenRouter/Z.A.I/MiniMax/Copilot wrapper helpers |
|
||||
| `plugin-sdk/provider-transport-runtime` | Provider transport helpers | Native provider transport helpers such as guarded fetch, transport message transforms, and writable transport event streams |
|
||||
| `plugin-sdk/keyed-async-queue` | Ordered async queue | `KeyedAsyncQueue` |
|
||||
| `plugin-sdk/media-runtime` | Shared media helpers | Media fetch/transform/store helpers plus media payload builders |
|
||||
| `plugin-sdk/media-generation-runtime` | Shared media-generation helpers | Shared failover helpers, candidate selection, and missing-model messaging for image/video/music generation |
|
||||
| `plugin-sdk/media-understanding` | Media-understanding helpers | Media understanding provider types plus provider-facing image/audio helper exports |
|
||||
| `plugin-sdk/text-runtime` | Shared text helpers | Assistant-visible-text stripping, markdown render/chunking/table helpers, redaction helpers, directive-tag helpers, safe-text utilities, and related text/logging helpers |
|
||||
| `plugin-sdk/text-chunking` | Text chunking helpers | Outbound text chunking helper |
|
||||
| `plugin-sdk/speech` | Speech helpers | Speech provider types plus provider-facing directive, registry, and validation helpers |
|
||||
| `plugin-sdk/speech-core` | Shared speech core | Speech provider types, registry, directives, normalization |
|
||||
| `plugin-sdk/realtime-transcription` | Realtime transcription helpers | Provider types and registry helpers |
|
||||
| `plugin-sdk/realtime-voice` | Realtime voice helpers | Provider types and registry helpers |
|
||||
| `plugin-sdk/image-generation-core` | Shared image-generation core | Image-generation types, failover, auth, and registry helpers |
|
||||
| `plugin-sdk/music-generation` | Music-generation helpers | Music-generation provider/request/result types |
|
||||
| `plugin-sdk/music-generation-core` | Shared music-generation core | Music-generation types, failover helpers, provider lookup, and model-ref parsing |
|
||||
| `plugin-sdk/video-generation` | Video-generation helpers | Video-generation provider/request/result types |
|
||||
| `plugin-sdk/video-generation-core` | Shared video-generation core | Video-generation types, failover helpers, provider lookup, and model-ref parsing |
|
||||
| `plugin-sdk/interactive-runtime` | Interactive reply helpers | Interactive reply payload normalization/reduction |
|
||||
| `plugin-sdk/channel-config-primitives` | Channel config primitives | Narrow channel config-schema primitives |
|
||||
| `plugin-sdk/channel-config-writes` | Channel config-write helpers | Channel config-write authorization helpers |
|
||||
| `plugin-sdk/channel-plugin-common` | Shared channel prelude | Shared channel plugin prelude exports |
|
||||
| `plugin-sdk/channel-status` | Channel status helpers | Shared channel status snapshot/summary helpers |
|
||||
| `plugin-sdk/allowlist-config-edit` | Allowlist config helpers | Allowlist config edit/read helpers |
|
||||
| `plugin-sdk/group-access` | Group access helpers | Shared group-access decision helpers |
|
||||
| `plugin-sdk/direct-dm` | Direct-DM helpers | Shared direct-DM auth/guard helpers |
|
||||
| `plugin-sdk/extension-shared` | Shared extension helpers | Passive-channel/status and ambient proxy helper primitives |
|
||||
| `plugin-sdk/webhook-targets` | Webhook target helpers | Webhook target registry and route-install helpers |
|
||||
| `plugin-sdk/webhook-path` | Webhook path helpers | Webhook path normalization helpers |
|
||||
| `plugin-sdk/web-media` | Shared web media helpers | Remote/local media loading helpers |
|
||||
| `plugin-sdk/zod` | Zod re-export | Re-exported `zod` for plugin SDK consumers |
|
||||
| `plugin-sdk/memory-core` | Bundled memory-core helpers | Memory manager/config/file/CLI helper surface |
|
||||
| `plugin-sdk/memory-core-engine-runtime` | Memory engine runtime facade | Memory index/search runtime facade |
|
||||
| `plugin-sdk/memory-core-host-engine-foundation` | Memory host foundation engine | Memory host foundation engine exports |
|
||||
| `plugin-sdk/memory-core-host-engine-embeddings` | Memory host embedding engine | Memory embedding contracts, registry access, local provider, and generic batch/remote helpers; concrete remote providers live in their owning plugins |
|
||||
| `plugin-sdk/memory-core-host-engine-qmd` | Memory host QMD engine | Memory host QMD engine exports |
|
||||
| `plugin-sdk/memory-core-host-engine-storage` | Memory host storage engine | Memory host storage engine exports |
|
||||
| `plugin-sdk/memory-core-host-multimodal` | Memory host multimodal helpers | Memory host multimodal helpers |
|
||||
| `plugin-sdk/memory-core-host-query` | Memory host query helpers | Memory host query helpers |
|
||||
| `plugin-sdk/memory-core-host-secret` | Memory host secret helpers | Memory host secret helpers |
|
||||
| `plugin-sdk/memory-core-host-events` | Memory host event journal helpers | Memory host event journal helpers |
|
||||
| `plugin-sdk/memory-core-host-status` | Memory host status helpers | Memory host status helpers |
|
||||
| `plugin-sdk/memory-core-host-runtime-cli` | Memory host CLI runtime | Memory host CLI runtime helpers |
|
||||
| `plugin-sdk/memory-core-host-runtime-core` | Memory host core runtime | Memory host core runtime helpers |
|
||||
| `plugin-sdk/memory-core-host-runtime-files` | Memory host file/runtime helpers | Memory host file/runtime helpers |
|
||||
| `plugin-sdk/memory-host-core` | Memory host core runtime alias | Vendor-neutral alias for memory host core runtime helpers |
|
||||
| `plugin-sdk/memory-host-events` | Memory host event journal alias | Vendor-neutral alias for memory host event journal helpers |
|
||||
| `plugin-sdk/memory-host-files` | Memory host file/runtime alias | Vendor-neutral alias for memory host file/runtime helpers |
|
||||
| `plugin-sdk/memory-host-markdown` | Managed markdown helpers | Shared managed-markdown helpers for memory-adjacent plugins |
|
||||
| `plugin-sdk/memory-host-search` | Active memory search facade | Lazy active-memory search-manager runtime facade |
|
||||
| `plugin-sdk/memory-host-status` | Memory host status alias | Vendor-neutral alias for memory host status helpers |
|
||||
| `plugin-sdk/memory-lancedb` | Bundled memory-lancedb helpers | Memory-lancedb helper surface |
|
||||
| `plugin-sdk/testing` | Test utilities | Test helpers and mocks |
|
||||
</Accordion>
|
||||
|
||||
This table is intentionally the common migration subset, not the full SDK
|
||||
surface. The full list of 200+ entrypoints lives in
|
||||
`scripts/lib/plugin-sdk-entrypoints.json`.
|
||||
|
||||
That list still includes some bundled-plugin helper seams such as
|
||||
`plugin-sdk/feishu`, `plugin-sdk/feishu-setup`, `plugin-sdk/zalo`,
|
||||
`plugin-sdk/zalo-setup`, and `plugin-sdk/matrix*`. Those remain exported for
|
||||
bundled-plugin maintenance and compatibility, but they are intentionally
|
||||
omitted from the common migration table and are not the recommended target for
|
||||
new plugin code.
|
||||
|
||||
The same rule applies to other bundled-helper families such as:
|
||||
|
||||
- browser support helpers: `plugin-sdk/browser-cdp`, `plugin-sdk/browser-config-runtime`, `plugin-sdk/browser-config-support`, `plugin-sdk/browser-control-auth`, `plugin-sdk/browser-node-runtime`, `plugin-sdk/browser-profiles`, `plugin-sdk/browser-security-runtime`, `plugin-sdk/browser-setup-tools`, `plugin-sdk/browser-support`
|
||||
- Matrix: `plugin-sdk/matrix*`
|
||||
- LINE: `plugin-sdk/line*`
|
||||
- IRC: `plugin-sdk/irc*`
|
||||
- bundled helper/plugin surfaces like `plugin-sdk/googlechat`,
|
||||
`plugin-sdk/zalouser`, `plugin-sdk/bluebubbles*`,
|
||||
`plugin-sdk/mattermost*`, `plugin-sdk/msteams`,
|
||||
`plugin-sdk/nextcloud-talk`, `plugin-sdk/nostr`, `plugin-sdk/tlon`,
|
||||
`plugin-sdk/twitch`,
|
||||
`plugin-sdk/github-copilot-login`, `plugin-sdk/github-copilot-token`,
|
||||
`plugin-sdk/diagnostics-otel`, `plugin-sdk/diffs`, `plugin-sdk/llm-task`,
|
||||
`plugin-sdk/thread-ownership`, and `plugin-sdk/voice-call`
|
||||
|
||||
`plugin-sdk/github-copilot-token` currently exposes the narrow token-helper
|
||||
surface `DEFAULT_COPILOT_API_BASE_URL`,
|
||||
`deriveCopilotApiBaseUrlFromToken`, and `resolveCopilotApiToken`.
|
||||
|
||||
Use the narrowest import that matches the job. If you cannot find an export,
|
||||
check the source at `src/plugin-sdk/` or ask in Discord.
|
||||
|
||||
## Removal timeline
|
||||
|
||||
| When | What happens |
|
||||
| ---------------------- | ----------------------------------------------------------------------- |
|
||||
| **Now** | Deprecated surfaces emit runtime warnings |
|
||||
| **Next major release** | Deprecated surfaces will be removed; plugins still using them will fail |
|
||||
|
||||
All core plugins have already been migrated. External plugins should migrate
|
||||
before the next major release.
|
||||
|
||||
## Suppressing the warnings temporarily
|
||||
|
||||
Set these environment variables while you work on migrating:
|
||||
|
||||
```bash
|
||||
OPENCLAW_SUPPRESS_PLUGIN_SDK_COMPAT_WARNING=1 openclaw gateway run
|
||||
OPENCLAW_SUPPRESS_EXTENSION_API_WARNING=1 openclaw gateway run
|
||||
```
|
||||
|
||||
This is a temporary escape hatch, not a permanent solution.
|
||||
|
||||
## Related
|
||||
|
||||
- [Getting Started](/plugins/building-plugins) — build your first plugin
|
||||
- [SDK Overview](/plugins/sdk-overview) — full subpath import reference
|
||||
- [Channel Plugins](/plugins/sdk-channel-plugins) — building channel plugins
|
||||
- [Provider Plugins](/plugins/sdk-provider-plugins) — building provider plugins
|
||||
- [Plugin Internals](/plugins/architecture) — architecture deep dive
|
||||
- [Plugin Manifest](/plugins/manifest) — manifest schema reference
|
||||
523
openclaw/docs/plugins/sdk-overview.md
Normal file
523
openclaw/docs/plugins/sdk-overview.md
Normal file
|
|
@ -0,0 +1,523 @@
|
|||
---
|
||||
title: "Plugin SDK Overview"
|
||||
sidebarTitle: "SDK Overview"
|
||||
summary: "Import map, registration API reference, and SDK architecture"
|
||||
read_when:
|
||||
- You need to know which SDK subpath to import from
|
||||
- You want a reference for all registration methods on OpenClawPluginApi
|
||||
- You are looking up a specific SDK export
|
||||
---
|
||||
|
||||
# Plugin SDK Overview
|
||||
|
||||
The plugin SDK is the typed contract between plugins and core. This page is the
|
||||
reference for **what to import** and **what you can register**.
|
||||
|
||||
<Tip>
|
||||
**Looking for a how-to guide?**
|
||||
- First plugin? Start with [Getting Started](/plugins/building-plugins)
|
||||
- Channel plugin? See [Channel Plugins](/plugins/sdk-channel-plugins)
|
||||
- Provider plugin? See [Provider Plugins](/plugins/sdk-provider-plugins)
|
||||
</Tip>
|
||||
|
||||
## Import convention
|
||||
|
||||
Always import from a specific subpath:
|
||||
|
||||
```typescript
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { defineChannelPluginEntry } from "openclaw/plugin-sdk/channel-core";
|
||||
```
|
||||
|
||||
Each subpath is a small, self-contained module. This keeps startup fast and
|
||||
prevents circular dependency issues. For channel-specific entry/build helpers,
|
||||
prefer `openclaw/plugin-sdk/channel-core`; keep `openclaw/plugin-sdk/core` for
|
||||
the broader umbrella surface and shared helpers such as
|
||||
`buildChannelConfigSchema`.
|
||||
|
||||
Do not add or depend on provider-named convenience seams such as
|
||||
`openclaw/plugin-sdk/slack`, `openclaw/plugin-sdk/discord`,
|
||||
`openclaw/plugin-sdk/signal`, `openclaw/plugin-sdk/whatsapp`, or
|
||||
channel-branded helper seams. Bundled plugins should compose generic
|
||||
SDK subpaths inside their own `api.ts` or `runtime-api.ts` barrels, and core
|
||||
should either use those plugin-local barrels or add a narrow generic SDK
|
||||
contract when the need is truly cross-channel.
|
||||
|
||||
The generated export map still contains a small set of bundled-plugin helper
|
||||
seams such as `plugin-sdk/feishu`, `plugin-sdk/feishu-setup`,
|
||||
`plugin-sdk/zalo`, `plugin-sdk/zalo-setup`, and `plugin-sdk/matrix*`. Those
|
||||
subpaths exist for bundled-plugin maintenance and compatibility only; they are
|
||||
intentionally omitted from the common table below and are not the recommended
|
||||
import path for new third-party plugins.
|
||||
|
||||
## Subpath reference
|
||||
|
||||
The most commonly used subpaths, grouped by purpose. The generated full list of
|
||||
200+ subpaths lives in `scripts/lib/plugin-sdk-entrypoints.json`.
|
||||
|
||||
Reserved bundled-plugin helper subpaths still appear in that generated list.
|
||||
Treat those as implementation detail/compatibility surfaces unless a doc page
|
||||
explicitly promotes one as public.
|
||||
|
||||
### Plugin entry
|
||||
|
||||
| Subpath | Key exports |
|
||||
| --------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `plugin-sdk/plugin-entry` | `definePluginEntry` |
|
||||
| `plugin-sdk/core` | `defineChannelPluginEntry`, `createChatChannelPlugin`, `createChannelPluginBase`, `defineSetupPluginEntry`, `buildChannelConfigSchema` |
|
||||
| `plugin-sdk/config-schema` | `OpenClawSchema` |
|
||||
| `plugin-sdk/provider-entry` | `defineSingleProviderPluginEntry` |
|
||||
|
||||
<AccordionGroup>
|
||||
<Accordion title="Channel subpaths">
|
||||
| Subpath | Key exports |
|
||||
| --- | --- |
|
||||
| `plugin-sdk/channel-core` | `defineChannelPluginEntry`, `defineSetupPluginEntry`, `createChatChannelPlugin`, `createChannelPluginBase` |
|
||||
| `plugin-sdk/config-schema` | Root `openclaw.json` Zod schema export (`OpenClawSchema`) |
|
||||
| `plugin-sdk/channel-setup` | `createOptionalChannelSetupSurface`, `createOptionalChannelSetupAdapter`, `createOptionalChannelSetupWizard`, plus `DEFAULT_ACCOUNT_ID`, `createTopLevelChannelDmPolicy`, `setSetupChannelEnabled`, `splitSetupEntries` |
|
||||
| `plugin-sdk/setup` | Shared setup wizard helpers, allowlist prompts, setup status builders |
|
||||
| `plugin-sdk/setup-runtime` | `createPatchedAccountSetupAdapter`, `createEnvPatchedAccountSetupAdapter`, `createSetupInputPresenceValidator`, `noteChannelLookupFailure`, `noteChannelLookupSummary`, `promptResolvedAllowFrom`, `splitSetupEntries`, `createAllowlistSetupWizardProxy`, `createDelegatedSetupWizardProxy` |
|
||||
| `plugin-sdk/setup-adapter-runtime` | `createEnvPatchedAccountSetupAdapter` |
|
||||
| `plugin-sdk/setup-tools` | `formatCliCommand`, `detectBinary`, `extractArchive`, `resolveBrewExecutable`, `formatDocsLink`, `CONFIG_DIR` |
|
||||
| `plugin-sdk/account-core` | Multi-account config/action-gate helpers, default-account fallback helpers |
|
||||
| `plugin-sdk/account-id` | `DEFAULT_ACCOUNT_ID`, account-id normalization helpers |
|
||||
| `plugin-sdk/account-resolution` | Account lookup + default-fallback helpers |
|
||||
| `plugin-sdk/account-helpers` | Narrow account-list/account-action helpers |
|
||||
| `plugin-sdk/channel-pairing` | `createChannelPairingController` |
|
||||
| `plugin-sdk/channel-reply-pipeline` | `createChannelReplyPipeline` |
|
||||
| `plugin-sdk/channel-config-helpers` | `createHybridChannelConfigAdapter` |
|
||||
| `plugin-sdk/channel-config-schema` | Channel config schema types |
|
||||
| `plugin-sdk/telegram-command-config` | Telegram custom-command normalization/validation helpers with bundled-contract fallback |
|
||||
| `plugin-sdk/command-gating` | Narrow command authorization gate helpers |
|
||||
| `plugin-sdk/channel-policy` | `resolveChannelGroupRequireMention` |
|
||||
| `plugin-sdk/channel-lifecycle` | `createAccountStatusSink` |
|
||||
| `plugin-sdk/inbound-envelope` | Shared inbound route + envelope builder helpers |
|
||||
| `plugin-sdk/inbound-reply-dispatch` | Shared inbound record-and-dispatch helpers |
|
||||
| `plugin-sdk/messaging-targets` | Target parsing/matching helpers |
|
||||
| `plugin-sdk/outbound-media` | Shared outbound media loading helpers |
|
||||
| `plugin-sdk/outbound-runtime` | Outbound identity/send delegate helpers |
|
||||
| `plugin-sdk/poll-runtime` | Narrow poll normalization helpers |
|
||||
| `plugin-sdk/thread-bindings-runtime` | Thread-binding lifecycle and adapter helpers |
|
||||
| `plugin-sdk/agent-media-payload` | Legacy agent media payload builder |
|
||||
| `plugin-sdk/conversation-runtime` | Conversation/thread binding, pairing, and configured-binding helpers |
|
||||
| `plugin-sdk/runtime-config-snapshot` | Runtime config snapshot helper |
|
||||
| `plugin-sdk/runtime-group-policy` | Runtime group-policy resolution helpers |
|
||||
| `plugin-sdk/channel-status` | Shared channel status snapshot/summary helpers |
|
||||
| `plugin-sdk/channel-config-primitives` | Narrow channel config-schema primitives |
|
||||
| `plugin-sdk/channel-config-writes` | Channel config-write authorization helpers |
|
||||
| `plugin-sdk/channel-plugin-common` | Shared channel plugin prelude exports |
|
||||
| `plugin-sdk/allowlist-config-edit` | Allowlist config edit/read helpers |
|
||||
| `plugin-sdk/group-access` | Shared group-access decision helpers |
|
||||
| `plugin-sdk/direct-dm` | Shared direct-DM auth/guard helpers |
|
||||
| `plugin-sdk/interactive-runtime` | Interactive reply payload normalization/reduction helpers |
|
||||
| `plugin-sdk/channel-inbound` | Compatibility barrel for inbound debounce, mention matching, mention-policy helpers, and envelope helpers |
|
||||
| `plugin-sdk/channel-mention-gating` | Narrow mention-policy helpers without the broader inbound runtime surface |
|
||||
| `plugin-sdk/channel-location` | Channel location context and formatting helpers |
|
||||
| `plugin-sdk/channel-logging` | Channel logging helpers for inbound drops and typing/ack failures |
|
||||
| `plugin-sdk/channel-send-result` | Reply result types |
|
||||
| `plugin-sdk/channel-actions` | `createMessageToolButtonsSchema`, `createMessageToolCardSchema` |
|
||||
| `plugin-sdk/channel-targets` | Target parsing/matching helpers |
|
||||
| `plugin-sdk/channel-contract` | Channel contract types |
|
||||
| `plugin-sdk/channel-feedback` | Feedback/reaction wiring |
|
||||
| `plugin-sdk/channel-secret-runtime` | Narrow secret-contract helpers such as `collectSimpleChannelFieldAssignments`, `getChannelSurface`, `pushAssignment`, and secret target types |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Provider subpaths">
|
||||
| Subpath | Key exports |
|
||||
| --- | --- |
|
||||
| `plugin-sdk/provider-entry` | `defineSingleProviderPluginEntry` |
|
||||
| `plugin-sdk/provider-setup` | Curated local/self-hosted provider setup helpers |
|
||||
| `plugin-sdk/self-hosted-provider-setup` | Focused OpenAI-compatible self-hosted provider setup helpers |
|
||||
| `plugin-sdk/cli-backend` | CLI backend defaults + watchdog constants |
|
||||
| `plugin-sdk/provider-auth-runtime` | Runtime API-key resolution helpers for provider plugins |
|
||||
| `plugin-sdk/provider-auth-api-key` | API-key onboarding/profile-write helpers such as `upsertApiKeyProfile` |
|
||||
| `plugin-sdk/provider-auth-result` | Standard OAuth auth-result builder |
|
||||
| `plugin-sdk/provider-auth-login` | Shared interactive login helpers for provider plugins |
|
||||
| `plugin-sdk/provider-env-vars` | Provider auth env-var lookup helpers |
|
||||
| `plugin-sdk/provider-auth` | `createProviderApiKeyAuthMethod`, `ensureApiKeyFromOptionEnvOrPrompt`, `upsertAuthProfile`, `upsertApiKeyProfile`, `writeOAuthCredentials` |
|
||||
| `plugin-sdk/provider-model-shared` | `ProviderReplayFamily`, `buildProviderReplayFamilyHooks`, `normalizeModelCompat`, shared replay-policy builders, provider-endpoint helpers, and model-id normalization helpers such as `normalizeNativeXaiModelId` |
|
||||
| `plugin-sdk/provider-catalog-shared` | `findCatalogTemplate`, `buildSingleProviderApiKeyCatalog`, `supportsNativeStreamingUsageCompat`, `applyProviderNativeStreamingUsageCompat` |
|
||||
| `plugin-sdk/provider-http` | Generic provider HTTP/endpoint capability helpers |
|
||||
| `plugin-sdk/provider-web-fetch-contract` | Narrow web-fetch config/selection contract helpers such as `enablePluginInConfig` and `WebFetchProviderPlugin` |
|
||||
| `plugin-sdk/provider-web-fetch` | Web-fetch provider registration/cache helpers |
|
||||
| `plugin-sdk/provider-web-search-config-contract` | Narrow web-search config/credential helpers for providers that do not need plugin-enable wiring |
|
||||
| `plugin-sdk/provider-web-search-contract` | Narrow web-search config/credential contract helpers such as `createWebSearchProviderContractFields`, `enablePluginInConfig`, `resolveProviderWebSearchPluginConfig`, and scoped credential setters/getters |
|
||||
| `plugin-sdk/provider-web-search` | Web-search provider registration/cache/runtime helpers |
|
||||
| `plugin-sdk/provider-tools` | `ProviderToolCompatFamily`, `buildProviderToolCompatFamilyHooks`, Gemini schema cleanup + diagnostics, and xAI compat helpers such as `resolveXaiModelCompatPatch` / `applyXaiModelCompat` |
|
||||
| `plugin-sdk/provider-usage` | `fetchClaudeUsage` and similar |
|
||||
| `plugin-sdk/provider-stream` | `ProviderStreamFamily`, `buildProviderStreamFamilyHooks`, `composeProviderStreamWrappers`, stream wrapper types, and shared Anthropic/Bedrock/Google/Kilocode/Moonshot/OpenAI/OpenRouter/Z.A.I/MiniMax/Copilot wrapper helpers |
|
||||
| `plugin-sdk/provider-transport-runtime` | Native provider transport helpers such as guarded fetch, transport message transforms, and writable transport event streams |
|
||||
| `plugin-sdk/provider-onboard` | Onboarding config patch helpers |
|
||||
| `plugin-sdk/global-singleton` | Process-local singleton/map/cache helpers |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Auth and security subpaths">
|
||||
| Subpath | Key exports |
|
||||
| --- | --- |
|
||||
| `plugin-sdk/command-auth` | `resolveControlCommandGate`, command registry helpers, sender-authorization helpers |
|
||||
| `plugin-sdk/command-status` | Command/help message builders such as `buildCommandsMessagePaginated` and `buildHelpMessage` |
|
||||
| `plugin-sdk/approval-auth-runtime` | Approver resolution and same-chat action-auth helpers |
|
||||
| `plugin-sdk/approval-client-runtime` | Native exec approval profile/filter helpers |
|
||||
| `plugin-sdk/approval-delivery-runtime` | Native approval capability/delivery adapters |
|
||||
| `plugin-sdk/approval-gateway-runtime` | Shared approval gateway-resolution helper |
|
||||
| `plugin-sdk/approval-handler-adapter-runtime` | Lightweight native approval adapter loading helpers for hot channel entrypoints |
|
||||
| `plugin-sdk/approval-handler-runtime` | Broader approval handler runtime helpers; prefer the narrower adapter/gateway seams when they are enough |
|
||||
| `plugin-sdk/approval-native-runtime` | Native approval target + account-binding helpers |
|
||||
| `plugin-sdk/approval-reply-runtime` | Exec/plugin approval reply payload helpers |
|
||||
| `plugin-sdk/command-auth-native` | Native command auth + native session-target helpers |
|
||||
| `plugin-sdk/command-detection` | Shared command detection helpers |
|
||||
| `plugin-sdk/command-surface` | Command-body normalization and command-surface helpers |
|
||||
| `plugin-sdk/allow-from` | `formatAllowFromLowercase` |
|
||||
| `plugin-sdk/channel-secret-runtime` | Narrow secret-contract collection helpers for channel/plugin secret surfaces |
|
||||
| `plugin-sdk/secret-ref-runtime` | Narrow `coerceSecretRef` and SecretRef typing helpers for secret-contract/config parsing |
|
||||
| `plugin-sdk/security-runtime` | Shared trust, DM gating, external-content, and secret-collection helpers |
|
||||
| `plugin-sdk/ssrf-policy` | Host allowlist and private-network SSRF policy helpers |
|
||||
| `plugin-sdk/ssrf-dispatcher` | Narrow pinned-dispatcher helpers without the broad infra runtime surface |
|
||||
| `plugin-sdk/ssrf-runtime` | Pinned-dispatcher, SSRF-guarded fetch, and SSRF policy helpers |
|
||||
| `plugin-sdk/secret-input` | Secret input parsing helpers |
|
||||
| `plugin-sdk/webhook-ingress` | Webhook request/target helpers |
|
||||
| `plugin-sdk/webhook-request-guards` | Request body size/timeout helpers |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Runtime and storage subpaths">
|
||||
| Subpath | Key exports |
|
||||
| --- | --- |
|
||||
| `plugin-sdk/runtime` | Broad runtime/logging/backup/plugin-install helpers |
|
||||
| `plugin-sdk/runtime-env` | Narrow runtime env, logger, timeout, retry, and backoff helpers |
|
||||
| `plugin-sdk/channel-runtime-context` | Generic channel runtime-context registration and lookup helpers |
|
||||
| `plugin-sdk/runtime-store` | `createPluginRuntimeStore` |
|
||||
| `plugin-sdk/plugin-runtime` | Shared plugin command/hook/http/interactive helpers |
|
||||
| `plugin-sdk/hook-runtime` | Shared webhook/internal hook pipeline helpers |
|
||||
| `plugin-sdk/lazy-runtime` | Lazy runtime import/binding helpers such as `createLazyRuntimeModule`, `createLazyRuntimeMethod`, and `createLazyRuntimeSurface` |
|
||||
| `plugin-sdk/process-runtime` | Process exec helpers |
|
||||
| `plugin-sdk/cli-runtime` | CLI formatting, wait, and version helpers |
|
||||
| `plugin-sdk/gateway-runtime` | Gateway client and channel-status patch helpers |
|
||||
| `plugin-sdk/config-runtime` | Config load/write helpers |
|
||||
| `plugin-sdk/telegram-command-config` | Telegram command-name/description normalization and duplicate/conflict checks, even when the bundled Telegram contract surface is unavailable |
|
||||
| `plugin-sdk/text-autolink-runtime` | File-reference autolink detection without the broad text-runtime barrel |
|
||||
| `plugin-sdk/approval-runtime` | Exec/plugin approval helpers, approval-capability builders, auth/profile helpers, native routing/runtime helpers |
|
||||
| `plugin-sdk/reply-runtime` | Shared inbound/reply runtime helpers, chunking, dispatch, heartbeat, reply planner |
|
||||
| `plugin-sdk/reply-dispatch-runtime` | Narrow reply dispatch/finalize helpers |
|
||||
| `plugin-sdk/reply-history` | Shared short-window reply-history helpers such as `buildHistoryContext`, `recordPendingHistoryEntry`, and `clearHistoryEntriesIfEnabled` |
|
||||
| `plugin-sdk/reply-reference` | `createReplyReferencePlanner` |
|
||||
| `plugin-sdk/reply-chunking` | Narrow text/markdown chunking helpers |
|
||||
| `plugin-sdk/session-store-runtime` | Session store path + updated-at helpers |
|
||||
| `plugin-sdk/state-paths` | State/OAuth dir path helpers |
|
||||
| `plugin-sdk/routing` | Route/session-key/account binding helpers such as `resolveAgentRoute`, `buildAgentSessionKey`, and `resolveDefaultAgentBoundAccountId` |
|
||||
| `plugin-sdk/status-helpers` | Shared channel/account status summary helpers, runtime-state defaults, and issue metadata helpers |
|
||||
| `plugin-sdk/target-resolver-runtime` | Shared target resolver helpers |
|
||||
| `plugin-sdk/string-normalization-runtime` | Slug/string normalization helpers |
|
||||
| `plugin-sdk/request-url` | Extract string URLs from fetch/request-like inputs |
|
||||
| `plugin-sdk/run-command` | Timed command runner with normalized stdout/stderr results |
|
||||
| `plugin-sdk/param-readers` | Common tool/CLI param readers |
|
||||
| `plugin-sdk/tool-payload` | Extract normalized payloads from tool result objects |
|
||||
| `plugin-sdk/tool-send` | Extract canonical send target fields from tool args |
|
||||
| `plugin-sdk/temp-path` | Shared temp-download path helpers |
|
||||
| `plugin-sdk/logging-core` | Subsystem logger and redaction helpers |
|
||||
| `plugin-sdk/markdown-table-runtime` | Markdown table mode helpers |
|
||||
| `plugin-sdk/json-store` | Small JSON state read/write helpers |
|
||||
| `plugin-sdk/file-lock` | Re-entrant file-lock helpers |
|
||||
| `plugin-sdk/persistent-dedupe` | Disk-backed dedupe cache helpers |
|
||||
| `plugin-sdk/acp-runtime` | ACP runtime/session and reply-dispatch helpers |
|
||||
| `plugin-sdk/acp-binding-resolve-runtime` | Read-only ACP binding resolution without lifecycle startup imports |
|
||||
| `plugin-sdk/agent-config-primitives` | Narrow agent runtime config-schema primitives |
|
||||
| `plugin-sdk/boolean-param` | Loose boolean param reader |
|
||||
| `plugin-sdk/dangerous-name-runtime` | Dangerous-name matching resolution helpers |
|
||||
| `plugin-sdk/device-bootstrap` | Device bootstrap and pairing token helpers |
|
||||
| `plugin-sdk/extension-shared` | Shared passive-channel, status, and ambient proxy helper primitives |
|
||||
| `plugin-sdk/models-provider-runtime` | `/models` command/provider reply helpers |
|
||||
| `plugin-sdk/skill-commands-runtime` | Skill command listing helpers |
|
||||
| `plugin-sdk/native-command-registry` | Native command registry/build/serialize helpers |
|
||||
| `plugin-sdk/agent-harness` | Experimental trusted-plugin surface for low-level agent harnesses: harness types, active-run steer/abort helpers, OpenClaw tool bridge helpers, and attempt result utilities |
|
||||
| `plugin-sdk/provider-zai-endpoint` | Z.AI endpoint detection helpers |
|
||||
| `plugin-sdk/infra-runtime` | System event/heartbeat helpers |
|
||||
| `plugin-sdk/collection-runtime` | Small bounded cache helpers |
|
||||
| `plugin-sdk/diagnostic-runtime` | Diagnostic flag and event helpers |
|
||||
| `plugin-sdk/error-runtime` | Error graph, formatting, shared error classification helpers, `isApprovalNotFoundError` |
|
||||
| `plugin-sdk/fetch-runtime` | Wrapped fetch, proxy, and pinned lookup helpers |
|
||||
| `plugin-sdk/runtime-fetch` | Dispatcher-aware runtime fetch without proxy/guarded-fetch imports |
|
||||
| `plugin-sdk/response-limit-runtime` | Bounded response-body reader without the broad media runtime surface |
|
||||
| `plugin-sdk/session-binding-runtime` | Current conversation binding state without configured binding routing or pairing stores |
|
||||
| `plugin-sdk/session-store-runtime` | Session-store read helpers without broad config writes/maintenance imports |
|
||||
| `plugin-sdk/context-visibility-runtime` | Context visibility resolution and supplemental context filtering without broad config/security imports |
|
||||
| `plugin-sdk/string-coerce-runtime` | Narrow primitive record/string coercion and normalization helpers without markdown/logging imports |
|
||||
| `plugin-sdk/host-runtime` | Hostname and SCP host normalization helpers |
|
||||
| `plugin-sdk/retry-runtime` | Retry config and retry runner helpers |
|
||||
| `plugin-sdk/agent-runtime` | Agent dir/identity/workspace helpers |
|
||||
| `plugin-sdk/directory-runtime` | Config-backed directory query/dedup |
|
||||
| `plugin-sdk/keyed-async-queue` | `KeyedAsyncQueue` |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Capability and testing subpaths">
|
||||
| Subpath | Key exports |
|
||||
| --- | --- |
|
||||
| `plugin-sdk/media-runtime` | Shared media fetch/transform/store helpers plus media payload builders |
|
||||
| `plugin-sdk/media-generation-runtime` | Shared media-generation failover helpers, candidate selection, and missing-model messaging |
|
||||
| `plugin-sdk/media-understanding` | Media understanding provider types plus provider-facing image/audio helper exports |
|
||||
| `plugin-sdk/text-runtime` | Shared text/markdown/logging helpers such as assistant-visible-text stripping, markdown render/chunking/table helpers, redaction helpers, directive-tag helpers, and safe-text utilities |
|
||||
| `plugin-sdk/text-chunking` | Outbound text chunking helper |
|
||||
| `plugin-sdk/speech` | Speech provider types plus provider-facing directive, registry, and validation helpers |
|
||||
| `plugin-sdk/speech-core` | Shared speech provider types, registry, directive, and normalization helpers |
|
||||
| `plugin-sdk/realtime-transcription` | Realtime transcription provider types and registry helpers |
|
||||
| `plugin-sdk/realtime-voice` | Realtime voice provider types and registry helpers |
|
||||
| `plugin-sdk/image-generation` | Image generation provider types |
|
||||
| `plugin-sdk/image-generation-core` | Shared image-generation types, failover, auth, and registry helpers |
|
||||
| `plugin-sdk/music-generation` | Music generation provider/request/result types |
|
||||
| `plugin-sdk/music-generation-core` | Shared music-generation types, failover helpers, provider lookup, and model-ref parsing |
|
||||
| `plugin-sdk/video-generation` | Video generation provider/request/result types |
|
||||
| `plugin-sdk/video-generation-core` | Shared video-generation types, failover helpers, provider lookup, and model-ref parsing |
|
||||
| `plugin-sdk/webhook-targets` | Webhook target registry and route-install helpers |
|
||||
| `plugin-sdk/webhook-path` | Webhook path normalization helpers |
|
||||
| `plugin-sdk/web-media` | Shared remote/local media loading helpers |
|
||||
| `plugin-sdk/zod` | Re-exported `zod` for plugin SDK consumers |
|
||||
| `plugin-sdk/testing` | `installCommonResolveTargetErrorCases`, `shouldAckReaction` |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Memory subpaths">
|
||||
| Subpath | Key exports |
|
||||
| --- | --- |
|
||||
| `plugin-sdk/memory-core` | Bundled memory-core helper surface for manager/config/file/CLI helpers |
|
||||
| `plugin-sdk/memory-core-engine-runtime` | Memory index/search runtime facade |
|
||||
| `plugin-sdk/memory-core-host-engine-foundation` | Memory host foundation engine exports |
|
||||
| `plugin-sdk/memory-core-host-engine-embeddings` | Memory host embedding contracts, registry access, local provider, and generic batch/remote helpers |
|
||||
| `plugin-sdk/memory-core-host-engine-qmd` | Memory host QMD engine exports |
|
||||
| `plugin-sdk/memory-core-host-engine-storage` | Memory host storage engine exports |
|
||||
| `plugin-sdk/memory-core-host-multimodal` | Memory host multimodal helpers |
|
||||
| `plugin-sdk/memory-core-host-query` | Memory host query helpers |
|
||||
| `plugin-sdk/memory-core-host-secret` | Memory host secret helpers |
|
||||
| `plugin-sdk/memory-core-host-events` | Memory host event journal helpers |
|
||||
| `plugin-sdk/memory-core-host-status` | Memory host status helpers |
|
||||
| `plugin-sdk/memory-core-host-runtime-cli` | Memory host CLI runtime helpers |
|
||||
| `plugin-sdk/memory-core-host-runtime-core` | Memory host core runtime helpers |
|
||||
| `plugin-sdk/memory-core-host-runtime-files` | Memory host file/runtime helpers |
|
||||
| `plugin-sdk/memory-host-core` | Vendor-neutral alias for memory host core runtime helpers |
|
||||
| `plugin-sdk/memory-host-events` | Vendor-neutral alias for memory host event journal helpers |
|
||||
| `plugin-sdk/memory-host-files` | Vendor-neutral alias for memory host file/runtime helpers |
|
||||
| `plugin-sdk/memory-host-markdown` | Shared managed-markdown helpers for memory-adjacent plugins |
|
||||
| `plugin-sdk/memory-host-search` | Active memory runtime facade for search-manager access |
|
||||
| `plugin-sdk/memory-host-status` | Vendor-neutral alias for memory host status helpers |
|
||||
| `plugin-sdk/memory-lancedb` | Bundled memory-lancedb helper surface |
|
||||
</Accordion>
|
||||
|
||||
<Accordion title="Reserved bundled-helper subpaths">
|
||||
| Family | Current subpaths | Intended use |
|
||||
| --- | --- | --- |
|
||||
| Browser | `plugin-sdk/browser-cdp`, `plugin-sdk/browser-config-runtime`, `plugin-sdk/browser-config-support`, `plugin-sdk/browser-control-auth`, `plugin-sdk/browser-node-runtime`, `plugin-sdk/browser-profiles`, `plugin-sdk/browser-security-runtime`, `plugin-sdk/browser-setup-tools`, `plugin-sdk/browser-support` | Bundled browser plugin support helpers (`browser-support` remains the compatibility barrel) |
|
||||
| Matrix | `plugin-sdk/matrix`, `plugin-sdk/matrix-helper`, `plugin-sdk/matrix-runtime-heavy`, `plugin-sdk/matrix-runtime-shared`, `plugin-sdk/matrix-runtime-surface`, `plugin-sdk/matrix-surface`, `plugin-sdk/matrix-thread-bindings` | Bundled Matrix helper/runtime surface |
|
||||
| Line | `plugin-sdk/line`, `plugin-sdk/line-core`, `plugin-sdk/line-runtime`, `plugin-sdk/line-surface` | Bundled LINE helper/runtime surface |
|
||||
| IRC | `plugin-sdk/irc`, `plugin-sdk/irc-surface` | Bundled IRC helper surface |
|
||||
| Channel-specific helpers | `plugin-sdk/googlechat`, `plugin-sdk/zalouser`, `plugin-sdk/bluebubbles`, `plugin-sdk/bluebubbles-policy`, `plugin-sdk/mattermost`, `plugin-sdk/mattermost-policy`, `plugin-sdk/feishu-conversation`, `plugin-sdk/msteams`, `plugin-sdk/nextcloud-talk`, `plugin-sdk/nostr`, `plugin-sdk/tlon`, `plugin-sdk/twitch` | Bundled channel compatibility/helper seams |
|
||||
| Auth/plugin-specific helpers | `plugin-sdk/github-copilot-login`, `plugin-sdk/github-copilot-token`, `plugin-sdk/diagnostics-otel`, `plugin-sdk/diffs`, `plugin-sdk/llm-task`, `plugin-sdk/thread-ownership`, `plugin-sdk/voice-call` | Bundled feature/plugin helper seams; `plugin-sdk/github-copilot-token` currently exports `DEFAULT_COPILOT_API_BASE_URL`, `deriveCopilotApiBaseUrlFromToken`, and `resolveCopilotApiToken` |
|
||||
</Accordion>
|
||||
</AccordionGroup>
|
||||
|
||||
## Registration API
|
||||
|
||||
The `register(api)` callback receives an `OpenClawPluginApi` object with these
|
||||
methods:
|
||||
|
||||
### Capability registration
|
||||
|
||||
| Method | What it registers |
|
||||
| ------------------------------------------------ | ------------------------------------- |
|
||||
| `api.registerProvider(...)` | Text inference (LLM) |
|
||||
| `api.registerAgentHarness(...)` | Experimental low-level agent executor |
|
||||
| `api.registerCliBackend(...)` | Local CLI inference backend |
|
||||
| `api.registerChannel(...)` | Messaging channel |
|
||||
| `api.registerSpeechProvider(...)` | Text-to-speech / STT synthesis |
|
||||
| `api.registerRealtimeTranscriptionProvider(...)` | Streaming realtime transcription |
|
||||
| `api.registerRealtimeVoiceProvider(...)` | Duplex realtime voice sessions |
|
||||
| `api.registerMediaUnderstandingProvider(...)` | Image/audio/video analysis |
|
||||
| `api.registerImageGenerationProvider(...)` | Image generation |
|
||||
| `api.registerMusicGenerationProvider(...)` | Music generation |
|
||||
| `api.registerVideoGenerationProvider(...)` | Video generation |
|
||||
| `api.registerWebFetchProvider(...)` | Web fetch / scrape provider |
|
||||
| `api.registerWebSearchProvider(...)` | Web search |
|
||||
|
||||
### Tools and commands
|
||||
|
||||
| Method | What it registers |
|
||||
| ------------------------------- | --------------------------------------------- |
|
||||
| `api.registerTool(tool, opts?)` | Agent tool (required or `{ optional: true }`) |
|
||||
| `api.registerCommand(def)` | Custom command (bypasses the LLM) |
|
||||
|
||||
### Infrastructure
|
||||
|
||||
| Method | What it registers |
|
||||
| ---------------------------------------------- | --------------------------------------- |
|
||||
| `api.registerHook(events, handler, opts?)` | Event hook |
|
||||
| `api.registerHttpRoute(params)` | Gateway HTTP endpoint |
|
||||
| `api.registerGatewayMethod(name, handler)` | Gateway RPC method |
|
||||
| `api.registerCli(registrar, opts?)` | CLI subcommand |
|
||||
| `api.registerService(service)` | Background service |
|
||||
| `api.registerInteractiveHandler(registration)` | Interactive handler |
|
||||
| `api.registerMemoryPromptSupplement(builder)` | Additive memory-adjacent prompt section |
|
||||
| `api.registerMemoryCorpusSupplement(adapter)` | Additive memory search/read corpus |
|
||||
|
||||
Reserved core admin namespaces (`config.*`, `exec.approvals.*`, `wizard.*`,
|
||||
`update.*`) always stay `operator.admin`, even if a plugin tries to assign a
|
||||
narrower gateway method scope. Prefer plugin-specific prefixes for
|
||||
plugin-owned methods.
|
||||
|
||||
### CLI registration metadata
|
||||
|
||||
`api.registerCli(registrar, opts?)` accepts two kinds of top-level metadata:
|
||||
|
||||
- `commands`: explicit command roots owned by the registrar
|
||||
- `descriptors`: parse-time command descriptors used for root CLI help,
|
||||
routing, and lazy plugin CLI registration
|
||||
|
||||
If you want a plugin command to stay lazy-loaded in the normal root CLI path,
|
||||
provide `descriptors` that cover every top-level command root exposed by that
|
||||
registrar.
|
||||
|
||||
```typescript
|
||||
api.registerCli(
|
||||
async ({ program }) => {
|
||||
const { registerMatrixCli } = await import("./src/cli.js");
|
||||
registerMatrixCli({ program });
|
||||
},
|
||||
{
|
||||
descriptors: [
|
||||
{
|
||||
name: "matrix",
|
||||
description: "Manage Matrix accounts, verification, devices, and profile state",
|
||||
hasSubcommands: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
);
|
||||
```
|
||||
|
||||
Use `commands` by itself only when you do not need lazy root CLI registration.
|
||||
That eager compatibility path remains supported, but it does not install
|
||||
descriptor-backed placeholders for parse-time lazy loading.
|
||||
|
||||
### CLI backend registration
|
||||
|
||||
`api.registerCliBackend(...)` lets a plugin own the default config for a local
|
||||
AI CLI backend such as `codex-cli`.
|
||||
|
||||
- The backend `id` becomes the provider prefix in model refs like `codex-cli/gpt-5`.
|
||||
- The backend `config` uses the same shape as `agents.defaults.cliBackends.<id>`.
|
||||
- User config still wins. OpenClaw merges `agents.defaults.cliBackends.<id>` over the
|
||||
plugin default before running the CLI.
|
||||
- Use `normalizeConfig` when a backend needs compatibility rewrites after merge
|
||||
(for example normalizing old flag shapes).
|
||||
|
||||
### Exclusive slots
|
||||
|
||||
| Method | What it registers |
|
||||
| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `api.registerContextEngine(id, factory)` | Context engine (one active at a time). The `assemble()` callback receives `availableTools` and `citationsMode` so the engine can tailor prompt additions. |
|
||||
| `api.registerMemoryCapability(capability)` | Unified memory capability |
|
||||
| `api.registerMemoryPromptSection(builder)` | Memory prompt section builder |
|
||||
| `api.registerMemoryFlushPlan(resolver)` | Memory flush plan resolver |
|
||||
| `api.registerMemoryRuntime(runtime)` | Memory runtime adapter |
|
||||
|
||||
### Memory embedding adapters
|
||||
|
||||
| Method | What it registers |
|
||||
| ---------------------------------------------- | ---------------------------------------------- |
|
||||
| `api.registerMemoryEmbeddingProvider(adapter)` | Memory embedding adapter for the active plugin |
|
||||
|
||||
- `registerMemoryCapability` is the preferred exclusive memory-plugin API.
|
||||
- `registerMemoryCapability` may also expose `publicArtifacts.listArtifacts(...)`
|
||||
so companion plugins can consume exported memory artifacts through
|
||||
`openclaw/plugin-sdk/memory-host-core` instead of reaching into a specific
|
||||
memory plugin's private layout.
|
||||
- `registerMemoryPromptSection`, `registerMemoryFlushPlan`, and
|
||||
`registerMemoryRuntime` are legacy-compatible exclusive memory-plugin APIs.
|
||||
- `registerMemoryEmbeddingProvider` lets the active memory plugin register one
|
||||
or more embedding adapter ids (for example `openai`, `gemini`, or a custom
|
||||
plugin-defined id).
|
||||
- User config such as `agents.defaults.memorySearch.provider` and
|
||||
`agents.defaults.memorySearch.fallback` resolves against those registered
|
||||
adapter ids.
|
||||
|
||||
### Events and lifecycle
|
||||
|
||||
| Method | What it does |
|
||||
| -------------------------------------------- | ----------------------------- |
|
||||
| `api.on(hookName, handler, opts?)` | Typed lifecycle hook |
|
||||
| `api.onConversationBindingResolved(handler)` | Conversation binding callback |
|
||||
|
||||
### Hook decision semantics
|
||||
|
||||
- `before_tool_call`: returning `{ block: true }` is terminal. Once any handler sets it, lower-priority handlers are skipped.
|
||||
- `before_tool_call`: returning `{ block: false }` is treated as no decision (same as omitting `block`), not as an override.
|
||||
- `before_install`: returning `{ block: true }` is terminal. Once any handler sets it, lower-priority handlers are skipped.
|
||||
- `before_install`: returning `{ block: false }` is treated as no decision (same as omitting `block`), not as an override.
|
||||
- `reply_dispatch`: returning `{ handled: true, ... }` is terminal. Once any handler claims dispatch, lower-priority handlers and the default model dispatch path are skipped.
|
||||
- `message_sending`: returning `{ cancel: true }` is terminal. Once any handler sets it, lower-priority handlers are skipped.
|
||||
- `message_sending`: returning `{ cancel: false }` is treated as no decision (same as omitting `cancel`), not as an override.
|
||||
|
||||
### API object fields
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------------------ | ------------------------- | ------------------------------------------------------------------------------------------- |
|
||||
| `api.id` | `string` | Plugin id |
|
||||
| `api.name` | `string` | Display name |
|
||||
| `api.version` | `string?` | Plugin version (optional) |
|
||||
| `api.description` | `string?` | Plugin description (optional) |
|
||||
| `api.source` | `string` | Plugin source path |
|
||||
| `api.rootDir` | `string?` | Plugin root directory (optional) |
|
||||
| `api.config` | `OpenClawConfig` | Current config snapshot (active in-memory runtime snapshot when available) |
|
||||
| `api.pluginConfig` | `Record<string, unknown>` | Plugin-specific config from `plugins.entries.<id>.config` |
|
||||
| `api.runtime` | `PluginRuntime` | [Runtime helpers](/plugins/sdk-runtime) |
|
||||
| `api.logger` | `PluginLogger` | Scoped logger (`debug`, `info`, `warn`, `error`) |
|
||||
| `api.registrationMode` | `PluginRegistrationMode` | Current load mode; `"setup-runtime"` is the lightweight pre-full-entry startup/setup window |
|
||||
| `api.resolvePath(input)` | `(string) => string` | Resolve path relative to plugin root |
|
||||
|
||||
## Internal module convention
|
||||
|
||||
Within your plugin, use local barrel files for internal imports:
|
||||
|
||||
```
|
||||
my-plugin/
|
||||
api.ts # Public exports for external consumers
|
||||
runtime-api.ts # Internal-only runtime exports
|
||||
index.ts # Plugin entry point
|
||||
setup-entry.ts # Lightweight setup-only entry (optional)
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Never import your own plugin through `openclaw/plugin-sdk/<your-plugin>`
|
||||
from production code. Route internal imports through `./api.ts` or
|
||||
`./runtime-api.ts`. The SDK path is the external contract only.
|
||||
</Warning>
|
||||
|
||||
Facade-loaded bundled plugin public surfaces (`api.ts`, `runtime-api.ts`,
|
||||
`index.ts`, `setup-entry.ts`, and similar public entry files) now prefer the
|
||||
active runtime config snapshot when OpenClaw is already running. If no runtime
|
||||
snapshot exists yet, they fall back to the resolved config file on disk.
|
||||
|
||||
Provider plugins can also expose a narrow plugin-local contract barrel when a
|
||||
helper is intentionally provider-specific and does not belong in a generic SDK
|
||||
subpath yet. Current bundled example: the Anthropic provider keeps its Claude
|
||||
stream helpers in its own public `api.ts` / `contract-api.ts` seam instead of
|
||||
promoting Anthropic beta-header and `service_tier` logic into a generic
|
||||
`plugin-sdk/*` contract.
|
||||
|
||||
Other current bundled examples:
|
||||
|
||||
- `@openclaw/openai-provider`: `api.ts` exports provider builders,
|
||||
default-model helpers, and realtime provider builders
|
||||
- `@openclaw/openrouter-provider`: `api.ts` exports the provider builder plus
|
||||
onboarding/config helpers
|
||||
|
||||
<Warning>
|
||||
Extension production code should also avoid `openclaw/plugin-sdk/<other-plugin>`
|
||||
imports. If a helper is truly shared, promote it to a neutral SDK subpath
|
||||
such as `openclaw/plugin-sdk/speech`, `.../provider-model-shared`, or another
|
||||
capability-oriented surface instead of coupling two plugins together.
|
||||
</Warning>
|
||||
|
||||
## Related
|
||||
|
||||
- [Entry Points](/plugins/sdk-entrypoints) — `definePluginEntry` and `defineChannelPluginEntry` options
|
||||
- [Runtime Helpers](/plugins/sdk-runtime) — full `api.runtime` namespace reference
|
||||
- [Setup and Config](/plugins/sdk-setup) — packaging, manifests, config schemas
|
||||
- [Testing](/plugins/sdk-testing) — test utilities and lint rules
|
||||
- [SDK Migration](/plugins/sdk-migration) — migrating from deprecated surfaces
|
||||
- [Plugin Internals](/plugins/architecture) — deep architecture and capability model
|
||||
767
openclaw/docs/plugins/sdk-provider-plugins.md
Normal file
767
openclaw/docs/plugins/sdk-provider-plugins.md
Normal file
|
|
@ -0,0 +1,767 @@
|
|||
---
|
||||
title: "Building Provider Plugins"
|
||||
sidebarTitle: "Provider Plugins"
|
||||
summary: "Step-by-step guide to building a model provider plugin for OpenClaw"
|
||||
read_when:
|
||||
- You are building a new model provider plugin
|
||||
- You want to add an OpenAI-compatible proxy or custom LLM to OpenClaw
|
||||
- You need to understand provider auth, catalogs, and runtime hooks
|
||||
---
|
||||
|
||||
# Building Provider Plugins
|
||||
|
||||
This guide walks through building a provider plugin that adds a model provider
|
||||
(LLM) to OpenClaw. By the end you will have a provider with a model catalog,
|
||||
API key auth, and dynamic model resolution.
|
||||
|
||||
<Info>
|
||||
If you have not built any OpenClaw plugin before, read
|
||||
[Getting Started](/plugins/building-plugins) first for the basic package
|
||||
structure and manifest setup.
|
||||
</Info>
|
||||
|
||||
<Tip>
|
||||
Provider plugins add models to OpenClaw's normal inference loop. If the model
|
||||
must run through a native agent daemon that owns threads, compaction, or tool
|
||||
events, pair the provider with an [agent harness](/plugins/sdk-agent-harness)
|
||||
instead of putting daemon protocol details in core.
|
||||
</Tip>
|
||||
|
||||
## Walkthrough
|
||||
|
||||
<Steps>
|
||||
<a id="step-1-package-and-manifest"></a>
|
||||
<Step title="Package and manifest">
|
||||
<CodeGroup>
|
||||
```json package.json
|
||||
{
|
||||
"name": "@myorg/openclaw-acme-ai",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"providers": ["acme-ai"],
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.3.24-beta.2",
|
||||
"minGatewayVersion": "2026.3.24-beta.2"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.3.24-beta.2",
|
||||
"pluginSdkVersion": "2026.3.24-beta.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
```json openclaw.plugin.json
|
||||
{
|
||||
"id": "acme-ai",
|
||||
"name": "Acme AI",
|
||||
"description": "Acme AI model provider",
|
||||
"providers": ["acme-ai"],
|
||||
"modelSupport": {
|
||||
"modelPrefixes": ["acme-"]
|
||||
},
|
||||
"providerAuthEnvVars": {
|
||||
"acme-ai": ["ACME_AI_API_KEY"]
|
||||
},
|
||||
"providerAuthAliases": {
|
||||
"acme-ai-coding": "acme-ai"
|
||||
},
|
||||
"providerAuthChoices": [
|
||||
{
|
||||
"provider": "acme-ai",
|
||||
"method": "api-key",
|
||||
"choiceId": "acme-ai-api-key",
|
||||
"choiceLabel": "Acme AI API key",
|
||||
"groupId": "acme-ai",
|
||||
"groupLabel": "Acme AI",
|
||||
"cliFlag": "--acme-ai-api-key",
|
||||
"cliOption": "--acme-ai-api-key <key>",
|
||||
"cliDescription": "Acme AI API key"
|
||||
}
|
||||
],
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
The manifest declares `providerAuthEnvVars` so OpenClaw can detect
|
||||
credentials without loading your plugin runtime. Add `providerAuthAliases`
|
||||
when a provider variant should reuse another provider id's auth. `modelSupport`
|
||||
is optional and lets OpenClaw auto-load your provider plugin from shorthand
|
||||
model ids like `acme-large` before runtime hooks exist. If you publish the
|
||||
provider on ClawHub, those `openclaw.compat` and `openclaw.build` fields
|
||||
are required in `package.json`.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Register the provider">
|
||||
A minimal provider needs an `id`, `label`, `auth`, and `catalog`:
|
||||
|
||||
```typescript index.ts
|
||||
import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
|
||||
import { createProviderApiKeyAuthMethod } from "openclaw/plugin-sdk/provider-auth";
|
||||
|
||||
export default definePluginEntry({
|
||||
id: "acme-ai",
|
||||
name: "Acme AI",
|
||||
description: "Acme AI model provider",
|
||||
register(api) {
|
||||
api.registerProvider({
|
||||
id: "acme-ai",
|
||||
label: "Acme AI",
|
||||
docsPath: "/providers/acme-ai",
|
||||
envVars: ["ACME_AI_API_KEY"],
|
||||
|
||||
auth: [
|
||||
createProviderApiKeyAuthMethod({
|
||||
providerId: "acme-ai",
|
||||
methodId: "api-key",
|
||||
label: "Acme AI API key",
|
||||
hint: "API key from your Acme AI dashboard",
|
||||
optionKey: "acmeAiApiKey",
|
||||
flagName: "--acme-ai-api-key",
|
||||
envVar: "ACME_AI_API_KEY",
|
||||
promptMessage: "Enter your Acme AI API key",
|
||||
defaultModel: "acme-ai/acme-large",
|
||||
}),
|
||||
],
|
||||
|
||||
catalog: {
|
||||
order: "simple",
|
||||
run: async (ctx) => {
|
||||
const apiKey =
|
||||
ctx.resolveProviderApiKey("acme-ai").apiKey;
|
||||
if (!apiKey) return null;
|
||||
return {
|
||||
provider: {
|
||||
baseUrl: "https://api.acme-ai.com/v1",
|
||||
apiKey,
|
||||
api: "openai-completions",
|
||||
models: [
|
||||
{
|
||||
id: "acme-large",
|
||||
name: "Acme Large",
|
||||
reasoning: true,
|
||||
input: ["text", "image"],
|
||||
cost: { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 },
|
||||
contextWindow: 200000,
|
||||
maxTokens: 32768,
|
||||
},
|
||||
{
|
||||
id: "acme-small",
|
||||
name: "Acme Small",
|
||||
reasoning: false,
|
||||
input: ["text"],
|
||||
cost: { input: 1, output: 5, cacheRead: 0.1, cacheWrite: 1.25 },
|
||||
contextWindow: 128000,
|
||||
maxTokens: 8192,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
That is a working provider. Users can now
|
||||
`openclaw onboard --acme-ai-api-key <key>` and select
|
||||
`acme-ai/acme-large` as their model.
|
||||
|
||||
If the upstream provider uses different control tokens than OpenClaw, add a
|
||||
small bidirectional text transform instead of replacing the stream path:
|
||||
|
||||
```typescript
|
||||
api.registerTextTransforms({
|
||||
input: [
|
||||
{ from: /red basket/g, to: "blue basket" },
|
||||
{ from: /paper ticket/g, to: "digital ticket" },
|
||||
{ from: /left shelf/g, to: "right shelf" },
|
||||
],
|
||||
output: [
|
||||
{ from: /blue basket/g, to: "red basket" },
|
||||
{ from: /digital ticket/g, to: "paper ticket" },
|
||||
{ from: /right shelf/g, to: "left shelf" },
|
||||
],
|
||||
});
|
||||
```
|
||||
|
||||
`input` rewrites the final system prompt and text message content before
|
||||
transport. `output` rewrites assistant text deltas and final text before
|
||||
OpenClaw parses its own control markers or channel delivery.
|
||||
|
||||
For bundled providers that only register one text provider with API-key
|
||||
auth plus a single catalog-backed runtime, prefer the narrower
|
||||
`defineSingleProviderPluginEntry(...)` helper:
|
||||
|
||||
```typescript
|
||||
import { defineSingleProviderPluginEntry } from "openclaw/plugin-sdk/provider-entry";
|
||||
|
||||
export default defineSingleProviderPluginEntry({
|
||||
id: "acme-ai",
|
||||
name: "Acme AI",
|
||||
description: "Acme AI model provider",
|
||||
provider: {
|
||||
label: "Acme AI",
|
||||
docsPath: "/providers/acme-ai",
|
||||
auth: [
|
||||
{
|
||||
methodId: "api-key",
|
||||
label: "Acme AI API key",
|
||||
hint: "API key from your Acme AI dashboard",
|
||||
optionKey: "acmeAiApiKey",
|
||||
flagName: "--acme-ai-api-key",
|
||||
envVar: "ACME_AI_API_KEY",
|
||||
promptMessage: "Enter your Acme AI API key",
|
||||
defaultModel: "acme-ai/acme-large",
|
||||
},
|
||||
],
|
||||
catalog: {
|
||||
buildProvider: () => ({
|
||||
api: "openai-completions",
|
||||
baseUrl: "https://api.acme-ai.com/v1",
|
||||
models: [{ id: "acme-large", name: "Acme Large" }],
|
||||
}),
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
If your auth flow also needs to patch `models.providers.*`, aliases, and
|
||||
the agent default model during onboarding, use the preset helpers from
|
||||
`openclaw/plugin-sdk/provider-onboard`. The narrowest helpers are
|
||||
`createDefaultModelPresetAppliers(...)`,
|
||||
`createDefaultModelsPresetAppliers(...)`, and
|
||||
`createModelCatalogPresetAppliers(...)`.
|
||||
|
||||
When a provider's native endpoint supports streamed usage blocks on the
|
||||
normal `openai-completions` transport, prefer the shared catalog helpers in
|
||||
`openclaw/plugin-sdk/provider-catalog-shared` instead of hardcoding
|
||||
provider-id checks. `supportsNativeStreamingUsageCompat(...)` and
|
||||
`applyProviderNativeStreamingUsageCompat(...)` detect support from the
|
||||
endpoint capability map, so native Moonshot/DashScope-style endpoints still
|
||||
opt in even when a plugin is using a custom provider id.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Add dynamic model resolution">
|
||||
If your provider accepts arbitrary model IDs (like a proxy or router),
|
||||
add `resolveDynamicModel`:
|
||||
|
||||
```typescript
|
||||
api.registerProvider({
|
||||
// ... id, label, auth, catalog from above
|
||||
|
||||
resolveDynamicModel: (ctx) => ({
|
||||
id: ctx.modelId,
|
||||
name: ctx.modelId,
|
||||
provider: "acme-ai",
|
||||
api: "openai-completions",
|
||||
baseUrl: "https://api.acme-ai.com/v1",
|
||||
reasoning: false,
|
||||
input: ["text"],
|
||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||
contextWindow: 128000,
|
||||
maxTokens: 8192,
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
If resolving requires a network call, use `prepareDynamicModel` for async
|
||||
warm-up — `resolveDynamicModel` runs again after it completes.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Add runtime hooks (as needed)">
|
||||
Most providers only need `catalog` + `resolveDynamicModel`. Add hooks
|
||||
incrementally as your provider requires them.
|
||||
|
||||
Shared helper builders now cover the most common replay/tool-compat
|
||||
families, so plugins usually do not need to hand-wire each hook one by one:
|
||||
|
||||
```typescript
|
||||
import { buildProviderReplayFamilyHooks } from "openclaw/plugin-sdk/provider-model-shared";
|
||||
import { buildProviderStreamFamilyHooks } from "openclaw/plugin-sdk/provider-stream";
|
||||
import { buildProviderToolCompatFamilyHooks } from "openclaw/plugin-sdk/provider-tools";
|
||||
|
||||
const GOOGLE_FAMILY_HOOKS = {
|
||||
...buildProviderReplayFamilyHooks({ family: "google-gemini" }),
|
||||
...buildProviderStreamFamilyHooks("google-thinking"),
|
||||
...buildProviderToolCompatFamilyHooks("gemini"),
|
||||
};
|
||||
|
||||
api.registerProvider({
|
||||
id: "acme-gemini-compatible",
|
||||
// ...
|
||||
...GOOGLE_FAMILY_HOOKS,
|
||||
});
|
||||
```
|
||||
|
||||
Available replay families today:
|
||||
|
||||
| Family | What it wires in |
|
||||
| --- | --- |
|
||||
| `openai-compatible` | Shared OpenAI-style replay policy for OpenAI-compatible transports, including tool-call-id sanitation, assistant-first ordering fixes, and generic Gemini-turn validation where the transport needs it |
|
||||
| `anthropic-by-model` | Claude-aware replay policy chosen by `modelId`, so Anthropic-message transports only get Claude-specific thinking-block cleanup when the resolved model is actually a Claude id |
|
||||
| `google-gemini` | Native Gemini replay policy plus bootstrap replay sanitation and tagged reasoning-output mode |
|
||||
| `passthrough-gemini` | Gemini thought-signature sanitation for Gemini models running through OpenAI-compatible proxy transports; does not enable native Gemini replay validation or bootstrap rewrites |
|
||||
| `hybrid-anthropic-openai` | Hybrid policy for providers that mix Anthropic-message and OpenAI-compatible model surfaces in one plugin; optional Claude-only thinking-block dropping stays scoped to the Anthropic side |
|
||||
|
||||
Real bundled examples:
|
||||
|
||||
- `google` and `google-gemini-cli`: `google-gemini`
|
||||
- `openrouter`, `kilocode`, `opencode`, and `opencode-go`: `passthrough-gemini`
|
||||
- `amazon-bedrock` and `anthropic-vertex`: `anthropic-by-model`
|
||||
- `minimax`: `hybrid-anthropic-openai`
|
||||
- `moonshot`, `ollama`, `xai`, and `zai`: `openai-compatible`
|
||||
|
||||
Available stream families today:
|
||||
|
||||
| Family | What it wires in |
|
||||
| --- | --- |
|
||||
| `google-thinking` | Gemini thinking payload normalization on the shared stream path |
|
||||
| `kilocode-thinking` | Kilo reasoning wrapper on the shared proxy stream path, with `kilo/auto` and unsupported proxy reasoning ids skipping injected thinking |
|
||||
| `moonshot-thinking` | Moonshot binary native-thinking payload mapping from config + `/think` level |
|
||||
| `minimax-fast-mode` | MiniMax fast-mode model rewrite on the shared stream path |
|
||||
| `openai-responses-defaults` | Shared native OpenAI/Codex Responses wrappers: attribution headers, `/fast`/`serviceTier`, text verbosity, native Codex web search, reasoning-compat payload shaping, and Responses context management |
|
||||
| `openrouter-thinking` | OpenRouter reasoning wrapper for proxy routes, with unsupported-model/`auto` skips handled centrally |
|
||||
| `tool-stream-default-on` | Default-on `tool_stream` wrapper for providers like Z.AI that want tool streaming unless explicitly disabled |
|
||||
|
||||
Real bundled examples:
|
||||
|
||||
- `google` and `google-gemini-cli`: `google-thinking`
|
||||
- `kilocode`: `kilocode-thinking`
|
||||
- `moonshot`: `moonshot-thinking`
|
||||
- `minimax` and `minimax-portal`: `minimax-fast-mode`
|
||||
- `openai` and `openai-codex`: `openai-responses-defaults`
|
||||
- `openrouter`: `openrouter-thinking`
|
||||
- `zai`: `tool-stream-default-on`
|
||||
|
||||
`openclaw/plugin-sdk/provider-model-shared` also exports the replay-family
|
||||
enum plus the shared helpers those families are built from. Common public
|
||||
exports include:
|
||||
|
||||
- `ProviderReplayFamily`
|
||||
- `buildProviderReplayFamilyHooks(...)`
|
||||
- shared replay builders such as `buildOpenAICompatibleReplayPolicy(...)`,
|
||||
`buildAnthropicReplayPolicyForModel(...)`,
|
||||
`buildGoogleGeminiReplayPolicy(...)`, and
|
||||
`buildHybridAnthropicOrOpenAIReplayPolicy(...)`
|
||||
- Gemini replay helpers such as `sanitizeGoogleGeminiReplayHistory(...)`
|
||||
and `resolveTaggedReasoningOutputMode()`
|
||||
- endpoint/model helpers such as `resolveProviderEndpoint(...)`,
|
||||
`normalizeProviderId(...)`, `normalizeGooglePreviewModelId(...)`, and
|
||||
`normalizeNativeXaiModelId(...)`
|
||||
|
||||
`openclaw/plugin-sdk/provider-stream` exposes both the family builder and
|
||||
the public wrapper helpers those families reuse. Common public exports
|
||||
include:
|
||||
|
||||
- `ProviderStreamFamily`
|
||||
- `buildProviderStreamFamilyHooks(...)`
|
||||
- `composeProviderStreamWrappers(...)`
|
||||
- shared OpenAI/Codex wrappers such as
|
||||
`createOpenAIAttributionHeadersWrapper(...)`,
|
||||
`createOpenAIFastModeWrapper(...)`,
|
||||
`createOpenAIServiceTierWrapper(...)`,
|
||||
`createOpenAIResponsesContextManagementWrapper(...)`, and
|
||||
`createCodexNativeWebSearchWrapper(...)`
|
||||
- shared proxy/provider wrappers such as `createOpenRouterWrapper(...)`,
|
||||
`createToolStreamWrapper(...)`, and `createMinimaxFastModeWrapper(...)`
|
||||
|
||||
Some stream helpers stay provider-local on purpose. Current bundled
|
||||
example: `@openclaw/anthropic-provider` exports
|
||||
`wrapAnthropicProviderStream`, `resolveAnthropicBetas`,
|
||||
`resolveAnthropicFastMode`, `resolveAnthropicServiceTier`, and the
|
||||
lower-level Anthropic wrapper builders from its public `api.ts` /
|
||||
`contract-api.ts` seam. Those helpers remain Anthropic-specific because
|
||||
they also encode Claude OAuth beta handling and `context1m` gating.
|
||||
|
||||
Other bundled providers also keep transport-specific wrappers local when
|
||||
the behavior is not shared cleanly across families. Current example: the
|
||||
bundled xAI plugin keeps native xAI Responses shaping in its own
|
||||
`wrapStreamFn`, including `/fast` alias rewrites, default `tool_stream`,
|
||||
unsupported strict-tool cleanup, and xAI-specific reasoning-payload
|
||||
removal.
|
||||
|
||||
`openclaw/plugin-sdk/provider-tools` currently exposes one shared
|
||||
tool-schema family plus shared schema/compat helpers:
|
||||
|
||||
- `ProviderToolCompatFamily` documents the shared family inventory today.
|
||||
- `buildProviderToolCompatFamilyHooks("gemini")` wires Gemini schema
|
||||
cleanup + diagnostics for providers that need Gemini-safe tool schemas.
|
||||
- `normalizeGeminiToolSchemas(...)` and `inspectGeminiToolSchemas(...)`
|
||||
are the underlying public Gemini schema helpers.
|
||||
- `resolveXaiModelCompatPatch()` returns the bundled xAI compat patch:
|
||||
`toolSchemaProfile: "xai"`, unsupported schema keywords, native
|
||||
`web_search` support, and HTML-entity tool-call argument decoding.
|
||||
- `applyXaiModelCompat(model)` applies that same xAI compat patch to a
|
||||
resolved model before it reaches the runner.
|
||||
|
||||
Real bundled example: the xAI plugin uses `normalizeResolvedModel` plus
|
||||
`contributeResolvedModelCompat` to keep that compat metadata owned by the
|
||||
provider instead of hardcoding xAI rules in core.
|
||||
|
||||
The same package-root pattern also backs other bundled providers:
|
||||
|
||||
- `@openclaw/openai-provider`: `api.ts` exports provider builders,
|
||||
default-model helpers, and realtime provider builders
|
||||
- `@openclaw/openrouter-provider`: `api.ts` exports the provider builder
|
||||
plus onboarding/config helpers
|
||||
|
||||
<Tabs>
|
||||
<Tab title="Token exchange">
|
||||
For providers that need a token exchange before each inference call:
|
||||
|
||||
```typescript
|
||||
prepareRuntimeAuth: async (ctx) => {
|
||||
const exchanged = await exchangeToken(ctx.apiKey);
|
||||
return {
|
||||
apiKey: exchanged.token,
|
||||
baseUrl: exchanged.baseUrl,
|
||||
expiresAt: exchanged.expiresAt,
|
||||
};
|
||||
},
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Custom headers">
|
||||
For providers that need custom request headers or body modifications:
|
||||
|
||||
```typescript
|
||||
// wrapStreamFn returns a StreamFn derived from ctx.streamFn
|
||||
wrapStreamFn: (ctx) => {
|
||||
if (!ctx.streamFn) return undefined;
|
||||
const inner = ctx.streamFn;
|
||||
return async (params) => {
|
||||
params.headers = {
|
||||
...params.headers,
|
||||
"X-Acme-Version": "2",
|
||||
};
|
||||
return inner(params);
|
||||
};
|
||||
},
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Native transport identity">
|
||||
For providers that need native request/session headers or metadata on
|
||||
generic HTTP or WebSocket transports:
|
||||
|
||||
```typescript
|
||||
resolveTransportTurnState: (ctx) => ({
|
||||
headers: {
|
||||
"x-request-id": ctx.turnId,
|
||||
},
|
||||
metadata: {
|
||||
session_id: ctx.sessionId ?? "",
|
||||
turn_id: ctx.turnId,
|
||||
},
|
||||
}),
|
||||
resolveWebSocketSessionPolicy: (ctx) => ({
|
||||
headers: {
|
||||
"x-session-id": ctx.sessionId ?? "",
|
||||
},
|
||||
degradeCooldownMs: 60_000,
|
||||
}),
|
||||
```
|
||||
</Tab>
|
||||
<Tab title="Usage and billing">
|
||||
For providers that expose usage/billing data:
|
||||
|
||||
```typescript
|
||||
resolveUsageAuth: async (ctx) => {
|
||||
const auth = await ctx.resolveOAuthToken();
|
||||
return auth ? { token: auth.token } : null;
|
||||
},
|
||||
fetchUsageSnapshot: async (ctx) => {
|
||||
return await fetchAcmeUsage(ctx.token, ctx.timeoutMs);
|
||||
},
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<Accordion title="All available provider hooks">
|
||||
OpenClaw calls hooks in this order. Most providers only use 2-3:
|
||||
|
||||
| # | Hook | When to use |
|
||||
| --- | --- | --- |
|
||||
| 1 | `catalog` | Model catalog or base URL defaults |
|
||||
| 2 | `applyConfigDefaults` | Provider-owned global defaults during config materialization |
|
||||
| 3 | `normalizeModelId` | Legacy/preview model-id alias cleanup before lookup |
|
||||
| 4 | `normalizeTransport` | Provider-family `api` / `baseUrl` cleanup before generic model assembly |
|
||||
| 5 | `normalizeConfig` | Normalize `models.providers.<id>` config |
|
||||
| 6 | `applyNativeStreamingUsageCompat` | Native streaming-usage compat rewrites for config providers |
|
||||
| 7 | `resolveConfigApiKey` | Provider-owned env-marker auth resolution |
|
||||
| 8 | `resolveSyntheticAuth` | Local/self-hosted or config-backed synthetic auth |
|
||||
| 9 | `shouldDeferSyntheticProfileAuth` | Lower synthetic stored-profile placeholders behind env/config auth |
|
||||
| 10 | `resolveDynamicModel` | Accept arbitrary upstream model IDs |
|
||||
| 11 | `prepareDynamicModel` | Async metadata fetch before resolving |
|
||||
| 12 | `normalizeResolvedModel` | Transport rewrites before the runner |
|
||||
|
||||
Runtime fallback notes:
|
||||
|
||||
- `normalizeConfig` checks the matched provider first, then other
|
||||
hook-capable provider plugins until one actually changes the config.
|
||||
If no provider hook rewrites a supported Google-family config entry, the
|
||||
bundled Google config normalizer still applies.
|
||||
- `resolveConfigApiKey` uses the provider hook when exposed. The bundled
|
||||
`amazon-bedrock` path also has a built-in AWS env-marker resolver here,
|
||||
even though Bedrock runtime auth itself still uses the AWS SDK default
|
||||
chain.
|
||||
| 13 | `contributeResolvedModelCompat` | Compat flags for vendor models behind another compatible transport |
|
||||
| 14 | `capabilities` | Legacy static capability bag; compatibility only |
|
||||
| 15 | `normalizeToolSchemas` | Provider-owned tool-schema cleanup before registration |
|
||||
| 16 | `inspectToolSchemas` | Provider-owned tool-schema diagnostics |
|
||||
| 17 | `resolveReasoningOutputMode` | Tagged vs native reasoning-output contract |
|
||||
| 18 | `prepareExtraParams` | Default request params |
|
||||
| 19 | `createStreamFn` | Fully custom StreamFn transport |
|
||||
| 20 | `wrapStreamFn` | Custom headers/body wrappers on the normal stream path |
|
||||
| 21 | `resolveTransportTurnState` | Native per-turn headers/metadata |
|
||||
| 22 | `resolveWebSocketSessionPolicy` | Native WS session headers/cool-down |
|
||||
| 23 | `formatApiKey` | Custom runtime token shape |
|
||||
| 24 | `refreshOAuth` | Custom OAuth refresh |
|
||||
| 25 | `buildAuthDoctorHint` | Auth repair guidance |
|
||||
| 26 | `matchesContextOverflowError` | Provider-owned overflow detection |
|
||||
| 27 | `classifyFailoverReason` | Provider-owned rate-limit/overload classification |
|
||||
| 28 | `isCacheTtlEligible` | Prompt cache TTL gating |
|
||||
| 29 | `buildMissingAuthMessage` | Custom missing-auth hint |
|
||||
| 30 | `suppressBuiltInModel` | Hide stale upstream rows |
|
||||
| 31 | `augmentModelCatalog` | Synthetic forward-compat rows |
|
||||
| 32 | `isBinaryThinking` | Binary thinking on/off |
|
||||
| 33 | `supportsXHighThinking` | `xhigh` reasoning support |
|
||||
| 34 | `resolveDefaultThinkingLevel` | Default `/think` policy |
|
||||
| 35 | `isModernModelRef` | Live/smoke model matching |
|
||||
| 36 | `prepareRuntimeAuth` | Token exchange before inference |
|
||||
| 37 | `resolveUsageAuth` | Custom usage credential parsing |
|
||||
| 38 | `fetchUsageSnapshot` | Custom usage endpoint |
|
||||
| 39 | `createEmbeddingProvider` | Provider-owned embedding adapter for memory/search |
|
||||
| 40 | `buildReplayPolicy` | Custom transcript replay/compaction policy |
|
||||
| 41 | `sanitizeReplayHistory` | Provider-specific replay rewrites after generic cleanup |
|
||||
| 42 | `validateReplayTurns` | Strict replay-turn validation before the embedded runner |
|
||||
| 43 | `onModelSelected` | Post-selection callback (e.g. telemetry) |
|
||||
|
||||
Prompt tuning note:
|
||||
|
||||
- `resolveSystemPromptContribution` lets a provider inject cache-aware
|
||||
system-prompt guidance for a model family. Prefer it over
|
||||
`before_prompt_build` when the behavior belongs to one provider/model
|
||||
family and should preserve the stable/dynamic cache split.
|
||||
|
||||
For detailed descriptions and real-world examples, see
|
||||
[Internals: Provider Runtime Hooks](/plugins/architecture#provider-runtime-hooks).
|
||||
</Accordion>
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Add extra capabilities (optional)">
|
||||
<a id="step-5-add-extra-capabilities"></a>
|
||||
A provider plugin can register speech, realtime transcription, realtime
|
||||
voice, media understanding, image generation, video generation, web fetch,
|
||||
and web search alongside text inference:
|
||||
|
||||
```typescript
|
||||
register(api) {
|
||||
api.registerProvider({ id: "acme-ai", /* ... */ });
|
||||
|
||||
api.registerSpeechProvider({
|
||||
id: "acme-ai",
|
||||
label: "Acme Speech",
|
||||
isConfigured: ({ config }) => Boolean(config.messages?.tts),
|
||||
synthesize: async (req) => ({
|
||||
audioBuffer: Buffer.from(/* PCM data */),
|
||||
outputFormat: "mp3",
|
||||
fileExtension: ".mp3",
|
||||
voiceCompatible: false,
|
||||
}),
|
||||
});
|
||||
|
||||
api.registerRealtimeTranscriptionProvider({
|
||||
id: "acme-ai",
|
||||
label: "Acme Realtime Transcription",
|
||||
isConfigured: () => true,
|
||||
createSession: (req) => ({
|
||||
connect: async () => {},
|
||||
sendAudio: () => {},
|
||||
close: () => {},
|
||||
isConnected: () => true,
|
||||
}),
|
||||
});
|
||||
|
||||
api.registerRealtimeVoiceProvider({
|
||||
id: "acme-ai",
|
||||
label: "Acme Realtime Voice",
|
||||
isConfigured: ({ providerConfig }) => Boolean(providerConfig.apiKey),
|
||||
createBridge: (req) => ({
|
||||
connect: async () => {},
|
||||
sendAudio: () => {},
|
||||
setMediaTimestamp: () => {},
|
||||
submitToolResult: () => {},
|
||||
acknowledgeMark: () => {},
|
||||
close: () => {},
|
||||
isConnected: () => true,
|
||||
}),
|
||||
});
|
||||
|
||||
api.registerMediaUnderstandingProvider({
|
||||
id: "acme-ai",
|
||||
capabilities: ["image", "audio"],
|
||||
describeImage: async (req) => ({ text: "A photo of..." }),
|
||||
transcribeAudio: async (req) => ({ text: "Transcript..." }),
|
||||
});
|
||||
|
||||
api.registerImageGenerationProvider({
|
||||
id: "acme-ai",
|
||||
label: "Acme Images",
|
||||
generate: async (req) => ({ /* image result */ }),
|
||||
});
|
||||
|
||||
api.registerVideoGenerationProvider({
|
||||
id: "acme-ai",
|
||||
label: "Acme Video",
|
||||
capabilities: {
|
||||
generate: {
|
||||
maxVideos: 1,
|
||||
maxDurationSeconds: 10,
|
||||
supportsResolution: true,
|
||||
},
|
||||
imageToVideo: {
|
||||
enabled: true,
|
||||
maxVideos: 1,
|
||||
maxInputImages: 1,
|
||||
maxDurationSeconds: 5,
|
||||
},
|
||||
videoToVideo: {
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
generateVideo: async (req) => ({ videos: [] }),
|
||||
});
|
||||
|
||||
api.registerWebFetchProvider({
|
||||
id: "acme-ai-fetch",
|
||||
label: "Acme Fetch",
|
||||
hint: "Fetch pages through Acme's rendering backend.",
|
||||
envVars: ["ACME_FETCH_API_KEY"],
|
||||
placeholder: "acme-...",
|
||||
signupUrl: "https://acme.example.com/fetch",
|
||||
credentialPath: "plugins.entries.acme.config.webFetch.apiKey",
|
||||
getCredentialValue: (fetchConfig) => fetchConfig?.acme?.apiKey,
|
||||
setCredentialValue: (fetchConfigTarget, value) => {
|
||||
const acme = (fetchConfigTarget.acme ??= {});
|
||||
acme.apiKey = value;
|
||||
},
|
||||
createTool: () => ({
|
||||
description: "Fetch a page through Acme Fetch.",
|
||||
parameters: {},
|
||||
execute: async (args) => ({ content: [] }),
|
||||
}),
|
||||
});
|
||||
|
||||
api.registerWebSearchProvider({
|
||||
id: "acme-ai-search",
|
||||
label: "Acme Search",
|
||||
search: async (req) => ({ content: [] }),
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
OpenClaw classifies this as a **hybrid-capability** plugin. This is the
|
||||
recommended pattern for company plugins (one plugin per vendor). See
|
||||
[Internals: Capability Ownership](/plugins/architecture#capability-ownership-model).
|
||||
|
||||
For video generation, prefer the mode-aware capability shape shown above:
|
||||
`generate`, `imageToVideo`, and `videoToVideo`. Flat aggregate fields such
|
||||
as `maxInputImages`, `maxInputVideos`, and `maxDurationSeconds` are not
|
||||
enough to advertise transform-mode support or disabled modes cleanly.
|
||||
|
||||
Music-generation providers should follow the same pattern:
|
||||
`generate` for prompt-only generation and `edit` for reference-image-based
|
||||
generation. Flat aggregate fields such as `maxInputImages`,
|
||||
`supportsLyrics`, and `supportsFormat` are not enough to advertise edit
|
||||
support; explicit `generate` / `edit` blocks are the expected contract.
|
||||
|
||||
</Step>
|
||||
|
||||
<Step title="Test">
|
||||
<a id="step-6-test"></a>
|
||||
```typescript src/provider.test.ts
|
||||
import { describe, it, expect } from "vitest";
|
||||
// Export your provider config object from index.ts or a dedicated file
|
||||
import { acmeProvider } from "./provider.js";
|
||||
|
||||
describe("acme-ai provider", () => {
|
||||
it("resolves dynamic models", () => {
|
||||
const model = acmeProvider.resolveDynamicModel!({
|
||||
modelId: "acme-beta-v3",
|
||||
} as any);
|
||||
expect(model.id).toBe("acme-beta-v3");
|
||||
expect(model.provider).toBe("acme-ai");
|
||||
});
|
||||
|
||||
it("returns catalog when key is available", async () => {
|
||||
const result = await acmeProvider.catalog!.run({
|
||||
resolveProviderApiKey: () => ({ apiKey: "test-key" }),
|
||||
} as any);
|
||||
expect(result?.provider?.models).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("returns null catalog when no key", async () => {
|
||||
const result = await acmeProvider.catalog!.run({
|
||||
resolveProviderApiKey: () => ({ apiKey: undefined }),
|
||||
} as any);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Publish to ClawHub
|
||||
|
||||
Provider plugins publish the same way as any other external code plugin:
|
||||
|
||||
```bash
|
||||
clawhub package publish your-org/your-plugin --dry-run
|
||||
clawhub package publish your-org/your-plugin
|
||||
```
|
||||
|
||||
Do not use the legacy skill-only publish alias here; plugin packages should use
|
||||
`clawhub package publish`.
|
||||
|
||||
## File structure
|
||||
|
||||
```
|
||||
<bundled-plugin-root>/acme-ai/
|
||||
├── package.json # openclaw.providers metadata
|
||||
├── openclaw.plugin.json # Manifest with provider auth metadata
|
||||
├── index.ts # definePluginEntry + registerProvider
|
||||
└── src/
|
||||
├── provider.test.ts # Tests
|
||||
└── usage.ts # Usage endpoint (optional)
|
||||
```
|
||||
|
||||
## Catalog order reference
|
||||
|
||||
`catalog.order` controls when your catalog merges relative to built-in
|
||||
providers:
|
||||
|
||||
| Order | When | Use case |
|
||||
| --------- | ------------- | ----------------------------------------------- |
|
||||
| `simple` | First pass | Plain API-key providers |
|
||||
| `profile` | After simple | Providers gated on auth profiles |
|
||||
| `paired` | After profile | Synthesize multiple related entries |
|
||||
| `late` | Last pass | Override existing providers (wins on collision) |
|
||||
|
||||
## Next steps
|
||||
|
||||
- [Channel Plugins](/plugins/sdk-channel-plugins) — if your plugin also provides a channel
|
||||
- [SDK Runtime](/plugins/sdk-runtime) — `api.runtime` helpers (TTS, search, subagent)
|
||||
- [SDK Overview](/plugins/sdk-overview) — full subpath import reference
|
||||
- [Plugin Internals](/plugins/architecture#provider-runtime-hooks) — hook details and bundled examples
|
||||
434
openclaw/docs/plugins/sdk-runtime.md
Normal file
434
openclaw/docs/plugins/sdk-runtime.md
Normal file
|
|
@ -0,0 +1,434 @@
|
|||
---
|
||||
title: "Plugin Runtime Helpers"
|
||||
sidebarTitle: "Runtime Helpers"
|
||||
summary: "api.runtime -- the injected runtime helpers available to plugins"
|
||||
read_when:
|
||||
- You need to call core helpers from a plugin (TTS, STT, image gen, web search, subagent)
|
||||
- You want to understand what api.runtime exposes
|
||||
- You are accessing config, agent, or media helpers from plugin code
|
||||
---
|
||||
|
||||
# Plugin Runtime Helpers
|
||||
|
||||
Reference for the `api.runtime` object injected into every plugin during
|
||||
registration. Use these helpers instead of importing host internals directly.
|
||||
|
||||
<Tip>
|
||||
**Looking for a walkthrough?** See [Channel Plugins](/plugins/sdk-channel-plugins)
|
||||
or [Provider Plugins](/plugins/sdk-provider-plugins) for step-by-step guides
|
||||
that show these helpers in context.
|
||||
</Tip>
|
||||
|
||||
```typescript
|
||||
register(api) {
|
||||
const runtime = api.runtime;
|
||||
}
|
||||
```
|
||||
|
||||
## Runtime namespaces
|
||||
|
||||
### `api.runtime.agent`
|
||||
|
||||
Agent identity, directories, and session management.
|
||||
|
||||
```typescript
|
||||
// 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);
|
||||
|
||||
// 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(...)` 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 compatibility alias.
|
||||
|
||||
**Session store helpers** are under `api.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`
|
||||
|
||||
Default model and provider constants:
|
||||
|
||||
```typescript
|
||||
const model = api.runtime.agent.defaults.model; // e.g. "anthropic/claude-sonnet-4-6"
|
||||
const provider = api.runtime.agent.defaults.provider; // e.g. "anthropic"
|
||||
```
|
||||
|
||||
### `api.runtime.subagent`
|
||||
|
||||
Launch and manage background subagent runs.
|
||||
|
||||
```typescript
|
||||
// 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",
|
||||
});
|
||||
```
|
||||
|
||||
<Warning>
|
||||
Model overrides (`provider`/`model`) require operator opt-in via
|
||||
`plugins.entries.<id>.subagent.allowModelOverride: true` in config.
|
||||
Untrusted plugins can still run subagents, but override requests are rejected.
|
||||
</Warning>
|
||||
|
||||
### `api.runtime.taskFlow`
|
||||
|
||||
Bind a Task Flow runtime to an existing OpenClaw session key or trusted tool
|
||||
context, then create and manage Task Flows without passing an owner on every call.
|
||||
|
||||
```typescript
|
||||
const taskFlow = api.runtime.taskFlow.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" },
|
||||
});
|
||||
```
|
||||
|
||||
Use `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`
|
||||
|
||||
Text-to-speech synthesis.
|
||||
|
||||
```typescript
|
||||
// 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,
|
||||
});
|
||||
```
|
||||
|
||||
Uses core `messages.tts` configuration and provider selection. Returns PCM audio
|
||||
buffer + sample rate.
|
||||
|
||||
### `api.runtime.mediaUnderstanding`
|
||||
|
||||
Image, audio, and video analysis.
|
||||
|
||||
```typescript
|
||||
// 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,
|
||||
});
|
||||
```
|
||||
|
||||
Returns `{ text: undefined }` when no output is produced (e.g. skipped input).
|
||||
|
||||
<Info>
|
||||
`api.runtime.stt.transcribeAudioFile(...)` remains as a compatibility alias
|
||||
for `api.runtime.mediaUnderstanding.transcribeAudioFile(...)`.
|
||||
</Info>
|
||||
|
||||
### `api.runtime.imageGeneration`
|
||||
|
||||
Image generation.
|
||||
|
||||
```typescript
|
||||
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 });
|
||||
```
|
||||
|
||||
### `api.runtime.webSearch`
|
||||
|
||||
Web search.
|
||||
|
||||
```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`
|
||||
|
||||
Low-level media utilities.
|
||||
|
||||
```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`
|
||||
|
||||
Config load and write.
|
||||
|
||||
```typescript
|
||||
const cfg = await api.runtime.config.loadConfig();
|
||||
await api.runtime.config.writeConfigFile(cfg);
|
||||
```
|
||||
|
||||
### `api.runtime.system`
|
||||
|
||||
System-level utilities.
|
||||
|
||||
```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`
|
||||
|
||||
Event subscriptions.
|
||||
|
||||
```typescript
|
||||
api.runtime.events.onAgentEvent((event) => {
|
||||
/* ... */
|
||||
});
|
||||
api.runtime.events.onSessionTranscriptUpdate((update) => {
|
||||
/* ... */
|
||||
});
|
||||
```
|
||||
|
||||
### `api.runtime.logging`
|
||||
|
||||
Logging.
|
||||
|
||||
```typescript
|
||||
const verbose = api.runtime.logging.shouldLogVerbose();
|
||||
const childLogger = api.runtime.logging.getChildLogger({ plugin: "my-plugin" }, { level: "debug" });
|
||||
```
|
||||
|
||||
### `api.runtime.modelAuth`
|
||||
|
||||
Model and provider auth resolution.
|
||||
|
||||
```typescript
|
||||
const auth = await api.runtime.modelAuth.getApiKeyForModel({ model, cfg });
|
||||
const providerAuth = await api.runtime.modelAuth.resolveApiKeyForProvider({
|
||||
provider: "openai",
|
||||
cfg,
|
||||
});
|
||||
```
|
||||
|
||||
### `api.runtime.state`
|
||||
|
||||
State directory resolution.
|
||||
|
||||
```typescript
|
||||
const stateDir = api.runtime.state.resolveStateDir();
|
||||
```
|
||||
|
||||
### `api.runtime.tools`
|
||||
|
||||
Memory tool factories and CLI.
|
||||
|
||||
```typescript
|
||||
const getTool = api.runtime.tools.createMemoryGetTool(/* ... */);
|
||||
const searchTool = api.runtime.tools.createMemorySearchTool(/* ... */);
|
||||
api.runtime.tools.registerMemoryCli(/* ... */);
|
||||
```
|
||||
|
||||
### `api.runtime.channel`
|
||||
|
||||
Channel-specific runtime helpers (available when a channel plugin is loaded).
|
||||
|
||||
`api.runtime.channel.mentions` is the shared inbound mention-policy surface for
|
||||
bundled channel plugins that use runtime injection:
|
||||
|
||||
```typescript
|
||||
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,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Available mention helpers:
|
||||
|
||||
- `buildMentionRegexes`
|
||||
- `matchesMentionPatterns`
|
||||
- `matchesMentionWithExplicit`
|
||||
- `implicitMentionKindWhen`
|
||||
- `resolveInboundMentionDecision`
|
||||
|
||||
`api.runtime.channel.mentions` intentionally does not expose the older
|
||||
`resolveMentionGating*` compatibility helpers. Prefer the normalized
|
||||
`{ facts, policy }` path.
|
||||
|
||||
## Storing runtime references
|
||||
|
||||
Use `createPluginRuntimeStore` to store the runtime reference for use outside
|
||||
the `register` callback:
|
||||
|
||||
```typescript
|
||||
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",
|
||||
});
|
||||
|
||||
// In your entry point
|
||||
export default defineChannelPluginEntry({
|
||||
id: "my-plugin",
|
||||
name: "My Plugin",
|
||||
description: "Example",
|
||||
plugin: myPlugin,
|
||||
setRuntime: store.setRuntime,
|
||||
});
|
||||
|
||||
// In other files
|
||||
export function getRuntime() {
|
||||
return store.getRuntime(); // throws if not initialized
|
||||
}
|
||||
|
||||
export function tryGetRuntime() {
|
||||
return store.tryGetRuntime(); // returns null if not initialized
|
||||
}
|
||||
```
|
||||
|
||||
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:
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------------------ | ------------------------- | ------------------------------------------------------------------------------------------- |
|
||||
| `api.id` | `string` | Plugin id |
|
||||
| `api.name` | `string` | Plugin display name |
|
||||
| `api.config` | `OpenClawConfig` | Current config snapshot (active in-memory runtime snapshot when available) |
|
||||
| `api.pluginConfig` | `Record<string, unknown>` | Plugin-specific config from `plugins.entries.<id>.config` |
|
||||
| `api.logger` | `PluginLogger` | Scoped logger (`debug`, `info`, `warn`, `error`) |
|
||||
| `api.registrationMode` | `PluginRegistrationMode` | Current load mode; `"setup-runtime"` is the lightweight pre-full-entry startup/setup window |
|
||||
| `api.resolvePath(input)` | `(string) => string` | Resolve a path relative to the plugin root |
|
||||
|
||||
## Related
|
||||
|
||||
- [SDK Overview](/plugins/sdk-overview) -- subpath reference
|
||||
- [SDK Entry Points](/plugins/sdk-entrypoints) -- `definePluginEntry` options
|
||||
- [Plugin Internals](/plugins/architecture) -- capability model and registry
|
||||
536
openclaw/docs/plugins/sdk-setup.md
Normal file
536
openclaw/docs/plugins/sdk-setup.md
Normal file
|
|
@ -0,0 +1,536 @@
|
|||
---
|
||||
title: "Plugin Setup and Config"
|
||||
sidebarTitle: "Setup and Config"
|
||||
summary: "Setup wizards, setup-entry.ts, config schemas, and package.json metadata"
|
||||
read_when:
|
||||
- You are adding a setup wizard to a plugin
|
||||
- You need to understand setup-entry.ts vs index.ts
|
||||
- You are defining plugin config schemas or package.json openclaw metadata
|
||||
---
|
||||
|
||||
# Plugin Setup and Config
|
||||
|
||||
Reference for plugin packaging (`package.json` metadata), manifests
|
||||
(`openclaw.plugin.json`), setup entries, and config schemas.
|
||||
|
||||
<Tip>
|
||||
**Looking for a walkthrough?** The how-to guides cover packaging in context:
|
||||
[Channel Plugins](/plugins/sdk-channel-plugins#step-1-package-and-manifest) and
|
||||
[Provider Plugins](/plugins/sdk-provider-plugins#step-1-package-and-manifest).
|
||||
</Tip>
|
||||
|
||||
## Package metadata
|
||||
|
||||
Your `package.json` needs an `openclaw` field that tells the plugin system what
|
||||
your plugin provides:
|
||||
|
||||
**Channel plugin:**
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "@myorg/openclaw-my-channel",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"setupEntry": "./setup-entry.ts",
|
||||
"channel": {
|
||||
"id": "my-channel",
|
||||
"label": "My Channel",
|
||||
"blurb": "Short description of the channel."
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Provider plugin / ClawHub publish baseline:**
|
||||
|
||||
```json openclaw-clawhub-package.json
|
||||
{
|
||||
"name": "@myorg/openclaw-my-plugin",
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"compat": {
|
||||
"pluginApi": ">=2026.3.24-beta.2",
|
||||
"minGatewayVersion": "2026.3.24-beta.2"
|
||||
},
|
||||
"build": {
|
||||
"openclawVersion": "2026.3.24-beta.2",
|
||||
"pluginSdkVersion": "2026.3.24-beta.2"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If you publish the plugin externally on ClawHub, those `compat` and `build`
|
||||
fields are required. The canonical publish snippets live in
|
||||
`docs/snippets/plugin-publish/`.
|
||||
|
||||
### `openclaw` fields
|
||||
|
||||
| Field | Type | Description |
|
||||
| ------------ | ---------- | ------------------------------------------------------------------------------------------------------ |
|
||||
| `extensions` | `string[]` | Entry point files (relative to package root) |
|
||||
| `setupEntry` | `string` | Lightweight setup-only entry (optional) |
|
||||
| `channel` | `object` | Channel catalog metadata for setup, picker, quickstart, and status surfaces |
|
||||
| `providers` | `string[]` | Provider ids registered by this plugin |
|
||||
| `install` | `object` | Install hints: `npmSpec`, `localPath`, `defaultChoice`, `minHostVersion`, `allowInvalidConfigRecovery` |
|
||||
| `startup` | `object` | Startup behavior flags |
|
||||
|
||||
### `openclaw.channel`
|
||||
|
||||
`openclaw.channel` is cheap package metadata for channel discovery and setup
|
||||
surfaces before runtime loads.
|
||||
|
||||
| Field | Type | What it means |
|
||||
| -------------------------------------- | ---------- | ----------------------------------------------------------------------------- |
|
||||
| `id` | `string` | Canonical channel id. |
|
||||
| `label` | `string` | Primary channel label. |
|
||||
| `selectionLabel` | `string` | Picker/setup label when it should differ from `label`. |
|
||||
| `detailLabel` | `string` | Secondary detail label for richer channel catalogs and status surfaces. |
|
||||
| `docsPath` | `string` | Docs path for setup and selection links. |
|
||||
| `docsLabel` | `string` | Override label used for docs links when it should differ from the channel id. |
|
||||
| `blurb` | `string` | Short onboarding/catalog description. |
|
||||
| `order` | `number` | Sort order in channel catalogs. |
|
||||
| `aliases` | `string[]` | Extra lookup aliases for channel selection. |
|
||||
| `preferOver` | `string[]` | Lower-priority plugin/channel ids this channel should outrank. |
|
||||
| `systemImage` | `string` | Optional icon/system-image name for channel UI catalogs. |
|
||||
| `selectionDocsPrefix` | `string` | Prefix text before docs links in selection surfaces. |
|
||||
| `selectionDocsOmitLabel` | `boolean` | Show the docs path directly instead of a labeled docs link in selection copy. |
|
||||
| `selectionExtras` | `string[]` | Extra short strings appended in selection copy. |
|
||||
| `markdownCapable` | `boolean` | Marks the channel as markdown-capable for outbound formatting decisions. |
|
||||
| `exposure` | `object` | Channel visibility controls for setup, configured lists, and docs surfaces. |
|
||||
| `quickstartAllowFrom` | `boolean` | Opt this channel into the standard quickstart `allowFrom` setup flow. |
|
||||
| `forceAccountBinding` | `boolean` | Require explicit account binding even when only one account exists. |
|
||||
| `preferSessionLookupForAnnounceTarget` | `boolean` | Prefer session lookup when resolving announce targets for this channel. |
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"openclaw": {
|
||||
"channel": {
|
||||
"id": "my-channel",
|
||||
"label": "My Channel",
|
||||
"selectionLabel": "My Channel (self-hosted)",
|
||||
"detailLabel": "My Channel Bot",
|
||||
"docsPath": "/channels/my-channel",
|
||||
"docsLabel": "my-channel",
|
||||
"blurb": "Webhook-based self-hosted chat integration.",
|
||||
"order": 80,
|
||||
"aliases": ["mc"],
|
||||
"preferOver": ["my-channel-legacy"],
|
||||
"selectionDocsPrefix": "Guide:",
|
||||
"selectionExtras": ["Markdown"],
|
||||
"markdownCapable": true,
|
||||
"exposure": {
|
||||
"configured": true,
|
||||
"setup": true,
|
||||
"docs": true
|
||||
},
|
||||
"quickstartAllowFrom": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`exposure` supports:
|
||||
|
||||
- `configured`: include the channel in configured/status-style listing surfaces
|
||||
- `setup`: include the channel in interactive setup/configure pickers
|
||||
- `docs`: mark the channel as public-facing in docs/navigation surfaces
|
||||
|
||||
`showConfigured` and `showInSetup` remain supported as legacy aliases. Prefer
|
||||
`exposure`.
|
||||
|
||||
### `openclaw.install`
|
||||
|
||||
`openclaw.install` is package metadata, not manifest metadata.
|
||||
|
||||
| Field | Type | What it means |
|
||||
| ---------------------------- | -------------------- | -------------------------------------------------------------------------------- |
|
||||
| `npmSpec` | `string` | Canonical npm spec for install/update flows. |
|
||||
| `localPath` | `string` | Local development or bundled install path. |
|
||||
| `defaultChoice` | `"npm"` \| `"local"` | Preferred install source when both are available. |
|
||||
| `minHostVersion` | `string` | Minimum supported OpenClaw version in the form `>=x.y.z`. |
|
||||
| `allowInvalidConfigRecovery` | `boolean` | Lets bundled-plugin reinstall flows recover from specific stale-config failures. |
|
||||
|
||||
If `minHostVersion` is set, install and manifest-registry loading both enforce
|
||||
it. Older hosts skip the plugin; invalid version strings are rejected.
|
||||
|
||||
`allowInvalidConfigRecovery` is not a general bypass for broken configs. It is
|
||||
for narrow bundled-plugin recovery only, so reinstall/setup can repair known
|
||||
upgrade leftovers like a missing bundled plugin path or stale `channels.<id>`
|
||||
entry for that same plugin. If config is broken for unrelated reasons, install
|
||||
still fails closed and tells the operator to run `openclaw doctor --fix`.
|
||||
|
||||
### Deferred full load
|
||||
|
||||
Channel plugins can opt into deferred loading with:
|
||||
|
||||
```json
|
||||
{
|
||||
"openclaw": {
|
||||
"extensions": ["./index.ts"],
|
||||
"setupEntry": "./setup-entry.ts",
|
||||
"startup": {
|
||||
"deferConfiguredChannelFullLoadUntilAfterListen": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
When enabled, OpenClaw loads only `setupEntry` during the pre-listen startup
|
||||
phase, even for already-configured channels. The full entry loads after the
|
||||
gateway starts listening.
|
||||
|
||||
<Warning>
|
||||
Only enable deferred loading when your `setupEntry` registers everything the
|
||||
gateway needs before it starts listening (channel registration, HTTP routes,
|
||||
gateway methods). If the full entry owns required startup capabilities, keep
|
||||
the default behavior.
|
||||
</Warning>
|
||||
|
||||
If your setup/full entry registers gateway RPC methods, keep them on a
|
||||
plugin-specific prefix. Reserved core admin namespaces (`config.*`,
|
||||
`exec.approvals.*`, `wizard.*`, `update.*`) stay core-owned and always resolve
|
||||
to `operator.admin`.
|
||||
|
||||
## Plugin manifest
|
||||
|
||||
Every native plugin must ship an `openclaw.plugin.json` in the package root.
|
||||
OpenClaw uses this to validate config without executing plugin code.
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-plugin",
|
||||
"name": "My Plugin",
|
||||
"description": "Adds My Plugin capabilities to OpenClaw",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {
|
||||
"webhookSecret": {
|
||||
"type": "string",
|
||||
"description": "Webhook verification secret"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For channel plugins, add `kind` and `channels`:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-channel",
|
||||
"kind": "channel",
|
||||
"channels": ["my-channel"],
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false,
|
||||
"properties": {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Even plugins with no config must ship a schema. An empty schema is valid:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "my-plugin",
|
||||
"configSchema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See [Plugin Manifest](/plugins/manifest) for the full schema reference.
|
||||
|
||||
## ClawHub publishing
|
||||
|
||||
For plugin packages, use the package-specific ClawHub command:
|
||||
|
||||
```bash
|
||||
clawhub package publish your-org/your-plugin --dry-run
|
||||
clawhub package publish your-org/your-plugin
|
||||
```
|
||||
|
||||
The legacy skill-only publish alias is for skills. Plugin packages should
|
||||
always use `clawhub package publish`.
|
||||
|
||||
## Setup entry
|
||||
|
||||
The `setup-entry.ts` file is a lightweight alternative to `index.ts` that
|
||||
OpenClaw loads when it only needs setup surfaces (onboarding, config repair,
|
||||
disabled channel inspection).
|
||||
|
||||
```typescript
|
||||
// setup-entry.ts
|
||||
import { defineSetupPluginEntry } from "openclaw/plugin-sdk/channel-core";
|
||||
import { myChannelPlugin } from "./src/channel.js";
|
||||
|
||||
export default defineSetupPluginEntry(myChannelPlugin);
|
||||
```
|
||||
|
||||
This avoids loading heavy runtime code (crypto libraries, CLI registrations,
|
||||
background services) during setup flows.
|
||||
|
||||
Bundled workspace channels that keep setup-safe exports in sidecar modules can
|
||||
use `defineBundledChannelSetupEntry(...)` from
|
||||
`openclaw/plugin-sdk/channel-entry-contract` instead of
|
||||
`defineSetupPluginEntry(...)`. That bundled contract also supports an optional
|
||||
`runtime` export so setup-time runtime wiring can stay lightweight and explicit.
|
||||
|
||||
**When OpenClaw uses `setupEntry` instead of the full entry:**
|
||||
|
||||
- The channel is disabled but needs setup/onboarding surfaces
|
||||
- The channel is enabled but unconfigured
|
||||
- Deferred loading is enabled (`deferConfiguredChannelFullLoadUntilAfterListen`)
|
||||
|
||||
**What `setupEntry` must register:**
|
||||
|
||||
- The channel plugin object (via `defineSetupPluginEntry`)
|
||||
- Any HTTP routes required before gateway listen
|
||||
- Any gateway methods needed during startup
|
||||
|
||||
Those startup gateway methods should still avoid reserved core admin
|
||||
namespaces such as `config.*` or `update.*`.
|
||||
|
||||
**What `setupEntry` should NOT include:**
|
||||
|
||||
- CLI registrations
|
||||
- Background services
|
||||
- Heavy runtime imports (crypto, SDKs)
|
||||
- Gateway methods only needed after startup
|
||||
|
||||
### Narrow setup helper imports
|
||||
|
||||
For hot setup-only paths, prefer the narrow setup helper seams over the broader
|
||||
`plugin-sdk/setup` umbrella when you only need part of the setup surface:
|
||||
|
||||
| Import path | Use it for | Key exports |
|
||||
| ---------------------------------- | ----------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `plugin-sdk/setup-runtime` | setup-time runtime helpers that stay available in `setupEntry` / deferred channel startup | `createPatchedAccountSetupAdapter`, `createEnvPatchedAccountSetupAdapter`, `createSetupInputPresenceValidator`, `noteChannelLookupFailure`, `noteChannelLookupSummary`, `promptResolvedAllowFrom`, `splitSetupEntries`, `createAllowlistSetupWizardProxy`, `createDelegatedSetupWizardProxy` |
|
||||
| `plugin-sdk/setup-adapter-runtime` | environment-aware account setup adapters | `createEnvPatchedAccountSetupAdapter` |
|
||||
| `plugin-sdk/setup-tools` | setup/install CLI/archive/docs helpers | `formatCliCommand`, `detectBinary`, `extractArchive`, `resolveBrewExecutable`, `formatDocsLink`, `CONFIG_DIR` |
|
||||
|
||||
Use the broader `plugin-sdk/setup` seam when you want the full shared setup
|
||||
toolbox, including config-patch helpers such as
|
||||
`moveSingleAccountChannelSectionToDefaultAccount(...)`.
|
||||
|
||||
The setup patch adapters stay hot-path safe on import. Their bundled
|
||||
single-account promotion contract-surface lookup is lazy, so importing
|
||||
`plugin-sdk/setup-runtime` does not eagerly load bundled contract-surface
|
||||
discovery before the adapter is actually used.
|
||||
|
||||
### Channel-owned single-account promotion
|
||||
|
||||
When a channel upgrades from a single-account top-level config to
|
||||
`channels.<id>.accounts.*`, the default shared behavior is to move promoted
|
||||
account-scoped values into `accounts.default`.
|
||||
|
||||
Bundled channels can narrow or override that promotion through their setup
|
||||
contract surface:
|
||||
|
||||
- `singleAccountKeysToMove`: extra top-level keys that should move into the
|
||||
promoted account
|
||||
- `namedAccountPromotionKeys`: when named accounts already exist, only these
|
||||
keys move into the promoted account; shared policy/delivery keys stay at the
|
||||
channel root
|
||||
- `resolveSingleAccountPromotionTarget(...)`: choose which existing account
|
||||
receives promoted values
|
||||
|
||||
Matrix is the current bundled example. If exactly one named Matrix account
|
||||
already exists, or if `defaultAccount` points at an existing non-canonical key
|
||||
such as `Ops`, promotion preserves that account instead of creating a new
|
||||
`accounts.default` entry.
|
||||
|
||||
## Config schema
|
||||
|
||||
Plugin config is validated against the JSON Schema in your manifest. Users
|
||||
configure plugins via:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"my-plugin": {
|
||||
config: {
|
||||
webhookSecret: "abc123",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Your plugin receives this config as `api.pluginConfig` during registration.
|
||||
|
||||
For channel-specific config, use the channel config section instead:
|
||||
|
||||
```json5
|
||||
{
|
||||
channels: {
|
||||
"my-channel": {
|
||||
token: "bot-token",
|
||||
allowFrom: ["user1", "user2"],
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
### Building channel config schemas
|
||||
|
||||
Use `buildChannelConfigSchema` from `openclaw/plugin-sdk/core` to convert a
|
||||
Zod schema into the `ChannelConfigSchema` wrapper that OpenClaw validates:
|
||||
|
||||
```typescript
|
||||
import { z } from "zod";
|
||||
import { buildChannelConfigSchema } from "openclaw/plugin-sdk/core";
|
||||
|
||||
const accountSchema = z.object({
|
||||
token: z.string().optional(),
|
||||
allowFrom: z.array(z.string()).optional(),
|
||||
accounts: z.object({}).catchall(z.any()).optional(),
|
||||
defaultAccount: z.string().optional(),
|
||||
});
|
||||
|
||||
const configSchema = buildChannelConfigSchema(accountSchema);
|
||||
```
|
||||
|
||||
## Setup wizards
|
||||
|
||||
Channel plugins can provide interactive setup wizards for `openclaw onboard`.
|
||||
The wizard is a `ChannelSetupWizard` object on the `ChannelPlugin`:
|
||||
|
||||
```typescript
|
||||
import type { ChannelSetupWizard } from "openclaw/plugin-sdk/channel-setup";
|
||||
|
||||
const setupWizard: ChannelSetupWizard = {
|
||||
channel: "my-channel",
|
||||
status: {
|
||||
configuredLabel: "Connected",
|
||||
unconfiguredLabel: "Not configured",
|
||||
resolveConfigured: ({ cfg }) => Boolean((cfg.channels as any)?.["my-channel"]?.token),
|
||||
},
|
||||
credentials: [
|
||||
{
|
||||
inputKey: "token",
|
||||
providerHint: "my-channel",
|
||||
credentialLabel: "Bot token",
|
||||
preferredEnvVar: "MY_CHANNEL_BOT_TOKEN",
|
||||
envPrompt: "Use MY_CHANNEL_BOT_TOKEN from environment?",
|
||||
keepPrompt: "Keep current token?",
|
||||
inputPrompt: "Enter your bot token:",
|
||||
inspect: ({ cfg, accountId }) => {
|
||||
const token = (cfg.channels as any)?.["my-channel"]?.token;
|
||||
return {
|
||||
accountConfigured: Boolean(token),
|
||||
hasConfiguredValue: Boolean(token),
|
||||
};
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
The `ChannelSetupWizard` type supports `credentials`, `textInputs`,
|
||||
`dmPolicy`, `allowFrom`, `groupAccess`, `prepare`, `finalize`, and more.
|
||||
See bundled plugin packages (for example the Discord plugin `src/channel.setup.ts`) for
|
||||
full examples.
|
||||
|
||||
For DM allowlist prompts that only need the standard
|
||||
`note -> prompt -> parse -> merge -> patch` flow, prefer the shared setup
|
||||
helpers from `openclaw/plugin-sdk/setup`: `createPromptParsedAllowFromForAccount(...)`,
|
||||
`createTopLevelChannelParsedAllowFromPrompt(...)`, and
|
||||
`createNestedChannelParsedAllowFromPrompt(...)`.
|
||||
|
||||
For channel setup status blocks that only vary by labels, scores, and optional
|
||||
extra lines, prefer `createStandardChannelSetupStatus(...)` from
|
||||
`openclaw/plugin-sdk/setup` instead of hand-rolling the same `status` object in
|
||||
each plugin.
|
||||
|
||||
For optional setup surfaces that should only appear in certain contexts, use
|
||||
`createOptionalChannelSetupSurface` from `openclaw/plugin-sdk/channel-setup`:
|
||||
|
||||
```typescript
|
||||
import { createOptionalChannelSetupSurface } from "openclaw/plugin-sdk/channel-setup";
|
||||
|
||||
const setupSurface = createOptionalChannelSetupSurface({
|
||||
channel: "my-channel",
|
||||
label: "My Channel",
|
||||
npmSpec: "@myorg/openclaw-my-channel",
|
||||
docsPath: "/channels/my-channel",
|
||||
});
|
||||
// Returns { setupAdapter, setupWizard }
|
||||
```
|
||||
|
||||
`plugin-sdk/channel-setup` also exposes the lower-level
|
||||
`createOptionalChannelSetupAdapter(...)` and
|
||||
`createOptionalChannelSetupWizard(...)` builders when you only need one half of
|
||||
that optional-install surface.
|
||||
|
||||
The generated optional adapter/wizard fail closed on real config writes. They
|
||||
reuse one install-required message across `validateInput`,
|
||||
`applyAccountConfig`, and `finalize`, and append a docs link when `docsPath` is
|
||||
set.
|
||||
|
||||
For binary-backed setup UIs, prefer the shared delegated helpers instead of
|
||||
copying the same binary/status glue into every channel:
|
||||
|
||||
- `createDetectedBinaryStatus(...)` for status blocks that vary only by labels,
|
||||
hints, scores, and binary detection
|
||||
- `createCliPathTextInput(...)` for path-backed text inputs
|
||||
- `createDelegatedSetupWizardStatusResolvers(...)`,
|
||||
`createDelegatedPrepare(...)`, `createDelegatedFinalize(...)`, and
|
||||
`createDelegatedResolveConfigured(...)` when `setupEntry` needs to forward to
|
||||
a heavier full wizard lazily
|
||||
- `createDelegatedTextInputShouldPrompt(...)` when `setupEntry` only needs to
|
||||
delegate a `textInputs[*].shouldPrompt` decision
|
||||
|
||||
## Publishing and installing
|
||||
|
||||
**External plugins:** publish to [ClawHub](/tools/clawhub) or npm, then install:
|
||||
|
||||
```bash
|
||||
openclaw plugins install @myorg/openclaw-my-plugin
|
||||
```
|
||||
|
||||
OpenClaw tries ClawHub first and falls back to npm automatically. You can also
|
||||
force ClawHub explicitly:
|
||||
|
||||
```bash
|
||||
openclaw plugins install clawhub:@myorg/openclaw-my-plugin # ClawHub only
|
||||
```
|
||||
|
||||
There is no matching `npm:` override. Use the normal npm package spec when you
|
||||
want the npm path after ClawHub fallback:
|
||||
|
||||
```bash
|
||||
openclaw plugins install @myorg/openclaw-my-plugin
|
||||
```
|
||||
|
||||
**In-repo plugins:** place under the bundled plugin workspace tree and they are automatically
|
||||
discovered during build.
|
||||
|
||||
**Users can install:**
|
||||
|
||||
```bash
|
||||
openclaw plugins install <package-name>
|
||||
```
|
||||
|
||||
<Info>
|
||||
For npm-sourced installs, `openclaw plugins install` runs
|
||||
`npm install --ignore-scripts` (no lifecycle scripts). Keep plugin dependency
|
||||
trees pure JS/TS and avoid packages that require `postinstall` builds.
|
||||
</Info>
|
||||
|
||||
## Related
|
||||
|
||||
- [SDK Entry Points](/plugins/sdk-entrypoints) -- `definePluginEntry` and `defineChannelPluginEntry`
|
||||
- [Plugin Manifest](/plugins/manifest) -- full manifest schema reference
|
||||
- [Building Plugins](/plugins/building-plugins) -- step-by-step getting started guide
|
||||
266
openclaw/docs/plugins/sdk-testing.md
Normal file
266
openclaw/docs/plugins/sdk-testing.md
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
---
|
||||
title: "Plugin Testing"
|
||||
sidebarTitle: "Testing"
|
||||
summary: "Testing utilities and patterns for OpenClaw plugins"
|
||||
read_when:
|
||||
- You are writing tests for a plugin
|
||||
- You need test utilities from the plugin SDK
|
||||
- You want to understand contract tests for bundled plugins
|
||||
---
|
||||
|
||||
# Plugin Testing
|
||||
|
||||
Reference for test utilities, patterns, and lint enforcement for OpenClaw
|
||||
plugins.
|
||||
|
||||
<Tip>
|
||||
**Looking for test examples?** The how-to guides include worked test examples:
|
||||
[Channel plugin tests](/plugins/sdk-channel-plugins#step-6-test) and
|
||||
[Provider plugin tests](/plugins/sdk-provider-plugins#step-6-test).
|
||||
</Tip>
|
||||
|
||||
## Test utilities
|
||||
|
||||
**Import:** `openclaw/plugin-sdk/testing`
|
||||
|
||||
The testing subpath exports a narrow set of helpers for plugin authors:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
installCommonResolveTargetErrorCases,
|
||||
shouldAckReaction,
|
||||
removeAckReactionAfterReply,
|
||||
} from "openclaw/plugin-sdk/testing";
|
||||
```
|
||||
|
||||
### Available exports
|
||||
|
||||
| Export | Purpose |
|
||||
| -------------------------------------- | ------------------------------------------------------ |
|
||||
| `installCommonResolveTargetErrorCases` | Shared test cases for target resolution error handling |
|
||||
| `shouldAckReaction` | Check whether a channel should add an ack reaction |
|
||||
| `removeAckReactionAfterReply` | Remove ack reaction after reply delivery |
|
||||
|
||||
### Types
|
||||
|
||||
The testing subpath also re-exports types useful in test files:
|
||||
|
||||
```typescript
|
||||
import type {
|
||||
ChannelAccountSnapshot,
|
||||
ChannelGatewayContext,
|
||||
OpenClawConfig,
|
||||
PluginRuntime,
|
||||
RuntimeEnv,
|
||||
MockFn,
|
||||
} from "openclaw/plugin-sdk/testing";
|
||||
```
|
||||
|
||||
## Testing target resolution
|
||||
|
||||
Use `installCommonResolveTargetErrorCases` to add standard error cases for
|
||||
channel target resolution:
|
||||
|
||||
```typescript
|
||||
import { describe } from "vitest";
|
||||
import { installCommonResolveTargetErrorCases } from "openclaw/plugin-sdk/testing";
|
||||
|
||||
describe("my-channel target resolution", () => {
|
||||
installCommonResolveTargetErrorCases({
|
||||
resolveTarget: ({ to, mode, allowFrom }) => {
|
||||
// Your channel's target resolution logic
|
||||
return myChannelResolveTarget({ to, mode, allowFrom });
|
||||
},
|
||||
implicitAllowFrom: ["user1", "user2"],
|
||||
});
|
||||
|
||||
// Add channel-specific test cases
|
||||
it("should resolve @username targets", () => {
|
||||
// ...
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
## Testing patterns
|
||||
|
||||
### Unit testing a channel plugin
|
||||
|
||||
```typescript
|
||||
import { describe, it, expect, vi } from "vitest";
|
||||
|
||||
describe("my-channel plugin", () => {
|
||||
it("should resolve account from config", () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
"my-channel": {
|
||||
token: "test-token",
|
||||
allowFrom: ["user1"],
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const account = myPlugin.setup.resolveAccount(cfg, undefined);
|
||||
expect(account.token).toBe("test-token");
|
||||
});
|
||||
|
||||
it("should inspect account without materializing secrets", () => {
|
||||
const cfg = {
|
||||
channels: {
|
||||
"my-channel": { token: "test-token" },
|
||||
},
|
||||
};
|
||||
|
||||
const inspection = myPlugin.setup.inspectAccount(cfg, undefined);
|
||||
expect(inspection.configured).toBe(true);
|
||||
expect(inspection.tokenStatus).toBe("available");
|
||||
// No token value exposed
|
||||
expect(inspection).not.toHaveProperty("token");
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Unit testing a provider plugin
|
||||
|
||||
```typescript
|
||||
import { describe, it, expect } from "vitest";
|
||||
|
||||
describe("my-provider plugin", () => {
|
||||
it("should resolve dynamic models", () => {
|
||||
const model = myProvider.resolveDynamicModel({
|
||||
modelId: "custom-model-v2",
|
||||
// ... context
|
||||
});
|
||||
|
||||
expect(model.id).toBe("custom-model-v2");
|
||||
expect(model.provider).toBe("my-provider");
|
||||
expect(model.api).toBe("openai-completions");
|
||||
});
|
||||
|
||||
it("should return catalog when API key is available", async () => {
|
||||
const result = await myProvider.catalog.run({
|
||||
resolveProviderApiKey: () => ({ apiKey: "test-key" }),
|
||||
// ... context
|
||||
});
|
||||
|
||||
expect(result?.provider?.models).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Mocking the plugin runtime
|
||||
|
||||
For code that uses `createPluginRuntimeStore`, mock the runtime in tests:
|
||||
|
||||
```typescript
|
||||
import { createPluginRuntimeStore } from "openclaw/plugin-sdk/runtime-store";
|
||||
import type { PluginRuntime } from "openclaw/plugin-sdk/runtime-store";
|
||||
|
||||
const store = createPluginRuntimeStore<PluginRuntime>({
|
||||
pluginId: "test-plugin",
|
||||
errorMessage: "test runtime not set",
|
||||
});
|
||||
|
||||
// In test setup
|
||||
const mockRuntime = {
|
||||
agent: {
|
||||
resolveAgentDir: vi.fn().mockReturnValue("/tmp/agent"),
|
||||
// ... other mocks
|
||||
},
|
||||
config: {
|
||||
loadConfig: vi.fn(),
|
||||
writeConfigFile: vi.fn(),
|
||||
},
|
||||
// ... other namespaces
|
||||
} as unknown as PluginRuntime;
|
||||
|
||||
store.setRuntime(mockRuntime);
|
||||
|
||||
// After tests
|
||||
store.clearRuntime();
|
||||
```
|
||||
|
||||
### Testing with per-instance stubs
|
||||
|
||||
Prefer per-instance stubs over prototype mutation:
|
||||
|
||||
```typescript
|
||||
// Preferred: per-instance stub
|
||||
const client = new MyChannelClient();
|
||||
client.sendMessage = vi.fn().mockResolvedValue({ id: "msg-1" });
|
||||
|
||||
// Avoid: prototype mutation
|
||||
// MyChannelClient.prototype.sendMessage = vi.fn();
|
||||
```
|
||||
|
||||
## Contract tests (in-repo plugins)
|
||||
|
||||
Bundled plugins have contract tests that verify registration ownership:
|
||||
|
||||
```bash
|
||||
pnpm test -- src/plugins/contracts/
|
||||
```
|
||||
|
||||
These tests assert:
|
||||
|
||||
- Which plugins register which providers
|
||||
- Which plugins register which speech providers
|
||||
- Registration shape correctness
|
||||
- Runtime contract compliance
|
||||
|
||||
### Running scoped tests
|
||||
|
||||
For a specific plugin:
|
||||
|
||||
```bash
|
||||
pnpm test -- <bundled-plugin-root>/my-channel/
|
||||
```
|
||||
|
||||
For contract tests only:
|
||||
|
||||
```bash
|
||||
pnpm test -- src/plugins/contracts/shape.contract.test.ts
|
||||
pnpm test -- src/plugins/contracts/auth.contract.test.ts
|
||||
pnpm test -- src/plugins/contracts/runtime.contract.test.ts
|
||||
```
|
||||
|
||||
## Lint enforcement (in-repo plugins)
|
||||
|
||||
Three rules are enforced by `pnpm check` for in-repo plugins:
|
||||
|
||||
1. **No monolithic root imports** -- `openclaw/plugin-sdk` root barrel is rejected
|
||||
2. **No direct `src/` imports** -- plugins cannot import `../../src/` directly
|
||||
3. **No self-imports** -- plugins cannot import their own `plugin-sdk/<name>` subpath
|
||||
|
||||
External plugins are not subject to these lint rules, but following the same
|
||||
patterns is recommended.
|
||||
|
||||
## Test configuration
|
||||
|
||||
OpenClaw uses Vitest with V8 coverage thresholds. For plugin tests:
|
||||
|
||||
```bash
|
||||
# Run all tests
|
||||
pnpm test
|
||||
|
||||
# Run specific plugin tests
|
||||
pnpm test -- <bundled-plugin-root>/my-channel/src/channel.test.ts
|
||||
|
||||
# Run with a specific test name filter
|
||||
pnpm test -- <bundled-plugin-root>/my-channel/ -t "resolves account"
|
||||
|
||||
# Run with coverage
|
||||
pnpm test:coverage
|
||||
```
|
||||
|
||||
If local runs cause memory pressure:
|
||||
|
||||
```bash
|
||||
OPENCLAW_VITEST_MAX_WORKERS=1 pnpm test
|
||||
```
|
||||
|
||||
## Related
|
||||
|
||||
- [SDK Overview](/plugins/sdk-overview) -- import conventions
|
||||
- [SDK Channel Plugins](/plugins/sdk-channel-plugins) -- channel plugin interface
|
||||
- [SDK Provider Plugins](/plugins/sdk-provider-plugins) -- provider plugin hooks
|
||||
- [Building Plugins](/plugins/building-plugins) -- getting started guide
|
||||
466
openclaw/docs/plugins/voice-call.md
Normal file
466
openclaw/docs/plugins/voice-call.md
Normal file
|
|
@ -0,0 +1,466 @@
|
|||
---
|
||||
summary: "Voice Call plugin: outbound + inbound calls via Twilio/Telnyx/Plivo (plugin install + config + CLI)"
|
||||
read_when:
|
||||
- You want to place an outbound voice call from OpenClaw
|
||||
- You are configuring or developing the voice-call plugin
|
||||
title: "Voice Call Plugin"
|
||||
---
|
||||
|
||||
# Voice Call (plugin)
|
||||
|
||||
Voice calls for OpenClaw via a plugin. Supports outbound notifications and
|
||||
multi-turn conversations with inbound policies.
|
||||
|
||||
Current providers:
|
||||
|
||||
- `twilio` (Programmable Voice + Media Streams)
|
||||
- `telnyx` (Call Control v2)
|
||||
- `plivo` (Voice API + XML transfer + GetInput speech)
|
||||
- `mock` (dev/no network)
|
||||
|
||||
Quick mental model:
|
||||
|
||||
- Install plugin
|
||||
- Restart Gateway
|
||||
- Configure under `plugins.entries.voice-call.config`
|
||||
- Use `openclaw voicecall ...` or the `voice_call` tool
|
||||
|
||||
## Where it runs (local vs remote)
|
||||
|
||||
The Voice Call plugin runs **inside the Gateway process**.
|
||||
|
||||
If you use a remote Gateway, install/configure the plugin on the **machine running the Gateway**, then restart the Gateway to load it.
|
||||
|
||||
## Install
|
||||
|
||||
### Option A: install from npm (recommended)
|
||||
|
||||
```bash
|
||||
openclaw plugins install @openclaw/voice-call
|
||||
```
|
||||
|
||||
Restart the Gateway afterwards.
|
||||
|
||||
### Option B: install from a local folder (dev, no copying)
|
||||
|
||||
```bash
|
||||
PLUGIN_SRC=./path/to/local/voice-call-plugin
|
||||
openclaw plugins install "$PLUGIN_SRC"
|
||||
cd "$PLUGIN_SRC" && pnpm install
|
||||
```
|
||||
|
||||
Restart the Gateway afterwards.
|
||||
|
||||
## Config
|
||||
|
||||
Set config under `plugins.entries.voice-call.config`:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"voice-call": {
|
||||
enabled: true,
|
||||
config: {
|
||||
provider: "twilio", // or "telnyx" | "plivo" | "mock"
|
||||
fromNumber: "+15550001234",
|
||||
toNumber: "+15550005678",
|
||||
|
||||
twilio: {
|
||||
accountSid: "ACxxxxxxxx",
|
||||
authToken: "...",
|
||||
},
|
||||
|
||||
telnyx: {
|
||||
apiKey: "...",
|
||||
connectionId: "...",
|
||||
// Telnyx webhook public key from the Telnyx Mission Control Portal
|
||||
// (Base64 string; can also be set via TELNYX_PUBLIC_KEY).
|
||||
publicKey: "...",
|
||||
},
|
||||
|
||||
plivo: {
|
||||
authId: "MAxxxxxxxxxxxxxxxxxxxx",
|
||||
authToken: "...",
|
||||
},
|
||||
|
||||
// Webhook server
|
||||
serve: {
|
||||
port: 3334,
|
||||
path: "/voice/webhook",
|
||||
},
|
||||
|
||||
// Webhook security (recommended for tunnels/proxies)
|
||||
webhookSecurity: {
|
||||
allowedHosts: ["voice.example.com"],
|
||||
trustedProxyIPs: ["100.64.0.1"],
|
||||
},
|
||||
|
||||
// Public exposure (pick one)
|
||||
// publicUrl: "https://example.ngrok.app/voice/webhook",
|
||||
// tunnel: { provider: "ngrok" },
|
||||
// tailscale: { mode: "funnel", path: "/voice/webhook" }
|
||||
|
||||
outbound: {
|
||||
defaultMode: "notify", // notify | conversation
|
||||
},
|
||||
|
||||
streaming: {
|
||||
enabled: true,
|
||||
provider: "openai", // optional; first registered realtime transcription provider when unset
|
||||
streamPath: "/voice/stream",
|
||||
providers: {
|
||||
openai: {
|
||||
apiKey: "sk-...", // optional if OPENAI_API_KEY is set
|
||||
model: "gpt-4o-transcribe",
|
||||
silenceDurationMs: 800,
|
||||
vadThreshold: 0.5,
|
||||
},
|
||||
},
|
||||
preStartTimeoutMs: 5000,
|
||||
maxPendingConnections: 32,
|
||||
maxPendingConnectionsPerIp: 4,
|
||||
maxConnections: 128,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- Twilio/Telnyx require a **publicly reachable** webhook URL.
|
||||
- Plivo requires a **publicly reachable** webhook URL.
|
||||
- `mock` is a local dev provider (no network calls).
|
||||
- If older configs still use `provider: "log"`, `twilio.from`, or legacy `streaming.*` OpenAI keys, run `openclaw doctor --fix` to rewrite them.
|
||||
- Telnyx requires `telnyx.publicKey` (or `TELNYX_PUBLIC_KEY`) unless `skipSignatureVerification` is true.
|
||||
- `skipSignatureVerification` is for local testing only.
|
||||
- If you use ngrok free tier, set `publicUrl` to the exact ngrok URL; signature verification is always enforced.
|
||||
- `tunnel.allowNgrokFreeTierLoopbackBypass: true` allows Twilio webhooks with invalid signatures **only** when `tunnel.provider="ngrok"` and `serve.bind` is loopback (ngrok local agent). Use for local dev only.
|
||||
- Ngrok free tier URLs can change or add interstitial behavior; if `publicUrl` drifts, Twilio signatures will fail. For production, prefer a stable domain or Tailscale funnel.
|
||||
- Streaming security defaults:
|
||||
- `streaming.preStartTimeoutMs` closes sockets that never send a valid `start` frame.
|
||||
- `streaming.maxPendingConnections` caps total unauthenticated pre-start sockets.
|
||||
- `streaming.maxPendingConnectionsPerIp` caps unauthenticated pre-start sockets per source IP.
|
||||
- `streaming.maxConnections` caps total open media stream sockets (pending + active).
|
||||
- Runtime fallback still accepts those old voice-call keys for now, but the rewrite path is `openclaw doctor --fix` and the compat shim is temporary.
|
||||
|
||||
## Streaming transcription
|
||||
|
||||
`streaming` selects a realtime transcription provider for live call audio.
|
||||
|
||||
Current runtime behavior:
|
||||
|
||||
- `streaming.provider` is optional. If unset, Voice Call uses the first
|
||||
registered realtime transcription provider.
|
||||
- Today the bundled provider is OpenAI, registered by the bundled `openai`
|
||||
plugin.
|
||||
- Provider-owned raw config lives under `streaming.providers.<providerId>`.
|
||||
- If `streaming.provider` points at an unregistered provider, or no realtime
|
||||
transcription provider is registered at all, Voice Call logs a warning and
|
||||
skips media streaming instead of failing the whole plugin.
|
||||
|
||||
OpenAI streaming transcription defaults:
|
||||
|
||||
- API key: `streaming.providers.openai.apiKey` or `OPENAI_API_KEY`
|
||||
- model: `gpt-4o-transcribe`
|
||||
- `silenceDurationMs`: `800`
|
||||
- `vadThreshold`: `0.5`
|
||||
|
||||
Example:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"voice-call": {
|
||||
config: {
|
||||
streaming: {
|
||||
enabled: true,
|
||||
provider: "openai",
|
||||
streamPath: "/voice/stream",
|
||||
providers: {
|
||||
openai: {
|
||||
apiKey: "sk-...", // optional if OPENAI_API_KEY is set
|
||||
model: "gpt-4o-transcribe",
|
||||
silenceDurationMs: 800,
|
||||
vadThreshold: 0.5,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Legacy keys are still auto-migrated by `openclaw doctor --fix`:
|
||||
|
||||
- `streaming.sttProvider` → `streaming.provider`
|
||||
- `streaming.openaiApiKey` → `streaming.providers.openai.apiKey`
|
||||
- `streaming.sttModel` → `streaming.providers.openai.model`
|
||||
- `streaming.silenceDurationMs` → `streaming.providers.openai.silenceDurationMs`
|
||||
- `streaming.vadThreshold` → `streaming.providers.openai.vadThreshold`
|
||||
|
||||
## Stale call reaper
|
||||
|
||||
Use `staleCallReaperSeconds` to end calls that never receive a terminal webhook
|
||||
(for example, notify-mode calls that never complete). The default is `0`
|
||||
(disabled).
|
||||
|
||||
Recommended ranges:
|
||||
|
||||
- **Production:** `120`–`300` seconds for notify-style flows.
|
||||
- Keep this value **higher than `maxDurationSeconds`** so normal calls can
|
||||
finish. A good starting point is `maxDurationSeconds + 30–60` seconds.
|
||||
|
||||
Example:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"voice-call": {
|
||||
config: {
|
||||
maxDurationSeconds: 300,
|
||||
staleCallReaperSeconds: 360,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Webhook Security
|
||||
|
||||
When a proxy or tunnel sits in front of the Gateway, the plugin reconstructs the
|
||||
public URL for signature verification. These options control which forwarded
|
||||
headers are trusted.
|
||||
|
||||
`webhookSecurity.allowedHosts` allowlists hosts from forwarding headers.
|
||||
|
||||
`webhookSecurity.trustForwardingHeaders` trusts forwarded headers without an allowlist.
|
||||
|
||||
`webhookSecurity.trustedProxyIPs` only trusts forwarded headers when the request
|
||||
remote IP matches the list.
|
||||
|
||||
Webhook replay protection is enabled for Twilio and Plivo. Replayed valid webhook
|
||||
requests are acknowledged but skipped for side effects.
|
||||
|
||||
Twilio conversation turns include a per-turn token in `<Gather>` callbacks, so
|
||||
stale/replayed speech callbacks cannot satisfy a newer pending transcript turn.
|
||||
|
||||
Unauthenticated webhook requests are rejected before body reads when the
|
||||
provider's required signature headers are missing.
|
||||
|
||||
The voice-call webhook uses the shared pre-auth body profile (64 KB / 5 seconds)
|
||||
plus a per-IP in-flight cap before signature verification.
|
||||
|
||||
Example with a stable public host:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"voice-call": {
|
||||
config: {
|
||||
publicUrl: "https://voice.example.com/voice/webhook",
|
||||
webhookSecurity: {
|
||||
allowedHosts: ["voice.example.com"],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## TTS for calls
|
||||
|
||||
Voice Call uses the core `messages.tts` configuration for
|
||||
streaming speech on calls. You can override it under the plugin config with the
|
||||
**same shape** — it deep‑merges with `messages.tts`.
|
||||
|
||||
```json5
|
||||
{
|
||||
tts: {
|
||||
provider: "elevenlabs",
|
||||
providers: {
|
||||
elevenlabs: {
|
||||
voiceId: "pMsXgVXv3BLzUgSXRplE",
|
||||
modelId: "eleven_multilingual_v2",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- Legacy `tts.<provider>` keys inside plugin config (`openai`, `elevenlabs`, `microsoft`, `edge`) are auto-migrated to `tts.providers.<provider>` on load. Prefer the `providers` shape in committed config.
|
||||
- **Microsoft speech is ignored for voice calls** (telephony audio needs PCM; the current Microsoft transport does not expose telephony PCM output).
|
||||
- Core TTS is used when Twilio media streaming is enabled; otherwise calls fall back to provider native voices.
|
||||
- If a Twilio media stream is already active, Voice Call does not fall back to TwiML `<Say>`. If telephony TTS is unavailable in that state, the playback request fails instead of mixing two playback paths.
|
||||
- When telephony TTS falls back to a secondary provider, Voice Call logs a warning with the provider chain (`from`, `to`, `attempts`) for debugging.
|
||||
|
||||
### More examples
|
||||
|
||||
Use core TTS only (no override):
|
||||
|
||||
```json5
|
||||
{
|
||||
messages: {
|
||||
tts: {
|
||||
provider: "openai",
|
||||
providers: {
|
||||
openai: { voice: "alloy" },
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Override to ElevenLabs just for calls (keep core default elsewhere):
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"voice-call": {
|
||||
config: {
|
||||
tts: {
|
||||
provider: "elevenlabs",
|
||||
providers: {
|
||||
elevenlabs: {
|
||||
apiKey: "elevenlabs_key",
|
||||
voiceId: "pMsXgVXv3BLzUgSXRplE",
|
||||
modelId: "eleven_multilingual_v2",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Override only the OpenAI model for calls (deep‑merge example):
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
"voice-call": {
|
||||
config: {
|
||||
tts: {
|
||||
providers: {
|
||||
openai: {
|
||||
model: "gpt-4o-mini-tts",
|
||||
voice: "marin",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## Inbound calls
|
||||
|
||||
Inbound policy defaults to `disabled`. To enable inbound calls, set:
|
||||
|
||||
```json5
|
||||
{
|
||||
inboundPolicy: "allowlist",
|
||||
allowFrom: ["+15550001234"],
|
||||
inboundGreeting: "Hello! How can I help?",
|
||||
}
|
||||
```
|
||||
|
||||
`inboundPolicy: "allowlist"` is a low-assurance caller-ID screen. The plugin
|
||||
normalizes the provider-supplied `From` value and compares it to `allowFrom`.
|
||||
Webhook verification authenticates provider delivery and payload integrity, but
|
||||
it does not prove PSTN/VoIP caller-number ownership. Treat `allowFrom` as
|
||||
caller-ID filtering, not strong caller identity.
|
||||
|
||||
Auto-responses use the agent system. Tune with:
|
||||
|
||||
- `responseModel`
|
||||
- `responseSystemPrompt`
|
||||
- `responseTimeoutMs`
|
||||
|
||||
### Spoken output contract
|
||||
|
||||
For auto-responses, Voice Call appends a strict spoken-output contract to the system prompt:
|
||||
|
||||
- `{"spoken":"..."}`
|
||||
|
||||
Voice Call then extracts speech text defensively:
|
||||
|
||||
- Ignores payloads marked as reasoning/error content.
|
||||
- Parses direct JSON, fenced JSON, or inline `"spoken"` keys.
|
||||
- Falls back to plain text and removes likely planning/meta lead-in paragraphs.
|
||||
|
||||
This keeps spoken playback focused on caller-facing text and avoids leaking planning text into audio.
|
||||
|
||||
### Conversation startup behavior
|
||||
|
||||
For outbound `conversation` calls, first-message handling is tied to live playback state:
|
||||
|
||||
- Barge-in queue clear and auto-response are suppressed only while the initial greeting is actively speaking.
|
||||
- If initial playback fails, the call returns to `listening` and the initial message remains queued for retry.
|
||||
- Initial playback for Twilio streaming starts on stream connect without extra delay.
|
||||
|
||||
### Twilio stream disconnect grace
|
||||
|
||||
When a Twilio media stream disconnects, Voice Call waits `2000ms` before auto-ending the call:
|
||||
|
||||
- If the stream reconnects during that window, auto-end is canceled.
|
||||
- If no stream is re-registered after the grace period, the call is ended to prevent stuck active calls.
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
openclaw voicecall call --to "+15555550123" --message "Hello from OpenClaw"
|
||||
openclaw voicecall start --to "+15555550123" # alias for call
|
||||
openclaw voicecall continue --call-id <id> --message "Any questions?"
|
||||
openclaw voicecall speak --call-id <id> --message "One moment"
|
||||
openclaw voicecall end --call-id <id>
|
||||
openclaw voicecall status --call-id <id>
|
||||
openclaw voicecall tail
|
||||
openclaw voicecall latency # summarize turn latency from logs
|
||||
openclaw voicecall expose --mode funnel
|
||||
```
|
||||
|
||||
`latency` reads `calls.jsonl` from the default voice-call storage path. Use
|
||||
`--file <path>` to point at a different log and `--last <n>` to limit analysis
|
||||
to the last N records (default 200). Output includes p50/p90/p99 for turn
|
||||
latency and listen-wait times.
|
||||
|
||||
## Agent tool
|
||||
|
||||
Tool name: `voice_call`
|
||||
|
||||
Actions:
|
||||
|
||||
- `initiate_call` (message, to?, mode?)
|
||||
- `continue_call` (callId, message)
|
||||
- `speak_to_user` (callId, message)
|
||||
- `end_call` (callId)
|
||||
- `get_status` (callId)
|
||||
|
||||
This repo ships a matching skill doc at `skills/voice-call/SKILL.md`.
|
||||
|
||||
## Gateway RPC
|
||||
|
||||
- `voicecall.initiate` (`to?`, `message`, `mode?`)
|
||||
- `voicecall.continue` (`callId`, `message`)
|
||||
- `voicecall.speak` (`callId`, `message`)
|
||||
- `voicecall.end` (`callId`)
|
||||
- `voicecall.status` (`callId`)
|
||||
194
openclaw/docs/plugins/webhooks.md
Normal file
194
openclaw/docs/plugins/webhooks.md
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
---
|
||||
summary: "Webhooks plugin: authenticated TaskFlow ingress for trusted external automation"
|
||||
read_when:
|
||||
- You want to trigger or drive TaskFlows from an external system
|
||||
- You are configuring the bundled webhooks plugin
|
||||
title: "Webhooks Plugin"
|
||||
---
|
||||
|
||||
# Webhooks (plugin)
|
||||
|
||||
The Webhooks plugin adds authenticated HTTP routes that bind external
|
||||
automation to OpenClaw TaskFlows.
|
||||
|
||||
Use it when you want a trusted system such as Zapier, n8n, a CI job, or an
|
||||
internal service to create and drive managed TaskFlows without writing a custom
|
||||
plugin first.
|
||||
|
||||
## Where it runs
|
||||
|
||||
The Webhooks plugin runs inside the Gateway process.
|
||||
|
||||
If your Gateway runs on another machine, install and configure the plugin on
|
||||
that Gateway host, then restart the Gateway.
|
||||
|
||||
## Configure routes
|
||||
|
||||
Set config under `plugins.entries.webhooks.config`:
|
||||
|
||||
```json5
|
||||
{
|
||||
plugins: {
|
||||
entries: {
|
||||
webhooks: {
|
||||
enabled: true,
|
||||
config: {
|
||||
routes: {
|
||||
zapier: {
|
||||
path: "/plugins/webhooks/zapier",
|
||||
sessionKey: "agent:main:main",
|
||||
secret: {
|
||||
source: "env",
|
||||
provider: "default",
|
||||
id: "OPENCLAW_WEBHOOK_SECRET",
|
||||
},
|
||||
controllerId: "webhooks/zapier",
|
||||
description: "Zapier TaskFlow bridge",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
Route fields:
|
||||
|
||||
- `enabled`: optional, defaults to `true`
|
||||
- `path`: optional, defaults to `/plugins/webhooks/<routeId>`
|
||||
- `sessionKey`: required session that owns the bound TaskFlows
|
||||
- `secret`: required shared secret or SecretRef
|
||||
- `controllerId`: optional controller id for created managed flows
|
||||
- `description`: optional operator note
|
||||
|
||||
Supported `secret` inputs:
|
||||
|
||||
- Plain string
|
||||
- SecretRef with `source: "env" | "file" | "exec"`
|
||||
|
||||
If a secret-backed route cannot resolve its secret at startup, the plugin skips
|
||||
that route and logs a warning instead of exposing a broken endpoint.
|
||||
|
||||
## Security model
|
||||
|
||||
Each route is trusted to act with the TaskFlow authority of its configured
|
||||
`sessionKey`.
|
||||
|
||||
This means the route can inspect and mutate TaskFlows owned by that session, so
|
||||
you should:
|
||||
|
||||
- Use a strong unique secret per route
|
||||
- Prefer secret references over inline plaintext secrets
|
||||
- Bind routes to the narrowest session that fits the workflow
|
||||
- Expose only the specific webhook path you need
|
||||
|
||||
The plugin applies:
|
||||
|
||||
- Shared-secret authentication
|
||||
- Request body size and timeout guards
|
||||
- Fixed-window rate limiting
|
||||
- In-flight request limiting
|
||||
- Owner-bound TaskFlow access through `api.runtime.taskFlow.bindSession(...)`
|
||||
|
||||
## Request format
|
||||
|
||||
Send `POST` requests with:
|
||||
|
||||
- `Content-Type: application/json`
|
||||
- `Authorization: Bearer <secret>` or `x-openclaw-webhook-secret: <secret>`
|
||||
|
||||
Example:
|
||||
|
||||
```bash
|
||||
curl -X POST https://gateway.example.com/plugins/webhooks/zapier \
|
||||
-H 'Content-Type: application/json' \
|
||||
-H 'Authorization: Bearer YOUR_SHARED_SECRET' \
|
||||
-d '{"action":"create_flow","goal":"Review inbound queue"}'
|
||||
```
|
||||
|
||||
## Supported actions
|
||||
|
||||
The plugin currently accepts these JSON `action` values:
|
||||
|
||||
- `create_flow`
|
||||
- `get_flow`
|
||||
- `list_flows`
|
||||
- `find_latest_flow`
|
||||
- `resolve_flow`
|
||||
- `get_task_summary`
|
||||
- `set_waiting`
|
||||
- `resume_flow`
|
||||
- `finish_flow`
|
||||
- `fail_flow`
|
||||
- `request_cancel`
|
||||
- `cancel_flow`
|
||||
- `run_task`
|
||||
|
||||
### `create_flow`
|
||||
|
||||
Creates a managed TaskFlow for the route's bound session.
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "create_flow",
|
||||
"goal": "Review inbound queue",
|
||||
"status": "queued",
|
||||
"notifyPolicy": "done_only"
|
||||
}
|
||||
```
|
||||
|
||||
### `run_task`
|
||||
|
||||
Creates a managed child task inside an existing managed TaskFlow.
|
||||
|
||||
Allowed runtimes are:
|
||||
|
||||
- `subagent`
|
||||
- `acp`
|
||||
|
||||
Example:
|
||||
|
||||
```json
|
||||
{
|
||||
"action": "run_task",
|
||||
"flowId": "flow_123",
|
||||
"runtime": "acp",
|
||||
"childSessionKey": "agent:main:acp:worker",
|
||||
"task": "Inspect the next message batch"
|
||||
}
|
||||
```
|
||||
|
||||
## Response shape
|
||||
|
||||
Successful responses return:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": true,
|
||||
"routeId": "zapier",
|
||||
"result": {}
|
||||
}
|
||||
```
|
||||
|
||||
Rejected requests return:
|
||||
|
||||
```json
|
||||
{
|
||||
"ok": false,
|
||||
"routeId": "zapier",
|
||||
"code": "not_found",
|
||||
"error": "TaskFlow not found.",
|
||||
"result": {}
|
||||
}
|
||||
```
|
||||
|
||||
The plugin intentionally scrubs owner/session metadata from webhook responses.
|
||||
|
||||
## Related docs
|
||||
|
||||
- [Plugin runtime SDK](/plugins/sdk-runtime)
|
||||
- [Hooks and webhooks overview](/automation/hooks)
|
||||
- [CLI webhooks](/cli/webhooks)
|
||||
78
openclaw/docs/plugins/zalouser.md
Normal file
78
openclaw/docs/plugins/zalouser.md
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
---
|
||||
summary: "Zalo Personal plugin: QR login + messaging via native zca-js (plugin install + channel config + tool)"
|
||||
read_when:
|
||||
- You want Zalo Personal (unofficial) support in OpenClaw
|
||||
- You are configuring or developing the zalouser plugin
|
||||
title: "Zalo Personal Plugin"
|
||||
---
|
||||
|
||||
# Zalo Personal (plugin)
|
||||
|
||||
Zalo Personal support for OpenClaw via a plugin, using native `zca-js` to automate a normal Zalo user account.
|
||||
|
||||
> **Warning:** Unofficial automation may lead to account suspension/ban. Use at your own risk.
|
||||
|
||||
## Naming
|
||||
|
||||
Channel id is `zalouser` to make it explicit this automates a **personal Zalo user account** (unofficial). We keep `zalo` reserved for a potential future official Zalo API integration.
|
||||
|
||||
## Where it runs
|
||||
|
||||
This plugin runs **inside the Gateway process**.
|
||||
|
||||
If you use a remote Gateway, install/configure it on the **machine running the Gateway**, then restart the Gateway.
|
||||
|
||||
No external `zca`/`openzca` CLI binary is required.
|
||||
|
||||
## Install
|
||||
|
||||
### Option A: install from npm
|
||||
|
||||
```bash
|
||||
openclaw plugins install @openclaw/zalouser
|
||||
```
|
||||
|
||||
Restart the Gateway afterwards.
|
||||
|
||||
### Option B: install from a local folder (dev)
|
||||
|
||||
```bash
|
||||
PLUGIN_SRC=./path/to/local/zalouser-plugin
|
||||
openclaw plugins install "$PLUGIN_SRC"
|
||||
cd "$PLUGIN_SRC" && pnpm install
|
||||
```
|
||||
|
||||
Restart the Gateway afterwards.
|
||||
|
||||
## Config
|
||||
|
||||
Channel config lives under `channels.zalouser` (not `plugins.entries.*`):
|
||||
|
||||
```json5
|
||||
{
|
||||
channels: {
|
||||
zalouser: {
|
||||
enabled: true,
|
||||
dmPolicy: "pairing",
|
||||
},
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
## CLI
|
||||
|
||||
```bash
|
||||
openclaw channels login --channel zalouser
|
||||
openclaw channels logout --channel zalouser
|
||||
openclaw channels status --probe
|
||||
openclaw message send --channel zalouser --target <threadId> --message "Hello from OpenClaw"
|
||||
openclaw directory peers list --channel zalouser --query "name"
|
||||
```
|
||||
|
||||
## Agent tool
|
||||
|
||||
Tool name: `zalouser`
|
||||
|
||||
Actions: `send`, `image`, `link`, `friends`, `groups`, `me`, `status`
|
||||
|
||||
Channel message actions also support `react` for message reactions.
|
||||
Loading…
Add table
Add a link
Reference in a new issue