Skip to content

Commit 8dac217

Browse files
authored
refactor(models): consolidate prepared catalog construction (#130654)
* refactor(models): consolidate prepared catalog construction * test(models): avoid shadowing registry fixture identifiers
1 parent b7d9be0 commit 8dac217

11 files changed

Lines changed: 210 additions & 202 deletions

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

Lines changed: 58 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { beforeEach, describe, expect, it, vi } from "vitest";
22
import type { PluginMetadataSnapshot } from "../../plugins/plugin-metadata-snapshot.types.js";
3-
import { getModelProviderRequestRouteFacts } from "../provider-request-config.js";
3+
import { getModelProviderLocalService } from "../provider-local-service.js";
4+
import {
5+
getModelProviderRequestRouteFacts,
6+
getModelProviderRequestTransport,
7+
} from "../provider-request-config.js";
48

59
const mocks = vi.hoisted(() => ({
610
loadPluginManifestRegistryCore: vi.fn(),
@@ -196,18 +200,42 @@ describe("prepared bundled provider static catalogs", () => {
196200
);
197201
});
198202

199-
it("projects prepared rows without rerunning hooks", async () => {
203+
it("projects heterogeneous prepared rows without rerunning hooks or resolving empty providers", async () => {
200204
mocks.resolveRuntimePluginDiscoveryProviders.mockResolvedValue([provider]);
201205
mocks.normalizePluginDiscoveryResult.mockReturnValue({
202206
google: {
207+
api: "fixture-api",
208+
baseUrl: "https://fixture.example/v1",
209+
authHeader: false,
210+
maxTokens: 4096,
211+
request: { headers: { "X-Catalog": "prepared" } },
212+
localService: { command: "fixture-service" },
203213
models: [
204214
{
205215
id: "gemini-3.1-pro-preview",
206216
name: "Gemini Pro",
207217
contextWindow: 1_048_576,
218+
reasoning: false,
219+
input: ["text", "image"],
220+
cost: { input: 0.5 },
221+
maxTokens: 0,
222+
},
223+
{
224+
id: "fallback-model",
225+
name: "",
226+
baseUrl: "",
227+
input: [],
228+
contextWindow: 0,
229+
contextTokens: 0,
208230
},
209231
],
210232
},
233+
empty: {
234+
request: {
235+
headers: { "X-Unused": { source: "env", provider: "default", id: "UNUSED_HEADER" } },
236+
},
237+
models: [],
238+
},
211239
});
212240

213241
const metadataSnapshot = createMetadataSnapshot(["google"]);
@@ -223,12 +251,37 @@ describe("prepared bundled provider static catalogs", () => {
223251
expect.objectContaining({
224252
id: "gemini-3.1-pro-preview",
225253
provider: "google",
254+
api: "fixture-api",
255+
baseUrl: "https://fixture.example/v1",
256+
authHeader: false,
257+
reasoning: false,
258+
input: ["text", "image"],
259+
cost: { input: 0.5 },
226260
contextWindow: 1_048_576,
261+
maxTokens: 0,
262+
}),
263+
expect.objectContaining({
264+
id: "fallback-model",
265+
name: "fallback-model",
266+
provider: "google",
267+
api: "fixture-api",
268+
baseUrl: "",
269+
input: ["text"],
270+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
271+
contextWindow: 0,
272+
contextTokens: 0,
273+
maxTokens: 4096,
227274
}),
228275
]);
229-
expect(getModelProviderRequestRouteFacts(models[0]!)?.providerMetadataOwners).toBe(
230-
metadataSnapshot.owners,
231-
);
276+
for (const model of models) {
277+
expect(getModelProviderRequestRouteFacts(model)?.providerMetadataOwners).toBe(
278+
metadataSnapshot.owners,
279+
);
280+
expect(getModelProviderRequestTransport(model)).toEqual({
281+
headers: { "X-Catalog": "prepared" },
282+
});
283+
expect(getModelProviderLocalService(model)).toEqual({ command: "fixture-service" });
284+
}
232285
expect(mocks.resolveRuntimePluginDiscoveryProviders).toHaveBeenCalledOnce();
233286
expect(mocks.runProviderStaticCatalog).not.toHaveBeenCalled();
234287
});

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

Lines changed: 26 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import {
2727
resolveOwningPluginIdsForProviderRef,
2828
} from "../../plugins/providers.js";
2929
import { DEFAULT_CONTEXT_TOKENS } from "../defaults.js";
30-
import { buildInlineProviderModels } from "./model.inline-provider.js";
30+
import { buildInlineProviderModels, type InlineModelEntry } from "./model.inline-provider.js";
3131
import {
3232
createStaticModelIdMatcher,
3333
staticModelIdMatches,
@@ -97,38 +97,22 @@ function modelFromStaticCatalogRow(row: NormalizedModelCatalogRow): ProviderRunt
9797
};
9898
}
9999

100-
function modelFromProviderStaticCatalog(params: {
101-
provider: string;
102-
providerConfig: ModelProviderConfig;
103-
model: ModelProviderConfig["models"][number];
104-
providerMetadataOwners?: PluginMetadataSnapshot["owners"];
105-
}): ProviderRuntimeModel {
106-
const [model] = buildInlineProviderModels(
107-
{
108-
[params.provider]: { ...params.providerConfig, models: [params.model] },
109-
},
110-
{ providerMetadataOwners: params.providerMetadataOwners },
111-
);
100+
function completeProviderStaticCatalogModel(
101+
model: InlineModelEntry,
102+
providerConfig: ModelProviderConfig,
103+
): ProviderRuntimeModel {
112104
return {
113105
...model,
114-
id: model?.id ?? params.model.id,
115-
name: model?.name || params.model.name || params.model.id,
116-
provider: params.provider,
117-
api: model?.api ?? params.model.api ?? params.providerConfig.api ?? "openai-responses",
118-
baseUrl: model?.baseUrl ?? params.model.baseUrl ?? params.providerConfig.baseUrl ?? "",
119-
reasoning: model?.reasoning ?? params.model.reasoning ?? false,
120-
input: normalizeStaticCatalogInput(model?.input ?? params.model.input),
121-
cost: model?.cost ?? normalizeStaticCatalogCost(params.model.cost),
122-
contextWindow: model?.contextWindow ?? params.model.contextWindow ?? DEFAULT_CONTEXT_TOKENS,
123-
contextTokens: model?.contextTokens ?? params.model.contextTokens,
124-
maxTokens:
125-
model?.maxTokens ??
126-
params.model.maxTokens ??
127-
params.providerConfig.maxTokens ??
128-
DEFAULT_CONTEXT_TOKENS,
129-
...(params.providerConfig.authHeader !== undefined
130-
? { authHeader: params.providerConfig.authHeader }
131-
: {}),
106+
name: model.name || model.id,
107+
api: model.api ?? providerConfig.api ?? "openai-responses",
108+
baseUrl: model.baseUrl ?? "",
109+
reasoning: model.reasoning ?? false,
110+
input: normalizeStaticCatalogInput(model.input),
111+
cost: model.cost ?? normalizeStaticCatalogCost(undefined),
112+
contextWindow: model.contextWindow ?? DEFAULT_CONTEXT_TOKENS,
113+
contextTokens: model.contextTokens,
114+
maxTokens: model.maxTokens ?? DEFAULT_CONTEXT_TOKENS,
115+
...(providerConfig.authHeader !== undefined ? { authHeader: providerConfig.authHeader } : {}),
132116
};
133117
}
134118

@@ -485,21 +469,20 @@ async function loadBundledProviderStaticCatalogModels(params: {
485469
});
486470
for (const [providerIdRaw, providerConfig] of Object.entries(normalized)) {
487471
const provider = normalizeProviderId(providerIdRaw);
488-
if (!provider || !Array.isArray(providerConfig.models)) {
472+
// Empty catalogs never resolve request secrets or transport settings.
473+
if (
474+
!provider ||
475+
!Array.isArray(providerConfig.models) ||
476+
providerConfig.models.length === 0
477+
) {
489478
continue;
490479
}
491480
const models = modelsByProvider.get(provider) ?? [];
492481
models.push(
493-
...providerConfig.models.map((model) =>
494-
modelFromProviderStaticCatalog({
495-
provider,
496-
providerConfig,
497-
model,
498-
...(params.providerMetadataOwners
499-
? { providerMetadataOwners: params.providerMetadataOwners }
500-
: {}),
501-
}),
502-
),
482+
...buildInlineProviderModels(
483+
{ [provider]: providerConfig },
484+
{ providerMetadataOwners: params.providerMetadataOwners },
485+
).map((model) => completeProviderStaticCatalogModel(model, providerConfig)),
503486
);
504487
modelsByProvider.set(provider, models);
505488
}
@@ -639,17 +622,6 @@ function createScopedBundledProviderStaticCatalogModelResolver(
639622
};
640623
}
641624

642-
/**
643-
* Prepares bundled provider static-catalog lookup.
644-
* Each provider hook runs at most once for the resolver lifetime.
645-
*/
646-
function createBundledProviderStaticCatalogModelResolver(
647-
params: BundledProviderStaticCatalogResolverParams = {},
648-
): (lookup: BundledStaticCatalogLookup) => Promise<ProviderRuntimeModel | undefined> {
649-
const resolveModel = createScopedBundledProviderStaticCatalogModelResolver(params);
650-
return async (lookup) => await resolveModel(lookup);
651-
}
652-
653625
function resolveOwnedNestedProviderLookup(params: {
654626
lookup: BundledStaticCatalogLookup;
655627
resolverParams: BundledProviderStaticCatalogResolverParams;
@@ -735,5 +707,5 @@ export async function resolveBundledProviderStaticCatalogModel(params: {
735707
env?: NodeJS.ProcessEnv;
736708
metadataSnapshot?: PluginMetadataSnapshot;
737709
}): Promise<ProviderRuntimeModel | undefined> {
738-
return createBundledProviderStaticCatalogModelResolver(params)(params);
710+
return createScopedBundledProviderStaticCatalogModelResolver(params)(params);
739711
}

‎src/agents/prepared-model-runtime.catalog-contract.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ConfiguredModelRef } from "@openclaw/model-catalog-core/configured-model-refs";
1+
import type { ModelCatalogRef } from "@openclaw/model-catalog-core/model-catalog-refs";
22
import type { ProviderCatalogOutcome } from "../plugins/provider-catalog.types.js";
33
import type { AuthProfileStore } from "./auth-profiles/types.js";
44
import type { InlineModelEntry } from "./embedded-agent-runner/model.inline-provider.js";
@@ -19,7 +19,7 @@ export type PreparedModelRuntimeAgentBaseFacts = {
1919
templateAuthStorage: AuthStorage;
2020
credentials: Readonly<AuthStorageData>;
2121
providerIds: string[];
22-
configuredModelRefs: readonly ConfiguredModelRef[];
22+
configuredModelRefs: readonly ModelCatalogRef[];
2323
};
2424

2525
export type PreparedModelRuntimeAgentFacts = PreparedModelRuntimeAgentBaseFacts & {

‎src/agents/prepared-model-runtime.configured-catalog.ts‎

Lines changed: 3 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import type { ConfiguredModelRef } from "@openclaw/model-catalog-core/configured-model-refs";
1+
import type { ModelCatalogRef } from "@openclaw/model-catalog-core/model-catalog-refs";
22
import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
33
import type { InlineModelEntry } from "./embedded-agent-runner/model.inline-provider.js";
44
import type { ModelCatalogEntry } from "./model-catalog.js";
@@ -11,7 +11,7 @@ import {
1111
import type { ModelRegistry } from "./sessions/model-registry.js";
1212

1313
type ConfiguredCatalogAgentFacts = {
14-
configuredModelRefs: readonly ConfiguredModelRef[];
14+
configuredModelRefs: readonly ModelCatalogRef[];
1515
runtimeCapabilityModels: readonly PreparedRuntimeCapabilityModel[];
1616
};
1717

@@ -50,16 +50,7 @@ function createConfiguredModelCatalogSnapshot(params: {
5050
for (const configured of params.configuredRuntimeModels) {
5151
addEntry(toStaticCatalogEntry(configured.model));
5252
}
53-
for (const { value } of params.agentFacts.configuredModelRefs) {
54-
const separator = value.indexOf("/");
55-
if (separator <= 0 || separator >= value.length - 1) {
56-
continue;
57-
}
58-
const provider = normalizeProviderId(value.slice(0, separator));
59-
const modelId = value.slice(separator + 1).trim();
60-
if (!provider || !modelId) {
61-
continue;
62-
}
53+
for (const { provider, modelId } of params.agentFacts.configuredModelRefs) {
6354
const model = params.templateModelRegistry.find(provider, modelId);
6455
if (model) {
6556
addEntry(toStaticCatalogEntry(model));

‎src/agents/prepared-model-runtime.configured-completion.ts‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
import type { ConfiguredModelRef } from "@openclaw/model-catalog-core/configured-model-refs";
21
import {
32
buildModelCatalogMergeKey,
4-
parseModelCatalogRef,
3+
type ModelCatalogRef,
54
} from "@openclaw/model-catalog-core/model-catalog-refs";
65
import type { ProviderRuntimeModel } from "../plugins/provider-runtime-model.types.js";
76
import type { PreparedConfiguredRuntimeModel } from "./prepared-model-runtime.configured.js";
87

98
export function completeConfiguredRuntimeModels(params: {
10-
configuredModelRefs: readonly ConfiguredModelRef[];
9+
configuredModelRefs: readonly ModelCatalogRef[];
1110
configuredRuntimeModels: readonly PreparedConfiguredRuntimeModel[];
1211
resolveDynamicModel: (lookup: {
1312
provider: string;
@@ -22,20 +21,16 @@ export function completeConfiguredRuntimeModels(params: {
2221
);
2322
const completed: PreparedConfiguredRuntimeModel[] = [];
2423
const seen = new Set<string>();
25-
for (const { value } of params.configuredModelRefs) {
26-
const parsed = parseModelCatalogRef(value);
27-
if (!parsed) {
28-
continue;
29-
}
30-
const key = buildModelCatalogMergeKey(parsed.provider, parsed.modelId);
24+
for (const ref of params.configuredModelRefs) {
25+
const key = buildModelCatalogMergeKey(ref.provider, ref.modelId);
3126
if (seen.has(key)) {
3227
continue;
3328
}
3429
seen.add(key);
3530
const prepared = existing.get(key);
36-
const model = prepared?.model ?? params.resolveDynamicModel(parsed);
31+
const model = prepared?.model ?? params.resolveDynamicModel(ref);
3732
if (model) {
38-
completed.push({ provider: parsed.provider, modelId: parsed.modelId, model });
33+
completed.push({ ...ref, model });
3934
}
4035
}
4136
return completed;

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

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
import {
66
buildModelCatalogMergeKey,
77
parseModelCatalogRef,
8+
type ModelCatalogRef,
89
} from "@openclaw/model-catalog-core/model-catalog-refs";
910
import { normalizeProviderId } from "@openclaw/model-catalog-core/provider-id";
1011
import { MODEL_APIS } from "../config/types.models.js";
@@ -163,8 +164,7 @@ export function collectConfiguredProviderIdsNeedingStaticCatalog(params: {
163164
}
164165

165166
export function prepareConfiguredRuntimeModels(params: {
166-
config: OpenClawConfig;
167-
configuredModelRefs?: readonly ConfiguredModelRef[];
167+
configuredModelRefs: readonly ModelCatalogRef[];
168168
metadataSnapshot: PluginMetadataSnapshot;
169169
preparedStaticProviderCatalog?: PreparedProviderStaticCatalog;
170170
providerStaticModels: readonly ProviderRuntimeModel[];
@@ -176,12 +176,7 @@ export function prepareConfiguredRuntimeModels(params: {
176176
}): PreparedConfiguredRuntimeModel[] {
177177
const prepared: PreparedConfiguredRuntimeModel[] = [];
178178
const seen = new Set<string>();
179-
for (const { value } of params.configuredModelRefs ?? collectConfiguredModelRefs(params.config)) {
180-
const parsed = parseModelCatalogRef(value);
181-
if (!parsed) {
182-
continue;
183-
}
184-
const { modelId, provider } = parsed;
179+
for (const { modelId, provider } of params.configuredModelRefs) {
185180
const key = buildModelCatalogMergeKey(provider, modelId);
186181
if (seen.has(key)) {
187182
continue;

0 commit comments

Comments
 (0)