From 5b952836e3d93a4bf80f3604a3d0f84202bf9219 Mon Sep 17 00:00:00 2001 From: Vincent Koc Date: Thu, 2 Apr 2026 14:10:57 +0900 Subject: [PATCH] perf(memory): trim telegram command runtime imports --- .../src/bot-native-commands.runtime.ts | 11 +++ .../telegram/src/bot-native-commands.ts | 72 ++++++++++--------- extensions/telegram/src/monitor.ts | 12 +++- 3 files changed, 61 insertions(+), 34 deletions(-) create mode 100644 extensions/telegram/src/bot-native-commands.runtime.ts diff --git a/extensions/telegram/src/bot-native-commands.runtime.ts b/extensions/telegram/src/bot-native-commands.runtime.ts new file mode 100644 index 00000000000..6e3c4a26821 --- /dev/null +++ b/extensions/telegram/src/bot-native-commands.runtime.ts @@ -0,0 +1,11 @@ +export { + ensureConfiguredBindingRouteReady, + recordInboundSessionMetaSafe, +} from "openclaw/plugin-sdk/conversation-runtime"; +export { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime"; +export { executePluginCommand, matchPluginCommand } from "openclaw/plugin-sdk/plugin-runtime"; +export { + finalizeInboundContext, + resolveChunkMode, +} from "openclaw/plugin-sdk/reply-dispatch-runtime"; +export { resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing"; diff --git a/extensions/telegram/src/bot-native-commands.ts b/extensions/telegram/src/bot-native-commands.ts index 4ec87da2c63..7696b0bce7b 100644 --- a/extensions/telegram/src/bot-native-commands.ts +++ b/extensions/telegram/src/bot-native-commands.ts @@ -15,13 +15,6 @@ import { } from "openclaw/plugin-sdk/command-auth-native"; import type { OpenClawConfig } from "openclaw/plugin-sdk/config-runtime"; import type { ChannelGroupPolicy } from "openclaw/plugin-sdk/config-runtime"; -import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime"; -import { getRuntimeConfigSnapshot } from "openclaw/plugin-sdk/runtime-config-snapshot"; -import { - normalizeTelegramCommandName, - resolveTelegramCustomCommands, - TELEGRAM_COMMAND_NAME_PATTERN, -} from "openclaw/plugin-sdk/telegram-command-config"; import type { ReplyToMode, TelegramAccountConfig, @@ -29,25 +22,18 @@ import type { TelegramGroupConfig, TelegramTopicConfig, } from "openclaw/plugin-sdk/config-runtime"; -import { - ensureConfiguredBindingRouteReady, - recordInboundSessionMetaSafe, -} from "openclaw/plugin-sdk/conversation-runtime"; -import { getAgentScopedMediaLocalRoots } from "openclaw/plugin-sdk/media-runtime"; -import { - executePluginCommand, - getPluginCommandSpecs, - matchPluginCommand, -} from "openclaw/plugin-sdk/plugin-runtime"; -import { - finalizeInboundContext, - resolveChunkMode, -} from "openclaw/plugin-sdk/reply-dispatch-runtime"; +import { resolveMarkdownTableMode } from "openclaw/plugin-sdk/markdown-table-runtime"; +import { getPluginCommandSpecs } from "openclaw/plugin-sdk/plugin-runtime"; import { resolveAgentRoute } from "openclaw/plugin-sdk/routing"; -import { resolveThreadSessionKeys } from "openclaw/plugin-sdk/routing"; +import { getRuntimeConfigSnapshot } from "openclaw/plugin-sdk/runtime-config-snapshot"; import { danger, logVerbose } from "openclaw/plugin-sdk/runtime-env"; import { getChildLogger } from "openclaw/plugin-sdk/runtime-env"; import type { RuntimeEnv } from "openclaw/plugin-sdk/runtime-env"; +import { + normalizeTelegramCommandName, + resolveTelegramCustomCommands, + TELEGRAM_COMMAND_NAME_PATTERN, +} from "openclaw/plugin-sdk/telegram-command-config"; import { resolveTelegramAccount } from "./accounts.js"; import { withTelegramApiErrorLogging } from "./api-logging.js"; import { isSenderAllowed, normalizeDmAllowFromWithStore } from "./bot-access.js"; @@ -89,6 +75,9 @@ const EMPTY_RESPONSE_FALLBACK = "No response generated. Please try again."; const TELEGRAM_NATIVE_COMMAND_CALLBACK_PREFIX = "tgcmd:"; type TelegramNativeCommandContext = Context & { match?: string }; +type TelegramChunkMode = ReturnType< + typeof import("openclaw/plugin-sdk/reply-dispatch-runtime").resolveChunkMode +>; type TelegramCommandAuthResult = { chatId: number; @@ -112,6 +101,15 @@ async function loadTelegramNativeCommandDeliveryRuntime() { return await telegramNativeCommandDeliveryRuntimePromise; } +let telegramNativeCommandRuntimePromise: + | Promise + | undefined; + +async function loadTelegramNativeCommandRuntime() { + telegramNativeCommandRuntimePromise ??= import("./bot-native-commands.runtime.js"); + return await telegramNativeCommandRuntimePromise; +} + export type RegisterTelegramHandlerParams = { cfg: OpenClawConfig; accountId: string; @@ -537,7 +535,7 @@ export const registerTelegramNativeCommands = ({ route: ReturnType["route"]; mediaLocalRoots: readonly string[] | undefined; tableMode: ReturnType; - chunkMode: ReturnType; + chunkMode: TelegramChunkMode; } | null> => { const { msg, runtimeCfg, isGroup, isForum, resolvedThreadId, senderId, topicAgentId } = params; const chatId = msg.chat.id; @@ -557,8 +555,9 @@ export const registerTelegramNativeCommands = ({ senderId, topicAgentId, }); + const nativeCommandRuntime = await loadTelegramNativeCommandRuntime(); if (configuredBinding) { - const ensured = await ensureConfiguredBindingRouteReady({ + const ensured = await nativeCommandRuntime.ensureConfiguredBindingRouteReady({ cfg: runtimeCfg, bindingResolution: configuredBinding, }); @@ -579,13 +578,20 @@ export const registerTelegramNativeCommands = ({ return null; } } - const mediaLocalRoots = getAgentScopedMediaLocalRoots(runtimeCfg, route.agentId); + const mediaLocalRoots = nativeCommandRuntime.getAgentScopedMediaLocalRoots( + runtimeCfg, + route.agentId, + ); const tableMode = resolveMarkdownTableMode({ cfg: runtimeCfg, channel: "telegram", accountId: route.accountId, }); - const chunkMode = resolveChunkMode(runtimeCfg, "telegram", route.accountId); + const chunkMode = nativeCommandRuntime.resolveChunkMode( + runtimeCfg, + "telegram", + route.accountId, + ); return { chatId, threadSpec, route, mediaLocalRoots, tableMode, chunkMode }; }; const buildCommandDeliveryBaseOptions = (params: { @@ -597,7 +603,7 @@ export const registerTelegramNativeCommands = ({ mediaLocalRoots?: readonly string[]; threadSpec: ReturnType; tableMode: ReturnType; - chunkMode: ReturnType; + chunkMode: TelegramChunkMode; linkPreview?: boolean; }) => ({ chatId: String(params.chatId), @@ -736,9 +742,10 @@ export const registerTelegramNativeCommands = ({ }); // DMs: use raw messageThreadId for thread sessions (not resolvedThreadId which is for forums) const dmThreadId = threadSpec.scope === "dm" ? threadSpec.id : undefined; + const nativeCommandRuntime = await loadTelegramNativeCommandRuntime(); const threadKeys = dmThreadId != null - ? resolveThreadSessionKeys({ + ? nativeCommandRuntime.resolveThreadSessionKeys({ baseSessionKey, threadId: `${chatId}:${dmThreadId}`, }) @@ -772,7 +779,7 @@ export const registerTelegramNativeCommands = ({ ? `${msg.chat.title} id:${chatId}` : `group:${chatId}` : (buildSenderName(msg) ?? String(senderId || chatId)); - const ctxPayload = finalizeInboundContext({ + const ctxPayload = nativeCommandRuntime.finalizeInboundContext({ Body: prompt, BodyForAgent: prompt, RawBody: prompt, @@ -804,7 +811,7 @@ export const registerTelegramNativeCommands = ({ OriginatingTo: originatingTo, }); - await recordInboundSessionMetaSafe({ + await nativeCommandRuntime.recordInboundSessionMetaSafe({ cfg: executionCfg, agentId: route.agentId, sessionKey: ctxPayload.SessionKey ?? route.sessionKey, @@ -894,7 +901,8 @@ export const registerTelegramNativeCommands = ({ const runtimeTelegramCfg = resolveFreshTelegramConfig(runtimeCfg); const rawText = ctx.match?.trim() ?? ""; const commandBody = `/${pluginCommand.command}${rawText ? ` ${rawText}` : ""}`; - const match = matchPluginCommand(commandBody); + const nativeCommandRuntime = await loadTelegramNativeCommandRuntime(); + const match = nativeCommandRuntime.matchPluginCommand(commandBody); if (!match) { await withTelegramApiErrorLogging({ operation: "sendMessage", @@ -950,7 +958,7 @@ export const registerTelegramNativeCommands = ({ const to = `telegram:${chatId}`; const { deliverReplies } = await loadTelegramNativeCommandDeliveryRuntime(); - const result = await executePluginCommand({ + const result = await nativeCommandRuntime.executePluginCommand({ command: match.command, args: match.args, senderId, diff --git a/extensions/telegram/src/monitor.ts b/extensions/telegram/src/monitor.ts index bb9376f3ae4..183e715537d 100644 --- a/extensions/telegram/src/monitor.ts +++ b/extensions/telegram/src/monitor.ts @@ -71,6 +71,14 @@ const isGrammyHttpError = (err: unknown): boolean => { return (err as { name?: string }).name === "HttpError"; }; +type TelegramMonitorPollingRuntime = typeof import("./monitor-polling.runtime.js"); +type TelegramPollingSessionInstance = InstanceType< + TelegramMonitorPollingRuntime["TelegramPollingSession"] +>; +type TelegramExecApprovalHandlerInstance = InstanceType< + TelegramMonitorPollingRuntime["TelegramExecApprovalHandler"] +>; + let telegramMonitorPollingRuntimePromise: | Promise | undefined; @@ -91,8 +99,8 @@ async function loadTelegramMonitorWebhookRuntime() { export async function monitorTelegramProvider(opts: MonitorTelegramOpts = {}) { const log = opts.runtime?.error ?? console.error; - let pollingSession: TelegramPollingSession | undefined; - let execApprovalsHandler: TelegramExecApprovalHandler | undefined; + let pollingSession: TelegramPollingSessionInstance | undefined; + let execApprovalsHandler: TelegramExecApprovalHandlerInstance | undefined; const unregisterHandler = registerUnhandledRejectionHandler((err) => { const isNetworkError = isRecoverableTelegramNetworkError(err, { context: "polling" });