Skip to content

Commit eeffa53

Browse files
authored
improve(plugins): compile externalized plugins in source builds (#124639)
* build(plugins): compile externalized plugins into local dist * test(plugins): assert native external plugin loading * chore(plugins): keep source runner asset scan unchanged * refactor(plugins): isolate external local dist builds * test(plugins): codify external artifact precedence * test(plugins): preserve contract path boundary
1 parent 146350f commit eeffa53

13 files changed

Lines changed: 382 additions & 85 deletions

‎docs/install/docker.md‎

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -230,10 +230,11 @@ OPENCLAW_DOCKER_BUILD_NODE_OPTIONS=--max-old-space-size=4096 OPENCLAW_DOCKER_BUI
230230
`OPENCLAW_EXTENSIONS` selects plugin manifest ids from the source checkout;
231231
existing source-directory names are also accepted when they differ. The Docker
232232
build resolves the selection to source directories once, installs production
233-
dependencies, and, when a selected plugin is published separately with
234-
`openclaw.build.bundledDist: false`, compiles its runtime into the root bundled
235-
dist. This Docker-only packaging does not change the plugin's npm or ClawHub
236-
artifact contract. Unknown, invalid, or ambiguous ids fail the image build.
233+
dependencies, and includes the selected plugin runtime in the image. Source
234+
checkouts also compile first-party plugins published separately with
235+
`openclaw.build.bundledDist: false`; that marker still preserves the plugin's
236+
external npm or ClawHub ownership and does not change either artifact contract.
237+
Unknown, invalid, or ambiguous ids fail the image build.
237238
Known dependency/source-only ids keep their existing source and dependency
238239
staging without gaining a compiled root dist entry. A selected plugin with
239240
unified build entries must compile successfully; unselected external plugin

‎scripts/build-all.mts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,7 @@ export const BUILD_ALL_STEPS: BuildAllStep[] = [
235235
},
236236
},
237237
},
238+
tsxStep("external-plugins:local-dist", "scripts/build-external-plugin-local-dist.mts"),
238239
tsxStep("check-cli-bootstrap-imports", "scripts/check-cli-bootstrap-imports.mts"),
239240
{
240241
label: "plugins:assets:copy",
@@ -289,6 +290,7 @@ export const BUILD_ALL_PROFILES: Record<string, string[]> = {
289290
"tsdown-ai",
290291
"tsdown-packages",
291292
"tsdown-unified",
293+
"external-plugins:local-dist",
292294
"check-cli-bootstrap-imports",
293295
"plugins:assets:copy",
294296
"runtime-postbuild",
@@ -304,6 +306,7 @@ export const BUILD_ALL_PROFILES: Record<string, string[]> = {
304306
ciArtifacts: [
305307
"plugins:assets:build",
306308
"tsdown",
309+
"external-plugins:local-dist",
307310
"check-cli-bootstrap-imports",
308311
"plugins:assets:copy",
309312
"runtime-postbuild",
@@ -318,6 +321,7 @@ export const BUILD_ALL_PROFILES: Record<string, string[]> = {
318321
],
319322
gatewayWatch: [
320323
"tsdown",
324+
"external-plugins:local-dist",
321325
"check-cli-bootstrap-imports",
322326
"runtime-postbuild",
323327
"build-stamp",
@@ -326,6 +330,7 @@ export const BUILD_ALL_PROFILES: Record<string, string[]> = {
326330
qaRuntime: [
327331
"plugins:assets:build",
328332
"tsdown",
333+
"external-plugins:local-dist",
329334
"check-cli-bootstrap-imports",
330335
"plugins:assets:copy",
331336
"runtime-postbuild",
@@ -335,6 +340,7 @@ export const BUILD_ALL_PROFILES: Record<string, string[]> = {
335340
sourcePerformance: [
336341
"plugins:assets:build",
337342
"tsdown",
343+
"external-plugins:local-dist",
338344
"check-cli-bootstrap-imports",
339345
"plugins:assets:copy",
340346
"runtime-postbuild",
@@ -345,6 +351,7 @@ export const BUILD_ALL_PROFILES: Record<string, string[]> = {
345351
],
346352
cliStartup: [
347353
"tsdown",
354+
"external-plugins:local-dist",
348355
"check-cli-bootstrap-imports",
349356
"runtime-postbuild",
350357
"build-stamp",
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#!/usr/bin/env node
2+
// Builds source-checkout runtime output for externally published first-party plugins.
3+
import fs from "node:fs";
4+
import path from "node:path";
5+
import { performance } from "node:perf_hooks";
6+
import { pathToFileURL } from "node:url";
7+
import { DOCKER_SELECTED_PLUGIN_BUILD_IDS_ENV } from "./lib/bundled-plugin-build-entries.mjs";
8+
import { shouldBuildBundledCluster } from "./lib/optional-bundled-clusters.mjs";
9+
import { assertRealOutputRoot } from "./lib/output-root-guard.mjs";
10+
import {
11+
buildPluginNpmRuntime,
12+
listPublishablePluginPackageDirs,
13+
type PluginPackageJson,
14+
} from "./lib/plugin-npm-runtime-build.mts";
15+
16+
type ExternalPluginLocalDistParams = {
17+
repoRoot?: string;
18+
env?: NodeJS.ProcessEnv;
19+
logLevel?: "silent" | "warn";
20+
};
21+
22+
function readPluginPackageJson(repoRoot: string, packageDir: string): PluginPackageJson {
23+
return JSON.parse(fs.readFileSync(path.join(repoRoot, packageDir, "package.json"), "utf8"));
24+
}
25+
26+
/** Lists external first-party packages that need source-checkout dist output. */
27+
export function listExternalPluginLocalDistPackageDirs(
28+
params: Pick<ExternalPluginLocalDistParams, "repoRoot" | "env"> = {},
29+
): string[] {
30+
const repoRoot = path.resolve(params.repoRoot ?? ".");
31+
const env = params.env ?? process.env;
32+
if (env[DOCKER_SELECTED_PLUGIN_BUILD_IDS_ENV]?.trim()) {
33+
return [];
34+
}
35+
return listPublishablePluginPackageDirs({ repoRoot }).filter((packageDir) => {
36+
const packageJson = readPluginPackageJson(repoRoot, packageDir);
37+
return (
38+
packageJson.openclaw?.build?.bundledDist === false &&
39+
shouldBuildBundledCluster(path.basename(packageDir), env, { packageJson })
40+
);
41+
});
42+
}
43+
44+
/** Builds isolated plugin graphs, then stages every output below its excluded root dist path. */
45+
export async function buildExternalPluginLocalDist(
46+
params: ExternalPluginLocalDistParams = {},
47+
): Promise<{ durationMs: number; pluginDirs: string[] }> {
48+
const repoRoot = path.resolve(params.repoRoot ?? ".");
49+
const packageDirs = listExternalPluginLocalDistPackageDirs({
50+
repoRoot,
51+
env: params.env,
52+
});
53+
const startedAt = performance.now();
54+
const pluginDirs: string[] = [];
55+
56+
for (const packageDir of packageDirs) {
57+
const result = await buildPluginNpmRuntime({
58+
repoRoot,
59+
packageDir,
60+
// Standalone package validation owns its existing bundler warnings; this
61+
// root build still surfaces errors and validates every emitted host import.
62+
logLevel: params.logLevel ?? "error",
63+
});
64+
if (!result) {
65+
throw new Error(`${packageDir} did not produce source-checkout runtime output`);
66+
}
67+
const targetDir = path.join(repoRoot, "dist", "extensions", result.pluginDir);
68+
assertRealOutputRoot(targetDir);
69+
fs.rmSync(targetDir, { recursive: true, force: true });
70+
fs.mkdirSync(path.dirname(targetDir), { recursive: true });
71+
fs.cpSync(result.outDir, targetDir, { recursive: true });
72+
fs.rmSync(result.outDir, { recursive: true, force: true });
73+
pluginDirs.push(result.pluginDir);
74+
}
75+
76+
return {
77+
durationMs: performance.now() - startedAt,
78+
pluginDirs,
79+
};
80+
}
81+
82+
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
83+
try {
84+
const result = await buildExternalPluginLocalDist();
85+
console.log(
86+
`[external-plugin-local-dist] built ${result.pluginDirs.length} plugins in ${Math.round(result.durationMs)}ms`,
87+
);
88+
} catch (error) {
89+
console.error(error instanceof Error ? error.message : String(error));
90+
process.exitCode = 1;
91+
}
92+
}

‎scripts/copy-bundled-plugin-metadata.mts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,15 @@ export function copyBundledPluginMetadata(params: CopyMetadataParams = {}): void
290290
: undefined;
291291
const packageJson = isRecord(parsedPackageJson) ? parsedPackageJson : undefined;
292292
const topLevelPublicSurfaceEntries = collectTopLevelPublicSurfaceEntries(pluginDir);
293-
if (!shouldCopyBundledPluginMetadata(dirent.name, env, buildablePluginDirs)) {
293+
const hasExternalLocalDist =
294+
isRecord(packageJson?.openclaw) &&
295+
isRecord(packageJson.openclaw.build) &&
296+
packageJson.openclaw.build.bundledDist === false &&
297+
fs.existsSync(distPluginDir);
298+
if (
299+
!hasExternalLocalDist &&
300+
!shouldCopyBundledPluginMetadata(dirent.name, env, buildablePluginDirs)
301+
) {
294302
removePathIfExists(distPluginDir);
295303
continue;
296304
}

‎scripts/lib/plugin-npm-runtime-build.mts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ export type PluginPackageJson = JsonRecord & {
2424
dependencies?: JsonRecord;
2525
openclaw?: {
2626
assetScripts?: { build?: unknown };
27-
build?: { openclawVersion?: unknown; runtimeFormat?: unknown };
27+
build?: { bundledDist?: unknown; openclawVersion?: unknown; runtimeFormat?: unknown };
2828
compat?: { pluginApi?: unknown };
2929
release?: {
3030
bundleRuntimeDependencies?: unknown;

‎scripts/test-built-plugin-singleton.mts‎

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,18 @@ const repoRoot = resolveRepoRoot(import.meta.url);
1414
const smokeEntryPath = path.join(repoRoot, "dist", "plugins", "build-smoke-entry.js");
1515
assert.ok(fs.existsSync(smokeEntryPath), `missing build output: ${smokeEntryPath}`);
1616

17-
const { clearPluginCommands, getPluginCommandSpecs, loadOpenClawPlugins, matchPluginCommand } =
18-
await import(pathToFileURL(smokeEntryPath).href);
17+
const {
18+
clearPluginCommands,
19+
getPluginCommandSpecs,
20+
getPluginModuleLoaderStats,
21+
loadOpenClawPlugins,
22+
matchPluginCommand,
23+
} = await import(pathToFileURL(smokeEntryPath).href);
1924

2025
assert.equal(typeof loadOpenClawPlugins, "function", "built loader export missing");
2126
assert.equal(typeof clearPluginCommands, "function", "clearPluginCommands missing");
2227
assert.equal(typeof getPluginCommandSpecs, "function", "getPluginCommandSpecs missing");
28+
assert.equal(typeof getPluginModuleLoaderStats, "function", "plugin loader stats missing");
2329
assert.equal(typeof matchPluginCommand, "function", "matchPluginCommand missing");
2430

2531
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-build-smoke-"));
@@ -105,6 +111,12 @@ stageBundledPluginRuntime({ repoRoot });
105111

106112
const runtimeEntryPath = path.join(runtimePluginDir, "index.js");
107113
assert.ok(fs.existsSync(runtimeEntryPath), "runtime overlay entry missing");
114+
const smsRuntimeEntryPath = path.join(repoRoot, "dist-runtime", "extensions", "sms", "index.js");
115+
assert.ok(fs.existsSync(smsRuntimeEntryPath), "compiled SMS runtime entry missing");
116+
assert.ok(
117+
fs.existsSync(path.join(repoRoot, "dist-runtime", "extensions", "mxc", "mxc-spawn-launcher.mjs")),
118+
"compiled MXC runtime asset missing",
119+
);
108120
assert.equal(
109121
fs.existsSync(path.join(repoRoot, "dist-runtime", "plugins", "commands.js")),
110122
false,
@@ -113,6 +125,54 @@ assert.equal(
113125

114126
clearPluginCommands();
115127

128+
const smsStatsBefore = getPluginModuleLoaderStats();
129+
const smsRegistry = loadOpenClawPlugins({
130+
cache: false,
131+
preferBuiltPluginArtifacts: true,
132+
workspaceDir: tempRoot,
133+
env: {
134+
...process.env,
135+
OPENCLAW_BUNDLED_PLUGINS_DIR: path.join(repoRoot, "dist-runtime", "extensions"),
136+
},
137+
config: {
138+
plugins: {
139+
enabled: true,
140+
allow: ["sms"],
141+
entries: {
142+
sms: { enabled: true },
143+
},
144+
},
145+
},
146+
});
147+
const smsRecord = smsRegistry.plugins.find((entry: { id: string }) => entry.id === "sms");
148+
assert.ok(smsRecord, "SMS plugin missing from registry");
149+
assert.equal(smsRecord.status, "loaded", smsRecord.error ?? "SMS plugin failed to load");
150+
const smsStatsAfter = getPluginModuleLoaderStats();
151+
assert.ok(
152+
smsStatsAfter.nativeHits > smsStatsBefore.nativeHits,
153+
"compiled SMS runtime did not use native loading",
154+
);
155+
for (const counter of [
156+
"nativeMisses",
157+
"sourceTransformForced",
158+
"sourceTransformFallbacks",
159+
] as const) {
160+
assert.equal(
161+
smsStatsAfter[counter],
162+
smsStatsBefore[counter],
163+
`compiled SMS runtime changed ${counter}`,
164+
);
165+
}
166+
assert.equal(
167+
smsStatsAfter.topSourceTransformTargets.some(({ target }: { target: string }) =>
168+
target.replaceAll("\\", "/").includes("/extensions/sms/"),
169+
),
170+
false,
171+
"compiled SMS runtime reached the source transformer",
172+
);
173+
174+
clearPluginCommands();
175+
116176
const registry = loadOpenClawPlugins({
117177
cache: false,
118178
workspaceDir: tempRoot,

‎src/plugins/build-smoke-entry.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,3 +2,4 @@
22
export { clearPluginCommands, executePluginCommand, matchPluginCommand } from "./commands.js";
33
export { getPluginCommandSpecs } from "./command-specs.js";
44
export { loadOpenClawPlugins, loadPluginRegistryHandle } from "./loader.js";
5+
export { getPluginModuleLoaderStats } from "./plugin-module-loader-cache.js";

‎src/plugins/copy-bundled-plugin-metadata.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,28 @@ describe("copyBundledPluginMetadata", () => {
445445
expect(fs.existsSync(staleDistDir)).toBe(false);
446446
});
447447

448+
it("preserves isolated source-checkout output for an external plugin", () => {
449+
const repoRoot = makeRepoRoot("openclaw-external-plugin-local-dist-meta-");
450+
createPlugin(repoRoot, {
451+
id: "sms",
452+
packageName: "@openclaw/sms",
453+
packageOpenClaw: {
454+
extensions: ["./index.ts"],
455+
build: { bundledDist: false },
456+
release: { publishToNpm: true },
457+
},
458+
});
459+
const distPluginDir = path.join(repoRoot, "dist", "extensions", "sms");
460+
fs.mkdirSync(distPluginDir, { recursive: true });
461+
fs.writeFileSync(path.join(distPluginDir, "index.js"), "export default {};\n", "utf8");
462+
463+
copyBundledPluginMetadata({ repoRoot });
464+
465+
expect(fs.existsSync(path.join(distPluginDir, "index.js"))).toBe(true);
466+
expect(fs.existsSync(path.join(distPluginDir, "openclaw.plugin.json"))).toBe(true);
467+
expect(readBundledPackageJson(repoRoot, "sms").openclaw?.extensions).toEqual(["./index.js"]);
468+
});
469+
448470
it("preserves manifest-less runtime support package outputs and copies package metadata", () => {
449471
const repoRoot = makeRepoRoot("openclaw-bundled-runtime-support-");
450472
const pluginDir = path.join(repoRoot, "extensions", "image-generation-core");

0 commit comments

Comments
 (0)