Skip to content

Commit 2ceb181

Browse files
authored
fix(plugins): resolve package module specifiers (#124600)
1 parent 605dece commit 2ceb181

6 files changed

Lines changed: 146 additions & 19 deletions

‎src/channels/plugins/module-loader.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,23 @@ describe("channel plugin module loader helpers", () => {
3636
expect(resolveExistingPluginModulePath(rootDir, "./src/checker")).toBe(expectedPath);
3737
});
3838

39+
it("preserves explicit JavaScript plugin module specifiers", () => {
40+
const rootDir = tempDirs.make("openclaw-channel-module-loader-");
41+
const expectedPath = path.join(rootDir, "checker.js");
42+
fs.writeFileSync(expectedPath, "export const ok = true;\n", "utf8");
43+
44+
expect(resolveExistingPluginModulePath(rootDir, "./checker.js")).toBe(expectedPath);
45+
});
46+
47+
it("resolves plugin module directories through their index", () => {
48+
const rootDir = tempDirs.make("openclaw-channel-module-loader-");
49+
const expectedPath = path.join(rootDir, "checker", "index.js");
50+
fs.mkdirSync(path.dirname(expectedPath), { recursive: true });
51+
fs.writeFileSync(expectedPath, "export const ok = true;\n", "utf8");
52+
53+
expect(resolveExistingPluginModulePath(rootDir, "./checker")).toBe(expectedPath);
54+
});
55+
3956
it("detects JavaScript module paths case-insensitively", () => {
4057
expect(isJavaScriptModulePath("/tmp/entry.js")).toBe(true);
4158
expect(isJavaScriptModulePath("/tmp/entry.MJS")).toBe(true);

‎src/channels/plugins/module-loader.ts‎

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import fs from "node:fs";
77
import { createRequire } from "node:module";
88
import path from "node:path";
99
import { describeRootFileOpenFailure, openRootFileSync } from "../../infra/boundary-file-read.js";
10+
import { hasErrnoCode } from "../../infra/errno.js";
1011
import { isJavaScriptModulePath } from "../../plugins/native-module-require.js";
1112
import {
1213
getCachedPluginModuleLoader,
@@ -15,6 +16,7 @@ import {
1516

1617
const nodeRequire = createRequire(import.meta.url);
1718
const SOURCE_MODULE_EXTENSIONS = new Set([".ts", ".tsx", ".mts", ".cts"]);
19+
const SOURCE_MODULE_RESOLUTION_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"] as const;
1820
const jitiLoaders: PluginModuleLoaderCache = new Map();
1921

2022
function hasNativeSourceRequireHook(modulePath: string): boolean {
@@ -64,34 +66,35 @@ function loadModule(modulePath: string): unknown {
6466
}
6567
}
6668

67-
function resolvePluginModuleCandidates(rootDir: string, specifier: string): string[] {
69+
function resolveSourceModuleCandidates(rootDir: string, specifier: string): string[] {
6870
const normalizedSpecifier = specifier.replace(/\\/g, "/");
6971
const resolvedPath = path.resolve(rootDir, normalizedSpecifier);
70-
const ext = path.extname(resolvedPath);
71-
if (ext) {
72-
return [resolvedPath];
72+
if (path.extname(resolvedPath)) {
73+
return [];
7374
}
74-
return [
75-
resolvedPath,
76-
`${resolvedPath}.ts`,
77-
`${resolvedPath}.mts`,
78-
`${resolvedPath}.js`,
79-
`${resolvedPath}.mjs`,
80-
`${resolvedPath}.cts`,
81-
`${resolvedPath}.cjs`,
82-
];
75+
return SOURCE_MODULE_RESOLUTION_EXTENSIONS.map((extension) => `${resolvedPath}${extension}`);
8376
}
8477

8578
/**
8679
* Resolves a plugin-relative module specifier to an existing candidate path.
8780
*/
8881
export function resolveExistingPluginModulePath(rootDir: string, specifier: string): string {
89-
for (const candidate of resolvePluginModuleCandidates(rootDir, specifier)) {
82+
const resolvedPath = path.resolve(rootDir, specifier.replace(/\\/g, "/"));
83+
try {
84+
// Match Node package semantics for explicit files, extensionless JavaScript,
85+
// package mains, and directory indexes before applying source-only fallbacks.
86+
return nodeRequire.resolve(resolvedPath);
87+
} catch (error) {
88+
if (!hasErrnoCode(error, "MODULE_NOT_FOUND")) {
89+
throw error;
90+
}
91+
}
92+
for (const candidate of resolveSourceModuleCandidates(rootDir, specifier)) {
9093
if (fs.existsSync(candidate)) {
9194
return candidate;
9295
}
9396
}
94-
return path.resolve(rootDir, specifier);
97+
return resolvedPath;
9598
}
9699

97100
/**

‎src/channels/plugins/package-state-probes.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import type { PluginChannelCatalogEntry } from "../../plugins/channel-catalog-registry.js";
77
import {
8+
collectBundledChannelPackageStateLoadFailures,
89
hasBundledChannelPackageState,
910
listBundledChannelIdsForPackageState,
1011
} from "./package-state-probes.js";
@@ -343,6 +344,13 @@ describe("channel package-state probes", () => {
343344
expect(warning).toContain("failed to load persistedAuthState checker for matrix");
344345
expect(warning).toContain(`plugin module path not found: ${builtRoot}`);
345346
expect(warning).not.toContain("escapes plugin root");
347+
expect(collectBundledChannelPackageStateLoadFailures()).toEqual([
348+
{
349+
detail: expect.stringContaining(`plugin module path not found: ${builtRoot}`),
350+
metadataKey: "persistedAuthState",
351+
pluginId: "matrix",
352+
},
353+
]);
346354
});
347355

348356
it("tries dist-runtime package-state probes before falling back to source", () => {

‎src/channels/plugins/package-state-probes.ts‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,14 @@ type ChannelPackageStateMetadata = {
3939
/**
4040
* Metadata keys that can declare a lightweight package-state checker.
4141
*/
42-
type ChannelPackageStateMetadataKey = "configuredState" | "persistedAuthState";
42+
const CHANNEL_PACKAGE_STATE_METADATA_KEYS = ["configuredState", "persistedAuthState"] as const;
43+
type ChannelPackageStateMetadataKey = (typeof CHANNEL_PACKAGE_STATE_METADATA_KEYS)[number];
44+
45+
type ChannelPackageStateLoadFailure = {
46+
detail: string;
47+
metadataKey: ChannelPackageStateMetadataKey;
48+
pluginId: string;
49+
};
4350

4451
const log = createSubsystemLogger("channels");
4552
const sourcePackageStateLoaderCache: PluginModuleLoaderCache = new Map();
@@ -193,7 +200,9 @@ function listChannelPackageStateCatalog(
193200

194201
function resolveChannelPackageStateChecker(params: {
195202
entry: PluginChannelCatalogEntry;
203+
emitWarning?: boolean;
196204
metadataKey: ChannelPackageStateMetadataKey;
205+
onLoadError?: (detail: string) => void;
197206
}): ChannelPackageStateChecker | null {
198207
const metadata = resolveChannelPackageStateMetadata(params.entry, params.metadataKey);
199208
if (!metadata) {
@@ -235,9 +244,12 @@ function resolveChannelPackageStateChecker(params: {
235244

236245
if (loadError) {
237246
const detail = formatErrorMessage(loadError);
238-
log.warn(
239-
`[channels] failed to load ${params.metadataKey} checker for ${params.entry.pluginId}: ${detail}`,
240-
);
247+
if (params.emitWarning !== false) {
248+
log.warn(
249+
`[channels] failed to load ${params.metadataKey} checker for ${params.entry.pluginId}: ${detail}`,
250+
);
251+
}
252+
params.onLoadError?.(detail);
241253
}
242254
return null;
243255
}
@@ -259,6 +271,24 @@ export function listBundledChannelIdsForPackageState(
259271
.toSorted((left, right) => left.localeCompare(right));
260272
}
261273

274+
/** Reports declared bundled channel package-state modules that cannot load. */
275+
export function collectBundledChannelPackageStateLoadFailures(
276+
discovery?: PluginDiscoveryResult,
277+
): ChannelPackageStateLoadFailure[] {
278+
const failures: ChannelPackageStateLoadFailure[] = [];
279+
for (const metadataKey of CHANNEL_PACKAGE_STATE_METADATA_KEYS) {
280+
for (const entry of listChannelPackageStateCatalog(metadataKey, discovery)) {
281+
resolveChannelPackageStateChecker({
282+
entry,
283+
emitWarning: false,
284+
metadataKey,
285+
onLoadError: (detail) => failures.push({ detail, metadataKey, pluginId: entry.pluginId }),
286+
});
287+
}
288+
}
289+
return failures;
290+
}
291+
262292
/**
263293
* Returns whether a bundled channel reports configured/auth package state.
264294
*/

‎src/flows/doctor-health-contributions-final.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,9 @@ import type {
4141
import { createDoctorHealthContribution } from "./doctor-health-contribution.js";
4242
import type { HealthCheck } from "./health-checks.js";
4343

44+
const CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID =
45+
"core/doctor/channel-package-state-capabilities";
46+
4447
export function resolveFinalDoctorHealthContributions(params: {
4548
runSystemdLingerHealth: (ctx: DoctorHealthFlowContext) => Promise<void>;
4649
detectSystemdLingerFindings: HealthCheck["detect"];
@@ -93,6 +96,27 @@ export function resolveFinalDoctorHealthContributions(params: {
9396
},
9497
},
9598
}),
99+
createDoctorHealthContribution({
100+
id: "doctor:channel-package-state-capabilities",
101+
label: "Channel package-state capabilities",
102+
healthChecks: {
103+
id: CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID,
104+
description: "Declared channel package-state checker modules must load.",
105+
defaultEnabled: true,
106+
async detect() {
107+
const { collectBundledChannelPackageStateLoadFailures } =
108+
await import("../channels/plugins/package-state-probes.js");
109+
return collectBundledChannelPackageStateLoadFailures().map((failure) => ({
110+
checkId: CHANNEL_PACKAGE_STATE_CAPABILITIES_CHECK_ID,
111+
severity: "warning" as const,
112+
message: `Plugin ${failure.pluginId} declared ${failure.metadataKey}, but its checker failed to load: ${failure.detail}`,
113+
target: failure.pluginId,
114+
requirement: "declared-channel-package-state-capability-loadable",
115+
fixHint: `Rebuild or reinstall plugin ${failure.pluginId}, then rerun \`openclaw doctor\`.`,
116+
}));
117+
},
118+
},
119+
}),
96120
createDoctorHealthContribution({
97121
id: "doctor:startup-channel-maintenance",
98122
label: "Startup channel maintenance",

‎src/flows/doctor-health-contributions.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ const mocks = vi.hoisted(() => ({
172172
requirement: hit.reason,
173173
}),
174174
),
175+
collectBundledChannelPackageStateLoadFailures: vi.fn(() => [] as unknown[]),
175176
collectStalePluginRuntimeSymlinkHealthFindings: vi.fn(async () => [] as unknown[]),
176177
collectChannelPreviewWarningHealthFindings: vi.fn(
177178
async (): Promise<readonly HealthFinding[]> => [],
@@ -514,6 +515,12 @@ vi.mock("../commands/doctor/shared/channel-plugin-blockers.js", () => ({
514515
channelPluginBlockerHitToHealthFinding: mocks.channelPluginBlockerHitToHealthFinding,
515516
}));
516517

518+
vi.mock("../channels/plugins/package-state-probes.js", async (importOriginal) => ({
519+
...(await importOriginal<typeof import("../channels/plugins/package-state-probes.js")>()),
520+
collectBundledChannelPackageStateLoadFailures:
521+
mocks.collectBundledChannelPackageStateLoadFailures,
522+
}));
523+
517524
vi.mock("./doctor-startup-channel-maintenance.js", async (importOriginal) => {
518525
const actual = await importOriginal<typeof import("./doctor-startup-channel-maintenance.js")>();
519526
return {
@@ -805,6 +812,8 @@ describe("doctor health contributions", () => {
805812
mocks.scanConfiguredChannelPluginBlockers.mockReset();
806813
mocks.scanConfiguredChannelPluginBlockers.mockReturnValue([]);
807814
mocks.channelPluginBlockerHitToHealthFinding.mockClear();
815+
mocks.collectBundledChannelPackageStateLoadFailures.mockReset();
816+
mocks.collectBundledChannelPackageStateLoadFailures.mockReturnValue([]);
808817
mocks.collectStalePluginRuntimeSymlinkHealthFindings.mockReset();
809818
mocks.collectStalePluginRuntimeSymlinkHealthFindings.mockResolvedValue([]);
810819
mocks.collectChannelPreviewWarningHealthFindings.mockReset();
@@ -2341,6 +2350,7 @@ describe("doctor health contributions", () => {
23412350
expect(contributionIds).toContain("core/doctor/whatsapp-responsiveness");
23422351
expect(contributionIds).toContain("core/doctor/device-pairing");
23432352
expect(contributionIds).toContain("core/doctor/channel-plugin-blockers");
2353+
expect(contributionIds).toContain("core/doctor/channel-package-state-capabilities");
23442354
expect(contributionIds).toContain("core/doctor/channel-preview-warnings");
23452355
expect(contributionIds).toContain("core/doctor/systemd-linger");
23462356
expect(contributionChecks.map((check) => check.id)).toEqual(contributionIds);
@@ -3058,6 +3068,41 @@ describe("doctor health contributions", () => {
30583068
expect(mocks.scanConfiguredChannelPluginBlockers).toHaveBeenCalledWith(ctx.cfg, process.env);
30593069
});
30603070

3071+
it("reports channel package-state capability load failures by default", async () => {
3072+
const contributionChecks = await resolveDoctorContributionHealthChecks();
3073+
const capabilityCheck = contributionChecks.find(
3074+
(check) => check.id === "core/doctor/channel-package-state-capabilities",
3075+
);
3076+
expect(capabilityCheck).toMatchObject({ defaultEnabled: true });
3077+
expect(capabilityCheck).toBeDefined();
3078+
mocks.collectBundledChannelPackageStateLoadFailures.mockReturnValue([
3079+
{
3080+
detail: "plugin module path not found: /plugins/example-chat/auth-presence",
3081+
metadataKey: "persistedAuthState",
3082+
pluginId: "example-chat",
3083+
},
3084+
]);
3085+
3086+
const ctx = {
3087+
cfg: {},
3088+
mode: "lint",
3089+
runtime: { log: vi.fn(), error: vi.fn(), exit: vi.fn() },
3090+
} as const;
3091+
3092+
await expect(runDoctorLintChecks(ctx, { checks: [capabilityCheck!] })).resolves.toMatchObject({
3093+
checksRun: 1,
3094+
checksSkipped: 0,
3095+
findings: [
3096+
expect.objectContaining({
3097+
checkId: "core/doctor/channel-package-state-capabilities",
3098+
severity: "warning",
3099+
target: "example-chat",
3100+
requirement: "declared-channel-package-state-capability-loadable",
3101+
}),
3102+
],
3103+
});
3104+
});
3105+
30613106
it("keeps channel preview warnings opt-in for default lint selection", async () => {
30623107
const contribution = requireDoctorContribution("doctor:startup-channel-maintenance");
30633108
expect(contribution.healthCheckIds).toEqual([

0 commit comments

Comments
 (0)