Skip to content

Commit bbd66c4

Browse files
authored
fix(plugins): fail closed when plugin runtime is unavailable during registration (#130597)
* fix(plugins): fail closed when plugin runtime is unavailable Core fabricated an empty object as `PluginRuntime` for the `cli-metadata` and `setup-only` registration passes, so any plugin touching `api.runtime` during `register()` died with an opaque `TypeError: Cannot read properties of undefined (reading 'openSyncKeyedStore')` that named neither the contract nor the mode. Replace those fabrications with one shared fail-closed runtime that throws a named, actionable error identifying the plugin and registration mode. Symbol reads stay inert so inspection and reflection cannot trigger the guard. Also resolve the lightweight `cli-metadata` entry beside the resolved plugin entry, not only at the package root. Published plugin packages emit it at `dist/cli-metadata.js`, so the probe always missed and the loader fell back to executing the full heavy entry for CLI metadata collection. Documents which registration modes expose a live `api.runtime`; the SDK reference previously claimed it was injected into every plugin. * fix(ui): restore sidebar lazy import boundaries Remove the redundant viewer-facepile dynamic import: sidebar consumers already register that element through the static graph. Import pet data and sprite helpers from their owning leaf modules, delete the registration module's re-export barrel, and make the element itself the lobster-pet.runtime.ts lazy boundary. Keep shared sprite styles with the look renderer so standalone pages do not need element registration. Regenerate the measured boot inventory with the canonical browser probe. Use Lit's typed lifecycle map to remove the obsolete assertion baseline entry and keep the now-private facepile variant type local. The full build has no INEFFECTIVE_DYNAMIC_IMPORT warnings. Relevant UI coverage passes (503 tests plus 5 Chromium E2E tests); the unchanged plugin runtime regression suites pass all 58 tests. The broad plugin suite still reports schema-version, doctor-closure, hook-process, and catalog failures.
1 parent 1cb914d commit bbd66c4

26 files changed

Lines changed: 209 additions & 113 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3561,7 +3561,7 @@ src/plugins/lazy-service-module.ts 1
35613561
src/plugins/legacy-session-surfaces.ts 3
35623562
src/plugins/loader-channel-runtime.ts 1
35633563
src/plugins/loader-channel-setup.ts 17
3564-
src/plugins/loader-cli-registry.ts 4
3564+
src/plugins/loader-cli-registry.ts 2
35653565
src/plugins/loader-discovery.ts 1
35663566
src/plugins/loader-load-context.ts 5
35673567
src/plugins/loader-module-runtime.ts 13
@@ -3641,7 +3641,7 @@ src/plugins/sdk-alias.ts 3
36413641
src/plugins/services.ts 1
36423642
src/plugins/session-catalog-history-import.ts 2
36433643
src/plugins/setup-registry-loader-state.ts 1
3644-
src/plugins/setup-registry.ts 13
3644+
src/plugins/setup-registry.ts 12
36453645
src/plugins/slots.ts 3
36463646
src/plugins/toggle-config.ts 3
36473647
src/plugins/tool-descriptor-cache.ts 4
@@ -3999,7 +3999,6 @@ ui/src/components/github-link-hovercard.runtime.ts 2
39993999
ui/src/components/hub-tabs.ts 2
40004000
ui/src/components/input-dialog.ts 1
40014001
ui/src/components/lobster-dex.ts 2
4002-
ui/src/components/lobster-pet.ts 1
40034002
ui/src/components/login-gate.ts 3
40044003
ui/src/components/markdown-assistant-transcript.ts 1
40054004
ui/src/components/markdown-code-blocks.ts 1

‎docs/plugins/sdk-entrypoints.md‎

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -391,14 +391,16 @@ limited to config-only routes or methods required by that setup flow.
391391

392392
`api.registrationMode` tells your plugin how it was loaded:
393393

394-
| Mode | When | What to register |
395-
| ------------------ | -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
396-
| `"full"` | Normal gateway startup | Everything |
397-
| `"discovery"` | Read-only capability discovery | Channel registration, static CLI descriptors, and inert providers; skip sockets, workers, clients, and services |
398-
| `"tool-discovery"` | Scoped load to list or run specific plugins' tools | Capability/tool registration only; no channel activation |
399-
| `"setup-only"` | Disabled/unconfigured channel | Channel registration only |
400-
| `"setup-runtime"` | Setup flow with runtime available | Channel registration plus only the lightweight runtime needed during setup |
401-
| `"cli-metadata"` | Root help / CLI metadata capture | CLI descriptors only |
394+
| Mode | When | Runtime | What to register |
395+
| ------------------ | -------------------------------------------------- | ----------- | --------------------------------------------------------------------------------------------------------------- |
396+
| `"full"` | Normal gateway startup | Live | Everything |
397+
| `"discovery"` | Read-only capability discovery | Live | Channel registration, static CLI descriptors, and inert providers; skip sockets, workers, clients, and services |
398+
| `"tool-discovery"` | Scoped load to list or run specific plugins' tools | Live | Capability/tool registration only; no channel activation |
399+
| `"setup-only"` | Disabled/unconfigured channel | Unavailable | Channel registration only |
400+
| `"setup-runtime"` | Setup flow with runtime available | Live | Channel registration plus only the lightweight runtime needed during setup |
401+
| `"cli-metadata"` | Root help / CLI metadata capture | Unavailable | CLI descriptors only |
402+
403+
In `"cli-metadata"` and `"setup-only"` modes, accessing a runtime capability throws an error naming the plugin and mode. Defer runtime access out of `register()` or declare root commands in the manifest's `cliCommands` so CLI metadata can be collected without executing the plugin.
402404

403405
`defineChannelPluginEntry` handles this split automatically. If you use
404406
`definePluginEntry` directly for a channel, check mode yourself and remember

‎docs/plugins/sdk-runtime.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ read_when:
99
- You are implementing model-picker persistence in a channel plugin
1010
---
1111

12-
Reference for the `api.runtime` object injected into every plugin during registration. Use these helpers instead of importing host internals directly.
12+
Reference for the live `api.runtime` object available during `"full"`, `"discovery"`, `"tool-discovery"`, and `"setup-runtime"` registration. During `"cli-metadata"` and `"setup-only"` registration, runtime capabilities are intentionally unavailable: accessing one throws an error naming the plugin and mode. Defer runtime access out of `register()` or, for root CLI commands, declare `cliCommands` in the plugin manifest. Use runtime helpers instead of importing host internals directly.
1313

1414
<CardGroup cols={2}>
1515
<Card title="Channel plugins" href="/plugins/sdk-channel-plugins">

‎src/plugins/api-builder.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,28 @@ const noopRegisterMemoryCorpusSupplement: OpenClawPluginApi["registerMemoryCorpu
186186
() => {};
187187
const noopOn: OpenClawPluginApi["on"] = () => {};
188188

189+
export function createUnavailableRuntime(
190+
registrationMode: "cli-metadata" | "setup-only",
191+
pluginId?: string,
192+
): PluginRuntime {
193+
const owner = pluginId ? `Plugin "${pluginId}"` : "Plugin";
194+
const guidance =
195+
registrationMode === "cli-metadata"
196+
? "Declare root commands in the manifest's cliCommands or defer runtime access out of register()."
197+
: "Defer runtime access out of register().";
198+
// SAFETY: String capabilities fail closed; symbols stay inert so reflection cannot trigger runtime errors.
199+
return new Proxy(Object.create(null) as PluginRuntime, {
200+
get(_target, property) {
201+
if (typeof property === "symbol") {
202+
return undefined;
203+
}
204+
throw new Error(
205+
`${owner} runtime is intentionally unavailable during "${registrationMode}" registration. ${guidance}`,
206+
);
207+
},
208+
});
209+
}
210+
189211
export function buildPluginApi(params: BuildPluginApiParams): OpenClawPluginApi {
190212
const handlers = params.handlers ?? {};
191213
const registerCli = handlers.registerCli ?? noopRegisterCli;

‎src/plugins/captured-registration.test.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,20 @@ import { capturePluginRegistration } from "./captured-registration.js";
44
import type { AnyAgentTool, OpenClawPluginApi } from "./types.js";
55

66
describe("captured plugin registration", () => {
7+
it("rejects runtime access while capturing CLI metadata without activating the real runtime", () => {
8+
expect(() =>
9+
capturePluginRegistration({
10+
id: "captured-cli-plugin",
11+
registrationMode: "cli-metadata",
12+
register(api) {
13+
api.runtime.state.openSyncKeyedStore({ namespace: "example", maxEntries: 1 });
14+
},
15+
}),
16+
).toThrow(
17+
'Plugin "captured-cli-plugin" runtime is intentionally unavailable during "cli-metadata" registration.',
18+
);
19+
});
20+
721
it("preserves root machine-output metadata", () => {
822
const machineOutput = ({ stdoutIsTTY }: { stdoutIsTTY: boolean }) => !stdoutIsTTY;
923
const captured = capturePluginRegistration({
@@ -156,6 +170,7 @@ describe("captured plugin registration", () => {
156170
expect(captured.textTransforms[0]?.input).toHaveLength(1);
157171
expect(captured.agentToolResultMiddlewares).toHaveLength(1);
158172
expect(captured.agentToolResultMiddlewares[0]?.runtimes).toEqual(["codex"]);
173+
expect(captured.api.runtime.version).toEqual(expect.any(String));
159174
});
160175

161176
it("enforces captured middleware runtime and tool scopes", async () => {

‎src/plugins/captured-registration.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import {
1212
agentToolResultMiddlewareRegistrationCoversTool,
1313
normalizeAgentToolResultMiddlewareRuntimes,
1414
} from "./agent-tool-result-middleware.js";
15-
import { buildPluginApi } from "./api-builder.js";
15+
import { buildPluginApi, createUnavailableRuntime } from "./api-builder.js";
1616
import type { CodexAppServerExtensionFactory } from "./codex-app-server-extension-types.js";
1717
import type { EmbeddingProviderAdapter } from "./embedding-providers.js";
1818
import type {
@@ -137,6 +137,7 @@ export function createCapturedPluginRegistration(params?: {
137137
const pluginId = params?.id ?? "captured-plugin-registration";
138138
const pluginName = params?.name ?? "Captured Plugin Registration";
139139
const pluginSource = params?.source ?? "captured-plugin-registration";
140+
const registrationMode = params?.registrationMode ?? "full";
140141
const noopLogger = {
141142
info() {},
142143
warn() {},
@@ -180,9 +181,12 @@ export function createCapturedPluginRegistration(params?: {
180181
id: pluginId,
181182
name: pluginName,
182183
source: pluginSource,
183-
registrationMode: params?.registrationMode ?? "full",
184+
registrationMode,
184185
config: params?.config ?? ({} as OpenClawConfig),
185-
runtime: createPluginRuntime(),
186+
runtime:
187+
registrationMode === "cli-metadata" || registrationMode === "setup-only"
188+
? createUnavailableRuntime(registrationMode, pluginId)
189+
: createPluginRuntime(),
186190
logger: noopLogger,
187191
resolvePath: (input) => input,
188192
handlers: {

‎src/plugins/loader-cli-registry.ts‎

Lines changed: 11 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import path from "node:path";
33
import type { GatewayRequestHandler } from "../gateway/server-methods/types.js";
44
import { describeRootFileOpenFailure, openRootFileSync } from "../infra/boundary-file-read.js";
55
import { resolveUserPath } from "../utils.js";
6-
import { buildPluginApi } from "./api-builder.js";
6+
import { buildPluginApi, createUnavailableRuntime } from "./api-builder.js";
77
import {
88
resolveEffectiveEnableState,
99
resolveEffectivePluginActivationState,
@@ -41,17 +41,9 @@ import { withProfile } from "./plugin-load-profile.js";
4141
import { normalizePluginPolicyId } from "./plugin-policy-id.js";
4242
import { createPluginIdScopeSet } from "./plugin-scope.js";
4343
import { createPluginRegistry, type PluginRecord, type PluginRegistry } from "./registry.js";
44-
import type { PluginRuntime } from "./runtime/types.js";
4544
import { hasKind, kindsEqual } from "./slots.js";
4645
import type { OpenClawPluginModule } from "./types.js";
4746

48-
const CLI_METADATA_ENTRY_BASENAMES = [
49-
"cli-metadata.ts",
50-
"cli-metadata.js",
51-
"cli-metadata.mjs",
52-
"cli-metadata.cjs",
53-
] as const;
54-
5547
export async function loadOpenClawPluginCliRegistry(
5648
options: PluginLoadOptions = {},
5749
): Promise<PluginRegistry> {
@@ -64,7 +56,7 @@ export async function loadOpenClawPluginCliRegistry(
6456
});
6557
const { registry, registerCli, rollbackPluginGlobalSideEffects } = createPluginRegistry({
6658
logger,
67-
runtime: {} as PluginRuntime,
59+
runtime: createUnavailableRuntime("cli-metadata"),
6860
coreGatewayHandlers: options.coreGatewayHandlers as Record<string, GatewayRequestHandler>,
6961
...(options.coreGatewayMethodNames !== undefined && {
7062
coreGatewayMethodNames: options.coreGatewayMethodNames,
@@ -198,7 +190,7 @@ export async function loadOpenClawPluginCliRegistry(
198190
pushPluginLoadError(`invalid config: ${validatedConfig.error.join(", ")}`);
199191
continue;
200192
}
201-
const cliMetadataSource = resolveCliMetadataEntrySource(candidate.rootDir);
193+
const cliMetadataSource = resolveCliMetadataEntrySource(candidate.rootDir, candidate.source);
202194
const sourceForCliMetadata =
203195
candidate.origin === "bundled"
204196
? cliMetadataSource
@@ -322,7 +314,7 @@ export async function loadOpenClawPluginCliRegistry(
322314
registrationMode: "cli-metadata",
323315
config: context.cfg,
324316
pluginConfig: validatedConfig.value,
325-
runtime: {} as PluginRuntime,
317+
runtime: createUnavailableRuntime("cli-metadata", record.id),
326318
logger,
327319
resolvePath: (input) => resolveUserPath(input),
328320
handlers: {
@@ -354,11 +346,13 @@ export async function loadOpenClawPluginCliRegistry(
354346
return registry;
355347
}
356348

357-
function resolveCliMetadataEntrySource(rootDir: string): string | null {
358-
for (const basename of CLI_METADATA_ENTRY_BASENAMES) {
359-
const candidate = path.join(rootDir, basename);
360-
if (fs.existsSync(candidate)) {
361-
return candidate;
349+
function resolveCliMetadataEntrySource(rootDir: string, source: string): string | null {
350+
for (const directory of new Set([rootDir, path.dirname(source)])) {
351+
for (const extension of [".ts", ".js", ".mjs", ".cjs"]) {
352+
const candidate = path.join(directory, `cli-metadata${extension}`);
353+
if (fs.existsSync(candidate)) {
354+
return candidate;
355+
}
362356
}
363357
}
364358
return null;

‎src/plugins/loader.cli-metadata.test.ts‎

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,82 @@ describe("plugin loader CLI metadata", () => {
7979
},
8080
);
8181

82+
it("rejects runtime access during CLI metadata registration with actionable plugin guidance", async () => {
83+
useNoBundledPlugins();
84+
const plugin = writePlugin({
85+
id: "runtime-dependent",
86+
filename: "runtime-dependent.cjs",
87+
body: `module.exports = {
88+
id: "runtime-dependent",
89+
register(api) {
90+
api.runtime.state.openSyncKeyedStore({ namespace: "example", maxEntries: 1 });
91+
},
92+
};`,
93+
});
94+
95+
const registry = await loadOpenClawPluginCliRegistry({
96+
config: {
97+
plugins: {
98+
load: { paths: [plugin.file] },
99+
allow: [plugin.id],
100+
},
101+
},
102+
});
103+
104+
const pluginError = registry.plugins.find((entry) => entry.id === plugin.id)?.error;
105+
expect(pluginError).toContain('Plugin "runtime-dependent"');
106+
expect(pluginError).toContain('"cli-metadata" registration');
107+
expect(pluginError).toContain("runtime is intentionally unavailable");
108+
expect(pluginError).toContain("cliCommands");
109+
expect(pluginError).toContain("defer runtime access out of register()");
110+
expect(pluginError).not.toContain("Cannot read properties of undefined");
111+
});
112+
113+
it("loads packaged CLI metadata beside the resolved dist entry without evaluating the heavy entry", async () => {
114+
useNoBundledPlugins();
115+
const pluginDir = makePluginLoaderTempDir();
116+
const distDir = path.join(pluginDir, "dist");
117+
const heavyMarker = path.join(pluginDir, "heavy-loaded.txt");
118+
fs.mkdirSync(distDir);
119+
const plugin = writePlugin({
120+
id: "packaged-cli-metadata",
121+
dir: pluginDir,
122+
filename: "dist/index.js",
123+
body: `require("node:fs").writeFileSync(${JSON.stringify(heavyMarker)}, "loaded");
124+
module.exports = { id: "packaged-cli-metadata", register() {} };`,
125+
});
126+
fs.writeFileSync(
127+
path.join(pluginDir, "package.json"),
128+
JSON.stringify({
129+
name: "packaged-cli-metadata",
130+
openclaw: { extensions: ["./dist/index.js"] },
131+
}),
132+
);
133+
fs.writeFileSync(
134+
path.join(distDir, "cli-metadata.js"),
135+
`module.exports = {
136+
id: "packaged-cli-metadata",
137+
register(api) {
138+
api.registerCli(() => {}, {
139+
descriptors: [{ name: "packaged-light", description: "Light entry", hasSubcommands: false }],
140+
});
141+
},
142+
};`,
143+
);
144+
145+
const registry = await loadOpenClawPluginCliRegistry({
146+
config: {
147+
plugins: {
148+
load: { paths: [pluginDir] },
149+
allow: [plugin.id],
150+
},
151+
},
152+
});
153+
154+
expect(fs.existsSync(heavyMarker)).toBe(false);
155+
expect(registry.cliRegistrars.flatMap((entry) => entry.commands)).toContain("packaged-light");
156+
});
157+
82158
it("suppresses trust warning logs during CLI metadata loads", async () => {
83159
useNoBundledPlugins();
84160
const stateDir = makePluginLoaderTempDir();

‎src/plugins/setup-registry.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -983,6 +983,29 @@ describe("setup-registry module loader", () => {
983983
);
984984
});
985985

986+
it("reports unavailable setup runtime access with the plugin id and registration mode", () => {
987+
const pluginRoot = makeTempDir();
988+
writeSetupApiStub(pluginRoot);
989+
mockSinglePlugin({ id: "runtime-dependent-setup", rootDir: pluginRoot });
990+
mocks.createJiti.mockImplementation(() => () => ({
991+
default: {
992+
register(api: import("./types.js").OpenClawPluginApi) {
993+
api.runtime.state.openSyncKeyedStore({ namespace: "example", maxEntries: 1 });
994+
},
995+
},
996+
}));
997+
998+
expect(resolvePluginSetupRegistry({ env: {} }).diagnostics).toMatchObject([
999+
{
1000+
pluginId: "runtime-dependent-setup",
1001+
code: "setup-registration-failed",
1002+
message: expect.stringContaining(
1003+
'Plugin "runtime-dependent-setup" runtime is intentionally unavailable during "setup-only" registration.',
1004+
),
1005+
},
1006+
]);
1007+
});
1008+
9861009
it("publishes each plugin setup registration atomically on synchronous success", () => {
9871010
const throwingRoot = makeTempDir();
9881011
const healthyRoot = makeTempDir();

‎src/plugins/setup-registry.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import {
99
} from "@openclaw/normalization-core/string-normalization";
1010
import type { OpenClawConfig } from "../config/types.openclaw.js";
1111
import { createSubsystemLogger } from "../logging/subsystem.js";
12-
import { buildPluginApi } from "./api-builder.js";
12+
import { buildPluginApi, createUnavailableRuntime } from "./api-builder.js";
1313
import { collectPluginConfigContractMatches } from "./config-contracts.js";
1414
import { getCurrentPluginMetadataSnapshotState } from "./current-plugin-metadata-state.js";
1515
import type { PluginManifestRecord, PluginManifestRegistry } from "./manifest-registry.js";
@@ -23,7 +23,6 @@ import {
2323
} from "./plugin-module-loader-cache.js";
2424
import { loadPluginManifestRegistryForPluginRegistry } from "./plugin-registry.js";
2525
import { resolvePreferredBundledRootArtifact } from "./plugin-runtime-artifact-selection.js";
26-
import type { PluginRuntime } from "./runtime/types.js";
2726
import { listSetupCliBackendIds, listSetupProviderIds } from "./setup-descriptors.js";
2827
import { pluginSetupRegistryLoaderState } from "./setup-registry-loader-state.js";
2928
import type {
@@ -94,7 +93,6 @@ type SetupAutoEnableReason = {
9493

9594
type PluginApiBuildParams = Parameters<typeof buildPluginApi>[0];
9695

97-
const EMPTY_RUNTIME = {} as PluginRuntime;
9896
const NOOP_LOGGER: PluginLogger = {
9997
info() {},
10098
warn() {},
@@ -312,7 +310,7 @@ function buildSetupPluginApi(params: {
312310
rootDir: params.record.rootDir,
313311
registrationMode: "setup-only",
314312
config: {} as OpenClawConfig,
315-
runtime: EMPTY_RUNTIME,
313+
runtime: createUnavailableRuntime("setup-only", params.record.id),
316314
logger: NOOP_LOGGER,
317315
resolvePath: (input) => input,
318316
handlers: params.handlers,

0 commit comments

Comments
 (0)