Skip to content

Commit aa16e62

Browse files
authored
fix: agent-specific model selection repeatedly rescans every plugin (#129510)
* fix(plugins): reuse metadata after selected-agent model lookups * fix(plugins): keep metadata adoption in its canonical owner * fix(plugins): publish metadata through lifecycle-owned runtime bridge * fix: avoid plugin discovery for default-provider aliases * test(plugins): isolate metadata lifecycle state * fix(agents): honor explicit plugin metadata bypass
1 parent c9acb95 commit aa16e62

9 files changed

Lines changed: 257 additions & 37 deletions

‎src/agents/embedded-agent-runner/model.static-catalog.prepared.test.ts‎

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

1515
vi.mock("../../plugins/current-plugin-metadata-snapshot.js", () => ({
1616
getCurrentPluginMetadataSnapshot: () => undefined,
17+
withPluginMetadataSnapshotScope: (_snapshot: unknown, run: () => unknown) => run(),
1718
}));
1819

1920
vi.mock("../../plugins/manifest-metadata-scan.js", () => ({

‎src/agents/embedded-agent-runner/model.static-catalog.snapshot-cache.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const providerMocks = vi.hoisted(() => ({
1919

2020
vi.mock("../../plugins/current-plugin-metadata-snapshot.js", () => ({
2121
getCurrentPluginMetadataSnapshot: manifestMocks.getCurrentPluginMetadataSnapshot,
22+
withPluginMetadataSnapshotScope: (_snapshot: unknown, run: () => unknown) => run(),
2223
}));
2324

2425
vi.mock("../../plugins/manifest-metadata-scan.js", () => ({

‎src/agents/model-selection-manifest-workspace.test.ts‎

Lines changed: 137 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { OpenClawConfig } from "../config/types.openclaw.js";
55
const loadManifestMetadataSnapshotMock = vi.hoisted(() => vi.fn());
66
const getCurrentPluginMetadataSnapshotMock = vi.hoisted(() => vi.fn());
77
const getActivePluginRegistryWorkspaceDirFromStateMock = vi.hoisted(() => vi.fn());
8+
const normalizeProviderModelIdWithRuntimeMock = vi.hoisted(() => vi.fn());
89

910
vi.mock("../plugins/current-plugin-metadata-snapshot.js", () => ({
1011
getCurrentPluginMetadataSnapshot: getCurrentPluginMetadataSnapshotMock,
@@ -19,7 +20,7 @@ vi.mock("../plugins/runtime-state.js", () => ({
1920
}));
2021

2122
vi.mock("./provider-model-normalization.runtime.js", () => ({
22-
normalizeProviderModelIdWithRuntime: () => undefined,
23+
normalizeProviderModelIdWithRuntime: normalizeProviderModelIdWithRuntimeMock,
2324
}));
2425

2526
describe("configured model manifest workspace scope", () => {
@@ -28,6 +29,7 @@ describe("configured model manifest workspace scope", () => {
2829
loadManifestMetadataSnapshotMock.mockReset();
2930
getCurrentPluginMetadataSnapshotMock.mockReset();
3031
getActivePluginRegistryWorkspaceDirFromStateMock.mockReset();
32+
normalizeProviderModelIdWithRuntimeMock.mockReset();
3133
getCurrentPluginMetadataSnapshotMock.mockReturnValue(undefined);
3234
loadManifestMetadataSnapshotMock.mockReturnValue({
3335
plugins: [
@@ -208,6 +210,140 @@ describe("configured model manifest workspace scope", () => {
208210
expect(loadManifestMetadataSnapshotMock).not.toHaveBeenCalled();
209211
});
210212

213+
it("indexes selected-agent default-provider aliases without cold manifest discovery", async () => {
214+
const { buildModelAliasIndex } = await import("./model-selection-shared.js");
215+
const cfg = {
216+
agents: {
217+
ownership: "explicit",
218+
defaults: { systemAgent: { agentId: "ops" } },
219+
entries: {
220+
ops: {
221+
models: {
222+
"openai/ops": { alias: "Operations" },
223+
},
224+
},
225+
},
226+
},
227+
} as unknown as OpenClawConfig;
228+
229+
const aliases = buildModelAliasIndex({ cfg, defaultProvider: "openai", agentId: "ops" });
230+
231+
expect(aliases.byAlias.get("operations")).toEqual({
232+
alias: "Operations",
233+
ref: { provider: "openai", model: "ops" },
234+
});
235+
expect(aliases.byKey.get("openai/ops")).toEqual(["Operations"]);
236+
expect(loadManifestMetadataSnapshotMock.mock.calls.length).toBe(0);
237+
expect(normalizeProviderModelIdWithRuntimeMock.mock.calls.length).toBe(0);
238+
});
239+
240+
it("resolves selected-agent default-provider aliases without cold manifest discovery", async () => {
241+
const { resolveConfiguredModelRef } = await import("./model-selection-shared.js");
242+
const cfg = {
243+
agents: {
244+
ownership: "explicit",
245+
defaults: { systemAgent: { agentId: "ops" } },
246+
entries: {
247+
ops: {
248+
model: { primary: "Operations" },
249+
models: { "openai/ops": { alias: "Operations" } },
250+
},
251+
},
252+
},
253+
} as unknown as OpenClawConfig;
254+
255+
expect(
256+
resolveConfiguredModelRef({
257+
cfg,
258+
agentId: "ops",
259+
defaultProvider: "openai",
260+
defaultModel: "gpt-5.6-sol",
261+
}),
262+
).toEqual({ provider: "openai", model: "ops" });
263+
expect(loadManifestMetadataSnapshotMock.mock.calls.length).toBe(0);
264+
expect(normalizeProviderModelIdWithRuntimeMock.mock.calls.length).toBe(0);
265+
});
266+
267+
it.each(["current", "supplied"] as const)(
268+
"preserves %s prepared manifest policy for default-provider aliases",
269+
async (source) => {
270+
const manifestPlugins = [
271+
{
272+
modelIdNormalization: {
273+
providers: {
274+
openai: { aliases: { legacy: "normalized" } },
275+
},
276+
},
277+
},
278+
];
279+
if (source === "current") {
280+
getCurrentPluginMetadataSnapshotMock.mockReturnValue({ plugins: manifestPlugins });
281+
}
282+
const { buildModelAliasIndex } = await import("./model-selection-shared.js");
283+
const cfg = {
284+
agents: { defaults: { models: { "openai/legacy": { alias: "Legacy" } } } },
285+
} as unknown as OpenClawConfig;
286+
287+
const aliases = buildModelAliasIndex({
288+
cfg,
289+
defaultProvider: "openai",
290+
...(source === "supplied" ? { manifestPlugins } : {}),
291+
});
292+
293+
expect(aliases.byAlias.get("legacy")?.ref).toEqual({
294+
provider: "openai",
295+
model: "normalized",
296+
});
297+
expect(loadManifestMetadataSnapshotMock.mock.calls.length).toBe(0);
298+
expect(normalizeProviderModelIdWithRuntimeMock.mock.calls.length).toBe(1);
299+
},
300+
);
301+
302+
it("preserves workspace manifest policy for default-provider aliases", async () => {
303+
getActivePluginRegistryWorkspaceDirFromStateMock.mockReturnValue("/workspace/a");
304+
loadManifestMetadataSnapshotMock.mockReturnValue({
305+
plugins: [
306+
{ modelIdNormalization: { providers: { openai: { aliases: { ops: "workspace-ops" } } } } },
307+
],
308+
});
309+
const { buildModelAliasIndex } = await import("./model-selection-shared.js");
310+
const cfg = {
311+
agents: { defaults: { models: { "openai/ops": { alias: "Operations" } } } },
312+
} as unknown as OpenClawConfig;
313+
314+
expect(
315+
buildModelAliasIndex({ cfg, defaultProvider: "openai" }).byAlias.get("operations")?.ref,
316+
).toEqual({ provider: "openai", model: "workspace-ops" });
317+
expect(loadManifestMetadataSnapshotMock.mock.calls.length).toBe(1);
318+
expect(loadManifestMetadataSnapshotMock.mock.calls[0]?.[0]?.workspaceDir).toBe("/workspace/a");
319+
});
320+
321+
it("preserves provider-owned manifest discovery for non-default aliases", async () => {
322+
const { buildModelAliasIndex } = await import("./model-selection-shared.js");
323+
const cfg = {
324+
agents: { defaults: { models: { "custom/ops": { alias: "Operations" } } } },
325+
} as unknown as OpenClawConfig;
326+
327+
expect(
328+
buildModelAliasIndex({ cfg, defaultProvider: "openai" }).byAlias.get("operations")?.ref,
329+
).toEqual({ provider: "custom", model: "workspace-custom/ops" });
330+
expect(loadManifestMetadataSnapshotMock.mock.calls.length).toBe(1);
331+
expect(normalizeProviderModelIdWithRuntimeMock.mock.calls.length).toBe(1);
332+
});
333+
334+
it("preserves manifest discovery for default-provider configured API-owner mappings", async () => {
335+
const { buildModelAliasIndex } = await import("./model-selection-shared.js");
336+
const cfg = {
337+
agents: { defaults: { models: { "openai/ops": { alias: "Operations" } } } },
338+
models: { providers: { openai: { api: "custom-owner", models: [] } } },
339+
} as unknown as OpenClawConfig;
340+
341+
expect(
342+
buildModelAliasIndex({ cfg, defaultProvider: "openai" }).byAlias.get("operations")?.ref,
343+
).toEqual({ provider: "openai", model: "ops" });
344+
expect(loadManifestMetadataSnapshotMock.mock.calls.length).toBe(1);
345+
});
346+
211347
it("does not load manifest metadata for statically resolved primary models", async () => {
212348
const { resolveConfiguredModelRef } = await import("./model-selection-shared.js");
213349
const cases: Array<{ cfg: OpenClawConfig; expected: { provider: string; model: string } }> = [

‎src/agents/model-selection-shared.ts‎

Lines changed: 22 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -164,15 +164,32 @@ function buildEffectiveModelAliases(
164164
if (candidates.length === 0) {
165165
return { aliases: [], disabledKeys: new Set() };
166166
}
167-
const manifestPlugins = params.manifestPluginContext.get();
168167
for (const candidate of candidates) {
168+
const isColdDefaultProviderAlias =
169+
params.allowManifestNormalization !== false &&
170+
hasSlashFormModelRef(candidate.keyRaw) &&
171+
normalizeProviderId(candidate.keyRaw.slice(0, candidate.keyRaw.indexOf("/"))) ===
172+
normalizeProviderId(DEFAULT_PROVIDER) &&
173+
!findExactConfiguredProviderRefParts({ cfg: params.cfg, raw: candidate.keyRaw }) &&
174+
params.manifestPluginContext.peek() === undefined &&
175+
!getActivePluginRegistryWorkspaceDirFromState() &&
176+
!getCurrentPluginMetadataSnapshot({ config: params.cfg, env: process.env });
177+
// The default-provider owner declares no manifest or runtime model normalizer;
178+
// cold alias indexing must not discover every plugin for an identity transform.
179+
const manifestPlugins = isColdDefaultProviderAlias
180+
? undefined
181+
: params.manifestPluginContext.get();
169182
const ref = parseModelRefWithCompatAlias({
170183
cfg: params.cfg,
171184
agentId: params.agentId,
172185
raw: candidate.keyRaw,
173186
defaultProvider: params.defaultProvider,
174-
allowManifestNormalization: params.allowManifestNormalization,
175-
allowPluginNormalization: params.allowPluginNormalization,
187+
allowManifestNormalization: isColdDefaultProviderAlias
188+
? false
189+
: params.allowManifestNormalization,
190+
allowPluginNormalization: isColdDefaultProviderAlias
191+
? false
192+
: params.allowPluginNormalization,
176193
manifestPlugins,
177194
});
178195
if (!ref) {
@@ -840,18 +857,7 @@ export function resolveConfiguredModelRef(
840857
if (profileAliasCandidate) {
841858
// Auth-profile suffixes are not part of alias matching; resolve the alias
842859
// target while preserving the provider/model semantics of the key.
843-
const aliasRef = parseModelRefWithCompatAlias({
844-
cfg: params.cfg,
845-
agentId: params.agentId,
846-
raw: profileAliasCandidate.keyRaw,
847-
defaultProvider: params.defaultProvider,
848-
allowManifestNormalization: params.allowManifestNormalization,
849-
allowPluginNormalization: params.allowPluginNormalization,
850-
manifestPlugins: manifestPluginContext.get(),
851-
});
852-
if (aliasRef) {
853-
return aliasRef;
854-
}
860+
return profileAliasCandidate.ref;
855861
}
856862
const primaryWithoutProfile = modelWithoutProfile || trimmed;
857863
const exactConfiguredPrimary = findExactConfiguredProviderRefParts({
@@ -885,18 +891,7 @@ export function resolveConfiguredModelRef(
885891
}
886892
}
887893
if (aliasCandidate) {
888-
const aliasRef = parseModelRefWithCompatAlias({
889-
cfg: params.cfg,
890-
agentId: params.agentId,
891-
raw: aliasCandidate.keyRaw,
892-
defaultProvider: params.defaultProvider,
893-
allowManifestNormalization: params.allowManifestNormalization,
894-
allowPluginNormalization: params.allowPluginNormalization,
895-
manifestPlugins: manifestPluginContext.get(),
896-
});
897-
if (aliasRef) {
898-
return aliasRef;
899-
}
894+
return aliasCandidate.ref;
900895
}
901896

902897
if (!trimmed.includes("/")) {

‎src/gateway/session-utils.test.ts‎

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
} from "../config/sessions/session-accessor.js";
2020
import { resolveSqliteTargetFromSessionStorePath } from "../config/sessions/session-sqlite-target.js";
2121
import type { CronJob } from "../cron/types.js";
22+
import { clearPluginMetadataLifecycleCaches } from "../plugins/plugin-metadata-lifecycle.js";
2223
import { createEmptyPluginRegistry } from "../plugins/registry-empty.js";
2324
import { resetPluginRuntimeStateForTest, setActivePluginRegistry } from "../plugins/runtime.js";
2425
import { closeOpenClawAgentDatabasesForTest } from "../state/openclaw-agent-db.js";
@@ -309,7 +310,8 @@ describe("gateway session utils", () => {
309310
});
310311

311312
beforeEach(() => {
312-
// Real artifact loading belongs to its owner tests; session projections only need the contract.
313+
// Real metadata/artifact loading belongs to owner tests; projections only need the contract.
314+
clearPluginMetadataLifecycleCaches();
313315
providerArtifactMocks.resolveBundledProviderPolicySurface.mockReset();
314316
providerArtifactMocks.resolveBundledProviderPolicySurface.mockReturnValue(null);
315317
});
@@ -1276,10 +1278,10 @@ describe("gateway session utils", () => {
12761278

12771279
expect(defaults.thinkingLevels?.map((level) => level.id)).toContain("xhigh");
12781280
expect(row.thinkingLevels?.map((level) => level.id)).toContain("xhigh");
1279-
expect(providerArtifactMocks.resolveBundledProviderPolicySurface).toHaveBeenCalledWith(
1280-
"openai",
1281-
{ manifestRegistry: undefined },
1282-
);
1281+
const [providerId, options] =
1282+
providerArtifactMocks.resolveBundledProviderPolicySurface.mock.calls.at(-1) ?? [];
1283+
expect(providerId).toBe("openai");
1284+
expect(options).toHaveProperty("manifestRegistry");
12831285
});
12841286

12851287
test("keeps stored thinking text without a catalog and clamps it when one is present", () => {

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,4 +458,7 @@ export function getCurrentPluginMetadataSnapshot(
458458
// Light bridges (plugin-metadata-snapshot.runtime.ts) serve reads through this
459459
// instance whenever the metadata system is loaded; the require fallback only
460460
// covers cold processes.
461-
registerPluginMetadataSnapshotReaders({ getCurrentPluginMetadataSnapshot });
461+
registerPluginMetadataSnapshotReaders({
462+
adoptCurrentPluginMetadataSnapshotIfAbsent,
463+
getCurrentPluginMetadataSnapshot,
464+
});

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

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,14 +13,15 @@ import { resolveGlobalSingleton } from "../shared/global-singleton.js";
1313

1414
type CurrentSnapshotModule = Pick<
1515
typeof import("./current-plugin-metadata-snapshot.js"),
16-
"getCurrentPluginMetadataSnapshot"
16+
"adoptCurrentPluginMetadataSnapshotIfAbsent" | "getCurrentPluginMetadataSnapshot"
1717
>;
1818
type SnapshotLoaderModule = Pick<
1919
typeof import("./plugin-metadata-snapshot.js"),
2020
"resolvePluginMetadataSnapshot"
2121
>;
2222

2323
type SnapshotReaderSlot = {
24+
adoptCurrentPluginMetadataSnapshotIfAbsent?: CurrentSnapshotModule["adoptCurrentPluginMetadataSnapshotIfAbsent"];
2425
getCurrentPluginMetadataSnapshot?: CurrentSnapshotModule["getCurrentPluginMetadataSnapshot"];
2526
resolvePluginMetadataSnapshot?: SnapshotLoaderModule["resolvePluginMetadataSnapshot"];
2627
};
@@ -80,6 +81,14 @@ export function getCurrentPluginMetadataSnapshotRuntime(
8081
return reader?.(params) ?? undefined;
8182
}
8283

84+
/** Publishes through the loaded lifecycle owner without waking a cold metadata system. */
85+
export function adoptCurrentPluginMetadataSnapshotIfAbsentRuntime(
86+
snapshot: Parameters<CurrentSnapshotModule["adoptCurrentPluginMetadataSnapshotIfAbsent"]>[0],
87+
options: Parameters<CurrentSnapshotModule["adoptCurrentPluginMetadataSnapshotIfAbsent"]>[1],
88+
): void {
89+
snapshotReaderSlot.adoptCurrentPluginMetadataSnapshotIfAbsent?.(snapshot, options);
90+
}
91+
8392
/**
8493
* Resolves a plugin metadata snapshot, or undefined when the metadata system
8594
* is unavailable (cold test workers without a CJS TS hook); callers treat that

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

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,64 @@ describe("plugin metadata snapshot", () => {
487487
);
488488
});
489489

490+
it("adopts a cold unscoped snapshot across equivalent selected-agent model configs", () => {
491+
const config = {
492+
agents: {
493+
entries: { ops: { models: { "openai/ops": { alias: "Operations" } } } },
494+
},
495+
};
496+
const index = makeIndex();
497+
index.policyHash = resolveInstalledPluginIndexPolicyHash(config);
498+
loadPluginRegistrySnapshotWithMetadata.mockReturnValue({
499+
source: "derived",
500+
snapshot: index,
501+
diagnostics: [],
502+
});
503+
504+
const snapshot = resolvePluginMetadataSnapshot({ config, env: {} });
505+
506+
expect(resolvePluginMetadataSnapshot({ config: structuredClone(config), env: {} })).toBe(
507+
snapshot,
508+
);
509+
expect(
510+
resolvePluginMetadataSnapshot({
511+
config: {
512+
agents: {
513+
entries: { support: { models: { "openai/support": { alias: "Support" } } } },
514+
},
515+
},
516+
env: {},
517+
}),
518+
).toBe(snapshot);
519+
expect(loadPluginRegistrySnapshotWithMetadata).toHaveBeenCalledOnce();
520+
expect(loadPluginManifestRegistryForInstalledIndex).toHaveBeenCalledOnce();
521+
});
522+
523+
it.each([
524+
{ scope: "workspace", options: { workspaceDir: "/workspace" } },
525+
{ scope: "plugin", options: { pluginIds: ["demo"] } },
526+
{ scope: "empty plugin", options: { pluginIds: [] } },
527+
{ scope: "caller-owned index", options: { index: makeIndex() } },
528+
{ scope: "current bypass", options: { allowCurrent: false } },
529+
{ scope: "persisted bypass", options: { preferPersisted: false } },
530+
{ scope: "state override", options: { stateDir: "/state" } },
531+
])("does not publish a cold $scope snapshot as process metadata", ({ options }) => {
532+
const config = {};
533+
const index = makeIndex();
534+
index.policyHash = resolveInstalledPluginIndexPolicyHash(config);
535+
loadPluginRegistrySnapshotWithMetadata.mockReturnValue({
536+
source: "derived",
537+
snapshot: index,
538+
diagnostics: [],
539+
});
540+
541+
const first = resolvePluginMetadataSnapshot({ config, env: {}, ...options });
542+
const second = resolvePluginMetadataSnapshot({ config, env: {}, ...options });
543+
544+
expect(second).not.toBe(first);
545+
expect(loadPluginRegistrySnapshotWithMetadata).toHaveBeenCalledTimes(2);
546+
});
547+
490548
it("propagates the current-snapshot bypass to the registry reader", () => {
491549
const config = {};
492550
const index = makeIndex();

0 commit comments

Comments
 (0)