refactor: cache repeated lazy imports

This commit is contained in:
Peter Steinberger
2026-04-18 16:31:48 +01:00
parent d13869aab9
commit cdaa70facb
13 changed files with 161 additions and 50 deletions

View File

@@ -5,17 +5,24 @@ import {
import { formatErrorMessage } from "openclaw/plugin-sdk/error-runtime";
import { registerMatrixCliMetadata } from "./cli-metadata.js";
type MatrixHandlersRuntimeModule = typeof import("./plugin-entry.handlers.runtime.js");
type MatrixSubagentHooksModule = typeof import("./src/matrix/subagent-hooks.js");
let matrixHandlersRuntimePromise: Promise<MatrixHandlersRuntimeModule> | null = null;
let matrixSubagentHooksPromise: Promise<MatrixSubagentHooksModule> | null = null;
function loadMatrixHandlersRuntimeModule() {
matrixHandlersRuntimePromise ??= import("./plugin-entry.handlers.runtime.js");
return matrixHandlersRuntimePromise;
}
function loadMatrixSubagentHooksModule() {
matrixSubagentHooksPromise ??= import("./src/matrix/subagent-hooks.js");
return matrixSubagentHooksPromise;
}
export function registerMatrixFullRuntime(api: OpenClawPluginApi): void {
void import("./plugin-entry.handlers.runtime.js")
void loadMatrixHandlersRuntimeModule()
.then(({ ensureMatrixCryptoRuntime }) =>
ensureMatrixCryptoRuntime({ log: api.logger.info }).catch((err: unknown) => {
const message = formatErrorMessage(err);
@@ -28,17 +35,17 @@ export function registerMatrixFullRuntime(api: OpenClawPluginApi): void {
});
api.registerGatewayMethod("matrix.verify.recoveryKey", async (ctx) => {
const { handleVerifyRecoveryKey } = await import("./plugin-entry.handlers.runtime.js");
const { handleVerifyRecoveryKey } = await loadMatrixHandlersRuntimeModule();
await handleVerifyRecoveryKey(ctx);
});
api.registerGatewayMethod("matrix.verify.bootstrap", async (ctx) => {
const { handleVerificationBootstrap } = await import("./plugin-entry.handlers.runtime.js");
const { handleVerificationBootstrap } = await loadMatrixHandlersRuntimeModule();
await handleVerificationBootstrap(ctx);
});
api.registerGatewayMethod("matrix.verify.status", async (ctx) => {
const { handleVerificationStatus } = await import("./plugin-entry.handlers.runtime.js");
const { handleVerificationStatus } = await loadMatrixHandlersRuntimeModule();
await handleVerificationStatus(ctx);
});

View File

@@ -44,12 +44,15 @@ type MatrixCredentialsReadDeps = {
credentialsMatchConfig: typeof import("../credentials-read.js").credentialsMatchConfig;
};
type MatrixCredentialsWriteRuntime = typeof import("../credentials-write.runtime.js");
type MatrixSecretInputDeps = {
resolveConfiguredSecretInputString: typeof import("./config-secret-input.runtime.js").resolveConfiguredSecretInputString;
};
let matrixAuthClientDepsPromise: Promise<MatrixAuthClientDeps> | undefined;
let matrixCredentialsReadDepsPromise: Promise<MatrixCredentialsReadDeps> | undefined;
let matrixCredentialsWriteRuntimePromise: Promise<MatrixCredentialsWriteRuntime> | undefined;
let matrixSecretInputDepsPromise: Promise<MatrixSecretInputDeps> | undefined;
let matrixAuthClientDepsForTest: MatrixAuthClientDeps | undefined;
@@ -87,6 +90,11 @@ async function loadMatrixCredentialsReadDeps(): Promise<MatrixCredentialsReadDep
return await matrixCredentialsReadDepsPromise;
}
async function loadMatrixCredentialsWriteRuntime(): Promise<MatrixCredentialsWriteRuntime> {
matrixCredentialsWriteRuntimePromise ??= import("../credentials-write.runtime.js");
return await matrixCredentialsWriteRuntimePromise;
}
async function loadMatrixSecretInputDeps(): Promise<MatrixSecretInputDeps> {
matrixSecretInputDepsPromise ??= import("./config-secret-input.runtime.js").then((runtime) => ({
resolveConfiguredSecretInputString: runtime.resolveConfiguredSecretInputString,
@@ -740,12 +748,6 @@ export async function resolveMatrixAuth(params?: {
const homeserver = await resolveValidatedMatrixHomeserverUrl(resolved.homeserver, {
dangerouslyAllowPrivateNetwork: resolved.allowPrivateNetwork,
});
let credentialsWriter: typeof import("../credentials-write.runtime.js") | undefined;
const loadCredentialsWriter = async () => {
credentialsWriter ??= await import("../credentials-write.runtime.js");
return credentialsWriter;
};
const { loadMatrixCredentials, credentialsMatchConfig } = await loadMatrixCredentialsReadDeps();
const cached = loadMatrixCredentials(env, accountId);
const cachedCredentials =
@@ -790,7 +792,7 @@ export async function resolveMatrixAuth(params?: {
cachedCredentials.userId !== userId ||
(cachedCredentials.deviceId || undefined) !== knownDeviceId;
if (shouldRefreshCachedCredentials) {
const { saveMatrixCredentials } = await loadCredentialsWriter();
const { saveMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
await saveMatrixCredentials(
{
homeserver,
@@ -802,7 +804,7 @@ export async function resolveMatrixAuth(params?: {
accountId,
);
} else if (hasMatchingCachedToken) {
const { touchMatrixCredentials } = await loadCredentialsWriter();
const { touchMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
await touchMatrixCredentials(env, accountId);
}
return {
@@ -823,7 +825,7 @@ export async function resolveMatrixAuth(params?: {
}
if (cachedCredentials) {
const { touchMatrixCredentials } = await loadCredentialsWriter();
const { touchMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
await touchMatrixCredentials(env, accountId);
return {
accountId,
@@ -905,7 +907,7 @@ export async function resolveMatrixAuth(params?: {
}),
};
const { saveMatrixCredentials } = await loadCredentialsWriter();
const { saveMatrixCredentials } = await loadMatrixCredentialsWriteRuntime();
await saveMatrixCredentials(
{
homeserver: auth.homeserver,
@@ -974,7 +976,7 @@ export async function backfillMatrixAuthDeviceIdAfterStartup(params: {
return undefined;
}
const credentialsWriter = await import("../credentials-write.runtime.js");
const credentialsWriter = await loadMatrixCredentialsWriteRuntime();
const saved = await credentialsWriter.saveBackfilledMatrixDeviceId(
{
homeserver: params.auth.homeserver,

View File

@@ -4,23 +4,32 @@ import type {
touchMatrixCredentials as touchMatrixCredentialsType,
} from "./credentials.js";
type MatrixCredentialsRuntime = typeof import("./credentials.js");
let matrixCredentialsRuntimePromise: Promise<MatrixCredentialsRuntime> | undefined;
function loadMatrixCredentialsRuntime(): Promise<MatrixCredentialsRuntime> {
matrixCredentialsRuntimePromise ??= import("./credentials.js");
return matrixCredentialsRuntimePromise;
}
export async function saveMatrixCredentials(
...args: Parameters<typeof saveMatrixCredentialsType>
): ReturnType<typeof saveMatrixCredentialsType> {
const runtime = await import("./credentials.js");
const runtime = await loadMatrixCredentialsRuntime();
return runtime.saveMatrixCredentials(...args);
}
export async function saveBackfilledMatrixDeviceId(
...args: Parameters<typeof saveBackfilledMatrixDeviceIdType>
): ReturnType<typeof saveBackfilledMatrixDeviceIdType> {
const runtime = await import("./credentials.js");
const runtime = await loadMatrixCredentialsRuntime();
return runtime.saveBackfilledMatrixDeviceId(...args);
}
export async function touchMatrixCredentials(
...args: Parameters<typeof touchMatrixCredentialsType>
): ReturnType<typeof touchMatrixCredentialsType> {
const runtime = await import("./credentials.js");
const runtime = await loadMatrixCredentialsRuntime();
return runtime.touchMatrixCredentials(...args);
}

View File

@@ -2,6 +2,15 @@ import type { GatewayRequestHandlerOptions } from "openclaw/plugin-sdk/gateway-r
import { normalizeOptionalString } from "openclaw/plugin-sdk/string-coerce-runtime";
import { formatMatrixErrorMessage } from "./matrix/errors.js";
type MatrixVerificationRuntime = typeof import("./matrix/actions/verification.js");
let matrixVerificationRuntimePromise: Promise<MatrixVerificationRuntime> | undefined;
function loadMatrixVerificationRuntime(): Promise<MatrixVerificationRuntime> {
matrixVerificationRuntimePromise ??= import("./matrix/actions/verification.js");
return matrixVerificationRuntimePromise;
}
function sendError(respond: (ok: boolean, payload?: unknown) => void, err: unknown) {
respond(false, { error: formatMatrixErrorMessage(err) });
}
@@ -18,7 +27,7 @@ export async function handleVerifyRecoveryKey({
respond,
}: GatewayRequestHandlerOptions): Promise<void> {
try {
const { verifyMatrixRecoveryKey } = await import("./matrix/actions/verification.js");
const { verifyMatrixRecoveryKey } = await loadMatrixVerificationRuntime();
const key = normalizeOptionalString(params?.key);
if (!key) {
respond(false, { error: "key required" });
@@ -37,7 +46,7 @@ export async function handleVerificationBootstrap({
respond,
}: GatewayRequestHandlerOptions): Promise<void> {
try {
const { bootstrapMatrixVerification } = await import("./matrix/actions/verification.js");
const { bootstrapMatrixVerification } = await loadMatrixVerificationRuntime();
const accountId = normalizeOptionalString(params?.accountId);
const recoveryKey = typeof params?.recoveryKey === "string" ? params.recoveryKey : undefined;
const forceResetCrossSigning = params?.forceResetCrossSigning === true;
@@ -57,7 +66,7 @@ export async function handleVerificationStatus({
respond,
}: GatewayRequestHandlerOptions): Promise<void> {
try {
const { getMatrixVerificationStatus } = await import("./matrix/actions/verification.js");
const { getMatrixVerificationStatus } = await loadMatrixVerificationRuntime();
const accountId = normalizeOptionalString(params?.accountId);
const includeRecoveryKey = params?.includeRecoveryKey === true;
const status = await getMatrixVerificationStatus({ accountId, includeRecoveryKey });

View File

@@ -5,6 +5,15 @@ import {
} from "openclaw/plugin-sdk/provider-web-search-config-contract";
const KIMI_CREDENTIAL_PATH = "plugins.entries.moonshot.config.webSearch.apiKey";
type KimiWebSearchProviderRuntime = typeof import("./kimi-web-search-provider.runtime.js");
let kimiWebSearchProviderRuntimePromise: Promise<KimiWebSearchProviderRuntime> | undefined;
function loadKimiWebSearchProviderRuntime(): Promise<KimiWebSearchProviderRuntime> {
kimiWebSearchProviderRuntimePromise ??= import("./kimi-web-search-provider.runtime.js");
return kimiWebSearchProviderRuntimePromise;
}
const KimiSearchSchema = {
type: "object",
properties: {
@@ -26,7 +35,7 @@ const KimiSearchSchema = {
async function runKimiSearchProviderSetup(
ctx: WebSearchProviderSetupContext,
): Promise<WebSearchProviderSetupContext["config"]> {
const runtime = await import("./kimi-web-search-provider.runtime.js");
const runtime = await loadKimiWebSearchProviderRuntime();
return await runtime.runKimiSearchProviderSetup(ctx);
}
@@ -54,8 +63,7 @@ export function createKimiWebSearchProvider(): WebSearchProviderPlugin {
"Search the web using Kimi by Moonshot. Returns AI-synthesized answers with citations from native $web_search.",
parameters: KimiSearchSchema,
execute: async (args) => {
const { executeKimiWebSearchProviderTool } =
await import("./kimi-web-search-provider.runtime.js");
const { executeKimiWebSearchProviderTool } = await loadKimiWebSearchProviderRuntime();
return await executeKimiWebSearchProviderTool(ctx, args);
},
}),

View File

@@ -12,14 +12,23 @@ import { qqbotSetupWizard } from "./setup-surface.js";
export { chunkText, TEXT_CHUNK_LIMIT } from "./text-utils.js";
import type { ResolvedQQBotAccount } from "./types.js";
type QQBotOutboundModule = typeof import("./outbound.js");
// Shared promise so concurrent multi-account startups serialize the dynamic
// import of the gateway module, avoiding an ESM circular-dependency race.
let _gatewayModulePromise: Promise<typeof import("./gateway.js")> | undefined;
let _outboundModulePromise: Promise<QQBotOutboundModule> | undefined;
function loadGatewayModule(): Promise<typeof import("./gateway.js")> {
_gatewayModulePromise ??= import("./gateway.js");
return _gatewayModulePromise;
}
function loadOutboundModule(): Promise<QQBotOutboundModule> {
_outboundModulePromise ??= import("./outbound.js");
return _outboundModulePromise;
}
export const qqbotPlugin: ChannelPlugin<ResolvedQQBotAccount> = {
id: "qqbot",
setupWizard: qqbotSetupWizard,
@@ -91,7 +100,7 @@ export const qqbotPlugin: ChannelPlugin<ResolvedQQBotAccount> = {
textChunkLimit: 5000,
sendText: async ({ to, text, accountId, replyToId, cfg }) => {
const account = resolveQQBotAccount(cfg, accountId);
const { sendText } = await import("./outbound.js");
const { sendText } = await loadOutboundModule();
initApiConfig(account.appId, { markdownSupport: account.markdownSupport });
const result = await sendText({ to, text, accountId, replyToId, account });
return {
@@ -102,7 +111,7 @@ export const qqbotPlugin: ChannelPlugin<ResolvedQQBotAccount> = {
},
sendMedia: async ({ to, text, mediaUrl, accountId, replyToId, cfg }) => {
const account = resolveQQBotAccount(cfg, accountId);
const { sendMedia } = await import("./outbound.js");
const { sendMedia } = await loadOutboundModule();
initApiConfig(account.appId, { markdownSupport: account.markdownSupport });
const result = await sendMedia({
to,

View File

@@ -13,6 +13,15 @@ import { shouldLogVerbose } from "openclaw/plugin-sdk/runtime-env";
import { WHATSAPP_LEGACY_OUTBOUND_SEND_DEP_KEYS } from "./outbound-send-deps.js";
import { resolveWhatsAppOutboundTarget } from "./resolve-outbound-target.js";
type WhatsAppSendModule = typeof import("./send.js");
let whatsAppSendModulePromise: Promise<WhatsAppSendModule> | undefined;
function loadWhatsAppSendModule(): Promise<WhatsAppSendModule> {
whatsAppSendModulePromise ??= import("./send.js");
return whatsAppSendModulePromise;
}
function trimLeadingWhitespace(text: string | undefined): string {
return text?.trimStart() ?? "";
}
@@ -54,7 +63,7 @@ export const whatsappOutbound: ChannelOutboundAdapter = {
const send =
resolveOutboundSendDep<typeof import("./send.js").sendMessageWhatsApp>(deps, "whatsapp", {
legacyKeys: WHATSAPP_LEGACY_OUTBOUND_SEND_DEP_KEYS,
}) ?? (await import("./send.js")).sendMessageWhatsApp;
}) ?? (await loadWhatsAppSendModule()).sendMessageWhatsApp;
return await send(to, normalizedText, {
verbose: false,
cfg,
@@ -77,7 +86,7 @@ export const whatsappOutbound: ChannelOutboundAdapter = {
const send =
resolveOutboundSendDep<typeof import("./send.js").sendMessageWhatsApp>(deps, "whatsapp", {
legacyKeys: WHATSAPP_LEGACY_OUTBOUND_SEND_DEP_KEYS,
}) ?? (await import("./send.js")).sendMessageWhatsApp;
}) ?? (await loadWhatsAppSendModule()).sendMessageWhatsApp;
return await send(to, normalizedText, {
verbose: false,
cfg,
@@ -90,7 +99,7 @@ export const whatsappOutbound: ChannelOutboundAdapter = {
},
sendPoll: async ({ cfg, to, poll, accountId }) =>
await (
await import("./send.js")
await loadWhatsAppSendModule()
).sendPollWhatsApp(to, poll, {
verbose: shouldLogVerbose(),
accountId: accountId ?? undefined,

View File

@@ -5,6 +5,15 @@ import {
} from "openclaw/plugin-sdk/provider-web-search-config-contract";
const XAI_CREDENTIAL_PATH = "plugins.entries.xai.config.webSearch.apiKey";
type XaiWebSearchProviderRuntime = typeof import("./src/web-search-provider.runtime.js");
let xaiWebSearchProviderRuntimePromise: Promise<XaiWebSearchProviderRuntime> | undefined;
function loadXaiWebSearchProviderRuntime(): Promise<XaiWebSearchProviderRuntime> {
xaiWebSearchProviderRuntimePromise ??= import("./src/web-search-provider.runtime.js");
return xaiWebSearchProviderRuntimePromise;
}
const GenericXaiSearchSchema = {
type: "object",
properties: {
@@ -22,7 +31,7 @@ const GenericXaiSearchSchema = {
async function runXaiSearchProviderSetup(
ctx: WebSearchProviderSetupContext,
): Promise<WebSearchProviderSetupContext["config"]> {
const runtime = await import("./src/web-search-provider.runtime.js");
const runtime = await loadXaiWebSearchProviderRuntime();
return await runtime.runXaiSearchProviderSetup(ctx);
}
@@ -50,8 +59,7 @@ export function createXaiWebSearchProvider(): WebSearchProviderPlugin {
"Search the web using xAI Grok. Returns AI-synthesized answers with citations from real-time web search.",
parameters: GenericXaiSearchSchema,
execute: async (args) => {
const { executeXaiWebSearchProviderTool } =
await import("./src/web-search-provider.runtime.js");
const { executeXaiWebSearchProviderTool } = await loadXaiWebSearchProviderRuntime();
return await executeXaiWebSearchProviderTool(ctx, args);
},
}),