π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(message): route IM sends through the conversation's own connection (#19893)
Rdmclin2c900f2315f61
diff --git a/apps/server/src/routers/lambda/botMessage.ts b/apps/server/src/routers/lambda/botMessage.tsindex dcb8343ef4a..97f2f2353c1 100644--- a/apps/server/src/routers/lambda/botMessage.ts+++ b/apps/server/src/routers/lambda/botMessage.ts@@ -1,8 +1,5 @@import type { MessagePlatformType } from '@lobechat/builtin-tool-message';import type { MessageRuntimeService } from '@lobechat/builtin-tool-message/executionRuntime';-import { LarkApiClient } from '@lobechat/chat-adapter-feishu';-import { QQApiClient } from '@lobechat/chat-adapter-qq';-import { WechatApiClient } from '@lobechat/chat-adapter-wechat';import {DEFAULT_BOT_HISTORY_LIMIT,MAX_BOT_HISTORY_LIMIT,@@ -13,25 +10,14 @@ import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';-import { getMessengerTelegramConfig } from '@/config/messenger';-import type { DecryptedBotProvider } from '@/database/models/agentBotProvider';import { AgentBotProviderModel } from '@/database/models/agentBotProvider';-import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';-import { MessengerInstallationModel } from '@/database/models/messengerInstallation';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';-import { mergeWithDefaults, platformRegistry } from '@/server/services/bot/platforms';-import { DiscordApi } from '@/server/services/bot/platforms/discord/api';-import { DiscordMessageService } from '@/server/services/bot/platforms/discord/service';-import { FeishuMessageService } from '@/server/services/bot/platforms/feishu/service';-import { QQMessageService } from '@/server/services/bot/platforms/qq/service';-import { SlackApi } from '@/server/services/bot/platforms/slack/api';-import { SlackMessageService } from '@/server/services/bot/platforms/slack/service';-import { TelegramApi } from '@/server/services/bot/platforms/telegram/api';-import { TelegramMessageService } from '@/server/services/bot/platforms/telegram/service';-import { WechatMessageService } from '@/server/services/bot/platforms/wechat/service';-import { TELEGRAM_INSTALLATION_KEY } from '@/server/services/messenger/installations/telegram';+import {+ resolveBotMessageTarget,+ resolveMessengerInstallTarget,+} from '@/server/services/bot/messageTarget';// ββ Middleware ββββββββββββββββββββββββββββββββββββββββββββ@@ -92,193 +78,10 @@ const embedsInputSchema = z.array(.passthrough(),);-// ββ Service Factory ββββββββββββββββββββββββββββββββββββββ--/**- * Build a `MessageRuntimeService` from raw platform + applicationId +- * credentials. Shared between two resolution sources:- *- * 1. Per-agent bot channels (`agent_bot_providers` row) β `resolveBot`- * 2. System Bot messenger installs (`messenger_installations` row) β- * `resolveMessengerInstall`- *- * Both paths produce the same underlying outbound API client, so the- * downstream `MessageRuntimeService` behavior (attachments included) is- * identical regardless of where the credentials came from.- */-const createServiceForCredentials = (- platform: string,- applicationId: string,- credentials: Record<string, any>,-): MessageRuntimeService => {- switch (platform) {- case 'discord': {- return new DiscordMessageService(new DiscordApi(credentials.botToken));- }- case 'slack': {- return new SlackMessageService(new SlackApi(credentials.botToken));- }- case 'telegram': {- return new TelegramMessageService(new TelegramApi(credentials.botToken));- }- case 'feishu': {- return new FeishuMessageService(- new LarkApiClient(applicationId, credentials.appSecret, 'feishu'),- 'feishu',- );- }- case 'lark': {- return new FeishuMessageService(- new LarkApiClient(applicationId, credentials.appSecret, 'lark'),- 'lark',- );- }- case 'qq': {- return new QQMessageService(new QQApiClient(applicationId, credentials.appSecret));- }- case 'wechat': {- return new WechatMessageService(- // `baseUrl` is issued during QR confirmation and must be honored when- // it differs from the default endpoint (see wechat/protocol-spec.md).- new WechatApiClient(credentials.botToken, credentials.botId, credentials.baseUrl),- applicationId,- );- }- default: {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Unsupported platform: ${platform}`,- });- }- }-};--const createServiceForBot = (provider: DecryptedBotProvider): MessageRuntimeService =>- createServiceForCredentials(- provider.platform,- provider.applicationId,- provider.credentials as Record<string, any>,- );--const resolveBot = async (- model: AgentBotProviderModel,- botId: string,-): Promise<{- platform: MessagePlatformType;- service: MessageRuntimeService;- settings: Record<string, unknown>;-}> => {- const provider = await model.findById(botId);- if (!provider) {- throw new TRPCError({ code: 'NOT_FOUND', message: `Bot not found: ${botId}` });- }- if (!provider.enabled) {- throw new TRPCError({ code: 'BAD_REQUEST', message: `Bot is disabled: ${botId}` });- }- const definition = platformRegistry.getPlatform(provider.platform);- const settings = definition- ? mergeWithDefaults(definition.schema, provider.settings as Record<string, unknown> | undefined)- : ((provider.settings as Record<string, unknown>) ?? {});- return {- platform: provider.platform as MessagePlatformType,- service: createServiceForBot(provider),- settings,- };-};--/** Resolve a user-owned System Bot connection into a runnable service. */-const resolveMessengerInstall = async (- ctx: { serverDB: any; userId: string },- installationId: string,-): Promise<{- platform: MessagePlatformType;- service: MessageRuntimeService;- settings: Record<string, unknown>;-}> => {- // Telegram is env-backed and never lives in `messenger_installations`. The- // synthetic id surfaced by `listMessengers` would 404 on `findById`, so- // short-circuit here: pull the bot token from env config and gate on the- // caller having an account link (analogue of the per-row ownership check).- if (installationId === TELEGRAM_INSTALLATION_KEY) {- const telegramConfig = await getMessengerTelegramConfig();- if (!telegramConfig) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: 'Telegram messenger is not configured on this deployment',- });- }- const link = await new MessengerAccountLinkModel(ctx.serverDB, ctx.userId).findByPlatform(- 'telegram',- );- if (!link) {- throw new TRPCError({- code: 'FORBIDDEN',- message:- 'You can only send through Telegram after linking your account. ' +- 'Open the Telegram bot and run /start to create the link.',- });- }- return {- platform: 'telegram',- service: createServiceForCredentials('telegram', TELEGRAM_INSTALLATION_KEY, {- botToken: telegramConfig.botToken,- }),- settings: {},- };- }-- const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);- const wechatLink = await new MessengerAccountLinkModel(- ctx.serverDB,- ctx.userId,- ).findByIdWithCredentials(installationId, 'wechat', gateKeeper);- if (wechatLink) {- if (!wechatLink.applicationId || typeof wechatLink.credentials.botToken !== 'string') {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `WeChat connection credentials are unavailable: ${installationId}`,- });- }- return {- platform: 'wechat',- service: createServiceForCredentials(- 'wechat',- wechatLink.applicationId,- wechatLink.credentials,- ),- settings: {},- };- }-- const row = await MessengerInstallationModel.findById(ctx.serverDB, installationId, gateKeeper);- if (!row) {- throw new TRPCError({- code: 'NOT_FOUND',- message: `Messenger installation not found: ${installationId}`,- });- }- if (row.revokedAt) {- throw new TRPCError({- code: 'BAD_REQUEST',- message: `Messenger installation has been revoked: ${installationId}`,- });- }- if (row.installedByUserId !== ctx.userId) {- throw new TRPCError({- code: 'FORBIDDEN',- message: 'You can only send through messenger installs you initiated',- });- }- return {- platform: row.platform as MessagePlatformType,- service: createServiceForCredentials(- row.platform,- row.applicationId,- row.credentials as Record<string, any>,- ),- settings: {},- };-};+// ββ Target resolution ββββββββββββββββββββββββββββββββββββ+// Credential β service resolution lives in `@/server/services/bot/messageTarget`+// so the server tool runtime routes `botId` / `messengerInstallationId`+// exactly like these procedures do./*** Common dispatcher: either a per-agent `botId` or a system-bot@@ -294,9 +97,9 @@ const resolveSendTarget = async (service: MessageRuntimeService;settings: Record<string, unknown>;}> => {- if (input.botId) return resolveBot(ctx.agentBotProviderModel, input.botId);+ if (input.botId) return resolveBotMessageTarget(ctx.agentBotProviderModel, input.botId);if (input.messengerInstallationId)- return resolveMessengerInstall(+ return resolveMessengerInstallTarget({ serverDB: ctx.serverDB, userId: ctx.userId },input.messengerInstallationId,);@@ -393,7 +196,7 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform, settings } = await resolveBot(+ const { service, platform, settings } = await resolveBotMessageTarget(ctx.agentBotProviderModel,input.botId,);@@ -423,7 +226,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );if (!service.readDocument) {throw new TRPCError({code: 'BAD_REQUEST',@@ -447,7 +253,10 @@ export const botMessageRouter = router({}),).mutation(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.editMessage({channelId: input.channelId,content: input.content,@@ -465,7 +274,10 @@ export const botMessageRouter = router({}),).mutation(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.deleteMessage({channelId: input.channelId,messageId: input.messageId,@@ -484,7 +296,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.searchMessages({authorId: input.authorId,channelId: input.channelId,@@ -506,7 +321,10 @@ export const botMessageRouter = router({}),).mutation(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.reactToMessage({channelId: input.channelId,emoji: input.emoji,@@ -524,7 +342,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.getReactions({channelId: input.channelId,messageId: input.messageId,@@ -543,7 +364,10 @@ export const botMessageRouter = router({}),).mutation(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.pinMessage({channelId: input.channelId,messageId: input.messageId,@@ -560,7 +384,10 @@ export const botMessageRouter = router({}),).mutation(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.unpinMessage({channelId: input.channelId,messageId: input.messageId,@@ -576,7 +403,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.listPins({channelId: input.channelId,platform,@@ -593,7 +423,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.getChannelInfo({channelId: input.channelId,platform,@@ -609,7 +442,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.listChannels({filter: input.filter,platform,@@ -628,7 +464,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.getMemberInfo({memberId: input.memberId,platform,@@ -649,7 +488,10 @@ export const botMessageRouter = router({}),).mutation(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.createThread({channelId: input.channelId,content: input.content,@@ -667,7 +509,10 @@ export const botMessageRouter = router({}),).query(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.listThreads({channelId: input.channelId,platform,@@ -714,7 +559,10 @@ export const botMessageRouter = router({}),).mutation(async ({ input, ctx }) => {- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);+ const { service, platform } = await resolveBotMessageTarget(+ ctx.agentBotProviderModel,+ input.botId,+ );return service.createPoll({channelId: input.channelId,duration: input.duration,diff --git a/apps/server/src/services/bot/messageTarget.ts b/apps/server/src/services/bot/messageTarget.tsnew file mode 100644index 00000000000..0922c2046f4--- /dev/null+++ b/apps/server/src/services/bot/messageTarget.ts@@ -0,0 +1,269 @@+import type { MessagePlatformType } from '@lobechat/builtin-tool-message';+import type { MessageRuntimeService } from '@lobechat/builtin-tool-message/executionRuntime';+import { LarkApiClient } from '@lobechat/chat-adapter-feishu';+import { QQApiClient } from '@lobechat/chat-adapter-qq';+import { WechatApiClient } from '@lobechat/chat-adapter-wechat';+import { TRPCError } from '@trpc/server';++import type { MessengerPlatform } from '@/config/messenger';+import { getMessengerTelegramConfig } from '@/config/messenger';+import type {+ AgentBotProviderModel,+ DecryptedBotProvider,+} from '@/database/models/agentBotProvider';+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';+import { MessengerInstallationModel } from '@/database/models/messengerInstallation';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { mergeWithDefaults, platformRegistry } from '@/server/services/bot/platforms';+import { DiscordApi } from '@/server/services/bot/platforms/discord/api';+import { DiscordMessageService } from '@/server/services/bot/platforms/discord/service';+import { FeishuMessageService } from '@/server/services/bot/platforms/feishu/service';+import { ImessageDesktopBridgeApi } from '@/server/services/bot/platforms/imessage/desktopBridge';+import { ImessageMessageService } from '@/server/services/bot/platforms/imessage/service';+import { QQMessageService } from '@/server/services/bot/platforms/qq/service';+import { SlackApi } from '@/server/services/bot/platforms/slack/api';+import { SlackMessageService } from '@/server/services/bot/platforms/slack/service';+import { TelegramApi } from '@/server/services/bot/platforms/telegram/api';+import { TelegramMessageService } from '@/server/services/bot/platforms/telegram/service';+import { WechatMessageService } from '@/server/services/bot/platforms/wechat/service';+import { getInstallationStore } from '@/server/services/messenger/installations';+import { TELEGRAM_INSTALLATION_KEY } from '@/server/services/messenger/installations/telegram';++/**+ * A concrete outbound connection for the `lobe-message` send APIs: the+ * platform service built from one bot's credentials, plus which bot it is.+ */+export interface ResolvedMessageTarget {+ /** Platform-side bot identity (e.g. the WeChat iLink App ID). */+ applicationId: string;+ platform: MessagePlatformType;+ service: MessageRuntimeService;+ settings: Record<string, unknown>;+}++/**+ * Build a `MessageRuntimeService` from raw platform + applicationId ++ * credentials. Shared by every resolution source β per-agent bot channels+ * (`agent_bot_providers`), System Bot connections (`messenger_installations`+ * / WeChat account links) and inbound messenger installation keys β so the+ * downstream behavior (attachments included) is identical regardless of+ * where the credentials came from.+ *+ * `userId` is only needed by iMessage, whose desktop bridge is addressed per+ * user; without it iMessage is reported as unsupported.+ */+export const createMessageServiceForCredentials = (+ platform: string,+ applicationId: string,+ credentials: Record<string, any>,+ options: { userId?: string } = {},+): MessageRuntimeService => {+ switch (platform) {+ case 'discord': {+ return new DiscordMessageService(new DiscordApi(credentials.botToken));+ }+ case 'slack': {+ return new SlackMessageService(new SlackApi(credentials.botToken));+ }+ case 'telegram': {+ return new TelegramMessageService(new TelegramApi(credentials.botToken));+ }+ case 'feishu': {+ return new FeishuMessageService(+ new LarkApiClient(applicationId, credentials.appSecret, 'feishu'),+ 'feishu',+ );+ }+ case 'lark': {+ return new FeishuMessageService(+ new LarkApiClient(applicationId, credentials.appSecret, 'lark'),+ 'lark',+ );+ }+ case 'qq': {+ return new QQMessageService(new QQApiClient(applicationId, credentials.appSecret));+ }+ case 'wechat': {+ return new WechatMessageService(+ // `baseUrl` is issued during QR confirmation and must be honored when+ // it differs from the default endpoint (see wechat/protocol-spec.md).+ new WechatApiClient(credentials.botToken, credentials.botId, credentials.baseUrl),+ applicationId,+ );+ }+ case 'imessage': {+ if (options.userId) {+ return new ImessageMessageService(+ new ImessageDesktopBridgeApi({+ applicationId,+ deviceId: credentials.desktopDeviceId,+ userId: options.userId,+ }),+ );+ }+ break;+ }+ }++ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Unsupported platform: ${platform}`,+ });+};++/** Resolve a per-agent bot (`listBots` β `botId`) into a runnable target. */+export const resolveBotMessageTarget = async (+ model: AgentBotProviderModel,+ botId: string,+ options: { userId?: string } = {},+): Promise<ResolvedMessageTarget & { provider: DecryptedBotProvider }> => {+ const provider = await model.findById(botId);+ if (!provider) {+ throw new TRPCError({ code: 'NOT_FOUND', message: `Bot not found: ${botId}` });+ }+ if (!provider.enabled) {+ throw new TRPCError({ code: 'BAD_REQUEST', message: `Bot is disabled: ${botId}` });+ }+ const definition = platformRegistry.getPlatform(provider.platform);+ const settings = definition+ ? mergeWithDefaults(definition.schema, provider.settings as Record<string, unknown> | undefined)+ : ((provider.settings as Record<string, unknown>) ?? {});+ return {+ applicationId: provider.applicationId,+ platform: provider.platform as MessagePlatformType,+ provider,+ service: createMessageServiceForCredentials(+ provider.platform,+ provider.applicationId,+ provider.credentials as Record<string, any>,+ options,+ ),+ settings,+ };+};++/**+ * Resolve a user-owned System Bot connection (`listMessengers` β+ * `messengerInstallationId`) into a runnable target.+ */+export const resolveMessengerInstallTarget = async (+ ctx: { serverDB: any; userId: string },+ installationId: string,+): Promise<ResolvedMessageTarget> => {+ // Telegram is env-backed and never lives in `messenger_installations`. The+ // synthetic id surfaced by `listMessengers` would 404 on `findById`, so+ // short-circuit here: pull the bot token from env config and gate on the+ // caller having an account link (analogue of the per-row ownership check).+ if (installationId === TELEGRAM_INSTALLATION_KEY) {+ const telegramConfig = await getMessengerTelegramConfig();+ if (!telegramConfig) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: 'Telegram messenger is not configured on this deployment',+ });+ }+ const link = await new MessengerAccountLinkModel(ctx.serverDB, ctx.userId).findByPlatform(+ 'telegram',+ );+ if (!link) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message:+ 'You can only send through Telegram after linking your account. ' ++ 'Open the Telegram bot and run /start to create the link.',+ });+ }+ return {+ applicationId: TELEGRAM_INSTALLATION_KEY,+ platform: 'telegram',+ service: createMessageServiceForCredentials('telegram', TELEGRAM_INSTALLATION_KEY, {+ botToken: telegramConfig.botToken,+ }),+ settings: {},+ };+ }++ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);+ const wechatLink = await new MessengerAccountLinkModel(+ ctx.serverDB,+ ctx.userId,+ ).findByIdWithCredentials(installationId, 'wechat', gateKeeper);+ if (wechatLink) {+ if (!wechatLink.applicationId || typeof wechatLink.credentials.botToken !== 'string') {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `WeChat connection credentials are unavailable: ${installationId}`,+ });+ }+ return {+ applicationId: wechatLink.applicationId,+ platform: 'wechat',+ service: createMessageServiceForCredentials(+ 'wechat',+ wechatLink.applicationId,+ wechatLink.credentials,+ ),+ settings: {},+ };+ }++ const row = await MessengerInstallationModel.findById(ctx.serverDB, installationId, gateKeeper);+ if (!row) {+ throw new TRPCError({+ code: 'NOT_FOUND',+ message: `Messenger installation not found: ${installationId}`,+ });+ }+ if (row.revokedAt) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: `Messenger installation has been revoked: ${installationId}`,+ });+ }+ if (row.installedByUserId !== ctx.userId) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'You can only send through messenger installs you initiated',+ });+ }+ return {+ applicationId: row.applicationId,+ platform: row.platform as MessagePlatformType,+ service: createMessageServiceForCredentials(+ row.platform,+ row.applicationId,+ row.credentials as Record<string, any>,+ ),+ settings: {},+ };+};++/**+ * Resolve the System Bot connection an inbound IM run arrived on, from the+ * `messengerInstallationKey` (`<platform>:<tenantId>` / `<platform>:singleton`)+ * that `MessengerRouter` stamps on the topic's bot context. Same installation+ * store `BotCallbackService` uses to post the run's own reply, so a send from+ * the tool goes out through exactly the connection the reply does.+ *+ * Returns undefined when the install no longer resolves (revoked, credentials+ * gone) β the caller then falls back to platform-level routing.+ */+export const resolveMessengerKeyTarget = async (+ platform: string,+ installationKey: string,+): Promise<ResolvedMessageTarget | undefined> => {+ const store = getInstallationStore(platform as MessengerPlatform);+ if (!store) return undefined;+ const creds = await store.resolveByKey(installationKey);+ if (!creds) return undefined;+ return {+ applicationId: creds.applicationId,+ platform: platform as MessagePlatformType,+ service: createMessageServiceForCredentials(platform, creds.applicationId, {+ baseUrl: creds.baseUrl,+ botId: creds.botId,+ botToken: creds.botToken,+ }),+ settings: {},+ };+};diff --git a/apps/server/src/services/bot/platforms/wechat/client.ts b/apps/server/src/services/bot/platforms/wechat/client.tsindex 1b67d18dd05..5fc0efc0343 100644--- a/apps/server/src/services/bot/platforms/wechat/client.ts+++ b/apps/server/src/services/bot/platforms/wechat/client.ts@@ -479,7 +479,9 @@ class WechatGatewayClient implements PlatformClient {await this.api.sendMessage(targetId, text, token);}if (attachments?.length) {- const sent = await sendWechatAttachments(this.api, targetId, attachments, token);+ const sent = await sendWechatAttachments(this.api, targetId, attachments, token, {+ applicationId: this.applicationId,+ });warnAttachmentFailures('bot-platform:wechat:reply', sent.failures);}};diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.tsindex 69733f4febf..e5dc277439a 100644--- a/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.test.ts@@ -242,6 +242,25 @@ describe('sendWechatAttachments', () => {expect(result.failures[0].detail).toContain('session timeout');});+ it('names the exact bot (App ID) whose session expired, so the right one gets rescanned', async () => {+ const api = makeApi();+ api.uploadCdnMedia.mockRejectedValueOnce(+ Object.assign(new Error('getuploadurl returned empty upload_param'), { code: -14 }),+ );++ const result = await sendWechatAttachments(+ api as any,+ 'user-1',+ [{ data: Buffer.from('doc').toString('base64'), name: 'a.docx', type: 'file' }],+ 'token-1',+ { applicationId: '[email protected]' },+ );++ expect(result.failures[0].detail).toContain(+ 'WeChat bot [email protected] session expired (errcode -14)',+ );+ });+it('skips an over-budget attachment with no fetchUrl instead of uploading it', async () => {const api = makeApi();budgetMocks.compressImageToBudget.mockResolvedValueOnce(undefined);diff --git a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts b/apps/server/src/services/bot/platforms/wechat/sendAttachments.tsindex f2b4bc4a84a..f619fd302da 100644--- a/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts+++ b/apps/server/src/services/bot/platforms/wechat/sendAttachments.ts@@ -52,14 +52,25 @@ export interface WechatAttachmentSendResult {// that mock the adapter module would make the import throw right there.const WECHAT_SESSION_EXPIRED = -14;-const describeWechatUploadError = (error: unknown): string => {+//+// Name the bot by its App ID: a user can hold several WeChat connections (a+// per-agent bot integration and the System Bot messenger), and without the id+// they rescan whichever one they think of first β usually the wrong one.+const describeWechatUploadError = (error: unknown, applicationId?: string): string => {const message = error instanceof Error ? error.message : String(error);const code = (error as { code?: unknown } | null)?.code;- if (code === WECHAT_SESSION_EXPIRED)- return `WeChat bot session expired (errcode -14): the bot must be logged in again by scanning its QR code before media can be sent; ${message}`;+ if (code === WECHAT_SESSION_EXPIRED) {+ const bot = applicationId ? `WeChat bot ${applicationId}` : 'WeChat bot';+ return `${bot} session expired (errcode -14): that bot must be logged in again by scanning its QR code before media can be sent; ${message}`;+ }return message;};+export interface SendWechatAttachmentsOptions {+ /** iLink App ID of the sending bot, surfaced in failure details. */+ applicationId?: string;+}+const mapAttachmentTypeToUploadMediaType = (type: WechatOutboundAttachment['type'],): WechatUploadMediaType => {@@ -137,6 +148,7 @@ export const sendWechatAttachments = async (toUserId: string,attachments: WechatOutboundAttachment[],contextToken: string,+ options: SendWechatAttachmentsOptions = {},): Promise<WechatAttachmentSendResult> => {const budget = PLATFORM_ATTACHMENT_BUDGETS.wechat;const fallbackLines: string[] = [];@@ -228,7 +240,7 @@ export const sendWechatAttachments = async (error,);failures.push({- detail: describeWechatUploadError(error),+ detail: describeWechatUploadError(error, options.applicationId),name: attachment.name,reason: 'upload-failed',type: attachment.type,diff --git a/apps/server/src/services/bot/platforms/wechat/service.ts b/apps/server/src/services/bot/platforms/wechat/service.tsindex 6362f7e78f0..4a6f4e2678f 100644--- a/apps/server/src/services/bot/platforms/wechat/service.ts+++ b/apps/server/src/services/bot/platforms/wechat/service.ts@@ -108,6 +108,7 @@ export class WechatMessageService implements MessageRuntimeService {params.channelId,params.attachments,contextToken,+ { applicationId: this.applicationId },);warnAttachmentFailures('bot-platform:wechat:sendMessage', attachments.failures);}diff --git a/apps/server/src/services/messenger/wechatPush.ts b/apps/server/src/services/messenger/wechatPush.tsindex bebcf32fa4a..03604882039 100644--- a/apps/server/src/services/messenger/wechatPush.ts+++ b/apps/server/src/services/messenger/wechatPush.ts@@ -196,6 +196,7 @@ const undeliveredPayload = (const deliver = async (api: WechatApiClient,+ applicationId: string,platformUserId: string,token: string,prepared: PreparedWechatDelivery,@@ -210,7 +211,9 @@ const deliver = async (// the untouched originals so a failed recompressed image is requeued as its// small source rather than megabytes of base64.const sendResult = prepared.attachments.length- ? await sendWechatAttachments(api, platformUserId, prepared.attachments, token)+ ? await sendWechatAttachments(api, platformUserId, prepared.attachments, token, {+ applicationId,+ }): { failures: [], undelivered: [] };const failed = sendResult.undelivered;@@ -454,7 +457,14 @@ export const sendProactiveWechatMessage = async (params: {const progress: DeliveryProgress = { contentDelivered: false };try {- await deliver(target.api, target.platformUserId, credit.token, prepared, progress);+ await deliver(+ target.api,+ target.applicationId,+ target.platformUserId,+ credit.token,+ prepared,+ progress,+ );return { remaining: credit.remaining, status: 'sent' };} catch (error) {// The consumed credit is intentionally not refunded β a rejected send@@ -499,7 +509,7 @@ const drainQueuedPushes = async (params: {const progress: DeliveryProgress = { contentDelivered: false };try {- await deliver(api, platformUserId, credit.token, prepared, progress);+ await deliver(api, applicationId, platformUserId, credit.token, prepared, progress);return 'sent';} catch (error) {log('drainQueuedPushes: replay failed for %s: %O', platformUserId, error);diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.test.tsindex f46d5b348bd..b101d4724b8 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/message.test.ts@@ -6,15 +6,60 @@ import type { ToolExecutionContext } from '../../types';// ==================== Mocks ====================const mockQuery = vi.fn();+const mockProviderFindById = vi.fn();+const mockFindEnabledByApplicationId = vi.fn();vi.mock('@/database/models/agentBotProvider', () => ({AgentBotProviderModel: vi.fn().mockImplementation(function () {return {+ findById: mockProviderFindById,+ findEnabledByApplicationId: mockFindEnabledByApplicationId,query: mockQuery,};}),}));+// The topic carries the inbound IM context (`metadata.bot`) the runtime+// routes current-conversation sends through.+const mockTopicFindById = vi.fn();++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return { findById: mockTopicFindById };+ }),+}));++// Messenger install store β resolves the inbound `messengerInstallationKey`.+const mockResolveByKey = vi.fn();++vi.mock('@/server/services/messenger/installations', () => ({+ getInstallationStore: vi.fn(() => ({ resolveByKey: mockResolveByKey })),+}));++// Per-bot runtime status, so the failed-bot skip can be exercised.+const mockGetBotRuntimeStatus = vi.fn();++vi.mock('@/server/services/gateway/runtimeStatus', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ getBotRuntimeStatus: mockGetBotRuntimeStatus,+}));++// WeChat client β records which bot token each send went out through.+const mockWechatSendMessage = vi.fn();+const wechatClientTokens: string[] = [];++vi.mock('@lobechat/chat-adapter-wechat', async (importOriginal) => ({+ ...(await importOriginal<Record<string, unknown>>()),+ WechatApiClient: vi.fn().mockImplementation(function (botToken: string) {+ return {+ sendMessage: async (...args: unknown[]) => {+ wechatClientTokens.push(botToken);+ return mockWechatSendMessage(...args);+ },+ };+ }),+}));+// ββ System Bot model mocks ββββββββββββββββββββββββββββββ// The `botProvider.*` System Bot methods (added in ) talk directly// to these models instead of going through the messenger TRPC router, so@@ -38,6 +83,7 @@ const mockLinkDelete = vi.fn();const mockLinkDeleteByPlatform = vi.fn();const mockLinkFindById = vi.fn();const mockLinkFindByPlatform = vi.fn();+const mockLinkFindByIdWithCredentials = vi.fn();vi.mock('@/database/models/messengerAccountLink', () => ({MessengerAccountLinkModel: vi.fn().mockImplementation(function () {@@ -45,6 +91,7 @@ vi.mock('@/database/models/messengerAccountLink', () => ({delete: mockLinkDelete,deleteByPlatform: mockLinkDeleteByPlatform,findById: mockLinkFindById,+ findByIdWithCredentials: mockLinkFindByIdWithCredentials,findByPlatform: mockLinkFindByPlatform,list: mockLinkList,setActiveAgent: mockLinkSetActiveAgent,@@ -257,6 +304,24 @@ const mockProviderFor = (platform: string, credentials: Record<string, string>)});};+beforeEach(() => {+ mockGetBotRuntimeStatus.mockReset();+ mockGetBotRuntimeStatus.mockImplementation(async (platform: string, applicationId: string) => ({+ applicationId,+ platform,+ status: 'connected',+ updatedAt: 0,+ }));+ mockTopicFindById.mockReset();+ mockResolveByKey.mockReset();+ mockProviderFindById.mockReset();+ mockFindEnabledByApplicationId.mockReset();+ mockLinkFindByIdWithCredentials.mockReset();+ mockWechatSendMessage.mockReset();+ mockWechatSendMessage.mockResolvedValue({});+ wechatClientTokens.length = 0;+});+// ==================== Tests ====================describe('messageRuntime', () => {@@ -557,6 +622,220 @@ describe('messageRuntime', () => {});});+ // ==================== Connection routing (LOBE-14350) ====================+ // A WeChat account can hold both a per-agent bot integration and a System+ // Bot connection. Sends must go out through the connection the caller+ // named, or β for the conversation the run is replying in β through the one+ // it arrived on; never through an arbitrary (possibly failed) bot.+ describe('connection routing', () => {+ const failedBot = {+ applicationId: '[email protected]',+ credentials: { botToken: 'stale-bot-token' },+ enabled: true,+ id: 'bot-stale',+ platform: 'wechat',+ workspaceId: null,+ };++ const messengerLink = {+ applicationId: '[email protected]',+ credentials: { botToken: 'messenger-token' },+ id: 'link-1',+ platform: 'wechat',+ tenantId: '[email protected]',+ };++ beforeEach(() => {+ mockQuery.mockImplementation(async (params?: { platform?: string }) =>+ params?.platform === 'wechat' ? [failedBot] : [],+ );+ mockGetBotRuntimeStatus.mockImplementation(+ async (platform: string, applicationId: string) => ({+ applicationId,+ platform,+ status: applicationId === failedBot.applicationId ? 'failed' : 'connected',+ updatedAt: 0,+ }),+ );+ });++ it('sends through the System Bot connection the conversation arrived on, not a per-agent bot', async () => {+ mockTopicFindById.mockResolvedValue({+ metadata: {+ bot: {+ applicationId: '[email protected]',+ messengerInstallationKey: 'wechat:[email protected]',+ platform: 'wechat',+ platformThreadId: 'wechat:dm:[email protected]',+ },+ },+ });+ mockResolveByKey.mockResolvedValue({+ applicationId: '[email protected]',+ botToken: 'messenger-token',+ installationKey: 'wechat:[email protected]',+ metadata: {},+ platform: 'wechat',+ tenantId: '[email protected]',+ });++ const runtime = await messageRuntime.factory({ ...validContext, topicId: 'topic-1' });+ const result = await runtime.sendMessage({+ channelId: '[email protected]',+ content: 'here is your file',+ platform: 'wechat',+ });++ expect(result.success).toBe(true);+ expect(mockResolveByKey).toHaveBeenCalledWith('wechat:[email protected]');+ expect(wechatClientTokens).toEqual(['messenger-token']);+ });++ it('sends through the per-agent bot the conversation arrived on', async () => {+ mockTopicFindById.mockResolvedValue({+ metadata: {+ bot: {+ applicationId: '[email protected]',+ platform: 'wechat',+ platformThreadId: 'wechat:dm:[email protected]',+ },+ },+ });+ mockFindEnabledByApplicationId.mockResolvedValue({+ applicationId: '[email protected]',+ credentials: { botToken: 'agent-bot-token' },+ enabled: true,+ platform: 'wechat',+ workspaceId: null,+ });++ const runtime = await messageRuntime.factory({ ...validContext, topicId: 'topic-1' });+ await runtime.sendMessage({+ channelId: '[email protected]',+ content: 'hi',+ platform: 'wechat',+ });++ expect(mockFindEnabledByApplicationId).toHaveBeenCalledWith('wechat', '[email protected]');+ expect(wechatClientTokens).toEqual(['agent-bot-token']);+ });++ it('honors an explicit messengerInstallationId instead of routing by platform', async () => {+ mockLinkFindByIdWithCredentials.mockResolvedValue(messengerLink);++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.sendMessage({+ channelId: '[email protected]',+ content: 'hi',+ messengerInstallationId: 'link-1',+ platform: 'wechat',+ });++ expect(result.success).toBe(true);+ expect(mockLinkFindByIdWithCredentials).toHaveBeenCalledWith('link-1', 'wechat', {});+ expect(wechatClientTokens).toEqual(['messenger-token']);+ expect(mockWechatSendMessage).toHaveBeenCalledWith('[email protected]', 'hi', '');+ });++ it('honors an explicit botId even when it is not the platform default', async () => {+ mockProviderFindById.mockResolvedValue({+ applicationId: '[email protected]',+ credentials: { botToken: 'explicit-bot-token' },+ enabled: true,+ platform: 'wechat',+ workspaceId: null,+ });++ const runtime = await messageRuntime.factory(validContext);+ await runtime.sendMessage({+ botId: 'bot-other',+ channelId: '[email protected]',+ content: 'hi',+ platform: 'wechat',+ });++ expect(mockProviderFindById).toHaveBeenCalledWith('bot-other');+ expect(wechatClientTokens).toEqual(['explicit-bot-token']);+ });++ it('rejects a botId that belongs to a different platform', async () => {+ mockProviderFindById.mockResolvedValue({+ applicationId: 'discord-app',+ credentials: { botToken: 'discord-token' },+ enabled: true,+ platform: 'discord',+ workspaceId: null,+ });++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.sendMessage({+ botId: 'bot-discord',+ channelId: '[email protected]',+ content: 'hi',+ platform: 'wechat',+ });++ expect(result.success).toBe(false);+ expect(result.content).toContain('is a discord connection, but the call targets wechat');+ });++ it('never auto-picks a failed bot, falling back to the WeChat System Bot connection', async () => {+ mockLinkFindByPlatform.mockResolvedValue({ id: 'link-1', platform: 'wechat' });+ mockLinkFindByIdWithCredentials.mockResolvedValue(messengerLink);++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.sendMessage({+ channelId: '[email protected]',+ content: 'hi',+ platform: 'wechat',+ });++ expect(result.success).toBe(true);+ expect(wechatClientTokens).toEqual(['messenger-token']);+ });++ it('names the failed bot when there is nothing usable to fall back to', async () => {+ mockLinkFindByPlatform.mockResolvedValue(undefined);++ const runtime = await messageRuntime.factory(validContext);+ const result = await runtime.sendMessage({+ channelId: '[email protected]',+ content: 'hi',+ platform: 'wechat',+ });++ expect(result.success).toBe(false);+ expect(result.content).toContain('Every enabled wechat bot is in a failed state');+ expect(result.content).toContain('[email protected]');+ expect(wechatClientTokens).toEqual([]);+ });++ it('keeps platform routing for a platform other than the conversationβs', async () => {+ mockTopicFindById.mockResolvedValue({+ metadata: {+ bot: {+ applicationId: '[email protected]',+ messengerInstallationKey: 'wechat:[email protected]',+ platform: 'wechat',+ platformThreadId: 'wechat:dm:[email protected]',+ },+ },+ });+ mockProviderFor('discord', { botToken: 'discord-token' });+ mockDiscordCreateMessage.mockResolvedValue({ id: 'msg-9' });++ const runtime = await messageRuntime.factory({ ...validContext, topicId: 'topic-1' });+ const result = await runtime.sendMessage({+ channelId: 'ch-1',+ content: 'cross-post',+ platform: 'discord',+ });++ expect(result.success).toBe(true);+ expect(mockResolveByKey).not.toHaveBeenCalled();+ });+ });+// ==================== System Bot management () ====================// Each test exercises both layers in one shot:// 1. `botProvider.<method>` in `apps/server/src/services/toolExecution/serverRuntimes/message/index.ts`diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/MessageDispatcherService.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/MessageDispatcherService.tsindex f94038b3ed1..23326f1afc6 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/message/MessageDispatcherService.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/MessageDispatcherService.ts@@ -20,6 +20,7 @@ import type {ListThreadsParams,ListThreadsState,MessageRuntimeService,+ MessageSendRoute,PinMessageParams,PinMessageState,ReactToMessageParams,@@ -38,23 +39,54 @@ import type {UnpinMessageState,} from '@lobechat/builtin-tool-message/executionRuntime';+/** Drop the routing keys so platform services only ever see their own params. */+const stripRoute = <T extends MessageSendRoute>(params: T): Omit<T, keyof MessageSendRoute> => {+ const { botId: _botId, messengerInstallationId: _messengerInstallationId, ...rest } = params;+ return rest;+};+export type AsyncServiceFactory = () => Promise<MessageRuntimeService>;+/** Routing inputs every dispatched call carries: its platform, plus an optional explicit connection. */+export type MessageRouteParams = MessageSendRoute & { platform: string };++/**+ * Picks the connection for one call before the per-platform default applies:+ * an explicit `botId` / `messengerInstallationId`, or the connection the+ * current IM conversation arrived on. Returns undefined to defer to the+ * platform default.+ */+export type MessageRouteResolver = (+ params: MessageRouteParams,+) => Promise<MessageRuntimeService | undefined>;+/**- * Routes MessageRuntimeService calls to the appropriate platform service- * based on the `platform` field in each method's params.+ * Routes MessageRuntimeService calls to the appropriate platform service.*- * Services are lazily created on first use for each platform.+ * Each call first asks `resolveRoute` (when given) for a specific connection;+ * otherwise it falls back to the per-platform default service, lazily created+ * on first use for each platform. The routing keys (`botId`,+ * `messengerInstallationId`) are stripped before the call reaches the+ * platform service.*/export class MessageDispatcherService implements MessageRuntimeService {private services = new Map<string, MessageRuntimeService>();private serviceFactories: Record<string, AsyncServiceFactory>;+ private resolveRoute?: MessageRouteResolver;- constructor(serviceFactories: Record<string, AsyncServiceFactory>) {+ constructor(+ serviceFactories: Record<string, AsyncServiceFactory>,+ options: { resolveRoute?: MessageRouteResolver } = {},+ ) {this.serviceFactories = serviceFactories;+ this.resolveRoute = options.resolveRoute;}- private async getService(platform: string): Promise<MessageRuntimeService> {+ private async getService(params: MessageRouteParams): Promise<MessageRuntimeService> {+ const routed = await this.resolveRoute?.(params);+ if (routed) return routed;++ const { platform } = params;const cached = this.services.get(platform);if (cached) return cached;@@ -75,17 +107,17 @@ export class MessageDispatcherService implements MessageRuntimeService {// ==================== Core Message Operations ====================sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {- return (await this.getService(params.platform)).sendMessage(params);+ return (await this.getService(params)).sendMessage(stripRoute(params));};readMessages = async (params: ReadMessagesParams): Promise<ReadMessagesState> => {- return (await this.getService(params.platform)).readMessages(params);+ return (await this.getService(params)).readMessages(params);};// Optional on the service contract: forward only when the platform has it,// so the runtime's "not supported on <platform>" branch stays reachable.readDocument = async (params: ReadDocumentParams): Promise<ReadDocumentState> => {- const service = await this.getService(params.platform);+ const service = await this.getService(params);if (!service.readDocument) {throw new Error(`readDocument is not supported on ${params.platform}`);}@@ -93,74 +125,74 @@ export class MessageDispatcherService implements MessageRuntimeService {};editMessage = async (params: EditMessageParams): Promise<EditMessageState> => {- return (await this.getService(params.platform)).editMessage(params);+ return (await this.getService(params)).editMessage(params);};deleteMessage = async (params: DeleteMessageParams): Promise<DeleteMessageState> => {- return (await this.getService(params.platform)).deleteMessage(params);+ return (await this.getService(params)).deleteMessage(params);};searchMessages = async (params: SearchMessagesParams): Promise<SearchMessagesState> => {- return (await this.getService(params.platform)).searchMessages(params);+ return (await this.getService(params)).searchMessages(params);};// ==================== Reactions ====================reactToMessage = async (params: ReactToMessageParams): Promise<ReactToMessageState> => {- return (await this.getService(params.platform)).reactToMessage(params);+ return (await this.getService(params)).reactToMessage(params);};getReactions = async (params: GetReactionsParams): Promise<GetReactionsState> => {- return (await this.getService(params.platform)).getReactions(params);+ return (await this.getService(params)).getReactions(params);};// ==================== Pin Management ====================pinMessage = async (params: PinMessageParams): Promise<PinMessageState> => {- return (await this.getService(params.platform)).pinMessage(params);+ return (await this.getService(params)).pinMessage(params);};unpinMessage = async (params: UnpinMessageParams): Promise<UnpinMessageState> => {- return (await this.getService(params.platform)).unpinMessage(params);+ return (await this.getService(params)).unpinMessage(params);};listPins = async (params: ListPinsParams): Promise<ListPinsState> => {- return (await this.getService(params.platform)).listPins(params);+ return (await this.getService(params)).listPins(params);};// ==================== Channel Management ====================getChannelInfo = async (params: GetChannelInfoParams): Promise<GetChannelInfoState> => {- return (await this.getService(params.platform)).getChannelInfo(params);+ return (await this.getService(params)).getChannelInfo(params);};listChannels = async (params: ListChannelsParams): Promise<ListChannelsState> => {- return (await this.getService(params.platform)).listChannels(params);+ return (await this.getService(params)).listChannels(params);};// ==================== Member Information ====================getMemberInfo = async (params: GetMemberInfoParams): Promise<GetMemberInfoState> => {- return (await this.getService(params.platform)).getMemberInfo(params);+ return (await this.getService(params)).getMemberInfo(params);};// ==================== Thread Operations ====================createThread = async (params: CreateThreadParams): Promise<CreateThreadState> => {- return (await this.getService(params.platform)).createThread(params);+ return (await this.getService(params)).createThread(params);};listThreads = async (params: ListThreadsParams): Promise<ListThreadsState> => {- return (await this.getService(params.platform)).listThreads(params);+ return (await this.getService(params)).listThreads(params);};replyToThread = async (params: ReplyToThreadParams): Promise<ReplyToThreadState> => {- return (await this.getService(params.platform)).replyToThread(params);+ return (await this.getService(params)).replyToThread(stripRoute(params));};// ==================== Platform-Specific: Polls ====================createPoll = async (params: CreatePollParams): Promise<CreatePollState> => {- return (await this.getService(params.platform)).createPoll(params);+ return (await this.getService(params)).createPoll(params);};}diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.tsindex 41a519c3a88..a6d7b6d3580 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts@@ -2,11 +2,12 @@ import {MessageToolIdentifier,MESSENGER_PUSH_CONTENT_MAX_LENGTH,} from '@lobechat/builtin-tool-message';-import type { BotProviderQuery } from '@lobechat/builtin-tool-message/executionRuntime';+import type {+ BotProviderQuery,+ MessageRuntimeService,+} from '@lobechat/builtin-tool-message/executionRuntime';import { MessageExecutionRuntime } from '@lobechat/builtin-tool-message/executionRuntime';-import { LarkApiClient } from '@lobechat/chat-adapter-feishu';-import { QQApiClient } from '@lobechat/chat-adapter-qq';-import { WechatApiClient } from '@lobechat/chat-adapter-wechat';+import type { ChatTopicBotContext } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { and, eq } from 'drizzle-orm';@@ -21,6 +22,7 @@ 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 { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';@@ -30,25 +32,21 @@ import {invalidateBotAfterUpdate,mergeBotSettingsForPersist,} 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 { DiscordApi } from '@/server/services/bot/platforms/discord/api';-import { DiscordMessageService } from '@/server/services/bot/platforms/discord/service';-import { FeishuMessageService } from '@/server/services/bot/platforms/feishu/service';-import { ImessageDesktopBridgeApi } from '@/server/services/bot/platforms/imessage/desktopBridge';-import { ImessageMessageService } from '@/server/services/bot/platforms/imessage/service';-import { QQMessageService } from '@/server/services/bot/platforms/qq/service';-import { SlackApi } from '@/server/services/bot/platforms/slack/api';-import { SlackMessageService } from '@/server/services/bot/platforms/slack/service';-import { TelegramApi } from '@/server/services/bot/platforms/telegram/api';-import { TelegramMessageService } from '@/server/services/bot/platforms/telegram/service';import {wechatLegacyTokenKey,wechatPendingPushKey,wechatWindowKey,} from '@/server/services/bot/platforms/wechat/contextWindow';-import { WechatMessageService } from '@/server/services/bot/platforms/wechat/service';import { GatewayService } from '@/server/services/gateway';-import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';+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';@@ -57,6 +55,7 @@ import { maybeSynthesizeTelegramInstall } from '@/server/services/messenger/instimport { sendMessengerPush } from '@/server/services/messenger/push';import type { ServerRuntimeRegistration } from '../types';+import type { MessageRouteParams } from './MessageDispatcherService';import { MessageDispatcherService } from './MessageDispatcherService';/**@@ -147,7 +146,15 @@ const disconnectWechatAccountLink = async (};/**- * Resolves credentials for the given platform from the user's configured bot providers.+ * 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@@ -160,23 +167,47 @@ const resolveCredentials = async (userId: string,): Promise<{ applicationId: string; credentials: Record<string, string> }> => {const providers = await providerModel.query({ platform });- const enabled = providers.find((p) => p.enabled);- if (!enabled?.credentials) {+ 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: enabled.applicationId,+ applicationId: usable.applicationId,platform,userId,- workspaceId: enabled.workspaceId ?? undefined,+ workspaceId: usable.workspaceId ?? undefined,});- return { applicationId: enabled.applicationId, credentials: enabled.credentials };+ return { applicationId: usable.applicationId, credentials: usable.credentials! };};+/** Platforms the message tool can reach through a per-agent bot provider. */+const PROVIDER_PLATFORMS = [+ 'discord',+ 'feishu',+ 'imessage',+ 'lark',+ 'qq',+ 'slack',+ 'telegram',+ 'wechat',+] as const;+export const messageRuntime: ServerRuntimeRegistration = {factory: async (context) => {if (!context.serverDB) {@@ -196,98 +227,192 @@ export const messageRuntime: ServerRuntimeRegistration = {context.workspaceId ?? undefined,);- const service = new MessageDispatcherService({- discord: async () => {- const { credentials } = await resolveCredentials(providerModel, 'discord', context.userId!);- return new DiscordMessageService(new DiscordApi(credentials.botToken));- },- feishu: async () => {- const { applicationId, credentials } = await resolveCredentials(- providerModel,- 'feishu',- context.userId!,- );- return new FeishuMessageService(- new LarkApiClient(applicationId, credentials.appSecret, 'feishu'),- 'feishu',- );- },- imessage: async () => {- const { applicationId, credentials } = await resolveCredentials(- providerModel,- 'imessage',- context.userId!,- );- return new ImessageMessageService(- new ImessageDesktopBridgeApi({- applicationId,- deviceId: credentials.desktopDeviceId,- userId: context.userId!,- }),- );- },- lark: async () => {- const { applicationId, credentials } = await resolveCredentials(- providerModel,- 'lark',- context.userId!,- );- return new FeishuMessageService(- new LarkApiClient(applicationId, credentials.appSecret, 'lark'),- 'lark',- );- },- qq: async () => {- const { applicationId, credentials } = await resolveCredentials(- providerModel,- 'qq',- context.userId!,- );- return new QQMessageService(new QQApiClient(applicationId, credentials.appSecret));- },- slack: async () => {- const { credentials } = await resolveCredentials(providerModel, 'slack', context.userId!);- return new SlackMessageService(new SlackApi(credentials.botToken));- },- telegram: async () => {- // Per-agent provider takes precedence; fall back to the env-backed- // singleton so the synthetic telegram:singleton install actually works.- try {- const { credentials } = await resolveCredentials(- providerModel,- 'telegram',- context.userId!,+ 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 new TelegramMessageService(new TelegramApi(credentials.botToken));- } 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 new TelegramMessageService(new TelegramApi(envConfig.botToken));}- },- wechat: async () => {- const { applicationId, credentials } = await resolveCredentials(- providerModel,- 'wechat',- context.userId!,- );- return new WechatMessageService(- // `baseUrl` is issued during QR confirmation and must be honored when- // it differs from the default endpoint (see wechat/protocol-spec.md).- new WechatApiClient(credentials.botToken, credentials.botId, credentials.baseUrl),- applicationId,+ 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 (LOBE-14350).+ */+ 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 });const botProvider: BotProviderQuery = {connectBot: async (botId) => {diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts b/packages/builtin-tool-message/src/ExecutionRuntime/index.tsindex df0ee7c985a..bb2ca310a10 100644--- a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts+++ b/packages/builtin-tool-message/src/ExecutionRuntime/index.ts@@ -126,6 +126,7 @@ export type {ListPlatformsState,ListThreadsParams,ListThreadsState,+ MessageSendRoute,MessengerInfo,MessengerLinkInfo,MessengerPlatformInfo,diff --git a/packages/builtin-tool-message/src/manifest.ts b/packages/builtin-tool-message/src/manifest.tsindex 187d372ce90..3de0bd51f88 100644--- a/packages/builtin-tool-message/src/manifest.ts+++ b/packages/builtin-tool-message/src/manifest.ts@@ -256,7 +256,7 @@ export const MessageManifest: BuiltinToolManifest = {// ==================== Direct Messaging ===================={description:- 'Send a direct/private message to ANOTHER user by their platform user ID. Creates a DM channel automatically. To reach the CURRENT user themselves ("DM me", "send me a message"), use `sendMessengerPush` instead β it needs no user id. Supports optional outbound media `attachments` (images / files / video / audio) and rich `embeds` cards (Discord). To pick the target: call `listBots` for the platform first β if there\'s an entry, use its `botId`; otherwise call `listMessengers` and use that entry\'s `id` as `messengerInstallationId`.',+ 'Send a direct/private message to ANOTHER user by their platform user ID. Creates a DM channel automatically. To reach the CURRENT user themselves ("DM me", "send me a message"), use `sendMessengerPush` instead β it needs no user id. Supports optional outbound media `attachments` (images / files / video / audio) and rich `embeds` cards (Discord). To pick the connection: when sending into the IM conversation you are currently in, pass neither `botId` nor `messengerInstallationId`; otherwise call `listBots` for the platform first β if there\'s a non-`failed` entry, use its `botId`; else call `listMessengers` and use that entry\'s `id` as `messengerInstallationId`.',name: MessageApiName.sendDirectMessage,ordered: true,parameters: {@@ -266,7 +266,7 @@ export const MessageManifest: BuiltinToolManifest = {embeds: embedsSchema,botId: {description:- 'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',+ 'Per-agent bot id from `listBots` (skip bots whose status is `failed`). Pass at most one of `botId` / `messengerInstallationId`; omit both when sending into the IM conversation you are currently in β the runtime then uses the connection that conversation arrived on.',type: 'string',},content: {@@ -275,7 +275,7 @@ export const MessageManifest: BuiltinToolManifest = {},messengerInstallationId: {description:- 'System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.',+ 'System Bot installation id from `listMessengers`. Pass at most one of `botId` / `messengerInstallationId`; omit both when sending into the IM conversation you are currently in.',type: 'string',},platform: {@@ -296,7 +296,7 @@ export const MessageManifest: BuiltinToolManifest = {// ==================== Core Message Operations ===================={description:- "Send a message to a specific channel or conversation on the target platform. Supports optional outbound media `attachments` (images / files / video / audio) β use this when you need to deliver a generated image, document, or other binary alongside your reply β and rich `embeds` cards (rendered natively on Discord; ignored elsewhere) for reports, dashboards, and structured summaries. To pick the target: call `listBots` first β if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",+ "Send a message to a specific channel or conversation on the target platform. Supports optional outbound media `attachments` (images / files / video / audio) β use this when you need to deliver a generated image, document, or other binary alongside your reply β and rich `embeds` cards (rendered natively on Discord; ignored elsewhere) for reports, dashboards, and structured summaries. To pick the connection: when sending into the IM conversation you are currently in, pass neither `botId` nor `messengerInstallationId`; otherwise call `listBots` first β if there's a non-`failed` entry for the platform, use its `botId`; else call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",name: MessageApiName.sendMessage,ordered: true,parameters: {@@ -305,7 +305,7 @@ export const MessageManifest: BuiltinToolManifest = {attachments: attachmentsSchema,botId: {description:- 'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',+ 'Per-agent bot id from `listBots` (skip bots whose status is `failed`). Pass at most one of `botId` / `messengerInstallationId`; omit both when sending into the IM conversation you are currently in β the runtime then uses the connection that conversation arrived on.',type: 'string',},channelId: {@@ -320,7 +320,7 @@ export const MessageManifest: BuiltinToolManifest = {embeds: embedsSchema,messengerInstallationId: {description:- 'System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.',+ 'System Bot installation id from `listMessengers`. Pass at most one of `botId` / `messengerInstallationId`; omit both when sending into the IM conversation you are currently in.',type: 'string',},platform: {@@ -750,7 +750,7 @@ export const MessageManifest: BuiltinToolManifest = {},{description:- "Send a reply to a thread. Supports optional outbound media `attachments` (images / files / video / audio) and rich `embeds` cards (Discord). To pick the target: call `listBots` first β if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",+ "Send a reply to a thread. Supports optional outbound media `attachments` (images / files / video / audio) and rich `embeds` cards (Discord). To pick the connection: when sending into the IM conversation you are currently in, pass neither `botId` nor `messengerInstallationId`; otherwise call `listBots` first β if there's a non-`failed` entry for the platform, use its `botId`; else call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",name: MessageApiName.replyToThread,ordered: true,parameters: {@@ -760,7 +760,7 @@ export const MessageManifest: BuiltinToolManifest = {embeds: embedsSchema,botId: {description:- 'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',+ 'Per-agent bot id from `listBots` (skip bots whose status is `failed`). Pass at most one of `botId` / `messengerInstallationId`; omit both when sending into the IM conversation you are currently in β the runtime then uses the connection that conversation arrived on.',type: 'string',},content: {@@ -769,7 +769,7 @@ export const MessageManifest: BuiltinToolManifest = {},messengerInstallationId: {description:- 'System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.',+ 'System Bot installation id from `listMessengers`. Pass at most one of `botId` / `messengerInstallationId`; omit both when sending into the IM conversation you are currently in.',type: 'string',},platform: {diff --git a/packages/builtin-tool-message/src/systemRole.ts b/packages/builtin-tool-message/src/systemRole.tsindex ad787afe071..5126963fa96 100644--- a/packages/builtin-tool-message/src/systemRole.ts+++ b/packages/builtin-tool-message/src/systemRole.ts@@ -12,7 +12,7 @@ export const systemPrompt = `You have access to a Message tool that provides uni<bot_management>1. **listPlatforms** β List all supported platforms and their required credential fields-2. **listBots** β List per-agent configured bots for the current agent (with runtime status). Also the primary discovery for sending to others β see \`<outbound_routing>\`.+2. **listBots** β List per-agent configured bots for the current agent (with runtime \`status\`; a \`failed\` bot is not usable for sending). Also the primary discovery for sending to others β see \`<outbound_routing>\`.3. **getBotDetail** β Get detailed info about a specific bot (returns \`settings\` β read this BEFORE \`updateBot\` for any field-level edit)4. **createBot** β Create a new per-agent bot integration (requires agentId, platform, applicationId, credentials; optional initial settings)5. **updateBot** β Update bot credentials or access-policy settings (DM policy, allowlists, owner userId, etc.)@@ -24,22 +24,25 @@ export const systemPrompt = `You have access to a Message tool that provides uni<outbound_routing>**First, check who the recipient is.** If the target is **the user themselves** β "send me a message on Telegram", "DM me the result", "notify me on Slack" β this is NOT a routing problem: call \`sendMessengerPush\` with \`platform\` + \`content\` and stop. It needs no bot, no channel id, and no platform user id, and its availability is decided by the user's **account links** (\`listMessengerLinks\`), NOT by \`listBots\` / \`listMessengers\`. Never conclude "I can't reach <platform>" for a self-targeted send without having actually called \`sendMessengerPush\` β see \`<proactive_push>\`.-The rest of this section is for sending to **someone else** or to a channel.+The rest of this section is for sending to **someone else**, to a channel, or into the conversation you're in.The send APIs (\`sendMessage\`, \`sendDirectMessage\`, \`replyToThread\`) can deliver through **two sources** β both use the same underlying platform clients (so attachments / formatting / rate behavior are identical), but they come from different lists:- **Per-agent bot** (pass \`botId\`) β the agent's own credentials, configured via \`createBot\`. Listed by \`listBots\`. Messages appear with the per-agent bot's identity.- **System Bot installation** (pass \`messengerInstallationId\`) β the LobeHub shared bot, connected by the user via Settings β Messenger. Listed by \`listMessengers\`. Messages appear with the LobeHub System Bot identity.-**Two-step routing rule β apply in order:**+**Routing rule β apply in order:**-1. **Call \`listBots\`.** If any entry has \`platform: "<target>"\` β use its \`botId\` on the send API. Done.+0. **The target is the conversation you are in right now** (you're running inside an IM conversation β there is a \`<current_conversation>\` block β and you're sending into it, e.g. delivering a generated file): pass **neither** \`botId\` nor \`messengerInstallationId\`. The runtime sends through the exact connection this conversation arrived on. Skip discovery entirely β another bot on the same platform is a different identity and may have a dead session.+1. **Call \`listBots\`.** If an entry has \`platform: "<target>"\` and its \`status\` is NOT \`failed\` β use its \`botId\` on the send API. Done. A \`failed\` bot's credentials are broken (e.g. an expired WeChat login accepts text but rejects every file); never auto-pick it β continue to step 2, and mention to the user that the bot needs reconnecting.2. **Otherwise call \`listMessengers\`.** If any entry has \`platform: "<target>"\` β use its \`id\` as \`messengerInstallationId\` on the send API. Done.-3. **Neither has the platform β do NOT pick a different platform.** Tell the user: "I can't reach <platform> for you yet. You can either provision a dedicated bot for this agent with \`createBot\`, or install the LobeHub System Bot via Settings β Messenger." Stop. (A self-targeted send should never reach this step β it goes through \`sendMessengerPush\`, which these two lists do not govern.)+3. **Neither has a usable connection for the platform β do NOT pick a different platform.** Tell the user: "I can't reach <platform> for you yet. You can either provision a dedicated bot for this agent with \`createBot\`, or install the LobeHub System Bot via Settings β Messenger." Stop. (A self-targeted send should never reach this step β it goes through \`sendMessengerPush\`, which these two lists do not govern.)-Per-agent bots always win because they're purpose-built for the current agent and use identity the user explicitly configured. Only fall back to System Bot when the agent has nothing for the platform. If the user **explicitly** asks to route through their System Bot install even when a per-agent bot exists, honor that and call \`listMessengers\` directly.+For sends elsewhere, healthy per-agent bots come first because they're purpose-built for the current agent and use identity the user explicitly configured. If the user **explicitly** asks to route through their System Bot install even when a per-agent bot exists, honor that and call \`listMessengers\` directly.-The send APIs accept **exactly one** of \`botId\` / \`messengerInstallationId\` β the server will reject both-or-neither.+Pass **at most one** of \`botId\` / \`messengerInstallationId\` β never both. Omitting both is only for step 0.++When a send reports a WeChat \`errcode -14\` (session expired), the error names the bot's App ID β tell the user to rescan the QR code of **that** bot (per-agent bot settings for a \`listBots\` App ID, Settings β Messenger for a System Bot connection), not whichever WeChat connection comes to mind.</outbound_routing><system_bot_management>@@ -201,10 +204,10 @@ Layout rules:<usage_guidelines>- **When the recipient is the user themselves, use \`sendMessengerPush\`** β that includes "DM me", "send me a message on <platform>", "ping me when done". Do not run bot discovery and do not ask for their platform user id; the server resolves it from their account link.-- **Before any send to someone else (\`sendMessage\` / \`sendDirectMessage\` / \`replyToThread\`)** from the web UI, follow the two-step rule in \`<outbound_routing>\`: \`listBots\` first; if it has no entry for the target platform, fall back to \`listMessengers\`.-- When you are already inside a platform conversation (e.g. replying in a Discord channel), you already have the channel context β skip discovery and reply directly to the current channel.+- **Before any send to someone else (\`sendMessage\` / \`sendDirectMessage\` / \`replyToThread\`)** from the web UI, follow the routing rule in \`<outbound_routing>\`: \`listBots\` first (skipping \`failed\` bots); if it has no usable entry for the target platform, fall back to \`listMessengers\`.+- When you are already inside a platform conversation (e.g. replying in a Discord channel), you already have the channel context β skip discovery and reply directly to the current channel. Sends into that conversation omit \`botId\` / \`messengerInstallationId\` (step 0 of \`<outbound_routing>\`).- **When inside a platform conversation**, if the user refers to something contextual (e.g. "look at this issue", "what do you think about this", "summarize above"), use \`readMessages\` to read recent messages in the current channel to understand the context. Do NOT ask the user to repeat or provide details β the context is in the chat history.-- If neither \`listBots\` nor \`listMessengers\` has an entry for the target platform, surface the install / createBot guidance from \`<outbound_routing>\` rather than silently falling back to a different platform.+- If neither \`listBots\` nor \`listMessengers\` has a usable entry for the target platform, surface the install / createBot guidance from \`<outbound_routing>\` rather than silently falling back to a different platform.- When the user asks to DM **a third party**, use \`sendDirectMessage\` with that person's platform user id. Never use it to reach the user themselves β \`sendMessengerPush\` covers that without an id.- **Never ask the user for channel IDs.** Use \`listChannels\` to discover channels yourself. If \`serverId\` is available from \`listBots\`, use it directly. If not, ask the user for the server/guild ID.- When the user references a channel by name (e.g. "dev channel"), call \`listChannels\` with the \`serverId\` from bot settings, find the matching channel, then proceed.diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.tsindex 93687f3fdc0..d72fb203810 100644--- a/packages/builtin-tool-message/src/types.ts+++ b/packages/builtin-tool-message/src/types.ts@@ -143,7 +143,20 @@ export interface SendMessageEmbed {// --- Direct Messaging ----export interface SendDirectMessageParams {+/**+ * Which connection a send goes out through. Both are optional: when neither is+ * set and the call targets the IM conversation this run is replying in, the+ * server runtime sends through the same connection the conversation arrived+ * on (per-agent bot or System Bot messenger). Never set both.+ */+export interface MessageSendRoute {+ /** Per-agent bot id from `listBots`. */+ botId?: string;+ /** System Bot connection id from `listMessengers`. */+ messengerInstallationId?: string;+}++export interface SendDirectMessageParams extends MessageSendRoute {/*** Optional: outbound media attachments (images / files / video / audio).* Same shape as `SendMessageParams.attachments` β see `SendMessageAttachment`.@@ -211,7 +224,7 @@ export interface SendMessageAttachment {type: 'image' | 'file' | 'video' | 'audio';}-export interface SendMessageParams {+export interface SendMessageParams extends MessageSendRoute {/*** Optional: outbound media attachments (images / files / video / audio).* Platforms that don't support outbound media silently drop these so the@@ -506,7 +519,7 @@ export interface ListThreadsState {threads?: { id: string; messageCount?: number; name: string }[];}-export interface ReplyToThreadParams {+export interface ReplyToThreadParams extends MessageSendRoute {/*** Optional: outbound media attachments (images / files / video / audio).* Same shape as `SendMessageParams.attachments` β see `SendMessageAttachment`.diff --git a/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snap b/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snapindex 4d49538b327..5c7561e9dd2 100644--- a/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snap+++ b/packages/prompts/src/prompts/botPlatformContext/__snapshots__/index.test.ts.snap@@ -14,7 +14,8 @@ You are a participant in a **WeChat** conversation β not an external assistant<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery><formatting>@@ -46,7 +47,8 @@ You are a participant in a **Discord** conversation β not an external assistan<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery></bot_platform_context>"`;@@ -65,7 +67,8 @@ You are a participant in a **WeChat** conversation β not an external assistant<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery><formatting>@@ -96,7 +99,8 @@ You are a participant in a **WeChat** conversation β not an external assistant<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery><formatting>@@ -135,7 +139,8 @@ You are a participant in a **WeChat** conversation β not an external assistant<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery><formatting>@@ -181,7 +186,8 @@ You are a participant in a **Telegram** conversation β not an external assista<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery><processing_warnings>@@ -208,7 +214,8 @@ You are a participant in a **Lark** conversation β not an external assistant b<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery><current_conversation platform="lark" channelId="oc_84983ff6516d731e">@@ -218,6 +225,7 @@ These are the EXACT argument values for any \`lobe-message\` call that targets tYou already have everything \`readMessages\` needs. Call it with these two values the moment you need prior context.NEVER ask the user for a chat / channel / group ID, and never call \`listChannels\` to look up the current one β it is right here.+When a \`lobe-message\` send targets this conversation, omit \`botId\` / \`messengerInstallationId\` β the runtime already knows which connection this conversation uses.</current_conversation></bot_platform_context>"`;@@ -236,7 +244,8 @@ You are a participant in a **WeChat** conversation β not an external assistant<message_delivery>Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.Do NOT call \`sendMessage\` or \`sendDirectMessage\` to reply in the current channel. Just respond with text directly.-\`sendMessage\` / \`sendDirectMessage\` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.+Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call \`sendMessage\` with \`attachments\` for the current conversation and pass NEITHER \`botId\` NOR \`messengerInstallationId\`: the runtime sends it through the same connection this conversation arrived on. Do not run \`listBots\` / \`listMessengers\` for this.+\`sendMessage\` / \`sendDirectMessage\` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.</message_delivery><formatting>diff --git a/packages/prompts/src/prompts/botPlatformContext/index.test.ts b/packages/prompts/src/prompts/botPlatformContext/index.test.tsindex 9c76bd87d5b..1e4131763ea 100644--- a/packages/prompts/src/prompts/botPlatformContext/index.test.ts+++ b/packages/prompts/src/prompts/botPlatformContext/index.test.ts@@ -38,6 +38,21 @@ describe('formatBotPlatformContext', () => {expect(result).toMatchSnapshot();});+ it('routes file delivery into the current conversation through its own connection', () => {+ const result = formatBotPlatformContext({+ canReadHistory: false,+ currentChannel: { id: '[email protected]', platformId: 'wechat' },+ platformName: 'WeChat',+ supportsMarkdown: false,+ });++ // Files can't ride the text reply, so `sendMessage` is allowed for them β+ // but without bot discovery, which could pick a different (failed) bot.+ expect(result).toContain('pass NEITHER `botId` NOR `messengerInstallationId`');+ expect(result).toContain('Do not run `listBots` / `listMessengers` for this.');+ expect(result).toContain('omit `botId` / `messengerInstallationId`');+ });+it('keeps the channel block on platforms without history-read, minus the readMessages line', () => {const result = formatBotPlatformContext({canReadHistory: false,diff --git a/packages/prompts/src/prompts/botPlatformContext/index.ts b/packages/prompts/src/prompts/botPlatformContext/index.tsindex c7d23cab910..20e9f84b107 100644--- a/packages/prompts/src/prompts/botPlatformContext/index.ts+++ b/packages/prompts/src/prompts/botPlatformContext/index.ts@@ -105,7 +105,12 @@ export const formatBotPlatformContext = ({'<message_delivery>','Your text response is AUTOMATICALLY delivered to the current conversation β the runtime pipeline handles it.','Do NOT call `sendMessage` or `sendDirectMessage` to reply in the current channel. Just respond with text directly.',- '`sendMessage` / `sendDirectMessage` should ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.',+ // Text replies cannot carry files, so delivering a generated file into this+ // conversation is the one legitimate `sendMessage` here. Without a route+ // hint the model runs `<outbound_routing>` discovery and may pick another+ // bot on the same platform β one with an expired session (LOBE-14350).+ 'Exception β files: your text reply cannot carry attachments. To deliver a file / image / video / audio into THIS conversation, call `sendMessage` with `attachments` for the current conversation and pass NEITHER `botId` NOR `messengerInstallationId`: the runtime sends it through the same connection this conversation arrived on. Do not run `listBots` / `listMessengers` for this.',+ '`sendMessage` / `sendDirectMessage` should otherwise ONLY be used when the user explicitly asks you to send a message to a DIFFERENT channel or user.','</message_delivery>',];@@ -129,6 +134,7 @@ export const formatBotPlatformContext = ({]: []),'NEVER ask the user for a chat / channel / group ID, and never call `listChannels` to look up the current one β it is right here.',+ 'When a `lobe-message` send targets this conversation, omit `botId` / `messengerInstallationId` β the runtime already knows which connection this conversation uses.','</current_conversation>',);}diff --git a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.test.ts b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.test.tsnew file mode 100644index 00000000000..a858310d770--- /dev/null+++ b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.test.ts@@ -0,0 +1,62 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { mockListProviders, mockSendMessage } = vi.hoisted(() => ({+ mockListProviders: vi.fn(),+ mockSendMessage: vi.fn(),+}));++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ agentBotProvider: { list: { query: mockListProviders } },+ botMessage: { sendMessage: { mutate: mockSendMessage } },+ },+}));++const { trpcMessageService } = await import('./trpcAdapters');++describe('trpcMessageService routing', () => {+ beforeEach(() => {+ mockListProviders.mockReset();+ mockSendMessage.mockReset();+ mockSendMessage.mockResolvedValue({ messageId: 'm-1' });+ });++ it('forwards a System Bot send as-is instead of injecting a platform default botId', async () => {+ mockListProviders.mockResolvedValue([+ { enabled: true, id: 'bot-1', platform: 'wechat', runtimeStatus: 'connected' },+ ]);++ await trpcMessageService.sendMessage({+ channelId: '[email protected]',+ content: 'hi',+ messengerInstallationId: 'link-1',+ platform: 'wechat',+ });++ expect(mockSendMessage).toHaveBeenCalledWith({+ channelId: '[email protected]',+ content: 'hi',+ messengerInstallationId: 'link-1',+ });+ expect(mockListProviders).not.toHaveBeenCalled();+ });++ it('skips failed bots when resolving the platform default', async () => {+ mockListProviders.mockResolvedValue([+ { enabled: true, id: 'bot-failed', platform: 'wechat', runtimeStatus: 'failed' },+ { enabled: true, id: 'bot-ok', platform: 'wechat', runtimeStatus: 'connected' },+ ]);++ await trpcMessageService.sendMessage({+ channelId: '[email protected]',+ content: 'hi',+ platform: 'wechat',+ });++ expect(mockSendMessage).toHaveBeenCalledWith({+ botId: 'bot-ok',+ channelId: '[email protected]',+ content: 'hi',+ });+ });+});diff --git a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.tsindex 8060ce15fab..cf0246563ab 100644--- a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts+++ b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts@@ -220,7 +220,7 @@ export const trpcBotProvider: BotProviderQuery = {** Runtime callers pass `{ platform, ...rest }` and may omit `botId`. We* resolve `botId` from `platform` here (frontend convenience β find the- * first enabled bot on that platform) and strip `platform` before+ * first enabled, non-failed bot on that platform) and strip `platform` before* forwarding, mirroring the original `_callBotMessage` behavior.*/const resolveBotId = async (params: { botId?: string; platform?: string }): Promise<string> => {@@ -229,7 +229,11 @@ const resolveBotId = async (params: { botId?: string; platform?: string }): Promthrow new Error('botId or platform is required');}const providers = (await lambdaClient.agentBotProvider.list.query()) as any[];- const bot = providers.find((b) => b.platform === params.platform && b.enabled);+ // A `failed` bot's credentials are known-broken (e.g. an expired WeChat+ // session rejects every upload) β never auto-pick one.+ const bot = providers.find(+ (b) => b.platform === params.platform && b.enabled && b.runtimeStatus !== 'failed',+ );if (!bot) {throw new Error(`No enabled bot found for platform "${params.platform}". Configure one first.`);}@@ -243,8 +247,12 @@ const resolveBotId = async (params: { botId?: string; platform?: string }): Prom* vary; the TRPC procedures will type-check the final shape.*/const buildTrpcInput = async (params: any): Promise<any> => {- const botId = await resolveBotId(params);const { botId: _b, platform: _p, ...rest } = params ?? {};+ // A System Bot send names its connection already; injecting a platform+ // default `botId` next to it would trip the procedures' "exactly one of"+ // check and reject the call.+ if (rest.messengerInstallationId) return rest;+ const botId = await resolveBotId(params);return { ...rest, botId };};