Skip to content

Commit 01e8887

Browse files
authored
refactor(providers): return prepared dynamic models directly (#126574)
1 parent 4324ba2 commit 01e8887

23 files changed

Lines changed: 555 additions & 425 deletions

‎docs/plugins/architecture-internals.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,7 @@ listed here.
272272
| `resolveExternalAuthProfiles` | Overlay provider-owned external auth profiles; default `persistence` is `runtime-only` for CLI/app-owned creds | Provider reuses external auth credentials without persisting copied refresh tokens; declare `contracts.externalAuthProviders` in the manifest |
273273
| `shouldDeferSyntheticProfileAuth` | Lower stored synthetic profile placeholders behind env/config-backed auth | Provider stores synthetic placeholder profiles that should not win precedence |
274274
| `resolveDynamicModel` | Sync fallback for provider-owned model ids not in the local registry yet | Provider accepts arbitrary upstream model ids |
275-
| `prepareDynamicModel` | Async warm-up, then `resolveDynamicModel` runs again | Provider needs network metadata before resolving unknown ids |
275+
| `prepareDynamicModel` | Return an asynchronously prepared model, or warm reusable metadata before retrying `resolveDynamicModel` | Provider needs network metadata before resolving unknown ids |
276276
| `normalizeResolvedModel` | Final rewrite before the embedded runner uses the resolved model | Provider needs transport rewrites but still uses a core transport |
277277
| `normalizeToolSchemas` | Normalize tool schemas before the embedded runner sees them | Provider needs transport-family schema cleanup |
278278
| `inspectToolSchemas` | Surface provider-owned schema diagnostics after normalization | Provider wants keyword warnings without teaching core provider-specific rules |

‎docs/plugins/sdk-provider-plugins.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -485,8 +485,10 @@ catalog, API-key auth, and dynamic model resolution.
485485
});
486486
```
487487

488-
If resolving requires a network call, use `prepareDynamicModel` for async
489-
warm-up - `resolveDynamicModel` runs again after it completes.
488+
If resolving requires a network call, return the requested model directly
489+
from `prepareDynamicModel`. OpenClaw applies the same configured overrides
490+
and normalization as synchronous dynamic resolution. Existing hooks that
491+
return nothing still retry `resolveDynamicModel` after preparation.
490492

491493
</Step>
492494

@@ -683,7 +685,7 @@ catalog, API-key auth, and dynamic model resolution.
683685
| `resolveExternalAuthProfiles` | Overlay provider-owned external auth profiles for CLI/app-managed credentials |
684686
| `shouldDeferSyntheticProfileAuth` | Lower synthetic stored-profile placeholders behind env/config auth |
685687
| `resolveDynamicModel` | Accept arbitrary upstream model IDs |
686-
| `prepareDynamicModel` | Async metadata fetch before resolving |
688+
| `prepareDynamicModel` | Return an asynchronously discovered model, or warm reusable metadata before sync resolution |
687689
| `normalizeResolvedModel` | Transport rewrites before the runner |
688690
| `normalizeToolSchemas` | Provider-owned tool-schema cleanup before registration |
689691
| `inspectToolSchemas` | Provider-owned tool-schema diagnostics |

‎extensions/llama-cpp/index.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import type { ProviderPlugin } from "openclaw/plugin-sdk/provider-model-shared";
1818
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
1919

2020
const mocks = vi.hoisted(() => ({
21+
discoverServer: vi.fn(),
2122
ensureModel: vi.fn(),
2223
prepareServer: vi.fn(),
2324
inspectRuntime: vi.fn(),
@@ -36,6 +37,11 @@ vi.mock("./src/managed-server.js", async (importOriginal) => ({
3637
inspectLlamaServerRuntime: mocks.inspectRuntime,
3738
}));
3839

40+
vi.mock("./src/external-server/discovery.js", async (importOriginal) => ({
41+
...(await importOriginal<typeof import("./src/external-server/discovery.js")>()),
42+
discoverLlamaServer: mocks.discoverServer,
43+
}));
44+
3945
import llamaCppPlugin from "./index.js";
4046
import {
4147
DEFAULT_LLAMA_CPP_EMBEDDING_CACHE_FILE,
@@ -52,6 +58,7 @@ let previousPluginRegistry: ReturnType<typeof getActivePluginRegistry>;
5258

5359
beforeEach(() => {
5460
previousPluginRegistry = getActivePluginRegistry();
61+
mocks.discoverServer.mockReset();
5562
mocks.ensureModel.mockResolvedValue("/models/model.gguf");
5663
mocks.prepareServer.mockResolvedValue({});
5764
mocks.inspectRuntime.mockResolvedValue({
@@ -171,6 +178,23 @@ describe("llama.cpp provider plugin", () => {
171178
expect(provider).not.toHaveProperty("createStreamFn");
172179
});
173180

181+
it("never discovers external models for a managed local service", async () => {
182+
const provider = registerTextProvider();
183+
const prepareDynamicModel = expectDefined(provider.prepareDynamicModel, "dynamic model hook");
184+
const { config } = configuredOptions();
185+
186+
await expect(
187+
prepareDynamicModel({
188+
config,
189+
provider: LLAMA_CPP_PROVIDER_ID,
190+
modelId: "gemma-4-e4b-it-q4_k_m",
191+
modelRegistry: {} as never,
192+
providerConfig: config.models.providers[LLAMA_CPP_PROVIDER_ID],
193+
}),
194+
).resolves.toBeUndefined();
195+
expect(mocks.discoverServer).not.toHaveBeenCalled();
196+
});
197+
174198
it("registers local embeddings through the generic provider contract", () => {
175199
const { config, registry } = createPluginRegistryFixture();
176200
registerVirtualTestPlugin({

‎extensions/llama-cpp/src/external-server/provider.test.ts‎

Lines changed: 105 additions & 104 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,7 @@ import type {
33
ProviderPrepareDynamicModelContext,
44
} from "openclaw/plugin-sdk/plugin-entry";
55
import { beforeEach, describe, expect, it, vi } from "vitest";
6-
import {
7-
discoverLlamaServerProvider,
8-
prepareLlamaServerDynamicModels,
9-
resolveLlamaServerDynamicModel,
10-
} from "./provider.js";
6+
import { discoverLlamaServerProvider, prepareLlamaServerDynamicModel } from "./provider.js";
117

128
const discoverMock = vi.hoisted(() => vi.fn());
139
const runtimeApiKeyMock = vi.hoisted(() => vi.fn());
@@ -64,6 +60,22 @@ function catalogContext(): ProviderCatalogContext {
6460
};
6561
}
6662

63+
function dynamicContext(
64+
overrides: Partial<ProviderPrepareDynamicModelContext> = {},
65+
): ProviderPrepareDynamicModelContext {
66+
return {
67+
config: {},
68+
provider: "llama-cpp",
69+
modelId: "org/model:Q4",
70+
modelRegistry: {} as never,
71+
providerConfig: {
72+
baseUrl: "http://localhost:8080/v1",
73+
api: "openai-completions",
74+
},
75+
...overrides,
76+
};
77+
}
78+
6779
describe("llama-server provider discovery", () => {
6880
beforeEach(() => {
6981
discoverMock.mockReset();
@@ -131,7 +143,29 @@ describe("llama-server provider discovery", () => {
131143
});
132144
});
133145

134-
it("scopes dynamic catalogs by agent runtime and auth profile", async () => {
146+
it("returns only the requested discovered model directly to its preparation owner", async () => {
147+
discoverMock.mockResolvedValue({
148+
...success(),
149+
models: [
150+
model(),
151+
{
152+
...model(),
153+
config: { ...model().config, id: "org/requested:Q8", name: "Requested model" },
154+
},
155+
],
156+
});
157+
await expect(
158+
prepareLlamaServerDynamicModel(dynamicContext({ modelId: "org/requested:Q8" })),
159+
).resolves.toMatchObject({
160+
provider: "llama-cpp",
161+
id: "org/requested:Q8",
162+
name: "Requested model",
163+
baseUrl: "http://localhost:8080/v1",
164+
api: "openai-completions",
165+
});
166+
});
167+
168+
it("keeps requested models and API keys isolated by agent runtime and auth profile", async () => {
135169
const first = success();
136170
const second = {
137171
...success(),
@@ -143,29 +177,20 @@ describe("llama-server provider discovery", () => {
143177
],
144178
};
145179
discoverMock.mockResolvedValueOnce(first).mockResolvedValueOnce(second);
146-
const base = {
147-
config: {},
148-
provider: "llama-cpp",
149-
modelId: "org/model:Q4",
150-
modelRegistry: {},
151-
providerConfig: {
152-
baseUrl: "http://localhost:8080/v1",
153-
api: "openai-completions",
154-
},
155-
};
156-
const firstCtx = {
157-
...base,
180+
runtimeApiKeyMock
181+
.mockResolvedValueOnce("first-profile-key")
182+
.mockResolvedValueOnce("second-profile-key");
183+
const firstCtx = dynamicContext({
158184
agentRuntimeId: "runtime-one",
159185
authProfileId: "profile-one",
160-
} as unknown as ProviderPrepareDynamicModelContext;
161-
const secondCtx = {
162-
...base,
186+
});
187+
const secondCtx = dynamicContext({
163188
agentRuntimeId: "runtime-two",
164189
authProfileId: "profile-two",
165-
} as unknown as ProviderPrepareDynamicModelContext;
190+
});
166191

167-
await prepareLlamaServerDynamicModels(firstCtx);
168-
await prepareLlamaServerDynamicModels(secondCtx);
192+
const firstModel = await prepareLlamaServerDynamicModel(firstCtx);
193+
const secondModel = await prepareLlamaServerDynamicModel(secondCtx);
169194

170195
expect(runtimeApiKeyMock).toHaveBeenNthCalledWith(
171196
1,
@@ -175,111 +200,87 @@ describe("llama-server provider discovery", () => {
175200
2,
176201
expect.objectContaining({ profileId: "profile-two" }),
177202
);
178-
expect(resolveLlamaServerDynamicModel(firstCtx)?.name).toBe("org/model:Q4");
179-
expect(resolveLlamaServerDynamicModel(secondCtx)?.name).toBe("second scope");
180-
});
181-
182-
it("bounds dynamic model snapshots by scope", async () => {
183-
discoverMock.mockResolvedValue(success());
184-
const contexts = Array.from(
185-
{ length: 101 },
186-
(_, index) =>
187-
({
188-
config: {},
189-
provider: "llama-cpp",
190-
modelId: "org/model:Q4",
191-
modelRegistry: {},
192-
agentRuntimeId: `runtime-${index}`,
193-
providerConfig: {
194-
baseUrl: "http://localhost:8080/v1",
195-
api: "openai-completions",
196-
},
197-
}) as unknown as ProviderPrepareDynamicModelContext,
203+
expect(discoverMock).toHaveBeenNthCalledWith(
204+
1,
205+
expect.objectContaining({ apiKey: "first-profile-key" }),
198206
);
199-
200-
for (const ctx of contexts) {
201-
await prepareLlamaServerDynamicModels(ctx);
202-
}
203-
204-
expect(resolveLlamaServerDynamicModel(contexts[0]!)).toBeUndefined();
205-
expect(resolveLlamaServerDynamicModel(contexts.at(-1)!)).toMatchObject({
206-
id: "org/model:Q4",
207-
});
207+
expect(discoverMock).toHaveBeenNthCalledWith(
208+
2,
209+
expect.objectContaining({ apiKey: "second-profile-key" }),
210+
);
211+
expect(firstModel?.name).toBe("org/model:Q4");
212+
expect(secondModel?.name).toBe("second scope");
208213
});
209214

210-
it("keeps dynamic snapshots separate when only the endpoint changes", async () => {
215+
it("keeps requested models separate when only the endpoint changes", async () => {
211216
discoverMock.mockResolvedValueOnce(success()).mockResolvedValueOnce({
212217
...success(),
213218
models: [{ ...model(), config: { ...model().config, name: "second endpoint" } }],
214219
});
215220
const base = {
216-
config: {},
217-
provider: "llama-cpp",
218-
modelId: "org/model:Q4",
219-
modelRegistry: {},
220221
agentRuntimeId: "endpoint-runtime",
221222
authProfileId: "endpoint-profile",
222223
};
223-
const first = {
224+
const first = dynamicContext({
224225
...base,
225226
providerConfig: { baseUrl: "http://localhost:8080/v1", api: "openai-completions" },
226-
} as unknown as ProviderPrepareDynamicModelContext;
227-
const second = {
227+
});
228+
const second = dynamicContext({
228229
...base,
229230
providerConfig: { baseUrl: "http://localhost:8081/v1", api: "openai-completions" },
230-
} as unknown as ProviderPrepareDynamicModelContext;
231+
});
231232

232-
await prepareLlamaServerDynamicModels(first);
233-
await prepareLlamaServerDynamicModels(second);
233+
const firstModel = await prepareLlamaServerDynamicModel(first);
234+
const secondModel = await prepareLlamaServerDynamicModel(second);
234235

235-
expect(resolveLlamaServerDynamicModel(first)?.name).toBe("org/model:Q4");
236-
expect(resolveLlamaServerDynamicModel(second)?.name).toBe("second endpoint");
236+
expect(firstModel).toMatchObject({
237+
name: "org/model:Q4",
238+
baseUrl: "http://localhost:8080/v1",
239+
});
240+
expect(secondModel).toMatchObject({
241+
name: "second endpoint",
242+
baseUrl: "http://localhost:8081/v1",
243+
});
237244
});
238245

239-
it("clears a scope snapshot when its refresh cannot discover the server", async () => {
240-
discoverMock.mockResolvedValueOnce(success()).mockResolvedValueOnce({
241-
kind: "unreachable",
242-
endpoint: { origin: "http://localhost:8080", inferenceBaseUrl: "http://localhost:8080/v1" },
243-
error: new Error("offline"),
244-
});
245-
const ctx = {
246-
config: {},
247-
provider: "llama-cpp",
248-
modelId: "org/model:Q4",
249-
modelRegistry: {},
250-
agentRuntimeId: "failed-refresh-runtime",
251-
providerConfig: {
252-
baseUrl: "http://localhost:8080/v1",
253-
api: "openai-completions",
254-
},
255-
} as unknown as ProviderPrepareDynamicModelContext;
246+
it("prefers explicit Authorization over the profile API key during model preparation", async () => {
247+
runtimeApiKeyMock.mockResolvedValue("profile-key");
248+
discoverMock.mockResolvedValue(success());
249+
const headers = { Authorization: "Bearer endpoint-key" };
250+
251+
await prepareLlamaServerDynamicModel(
252+
dynamicContext({
253+
providerConfig: { baseUrl: "http://localhost:8080/v1", headers },
254+
}),
255+
);
256256

257-
await prepareLlamaServerDynamicModels(ctx);
258-
expect(resolveLlamaServerDynamicModel(ctx)).toMatchObject({ id: "org/model:Q4" });
259-
await prepareLlamaServerDynamicModels(ctx);
260-
expect(resolveLlamaServerDynamicModel(ctx)).toBeUndefined();
257+
expect(discoverMock).toHaveBeenCalledWith(
258+
expect.objectContaining({ apiKey: undefined, headers, cacheTtlMs: 0 }),
259+
);
261260
});
262261

263-
it("refreshes and resolves dynamic model ids containing slashes", async () => {
264-
discoverMock.mockResolvedValue(success());
265-
const ctx = {
266-
config: {},
267-
provider: "llama-cpp",
268-
modelId: "org/model:Q4",
269-
modelRegistry: {},
270-
providerConfig: {
271-
baseUrl: "http://localhost:8080/v1",
272-
api: "openai-completions",
262+
it.each([
263+
{
264+
label: "the server is unavailable",
265+
discovery: {
266+
kind: "unreachable" as const,
267+
endpoint: { origin: "http://localhost:8080", inferenceBaseUrl: "http://localhost:8080/v1" },
268+
error: new Error("offline"),
273269
},
274-
} as unknown as ProviderPrepareDynamicModelContext;
275-
276-
await prepareLlamaServerDynamicModels(ctx);
270+
},
271+
{
272+
label: "the requested model disappears",
273+
discovery: { ...success(), models: [] },
274+
},
275+
])("returns no stale model when $label", async ({ discovery }) => {
276+
discoverMock.mockResolvedValueOnce(success()).mockResolvedValueOnce(discovery);
277+
const ctx = dynamicContext({
278+
agentRuntimeId: "failed-refresh-runtime",
279+
});
277280

278-
expect(resolveLlamaServerDynamicModel(ctx)).toMatchObject({
279-
provider: "llama-cpp",
281+
await expect(prepareLlamaServerDynamicModel(ctx)).resolves.toMatchObject({
280282
id: "org/model:Q4",
281-
baseUrl: "http://localhost:8080/v1",
282-
api: "openai-completions",
283283
});
284+
await expect(prepareLlamaServerDynamicModel(ctx)).resolves.toBeUndefined();
284285
});
285286
});

0 commit comments

Comments
 (0)