> For the complete documentation index, see [llms.txt](https://www.openclawbook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.openclawbook.xyz/en/ch21-channel-extension-mechanism/21.5-source-deep-dive-loader-jiti-and-sdk-surface.md). Agents can also search and read this documentation through its [MCP server](https://www.openclawbook.xyz/~gitbook/mcp).

# 21.5 Source Deep Dive: The Loader, jiti, and the SDK Capability Surface

> **Generated by**: Claude Opus 5 (claude-opus-5\[1m]) **Token usage**: Input \~254,000 tokens, Output \~14,000 tokens (this section) **Source baseline**: `v2026.3.9` (`v2026.3.8-170-g665f67726`); line numbers refer to this commit

***

Understanding OpenClaw's plugin system requires accepting one design premise up front:

> **Plugins are designed as trusted code loaded in-process.**

So the whole security model's center of gravity is **not "isolate plugins"** but "control what is allowed to become a plugin" and "hold the boundaries outside plugins."

Accept that, and several apparently radical decisions — jiti loading TypeScript source directly, plugins reading the fully-resolved config — all make sense.

This section covers loading and the SDK; the trust model and security boundaries are §32.6.

## 21.5.1 From Directory to Runtime Capability: Five Steps

```mermaid
flowchart TB
    subgraph discovery["Discovery layer, discovery.ts"]
        A1["bundled<br/>extensions/ shipped with core"] --> B
        A2["global<br/>~/.openclaw/extensions/"] --> B
        A3["workspace<br/>workspace extensions dir"] --> B
        A4["config<br/>plugins.load.paths"] --> B
        B["candidate list PluginCandidate<br/>(origin tagged)"]
    end
    B --> C["manifest-registry<br/>read openclaw.plugin.json<br/>executes no plugin code"]
    C --> D{"enable adjudication<br/>plugins.allow / deny<br/>plugins.entries.*.enabled<br/>slots.memory exclusive slot"}
    D -- disabled --> E["record disabled state<br/>enters registry but isn't loaded"]
    D -- enabled --> F["openBoundaryFileSync<br/>entry path escape check"]
    F --> G["jiti loads TS/JS source<br/>alias: openclaw/plugin-sdk"]
    G --> H["register(api) runs synchronously"]
    H --> I["PluginRegistry<br/>tools / hooks / channels / providers<br/>gateway RPC / HTTP routes / CLI / services"]
    I --> J["security audit<br/>provenance warnings + code scan"]
```

Three key facts:

**1. Config validation executes no plugin code.** The manifest `openclaw.plugin.json` carries a JSON Schema. Doctor and config validation **read only the manifest**; the plugin module itself is executed by jiti only at Gateway startup load time.

**2. The four sources have priority.** On an id collision, **first seen wins**, and later ones are tagged `overridden by ... plugin` (`loader.ts:589`).

**3. Registration is synchronous.** A `register` that returns a Promise gets a warning and is ignored (`loader.ts:776-784`).

> The third is easy to skim past but matters: **forcing synchronous registration keeps startup ordering deterministic** — a plugin has no opportunity to turn the load phase into an asynchronous black hole. Otherwise one plugin `await`ing a promise that never resolves would hang the entire Gateway at startup.

## 21.5.2 Manifest First

Every plugin must carry a manifest at its root; **a missing id or configSchema is an immediate error**:

```ts
// src/plugins/manifest.ts:81-88
const id = typeof raw.id === "string" ? raw.id.trim() : "";
if (!id) {
  return { ok: false, error: "plugin manifest requires id", manifestPath };
}
const configSchema = isRecord(raw.configSchema) ? raw.configSchema : null;
if (!configSchema) {
  return { ok: false, error: "plugin manifest requires configSchema", manifestPath };
}
```

The motive is documented in `docs/plugins/manifest.md`:

> OpenClaw uses this manifest to validate configuration **without executing plugin code**.

Which means all of these happen **without touching plugin code**:

* Validating `plugins.entries.<id>.config`
* Erroring on unknown channel keys
* Checking whether ids referenced in `plugins.allow` exist

Even for a plugin loaded from a local path the manifest is mandatory.

Even reading the manifest file goes through `openBoundaryFileSync`, **rejecting symlinks and hardlinks that would take the read outside the plugin root** (`manifest.ts:50-55`).

> This is §45.1's fifth pattern: **"validating config never becomes running code."** Many plugin systems `require` the module during validation — at which point "scan this plugin for safety" is itself an execution.

## 21.5.3 jiti: The Trade-off of Loading TypeScript Source Directly

The loading core lives in `loadOpenClawPlugins`. The jiti loader is **lazily initialized** and aliases `openclaw/plugin-sdk` to the installed SDK:

```ts
// src/plugins/loader.ts:548-556
jitiLoader = createJiti(import.meta.url, {
  interopDefault: true,
  extensions: [".ts", ".tsx", ".mts", ".cts", ".mtsx", ".ctsx", ".js", ".mjs", ".cjs", ".json"],
  ...(Object.keys(aliasMap).length > 0
    ? { alias: aliasMap }
    : {}),
});
```

Alias resolution (`loader.ts:53-110`) probes **up to six levels up the directory tree**, choosing between `src/plugin-sdk/*.ts` (running from source) and `dist/plugin-sdk/*.js` (packaged install) based on the runtime environment.

**This single move solves the plugin ecosystem's most annoying dependency problem**: a plugin's `package.json` **doesn't need (and shouldn't have)** `openclaw` as a runtime dependency — the repo's `CLAUDE.md` explicitly requires it in `devDependencies` / `peerDependencies`, with jiti's alias taking over at runtime.

Plugin packages can therefore ship as **pure source with zero build steps**.

### The two sides of the trade

**Gains:**

| Gain                   | Detail                                                                                                                          |
| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| **Audit what runs**    | Authors publish `.ts` directly — no "compiled output differs from source" supply-chain problem; **what you audit is what runs** |
| **Zero version drift** | Core and plugins share one SDK's types and implementation; no "plugin bundled an old SDK"                                       |
| Developer experience   | `plugins install -l ./dir` symlinks, and edits take effect immediately                                                          |

**Costs:**

| Cost                                                | Compensating design                                                                                                                                                                                              |
| --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| jiti transpiles at runtime, adding cost to startup  | Registry caching (`loader.ts:47`), lazy jiti creation (`:537-539`), **early short-circuit for the bundled memory plugin when it definitely won't be enabled** to avoid importing heavy dependencies (`:636-653`) |
| In-process `require` semantics = **zero isolation** | None — this is a design decision SECURITY.md acknowledges head-on                                                                                                                                                |

The second point bears repeating: plugins share **the same V8 heap, the same environment variables, the same filesystem permissions** as the core. There is no runtime isolation whatsoever.

### What the loader does is path integrity, not permission isolation

```ts
// src/plugins/loader.ts:660-669
const pluginRoot = safeRealpathOrResolve(candidate.rootDir);
const opened = openBoundaryFileSync({
  absolutePath: candidate.source,
  rootPath: pluginRoot,
  boundaryLabel: "plugin root",
  rejectHardlinks: candidate.origin !== "bundled",
  skipLexicalRootCheck: true,
});
if (!opened.ok) {
  pushPluginLoadError("plugin entry path escapes plugin root or fails alias checks");
```

The entry file must **genuinely reside** inside the plugin root, and non-bundled origins must additionally **reject hardlinks**.

Note what this check defends against: not "a plugin doing bad things" (it has TCB status; doing bad things isn't a vulnerability) but **"something unexpected being loaded as a plugin"** — for instance, a symlink disguising a file in `/tmp` as an approved plugin's entry point.

## 21.5.4 Two "Social" Defenses: No Blocking, Just Friction

**Defense one: warn when `plugins.allow` is empty.** If non-bundled plugins are discovered but no allowlist is set, startup emits a warning listing the plugins that may be auto-loaded (`loader.ts:407-409`).

**Defense two: provenance tracking.** Every successfully loaded non-bundled plugin is matched against `plugins.installs` records and `plugins.load.paths`; anything that doesn't match is tagged:

> loaded without install/load-path provenance; treat as **untracked local code**

(`loader.ts:430-431`)

So a directory that simply appeared in `~/.openclaw/extensions/` can still load (it's inside the operator trust boundary), but it **keeps stinking** in diagnostics and `security audit` until the operator explicitly pins it.

> **"Available by default, anomalies visible"** — a pragmatic midpoint between zero friction and zero trust. It doesn't stop you doing something dangerous; it guarantees you won't be unaware you did it.

## 21.5.5 The SDK Capability Surface: One api Object, Eleven Extension Points

The only handle a plugin receives is `OpenClawPluginApi` (`src/plugins/types.ts:263-306`):

| Registration method     | Capability                                                                                                                                                    |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `registerTool`          | Add tools for the agent (factory functions can generate per-session; **`optional: true` means not in the default set, requiring explicit tool-policy allow**) |
| `registerHook` / `on`   | Config-style hooks plus 23 typed lifecycle hooks                                                                                                              |
| `registerChannel`       | A complete message channel (ChannelPlugin + dock)                                                                                                             |
| `registerProvider`      | Model providers and their OAuth / API key flows                                                                                                               |
| `registerGatewayMethod` | Gateway RPC methods                                                                                                                                           |
| `registerHttpRoute`     | Gateway HTTP routes (`auth: "gateway"` uses gateway auth, `"plugin"` self-authenticates)                                                                      |
| `registerCli`           | CLI subcommands                                                                                                                                               |
| `registerService`       | Background services started and stopped with the Gateway                                                                                                      |
| `registerCommand`       | **Slash commands that bypass the LLM** (handled before the agent)                                                                                             |
| `registerContextEngine` | Context engine (exclusive slot, §17.5)                                                                                                                        |

Typed hooks cover nearly every gate in the agent's main loop (`types.ts:347-372`): `before_model_resolve`, `before_prompt_build`, `llm_input` / `llm_output`, `before_tool_call` / `after_tool_call`, `message_received` / `sending` / `sent`, plus the full compaction / session / subagent / gateway lifecycles.

Execution semantics (`src/plugins/hooks.ts:112-120`): **sorted by priority descending, executed in order, results merged with "first defined override wins."**

### The one mandatory policy: the prompt-injection switch

`before_prompt_build` and `before_agent_start` are explicitly classified as **prompt-injection hooks** (`types.ts:384-388`).

An operator can set `plugins.entries.<id>.hooks.allowPromptInjection = false` per plugin, after which:

* the former is **refused registration outright**;
* the latter's prompt-rewriting fields are **stripped** (`registry.ts:535-556`).

> This is the compromise for "plugins are trusted, but **a plugin's invisible influence on the system prompt must be auditable and switchable off**."
>
> Why single out prompt injection for a switch? Because it's the most invisible kind of influence — a plugin changes the system prompt, the agent's behavior changes, and nothing in the logs or tool-call records reveals why.

## 21.5.6 What a Plugin Can Reach: A Candid Inventory

The core surface exposed by `api.runtime` (`src/plugins/runtime/types-core.ts:10-67`):

```ts
// src/plugins/runtime/types-core.ts:10-21 (excerpt)
export type PluginRuntimeCore = {
  version: string;
  config: {
    loadConfig: typeof import("../../config/config.js").loadConfig;
    writeConfigFile: typeof import("../../config/config.js").writeConfigFile;
  };
  system: {
    enqueueSystemEvent: ...;
    requestHeartbeatNow: ...;
    runCommandWithTimeout: typeof import("../../process/exec.js").runCommandWithTimeout;
    ...
  };
```

Item by item, what it **can** reach:

| Capability                                                 | Meaning                                                                                                                            |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `config.loadConfig` / `writeConfigFile`                    | **Read and write global config** — including changing `plugins.allow` to renew its own lease                                       |
| `system.runCommandWithTimeout`                             | **Run host commands** — SECURITY.md notes directly that this is "a convenience API, not a sandbox boundary"                        |
| `modelAuth.getApiKeyForModel` / `resolveApiKeyForProvider` | **Resolve a usable API key for any provider**                                                                                      |
| `events.onAgentEvent` / `onSessionTranscriptUpdate`        | Media/TTS/STT pipelines, agent event streams, **session transcript events** — effectively full observability of every conversation |
| `api.config`                                               | The complete `OpenClawConfig` (**resolved, including plaintext**)                                                                  |

**The "cannot reach" list is much shorter, and different in kind** — these aren't permission fences but **the absence of an official channel**: plugins have no separate secret-store read API (though nothing in-process can stop them), HTTP routes default to gateway auth, and `registerCommand` defaults to `requireAuth: true`, open only to allowlisted senders.

**There are exactly three boundaries with real force:**

1. The allow / deny list at load time;
2. The tool policy determining whether a tool enters the agent's set (`optional` tools must be explicitly allowed);
3. The prompt-injection hook switch.

Beyond those, **the plugin API's "capability boundary" is a documentation boundary, not a runtime boundary.**

SECURITY.md endorses this in one line:

> Installing or enabling a plugin grants it the same trust level as local code running on that gateway host.

### The SDK's other half: `src/plugin-sdk/index.ts`

825 lines, the toolbox for channel plugins: webhook path normalization, request-body rate guards, file locks, keyed async queues, pairing integration, allowlist resolution, media payload construction — roughly a hundred exports.

**Its existence makes the 21 channel extensions highly isomorphic** — a channel plugin's security-critical logic (`allowFrom` resolution, group admission, command authorization) **all runs through one shared implementation in the SDK** rather than each channel copying it.

> That matters enormously for security: among 21 hand-copied allowlist parsers, one getting a boundary condition wrong is a vulnerability. A shared implementation compresses that risk from 21 places to 1.

## 21.5.7 The Ecosystem: 40 Packages

| Category                 | Count | Members                                                                                                                                                                                           |
| ------------------------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Channels**             | 21    | telegram, discord, slack, signal, whatsapp, imessage, bluebubbles, matrix, mattermost, msteams, feishu, googlechat, irc, line, nextcloud-talk, nostr, synology-chat, tlon, twitch, zalo, zalouser |
| **Tools / capabilities** | 11    | llm-task, lobster, voice-call, talk-voice, phone-control, open-prose, diffs, acpx, device-pair, diagnostics-otel, thread-ownership                                                                |
| **Auth**                 | 4     | copilot-proxy, google-gemini-cli-auth, minimax-portal-auth, qwen-portal-auth                                                                                                                      |
| **Memory**               | 2     | memory-core, memory-lancedb (mutually exclusive via `plugins.slots.memory`)                                                                                                                       |

(Plus `shared` and `test-utils`, internal infrastructure rather than plugins.)

**One telling structural signal**: even first-class channels like Telegram, Discord, and WhatsApp are extension packages (bundled plugins), going through the same loading path as everything else.

> **The plugin system isn't a peripheral extension mechanism — it's the foundation of the channel system itself.** Teams has been plugin-only since 2026.1.15.
>
> This is also a practical test of any plugin system: **does the core use it for its own features?** If yes, the API surface is sufficient. If no, plugins will always be second-class.

## 21.5.8 A Minimal Sample: llm-task

`extensions/llm-task` is the smallest usable tool-plugin sample, just over 400 lines total. The entry point is six lines:

```ts
// extensions/llm-task/index.ts:1-6
import type { AnyAgentTool, OpenClawPluginApi } from "openclaw/plugin-sdk/llm-task";
import { createLlmTaskTool } from "./src/llm-task-tool.js";

export default function register(api: OpenClawPluginApi) {
  api.registerTool(createLlmTaskTool(api) as unknown as AnyAgentTool, { optional: true });
}
```

Three integration details worth recording:

**1. `optional: true`.** llm-task doesn't enter any agent's tool set by default; a tool policy must name it explicitly. It's positioned to be orchestrated by Lobster workflows through `openclaw.invoke`, not casually invoked by a chat agent.

**2. Tool-less subagents.** Internally it starts a **one-shot embedded agent** via `runEmbeddedPiAgent({ ..., disableTools: true })` for JSON-only tasks (`llm-task-tool.ts:195-209`), with session files under an OpenClaw-managed temp root, deleted after use.

**LLM recursion is explicitly cut off** — no "an agent inside a tool that then executes tools" amplification chain.

**3. Model allowlist.** The manifest's configSchema provides `allowedModels` (`provider/model` keys), validated before execution — **preventing prompt manipulation of the `provider` / `model` parameters from routing tasks to an expensive or unauthorized model**.

That third one is an easily overlooked attack surface: if the model field in a tool's arguments is entirely model-filled, a single injection can send every request to your most expensive model.

### One monorepo edge cost

llm-task also shows a pragmatic compromise for bundled plugins: a **dual-path dynamic import** using `import("../../../src/...")` when running from source and falling back to `dist/extensionAPI.js` when packaged (`llm-task-tool.ts:14-37`).

Plugins living in the same repo as the core but needing to work in both distribution forms — that boilerplate is jiti's cost inside a monorepo.

## 21.5.9 Why npm Distribution Instead of a Central Marketplace

`openclaw plugins install <spec>` is implemented as: `npm pack` → unpack into `~/.openclaw/extensions/<id>/` → write config to enable.

Around that path is a set of **deliberately tightened** constraints:

```ts
// src/infra/npm-registry-spec.ts:25-33
// Registry-only: no URLs, git, file, or alias protocols.
// Keep strict: this runs on the gateway host.
if (spec.includes("://")) {
  return { ok: false, error: "unsupported npm spec: URLs are not allowed" };
}
if (spec.includes("#")) {
  return { ok: false, error: "unsupported npm spec: git refs are not allowed" };
}
```

| Constraint                        | Detail                                                                                                                                                                                                    |
| --------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Registry-only**                 | git / URL / file protocols and semver ranges are all rejected; only a package name plus an exact version or dist-tag; a bare spec resolving to a prerelease aborts and demands an explicit `@beta` opt-in |
| **`--ignore-scripts` throughout** | Both the `npm pack` stage (`install-source-utils.ts:219`) and dependency installation (`install-package-dir.ts:192`) disable lifecycle scripts                                                            |
| **id normalization**              | The config key comes from the manifest id (scoped packages drop the scope), decoupled from the npm package name (`install.ts:239-264`)                                                                    |

**`--ignore-scripts` removes the postinstall supply-chain surface entirely**, at the cost of requiring plugin dependency trees to stay "pure JS/TS" (no native modules needing compilation).

### A three-layer answer

Why no central marketplace?

**1. The trust model doesn't need one.** "What plugins to install" is already the operator's sovereign decision. Central review can't offer a stronger guarantee than `plugins.allow` + `security audit`, but it *would* create **the illusion that "it's on the marketplace, so it's safe"** — and SECURITY.md explicitly excludes "a trusted-installed malicious plugin doing bad things" from the vulnerability definition, so a reviewed marketplace contradicts that stance logically.

**2. npm already provides** publishing identity, version immutability, distribution, and unpublish mechanisms; running a registry is duplicated effort. `docs/plugins/community.md`'s listing bar confirms it: to be listed you need "published on npmjs + a public GitHub repo + signs of maintenance." **The project curates a directory, it doesn't host.**

**3. Audit closes the loop.** The "after the fact" supervision that decentralized distribution lacks is supplied locally by three checks (`src/security/audit-extra*.ts`):

```
plugins.installs_unpinned_npm_specs   watches unpinned versions
plugins.installs_missing_integrity    watches missing integrity records
plugins.installs_version_drift        watches disk contents drifting from install records
```

> In one line: **OpenClaw split "the marketplace" into npm (distribution) + a documentation directory (discovery) + local audit (supervision) — and the one thing it refuses to do is make the trust decision on the user's behalf.**

***

## Section Summary

1. **The design premise is that plugins are trusted, in-process code** — the security center of gravity is controlling what may become a plugin and holding the boundaries outside plugins, not isolating them.
2. **Five loading steps**: discovery (four sources, first seen wins) → manifest validation (**executes no code**) → allow/deny adjudication → path boundary check → jiti load + **synchronous register** (preventing the load phase from becoming an async black hole).
3. **The manifest must have id and configSchema**; config validation, Doctor, and UI all depend only on it — **"validating config never becomes running code."**
4. **jiti's trade**: gains are **audit-what-runs** (no compiled artifacts) + **zero SDK version drift** + plugins not needing to depend on `openclaw`; costs are startup transpilation (offset by caching, lazy init, and early short-circuits) and **zero runtime isolation**, acknowledged head-on by SECURITY.md.
5. **Two social defenses**: warning when the allowlist is empty, and provenance tagging plugins that appeared from nowhere as untracked local code — **"available by default, anomalies visible."**
6. **Eleven extension points, but only three boundaries with real force**: the allow/deny list, tool policy (`optional` tools need explicit allow), and **the prompt-injection hook switch**. Everything else is a documentation boundary, not a runtime one.
7. **`src/plugin-sdk/index.ts` routes 21 channels' security-critical logic through one implementation** — compressing "one of 21 hand-copied allowlist parsers gets a boundary wrong" from 21 places to 1.
8. **Core channels are themselves bundled plugins** — the plugin system is the channel system's foundation, not a peripheral mechanism; **a practical test of any plugin system is whether the core's own features use it.**
9. **llm-task's three patterns**: `optional: true` staying out of the default set, subagents with `disableTools` cutting the recursion amplification chain, and **a model allowlist preventing prompt manipulation from routing to expensive models**.
10. **npm distribution's three pieces**: registry-only (no git/URL/ranges) + **`--ignore-scripts` throughout** (removing the postinstall supply-chain surface) + three local audit checks. No central marketplace because **review would create the illusion that "listed means safe,"** contradicting the trust model.
