New to OpenClaw plugins? Read Getting Started
first for package structure and manifest setup.
Walkthrough
1
Package and manifest
Step 1: Package and manifest
setup.providers[].envVars lets OpenClaw 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. openclaw.compat
and openclaw.build in package.json are required for ClawHub
publishing (openclaw.compat.pluginApi and openclaw.build.openclawVersion
are the two required fields; minGatewayVersion falls back to
openclaw.install.minHostVersion when omitted).2
Register the provider
A minimal text provider needs an OpenClaw keeps the inline value only while staged validation runs. At the
final persistence boundary it writes the value to the protected local store
and saves a Do not use
id, label, auth, and catalog.
catalog is the provider-owned runtime/config hook; it can call live
vendor APIs and returns models.providers entries.index.ts
registerModelCatalogProvider is the newer control-plane catalog surface
for list/help/picker UI, covering text, voice, image_generation,
video_generation, and music_generation rows. Keep vendor endpoint
calls and response mapping in the plugin; OpenClaw owns the shared row
shape, source labels, and help rendering.That is a working provider. Users can now run
openclaw onboard --acme-ai-api-key <key> and select
acme-ai/acme-large as their model.For provider-key lookup and selection from an already loaded auth store,
import findNormalizedProviderValue and resolveAuthProfileOrder from
openclaw/plugin-sdk/provider-auth. This keeps provider entrypoints from
loading the full agent runtime just to select a credential. The deprecated
agent-runtime exports remain available for compatibility; use the narrower
provider-auth route in new code.A custom interactive auth method that mints a static token or API key can
request protected persistence on its returned profile:tokenRef or keyRef in the auth profile. namePrefix must be
an uppercase environment-style name. OpenClaw adds a stable suffix derived
from the provider and final profile id so multiple profiles remain separate.
Use this only for provider-minted static credentials, not rotating OAuth
credentials or values already supplied as SecretRefs.Live model discovery
If your provider exposes an OpenAI-compatible/models API, opt the
single-provider helper into shared discovery:liveModelDiscovery: true is a public Plugin SDK contract with these
behaviors:For a non-Bearer or nonstandard list endpoint, pass options instead of
true:endpointUrl as an unconditional alternate host. Its
requireBaseUrl check is the credential-isolation boundary for providers
whose model-list host differs from their inference host.If the provider needs custom model semantics rather than the conservative
OpenAI-compatible projection, keep only that projection in the plugin. Pass
it as projectRows; the shared runtime still owns guarded fetches,
provider-auth headers, cache admission, and static fallback.Use buildLiveModelProviderConfig when the live API only tells you which
provider-owned static catalog rows are currently available:index.ts
run should stay auth-gated and return null when no usable credential is
available. Keep an offline staticRun or static fallback so setup, docs,
tests, and picker surfaces do not depend on live network access. Use a TTL
appropriate for model-list freshness, avoid request-time filesystem polling,
and pass a provider-specific readRows / readModelId only when the
upstream response is not an OpenAI-compatible { data: [{ id, object }] }
shape.For a separate authoritative metadata feed, the same
provider-catalog-live-runtime subpath exposes ProviderCatalogSnapshot:
each entry pairs a runtime model with its lifecycle status.
projectUpstreamProviderCatalogSnapshot rebuilds that snapshot from a
trusted seed and accepted upstream rows, dropping withdrawn upstream-only
models. projectProviderCatalogSnapshotRows intersects advertised IDs with
active snapshot entries, deduplicating in endpoint order;
listProviderCatalogSnapshotEntries projects the same lifecycle facts for
catalog consumers. Keep seed lifecycle policy and model-specific decoration
in the owning plugin. Derive static fallback eligibility after refreshing
metadata so the first failed or fully filtered discovery uses current status.
Public metadata never establishes account entitlement or expands the
credential scope of discovery.Official plugins use the private, pure
openclaw/plugin-sdk/model-catalog-pricing runtime subpath. It exposes
normalizeModelPricingCatalog(rows, normalizePricing, options?) for
provider-owned pricing feeds. It returns a map of complete costs: absent
prices are omitted, while malformed declared prices, invalid or duplicate
model IDs, and a feed with no usable prices return undefined. Supply the
provider’s unit conversion. Options can select readModelId(model) (default
model.id), readPricing(model) (default model.pricing), and
isSupportedPricing(rawPricing) (default true). Declared prices are
normalized and validated before unsupported schedules are omitted; duplicate
IDs are rejected even on unpriced or unsupported rows. Non-token domains
can return undefined from readPricing. No auth, discovery, or runtime
loader is imported.DeepInfra’s pricing-api.ts uses these selectors for its native array and
model_name identities. Release plugins using the options contract (including
DeepInfra and Venice) with a matching host, and coordinate their plugin API
and minimum-host floors at release time. The private subpath is not an
independently versioned third-party compatibility API.This subpath also exposes normalizeOpenRouterModelPricing(pricing) for
native OpenRouter pricing objects. It converts per-token rates and static
prompt-length overrides into a complete per-million cost schedule, without
network access or prices from another source. Overrides apply strictly above
min_prompt_tokens, counting uncached input, cache reads, and cache writes.
Matching entries apply in source order: later entries win per price key,
including at equal thresholds; omitted keys inherit the native base or an
earlier matching entry. Cache rates absent from the base default to zero.
Invalid effective token rates return undefined. Entries with time-based or
unknown conditions are skipped; other known charge dimensions are ignored.When ctx.providerIds is present, it contains the normalized provider
identities selected for that catalog owner. Return null before resolving
credentials or making network requests when the hook serves none of them;
OpenClaw also filters returned identities to that scope. An absent scope
means the caller requested the full catalog.If the upstream provider uses different control tokens than OpenClaw, add a
small bidirectional text transform instead of replacing the stream path: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:buildProvider is the live catalog path used when OpenClaw can resolve real
provider auth. It may perform provider-specific discovery. Use
buildStaticProvider only for offline rows that are safe to show before auth
is configured; it must not require credentials or make network requests.
OpenClaw’s models list --all display currently executes static catalogs
only for bundled provider plugins, with an empty config, empty env, and no
agent/workspace paths.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.The live discovery examples above cover /models-style provider APIs. Keep
that discovery inside catalog.run, gated on usable auth, and keep
staticRun network-free for offline catalog generation.3
Add dynamic model resolution
If your provider accepts arbitrary model IDs (like a proxy or router),
add If resolving requires a network call, return the requested model directly
from
resolveDynamicModel:prepareDynamicModel. OpenClaw applies the same configured overrides
and normalization as synchronous dynamic resolution. Existing hooks that
return nothing still retry resolveDynamicModel after preparation.4
Add runtime hooks (as needed)
Most providers only need Available replay families today:
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:Available stream families today:
SDK seams powering the family builders
SDK seams powering the family builders
Each family builder is composed from lower-level public helpers exported from the same package, which you can reach for when a provider needs to go off the common pattern:
openclaw/plugin-sdk/provider-model-shared-ProviderReplayFamily,buildProviderReplayFamilyHooks(...), and the raw replay builders (buildOpenAICompatibleReplayPolicy,buildAnthropicReplayPolicyForModel,buildGoogleGeminiReplayPolicy,buildHybridAnthropicOrOpenAIReplayPolicy). Also exports Gemini replay helpers (sanitizeGoogleGeminiReplayHistory,resolveTaggedReasoningOutputMode) and endpoint/model helpers (resolveProviderEndpoint,normalizeProviderId,normalizeGooglePreviewModelId).openclaw/plugin-sdk/provider-stream-ProviderStreamFamily,buildProviderStreamFamilyHooks(...),composeProviderStreamWrappers(...), plus the shared OpenAI/Codex wrappers (createOpenAIAttributionHeadersWrapper,createOpenAIFastModeWrapper,createOpenAIServiceTierWrapper,createOpenAIResponsesContextManagementWrapper,createCodexNativeWebSearchWrapper), DeepSeek V4 OpenAI-compatible wrapper (createDeepSeekV4OpenAICompatibleThinkingWrapper), Anthropic Messages thinking prefill cleanup (createAnthropicThinkingPrefillPayloadWrapper), plain-text tool-call compat (createPlainTextToolCallCompatWrapper), and shared proxy/provider wrappers (createOpenRouterWrapper,createToolStreamWrapper,createMinimaxFastModeWrapper).openclaw/plugin-sdk/provider-stream-shared- lightweight payload and event wrappers for hot provider paths, includingcreateOpenAICompatibleCompletionsThinkingOffWrapper,createPayloadPatchStreamWrapper,createPlainTextToolCallCompatWrapper,normalizeOpenAICompatibleReasoningPayload(...), andsetQwenChatTemplateThinking(...).openclaw/plugin-sdk/provider-tools-ProviderToolCompatFamily,buildProviderToolCompatFamilyHooks("deepseek" | "gemini" | "openai"), and underlying provider schema helpers.
native
reasoning output so OpenClaw consumes native thought parts without adding
<think> / <final> prompt directives. Text-only Gemini CLI-style
backends that parse a final JSON/text response can keep the shared
google-gemini tagged contract.Some stream helpers stay provider-local on purpose. @openclaw/anthropic-provider keeps wrapAnthropicProviderStream, resolveAnthropicBetas, resolveAnthropicFastMode, resolveAnthropicServiceTier, and the lower-level Anthropic wrapper builders in its own public api.ts / contract-api.ts seam because they encode Claude OAuth beta handling and context1m gating. The xAI plugin similarly keeps native xAI Responses shaping in its own wrapStreamFn (/fast aliases, default tool_stream, unsupported strict-tool cleanup, xAI-specific reasoning-payload removal).The same package-root pattern also backs @openclaw/openai-provider (provider builders, default-model helpers, realtime provider builders) and @openclaw/openrouter-provider (provider builder plus onboarding/config helpers).- Token exchange
- Custom headers
- Native transport identity
- Usage and billing
For providers that need a token exchange before each inference call:
Common provider hooks
Common provider hooks
OpenClaw calls hooks in roughly this order for model/provider plugins.
Most providers only use 2-3. This is not the full
ProviderPlugin
contract - see Internals: Provider Runtime
Hooks for the
complete, currently-accurate hook list and fallback notes.
Compatibility-only provider fields that OpenClaw no longer calls, such as
ProviderPlugin.capabilities and suppressBuiltInModel, are not listed
here.Keep resolveSyntheticAuth synchronous and bounded. External process/network login
checks belong in prepareSyntheticAuth, which receives the captured config,
environment, and cancellation signal and returns a synthetic auth result or
no result. OpenClaw retains completed availability within that preparation
generation. Read-only workers receive the final provider-ref outcome (including
unavailable), preserving alias precedence without rerunning external checks.
Cancelled preparation must reject after cleanup, not report a missing login.Runtime fallback notes:
- Error classification uses the prepared provider owner or already loaded provider hooks.
matchesContextOverflowErrorandclassifyFailoverReasonnever trigger plugin discovery while handling an error; provider preparation owns loading those hooks. normalizeConfigresolves one owning plugin per provider id (bundled providers first, then the matched runtime plugin) and calls only that hook - there is no scan across other providers. Google’s ownnormalizeConfighook is what normalizesgoogle/google-vertex/google-antigravityconfig entries; it is not a separate core fallback.resolveConfigApiKeyuses the provider hook when exposed. Amazon Bedrock keeps AWS env-marker resolution in its provider plugin; runtime auth itself still uses the AWS SDK default chain when configured withauth: "aws-sdk".resolveThinkingProfile(ctx)receives the selectedprovider,modelId, optional mergedreasoningcatalog hint, and optional merged modelcompatfacts. Usecompatonly to select the provider’s thinking UI/profile.resolveSystemPromptContributionlets a provider inject cache-aware system-prompt guidance for a model family. Prefer it over the legacy plugin-widebefore_prompt_buildhook when the behavior belongs to one provider/model family and should preserve the stable/dynamic cache split.
5
Add extra capabilities (optional)
Step 5: Add extra capabilities
A provider plugin can register embeddings, speech, realtime transcription, realtime voice, media understanding, image generation, video generation, web fetch, and web search alongside text inference. OpenClaw classifies this as a hybrid-capability plugin - the recommended pattern for company plugins (one plugin per vendor). See Internals: Capability Ownership.Register each capability insideregister(api) alongside your existing
api.registerProvider(...) call. Pick only the tabs you need:- Speech (TTS)
- Realtime transcription
- Realtime voice
- Media understanding
- Embeddings
- Image and video generation
- Web fetch and search
assertOkOrThrowProviderError(...) for provider HTTP failures so
plugins share capped error-body reads, JSON error parsing, and
request-id suffixes. Pass { requestHeaders: headers } as its third
argument when requests carry credentials: this redacts reflected header
values before error details and metadata are retained. Pass the same
option to readProviderJsonResponse(...) to omit unsafe parser excerpts.
For provider-specific failure payloads, use
redactProviderResponseErrorText(text, headers) or the bounded
readProviderResponseErrorText(response, limitBytes, headers) helper
from the same SDK entrypoint.6
Test
Step 6: Test
src/provider.test.ts
Publish to ClawHub
Provider plugins publish the same way as any other external code plugin:clawhub skill publish <path> is a different command for publishing a skill
folder, not a plugin package - do not use it here.
File structure
Catalog order reference
catalog.order controls when your catalog merges relative to built-in
providers:
Next steps
- Channel Plugins - if your plugin also provides a channel
- SDK Runtime -
api.runtimehelpers (TTS, search, subagent) - SDK Overview - full subpath import reference
- Plugin Internals - hook details and bundled examples