Skip to content

Commit f7de523

Browse files
vincentkocsasan1200
andcommitted
fix(models): reuse prepared plugin metadata
Carry lifecycle-owned manifest, discovery, and provider owner facts through model normalization instead of rescanning plugin metadata per model. Co-authored-by: Sasan Sotoodehfar <[email protected]>
1 parent 02419ed commit f7de523

11 files changed

Lines changed: 243 additions & 20 deletions

‎src/agents/agent-model-discovery.ts‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from "node:path";
33
import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
44
import type { OpenClawConfig } from "../config/types.openclaw.js";
55
import type { Model } from "../llm/types.js";
6+
import type { PluginMetadataSnapshotOwnerMaps } from "../plugins/plugin-metadata-snapshot.types.js";
67
import { normalizeModelCompat } from "../plugins/provider-model-compat.js";
78
import {
89
applyProviderResolvedTransportWithPlugin,
@@ -44,6 +45,10 @@ type DiscoverModelsOptions = {
4445
normalizeModels?: boolean;
4546
};
4647

48+
type NormalizeDiscoveredModelOptions = Pick<DiscoverModelsOptions, "config" | "workspaceDir"> & {
49+
providerMetadataOwners?: PluginMetadataSnapshotOwnerMaps;
50+
};
51+
4752
type DiscoverCapturedModelsOptions = Omit<
4853
DiscoverModelsOptions,
4954
"modelsJsonContents" | "normalizeModels" | "pluginCatalogs"
@@ -56,7 +61,7 @@ type DiscoverCapturedModelsOptions = Omit<
5661
export function normalizeDiscoveredAgentModel<T>(
5762
value: T,
5863
agentDir: string,
59-
options?: Pick<DiscoverModelsOptions, "config" | "workspaceDir">,
64+
options?: NormalizeDiscoveredModelOptions,
6065
): T {
6166
if (!isRecord(value)) {
6267
return value;
@@ -106,7 +111,7 @@ export function normalizeDiscoveredAgentModel<T>(
106111
) {
107112
return value;
108113
}
109-
return normalizeModelCompat(transportNormalized as Model) as T;
114+
return normalizeModelCompat(transportNormalized as Model, options?.providerMetadataOwners) as T;
110115
}
111116

112117
function createOpenClawModelRegistry(
@@ -151,7 +156,12 @@ function createOpenClawModelRegistry(
151156
if (!agentDir) {
152157
throw new Error("agent directory is required for model normalization");
153158
}
154-
return normalizeDiscoveredAgentModel(entry, agentDir, options);
159+
return normalizeDiscoveredAgentModel(entry, agentDir, {
160+
...options,
161+
...(pluginMetadataSnapshot?.owners
162+
? { providerMetadataOwners: pluginMetadataSnapshot.owners }
163+
: {}),
164+
});
155165
};
156166

157167
registry.getAll = () => {

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import type { PluginMetadataSnapshotOwnerMaps } from "../plugins/plugin-metadata-snapshot.types.js";
23

34
const mocks = vi.hoisted(() => {
45
class OwnerNotPublishedError extends Error {}
@@ -53,6 +54,9 @@ function createSnapshot(
5354
fork: vi.fn(),
5455
getAll: vi.fn(() => models),
5556
getAvailable: vi.fn(() => models),
57+
getProviderMetadataOwners: vi.fn<() => PluginMetadataSnapshotOwnerMaps | undefined>(
58+
() => undefined,
59+
),
5660
find: vi.fn((provider: string, id: string) =>
5761
models.find((model) => model.provider === provider && model.id === id),
5862
),
@@ -167,6 +171,31 @@ describe("prepared agent model registry", () => {
167171
expect(rawFind).toHaveBeenCalledWith("openai", "gpt-test");
168172
});
169173

174+
it("normalizes with the registry's exact plugin metadata generation", async () => {
175+
const { registry, snapshot } = createSnapshot();
176+
const providerMetadataOwners = {
177+
channels: new Map(),
178+
channelConfigs: new Map(),
179+
providers: new Map(),
180+
modelCatalogProviders: new Map(),
181+
cliBackends: new Map(),
182+
setupProviders: new Map(),
183+
commandAliases: new Map(),
184+
contracts: new Map(),
185+
};
186+
registry.getProviderMetadataOwners.mockReturnValue(providerMetadataOwners);
187+
mocks.prepareSnapshot.mockResolvedValue(snapshot);
188+
189+
const loaded = await loadPreparedAgentModelRegistry({});
190+
loaded.registry.getAll();
191+
192+
expect(mocks.normalizeModel).toHaveBeenCalledWith(
193+
expect.objectContaining({ id: "gpt-test" }),
194+
"/agents/main",
195+
expect.objectContaining({ providerMetadataOwners }),
196+
);
197+
});
198+
170199
it("prepares a distinct credential-free lifecycle owner", async () => {
171200
const { snapshot } = createSnapshot();
172201
mocks.prepareSnapshot.mockRejectedValue(new mocks.OwnerNotPublishedError());

‎src/agents/prepared-model-registry.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,12 @@ function createRegistryView(params: {
4848
const matchesProviderFilter = (entry: Model) =>
4949
!providerFilter || normalizeProviderId(entry.provider) === providerFilter;
5050
const shouldNormalize = params.normalizeModels !== false;
51+
const providerMetadataOwners = registry.getProviderMetadataOwners();
5152
const normalizeEntry = (entry: Model) =>
5253
shouldNormalize
5354
? normalizeDiscoveredAgentModel(entry, params.agentDir, {
5455
config: params.config,
56+
...(providerMetadataOwners ? { providerMetadataOwners } : {}),
5557
...(params.workspaceDir ? { workspaceDir: params.workspaceDir } : {}),
5658
})
5759
: entry;

‎src/agents/provider-attribution.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,7 @@ vi.mock("../plugins/plugin-metadata-snapshot.js", () => ({
165165
loadPluginMetadataSnapshot,
166166
}));
167167

168+
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
168169
import {
169170
resolveProviderEndpoint,
170171
resolveProviderRequestCapabilities,
@@ -206,6 +207,7 @@ describe("provider attribution", () => {
206207
providerMetadataState.pluginIdScoped = false;
207208
providerMetadataState.snapshot = undefined;
208209
loadPluginMetadataSnapshot.mockClear();
210+
clearPluginMetadataLifecycleCaches();
209211
});
210212

211213
it("uses provider facts from the replacement plugin snapshot after reload", () => {
@@ -287,6 +289,20 @@ describe("provider attribution", () => {
287289
expect(loadPluginMetadataSnapshot).not.toHaveBeenCalled();
288290
});
289291

292+
it("scans plugin metadata once when falling back without a lifecycle snapshot", () => {
293+
providerMetadataState.pluginIdScoped = true;
294+
providerMetadataState.snapshot = undefined;
295+
296+
for (let index = 0; index < 10; index += 1) {
297+
resolveProviderRequestPolicy({ provider: "fallback-provider" });
298+
}
299+
expect(loadPluginMetadataSnapshot).toHaveBeenCalledTimes(1);
300+
301+
clearPluginMetadataLifecycleCaches();
302+
resolveProviderRequestPolicy({ provider: "fallback-provider" });
303+
expect(loadPluginMetadataSnapshot).toHaveBeenCalledTimes(2);
304+
});
305+
290306
it("uses explicitly prepared provider facts without reading process metadata", () => {
291307
providerMetadataState.pluginIdScoped = true;
292308
providerMetadataState.snapshot = undefined;

‎src/agents/provider-attribution.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import type {
88
PluginManifestProviderEndpoint,
99
PluginManifestProviderRequestProvider,
1010
} from "../plugins/manifest.js";
11+
import { registerPluginMetadataProcessMemoLifecycleClear } from "../plugins/plugin-metadata-lifecycle.js";
1112
import { normalizePluginProviderBaseUrl } from "../plugins/plugin-metadata-provider-facts.js";
1213
import { loadPluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1314
import type { PluginMetadataSnapshotOwnerMaps } from "../plugins/plugin-metadata-snapshot.types.js";
@@ -179,6 +180,28 @@ type ProviderMetadataOwners = {
179180
providerRequests: ReadonlyMap<string, PluginManifestProviderRequestProvider>;
180181
};
181182

183+
let fallbackProviderMetadataOwnersMemo: ProviderMetadataOwners | undefined;
184+
185+
function clearFallbackProviderMetadataOwnersMemo(): void {
186+
fallbackProviderMetadataOwnersMemo = undefined;
187+
}
188+
189+
// This input-free fallback is process-stable until plugin metadata lifecycle reset.
190+
// Without the memo, model catalog normalization rescans every manifest per model.
191+
registerPluginMetadataProcessMemoLifecycleClear(clearFallbackProviderMetadataOwnersMemo);
192+
193+
function resolveFallbackProviderMetadataOwners(): ProviderMetadataOwners {
194+
if (fallbackProviderMetadataOwnersMemo) {
195+
return fallbackProviderMetadataOwnersMemo;
196+
}
197+
const fallback = loadPluginMetadataSnapshot({ config: {} }).owners;
198+
fallbackProviderMetadataOwnersMemo = {
199+
providerEndpoints: fallback.providerEndpoints ?? [],
200+
providerRequests: fallback.providerRequests ?? new Map(),
201+
};
202+
return fallbackProviderMetadataOwnersMemo;
203+
}
204+
182205
function resolveProviderMetadataOwners(
183206
prepared?: PluginMetadataSnapshotOwnerMaps,
184207
): ProviderMetadataOwners {
@@ -197,11 +220,7 @@ function resolveProviderMetadataOwners(
197220
providerRequests: current.owners?.providerRequests ?? new Map(),
198221
};
199222
}
200-
const fallback = loadPluginMetadataSnapshot({ config: {} }).owners;
201-
return {
202-
providerEndpoints: fallback.providerEndpoints ?? [],
203-
providerRequests: fallback.providerRequests ?? new Map(),
204-
};
223+
return resolveFallbackProviderMetadataOwners();
205224
}
206225

207226
function resolveManifestProviderRequest(params: {

‎src/plugins/activation-context.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import {
77
import type { OpenClawConfig } from "../config/types.openclaw.js";
88
import { setCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot.js";
99
import { clearCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-state.js";
10+
import type { PluginDiscoveryResult } from "./discovery.js";
1011

1112
const applyPluginAutoEnableMock = vi.hoisted(() =>
1213
vi.fn((params: { config?: OpenClawConfig }) => ({
@@ -57,4 +58,42 @@ describe("resolveBundledPluginCompatibleActivationInputs", () => {
5758
manifestRegistry,
5859
});
5960
});
61+
62+
it("uses the caller's exact metadata generation across lifecycle replacement", () => {
63+
const firstManifestRegistry = makeRegistry([
64+
{ id: "first", channels: [], providers: ["first"] },
65+
]);
66+
const secondManifestRegistry = makeRegistry([
67+
{ id: "second", channels: [], providers: ["second"] },
68+
]);
69+
const firstDiscovery = { plugins: [], diagnostics: [] } as unknown as PluginDiscoveryResult;
70+
const secondDiscovery = { plugins: [], diagnostics: [] } as unknown as PluginDiscoveryResult;
71+
72+
for (const [manifestRegistry, discovery] of [
73+
[firstManifestRegistry, firstDiscovery],
74+
[secondManifestRegistry, secondDiscovery],
75+
] as const) {
76+
resolveBundledPluginCompatibleActivationInputs({
77+
rawConfig: { plugins: { allow: [manifestRegistry.plugins[0]!.id] } },
78+
manifestRegistry,
79+
discovery,
80+
applyAutoEnable: true,
81+
compatMode: {},
82+
resolveCompatPluginIds: () => [],
83+
});
84+
}
85+
86+
expect(applyPluginAutoEnableMock).toHaveBeenNthCalledWith(1, {
87+
config: { plugins: { allow: ["first"] } },
88+
env: process.env,
89+
manifestRegistry: firstManifestRegistry,
90+
discovery: firstDiscovery,
91+
});
92+
expect(applyPluginAutoEnableMock).toHaveBeenNthCalledWith(2, {
93+
config: { plugins: { allow: ["second"] } },
94+
env: process.env,
95+
manifestRegistry: secondManifestRegistry,
96+
discovery: secondDiscovery,
97+
});
98+
});
6099
});

‎src/plugins/activation-context.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
} from "./config-state.js";
1414
import { getCurrentPluginMetadataSnapshot } from "./current-plugin-metadata-snapshot.js";
1515
import type { PluginDiscoveryResult } from "./discovery.js";
16+
import type { PluginManifestRegistry } from "./manifest-registry.js";
1617

1718
type PluginActivationCompatConfig = {
1819
enablementPluginIds?: readonly string[];
@@ -58,6 +59,7 @@ type BundledPluginCompatibleActivationParams = {
5859
onlyPluginIds?: readonly string[];
5960
}) => string[];
6061
discovery?: PluginDiscoveryResult;
62+
manifestRegistry?: PluginManifestRegistry;
6163
};
6264

6365
export function withActivatedPluginIds(params: {
@@ -147,15 +149,18 @@ function applyPluginAutoEnableForActivation(params: {
147149
env: NodeJS.ProcessEnv;
148150
workspaceDir?: string;
149151
discovery?: PluginDiscoveryResult;
152+
manifestRegistry?: PluginManifestRegistry;
150153
}) {
151-
const currentSnapshot = getCurrentPluginMetadataSnapshot({
152-
config: params.config,
153-
env: params.env,
154-
workspaceDir: params.workspaceDir,
155-
allowWorkspaceScopedSnapshot: true,
156-
});
154+
const currentSnapshot = params.manifestRegistry
155+
? undefined
156+
: getCurrentPluginMetadataSnapshot({
157+
config: params.config,
158+
env: params.env,
159+
workspaceDir: params.workspaceDir,
160+
allowWorkspaceScopedSnapshot: true,
161+
});
157162
const defaultDiscoverySnapshot =
158-
normalizePluginsConfig(params.config.plugins).loadPaths.length === 0
163+
!params.manifestRegistry && normalizePluginsConfig(params.config.plugins).loadPaths.length === 0
159164
? getCurrentPluginMetadataSnapshot({
160165
env: params.env,
161166
workspaceDir: params.workspaceDir,
@@ -164,12 +169,15 @@ function applyPluginAutoEnableForActivation(params: {
164169
})
165170
: undefined;
166171
const currentManifestRegistry =
167-
currentSnapshot?.manifestRegistry ?? defaultDiscoverySnapshot?.manifestRegistry;
172+
params.manifestRegistry ??
173+
currentSnapshot?.manifestRegistry ??
174+
defaultDiscoverySnapshot?.manifestRegistry;
168175
return applyPluginAutoEnable({
169176
config: params.config,
170177
env: params.env,
171178
manifestRegistry: currentManifestRegistry,
172-
discovery: params.discovery,
179+
discovery:
180+
params.discovery ?? currentSnapshot?.discovery ?? defaultDiscoverySnapshot?.discovery,
173181
});
174182
}
175183

@@ -181,6 +189,7 @@ function resolvePluginActivationSnapshot(params: {
181189
workspaceDir?: string;
182190
applyAutoEnable?: boolean;
183191
discovery?: PluginDiscoveryResult;
192+
manifestRegistry?: PluginManifestRegistry;
184193
}): PluginActivationInputs {
185194
const env = params.env ?? process.env;
186195
const rawConfig = params.rawConfig ?? params.resolvedConfig;
@@ -193,6 +202,7 @@ function resolvePluginActivationSnapshot(params: {
193202
env,
194203
workspaceDir: params.workspaceDir,
195204
discovery: params.discovery,
205+
manifestRegistry: params.manifestRegistry,
196206
});
197207
resolvedConfig = autoEnabled.config;
198208
autoEnabledReasons = autoEnabled.autoEnabledReasons;
@@ -219,6 +229,7 @@ function resolvePluginActivationInputs(params: {
219229
compat?: PluginActivationCompatConfig;
220230
applyAutoEnable?: boolean;
221231
discovery?: PluginDiscoveryResult;
232+
manifestRegistry?: PluginManifestRegistry;
222233
}): PluginActivationInputs {
223234
const env = params.env ?? process.env;
224235
const snapshot = resolvePluginActivationSnapshot({
@@ -229,6 +240,7 @@ function resolvePluginActivationInputs(params: {
229240
workspaceDir: params.workspaceDir,
230241
applyAutoEnable: params.applyAutoEnable,
231242
discovery: params.discovery,
243+
manifestRegistry: params.manifestRegistry,
232244
});
233245
const config = applyPluginCompatibilityOverrides({
234246
config: snapshot.config,
@@ -257,6 +269,7 @@ export function resolveBundledPluginCompatibleActivationInputs(
257269
workspaceDir: params.workspaceDir,
258270
applyAutoEnable: params.applyAutoEnable,
259271
discovery: params.discovery,
272+
manifestRegistry: params.manifestRegistry,
260273
});
261274
const shouldResolveCompatPluginIds = shouldResolveBundledCompatPluginIds({
262275
compatMode: params.compatMode,
@@ -280,6 +293,7 @@ export function resolveBundledPluginCompatibleActivationInputs(
280293
compatPluginIds,
281294
}),
282295
discovery: params.discovery,
296+
manifestRegistry: params.manifestRegistry,
283297
});
284298

285299
return {
@@ -302,6 +316,7 @@ export function resolveBundledPluginCompatibleLoadValues(
302316
env,
303317
workspaceDir: params.workspaceDir,
304318
discovery: params.discovery,
319+
manifestRegistry: params.manifestRegistry,
305320
});
306321
resolvedConfig = autoEnabled.config;
307322
autoEnabledReasons = autoEnabled.autoEnabledReasons;

‎src/plugins/plugin-metadata-snapshot.types.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,10 @@ export type PluginMetadataSnapshot = {
6363
discovery?: PluginDiscoveryResult;
6464
};
6565

66-
export type PluginMetadataRegistryView = Pick<PluginMetadataSnapshot, "index" | "manifestRegistry">;
66+
export type PluginMetadataRegistryView = Pick<
67+
PluginMetadataSnapshot,
68+
"index" | "manifestRegistry" | "discovery"
69+
>;
6770

6871
export type PluginMetadataManifestView = Pick<PluginMetadataSnapshot, "index" | "plugins">;
6972

0 commit comments

Comments
 (0)