Skip to content

Commit 3b80c2f

Browse files
committed
refactor(plugins): keep provider catalog registration lightweight
Move manifest catalog builders into the existing plugin owner while retaining public SDK exports. Defer live discovery imports until the selected catalog hook runs, with a regression covering the static import boundary.
1 parent 416057e commit 3b80c2f

5 files changed

Lines changed: 276 additions & 215 deletions

File tree

‎config/assertion-safety-baseline.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3404,7 +3404,7 @@ src/plugin-sdk/provider-auth-result.ts 4
34043404
src/plugin-sdk/provider-auth-runtime.ts 1
34053405
src/plugin-sdk/provider-auth.ts 1
34063406
src/plugin-sdk/provider-catalog-live-runtime.ts 2
3407-
src/plugin-sdk/provider-catalog-shared.ts 4
3407+
src/plugin-sdk/provider-catalog-shared.ts 1
34083408
src/plugin-sdk/provider-enable-config.ts 2
34093409
src/plugin-sdk/provider-entry.ts 3
34103410
src/plugin-sdk/provider-onboard.ts 6

‎src/plugin-sdk/provider-catalog-shared.ts‎

Lines changed: 5 additions & 202 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,15 @@
11
// Provider catalog helpers normalize, hash, and expose model catalogs for provider plugins.
22
import { createHash } from "node:crypto";
3-
import { normalizeModelCatalog } from "@openclaw/model-catalog-core/model-catalog-normalize";
4-
import { buildModelCatalogRef } from "@openclaw/model-catalog-core/model-catalog-refs";
5-
import type {
6-
ModelCatalogCost,
7-
ModelCatalogMediaInputConfig,
8-
ModelCatalogModel,
9-
ModelCatalogTieredCost,
10-
} from "@openclaw/model-catalog-core/model-catalog-types";
113
import { findNormalizedProviderKey } from "@openclaw/model-catalog-core/provider-id";
124
import {
135
isFutureDateTimestampMs,
146
resolveExpiresAtMsFromDurationMs,
157
} from "../../packages/normalization-core/src/number-coercion.js";
16-
import { normalizeOptionalString } from "../../packages/normalization-core/src/string-coerce.js";
178
import { normalizeConfiguredProviderCatalogModelId } from "../agents/model-ref-shared.js";
189
import { resolveProviderRequestCapabilities } from "../agents/provider-attribution.js";
1910
import type { ModelDefinitionConfig } from "../config/types.models.js";
2011
import type { OpenClawConfig } from "../config/types.openclaw.js";
2112
import { pruneMapToMaxSize } from "../infra/map-size.js";
22-
import type { ProviderPlugin } from "../plugins/types.js";
2313
import type { ModelProviderConfig } from "./provider-model-shared.js";
2414

2515
export type {
@@ -29,9 +19,14 @@ export type {
2919
} from "../plugins/types.js";
3020

3121
export {
22+
buildManifestModelProviderConfig,
23+
buildManifestProviderCatalogFamily,
3224
buildPairedProviderApiKeyCatalog,
3325
buildSingleProviderApiKeyCatalog,
3426
findCatalogTemplate,
27+
readManifestProviderDefaultModelRef,
28+
type ManifestProviderCatalogEntry,
29+
type ManifestProviderCatalogSurface,
3530
} from "../plugins/provider-catalog.js";
3631

3732
/**
@@ -119,198 +114,6 @@ export function clearLiveCatalogCacheForTests(): void {
119114
liveCatalogCache.clear();
120115
}
121116

122-
function countRawManifestCatalogModels(catalog: unknown): number | undefined {
123-
if (!catalog || typeof catalog !== "object") {
124-
return undefined;
125-
}
126-
const models = (catalog as { models?: unknown }).models;
127-
return Array.isArray(models) ? models.length : undefined;
128-
}
129-
130-
/** Reads a provider's normalized manifest default as a fully qualified model ref. */
131-
export function readManifestProviderDefaultModelRef(
132-
manifest: unknown,
133-
providerId: string,
134-
): string | undefined {
135-
const catalog = (manifest as { modelCatalog?: { providers?: Record<string, unknown> } })
136-
?.modelCatalog?.providers?.[providerId];
137-
const defaultModel = normalizeOptionalString(
138-
(catalog as { defaultModel?: unknown })?.defaultModel,
139-
);
140-
return defaultModel ? buildModelCatalogRef(providerId, defaultModel) : undefined;
141-
}
142-
143-
function cloneManifestCatalogTieredCost(
144-
tier: ModelCatalogTieredCost,
145-
): NonNullable<ModelDefinitionConfig["cost"]["tieredPricing"]>[number] {
146-
return {
147-
input: tier.input,
148-
output: tier.output,
149-
cacheRead: tier.cacheRead,
150-
cacheWrite: tier.cacheWrite,
151-
range: tier.range.length === 1 ? [tier.range[0]] : [tier.range[0], tier.range[1]],
152-
};
153-
}
154-
155-
function cloneManifestCatalogCost(cost: ModelCatalogCost): ModelDefinitionConfig["cost"] {
156-
return {
157-
input: cost.input ?? 0,
158-
output: cost.output ?? 0,
159-
cacheRead: cost.cacheRead ?? 0,
160-
cacheWrite: cost.cacheWrite ?? 0,
161-
...(cost.tieredPricing
162-
? { tieredPricing: cost.tieredPricing.map(cloneManifestCatalogTieredCost) }
163-
: {}),
164-
};
165-
}
166-
167-
function buildManifestCatalogModelInput(model: ModelCatalogModel): ModelDefinitionConfig["input"] {
168-
if (model.input?.includes("document")) {
169-
throw new Error(
170-
`Manifest modelCatalog row ${model.id} uses unsupported runtime input document`,
171-
);
172-
}
173-
return model.input?.filter((item): item is "text" | "image" => item !== "document") ?? ["text"];
174-
}
175-
176-
function cloneManifestCatalogMediaInput(
177-
mediaInput?: ModelCatalogMediaInputConfig,
178-
): ModelDefinitionConfig["mediaInput"] | undefined {
179-
if (!mediaInput?.image) {
180-
return undefined;
181-
}
182-
return {
183-
image: { ...mediaInput.image },
184-
};
185-
}
186-
187-
function buildManifestCatalogModel(
188-
providerId: string,
189-
model: ModelCatalogModel,
190-
): ModelDefinitionConfig {
191-
if (model.contextWindow === undefined) {
192-
throw new Error(`Manifest modelCatalog row ${model.id} is missing contextWindow`);
193-
}
194-
if (model.maxTokens === undefined) {
195-
throw new Error(`Manifest modelCatalog row ${model.id} is missing maxTokens`);
196-
}
197-
const id = normalizeConfiguredProviderCatalogModelId(providerId, model.id, {
198-
allowManifestNormalization: false,
199-
});
200-
return {
201-
id,
202-
name: model.name ?? id,
203-
...(model.api ? { api: model.api } : {}),
204-
...(model.baseUrl ? { baseUrl: model.baseUrl } : {}),
205-
reasoning: model.reasoning ?? false,
206-
input: buildManifestCatalogModelInput(model),
207-
cost: cloneManifestCatalogCost(model.cost ?? {}),
208-
contextWindow: model.contextWindow,
209-
...(model.contextTokens !== undefined ? { contextTokens: model.contextTokens } : {}),
210-
maxTokens: model.maxTokens,
211-
...(model.thinkingLevelMap ? { thinkingLevelMap: { ...model.thinkingLevelMap } } : {}),
212-
...(model.headers ? { headers: { ...model.headers } } : {}),
213-
...(model.compat ? { compat: { ...model.compat } } : {}),
214-
...(model.mediaInput ? { mediaInput: cloneManifestCatalogMediaInput(model.mediaInput) } : {}),
215-
};
216-
}
217-
218-
/**
219-
* Converts a plugin manifest modelCatalog provider into runtime provider config.
220-
*/
221-
export function buildManifestModelProviderConfig(params: {
222-
/** Provider id that owns the manifest catalog rows. */
223-
providerId: string;
224-
/** Raw manifest modelCatalog provider block to normalize into runtime config. */
225-
catalog: unknown;
226-
}): ModelProviderConfig {
227-
const catalog = normalizeModelCatalog(
228-
{ providers: { [params.providerId]: params.catalog } },
229-
{ ownedProviders: new Set([params.providerId]) },
230-
)?.providers?.[params.providerId];
231-
if (!catalog) {
232-
throw new Error(`Missing modelCatalog.providers.${params.providerId}`);
233-
}
234-
if (!catalog.baseUrl) {
235-
throw new Error(`Missing modelCatalog.providers.${params.providerId}.baseUrl`);
236-
}
237-
const rawModelCount = countRawManifestCatalogModels(params.catalog);
238-
if (rawModelCount !== undefined && rawModelCount !== catalog.models.length) {
239-
throw new Error(`Invalid modelCatalog.providers.${params.providerId}.models`);
240-
}
241-
return {
242-
baseUrl: catalog.baseUrl,
243-
...(catalog.api ? { api: catalog.api } : {}),
244-
...(catalog.headers ? { headers: { ...catalog.headers } } : {}),
245-
models: catalog.models.map((model) => buildManifestCatalogModel(params.providerId, model)),
246-
};
247-
}
248-
249-
export type ManifestProviderCatalogSurface = {
250-
id: string;
251-
label: string;
252-
catalog: unknown;
253-
};
254-
255-
export type ManifestProviderCatalogEntry = {
256-
id: string;
257-
label: string;
258-
baseUrl: string;
259-
models: ModelProviderConfig["models"];
260-
buildProvider: () => ModelProviderConfig;
261-
};
262-
263-
/** Projects an ordered family of manifest catalogs into static provider and model surfaces. */
264-
export function buildManifestProviderCatalogFamily(params: {
265-
surfaces: readonly ManifestProviderCatalogSurface[];
266-
docsPath?: string;
267-
}) {
268-
const entries: ManifestProviderCatalogEntry[] = params.surfaces.map((surface) => {
269-
const buildProvider = () =>
270-
buildManifestModelProviderConfig({
271-
providerId: surface.id,
272-
catalog: surface.catalog,
273-
});
274-
const provider = buildProvider();
275-
return {
276-
id: surface.id,
277-
label: surface.label,
278-
baseUrl: provider.baseUrl,
279-
models: provider.models,
280-
buildProvider,
281-
};
282-
});
283-
const staticDiscovery: ProviderPlugin[] = entries.map(({ id, label, buildProvider }) => ({
284-
id,
285-
label,
286-
docsPath: params.docsPath ?? "/providers/models",
287-
auth: [],
288-
staticCatalog: {
289-
order: "simple",
290-
run: async () => ({ provider: buildProvider() }),
291-
},
292-
}));
293-
294-
return {
295-
entries,
296-
staticDiscovery,
297-
staticCatalog: async () => ({
298-
providers: Object.fromEntries(entries.map(({ id, buildProvider }) => [id, buildProvider()])),
299-
}),
300-
augmentModelCatalog: () =>
301-
entries.flatMap(({ id: provider, models }) =>
302-
models.map((entry) => ({
303-
provider,
304-
id: entry.id,
305-
name: entry.name,
306-
reasoning: entry.reasoning,
307-
input: [...entry.input],
308-
contextWindow: entry.contextWindow,
309-
})),
310-
),
311-
};
312-
}
313-
314117
function normalizeConfiguredCatalogModelInput(
315118
input: unknown,
316119
): ConfiguredProviderCatalogEntry["input"] | undefined {

‎src/plugin-sdk/provider-entry.test.ts‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Provider entry tests cover provider plugin entry contracts and catalog integration.
2-
import { describe, expect, it } from "vitest";
2+
import { describe, expect, it, vi } from "vitest";
33
import type { ModelDefinitionConfig } from "../config/types.models.js";
44
import { capturePluginRegistration } from "../plugins/captured-registration.js";
55
import type { ProviderCatalogContext } from "../plugins/types.js";
@@ -86,6 +86,58 @@ async function captureProviderEntry(params: {
8686
}
8787

8888
describe("defineSingleProviderPluginEntry", () => {
89+
it("keeps static catalog registration independent of live discovery", async () => {
90+
const liveCatalog = {
91+
provider: { baseUrl: "https://api.demo.test/v1", models: [createModel("live", "Live")] },
92+
};
93+
const buildLiveCatalog = vi.fn(async () => liveCatalog);
94+
const loadLiveCatalog = vi.fn(() => ({
95+
buildOpenAICompatibleProviderCatalog: buildLiveCatalog,
96+
}));
97+
vi.doMock("../agents/provider-attribution.js", () => {
98+
throw new Error("Static provider entry loaded transport policy");
99+
});
100+
vi.doMock("./provider-catalog-live-runtime.js", loadLiveCatalog);
101+
vi.resetModules();
102+
try {
103+
const { defineSingleProviderPluginEntry: defineColdEntry } =
104+
await import("./provider-entry.js");
105+
const entry = defineColdEntry({
106+
id: "demo",
107+
name: "Demo Provider",
108+
description: "Demo provider plugin",
109+
manifest: createProviderManifest(),
110+
provider: {
111+
label: "Demo",
112+
docsPath: "/providers/demo",
113+
aliases: ["demo-alias"],
114+
catalog: { liveModelDiscovery: true },
115+
},
116+
});
117+
const provider = capturePluginRegistration(entry).providers[0];
118+
const context = createCatalogContext();
119+
await expect(provider?.staticCatalog?.run(context)).resolves.toMatchObject({
120+
provider: { models: [createModel("default", "Default")] },
121+
});
122+
await expect(provider?.catalog?.run({ ...context, providerIds: [] })).resolves.toBeNull();
123+
expect(loadLiveCatalog).not.toHaveBeenCalled();
124+
125+
const scopedContext = { ...context, providerIds: ["demo-alias"] };
126+
await expect(provider?.catalog?.run(scopedContext)).resolves.toBe(liveCatalog);
127+
expect(buildLiveCatalog).toHaveBeenCalledExactlyOnceWith(
128+
expect.objectContaining({
129+
ctx: scopedContext,
130+
providerId: "demo",
131+
providerAliases: ["demo-alias"],
132+
}),
133+
);
134+
} finally {
135+
vi.doUnmock("../agents/provider-attribution.js");
136+
vi.doUnmock("./provider-catalog-live-runtime.js");
137+
vi.resetModules();
138+
}
139+
});
140+
89141
it("derives API-key auth and static and live model catalogs from the provider manifest", async () => {
90142
const manifest = createProviderManifest();
91143
const entry = defineSingleProviderPluginEntry({

‎src/plugin-sdk/provider-entry.ts‎

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ import type {
1111
} from "../plugins/manifest-types.js";
1212
import { createProviderApiKeyAuthMethod } from "../plugins/provider-api-key-auth.js";
1313
import { projectProviderCatalogResultToUnifiedTextRows } from "../plugins/provider-catalog-unified-text.js";
14+
import {
15+
buildManifestModelProviderConfig,
16+
buildSingleProviderApiKeyCatalog,
17+
readManifestProviderDefaultModelRef,
18+
} from "../plugins/provider-catalog.js";
1419
import type {
1520
ProviderPlugin,
1621
ProviderCatalogContext,
@@ -25,21 +30,20 @@ import {
2530
isRecordWithoutThrowing,
2631
readRecordValue,
2732
} from "../shared/safe-record.js";
33+
import { createLazyRuntimeMethod, createLazyRuntimeModule } from "./lazy-runtime.js";
2834
import { definePluginEntry } from "./plugin-entry.js";
2935
import type {
3036
OpenClawPluginApi,
3137
OpenClawPluginConfigSchema,
3238
OpenClawPluginDefinition,
3339
} from "./plugin-entry.js";
34-
import {
35-
buildOpenAICompatibleProviderCatalog,
36-
type OpenAICompatibleModelDiscoveryOptions,
37-
} from "./provider-catalog-live-runtime.js";
38-
import {
39-
buildManifestModelProviderConfig,
40-
buildSingleProviderApiKeyCatalog,
41-
readManifestProviderDefaultModelRef,
42-
} from "./provider-catalog-shared.js";
40+
import type { OpenAICompatibleModelDiscoveryOptions } from "./provider-catalog-live-runtime.js";
41+
42+
// Registration needs static metadata; live discovery loads only when its catalog hook runs.
43+
const buildOpenAICompatibleProviderCatalog = createLazyRuntimeMethod(
44+
createLazyRuntimeModule(() => import("./provider-catalog-live-runtime.js")),
45+
(runtime) => runtime.buildOpenAICompatibleProviderCatalog,
46+
);
4347

4448
type ApiKeyAuthMethodOptions = Parameters<typeof createProviderApiKeyAuthMethod>[0];
4549

0 commit comments

Comments
 (0)