Skip to content

Commit f9dd6ed

Browse files
authored
refactor(models): simplify prepared owner access (#130683)
1 parent 71d4a8c commit f9dd6ed

6 files changed

Lines changed: 87 additions & 96 deletions

‎src/agents/embedded-agent-runner/model.generation-scope.test.ts‎

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1-
import { afterEach, beforeEach, describe, expect, it } from "vitest";
1+
import { expectDefined } from "@openclaw/normalization-core";
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
23
import type { OpenClawConfig } from "../../config/types.openclaw.js";
34
import { clearPluginMetadataLifecycleCaches } from "../../plugins/plugin-metadata-lifecycle.js";
5+
import { AuthStorage, ModelRegistry } from "../sessions/index.js";
46
import {
57
createModelGenerationFixture,
68
publishCurrentModelGeneration,
@@ -32,9 +34,50 @@ describe("model runtime generation scope", () => {
3234
});
3335

3436
afterEach(() => {
37+
vi.restoreAllMocks();
3538
resetModelGenerationFixtureState();
3639
});
3740

41+
it.each([
42+
{ auth: true, registry: true },
43+
{ auth: true, registry: false },
44+
{ auth: false, registry: true },
45+
{ auth: false, registry: false },
46+
])("fills only missing discovery stores (auth=$auth, registry=$registry)", async (supplied) => {
47+
const generation = createModelGenerationFixture({ config: {}, label: "stores" });
48+
const { preparedModelRuntime } = generation;
49+
const stores = preparedModelRuntime.createStores();
50+
stores.authStorage.setRuntimeApiKey(generation.provider, "fixture-runtime-key");
51+
const preparedStores = vi.spyOn(preparedModelRuntime, "createStores");
52+
const emptyAuth = vi.spyOn(AuthStorage, "inMemory");
53+
const emptyRegistry = vi.spyOn(ModelRegistry, "inMemory");
54+
55+
const result = await resolveModelAsync(
56+
generation.provider,
57+
generation.modelId,
58+
preparedModelRuntime.agentDir,
59+
preparedModelRuntime.config,
60+
{
61+
...(supplied.auth ? { authStorage: stores.authStorage } : {}),
62+
...(supplied.registry ? { modelRegistry: stores.modelRegistry } : {}),
63+
preparedModelRuntime,
64+
skipAgentDiscovery: true,
65+
workspaceDir: preparedModelRuntime.workspaceDir,
66+
},
67+
);
68+
69+
expect(preparedStores).not.toHaveBeenCalled();
70+
const allocations = supplied.auth && supplied.registry ? 0 : 1;
71+
expect(emptyAuth).toHaveBeenCalledTimes(allocations);
72+
expect(emptyRegistry).toHaveBeenCalledTimes(allocations);
73+
expect(result.authStorage === stores.authStorage).toBe(supplied.auth);
74+
expect(result.modelRegistry === stores.modelRegistry).toBe(supplied.registry);
75+
const model = expectDefined(result.model, "resolved fixture model");
76+
expect(await result.modelRegistry.getApiKeyAndHeaders(model)).toMatchObject({
77+
apiKey: supplied.auth || supplied.registry ? "fixture-runtime-key" : undefined,
78+
});
79+
});
80+
3881
it("keeps alias, suppression, static metadata, and runtime hooks on the prepared generation", async () => {
3982
const config = {} satisfies OpenClawConfig;
4083
const generationA = createModelGenerationFixture({ config, label: "a" });

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

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,7 @@ import {
1414
loadPreparedModelRuntimeSnapshot,
1515
type PreparedModelRuntimeSnapshot,
1616
} from "../prepared-model-runtime.js";
17-
import {
18-
AuthStorage as AgentAuthStorageClass,
19-
ModelRegistry as AgentModelRegistryClass,
20-
type AuthStorage,
21-
type ModelRegistry,
22-
} from "../sessions/index.js";
17+
import { AuthStorage, ModelRegistry } from "../sessions/index.js";
2318
import { mergeModelMediaInput } from "./model.compat.js";
2419
import { buildConfiguredFallbackModel } from "./model.configured-fallback.js";
2520
import {
@@ -74,15 +69,8 @@ export function createEmptyAgentDiscoveryStores(): {
7469
authStorage: AuthStorage;
7570
modelRegistry: ModelRegistry;
7671
} {
77-
const authStorage =
78-
typeof AgentAuthStorageClass.inMemory === "function"
79-
? AgentAuthStorageClass.inMemory({})
80-
: AgentAuthStorageClass.create();
81-
const modelRegistry =
82-
typeof AgentModelRegistryClass.inMemory === "function"
83-
? AgentModelRegistryClass.inMemory(authStorage)
84-
: AgentModelRegistryClass.create(authStorage);
85-
return { authStorage, modelRegistry };
72+
const authStorage = AuthStorage.inMemory({});
73+
return { authStorage, modelRegistry: ModelRegistry.inMemory(authStorage) };
8674
}
8775

8876
function resolvePreparedAgentSnapshot(
@@ -163,18 +151,17 @@ export async function resolveModelAsync(
163151
const workspaceDir =
164152
options?.workspaceDir ?? preparedModelRuntime?.workspaceDir ?? derivedWorkspaceDir;
165153
const normalizedRef = normalizeProviderModelRef({ provider, modelId, cfg, workspaceDir });
166-
const preparedStores =
167-
!options?.authStorage || !options?.modelRegistry
168-
? preparedModelRuntime?.createStores()
169-
: undefined;
170-
const fallbackStores =
171-
emptyDiscoveryStores ?? preparedStores ?? createEmptyAgentDiscoveryStores();
172-
const authStorage = options?.authStorage ?? fallbackStores.authStorage;
173-
const modelRegistry =
174-
options?.modelRegistry ??
175-
(options?.authStorage
176-
? fallbackStores.modelRegistry.fork(authStorage)
177-
: fallbackStores.modelRegistry);
154+
let { authStorage, modelRegistry } = options ?? {};
155+
if (!authStorage || !modelRegistry) {
156+
const stores =
157+
emptyDiscoveryStores ??
158+
preparedModelRuntime?.createStores() ??
159+
createEmptyAgentDiscoveryStores();
160+
authStorage ??= stores.authStorage;
161+
modelRegistry ??= options?.authStorage
162+
? stores.modelRegistry.fork(authStorage)
163+
: stores.modelRegistry;
164+
}
178165
const runtimeHooks = resolveRuntimeHooks(options);
179166
let staticCatalogResolved = false;
180167
let staticCatalogModel: StaticCatalogFallbackModel | undefined;

‎src/agents/prepared-model-catalog.scoped-thinking.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// Boundary proof for the turn-path thinking fallback: manifest first, then a provider-scoped
2-
// static catalog, then scoped live discovery only for runtime-only models (e.g. Ollama).
1+
// Turn-path thinking reuses published facts before manifest/scoped discovery fallback.
32
import { beforeEach, describe, expect, it, vi } from "vitest";
43

54
const manifestCatalogMock = vi.fn((..._args: unknown[]): Array<Record<string, unknown>> => []);
@@ -90,6 +89,7 @@ describe("loadProviderScopedThinkingCatalog", () => {
9089
});
9190

9291
expect(catalog[0]?.compat?.supportedReasoningEfforts).toContain("ultra");
92+
expect(manifestCatalogMock).not.toHaveBeenCalled();
9393
expect(scopedStaticMock).not.toHaveBeenCalled();
9494
expect(scopedLiveMock).not.toHaveBeenCalled();
9595
});

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

Lines changed: 9 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,7 @@ export function getPreparedModelCatalogOwnerSnapshot(
163163
if (publishedFull && preparedModelRuntimeConfigsMatch(publishedFull.config, full.config)) {
164164
return publishedFull;
165165
}
166-
if (activationFull && activationFull.workspaceDir !== full.workspaceDir) {
166+
if (activationFull.workspaceDir !== full.workspaceDir) {
167167
const activatedFull = getPreparedModelRuntimeSnapshot(activationFull);
168168
if (activatedFull && preparedModelRuntimeConfigsMatch(activatedFull.config, full.config)) {
169169
return activatedFull;
@@ -176,7 +176,7 @@ export function getPreparedModelCatalogOwnerSnapshot(
176176
if (publishedExact && preparedModelRuntimeConfigsMatch(publishedExact.config, exact.config)) {
177177
return publishedExact;
178178
}
179-
if (!activationExact || activationExact.workspaceDir === exact.workspaceDir) {
179+
if (activationExact.workspaceDir === exact.workspaceDir) {
180180
return undefined;
181181
}
182182
const activatedExact = getPreparedModelRuntimeSnapshot(activationExact);
@@ -250,22 +250,6 @@ async function resolvePreparedModelCatalogOwnerSnapshotWithPolicy(
250250
lease.release();
251251
}
252252
}
253-
if (exact !== full) {
254-
const fullCandidates =
255-
activationFull.workspaceDir === full.workspaceDir ? [full] : [full, activationFull];
256-
for (const candidate of fullCandidates) {
257-
try {
258-
const preparedFull = await prepareModelRuntimeSnapshot(candidate);
259-
if (acceptsPreparedSnapshotConfig(preparedFull, full, configPolicy)) {
260-
return preparedFull;
261-
}
262-
} catch (error) {
263-
if (!(error instanceof PreparedModelRuntimeOwnerNotPublishedError)) {
264-
throw error;
265-
}
266-
}
267-
}
268-
}
269253
try {
270254
const preparedExact = await prepareModelRuntimeSnapshot(exact);
271255
if (acceptsPreparedSnapshotConfig(preparedExact, exact, configPolicy)) {
@@ -363,13 +347,6 @@ export async function loadProviderScopedThinkingCatalog(params: {
363347
agentDir?: string;
364348
workspaceDir?: string;
365349
}): Promise<ModelCatalogEntry[]> {
366-
const { loadManifestModelCatalog } = await import("./model-catalog.js");
367-
const manifestCatalog = normalizeThinkingCatalogProviders(
368-
loadManifestModelCatalog({
369-
config: params.config,
370-
...(params.workspaceDir ? { workspaceDir: params.workspaceDir } : {}),
371-
}),
372-
);
373350
const scopedParams = {
374351
config: params.config,
375352
...(params.agentId ? { agentId: params.agentId } : {}),
@@ -401,6 +378,13 @@ export async function loadProviderScopedThinkingCatalog(params: {
401378
if (publishedCatalog && entryResolved(publishedCatalog.entries)) {
402379
return await augmentHarnessCatalog(publishedCatalog);
403380
}
381+
const { loadManifestModelCatalog } = await import("./model-catalog.js");
382+
const manifestCatalog = normalizeThinkingCatalogProviders(
383+
loadManifestModelCatalog({
384+
config: params.config,
385+
...(params.workspaceDir ? { workspaceDir: params.workspaceDir } : {}),
386+
}),
387+
);
404388
if (entryResolved(manifestCatalog)) {
405389
return await augmentHarnessCatalog({
406390
entries: manifestCatalog,

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

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import {
22
getPreparedRuntimeAuthMaterializations,
33
registerRuntimeAuthMaterializationMutationListener,
4-
type RuntimeAuthMaterialization,
54
} from "./auth-profiles/runtime-materializations.js";
65
import { setPreparedModelRuntimeAuthMaterializations } from "./prepared-model-runtime-auth.js";
76
import {
@@ -47,7 +46,6 @@ function publishPreparedRuntimeAuthMaterializations(params: {
4746
owners: ReadonlyMap<string, PreparedModelRuntimeOwner>;
4847
onInvalidated: () => void;
4948
onPublished: () => void;
50-
read?: (agentDir?: string) => readonly RuntimeAuthMaterialization[];
5149
}): void {
5250
const event = {
5351
...params.event,
@@ -65,13 +63,12 @@ function publishPreparedRuntimeAuthMaterializations(params: {
6563
if (affectedOwners.length === 0) {
6664
return;
6765
}
68-
const read = params.read ?? getPreparedRuntimeAuthMaterializations;
6966
for (const { owner, snapshot } of affectedOwners) {
7067
// A successful route only changes this bounded secret-free fact set. Rebuilding the model
7168
// catalog here would pull plugin lifecycle work into the turn-completion boundary.
7269
setPreparedModelRuntimeAuthMaterializations(
7370
snapshot,
74-
Object.freeze([...read(owner.input.agentDir)]),
71+
Object.freeze([...getPreparedRuntimeAuthMaterializations(owner.input.agentDir)]),
7572
);
7673
}
7774
// Chat metadata treats published as "every configured owner is capturable".

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

Lines changed: 17 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -117,23 +117,11 @@ export async function loadPreparedModelRuntimeSnapshot(
117117
throw error;
118118
}
119119
}
120-
const activationGate = pendingModelRuntimeReplacement;
121-
if (activationGate) {
122-
await activationGate.promise;
123-
if (pendingModelRuntimeReplacement) {
124-
continue;
125-
}
126-
input = rebindInputToCommittedConfiguredOwner(owners, input);
120+
if (pendingModelRuntimeReplacement) {
127121
continue;
128122
}
129123
const activated = await activateStandalonePreparedModelRuntime(input);
130-
const replacementAfterActivation = pendingModelRuntimeReplacement;
131-
if (replacementAfterActivation) {
132-
await replacementAfterActivation.promise;
133-
if (pendingModelRuntimeReplacement) {
134-
continue;
135-
}
136-
input = rebindInputToCommittedConfiguredOwner(owners, input);
124+
if (pendingModelRuntimeReplacement) {
137125
continue;
138126
}
139127
if (!activated) {
@@ -185,29 +173,21 @@ export async function publishPreparedModelRuntimeSnapshot(
185173
if (!options.force && hasSameLifecycleInput(existing.input, input)) {
186174
return await existing.pending;
187175
}
188-
return await publishModelRuntimeSnapshot(
189-
input,
190-
owners,
191-
agentBuildCompletions,
192-
modelRuntimeBuildTimeoutMs,
193-
existing,
194-
options.provenance,
195-
options.catalogMode,
196-
);
197-
}
198-
if (existing?.buildCompletion) {
199-
throw (
200-
existing.refreshError ??
201-
new Error(`prepared model runtime build is still settling for ${input.agentDir}`)
202-
);
203-
}
204-
if (
205-
existing?.snapshot &&
206-
!existing.needsRefresh &&
207-
!options.force &&
208-
hasSameLifecycleInput(existing.input, input)
209-
) {
210-
return existing.snapshot;
176+
} else {
177+
if (existing?.buildCompletion) {
178+
throw (
179+
existing.refreshError ??
180+
new Error(`prepared model runtime build is still settling for ${input.agentDir}`)
181+
);
182+
}
183+
if (
184+
existing?.snapshot &&
185+
!existing.needsRefresh &&
186+
!options.force &&
187+
hasSameLifecycleInput(existing.input, input)
188+
) {
189+
return existing.snapshot;
190+
}
211191
}
212192
return await publishModelRuntimeSnapshot(
213193
input,

0 commit comments

Comments
 (0)