Files
test-openclaw/src/plugins/tools.ts
T
Dewaldt HuysamenandAyaan Zaidi 27188fa39f fix: scope subagent registry reuse to tool loading (#56240) (thanks @GodsBoy)
* fix(plugins): reuse active registry for sub-agent tool resolution

* test(plugins): harden resolveRuntimePluginRegistry with per-field, caller-shape, and cold-start tests

Add 11 regression tests covering:
- R1: Per-field isolation (coreGatewayHandlers, includeSetupOnlyChannelPlugins,
  preferSetupRuntimeForChannelPlugins each independently prevent fallback;
  empty onlyPluginIds[] treated as non-gateway-scoped)
- R2: Caller-shape regression (tools.ts, memory-runtime.ts,
  channel-resolution.ts shapes fall back; web-search-providers.runtime.ts
  with onlyPluginIds does not)
- R3: Cold-start path (null active registry falls through to loadOpenClawPlugins)

Add debug logging to resolveRuntimePluginRegistry recording which exit path
was taken (no-options, cache-key-match, non-gateway-scoped fallback, fresh load).

* refactor: simplify plugin registry resolution tests and trim happy-path debug logs

* fix(plugins): address review comments on registry fallback

- Fix cold-start test assertion: loadOpenClawPlugins always activates
  the registry (shouldActivate defaults to true), so getActivePluginRegistry()
  is not null after the call. Updated assertion to match actual behavior.

- Add safety comment documenting why the non-gateway-scoped fallback is
  safe despite cache-key mismatch: single-gateway-per-process model means
  sub-agents share workspaceDir, config, and env with the gateway.

* test(plugins): restructure per-field isolation tests to avoid load timeouts

Test isGatewayScopedLoad directly instead of going through the full
resolveRuntimePluginRegistry path which triggers expensive plugin
discovery. This fixes the includeSetupOnlyChannelPlugins test timing
out in CI while providing more precise coverage of the predicate.

* fix(plugins): expand safety comment to address startup-scoped registry concern

* fix(plugins): scope subagent registry reuse to tool loading

---------

Co-authored-by: Ayaan Zaidi <hi@obviy.us>
2026-03-29 09:36:09 +05:30

180 lines
5.6 KiB
TypeScript

import { normalizeToolName } from "../agents/tool-policy.js";
import type { AnyAgentTool } from "../agents/tools/common.js";
import { applyPluginAutoEnable } from "../config/plugin-auto-enable.js";
import { createSubsystemLogger } from "../logging/subsystem.js";
import { applyTestPluginDefaults, normalizePluginsConfig } from "./config-state.js";
import { resolveRuntimePluginRegistry, type PluginLoadOptions } from "./loader.js";
import { createPluginLoaderLogger } from "./logger.js";
import { getActivePluginRegistry } from "./runtime.js";
import type { OpenClawPluginToolContext } from "./types.js";
const log = createSubsystemLogger("plugins");
type PluginToolMeta = {
pluginId: string;
optional: boolean;
};
const pluginToolMeta = new WeakMap<AnyAgentTool, PluginToolMeta>();
export function getPluginToolMeta(tool: AnyAgentTool): PluginToolMeta | undefined {
return pluginToolMeta.get(tool);
}
export function copyPluginToolMeta(source: AnyAgentTool, target: AnyAgentTool): void {
const meta = pluginToolMeta.get(source);
if (meta) {
pluginToolMeta.set(target, meta);
}
}
function normalizeAllowlist(list?: string[]) {
return new Set((list ?? []).map(normalizeToolName).filter(Boolean));
}
function isOptionalToolAllowed(params: {
toolName: string;
pluginId: string;
allowlist: Set<string>;
}): boolean {
if (params.allowlist.size === 0) {
return false;
}
const toolName = normalizeToolName(params.toolName);
if (params.allowlist.has(toolName)) {
return true;
}
const pluginKey = normalizeToolName(params.pluginId);
if (params.allowlist.has(pluginKey)) {
return true;
}
return params.allowlist.has("group:plugins");
}
function resolvePluginToolRegistry(params: {
loadOptions: PluginLoadOptions;
allowGatewaySubagentBinding?: boolean;
}) {
if (params.allowGatewaySubagentBinding) {
return getActivePluginRegistry() ?? resolveRuntimePluginRegistry(params.loadOptions);
}
return resolveRuntimePluginRegistry(params.loadOptions);
}
export function resolvePluginTools(params: {
context: OpenClawPluginToolContext;
existingToolNames?: Set<string>;
toolAllowlist?: string[];
suppressNameConflicts?: boolean;
allowGatewaySubagentBinding?: boolean;
env?: NodeJS.ProcessEnv;
}): AnyAgentTool[] {
// Fast path: when plugins are effectively disabled, avoid discovery/jiti entirely.
// This matters a lot for unit tests and for tool construction hot paths.
const env = params.env ?? process.env;
const baseConfig = applyTestPluginDefaults(params.context.config ?? {}, env);
const effectiveConfig = applyPluginAutoEnable({ config: baseConfig, env }).config;
const normalized = normalizePluginsConfig(effectiveConfig.plugins);
if (!normalized.enabled) {
return [];
}
const runtimeOptions = params.allowGatewaySubagentBinding
? { allowGatewaySubagentBinding: true as const }
: undefined;
const loadOptions = {
config: effectiveConfig,
workspaceDir: params.context.workspaceDir,
runtimeOptions,
env,
logger: createPluginLoaderLogger(log),
};
const registry = resolvePluginToolRegistry({
loadOptions,
allowGatewaySubagentBinding: params.allowGatewaySubagentBinding,
});
if (!registry) {
return [];
}
const tools: AnyAgentTool[] = [];
const existing = params.existingToolNames ?? new Set<string>();
const existingNormalized = new Set(Array.from(existing, (tool) => normalizeToolName(tool)));
const allowlist = normalizeAllowlist(params.toolAllowlist);
const blockedPlugins = new Set<string>();
for (const entry of registry.tools) {
if (blockedPlugins.has(entry.pluginId)) {
continue;
}
const pluginIdKey = normalizeToolName(entry.pluginId);
if (existingNormalized.has(pluginIdKey)) {
const message = `plugin id conflicts with core tool name (${entry.pluginId})`;
if (!params.suppressNameConflicts) {
log.error(message);
registry.diagnostics.push({
level: "error",
pluginId: entry.pluginId,
source: entry.source,
message,
});
}
blockedPlugins.add(entry.pluginId);
continue;
}
let resolved: AnyAgentTool | AnyAgentTool[] | null | undefined = null;
try {
resolved = entry.factory(params.context);
} catch (err) {
log.error(`plugin tool failed (${entry.pluginId}): ${String(err)}`);
continue;
}
if (!resolved) {
if (entry.names.length > 0) {
log.debug(
`plugin tool factory returned null (${entry.pluginId}): [${entry.names.join(", ")}]`,
);
}
continue;
}
const listRaw = Array.isArray(resolved) ? resolved : [resolved];
const list = entry.optional
? listRaw.filter((tool) =>
isOptionalToolAllowed({
toolName: tool.name,
pluginId: entry.pluginId,
allowlist,
}),
)
: listRaw;
if (list.length === 0) {
continue;
}
const nameSet = new Set<string>();
for (const tool of list) {
if (nameSet.has(tool.name) || existing.has(tool.name)) {
const message = `plugin tool name conflict (${entry.pluginId}): ${tool.name}`;
if (!params.suppressNameConflicts) {
log.error(message);
registry.diagnostics.push({
level: "error",
pluginId: entry.pluginId,
source: entry.source,
message,
});
}
continue;
}
nameSet.add(tool.name);
existing.add(tool.name);
pluginToolMeta.set(tool, {
pluginId: entry.pluginId,
optional: entry.optional,
});
tools.push(tool);
}
}
return tools;
}