Skip to content

Commit 922f701

Browse files
perf(gateway): bound prepared runtime startup work
1 parent 3e67671 commit 922f701

56 files changed

Lines changed: 4811 additions & 922 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎scripts/bench-gateway-startup.ts‎

Lines changed: 182 additions & 21 deletions
Large diffs are not rendered by default.

‎src/agents/agent-auth-discovery.external-cli.test.ts‎

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,6 @@ import type { OpenClawConfig } from "../config/types.openclaw.js";
55
const storeMocks = vi.hoisted(() => ({
66
ensureAuthProfileStore: vi.fn(() => ({ version: 1, profiles: {} })),
77
ensureAuthProfileStoreWithoutExternalProfiles: vi.fn(() => ({ version: 1, profiles: {} })),
8-
loadAuthProfileStoreWithoutExternalProfiles: vi.fn(() => ({ version: 1, profiles: {} })),
9-
loadAuthProfileStoreForRuntime: vi.fn(() => ({ version: 1, profiles: {} })),
10-
loadAuthProfileStoreForSecretsRuntime: vi.fn(() => ({ version: 1, profiles: {} })),
118
}));
129

1310
const credentialMocks = vi.hoisted(() => ({
@@ -44,6 +41,7 @@ import { externalCliDiscoveryForProviders } from "./auth-profiles/external-cli-d
4441
describe("resolveAgentCredentialsForDiscovery external CLI scoping", () => {
4542
beforeEach(() => {
4643
vi.clearAllMocks();
44+
credentialMocks.resolveAgentCredentialMapFromStore.mockReturnValue({});
4745
});
4846

4947
it("threads scoped external CLI discovery into writable auth store loading", () => {
@@ -64,10 +62,9 @@ describe("resolveAgentCredentialsForDiscovery external CLI scoping", () => {
6462
config: cfg,
6563
externalCli,
6664
});
67-
expect(storeMocks.loadAuthProfileStoreForRuntime).not.toHaveBeenCalled();
6865
});
6966

70-
it("preserves scoped external CLI discovery for read-only auth store loading", () => {
67+
it("reuses the active runtime generation for read-only auth discovery", () => {
7168
const cfg = {} as OpenClawConfig;
7269
const externalCli = externalCliDiscoveryForProviders({
7370
cfg,
@@ -81,14 +78,37 @@ describe("resolveAgentCredentialsForDiscovery external CLI scoping", () => {
8178
readOnly: true,
8279
});
8380

84-
expect(storeMocks.loadAuthProfileStoreForRuntime).toHaveBeenCalledWith("/tmp/openclaw-agent", {
81+
expect(storeMocks.ensureAuthProfileStore).toHaveBeenCalledWith("/tmp/openclaw-agent", {
8582
allowKeychainPrompt: false,
8683
config: cfg,
8784
externalCli,
8885
readOnly: true,
8986
});
9087
});
9188

89+
it("merges prepared ambient credentials without repeating ambient discovery", () => {
90+
credentialMocks.resolveAgentCredentialMapFromStore.mockReturnValue({
91+
fireworks: { type: "api_key", key: "agent-key" },
92+
});
93+
94+
const credentials = resolveAgentCredentialsForDiscovery("/tmp/openclaw-agent", {
95+
ambientCredentials: {
96+
fireworks: { type: "api_key", key: "ambient-key" },
97+
"claude-cli": { type: "api_key", key: "synthetic-key" },
98+
},
99+
env: {},
100+
readOnly: true,
101+
});
102+
103+
expect(credentials).toEqual({
104+
fireworks: { type: "api_key", key: "agent-key" },
105+
"claude-cli": { type: "api_key", key: "synthetic-key" },
106+
});
107+
expect(discoveryCoreMocks.addEnvBackedAgentCredentials).not.toHaveBeenCalled();
108+
expect(syntheticAuthMocks.resolveRuntimeSyntheticAuthProviderRefs).not.toHaveBeenCalled();
109+
expect(syntheticAuthMocks.resolveProviderSyntheticAuthWithPlugin).not.toHaveBeenCalled();
110+
});
111+
92112
it("can skip runtime external auth overlays and scope synthetic auth discovery", () => {
93113
resolveAgentCredentialsForDiscovery("/tmp/openclaw-agent", {
94114
env: {},
@@ -106,6 +126,9 @@ describe("resolveAgentCredentialsForDiscovery external CLI scoping", () => {
106126
expect(syntheticAuthMocks.resolveRuntimeSyntheticAuthProviderRefs).not.toHaveBeenCalled();
107127
expect(syntheticAuthMocks.resolveProviderSyntheticAuthWithPlugin).toHaveBeenCalledWith({
108128
provider: "fireworks",
129+
config: undefined,
130+
workspaceDir: undefined,
131+
env: {},
109132
context: {
110133
config: undefined,
111134
provider: "fireworks",

‎src/agents/agent-auth-discovery.ts‎

Lines changed: 73 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,11 @@ import type { ExternalCliAuthDiscovery } from "./auth-profiles/external-cli-disc
1414
import {
1515
ensureAuthProfileStore,
1616
ensureAuthProfileStoreWithoutExternalProfiles,
17-
loadAuthProfileStoreWithoutExternalProfiles,
18-
loadAuthProfileStoreForRuntime,
19-
loadAuthProfileStoreForSecretsRuntime,
2017
} from "./auth-profiles/store.js";
2118

2219
/** Options for discovering credentials without prompting for secret material. */
2320
export type DiscoverAuthStorageOptions = {
21+
ambientCredentials?: Readonly<AgentCredentialMap>;
2422
externalCli?: ExternalCliAuthDiscovery;
2523
inheritedAuthDir?: string;
2624
readOnly?: boolean;
@@ -29,73 +27,50 @@ export type DiscoverAuthStorageOptions = {
2927
syntheticAuthProviderRefs?: Iterable<string>;
3028
} & AgentDiscoveryAuthLookupOptions;
3129

32-
/** Resolves agent credentials from auth profiles, env, and synthetic auth hooks. */
33-
export function resolveAgentCredentialsForDiscovery(
34-
agentDir: string,
35-
options?: DiscoverAuthStorageOptions,
30+
type AmbientAgentCredentialOptions = AgentDiscoveryAuthLookupOptions & {
31+
resolveSyntheticAuth?: (provider: string) => { apiKey?: string } | undefined;
32+
syntheticAuthProviderRefs?: Iterable<string>;
33+
};
34+
35+
/** Resolves workspace/config/env-stable credentials independently of agent-local profiles. */
36+
export function resolveAmbientAgentCredentialsForDiscovery(
37+
options: AmbientAgentCredentialOptions = {},
3638
): AgentCredentialMap {
37-
const storeOptions = {
38-
allowKeychainPrompt: false,
39-
...(options?.config ? { config: options.config } : {}),
40-
...(options?.externalCli ? { externalCli: options.externalCli } : {}),
41-
...(options?.inheritedAuthDir ? { inheritedAuthDir: options.inheritedAuthDir } : {}),
42-
};
43-
const store =
44-
options?.skipExternalAuthProfiles === true
45-
? options.readOnly === true
46-
? loadAuthProfileStoreWithoutExternalProfiles(
47-
agentDir,
48-
options.inheritedAuthDir ? { inheritedAuthDir: options.inheritedAuthDir } : undefined,
49-
)
50-
: ensureAuthProfileStoreWithoutExternalProfiles(agentDir, {
51-
allowKeychainPrompt: false,
52-
...(options?.inheritedAuthDir ? { inheritedAuthDir: options.inheritedAuthDir } : {}),
53-
})
54-
: options?.readOnly === true
55-
? options.externalCli || options.config || options.inheritedAuthDir
56-
? loadAuthProfileStoreForRuntime(agentDir, { readOnly: true, ...storeOptions })
57-
: loadAuthProfileStoreForSecretsRuntime(agentDir)
58-
: ensureAuthProfileStore(agentDir, storeOptions);
59-
const credentials = addEnvBackedAgentCredentials(
60-
resolveAgentCredentialMapFromStore(store, {
61-
includeSecretRefPlaceholders: options?.readOnly === true,
62-
config: options?.config,
63-
}),
64-
{
65-
config: options?.config,
66-
workspaceDir: options?.workspaceDir,
67-
env: options?.env,
68-
},
69-
);
39+
const credentials = addEnvBackedAgentCredentials({}, options);
7040
const syntheticAuthProviderRefs =
71-
options?.syntheticAuthProviderRefs ?? resolveRuntimeSyntheticAuthProviderRefs();
41+
options.syntheticAuthProviderRefs ?? resolveRuntimeSyntheticAuthProviderRefs();
42+
const resolveSyntheticAuth =
43+
options.resolveSyntheticAuth ??
44+
((provider: string) =>
45+
resolveProviderSyntheticAuthWithPlugin({
46+
provider,
47+
config: options.config,
48+
workspaceDir: options.workspaceDir,
49+
env: options.env,
50+
context: {
51+
config: options.config,
52+
provider,
53+
providerConfig: options.config?.models?.providers?.[provider],
54+
},
55+
}));
7256
for (const provider of syntheticAuthProviderRefs) {
7357
if (credentials[provider]) {
7458
continue;
7559
}
7660
if (
7761
!isAmbientCredentialAllowedByProviderAuthPin({
78-
config: options?.config,
62+
config: options.config,
7963
authAliasLookupParams: {
80-
...(options?.env ? { env: options.env } : {}),
81-
...(options?.workspaceDir ? { workspaceDir: options.workspaceDir } : {}),
64+
...(options.env ? { env: options.env } : {}),
65+
...(options.workspaceDir ? { workspaceDir: options.workspaceDir } : {}),
8266
},
8367
provider,
8468
type: "api_key",
8569
})
8670
) {
8771
continue;
8872
}
89-
// Synthetic auth is a plugin/runtime fallback. Only fill empty providers so
90-
// persisted profiles and env-backed credentials remain authoritative.
91-
const resolved = resolveProviderSyntheticAuthWithPlugin({
92-
provider,
93-
context: {
94-
config: undefined,
95-
provider,
96-
providerConfig: undefined,
97-
},
98-
});
73+
const resolved = resolveSyntheticAuth(provider);
9974
const apiKey = resolved?.apiKey?.trim();
10075
if (!apiKey) {
10176
continue;
@@ -107,3 +82,47 @@ export function resolveAgentCredentialsForDiscovery(
10782
}
10883
return credentials;
10984
}
85+
86+
/** Resolves agent credentials from auth profiles, env, and synthetic auth hooks. */
87+
export function resolveAgentCredentialsForDiscovery(
88+
agentDir: string,
89+
options?: DiscoverAuthStorageOptions,
90+
): AgentCredentialMap {
91+
const storeOptions = {
92+
allowKeychainPrompt: false,
93+
...(options?.config ? { config: options.config } : {}),
94+
...(options?.externalCli ? { externalCli: options.externalCli } : {}),
95+
...(options?.inheritedAuthDir ? { inheritedAuthDir: options.inheritedAuthDir } : {}),
96+
};
97+
const store =
98+
options?.skipExternalAuthProfiles === true
99+
? ensureAuthProfileStoreWithoutExternalProfiles(agentDir, {
100+
allowKeychainPrompt: false,
101+
...(options?.inheritedAuthDir ? { inheritedAuthDir: options.inheritedAuthDir } : {}),
102+
...(options?.readOnly === true ? { readOnly: true } : {}),
103+
})
104+
: ensureAuthProfileStore(agentDir, {
105+
...storeOptions,
106+
...(options?.readOnly === true ? { readOnly: true } : {}),
107+
});
108+
const credentials = resolveAgentCredentialMapFromStore(store, {
109+
includeSecretRefPlaceholders: options?.readOnly === true,
110+
config: options?.config,
111+
});
112+
const ambientCredentials =
113+
options?.ambientCredentials ??
114+
resolveAmbientAgentCredentialsForDiscovery({
115+
config: options?.config,
116+
workspaceDir: options?.workspaceDir,
117+
env: options?.env,
118+
syntheticAuthProviderRefs: options?.syntheticAuthProviderRefs,
119+
});
120+
for (const [provider, credential] of Object.entries(ambientCredentials)) {
121+
if (credentials[provider]) {
122+
continue;
123+
}
124+
// Ambient auth is a lifecycle-owned fallback. Agent-local profiles remain authoritative.
125+
credentials[provider] = credential;
126+
}
127+
return credentials;
128+
}

‎src/agents/agent-model-discovery.synthetic-auth.test.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ vi.mock("../plugins/provider-runtime.js", () => ({
3131

3232
vi.mock("./auth-profiles/store.js", () => ({
3333
ensureAuthProfileStore: () => ({ version: 1, profiles: {} }),
34-
loadAuthProfileStoreForSecretsRuntime: () => ({ version: 1, profiles: {} }),
34+
ensureAuthProfileStoreWithoutExternalProfiles: () => ({ version: 1, profiles: {} }),
3535
}));
3636

3737
vi.mock("./agent-auth-discovery-core.js", () => ({
@@ -74,6 +74,9 @@ describe("agent model discovery synthetic auth", () => {
7474
expect(resolveProviderSyntheticAuthWithPlugin).toHaveBeenCalledTimes(1);
7575
expect(resolveProviderSyntheticAuthWithPlugin).toHaveBeenCalledWith({
7676
provider: "claude-cli",
77+
config: undefined,
78+
workspaceDir: undefined,
79+
env: undefined,
7780
context: {
7881
config: undefined,
7982
provider: "claude-cli",

‎src/agents/agent-model-discovery.test.ts‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,11 @@ import path from "node:path";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import type { OpenClawConfig } from "../config/types.openclaw.js";
77
import { clearCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-state.js";
8-
import { discoverAuthStorage, discoverModels } from "./agent-model-discovery.js";
8+
import {
9+
discoverAuthStorage,
10+
discoverModels,
11+
discoverModelsFromCapturedSources,
12+
} from "./agent-model-discovery.js";
913

1014
// Discovery must not cold-load bundled plugin runtime: with build artifacts
1115
// present, the openai plugin's normalizeResolvedModel currently overrides
@@ -37,6 +41,33 @@ function writeModelsJson(agentDir: string, modelId: string): void {
3741
}
3842

3943
describe("discoverModels", () => {
44+
it("uses a directory-independent source label for lifecycle-captured catalogs", () => {
45+
const firstAgentDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-models-first-"));
46+
const secondAgentDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-models-second-"));
47+
try {
48+
const createRegistry = (agentDir: string) =>
49+
discoverModelsFromCapturedSources(
50+
discoverAuthStorage(agentDir, { skipCredentials: true }),
51+
{
52+
includePluginCatalogs: true,
53+
modelsJsonContents: "not valid json",
54+
pluginCatalogs: [],
55+
},
56+
);
57+
58+
const firstError = createRegistry(firstAgentDir).getError();
59+
const secondError = createRegistry(secondAgentDir).getError();
60+
61+
expect(firstError).toBe(secondError);
62+
expect(firstError).toContain("captured:models.json");
63+
expect(firstError).not.toContain(firstAgentDir);
64+
expect(secondError).not.toContain(secondAgentDir);
65+
} finally {
66+
fs.rmSync(firstAgentDir, { recursive: true, force: true });
67+
fs.rmSync(secondAgentDir, { recursive: true, force: true });
68+
}
69+
});
70+
4071
it("clears cached find results when the agent model registry refreshes", () => {
4172
const agentDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-agent-models-"));
4273
writeModelsJson(agentDir, "old-model");

0 commit comments

Comments
 (0)