Skip to content

Commit 4e7de4b

Browse files
committed
feat: reuse current plugin metadata for provider discovery
1 parent a478ab3 commit 4e7de4b

10 files changed

Lines changed: 305 additions & 3 deletions

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Docs: https://docs.openclaw.ai
99
- Plugins/models: wire manifest `modelCatalog.aliases` and `modelCatalog.suppressions` into model-catalog planning and built-in model suppression, with OpenAI stale Spark suppression now declared in the plugin manifest before runtime fallback. Thanks @shakkernerd.
1010
- Channels/Yuanbao: register the Tencent Yuanbao external channel plugin (`openclaw-plugin-yuanbao`) in the official channel catalog, contract suites, and community plugin docs, with a new `docs/channels/yuanbao.md` quick-start guide for WebSocket bot DMs and group chats. (#72756) Thanks @loongfay.
1111
- Channels/QQBot: add full group chat support (history tracking, @-mention gating, activation modes, per-group config, FIFO message queue with deliver debounce), C2C `stream_messages` streaming with a `StreamingController` lifecycle manager, unified `sendMedia` with chunked upload for large files, and refactor the engine into pipeline stages, focused outbound submodules, builtin slash-command modules, and explicit DI ports via `createEngineAdapters()`. (#70624) Thanks @cxyhhhhh.
12+
- Gateway/runtime: reuse the current plugin metadata snapshot for provider discovery so repeated model-provider discovery avoids rebuilding plugin manifest metadata. Thanks @shakkernerd.
1213
- Gateway/startup: pass the plugin metadata snapshot from config validation into plugin bootstrap so startup reuses one manifest product instead of rebuilding plugin metadata. Thanks @shakkernerd.
1314

1415
## 2026.4.26

‎docs/plugins/architecture.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ Gateway startup builds one `PluginMetadataSnapshot` for the current config snaps
151151

152152
Plugin-aware config validation, startup auto-enable, and Gateway plugin bootstrap consume that snapshot instead of rebuilding manifest/index metadata independently. `PluginLookUpTable` is derived from the same snapshot and adds the startup plugin plan for the current runtime config.
153153

154+
After startup, Gateway keeps the current metadata snapshot as a replaceable runtime product. Repeated runtime provider discovery can borrow that snapshot instead of reconstructing the installed index and manifest registry for each provider-catalog pass. The snapshot is cleared or replaced on Gateway shutdown, config/plugin inventory changes, and installed index writes; callers fall back to the cold manifest/index path when no compatible current snapshot exists.
155+
154156
The snapshot and lookup table keep repeated startup decisions on the fast path:
155157

156158
- channel ownership

‎src/agents/models-config.applies-config-env-vars.test.ts‎

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
11
import { describe, expect, it } from "vitest";
22
import type { OpenClawConfig } from "../config/config.js";
33
import { createConfigRuntimeEnv } from "../config/env-vars.js";
4+
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
45
import { unsetEnv, withTempEnv } from "./models-config.e2e-harness.js";
5-
import { resolveProvidersForModelsJsonWithDeps } from "./models-config.plan.js";
6+
import {
7+
planOpenClawModelsJsonWithDeps,
8+
resolveProvidersForModelsJsonWithDeps,
9+
} from "./models-config.plan.js";
610
import type { ProviderConfig } from "./models-config.providers.secrets.js";
711

812
const TEST_ENV_VAR = "OPENCLAW_MODELS_CONFIG_TEST_ENV";
@@ -72,6 +76,64 @@ async function resolveProvidersAndCaptureDiscoveryEnv(cfg: OpenClawConfig) {
7276
}
7377

7478
describe("models-config", () => {
79+
it("threads plugin metadata snapshots into implicit provider discovery", async () => {
80+
const pluginMetadataSnapshot = {
81+
index: { plugins: [] },
82+
manifestRegistry: { plugins: [], diagnostics: [] },
83+
owners: { providers: new Map() },
84+
} as unknown as Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">;
85+
let observedSnapshot:
86+
| Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">
87+
| undefined;
88+
89+
await resolveProvidersForModelsJsonWithDeps(
90+
{
91+
cfg: { models: { providers: {} } },
92+
agentDir: "/tmp/openclaw-models-config-env-vars-test",
93+
env: {},
94+
pluginMetadataSnapshot,
95+
},
96+
{
97+
resolveImplicitProviders: async ({ pluginMetadataSnapshot: receivedSnapshot }) => {
98+
observedSnapshot = receivedSnapshot;
99+
return {};
100+
},
101+
},
102+
);
103+
104+
expect(observedSnapshot).toBe(pluginMetadataSnapshot);
105+
});
106+
107+
it("threads plugin metadata snapshots through models.json planning", async () => {
108+
const pluginMetadataSnapshot = {
109+
index: { plugins: [] },
110+
manifestRegistry: { plugins: [], diagnostics: [] },
111+
owners: { providers: new Map() },
112+
} as unknown as Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">;
113+
let observedSnapshot:
114+
| Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">
115+
| undefined;
116+
117+
await planOpenClawModelsJsonWithDeps(
118+
{
119+
cfg: { models: { providers: {} } },
120+
agentDir: "/tmp/openclaw-models-config-env-vars-test",
121+
env: {},
122+
existingRaw: "",
123+
existingParsed: null,
124+
pluginMetadataSnapshot,
125+
},
126+
{
127+
resolveImplicitProviders: async ({ pluginMetadataSnapshot: receivedSnapshot }) => {
128+
observedSnapshot = receivedSnapshot;
129+
return {};
130+
},
131+
},
132+
);
133+
134+
expect(observedSnapshot).toBe(pluginMetadataSnapshot);
135+
});
136+
75137
it("uses config env.vars entries for implicit provider discovery without mutating process.env", async () => {
76138
await withTempEnv(["OPENROUTER_API_KEY", TEST_ENV_VAR], async () => {
77139
unsetEnv(["OPENROUTER_API_KEY", TEST_ENV_VAR]);

‎src/agents/models-config.plan.ts‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { OpenClawConfig } from "../config/types.openclaw.js";
2+
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
23
import { isRecord } from "../utils.js";
34
import {
45
mergeProviders,
@@ -19,6 +20,7 @@ export type ResolveImplicitProvidersForModelsJson = (params: {
1920
config: OpenClawConfig;
2021
env: NodeJS.ProcessEnv;
2122
explicitProviders: Record<string, ProviderConfig>;
23+
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">;
2224
}) => Promise<Record<string, ProviderConfig>>;
2325

2426
export type ModelsJsonPlan =
@@ -38,6 +40,7 @@ export async function resolveProvidersForModelsJsonWithDeps(
3840
cfg: OpenClawConfig;
3941
agentDir: string;
4042
env: NodeJS.ProcessEnv;
43+
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">;
4144
},
4245
deps?: {
4346
resolveImplicitProviders?: ResolveImplicitProvidersForModelsJson;
@@ -51,6 +54,9 @@ export async function resolveProvidersForModelsJsonWithDeps(
5154
config: cfg,
5255
env,
5356
explicitProviders,
57+
...(params.pluginMetadataSnapshot
58+
? { pluginMetadataSnapshot: params.pluginMetadataSnapshot }
59+
: {}),
5460
});
5561
return mergeProviders({
5662
implicit: implicitProviders,
@@ -90,13 +96,24 @@ export async function planOpenClawModelsJsonWithDeps(
9096
env: NodeJS.ProcessEnv;
9197
existingRaw: string;
9298
existingParsed: unknown;
99+
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">;
93100
},
94101
deps?: {
95102
resolveImplicitProviders?: ResolveImplicitProvidersForModelsJson;
96103
},
97104
): Promise<ModelsJsonPlan> {
98105
const { cfg, agentDir, env } = params;
99-
const providers = await resolveProvidersForModelsJsonWithDeps({ cfg, agentDir, env }, deps);
106+
const providers = await resolveProvidersForModelsJsonWithDeps(
107+
{
108+
cfg,
109+
agentDir,
110+
env,
111+
...(params.pluginMetadataSnapshot
112+
? { pluginMetadataSnapshot: params.pluginMetadataSnapshot }
113+
: {}),
114+
},
115+
deps,
116+
);
100117

101118
if (Object.keys(providers).length === 0) {
102119
return { action: "skip" };

‎src/agents/models-config.providers.implicit.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { OpenClawConfig } from "../config/types.openclaw.js";
22
import { formatErrorMessage } from "../infra/errors.js";
33
import { createSubsystemLogger } from "../logging/subsystem.js";
4+
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
45
import {
56
groupPluginDiscoveryProvidersByOrder,
67
normalizePluginDiscoveryResult,
@@ -43,6 +44,7 @@ type ImplicitProviderParams = {
4344
env?: NodeJS.ProcessEnv;
4445
workspaceDir?: string;
4546
explicitProviders?: Record<string, ProviderConfig> | null;
47+
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">;
4648
};
4749

4850
type ImplicitProviderContext = ImplicitProviderParams & {
@@ -367,7 +369,13 @@ export async function resolveImplicitProviders(
367369
config: params.config,
368370
workspaceDir: params.workspaceDir,
369371
env,
372+
resolveOwners: params.pluginMetadataSnapshot
373+
? (provider) => params.pluginMetadataSnapshot?.owners.providers.get(provider)
374+
: undefined,
370375
}),
376+
...(params.pluginMetadataSnapshot
377+
? { pluginMetadataSnapshot: params.pluginMetadataSnapshot }
378+
: {}),
371379
});
372380

373381
for (const order of PLUGIN_DISCOVERY_ORDERS) {

‎src/agents/models-config.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@ import {
77
type OpenClawConfig,
88
} from "../config/config.js";
99
import { createConfigRuntimeEnv } from "../config/env-vars.js";
10+
import { getCurrentPluginMetadataSnapshot } from "../plugins/current-plugin-metadata-snapshot.js";
11+
import { resolveInstalledManifestRegistryIndexFingerprint } from "../plugins/manifest-registry-installed.js";
12+
import type { PluginMetadataSnapshot } from "../plugins/plugin-metadata-snapshot.js";
1013
import { resolveOpenClawAgentDir } from "./agent-paths.js";
1114
import { MODELS_JSON_STATE } from "./models-config-state.js";
1215
import { planOpenClawModelsJson } from "./models-config.plan.js";
@@ -41,18 +44,23 @@ async function buildModelsJsonFingerprint(params: {
4144
config: OpenClawConfig;
4245
sourceConfigForSecrets: OpenClawConfig;
4346
agentDir: string;
47+
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "index">;
4448
}): Promise<string> {
4549
const authProfilesMtimeMs = await readFileMtimeMs(
4650
path.join(params.agentDir, "auth-profiles.json"),
4751
);
4852
const modelsFileMtimeMs = await readFileMtimeMs(path.join(params.agentDir, "models.json"));
4953
const envShape = createConfigRuntimeEnv(params.config, {});
54+
const pluginMetadataSnapshotIndexFingerprint = params.pluginMetadataSnapshot
55+
? resolveInstalledManifestRegistryIndexFingerprint(params.pluginMetadataSnapshot.index)
56+
: undefined;
5057
return stableStringify({
5158
config: params.config,
5259
sourceConfigForSecrets: params.sourceConfigForSecrets,
5360
envShape,
5461
authProfilesMtimeMs,
5562
modelsFileMtimeMs,
63+
pluginMetadataSnapshotIndexFingerprint,
5664
});
5765
}
5866

@@ -138,15 +146,21 @@ async function withModelsJsonWriteLock<T>(targetPath: string, run: () => Promise
138146
export async function ensureOpenClawModelsJson(
139147
config?: OpenClawConfig,
140148
agentDirOverride?: string,
149+
options: {
150+
pluginMetadataSnapshot?: Pick<PluginMetadataSnapshot, "index" | "manifestRegistry" | "owners">;
151+
} = {},
141152
): Promise<{ agentDir: string; wrote: boolean }> {
142153
const resolved = resolveModelsConfigInput(config);
143154
const cfg = resolved.config;
155+
const pluginMetadataSnapshot =
156+
options.pluginMetadataSnapshot ?? getCurrentPluginMetadataSnapshot({ config: cfg });
144157
const agentDir = agentDirOverride?.trim() ? agentDirOverride.trim() : resolveOpenClawAgentDir();
145158
const targetPath = path.join(agentDir, "models.json");
146159
const fingerprint = await buildModelsJsonFingerprint({
147160
config: cfg,
148161
sourceConfigForSecrets: resolved.sourceConfigForSecrets,
149162
agentDir,
163+
...(pluginMetadataSnapshot ? { pluginMetadataSnapshot } : {}),
150164
});
151165
const cached = MODELS_JSON_STATE.readyCache.get(targetPath);
152166
if (cached) {
@@ -169,6 +183,7 @@ export async function ensureOpenClawModelsJson(
169183
env,
170184
existingRaw: existingModelsFile.raw,
171185
existingParsed: existingModelsFile.parsed,
186+
...(pluginMetadataSnapshot ? { pluginMetadataSnapshot } : {}),
172187
});
173188

174189
if (plan.action === "skip") {

‎src/gateway/server.impl.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,10 @@ import type { VoiceWakeRoutingConfig } from "../infra/voicewake-routing.js";
3131
import { startDiagnosticHeartbeat, stopDiagnosticHeartbeat } from "../logging/diagnostic.js";
3232
import { createSubsystemLogger, runtimeForLogger } from "../logging/subsystem.js";
3333
import { getActiveBundledRuntimeDepsInstallCount } from "../plugins/bundled-runtime-deps-activity.js";
34+
import {
35+
clearCurrentPluginMetadataSnapshot,
36+
setCurrentPluginMetadataSnapshot,
37+
} from "../plugins/current-plugin-metadata-snapshot.js";
3438
import { runGlobalGatewayStopSafely } from "../plugins/hook-runner-global.js";
3539
import type { PluginRuntime } from "../plugins/runtime/types.js";
3640
import { getTotalQueueSize } from "../process/command-queue.js";
@@ -424,6 +428,7 @@ export async function startGatewayServer(
424428
pluginLookUpTable,
425429
baseMethods,
426430
} = pluginBootstrap;
431+
setCurrentPluginMetadataSnapshot(pluginLookUpTable, { config: gatewayPluginConfigAtStart });
427432
if (pluginLookUpTable) {
428433
const metrics = pluginLookUpTable.metrics;
429434
startupTrace.detail("plugins.lookup-table", [
@@ -640,7 +645,8 @@ export async function startGatewayServer(
640645
});
641646
deps.cron = runtimeState.cronState.cron;
642647

643-
const runClosePrelude = async () =>
648+
const runClosePrelude = async () => {
649+
clearCurrentPluginMetadataSnapshot();
644650
await runGatewayClosePrelude({
645651
...(diagnosticsEnabled ? { stopDiagnostics: stopDiagnosticHeartbeat } : {}),
646652
clearSkillsRefreshTimer: () => {
@@ -658,6 +664,7 @@ export async function startGatewayServer(
658664
clearSecretsRuntimeSnapshot,
659665
closeMcpServer: closeMcpLoopbackServerOnDemand,
660666
});
667+
};
661668
const { getRuntimeSnapshot, startChannels, startChannel, stopChannel, markChannelLoggedOut } =
662669
channelManager;
663670
const createCloseHandler = () =>
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
import fs from "node:fs";
2+
import os from "node:os";
3+
import path from "node:path";
4+
import { describe, expect, it } from "vitest";
5+
import {
6+
clearCurrentPluginMetadataSnapshot,
7+
getCurrentPluginMetadataSnapshot,
8+
setCurrentPluginMetadataSnapshot,
9+
} from "./current-plugin-metadata-snapshot.js";
10+
import { resolveInstalledPluginIndexPolicyHash } from "./installed-plugin-index-policy.js";
11+
import { writePersistedInstalledPluginIndexSync } from "./installed-plugin-index-store.js";
12+
import type { PluginMetadataSnapshot } from "./plugin-metadata-snapshot.js";
13+
14+
function createSnapshot(
15+
params: {
16+
config?: Parameters<typeof resolveInstalledPluginIndexPolicyHash>[0];
17+
workspaceDir?: string;
18+
} = {},
19+
): PluginMetadataSnapshot {
20+
return {
21+
policyHash: resolveInstalledPluginIndexPolicyHash(params.config),
22+
...(params.workspaceDir ? { workspaceDir: params.workspaceDir } : {}),
23+
index: {
24+
version: 1,
25+
hostContractVersion: "test",
26+
compatRegistryVersion: "test",
27+
migrationVersion: 1,
28+
policyHash: resolveInstalledPluginIndexPolicyHash(params.config),
29+
generatedAtMs: 1,
30+
installRecords: {},
31+
plugins: [],
32+
diagnostics: [],
33+
},
34+
registryDiagnostics: [],
35+
manifestRegistry: { plugins: [], diagnostics: [] },
36+
plugins: [],
37+
diagnostics: [],
38+
byPluginId: new Map(),
39+
normalizePluginId: (pluginId) => pluginId,
40+
owners: {
41+
channels: new Map(),
42+
channelConfigs: new Map(),
43+
providers: new Map(),
44+
modelCatalogProviders: new Map(),
45+
cliBackends: new Map(),
46+
setupProviders: new Map(),
47+
commandAliases: new Map(),
48+
contracts: new Map(),
49+
},
50+
metrics: {
51+
registrySnapshotMs: 0,
52+
manifestRegistryMs: 0,
53+
ownerMapsMs: 0,
54+
totalMs: 0,
55+
indexPluginCount: 0,
56+
manifestPluginCount: 0,
57+
},
58+
};
59+
}
60+
61+
describe("current plugin metadata snapshot", () => {
62+
it("returns the current snapshot only for matching config policy and workspace", () => {
63+
const config = { plugins: { allow: ["demo"] } };
64+
const snapshot = createSnapshot({ config, workspaceDir: "/workspace/a" });
65+
setCurrentPluginMetadataSnapshot(snapshot, { config });
66+
67+
expect(getCurrentPluginMetadataSnapshot({ config, workspaceDir: "/workspace/a" })).toBe(
68+
snapshot,
69+
);
70+
expect(getCurrentPluginMetadataSnapshot({ config })).toBe(snapshot);
71+
expect(
72+
getCurrentPluginMetadataSnapshot({
73+
config: { plugins: { allow: ["other"] } },
74+
workspaceDir: "/workspace/a",
75+
}),
76+
).toBeUndefined();
77+
expect(
78+
getCurrentPluginMetadataSnapshot({ config, workspaceDir: "/workspace/b" }),
79+
).toBeUndefined();
80+
});
81+
82+
it("rejects a current snapshot when plugin load paths change", () => {
83+
const config = { plugins: { load: { paths: ["/plugins/one"] } } };
84+
const snapshot = createSnapshot({ config });
85+
setCurrentPluginMetadataSnapshot(snapshot, { config });
86+
87+
expect(getCurrentPluginMetadataSnapshot({ config })).toBe(snapshot);
88+
expect(
89+
getCurrentPluginMetadataSnapshot({
90+
config: { plugins: { load: { paths: ["/plugins/two"] } } },
91+
}),
92+
).toBeUndefined();
93+
});
94+
95+
it("clears the current snapshot", () => {
96+
setCurrentPluginMetadataSnapshot(createSnapshot());
97+
clearCurrentPluginMetadataSnapshot();
98+
99+
expect(getCurrentPluginMetadataSnapshot()).toBeUndefined();
100+
});
101+
102+
it("clears the current snapshot when the persisted installed index changes", () => {
103+
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "openclaw-plugin-metadata-"));
104+
try {
105+
setCurrentPluginMetadataSnapshot(createSnapshot());
106+
107+
writePersistedInstalledPluginIndexSync(createSnapshot().index, { stateDir: tempDir });
108+
109+
expect(getCurrentPluginMetadataSnapshot()).toBeUndefined();
110+
} finally {
111+
fs.rmSync(tempDir, { recursive: true, force: true });
112+
}
113+
});
114+
});

0 commit comments

Comments
 (0)