Skip to content

Commit a6e0002

Browse files
authored
perf(agents): carry prepared plugin load context into per-attempt tool construction (#118398)
* perf(plugins): carry prepared load context into tools * fix(agents): keep prepared context setter private * fix(agents): reuse prepared plugin metadata context * refactor(agents): relocate prepared plugin context wiring * test(agents): cover prepared plugin context owner path * refactor(plugins): remove duplicate metadata type exports
1 parent 978a449 commit a6e0002

16 files changed

Lines changed: 361 additions & 87 deletions

‎src/agents/agent-tools.create-openclaw-coding-tools.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1059,6 +1059,7 @@ describe("createOpenClawCodingTools", () => {
10591059
const resolvePluginToolsSpy = vi
10601060
.spyOn(openClawPluginTools, "resolveOpenClawPluginToolsForOptions")
10611061
.mockReturnValue([]);
1062+
const preparedModelRuntime = { metadataSnapshot: {} } as never;
10621063

10631064
try {
10641065
createOpenClawCodingTools({
@@ -1069,6 +1070,7 @@ describe("createOpenClawCodingTools", () => {
10691070
modelId: "openrouter/auto",
10701071
nativeChannelId: "oc_native_chat",
10711072
clientCaps: ["inline-widgets"],
1073+
preparedModelRuntime,
10721074
toolConstructionPlan: {
10731075
includeBaseCodingTools: false,
10741076
includeShellTools: false,
@@ -1085,6 +1087,7 @@ describe("createOpenClawCodingTools", () => {
10851087
expect(pluginToolOptions?.modelId).toBe("openrouter/auto");
10861088
expect(pluginToolOptions?.nativeChannelId).toBe("oc_native_chat");
10871089
expect(pluginToolOptions?.clientCaps).toEqual(["inline-widgets"]);
1090+
expect(pluginToolOptions?.preparedModelRuntime).toBe(preparedModelRuntime);
10881091
} finally {
10891092
resolvePluginToolsSpy.mockRestore();
10901093
}

‎src/agents/agent-tools.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -887,6 +887,7 @@ function createOpenClawCodingToolsInternal(options?: OpenClawCodingToolsOptions)
887887
agentThreadId: options?.messageThreadId,
888888
nativeChannelId: options?.nativeChannelId,
889889
agentDir: options?.agentDir,
890+
preparedModelRuntime: options?.preparedModelRuntime,
890891
workspaceDir: workspaceRoot,
891892
config: options?.config,
892893
fsPolicy,

‎src/agents/openclaw-plugin-tools.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,14 @@ import {
1919
type OpenClawPluginToolOptions,
2020
} from "./openclaw-tools.plugin-context.js";
2121
import { applyPluginToolDeliveryDefaults } from "./plugin-tool-delivery-defaults.js";
22+
import { getPreparedPluginRuntimeLoadContext } from "./prepared-model-runtime.plugin-context.js";
23+
import type { PreparedModelRuntimeSnapshot } from "./prepared-model-runtime.types.js";
2224
import { resolveAgentRuntimeToolConfig } from "./tool-runtime-config.js";
2325
import type { AnyAgentTool } from "./tools/common.js";
2426
import { hasProviderAuthForTool } from "./tools/model-config.helpers.js";
2527

2628
type ResolveOpenClawPluginToolsOptions = OpenClawPluginToolOptions & {
29+
preparedModelRuntime?: PreparedModelRuntimeSnapshot;
2730
pluginToolAllowlist?: string[];
2831
pluginToolDenylist?: string[];
2932
currentThreadTs?: string;
@@ -134,6 +137,7 @@ export function resolveOpenClawPluginToolsForOptions(params: {
134137
}
135138
: undefined;
136139
const existingToolNames = new Set(params.existingToolNames ?? []);
140+
const preparedModelRuntime = params.options?.preparedModelRuntime;
137141
const pluginTools = resolvePluginTools({
138142
...pluginToolInputs,
139143
context: {
@@ -147,6 +151,15 @@ export function resolveOpenClawPluginToolsForOptions(params: {
147151
toolDenylist: params.options?.pluginToolDenylist,
148152
allowGatewaySubagentBinding: params.options?.allowGatewaySubagentBinding,
149153
...(hasAuthForProvider ? { hasAuthForProvider } : {}),
154+
...(preparedModelRuntime
155+
? {
156+
preparedRuntime: {
157+
loadContext: getPreparedPluginRuntimeLoadContext(preparedModelRuntime.pluginRegistry),
158+
metadataSnapshot: preparedModelRuntime.metadataSnapshot,
159+
registry: preparedModelRuntime.pluginRegistry,
160+
},
161+
}
162+
: {}),
150163
});
151164
for (const tool of pluginTools) {
152165
existingToolNames.add(tool.name);

‎src/agents/openclaw-tools.browser-plugin.integration.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,19 @@ import path from "node:path";
44
import { afterEach, describe, expect, it, vi } from "vitest";
55
import type { OpenClawConfig } from "../config/config.js";
66
import { resetConfigRuntimeState, setRuntimeConfigSnapshot } from "../config/config.js";
7+
import {
8+
createPluginMetadataSnapshot,
9+
makeRegistry,
10+
} from "../config/plugin-auto-enable.test-helpers.js";
11+
import * as pluginMetadata from "../plugins/plugin-metadata-snapshot.js";
712
import { activateSecretsRuntimeSnapshot, clearSecretsRuntimeSnapshot } from "../secrets/runtime.js";
813
import { getRuntimeAuthProfileStoreCredentialsRevision } from "./auth-profiles/runtime-snapshots.js";
914
import { resolveOpenClawPluginToolsForOptions } from "./openclaw-plugin-tools.js";
1015
import { createOpenClawTools } from "./openclaw-tools.js";
16+
import {
17+
getPreparedPluginRuntimeLoadContext,
18+
prepareOwnedPluginLoadContext,
19+
} from "./prepared-model-runtime.plugin-context.js";
1120

1221
const hoisted = vi.hoisted(() => ({
1322
resolvePluginTools: vi.fn(),
@@ -156,6 +165,62 @@ describe("createOpenClawTools browser plugin integration", () => {
156165
expect(firstResolvePluginToolsParams().allowGatewaySubagentBinding).toBe(true);
157166
});
158167

168+
it("forwards lifecycle-prepared plugin facts to plugin resolution", () => {
169+
hoisted.resolvePluginTools.mockReturnValue([]);
170+
const config = { plugins: { enabled: true } } as OpenClawConfig;
171+
const pluginRegistry = { tools: [] } as never;
172+
const metadataSnapshot = createPluginMetadataSnapshot({
173+
config,
174+
manifestRegistry: makeRegistry([]),
175+
workspaceDir: "/tmp",
176+
});
177+
const resolveMetadata = vi
178+
.spyOn(pluginMetadata, "resolvePluginMetadataSnapshot")
179+
.mockReturnValue(metadataSnapshot);
180+
try {
181+
expect(
182+
prepareOwnedPluginLoadContext(
183+
{ agentDir: "/tmp/agent", config, workspaceDir: "/tmp" },
184+
process.env,
185+
pluginRegistry,
186+
),
187+
).toBe(metadataSnapshot);
188+
} finally {
189+
resolveMetadata.mockRestore();
190+
}
191+
const loadContext = getPreparedPluginRuntimeLoadContext(pluginRegistry);
192+
if (!loadContext) {
193+
throw new Error("expected prepared plugin load context");
194+
}
195+
196+
resolveOpenClawPluginToolsForOptions({
197+
options: {
198+
config,
199+
workspaceDir: "/tmp",
200+
preparedModelRuntime: {
201+
agentDir: "/tmp/agent",
202+
workspaceDir: "/tmp",
203+
activeProjectKeys: [],
204+
config,
205+
metadataSnapshot,
206+
pluginRegistry,
207+
allowGatewaySubagentBinding: false,
208+
modelCatalog: { entries: [], routeVariants: [] },
209+
configuredRuntimeModels: [],
210+
inlineProviderModels: [],
211+
createStores: vi.fn(),
212+
},
213+
},
214+
resolvedConfig: config,
215+
});
216+
217+
expect(firstResolvePluginToolsParams().preparedRuntime).toEqual({
218+
loadContext,
219+
metadataSnapshot,
220+
registry: pluginRegistry,
221+
});
222+
});
223+
159224
it("forwards auth profile helpers to plugin resolution and context", async () => {
160225
let capturedParams:
161226
| {

‎src/agents/prepared-model-runtime.facts.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import type { PreparedMessageToolCatalog } from "../channels/plugins/message-act
88
import { hashRuntimeConfigValue } from "../config/runtime-snapshot.js";
99
import { sha256Base64Url } from "../infra/crypto-digest.js";
1010
import { prepareMediaCapabilityProviders } from "../plugins/capability-provider-runtime.js";
11-
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1211
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
1312
import {
1413
getPreparedMessageToolCatalog,
@@ -53,6 +52,7 @@ import {
5352
toStaticCatalogEntry,
5453
type PreparedConfiguredRuntimeModel,
5554
} from "./prepared-model-runtime.configured.js";
55+
import { prepareOwnedPluginLoadContext } from "./prepared-model-runtime.plugin-context.js";
5656
import type {
5757
PreparedModelRuntimeBuildStats,
5858
PreparedModelRuntimeCatalogMode,
@@ -228,6 +228,7 @@ export async function prepareWorkspaceBuildGroup(
228228
const runtimePluginRegistry = !input.readOnly
229229
? loadAgentRuntimePluginRegistryHandle({
230230
config: input.config,
231+
env,
231232
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
232233
...(input.allowGatewaySubagentBinding ? { allowGatewaySubagentBinding: true } : {}),
233234
selections: input.runtimePluginSelections,
@@ -236,11 +237,7 @@ export async function prepareWorkspaceBuildGroup(
236237
const runtimePluginMs = performance.now() - runtimePluginStartedAt;
237238
return await withPluginRuntimeRegistryScope(runtimePluginRegistry, async () => {
238239
const pluginMetadataStartedAt = performance.now();
239-
const pluginMetadataSnapshot = resolvePluginMetadataSnapshot({
240-
config: input.config,
241-
env,
242-
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
243-
});
240+
const pluginMetadataSnapshot = prepareOwnedPluginLoadContext(input, env, runtimePluginRegistry);
244241
const pluginMetadataMs = performance.now() - pluginMetadataStartedAt;
245242
const matchesStaticModelId = createStaticModelIdMatcher({
246243
manifestPlugins: pluginMetadataSnapshot.plugins,
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import type { PluginDiscoveryResult } from "../plugins/discovery.js";
2+
import { extractPluginInstallRecordsFromInstalledPluginIndex } from "../plugins/installed-plugin-index-install-records.js";
3+
import { resolvePluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
4+
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.types.js";
5+
import type { PluginRegistry } from "../plugins/registry-types.js";
6+
import {
7+
resolvePluginRuntimeLoadContext,
8+
type PluginRuntimeLoadContext,
9+
} from "../plugins/runtime/load-context.js";
10+
import type { PreparedModelRuntimeInput } from "./prepared-model-runtime.types.js";
11+
12+
const preparedPluginRuntimeLoadContext = Symbol("preparedPluginRuntimeLoadContext");
13+
const emptyPluginDiscovery: PluginDiscoveryResult = { candidates: [], diagnostics: [] };
14+
15+
type PreparedPluginRegistry = PluginRegistry & {
16+
[preparedPluginRuntimeLoadContext]?: PluginRuntimeLoadContext;
17+
};
18+
19+
function setPreparedPluginRuntimeLoadContext(
20+
registry: PluginRegistry,
21+
context: PluginRuntimeLoadContext,
22+
): void {
23+
(registry as PreparedPluginRegistry)[preparedPluginRuntimeLoadContext] = context;
24+
}
25+
26+
function preparePluginLoadContext(
27+
input: PreparedModelRuntimeInput,
28+
env: NodeJS.ProcessEnv,
29+
registry: PluginRegistry | undefined,
30+
metadataSnapshot: PluginMetadataSnapshot,
31+
): PluginRuntimeLoadContext & { metadataSnapshot: PluginMetadataSnapshot } {
32+
const { config, workspaceDir } = input;
33+
// The prepared owner already resolved metadata for this exact config/env/workspace tuple.
34+
// Missing discovery facts stay empty here instead of reopening cold channel discovery.
35+
const preparedMetadataSnapshot = metadataSnapshot.discovery
36+
? metadataSnapshot
37+
: { ...metadataSnapshot, discovery: emptyPluginDiscovery };
38+
const context = {
39+
...resolvePluginRuntimeLoadContext({
40+
config,
41+
env,
42+
workspaceDir,
43+
metadataSnapshot: preparedMetadataSnapshot,
44+
manifestRegistry: metadataSnapshot.manifestRegistry,
45+
}),
46+
metadataSnapshot,
47+
installRecords: extractPluginInstallRecordsFromInstalledPluginIndex(metadataSnapshot.index),
48+
};
49+
if (registry) {
50+
// The prepared registry is the lifecycle-owned carrier; standalone callers keep the cold path.
51+
setPreparedPluginRuntimeLoadContext(registry, context);
52+
}
53+
return context;
54+
}
55+
56+
/** Resolves and attaches the plugin facts owned by one prepared workspace generation. */
57+
export function prepareOwnedPluginLoadContext(
58+
input: PreparedModelRuntimeInput,
59+
env: NodeJS.ProcessEnv,
60+
registry: PluginRegistry | undefined,
61+
): PluginMetadataSnapshot {
62+
const metadataSnapshot = resolvePluginMetadataSnapshot({
63+
config: input.config,
64+
env,
65+
...(input.workspaceDir ? { workspaceDir: input.workspaceDir } : {}),
66+
});
67+
preparePluginLoadContext(input, env, registry, metadataSnapshot);
68+
return metadataSnapshot;
69+
}
70+
71+
/** Reads plugin facts carried by a lifecycle-owned prepared runtime snapshot. */
72+
export const getPreparedPluginRuntimeLoadContext = (
73+
registry: PluginRegistry | undefined,
74+
): PluginRuntimeLoadContext | undefined =>
75+
(registry as PreparedPluginRegistry | undefined)?.[preparedPluginRuntimeLoadContext];

‎src/agents/prepared-model-runtime.startup-static.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ const mocks = vi.hoisted(() => {
101101
});
102102

103103
vi.mock("../plugins/plugin-metadata-snapshot.js", () => ({
104+
isPluginMetadataSnapshotCompatible: () => true,
104105
loadPluginMetadataSnapshot: () => mocks.metadataSnapshot,
105106
resolvePluginMetadataSnapshot: mocks.resolvePluginMetadataSnapshot,
106107
}));

‎src/agents/prepared-model-runtime.test.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
rejectPendingPreparedModelRuntimeReplacement,
1515
refreshPreparedModelRuntimeSnapshots,
1616
} from "./prepared-model-runtime.js";
17+
import { getPreparedPluginRuntimeLoadContext } from "./prepared-model-runtime.plugin-context.js";
1718
import {
1819
getPreparedModelRuntimeMocks,
1920
resetPreparedModelRuntimeHarness,
@@ -127,6 +128,7 @@ describe("prepared model runtime snapshots", () => {
127128

128129
expect(mocks.loadAgentRuntimePluginRegistryHandle).toHaveBeenCalledWith({
129130
config: {},
131+
env: process.env,
130132
workspaceDir: "/tmp/prepared-model-runtime-plugin-workspace",
131133
selections: undefined,
132134
});
@@ -138,14 +140,20 @@ describe("prepared model runtime snapshots", () => {
138140

139141
it("uses an explicit lifecycle environment for catalog and auth discovery", async () => {
140142
const env = { NVIDIA_API_KEY: "test-nvidia-api-key" };
141-
await publishPreparedModelRuntimeSnapshot({
142-
config: {},
143+
const config = {};
144+
const snapshot = await publishPreparedModelRuntimeSnapshot({
145+
config,
143146
agentDir: "/tmp/prepared-model-runtime-explicit-env",
144147
env,
145148
});
146149

150+
expect(getPreparedPluginRuntimeLoadContext(snapshot.pluginRegistry)).toMatchObject({
151+
rawConfig: config,
152+
env,
153+
});
154+
147155
expect(mocks.ensureOpenClawModelsJson).toHaveBeenCalledWith(
148-
{},
156+
config,
149157
"/tmp/prepared-model-runtime-explicit-env",
150158
expect.objectContaining({ env }),
151159
);

‎src/agents/runtime-plugins.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,16 +33,23 @@ describe("agent runtime plugin registries", () => {
3333

3434
it("returns a non-activating handle for a prepared runtime", () => {
3535
const config = {} as never;
36+
const env = { OPENCLAW_STATE_DIR: "/tmp/openclaw-state" };
3637
const selections = [{ provider: "openai", modelId: "gpt-5.5", runtime: "codex" }];
3738

3839
expect(
3940
loadAgentRuntimePluginRegistryHandle({
4041
config,
42+
env,
4143
workspaceDir: "/tmp/workspace",
4244
allowGatewaySubagentBinding: true,
4345
selections,
4446
}),
4547
).toEqual({ handle: true });
48+
expect(hoisted.getCurrentPluginMetadataSnapshot).toHaveBeenCalledWith({
49+
config,
50+
env,
51+
workspaceDir: "/tmp/workspace",
52+
});
4653
expect(hoisted.resolveAgentRuntimePluginLoadPlan).toHaveBeenCalledWith({
4754
config,
4855
workspaceDir: "/tmp/workspace",
@@ -52,6 +59,7 @@ describe("agent runtime plugin registries", () => {
5259
activate: false,
5360
config,
5461
activationSourceConfig: config,
62+
env,
5563
workspaceDir: "/tmp/workspace",
5664
runtimeOptions: { allowGatewaySubagentBinding: true },
5765
});

‎src/agents/runtime-plugins.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,12 @@ type StartupScopedPluginSnapshot = NonNullable<
2020

2121
function resolveStartupPluginIdsFromCurrentSnapshot(params: {
2222
config?: OpenClawConfig;
23+
env?: NodeJS.ProcessEnv;
2324
workspaceDir?: string;
2425
}): string[] | undefined {
2526
const snapshot = getCurrentPluginMetadataSnapshot({
2627
config: params.config,
28+
env: params.env,
2729
workspaceDir: params.workspaceDir,
2830
}) as StartupScopedPluginSnapshot | undefined;
2931
const pluginIds = snapshot?.startup?.pluginIds;
@@ -35,6 +37,7 @@ function resolveStartupPluginIdsFromCurrentSnapshot(params: {
3537

3638
type AgentRuntimePluginRegistryParams = {
3739
config?: OpenClawConfig;
40+
env?: NodeJS.ProcessEnv;
3841
workspaceDir?: string | null;
3942
allowGatewaySubagentBinding?: boolean;
4043
selections?: readonly AgentHarnessPluginSelection[];
@@ -51,6 +54,7 @@ function resolveAgentRuntimePluginRegistryLoad(params: AgentRuntimePluginRegistr
5154
loadOptions: {
5255
config: params.config,
5356
activationSourceConfig: params.config,
57+
...(params.env ? { env: params.env } : {}),
5458
workspaceDir,
5559
onlyPluginIds: [],
5660
runtimeOptions: params.allowGatewaySubagentBinding
@@ -61,6 +65,7 @@ function resolveAgentRuntimePluginRegistryLoad(params: AgentRuntimePluginRegistr
6165
}
6266
const startupPluginIds = resolveStartupPluginIdsFromCurrentSnapshot({
6367
config: params.config,
68+
env: params.env,
6469
workspaceDir,
6570
});
6671
const plan = resolveAgentRuntimePluginLoadPlan({
@@ -81,6 +86,7 @@ function resolveAgentRuntimePluginRegistryLoad(params: AgentRuntimePluginRegistr
8186
loadOptions: {
8287
config: plan.config,
8388
...(plan.config ? { activationSourceConfig: plan.config } : {}),
89+
...(params.env ? { env: params.env } : {}),
8490
workspaceDir,
8591
...(startupPluginIds === undefined || plan.pluginIds === undefined
8692
? {}

0 commit comments

Comments
 (0)