Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

37.4 KB
Raw Blame
import {
  MessageToolIdentifier,
  MESSENGER_PUSH_CONTENT_MAX_LENGTH,
} from '@lobechat/builtin-tool-message';
import type {
  BotProviderQuery,
  MessageRuntimeService,
} from '@lobechat/builtin-tool-message/executionRuntime';
import { MessageExecutionRuntime } from '@lobechat/builtin-tool-message/executionRuntime';
import type { ChatTopicBotContext } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import { and, eq } from 'drizzle-orm';

import { assertBotFeatureAccess, BotFeatureAccessError } from '@/business/server/bot/featureAccess';
import {
  getEnabledMessengerPlatforms,
  getMessengerDiscordConfig,
  getMessengerSlackConfig,
  getMessengerTelegramConfig,
} from '@/config/messenger';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import type { SafeMessengerAccountLink } from '@/database/models/messengerAccountLink';
import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
import { MessengerInstallationModel } from '@/database/models/messengerInstallation';
import { TopicModel } from '@/database/models/topic';
import { agents } from '@/database/schemas';
import { notTrashed } from '@/database/utils/softDelete';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import {
  assertBotAccessSettings,
  assertWatchKeywordsWritable,
  invalidateBotAfterUpdate,
  mergeBotSettingsForCreate,
  mergeBotSettingsPatch,
} from '@/server/services/bot/agentBotProviderSettings';
import type { ResolvedMessageTarget } from '@/server/services/bot/messageTarget';
import {
  createMessageServiceForCredentials,
  resolveBotMessageTarget,
  resolveMessengerInstallTarget,
  resolveMessengerKeyTarget,
} from '@/server/services/bot/messageTarget';
import { platformRegistry } from '@/server/services/bot/platforms';
import {
  wechatLegacyTokenKey,
  wechatPendingPushKey,
  wechatWindowKey,
} from '@/server/services/bot/platforms/wechat/contextWindow';
import { flattenBotWakeSettings } from '@/server/services/conversationWake/config';
import { GatewayService } from '@/server/services/gateway';
import { getReplyConnectionUnavailableReason } from '@/server/services/gateway/replyConnectionHost';
import { BOT_RUNTIME_STATUSES, getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';
import { getMessengerRouter, messengerPlatformRegistry } from '@/server/services/messenger';
import { TELEGRAM_INSTALLATION_KEY } from '@/server/services/messenger/installations/telegram';
import { wechatInstallationKey } from '@/server/services/messenger/installations/wechat';
import type { TelegramInstallationView } from '@/server/services/messenger/installationViews';
import { maybeSynthesizeTelegramInstall } from '@/server/services/messenger/installationViews';
import { sendMessengerPush } from '@/server/services/messenger/push';

import type { ServerRuntimeRegistration } from '../types';
import type { MessageRouteParams } from './MessageDispatcherService';
import { MessageDispatcherService } from './MessageDispatcherService';
import { createMessageImageStore } from './storeMessageImages';

/**
 * Shape returned by `listMessengers` / `getMessengerDetail` to the tool runtime.
 * Mirrors the public Z schema in builtin-tool-message; declared here so the
 * Telegram synthesis path produces an entry shape-identical to the DB-backed
 * rows without duplicating the column-mapping logic in three places.
 */
type MessengerInstallationView = {
  applicationId: string;
  enterpriseId: string | null;
  id: string;
  installedAt: string;
  isEnterpriseInstall: boolean;
  platform: string;
  scope: string;
  tenantId: string;
  tenantName: string;
};

/**
 * Adapt the shared Telegram singleton view (which keeps `installedAt` as a
 * `Date` for the TRPC contract) to this runtime's ISO-string shape.
 */
const toTelegramInstallationView = (
  view: TelegramInstallationView | undefined,
): MessengerInstallationView | undefined =>
  view && { ...view, installedAt: view.installedAt.toISOString() };

const synthesizeWechatInstalls = (
  links: SafeMessengerAccountLink[],
): MessengerInstallationView[] => {
  return links
    .filter(
      (link): link is SafeMessengerAccountLink & { applicationId: string } =>
        link.platform === 'wechat' && typeof link.applicationId === 'string',
    )
    .map((link) => ({
      applicationId: link.applicationId,
      enterpriseId: null,
      id: link.id,
      installedAt:
        link.createdAt instanceof Date ? link.createdAt.toISOString() : String(link.createdAt),
      isEnterpriseInstall: false,
      platform: 'wechat',
      scope: '',
      tenantId: link.tenantId,
      tenantName: 'WeChat',
    }));
};

/**
 * Resolve the caller's account links once, then derive every synthetic install
 * from them: the Telegram singleton (no DB row) + user-owned WeChat accounts.
 */
const synthesizeInstallsFromLinks = async (
  serverDB: NonNullable<Parameters<typeof MessengerInstallationModel.listByInstallerUserId>[0]>,
  userId: string,
): Promise<MessengerInstallationView[]> => {
  const links = await new MessengerAccountLinkModel(serverDB, userId).list();
  const telegramView = toTelegramInstallationView(await maybeSynthesizeTelegramInstall(links));

  return [...(telegramView ? [telegramView] : []), ...synthesizeWechatInstalls(links)];
};

const disconnectWechatAccountLink = async (
  link: SafeMessengerAccountLink,
  userId: string,
): Promise<void> => {
  const installationKey = wechatInstallationKey(link.tenantId);
  await new GatewayService().disconnectUserMessenger({
    installationKey,
    platform: 'wechat',
    userId,
  });
  // Credential bundles rotate under the same installation key on rescan —
  // evict the cached Chat SDK bot so webhooks rebuild it with fresh creds.
  getMessengerRouter().invalidateBot(installationKey);
  if (!link.applicationId) return;

  const redis = getAgentRuntimeRedisClient();
  if (redis)
    await redis.del(
      wechatLegacyTokenKey(link.applicationId, link.tenantId),
      wechatWindowKey(link.applicationId, link.tenantId),
      wechatPendingPushKey(link.applicationId, link.tenantId),
    );
};

/**
 * Resolves credentials for the given platform from the user's configured bot
 * providers — the platform-level default used when a call names no connection
 * and does not target the conversation the run is replying in.
 *
 * Bots whose runtime status is `failed` are skipped: their credentials are
 * known-broken (e.g. an expired WeChat iLink session still accepts text but
 * rejects every media upload), so auto-picking one silently loses whatever the
 * agent sends. Other statuses are kept — `disconnected` is also the fallback
 * when no status was ever recorded, which is normal for webhook bots.
 *
 * Every outbound platform service is built through here, so this is also the
 * runtime paid-feature gate: an enabled provider whose plan no longer covers
 * the channel must not keep sending through the Message tool while the
 * inbound/gateway paths are already denied.
 */
const resolveCredentials = async (
  providerModel: AgentBotProviderModel,
  platform: string,
  userId: string,
): Promise<{ applicationId: string; credentials: Record<string, string> }> => {
  const providers = await providerModel.query({ platform });
  const enabled = providers.filter((p) => p.enabled && p.credentials);
  if (enabled.length === 0) {
    throw new Error(
      `No enabled ${platform} bot provider found. ` +
        `Please configure a ${platform} integration in your bot settings.`,
    );
  }
  const statuses = await Promise.all(
    enabled.map((p) => getBotRuntimeStatus(platform, p.applicationId)),
  );
  const usable = enabled.find((_, i) => statuses[i].status !== BOT_RUNTIME_STATUSES.failed);
  if (!usable) {
    throw new Error(
      `Every enabled ${platform} bot is in a failed state (App ID: ${enabled
        .map((p) => p.applicationId)
        .join(', ')}). Reconnect it in the bot settings (WeChat: rescan its QR code), ` +
        'or send through a System Bot connection from `listMessengers`.',
    );
  }
  await assertBotFeatureAccess({
    action: 'runtime',
    applicationId: usable.applicationId,
    platform,
    userId,
    workspaceId: usable.workspaceId ?? undefined,
  });
  return { applicationId: usable.applicationId, credentials: usable.credentials! };
};

/** Platforms the message tool can reach through a per-agent bot provider. */
const PROVIDER_PLATFORMS = [
  'dingtalk',
  'discord',
  'feishu',
  'imessage',
  'lark',
  'qq',
  'slack',
  'telegram',
  'wechat',
] as const;

export const messageRuntime: ServerRuntimeRegistration = {
  factory: async (context) => {
    if (!context.serverDB) {
      throw new Error('serverDB is required for Message tool execution');
    }
    if (!context.userId) {
      throw new Error('userId is required for Message tool execution');
    }

    const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
    // Mirror the TRPC router (agentBotProviderProcedure): workspace runs scope
    // bot rows and paid-feature checks to the workspace, not the personal plan.
    const providerModel = new AgentBotProviderModel(
      context.serverDB,
      context.userId,
      gateKeeper,
      context.workspaceId ?? undefined,
    );

    const userId = context.userId;
    const serverDB = context.serverDB;

    const serviceForProvider = async (platform: string) => {
      const { applicationId, credentials } = await resolveCredentials(
        providerModel,
        platform,
        userId,
      );
      return createMessageServiceForCredentials(platform, applicationId, credentials, { userId });
    };

    const serviceFactories: Record<string, () => Promise<MessageRuntimeService>> =
      Object.fromEntries(
        PROVIDER_PLATFORMS.map((platform) => [platform, () => serviceForProvider(platform)]),
      );

    // Per-agent provider takes precedence; fall back to the env-backed
    // singleton so the synthetic telegram:singleton install actually works.
    serviceFactories.telegram = async () => {
      try {
        return await serviceForProvider('telegram');
      } catch (error) {
        // A paid-gate denial is not a "provider missing" condition — falling
        // back to the env singleton here would bypass the feature gate.
        if (error instanceof BotFeatureAccessError) throw error;
        const envConfig = await getMessengerTelegramConfig();
        if (!envConfig) {
          throw new Error(
            'No enabled telegram bot provider found and no env-backed Telegram config available. ' +
              'Please configure a telegram integration in your bot settings.',
            { cause: error },
          );
        }
        return createMessageServiceForCredentials('telegram', TELEGRAM_INSTALLATION_KEY, {
          botToken: envConfig.botToken,
        });
      }
    };

    // No usable per-agent WeChat bot (none, or all failed) → the user's own
    // System Bot WeChat connection, which is where the user most likely talks
    // to LobeHub anyway.
    serviceFactories.wechat = async () => {
      try {
        return await serviceForProvider('wechat');
      } catch (error) {
        if (error instanceof BotFeatureAccessError) throw error;
        const link = await new MessengerAccountLinkModel(serverDB, userId).findByPlatform('wechat');
        if (!link) throw error;
        return (await resolveMessengerInstallTarget({ serverDB, userId }, link.id)).service;
      }
    };

    // The IM conversation this run replies in, as stamped on its topic by the
    // bot/messenger router. Loaded at most once per runtime, only when a call
    // actually needs it.
    let inboundBotContext: Promise<ChatTopicBotContext | undefined> | undefined;
    const loadInboundBotContext = () => {
      inboundBotContext ??= (async () => {
        if (!context.topicId) return undefined;
        const topic = await new TopicModel(
          serverDB,
          userId,
          context.workspaceId ?? undefined,
        ).findById(context.topicId);
        return topic?.metadata?.bot as ChatTopicBotContext | undefined;
      })();
      return inboundBotContext;
    };

    /**
     * The connection the current conversation arrived on: the System Bot
     * install (messenger runs carry `messengerInstallationKey`) or the
     * per-agent bot whose `applicationId` received it. Undefined when that
     * connection is gone — callers then fall back to platform routing.
     */
    const resolveInboundTarget = async (
      botContext: ChatTopicBotContext,
    ): Promise<ResolvedMessageTarget | undefined> => {
      if (botContext.messengerInstallationKey) {
        return resolveMessengerKeyTarget(botContext.platform, botContext.messengerInstallationKey);
      }
      const provider = await providerModel.findEnabledByApplicationId(
        botContext.platform,
        botContext.applicationId,
      );
      if (!provider) return undefined;
      await assertBotFeatureAccess({
        action: 'runtime',
        applicationId: provider.applicationId,
        platform: provider.platform,
        userId,
        workspaceId: provider.workspaceId ?? undefined,
      });
      return {
        applicationId: provider.applicationId,
        platform: botContext.platform as ResolvedMessageTarget['platform'],
        service: createMessageServiceForCredentials(
          provider.platform,
          provider.applicationId,
          provider.credentials as Record<string, any>,
          { userId },
        ),
        settings: {},
      };
    };

    const assertTargetPlatform = (
      target: ResolvedMessageTarget,
      params: MessageRouteParams,
      label: string,
    ) => {
      if (target.platform !== params.platform) {
        throw new Error(
          `${label} is a ${target.platform} connection, but the call targets ${params.platform}.`,
        );
      }
    };

    // Resolved connections, cached per routing key for this runtime.
    const routedServices = new Map<string, MessageRuntimeService>();
    const cachedRoute = async (
      key: string,
      resolve: () => Promise<MessageRuntimeService | undefined>,
    ) => {
      const cached = routedServices.get(key);
      if (cached) return cached;
      const service = await resolve();
      if (service) routedServices.set(key, service);
      return service;
    };

    /**
     * Connection priority for every call: explicit `botId` → explicit
     * `messengerInstallationId` → the connection the current conversation
     * arrived on (same platform only) → the platform default above.
     *
     * Without the inbound step, a WeChat conversation held over the System
     * Bot would have its files sent through whatever per-agent WeChat bot the
     * account also has — including a failed one, whose expired session rejects
     * every upload.
     */
    const resolveRoute = async (
      params: MessageRouteParams,
    ): Promise<MessageRuntimeService | undefined> => {
      const { botId, messengerInstallationId } = params;
      if (botId && messengerInstallationId) {
        throw new Error('Provide at most one of botId or messengerInstallationId.');
      }

      if (botId) {
        return cachedRoute(`bot:${botId}`, async () => {
          const target = await resolveBotMessageTarget(providerModel, botId, { userId });
          assertTargetPlatform(target, params, `Bot ${botId}`);
          await assertBotFeatureAccess({
            action: 'runtime',
            applicationId: target.applicationId,
            platform: target.platform,
            userId,
            workspaceId: target.provider.workspaceId ?? undefined,
          });
          return target.service;
        });
      }

      if (messengerInstallationId) {
        return cachedRoute(`messenger:${messengerInstallationId}`, async () => {
          const target = await resolveMessengerInstallTarget(
            { serverDB, userId },
            messengerInstallationId,
          );
          assertTargetPlatform(target, params, `Messenger connection ${messengerInstallationId}`);
          return target.service;
        });
      }

      const botContext = await loadInboundBotContext();
      if (botContext?.platform !== params.platform) return undefined;
      return cachedRoute(
        `inbound:${botContext.platform}`,
        async () => (await resolveInboundTarget(botContext))?.service,
      );
    };

    const service = new MessageDispatcherService(serviceFactories, { resolveRoute });

    /**
     * Bot runs act with the owner's credentials, so whoever talks to the bot in a shared channel
     * could otherwise talk it into rewiring itself. Every call that changes a bot or messenger
     * connection refuses unless the person who sent the message this run answers is the owner.
     * Keyed on the run's own sender (`botContext`, built per inbound message), not the topic's
     * first author; a run outside an IM conversation carries none and is unaffected.
     */
    const assertOwnerMayManageBots = () => {
      if (context.botContext && !context.botContext.isOwner) {
        throw new Error(
          "Only the bot's owner can change its settings. Ask them to make this change.",
        );
      }
    };

    const botProvider: BotProviderQuery = {
      connectBot: async (botId) => {
        assertOwnerMayManageBots();
        const bot = await providerModel.findById(botId);
        if (!bot) throw new Error(`Bot not found: ${botId}`);
        await assertBotFeatureAccess({
          action: 'manage',
          applicationId: bot.applicationId,
          platform: bot.platform,
          userId: context.userId!,
          workspaceId: bot.workspaceId ?? undefined,
        });
        const gateway = new GatewayService();
        const status = await gateway.startClient(bot.platform, bot.applicationId, context.userId!);
        return { status };
      },
      createBot: async (params) => {
        assertOwnerMayManageBots();
        const unavailableReason = getReplyConnectionUnavailableReason(
          platformRegistry.getPlatform(params.platform),
        );
        if (unavailableReason) throw new Error(unavailableReason);
        await assertBotFeatureAccess({
          action: 'manage',
          applicationId: params.applicationId,
          platform: params.platform,
          userId: context.userId!,
          workspaceId: context.workspaceId ?? undefined,
        });
        const settings = await mergeBotSettingsForCreate(
          serverDB,
          params.agentId,
          params.platform,
          params.settings,
        );
        assertBotAccessSettings(settings);
        await assertWatchKeywordsWritable({
          applicationId: params.applicationId,
          platform: params.platform,
          settings,
          userId: context.userId!,
          workspaceId: context.workspaceId ?? undefined,
        });
        const result = await providerModel.create({ ...params, settings });
        return { id: result.id, platform: params.platform };
      },
      deleteBot: async (botId) => {
        assertOwnerMayManageBots();
        const existing = await providerModel.findById(botId);
        await providerModel.delete(botId);
        if (existing) {
          await invalidateBotAfterUpdate(
            {
              applicationId: existing.applicationId,
              platform: existing.platform,
              userId: context.userId!,
            },
            { enabled: false },
          );
        }
      },
      getBotDetail: async (botId) => {
        const bot = await providerModel.findById(botId);
        if (!bot) return null;
        const status = await getBotRuntimeStatus(bot.platform, bot.applicationId);
        return {
          applicationId: bot.applicationId,
          enabled: bot.enabled,
          id: bot.id,
          platform: bot.platform,
          runtimeStatus: status.status,
          // As the settings form shows them, so the agent reads the keys `updateBot` writes
          // (`botWakeDuties`) even for a bot configured with a nested `botWake` object.
          settings: flattenBotWakeSettings(bot.settings as Record<string, unknown>) ?? undefined,
        };
      },
      listBots: async () => {
        if (!context.agentId) {
          throw new Error('agentId is required to list bots');
        }
        const providers = await providerModel.findByAgentId(context.agentId);

        const statuses = await Promise.all(
          providers.map((p) => getBotRuntimeStatus(p.platform, p.applicationId)),
        );
        return providers.map((p, i) => ({
          applicationId: p.applicationId,
          enabled: p.enabled,
          id: p.id,
          serverId: (p.settings as any)?.serverId as string | undefined,
          userId: (p.settings as any)?.userId as string | undefined,
          platform: p.platform,
          runtimeStatus: statuses[i].status,
        }));
      },
      listPlatforms: async () => {
        // Platforms this deployment cannot run are not offered for new bots; existing ones still
        // show up in `listBots` so they can be disabled or removed.
        return platformRegistry
          .listSerializedPlatforms()
          .filter((p) => !getReplyConnectionUnavailableReason(p))
          .map((p) => {
            const credSchema = (p.schema ?? []).find(
              (f: any) => f.key === 'credentials' && f.properties,
            );
            const credFields = (credSchema as any)?.properties ?? [];
            return {
              credentialFields: credFields.map((f: any) => ({
                key: f.key,
                label: f.label ?? f.key,
                required: !!f.required,
                type: f.type ?? 'string',
              })),
              id: p.id,
              name: p.name,
            };
          });
      },
      toggleBot: async (botId, enabled) => {
        assertOwnerMayManageBots();
        const existing = await providerModel.findById(botId);
        if (!existing) throw new Error(`Bot not found: ${botId}`);
        if (enabled) {
          await assertBotFeatureAccess({
            action: 'manage',
            applicationId: existing.applicationId,
            platform: existing.platform,
            userId: context.userId!,
            workspaceId: existing.workspaceId ?? undefined,
          });
        }
        await providerModel.update(botId, { enabled });
        await invalidateBotAfterUpdate(
          {
            applicationId: existing.applicationId,
            platform: existing.platform,
            userId: context.userId!,
          },
          { enabled },
        );
      },
      updateBot: async (botId, params) => {
        assertOwnerMayManageBots();
        const existing = await providerModel.findById(botId);
        if (!existing) throw new Error(`Bot not found: ${botId}`);
        await assertBotFeatureAccess({
          action: 'manage',
          applicationId: existing.applicationId,
          platform: existing.platform,
          userId: context.userId!,
          workspaceId: existing.workspaceId ?? undefined,
        });

        const value: { credentials?: Record<string, string>; settings?: Record<string, unknown> } =
          {};
        if (params.credentials !== undefined) value.credentials = params.credentials;
        if (params.settings !== undefined) {
          // A partial update: the keys the agent did not send keep their stored values.
          const merged = mergeBotSettingsPatch(
            existing.platform,
            existing.settings as Record<string, unknown> | null,
            params.settings,
          );
          assertBotAccessSettings(merged);
          await assertWatchKeywordsWritable({
            applicationId: existing.applicationId,
            existingSettings: existing.settings,
            platform: existing.platform,
            settings: merged,
            userId: context.userId!,
            workspaceId: existing.workspaceId ?? undefined,
          });
          value.settings = merged;
        }

        await providerModel.update(botId, value);
        await invalidateBotAfterUpdate(
          {
            applicationId: existing.applicationId,
            credentials: existing.credentials,
            platform: existing.platform,
            settings: existing.settings,
            userId: context.userId!,
          },
          value,
        );
      },

      // ─── System Bot messenger management ─────────────────────────────────
      // Mirrors `messenger.*` TRPC procedures but exposed via the tool runtime
      // so LLM-driven flows can manage installs + links the same way the
      // Marketplace → Apps UI does. Each handler enforces user ownership;
      // the underlying models are already user-scoped where applicable.
      listMessengers: async () => {
        if (!context.userId || !context.serverDB) {
          throw new Error('userId and serverDB are required to list System Bot installations');
        }
        const linkGateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
        const rows = await MessengerInstallationModel.listByInstallerUserId(
          context.serverDB,
          context.userId,
          linkGateKeeper,
        );
        // We intentionally skip the Slack auth.test reconciliation that the
        // `messenger.listMyInstallations` TRPC procedure runs. A stale Slack
        // install will still appear here; the actual send/uninstall call will
        // surface the underlying token error if and when it matters.
        const installations: MessengerInstallationView[] = rows
          .filter((row) => !row.revokedAt && row.platform !== 'wechat')
          .map((row) => ({
            applicationId: row.applicationId,
            enterpriseId:
              ((row.metadata as Record<string, unknown> | null)?.enterpriseId as
                string | null | undefined) ?? null,
            id: row.id,
            installedAt:
              row.createdAt instanceof Date ? row.createdAt.toISOString() : String(row.createdAt),
            isEnterpriseInstall:
              (row.metadata as Record<string, unknown> | null)?.isEnterpriseInstall === true,
            platform: row.platform,
            scope: ((row.metadata as Record<string, unknown> | null)?.scope as string) ?? '',
            tenantId: row.tenantId,
            tenantName:
              ((row.metadata as Record<string, unknown> | null)?.tenantName as string) ?? '',
          }));

        installations.push(
          ...(await synthesizeInstallsFromLinks(context.serverDB, context.userId)),
        );

        return installations;
      },

      getMessengerDetail: async (installationId) => {
        if (!context.userId || !context.serverDB) {
          throw new Error('userId and serverDB are required to load installation');
        }
        // Telegram singleton has no DB row — synthesize the detail view from
        // env config + the caller's account link. Without this branch the
        // synthetic install id returned by `listMessengers` would 404 here.
        if (installationId === TELEGRAM_INSTALLATION_KEY) {
          const links = await new MessengerAccountLinkModel(
            context.serverDB,
            context.userId,
          ).list();
          const telegramView = toTelegramInstallationView(
            await maybeSynthesizeTelegramInstall(links),
          );
          if (!telegramView) return null;
          return { ...telegramView, revokedAt: null };
        }
        const wechatLink = await new MessengerAccountLinkModel(
          context.serverDB,
          context.userId,
        ).findById(installationId, 'wechat');
        if (wechatLink?.applicationId) {
          return {
            applicationId: wechatLink.applicationId,
            enterpriseId: null,
            id: wechatLink.id,
            installedAt:
              wechatLink.createdAt instanceof Date
                ? wechatLink.createdAt.toISOString()
                : String(wechatLink.createdAt),
            isEnterpriseInstall: false,
            platform: 'wechat',
            revokedAt: null,
            scope: '',
            tenantId: wechatLink.tenantId,
            tenantName: 'WeChat',
          };
        }
        const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
        const row = await MessengerInstallationModel.findById(
          context.serverDB,
          installationId,
          gateKeeper,
        );
        if (!row) return null;
        // Same ownership guard as `messenger.uninstallInstallation` — the
        // installer is the only user who can see install metadata via the tool.
        if (row.installedByUserId !== context.userId) {
          throw new Error('You can only view installations you initiated');
        }
        return {
          applicationId: row.applicationId,
          enterpriseId:
            ((row.metadata as Record<string, unknown> | null)?.enterpriseId as
              string | null | undefined) ?? null,
          id: row.id,
          installedAt:
            row.createdAt instanceof Date ? row.createdAt.toISOString() : String(row.createdAt),
          isEnterpriseInstall:
            (row.metadata as Record<string, unknown> | null)?.isEnterpriseInstall === true,
          platform: row.platform,
          revokedAt:
            row.revokedAt instanceof Date ? row.revokedAt.toISOString() : (row.revokedAt ?? null),
          scope: ((row.metadata as Record<string, unknown> | null)?.scope as string) ?? '',
          tenantId: row.tenantId,
          tenantName:
            ((row.metadata as Record<string, unknown> | null)?.tenantName as string) ?? '',
        };
      },

      uninstallMessenger: async (installationId) => {
        assertOwnerMayManageBots();
        if (!context.userId || !context.serverDB) {
          throw new Error('userId and serverDB are required to uninstall');
        }
        // Telegram is env-backed and shared across all users — there is no
        // installation row to revoke. Direct callers to `unlinkMessenger`,
        // which removes only this user's routing without affecting anyone else.
        if (installationId === TELEGRAM_INSTALLATION_KEY) {
          throw new TRPCError({
            code: 'BAD_REQUEST',
            message:
              'Telegram is a global env-backed bot and cannot be uninstalled here. ' +
              "Use unlinkMessenger({ platform: 'telegram' }) to remove your own routing.",
          });
        }
        const linkModel = new MessengerAccountLinkModel(context.serverDB, context.userId);
        const wechatLink = await linkModel.findById(installationId, 'wechat');
        if (wechatLink) {
          await linkModel.delete(wechatLink.id);
          await disconnectWechatAccountLink(wechatLink, context.userId);
          return;
        }
        const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
        const row = await MessengerInstallationModel.findById(
          context.serverDB,
          installationId,
          gateKeeper,
        );
        if (!row) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `Installation not found: ${installationId}`,
          });
        }
        if (row.installedByUserId !== context.userId) {
          throw new TRPCError({
            code: 'FORBIDDEN',
            message: 'You can only uninstall installations you initiated',
          });
        }
        await MessengerInstallationModel.markRevoked(context.serverDB, row.id);
      },

      listMessengerPlatforms: async () => {
        // Mirror of `messenger.availablePlatforms` — surfaces per-deployment
        // OAuth deep-link fields (appId / botUsername) so the LLM can tell the
        // user *which* LobeHub bot identity they'd be installing.
        const enabled = await getEnabledMessengerPlatforms();
        const enabledSet = new Set<string>(enabled);
        const definitions = messengerPlatformRegistry
          .listSerializedPlatforms()
          .filter((def) => enabledSet.has(def.id));

        const [discordConfig, slackConfig, telegramConfig] = await Promise.all([
          enabledSet.has('discord') ? getMessengerDiscordConfig() : Promise.resolve(null),
          enabledSet.has('slack') ? getMessengerSlackConfig() : Promise.resolve(null),
          enabledSet.has('telegram') ? getMessengerTelegramConfig() : Promise.resolve(null),
        ]);

        return definitions.map((def) => ({
          appId:
            def.id === 'slack'
              ? slackConfig?.appId
              : def.id === 'discord'
                ? discordConfig?.applicationId
                : undefined,
          botUsername: def.id === 'telegram' ? telegramConfig?.botUsername : undefined,
          id: def.id,
          name: def.name,
        }));
      },

      listMessengerLinks: async () => {
        if (!context.userId || !context.serverDB) {
          throw new Error('userId and serverDB are required to list account links');
        }
        const linkModel = new MessengerAccountLinkModel(context.serverDB, context.userId);
        const rows = await linkModel.list();
        return rows.map((row) => ({
          activeAgentId: row.activeAgentId ?? null,
          createdAt:
            row.createdAt instanceof Date ? row.createdAt.toISOString() : String(row.createdAt),
          platform: row.platform,
          platformUserId: row.platformUserId,
          platformUsername: row.platformUsername ?? undefined,
          tenantId: row.tenantId || undefined,
        }));
      },

      setMessengerActiveAgent: async (params) => {
        assertOwnerMayManageBots();
        if (!context.userId || !context.serverDB) {
          throw new Error('userId and serverDB are required');
        }
        // Validate agent ownership before mutating the link — matches the
        // `messenger.setActiveAgent` behavior (rejects cross-user agent ids).
        if (params.agentId !== null) {
          const [agentRow] = await context.serverDB
            .select({ id: agents.id })
            .from(agents)
            .where(
              and(
                eq(agents.id, params.agentId),
                eq(agents.userId, context.userId),
                notTrashed(agents.isDeleted),
              ),
            )
            .limit(1);
          if (!agentRow) {
            throw new TRPCError({
              code: 'NOT_FOUND',
              message: `Agent not found or not owned by you: ${params.agentId}`,
            });
          }
        }
        const linkModel = new MessengerAccountLinkModel(context.serverDB, context.userId);
        // This in-chat tool only resolves personal-owned agents (validated
        // above via `agents.userId === userId`), so the active scope is always
        // personal (`workspaceId: null`).
        const updated = await linkModel.setActiveAgent(
          params.platform,
          params.agentId,
          null,
          params.tenantId,
        );
        if (!updated) {
          throw new TRPCError({
            code: 'NOT_FOUND',
            message: `No account link found for ${params.platform}${params.tenantId ? ` (tenant ${params.tenantId})` : ''}. The user must complete verify-im first.`,
          });
        }
      },

      unlinkMessenger: async (params) => {
        assertOwnerMayManageBots();
        if (!context.userId || !context.serverDB) {
          throw new Error('userId and serverDB are required');
        }
        const linkModel = new MessengerAccountLinkModel(context.serverDB, context.userId);
        if (params.platform === 'wechat') {
          const links = (await linkModel.list()).filter(
            (link) =>
              link.platform === 'wechat' &&
              (params.tenantId === undefined || link.tenantId === params.tenantId),
          );
          await linkModel.deleteByPlatform(params.platform, params.tenantId);
          await Promise.all(
            links.map((link) => disconnectWechatAccountLink(link, context.userId!)),
          );
          return;
        }
        await linkModel.deleteByPlatform(params.platform, params.tenantId);
      },

      // Proactive push into the caller's own DM. The runtime already resolved
      // Slack workspace ambiguity, so this is a straight pass-through to the
      // platform-agnostic push entry (same one the settings UI test-push uses).
      sendMessengerPush: async (params) => {
        if (!context.userId || !context.serverDB) {
          throw new Error('userId and serverDB are required to push messenger messages');
        }
        // The TRPC route caps this with Zod, but this runtime calls the push
        // service directly and `BaseExecutor` dispatches params unvalidated —
        // so without this guard the advertised limit would hold on the client
        // path and silently vanish on the server path (the Cloud default).
        // Rejecting beats truncating: a half-delivered notification reads as
        // complete to the recipient, while an error lets the agent summarize
        // or split and retry.
        if (params.content.length > MESSENGER_PUSH_CONTENT_MAX_LENGTH) {
          throw new Error(
            `Message content is ${params.content.length} characters, exceeding the ${MESSENGER_PUSH_CONTENT_MAX_LENGTH}-character limit. Summarize or split it before pushing.`,
          );
        }
        const result = await sendMessengerPush({
          content: params.content,
          platform: params.platform,
          serverDB: context.serverDB,
          tenantId: params.tenantId,
          userId: context.userId,
        });
        return { remaining: result.remaining, status: result.status };
      },
    };

    return new MessageExecutionRuntime({
      botProvider,
      resolveImages: createMessageImageStore({
        agentId: context.agentId,
        serverDB,
        userId,
        workspaceId: context.workspaceId,
      }),
      service,
    });
  },
  identifier: MessageToolIdentifier,
};