Skip to content

Commit 1b234b9

Browse files
committed
Gateway: defer full channel plugins until after listen
1 parent 541e697 commit 1b234b9

5 files changed

Lines changed: 212 additions & 11 deletions

File tree

‎src/gateway/server-plugins.test.ts‎

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,65 @@ describe("loadGatewayPlugins", () => {
162162
expect(typeof subagent?.getSession).toBe("function");
163163
});
164164

165+
test("can prefer setup-runtime channel plugins during startup loads", async () => {
166+
const { loadGatewayPlugins } = await importServerPluginsModule();
167+
loadOpenClawPlugins.mockReturnValue(createRegistry([]));
168+
169+
const log = {
170+
info: vi.fn(),
171+
warn: vi.fn(),
172+
error: vi.fn(),
173+
debug: vi.fn(),
174+
};
175+
176+
loadGatewayPlugins({
177+
cfg: {},
178+
workspaceDir: "/tmp",
179+
log,
180+
coreGatewayHandlers: {},
181+
baseMethods: [],
182+
preferSetupRuntimeForChannelPlugins: true,
183+
});
184+
185+
expect(loadOpenClawPlugins).toHaveBeenCalledWith(
186+
expect.objectContaining({
187+
preferSetupRuntimeForChannelPlugins: true,
188+
}),
189+
);
190+
});
191+
192+
test("can suppress duplicate diagnostics when reloading full runtime plugins", async () => {
193+
const { loadGatewayPlugins } = await importServerPluginsModule();
194+
const diagnostics: PluginDiagnostic[] = [
195+
{
196+
level: "error",
197+
pluginId: "telegram",
198+
source: "/tmp/telegram/index.ts",
199+
message: "failed to load plugin: boom",
200+
},
201+
];
202+
loadOpenClawPlugins.mockReturnValue(createRegistry(diagnostics));
203+
204+
const log = {
205+
info: vi.fn(),
206+
warn: vi.fn(),
207+
error: vi.fn(),
208+
debug: vi.fn(),
209+
};
210+
211+
loadGatewayPlugins({
212+
cfg: {},
213+
workspaceDir: "/tmp",
214+
log,
215+
coreGatewayHandlers: {},
216+
baseMethods: [],
217+
logDiagnostics: false,
218+
});
219+
220+
expect(log.error).not.toHaveBeenCalled();
221+
expect(log.info).not.toHaveBeenCalled();
222+
});
223+
165224
test("shares fallback context across module reloads for existing runtimes", async () => {
166225
const first = await importServerPluginsModule();
167226
const runtime = createSubagentRuntime(first);

‎src/gateway/server-plugins.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,8 @@ export function loadGatewayPlugins(params: {
172172
};
173173
coreGatewayHandlers: Record<string, GatewayRequestHandler>;
174174
baseMethods: string[];
175+
preferSetupRuntimeForChannelPlugins?: boolean;
176+
logDiagnostics?: boolean;
175177
}) {
176178
const pluginRegistry = loadOpenClawPlugins({
177179
config: params.cfg,
@@ -186,10 +188,11 @@ export function loadGatewayPlugins(params: {
186188
runtimeOptions: {
187189
subagent: createGatewaySubagentRuntime(),
188190
},
191+
preferSetupRuntimeForChannelPlugins: params.preferSetupRuntimeForChannelPlugins,
189192
});
190193
const pluginMethods = Object.keys(pluginRegistry.gatewayHandlers);
191194
const gatewayMethods = Array.from(new Set([...params.baseMethods, ...pluginMethods]));
192-
if (pluginRegistry.diagnostics.length > 0) {
195+
if ((params.logDiagnostics ?? true) && pluginRegistry.diagnostics.length > 0) {
193196
for (const diag of pluginRegistry.diagnostics) {
194197
const details = [
195198
diag.pluginId ? `plugin=${diag.pluginId}` : null,

‎src/gateway/server.impl.ts‎

Lines changed: 30 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import { enqueueSystemEvent } from "../infra/system-events.js";
4545
import { scheduleGatewayUpdateCheck } from "../infra/update-startup.js";
4646
import { startDiagnosticHeartbeat, stopDiagnosticHeartbeat } from "../logging/diagnostic.js";
4747
import { createSubsystemLogger, runtimeForLogger } from "../logging/subsystem.js";
48+
import { resolveConfiguredChannelPluginIds } from "../plugins/channel-plugin-ids.js";
4849
import { getGlobalHookRunner, runGlobalGatewayStopSafely } from "../plugins/hook-runner-global.js";
4950
import { createEmptyPluginRegistry } from "../plugins/registry.js";
5051
import { createPluginRuntime } from "../plugins/runtime/index.js";
@@ -473,17 +474,27 @@ export async function startGatewayServer(
473474
initSubagentRegistry();
474475
const defaultAgentId = resolveDefaultAgentId(cfgAtStart);
475476
const defaultWorkspaceDir = resolveAgentWorkspaceDir(cfgAtStart, defaultAgentId);
476-
const baseMethods = listGatewayMethods();
477-
const emptyPluginRegistry = createEmptyPluginRegistry();
478-
const { pluginRegistry, gatewayMethods: baseGatewayMethods } = minimalTestGateway
479-
? { pluginRegistry: emptyPluginRegistry, gatewayMethods: baseMethods }
480-
: loadGatewayPlugins({
481-
cfg: cfgAtStart,
477+
const configuredChannelPluginIds = minimalTestGateway
478+
? []
479+
: resolveConfiguredChannelPluginIds({
480+
config: cfgAtStart,
482481
workspaceDir: defaultWorkspaceDir,
483-
log,
484-
coreGatewayHandlers,
485-
baseMethods,
482+
env: process.env,
486483
});
484+
const baseMethods = listGatewayMethods();
485+
const emptyPluginRegistry = createEmptyPluginRegistry();
486+
let pluginRegistry = emptyPluginRegistry;
487+
let baseGatewayMethods = baseMethods;
488+
if (!minimalTestGateway) {
489+
({ pluginRegistry, gatewayMethods: baseGatewayMethods } = loadGatewayPlugins({
490+
cfg: cfgAtStart,
491+
workspaceDir: defaultWorkspaceDir,
492+
log,
493+
coreGatewayHandlers,
494+
baseMethods,
495+
preferSetupRuntimeForChannelPlugins: configuredChannelPluginIds.length > 0,
496+
}));
497+
}
487498
const channelLogs = Object.fromEntries(
488499
listChannelPlugins().map((plugin) => [plugin.id, logChannels.child(plugin.id)]),
489500
) as Record<ChannelId, ReturnType<typeof createSubsystemLogger>>;
@@ -940,6 +951,16 @@ export async function startGatewayServer(
940951

941952
let browserControl: Awaited<ReturnType<typeof startBrowserControlServerIfEnabled>> = null;
942953
if (!minimalTestGateway) {
954+
if (configuredChannelPluginIds.length > 0) {
955+
({ pluginRegistry } = loadGatewayPlugins({
956+
cfg: cfgAtStart,
957+
workspaceDir: defaultWorkspaceDir,
958+
log,
959+
coreGatewayHandlers,
960+
baseMethods,
961+
logDiagnostics: false,
962+
}));
963+
}
943964
({ browserControl, pluginServices } = await startGatewaySidecars({
944965
cfg: cfgAtStart,
945966
pluginRegistry,

‎src/plugins/loader.test.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2030,6 +2030,113 @@ module.exports = {
20302030
expect(registry.channels).toHaveLength(1);
20312031
});
20322032

2033+
it("can prefer setupEntry for configured channel loads during startup", () => {
2034+
useNoBundledPlugins();
2035+
const pluginDir = makeTempDir();
2036+
const fullMarker = path.join(pluginDir, "full-loaded.txt");
2037+
const setupMarker = path.join(pluginDir, "setup-loaded.txt");
2038+
fs.writeFileSync(
2039+
path.join(pluginDir, "package.json"),
2040+
JSON.stringify(
2041+
{
2042+
name: "@openclaw/setup-runtime-preferred-test",
2043+
openclaw: {
2044+
extensions: ["./index.cjs"],
2045+
setupEntry: "./setup-entry.cjs",
2046+
},
2047+
},
2048+
null,
2049+
2,
2050+
),
2051+
"utf-8",
2052+
);
2053+
fs.writeFileSync(
2054+
path.join(pluginDir, "openclaw.plugin.json"),
2055+
JSON.stringify(
2056+
{
2057+
id: "setup-runtime-preferred-test",
2058+
configSchema: EMPTY_PLUGIN_SCHEMA,
2059+
channels: ["setup-runtime-preferred-test"],
2060+
},
2061+
null,
2062+
2,
2063+
),
2064+
"utf-8",
2065+
);
2066+
fs.writeFileSync(
2067+
path.join(pluginDir, "index.cjs"),
2068+
`require("node:fs").writeFileSync(${JSON.stringify(fullMarker)}, "loaded", "utf-8");
2069+
module.exports = {
2070+
id: "setup-runtime-preferred-test",
2071+
register(api) {
2072+
api.registerChannel({
2073+
plugin: {
2074+
id: "setup-runtime-preferred-test",
2075+
meta: {
2076+
id: "setup-runtime-preferred-test",
2077+
label: "Setup Runtime Preferred Test",
2078+
selectionLabel: "Setup Runtime Preferred Test",
2079+
docsPath: "/channels/setup-runtime-preferred-test",
2080+
blurb: "full entry should be deferred while startup is still cold",
2081+
},
2082+
capabilities: { chatTypes: ["direct"] },
2083+
config: {
2084+
listAccountIds: () => ["default"],
2085+
resolveAccount: () => ({ accountId: "default", token: "configured" }),
2086+
},
2087+
outbound: { deliveryMode: "direct" },
2088+
},
2089+
});
2090+
},
2091+
};`,
2092+
"utf-8",
2093+
);
2094+
fs.writeFileSync(
2095+
path.join(pluginDir, "setup-entry.cjs"),
2096+
`require("node:fs").writeFileSync(${JSON.stringify(setupMarker)}, "loaded", "utf-8");
2097+
module.exports = {
2098+
plugin: {
2099+
id: "setup-runtime-preferred-test",
2100+
meta: {
2101+
id: "setup-runtime-preferred-test",
2102+
label: "Setup Runtime Preferred Test",
2103+
selectionLabel: "Setup Runtime Preferred Test",
2104+
docsPath: "/channels/setup-runtime-preferred-test",
2105+
blurb: "setup runtime preferred",
2106+
},
2107+
capabilities: { chatTypes: ["direct"] },
2108+
config: {
2109+
listAccountIds: () => ["default"],
2110+
resolveAccount: () => ({ accountId: "default", token: "configured" }),
2111+
},
2112+
outbound: { deliveryMode: "direct" },
2113+
},
2114+
};`,
2115+
"utf-8",
2116+
);
2117+
2118+
const registry = loadOpenClawPlugins({
2119+
cache: false,
2120+
preferSetupRuntimeForChannelPlugins: true,
2121+
config: {
2122+
channels: {
2123+
"setup-runtime-preferred-test": {
2124+
enabled: true,
2125+
},
2126+
},
2127+
plugins: {
2128+
load: { paths: [pluginDir] },
2129+
allow: ["setup-runtime-preferred-test"],
2130+
},
2131+
},
2132+
});
2133+
2134+
expect(fs.existsSync(setupMarker)).toBe(true);
2135+
expect(fs.existsSync(fullMarker)).toBe(false);
2136+
expect(registry.channelSetups).toHaveLength(1);
2137+
expect(registry.channels).toHaveLength(1);
2138+
});
2139+
20332140
it("blocks before_prompt_build but preserves legacy model overrides when prompt injection is disabled", async () => {
20342141
useNoBundledPlugins();
20352142
const plugin = writePlugin({

‎src/plugins/loader.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export type PluginLoadOptions = {
5454
mode?: "full" | "validate";
5555
onlyPluginIds?: string[];
5656
includeSetupOnlyChannelPlugins?: boolean;
57+
preferSetupRuntimeForChannelPlugins?: boolean;
5758
activate?: boolean;
5859
};
5960

@@ -336,6 +337,7 @@ function buildCacheKey(params: {
336337
env: NodeJS.ProcessEnv;
337338
onlyPluginIds?: string[];
338339
includeSetupOnlyChannelPlugins?: boolean;
340+
preferSetupRuntimeForChannelPlugins?: boolean;
339341
}): string {
340342
const { roots, loadPaths } = resolvePluginCacheInputs({
341343
workspaceDir: params.workspaceDir,
@@ -360,11 +362,13 @@ function buildCacheKey(params: {
360362
);
361363
const scopeKey = JSON.stringify(params.onlyPluginIds ?? []);
362364
const setupOnlyKey = params.includeSetupOnlyChannelPlugins === true ? "setup-only" : "runtime";
365+
const startupChannelMode =
366+
params.preferSetupRuntimeForChannelPlugins === true ? "prefer-setup" : "full";
363367
return `${roots.workspace ?? ""}::${roots.global ?? ""}::${roots.stock ?? ""}::${JSON.stringify({
364368
...params.plugins,
365369
installs,
366370
loadPaths,
367-
})}::${scopeKey}::${setupOnlyKey}`;
371+
})}::${scopeKey}::${setupOnlyKey}::${startupChannelMode}`;
368372
}
369373

370374
function normalizeScopedPluginIds(ids?: string[]): string[] | undefined {
@@ -447,10 +451,14 @@ function shouldLoadChannelPluginInSetupRuntime(params: {
447451
setupSource?: string;
448452
cfg: OpenClawConfig;
449453
env: NodeJS.ProcessEnv;
454+
preferSetupRuntimeForChannelPlugins?: boolean;
450455
}): boolean {
451456
if (!params.setupSource || params.manifestChannels.length === 0) {
452457
return false;
453458
}
459+
if (params.preferSetupRuntimeForChannelPlugins) {
460+
return true;
461+
}
454462
return !params.manifestChannels.some((channelId) =>
455463
isChannelConfigured(params.cfg, channelId, params.env),
456464
);
@@ -800,6 +808,7 @@ export function loadOpenClawPlugins(options: PluginLoadOptions = {}): PluginRegi
800808
const onlyPluginIds = normalizeScopedPluginIds(options.onlyPluginIds);
801809
const onlyPluginIdSet = onlyPluginIds ? new Set(onlyPluginIds) : null;
802810
const includeSetupOnlyChannelPlugins = options.includeSetupOnlyChannelPlugins === true;
811+
const preferSetupRuntimeForChannelPlugins = options.preferSetupRuntimeForChannelPlugins === true;
803812
const shouldActivate = options.activate !== false;
804813
// NOTE: `activate` is intentionally excluded from the cache key. All non-activating
805814
// (snapshot) callers pass `cache: false` via loadOnboardingPluginRegistry(), so they
@@ -812,6 +821,7 @@ export function loadOpenClawPlugins(options: PluginLoadOptions = {}): PluginRegi
812821
env,
813822
onlyPluginIds,
814823
includeSetupOnlyChannelPlugins,
824+
preferSetupRuntimeForChannelPlugins,
815825
});
816826
const cacheEnabled = options.cache !== false;
817827
if (cacheEnabled) {
@@ -1068,6 +1078,7 @@ export function loadOpenClawPlugins(options: PluginLoadOptions = {}): PluginRegi
10681078
setupSource: manifestRecord.setupSource,
10691079
cfg,
10701080
env,
1081+
preferSetupRuntimeForChannelPlugins,
10711082
})
10721083
? "setup-runtime"
10731084
: "full"

0 commit comments

Comments
 (0)