Skip to content

Commit ae800e1

Browse files
committed
fix: prefer source plugins in dev runs
1 parent e086bfe commit ae800e1

7 files changed

Lines changed: 233 additions & 10 deletions

‎src/plugins/dev-source-root.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import fs from "node:fs";
2+
import path from "node:path";
3+
import { resolveUserPath } from "../utils.js";
4+
import { isPathInside, safeRealpathSync } from "./path-safety.js";
5+
6+
export const OPENCLAW_DEV_SOURCE_ROOT_ENV = "OPENCLAW_DEV_SOURCE_ROOT";
7+
8+
function readPackageName(packageJsonPath: string): string | null {
9+
try {
10+
const parsed = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8")) as { name?: unknown };
11+
return typeof parsed.name === "string" ? parsed.name : null;
12+
} catch {
13+
return null;
14+
}
15+
}
16+
17+
export function resolveOpenClawDevSourceRoot(env: NodeJS.ProcessEnv = process.env): string | null {
18+
const rawRoot = env[OPENCLAW_DEV_SOURCE_ROOT_ENV]?.trim();
19+
if (!rawRoot) {
20+
return null;
21+
}
22+
const resolvedRoot = resolveUserPath(rawRoot, env);
23+
const realRoot = safeRealpathSync(resolvedRoot);
24+
if (!realRoot) {
25+
return null;
26+
}
27+
if (readPackageName(path.join(realRoot, "package.json")) !== "openclaw") {
28+
return null;
29+
}
30+
if (!fs.existsSync(path.join(realRoot, "src"))) {
31+
return null;
32+
}
33+
if (!fs.existsSync(path.join(realRoot, "extensions"))) {
34+
return null;
35+
}
36+
return realRoot;
37+
}
38+
39+
export function isBundledPluginInsideDevSourceRoot(params: {
40+
rootDir: string;
41+
env: NodeJS.ProcessEnv;
42+
}): boolean {
43+
const devSourceRoot = resolveOpenClawDevSourceRoot(params.env);
44+
if (!devSourceRoot) {
45+
return false;
46+
}
47+
const extensionsRoot = safeRealpathSync(path.join(devSourceRoot, "extensions"));
48+
const pluginRoot = safeRealpathSync(resolveUserPath(params.rootDir, params.env));
49+
if (!extensionsRoot || !pluginRoot) {
50+
return false;
51+
}
52+
return isPathInside(extensionsRoot, pluginRoot);
53+
}

‎src/plugins/loader-provenance.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { normalizeTrimmedStringList } from "@openclaw/normalization-core/string-normalization";
22
import type { PluginInstallRecord } from "../config/types.plugins.js";
33
import { resolveUserPath } from "../utils.js";
4+
import { isBundledPluginInsideDevSourceRoot } from "./dev-source-root.js";
45
import type { PluginCandidate } from "./discovery.js";
56
import { loadInstalledPluginIndexInstallRecordsSync } from "./installed-plugin-index-records.js";
67
import type { PluginManifestRecord } from "./manifest-registry.js";
@@ -152,17 +153,26 @@ function resolveCandidateDuplicateRank(params: {
152153
if (params.candidate.origin === "config") {
153154
return 0;
154155
}
155-
if (params.candidate.origin === "global" && isExplicitInstall) {
156+
if (
157+
params.candidate.origin === "bundled" &&
158+
isBundledPluginInsideDevSourceRoot({
159+
rootDir: params.candidate.rootDir,
160+
env: params.env,
161+
})
162+
) {
156163
return 1;
157164
}
165+
if (params.candidate.origin === "global" && isExplicitInstall) {
166+
return 2;
167+
}
158168
if (params.candidate.origin === "bundled") {
159169
// Bundled plugin ids stay reserved unless the operator configured an override.
160-
return 2;
170+
return 3;
161171
}
162172
if (params.candidate.origin === "workspace") {
163-
return 3;
173+
return 4;
164174
}
165-
return 4;
175+
return 5;
166176
}
167177

168178
export function compareDuplicateCandidateOrder(params: {

‎src/plugins/loader.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,14 @@ function writeBundledPlugin(params: {
210210
return { bundledDir, plugin };
211211
}
212212

213+
function makeOpenClawDevSourceRoot() {
214+
const root = makeTempDir();
215+
fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "openclaw" }), "utf-8");
216+
mkdirSafe(path.join(root, "src"));
217+
mkdirSafe(path.join(root, "extensions"));
218+
return root;
219+
}
220+
213221
function writeWorkspacePlugin(params: {
214222
id: string;
215223
body?: string;
@@ -7370,6 +7378,58 @@ module.exports = {
73707378
expectDuplicateWarning: false,
73717379
assert: expectPluginSourcePrecedence,
73727380
},
7381+
{
7382+
label: "dev source bundled beats installed global duplicate",
7383+
pluginId: "demo-dev-source-duplicate",
7384+
bundledFilename: "index.cjs",
7385+
loadRegistry: () => {
7386+
const devSourceRoot = makeOpenClawDevSourceRoot();
7387+
const bundledPluginsDir = path.join(devSourceRoot, "extensions");
7388+
writeBundledPlugin({
7389+
id: "demo-dev-source-duplicate",
7390+
body: simplePluginBody("demo-dev-source-duplicate"),
7391+
bundledDir: path.join(bundledPluginsDir, "demo-dev-source-duplicate"),
7392+
});
7393+
process.env.OPENCLAW_BUNDLED_PLUGINS_DIR = bundledPluginsDir;
7394+
return withEnv({ OPENCLAW_DEV_SOURCE_ROOT: devSourceRoot }, () =>
7395+
withStateDir((stateDir) => {
7396+
const globalDir = path.join(stateDir, "extensions", "demo-dev-source-duplicate");
7397+
mkdirSafe(globalDir);
7398+
writePlugin({
7399+
id: "demo-dev-source-duplicate",
7400+
body: simplePluginBody("demo-dev-source-duplicate"),
7401+
dir: globalDir,
7402+
filename: "index.cjs",
7403+
});
7404+
writePersistedInstalledPluginIndexInstallRecordsSync(
7405+
{
7406+
"demo-dev-source-duplicate": {
7407+
source: "npm",
7408+
installPath: globalDir,
7409+
},
7410+
},
7411+
{ stateDir },
7412+
);
7413+
7414+
return loadOpenClawPlugins({
7415+
cache: false,
7416+
config: {
7417+
plugins: {
7418+
allow: ["demo-dev-source-duplicate"],
7419+
entries: {
7420+
"demo-dev-source-duplicate": { enabled: true },
7421+
},
7422+
},
7423+
},
7424+
});
7425+
}),
7426+
);
7427+
},
7428+
expectedLoadedOrigin: "bundled",
7429+
expectedDisabledOrigin: "global",
7430+
expectedDisabledError: "overridden by bundled plugin",
7431+
assert: expectPluginSourcePrecedence,
7432+
},
73737433
{
73747434
label: "transient installed memory plugin beats bundled duplicate",
73757435
pluginId: "memory-lancedb",

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

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,14 @@ function makeTempDir() {
2828
return makeTrackedTempDir("openclaw-manifest-registry", tempDirs);
2929
}
3030

31+
function makeOpenClawDevSourceRoot() {
32+
const root = makeTempDir();
33+
fs.writeFileSync(path.join(root, "package.json"), JSON.stringify({ name: "openclaw" }), "utf-8");
34+
mkdirSafe(path.join(root, "src"));
35+
mkdirSafe(path.join(root, "extensions"));
36+
return root;
37+
}
38+
3139
function writeManifest(dir: string, manifest: Record<string, unknown>) {
3240
fs.writeFileSync(path.join(dir, "openclaw.plugin.json"), JSON.stringify(manifest), "utf-8");
3341
}
@@ -582,6 +590,41 @@ describe("loadPluginManifestRegistry", () => {
582590
expect(registry.plugins[0]?.origin).toBe("global");
583591
});
584592

593+
it("prefers dev source bundled plugins over installed globals with the same id", () => {
594+
const devSourceRoot = makeOpenClawDevSourceRoot();
595+
const bundledDir = path.join(devSourceRoot, "extensions", "codex");
596+
const globalDir = makeTempDir();
597+
const manifest = { id: "codex", configSchema: { type: "object" } };
598+
mkdirSafe(bundledDir);
599+
writeManifest(bundledDir, manifest);
600+
writeManifest(globalDir, manifest);
601+
602+
const registry = loadPluginManifestRegistry({
603+
env: hermeticEnv({ OPENCLAW_DEV_SOURCE_ROOT: devSourceRoot }),
604+
installRecords: {
605+
codex: {
606+
source: "npm",
607+
installPath: globalDir,
608+
},
609+
},
610+
candidates: [
611+
createPluginCandidate({
612+
idHint: "codex",
613+
rootDir: bundledDir,
614+
origin: "bundled",
615+
}),
616+
createPluginCandidate({
617+
idHint: "codex",
618+
rootDir: globalDir,
619+
origin: "global",
620+
}),
621+
],
622+
});
623+
624+
expect(registry.plugins).toHaveLength(1);
625+
expect(registry.plugins[0]?.origin).toBe("bundled");
626+
});
627+
585628
it("suppresses duplicate warnings when the installed global is discovered before bundled", () => {
586629
const bundledDir = makeTempDir();
587630
const globalDir = makeTempDir();

‎src/plugins/manifest-registry.ts‎

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import { resolveUserPath } from "../utils.js";
1414
import { resolveCompatibilityHostVersion } from "../version.js";
1515
import { loadBundleManifest } from "./bundle-manifest.js";
1616
import { normalizePluginsConfigWithResolver } from "./config-policy.js";
17+
import { isBundledPluginInsideDevSourceRoot } from "./dev-source-root.js";
1718
import {
1819
discoverOpenClawPlugins,
1920
type PluginCandidate,
@@ -868,6 +869,15 @@ function resolveDuplicatePrecedenceRank(params: {
868869
if (params.candidate.origin === "config") {
869870
return 0;
870871
}
872+
if (
873+
params.candidate.origin === "bundled" &&
874+
isBundledPluginInsideDevSourceRoot({
875+
rootDir: params.candidate.rootDir,
876+
env: params.env,
877+
})
878+
) {
879+
return 1;
880+
}
871881
if (
872882
params.candidate.origin === "global" &&
873883
matchesInstalledPluginRecord({
@@ -878,16 +888,16 @@ function resolveDuplicatePrecedenceRank(params: {
878888
installRecords: params.installRecords,
879889
})
880890
) {
881-
return 1;
891+
return 2;
882892
}
883893
if (params.candidate.origin === "bundled") {
884894
// Bundled plugin ids are reserved unless the operator explicitly overrides them.
885-
return 2;
895+
return 3;
886896
}
887897
if (params.candidate.origin === "workspace") {
888-
return 3;
898+
return 4;
889899
}
890-
return 4;
900+
return 5;
891901
}
892902

893903
function isIntentionalInstalledBundledDuplicate(params: {
@@ -913,8 +923,12 @@ function isIntentionalInstalledBundledDuplicate(params: {
913923
installRecords: params.installRecords,
914924
});
915925
return (
916-
(leftIsInstalled && params.right.origin === "bundled") ||
917-
(rightIsInstalled && params.left.origin === "bundled")
926+
(leftIsInstalled &&
927+
params.right.origin === "bundled" &&
928+
!isBundledPluginInsideDevSourceRoot({ rootDir: params.right.rootDir, env: params.env })) ||
929+
(rightIsInstalled &&
930+
params.left.origin === "bundled" &&
931+
!isBundledPluginInsideDevSourceRoot({ rootDir: params.left.rootDir, env: params.env }))
918932
);
919933
}
920934

‎src/plugins/plugin-sdk-native-resolver.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ function writeFakeOpenClawPackage(root: string): { distRoot: string; loaderModul
2929
exports: {
3030
"./cli-entry": "./dist/cli-entry.js",
3131
"./plugin-sdk": "./dist/plugin-sdk/root-alias.cjs",
32+
"./plugin-sdk/agent-runtime": "./dist/plugin-sdk/agent-runtime.js",
3233
"./plugin-sdk/channel-message": "./dist/plugin-sdk/channel-message.js",
3334
"./plugin-sdk/channel-outbound": "./dist/plugin-sdk/channel-outbound.js",
3435
"./plugin-sdk/source-only": "./dist/plugin-sdk/source-only.js",
@@ -39,6 +40,11 @@ function writeFakeOpenClawPackage(root: string): { distRoot: string; loaderModul
3940
const pluginSdkDir = path.join(distRoot, "plugin-sdk");
4041
fs.mkdirSync(pluginSdkDir, { recursive: true });
4142
fs.writeFileSync(path.join(pluginSdkDir, "root-alias.cjs"), "module.exports = {};\n", "utf8");
43+
fs.writeFileSync(
44+
path.join(pluginSdkDir, "agent-runtime.js"),
45+
"export const agentRuntimeSource = import.meta.url;\n",
46+
"utf8",
47+
);
4248
fs.writeFileSync(
4349
path.join(pluginSdkDir, "channel-message.js"),
4450
['export * from "./channel-outbound.js";', ""].join("\n"),
@@ -74,6 +80,37 @@ function writeNormalizationCoreSource(root: string): string {
7480
}
7581

7682
describe("installOpenClawPluginSdkNativeResolver", () => {
83+
it("resolves installed plugin SDK imports to the dev source root", () => {
84+
const stableRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-sdk-native-stable-"));
85+
const devRoot = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-sdk-native-dev-source-"));
86+
const { loaderModulePath } = writeFakeOpenClawPackage(stableRoot);
87+
writeFakeOpenClawPackage(devRoot);
88+
fs.mkdirSync(path.join(devRoot, "src"), { recursive: true });
89+
fs.mkdirSync(path.join(devRoot, "extensions"), { recursive: true });
90+
const externalPluginEntry = writeExternalPluginEntry(path.join(stableRoot, "external-plugin"));
91+
const previousDevSourceRoot = process.env.OPENCLAW_DEV_SOURCE_ROOT;
92+
process.env.OPENCLAW_DEV_SOURCE_ROOT = devRoot;
93+
94+
try {
95+
const installedAliases = installOpenClawPluginSdkNativeResolver({
96+
modulePath: loaderModulePath,
97+
pluginModulePath: externalPluginEntry,
98+
});
99+
100+
expect(installedAliases).toContain("openclaw/plugin-sdk/agent-runtime");
101+
const requireFromPlugin = createRequire(externalPluginEntry);
102+
expect(fs.realpathSync(requireFromPlugin.resolve("openclaw/plugin-sdk/agent-runtime"))).toBe(
103+
fs.realpathSync(path.join(devRoot, "dist", "plugin-sdk", "agent-runtime.js")),
104+
);
105+
} finally {
106+
if (previousDevSourceRoot === undefined) {
107+
delete process.env.OPENCLAW_DEV_SOURCE_ROOT;
108+
} else {
109+
process.env.OPENCLAW_DEV_SOURCE_ROOT = previousDevSourceRoot;
110+
}
111+
}
112+
});
113+
77114
it("keeps native aliases on JS dist artifacts when source files exist", () => {
78115
const root = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-sdk-native-source-resolver-"));
79116
const { loaderModulePath } = writeFakeOpenClawPackage(root);

‎src/plugins/sdk-alias.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
55
import { normalizeLowercaseStringOrEmpty } from "@openclaw/normalization-core/string-coerce";
66
import { tryReadJsonSync } from "../infra/json-files.js";
77
import { resolveOpenClawPackageRootSync } from "../infra/openclaw-root.js";
8+
import { OPENCLAW_DEV_SOURCE_ROOT_ENV, resolveOpenClawDevSourceRoot } from "./dev-source-root.js";
89
import { PluginLruCache } from "./plugin-cache-primitives.js";
910

1011
type PluginSdkAliasCandidateKind = "dist" | "src";
@@ -335,6 +336,10 @@ function formatResolutionError(error: unknown): string {
335336
function resolveLoaderPluginSdkPackageRoot(
336337
params: LoaderModuleResolveParams & { modulePath: string },
337338
): string | null {
339+
const devSourceRoot = resolveOpenClawDevSourceRoot(process.env);
340+
if (devSourceRoot) {
341+
return devSourceRoot;
342+
}
338343
const cwd = params.cwd ?? path.dirname(params.modulePath);
339344
const fromCwd = resolveOpenClawPackageRootSync({ cwd });
340345
const fromExplicitHints =
@@ -1527,6 +1532,7 @@ function buildPluginLoaderAliasMapCacheKey(params: {
15271532
params.moduleUrl ?? "",
15281533
params.pluginSdkResolution,
15291534
process.cwd(),
1535+
process.env[OPENCLAW_DEV_SOURCE_ROOT_ENV] ?? "",
15301536
process.env.NODE_ENV === "production" ? "production" : "non-production",
15311537
shouldIncludePrivateLocalOnlyPluginSdkSubpaths() ? "private-qa" : "public",
15321538
].join("\0");

0 commit comments

Comments
 (0)