Skip to content

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

๐Ÿ› fix(bot): show chat images to the model in readMessages / searchMessages results (#21758)

Arvin Xu2b8ee4c9784e
diff --git a/apps/server/src/services/bot/platforms/discord/service.ts b/apps/server/src/services/bot/platforms/discord/service.ts
index 8ac6a2f5b2e..dbe2f8e52f9 100644
--- a/apps/server/src/services/bot/platforms/discord/service.ts
+++ b/apps/server/src/services/bot/platforms/discord/service.ts
@@ -52,7 +52,12 @@ import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttac
* Normalize a Discord API message object to MessageItem.
*/
const toMessageItem = (msg: any): MessageItem => ({
- attachments: msg.attachments?.map((a: any) => ({ name: a.filename, url: a.url })),
+ attachments: msg.attachments?.map((a: any) => ({
+ contentType: a.content_type,
+ name: a.filename,
+ size: a.size,
+ url: a.url,
+ })),
author: { id: msg.author?.id ?? '', name: msg.author?.username ?? 'Unknown' },
content: msg.content ?? '',
id: msg.id,
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
index 5c26b1091eb..e90e8a6884a 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/index.ts
@@ -60,6 +60,7 @@ import { sendMessengerPush } from '@/server/services/messenger/push';
import type { ServerRuntimeRegistration } from '../types';
import type { MessageRouteParams } from './MessageDispatcherService';
import { MessageDispatcherService } from './MessageDispatcherService';
+import { createMessageImageStore } from './storeMessageImages';
/**
* Shape returned by `listMessengers` / `getMessengerDetail` to the tool runtime.
@@ -906,7 +907,16 @@ export const messageRuntime: ServerRuntimeRegistration = {
},
};
- return new MessageExecutionRuntime({ botProvider, service });
+ return new MessageExecutionRuntime({
+ botProvider,
+ resolveImages: createMessageImageStore({
+ agentId: context.agentId,
+ serverDB,
+ userId,
+ workspaceId: context.workspaceId,
+ }),
+ service,
+ });
},
identifier: MessageToolIdentifier,
};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/storeMessageImages.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/storeMessageImages.test.ts
new file mode 100644
index 00000000000..6096da18615
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/storeMessageImages.test.ts
@@ -0,0 +1,118 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createMessageImageStore, MAX_MESSAGE_IMAGE_BYTES } from './storeMessageImages';
+
+const uploadFromBuffer = vi.hoisted(() => vi.fn());
+const fetchMock = vi.hoisted(() => vi.fn());
+
+vi.mock('@lobechat/ssrf-safe-fetch', () => ({ ssrfSafeFetch: fetchMock }));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return { uploadFromBuffer };
+ }),
+}));
+
+vi.mock('../resolveWorkspaceScope', () => ({
+ resolveContentWorkspaceId: vi.fn().mockResolvedValue('ws_1'),
+}));
+
+const candidate = (overrides: Record<string, unknown> = {}) => ({
+ mediaType: 'image/png',
+ messageId: '1564834535558881420',
+ name: 'image.png',
+ size: 1000,
+ url: 'https://cdn.discordapp.com/attachments/1/2/image.png?ex=1',
+ ...overrides,
+});
+
+const pngResponse = (bytes = 1000, contentType = 'image/png') =>
+ new Response(new Uint8Array(bytes), {
+ headers: { 'content-length': String(bytes), 'content-type': contentType },
+ });
+
+const store = createMessageImageStore({ serverDB: {} as any, userId: 'user_1' });
+
+describe('createMessageImageStore', () => {
+ beforeEach(() => {
+ uploadFromBuffer.mockResolvedValue({ fileId: 'file_1', key: 'k', url: 'https://app/f/file_1' });
+ });
+
+ afterEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('copies a Discord image into file storage and returns the durable URL', async () => {
+ fetchMock.mockResolvedValue(pngResponse());
+
+ const images = await store([candidate()]);
+
+ expect(images).toEqual([
+ {
+ fileId: 'file_1',
+ mediaType: 'image/png',
+ messageId: '1564834535558881420',
+ name: 'image.png',
+ url: 'https://app/f/file_1',
+ },
+ ]);
+ const [buffer, mediaType, pathname] = uploadFromBuffer.mock.calls[0];
+ expect(buffer.length).toBe(1000);
+ expect(mediaType).toBe('image/png');
+ expect(pathname).toMatch(
+ /^files\/\d{4}-\d{2}-\d{2}\/im-1564834535558881420-[\da-f]{12}-image\.png$/,
+ );
+ });
+
+ it('never fetches hosts off the allowlist', async () => {
+ const images = await store([
+ candidate({ url: 'https://files.slack.com/private/a.png' }),
+ candidate({ url: 'http://cdn.discordapp.com/a.png' }),
+ candidate({ url: 'https://169.254.169.254/latest' }),
+ ]);
+
+ expect(images).toEqual([]);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('skips images over the size limit, by declared size or by body', async () => {
+ fetchMock.mockResolvedValue(pngResponse(MAX_MESSAGE_IMAGE_BYTES + 1));
+
+ const images = await store([
+ candidate({ size: MAX_MESSAGE_IMAGE_BYTES + 1 }),
+ candidate({ name: 'b.png', size: undefined }),
+ ]);
+
+ expect(images).toEqual([]);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(uploadFromBuffer).not.toHaveBeenCalled();
+ });
+
+ it('skips a body whose type is not the image the platform announced', async () => {
+ fetchMock.mockResolvedValue(pngResponse(1000, 'text/html'));
+
+ expect(await store([candidate()])).toEqual([]);
+ });
+
+ it('keeps the images that worked when another one fails', async () => {
+ fetchMock.mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce(pngResponse());
+
+ const images = await store([candidate({ name: 'a.png' }), candidate({ name: 'b.png' })]);
+
+ expect(images.map((image) => image.name)).toEqual(['b.png']);
+ });
+
+ it('gives two attachments with the same file name different object keys', async () => {
+ fetchMock.mockImplementation(async () => pngResponse());
+
+ await store([
+ candidate({ url: 'https://cdn.discordapp.com/attachments/1/111/image.png' }),
+ candidate({ url: 'https://cdn.discordapp.com/attachments/1/222/image.png' }),
+ ]);
+
+ const keys = uploadFromBuffer.mock.calls.map((call) => call[2]);
+ expect(keys).toHaveLength(2);
+ expect(new Set(keys).size).toBe(2);
+ });
+});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/message/storeMessageImages.ts b/apps/server/src/services/toolExecution/serverRuntimes/message/storeMessageImages.ts
new file mode 100644
index 00000000000..de42accb194
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/message/storeMessageImages.ts
@@ -0,0 +1,139 @@
+import { createHash } from 'node:crypto';
+
+import type {
+ MessageImageCandidate,
+ MessageImageResolver,
+ MessageToolImage,
+} from '@lobechat/builtin-tool-message/executionRuntime';
+import type { LobeChatDatabase } from '@lobechat/database';
+import { ssrfSafeFetch } from '@lobechat/ssrf-safe-fetch';
+import { readBlobWithLimit } from '@lobechat/utils/imageToBase64';
+import debug from 'debug';
+import pMap from 'p-map';
+
+import { FileService } from '@/server/services/file';
+
+import { resolveContentWorkspaceId } from '../resolveWorkspaceScope';
+
+const log = debug('lobe-server:message-runtime:images');
+
+/**
+ * Hosts whose attachment URLs are public and need no credentials. Slack (`url_private`) and the
+ * others need the bot token to download, so their images stay text markers for now.
+ */
+const ALLOWED_HOSTS = new Set(['cdn.discordapp.com', 'media.discordapp.net']);
+
+/** Anthropic rejects images above 5 MB; the smallest provider limit wins. */
+export const MAX_MESSAGE_IMAGE_BYTES = 5 * 1024 * 1024;
+const FETCH_TIMEOUT_MS = 10_000;
+/** Downloads and uploads run a couple at a time; a page carries at most a few images anyway. */
+const STORE_CONCURRENCY = 2;
+
+const isAllowedUrl = (raw: string) => {
+ try {
+ const url = new URL(raw);
+ return url.protocol === 'https:' && ALLOWED_HOSTS.has(url.hostname);
+ } catch {
+ return false;
+ }
+};
+
+const safeName = (name: string) => name.replaceAll(/[^\w.-]/g, '_').slice(-80) || 'image';
+
+/**
+ * One object key per attachment. Two attachments of a message can share a file name (or collide
+ * once sanitized), so the key carries a hash of the attachment URL's path, which names the
+ * attachment itself (Discord: `/attachments/{channel}/{attachment}/{file}`).
+ */
+export const messageImageKey = (candidate: MessageImageCandidate, date: string) => {
+ const path = new URL(candidate.url).pathname;
+ const id = createHash('sha256').update(path).digest('hex').slice(0, 12);
+ return `files/${date}/im-${candidate.messageId}-${id}-${safeName(candidate.name)}`;
+};
+
+/** Downloads one image within the size and type limits; undefined when it does not qualify. */
+const download = async (candidate: MessageImageCandidate) => {
+ if (!isAllowedUrl(candidate.url)) return;
+ if (candidate.size !== undefined && candidate.size > MAX_MESSAGE_IMAGE_BYTES) return;
+
+ // The host allowlist is checked before the request; ssrfSafeFetch also validates the resolved
+ // address at connect time and on every redirect hop, so DNS cannot point it inside.
+ const response = await ssrfSafeFetch(
+ candidate.url,
+ { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) },
+ { maxContentLength: MAX_MESSAGE_IMAGE_BYTES + 1 },
+ );
+ if (!response.ok) {
+ await response.body?.cancel().catch(() => {});
+ throw new Error(`HTTP ${response.status}`);
+ }
+
+ const mediaType = response.headers.get('content-type')?.split(';')[0].trim().toLowerCase();
+ if (mediaType !== candidate.mediaType) {
+ await response.body?.cancel().catch(() => {});
+ return;
+ }
+
+ const blob = await readBlobWithLimit(response, MAX_MESSAGE_IMAGE_BYTES);
+ const buffer = Buffer.from(await blob.arrayBuffer());
+ if (buffer.length === 0) return;
+
+ return buffer;
+};
+
+/**
+ * Copies chat image attachments into file storage so the readMessages / searchMessages result
+ * can show them to a vision model. Platform CDN links expire (Discord signs them for about a
+ * day) and a bot topic outlives that, so the stored proxy URL is what the tool result keeps.
+ *
+ * Best-effort per image: one that is too large, of another type, off the host allowlist or
+ * failing to download is left out, and the rest still ride on the result.
+ */
+export const createMessageImageStore = (context: {
+ agentId?: string;
+ serverDB: LobeChatDatabase;
+ userId: string;
+ workspaceId?: string | null;
+}): MessageImageResolver => {
+ return async (candidates) => {
+ const eligible = candidates.filter((candidate) => isAllowedUrl(candidate.url));
+ if (eligible.length === 0) return [];
+
+ const workspaceId = await resolveContentWorkspaceId({
+ agentId: context.agentId,
+ serverDB: context.serverDB,
+ workspaceId: context.workspaceId ?? undefined,
+ } as never);
+ const fileService = new FileService(context.serverDB, context.userId, workspaceId);
+ const date = new Date().toISOString().slice(0, 10);
+
+ const stored = await pMap(
+ eligible,
+ async (candidate): Promise<MessageToolImage | undefined> => {
+ try {
+ const buffer = await download(candidate);
+ if (!buffer) return;
+
+ const { fileId, url } = await fileService.uploadFromBuffer(
+ buffer,
+ candidate.mediaType,
+ messageImageKey(candidate, date),
+ );
+
+ return {
+ fileId,
+ mediaType: candidate.mediaType,
+ messageId: candidate.messageId,
+ name: candidate.name,
+ url,
+ };
+ } catch (error) {
+ log('image %s skipped: %O', candidate.url, error);
+ }
+ },
+ { concurrency: STORE_CONCURRENCY },
+ );
+
+ return stored.filter((image): image is MessageToolImage => !!image);
+ };
+};
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/attachmentOutcome.ts b/packages/builtin-tool-message/src/ExecutionRuntime/attachmentOutcome.ts
new file mode 100644
index 00000000000..9b8e0fca31f
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/attachmentOutcome.ts
@@ -0,0 +1,45 @@
+import type { SendAttachmentsOutcome, SendMessageAttachment } from '../types';
+
+/**
+ * Turn a send state's attachment outcome into what the model must read.
+ *
+ * Attachment failures are swallowed per item on purpose so the text leg still
+ * ships โ€” but a `success: true` that says nothing about them is how the model
+ * ends up telling the user "see attached" about a file that never arrived.
+ * The failed attachments are named, with the reason, and the model is told
+ * to fall back to a download link instead of claiming delivery.
+ *
+ * `success` stays true while SOMETHING reached the user (text, an embed, or
+ * at least one attachment). When there was no text and every attachment failed, nothing was
+ * delivered and the call is reported as failed.
+ */
+export const describeAttachmentOutcome = (
+ params: { attachments?: SendMessageAttachment[]; content?: string; embeds?: unknown[] },
+ state: SendAttachmentsOutcome,
+ /** The success line, used verbatim while something reached the user. */
+ sentLine: string,
+): { content: string; success: boolean } => {
+ const failures = state.attachmentFailures ?? [];
+ if (failures.length === 0) return { content: sentLine, success: true };
+
+ const requested = params.attachments?.length ?? failures.length;
+ const lines = failures.map(
+ (f) =>
+ `- "${f.name ?? '(unnamed)'}" (${f.type}): ${f.reason}${f.detail ? ` โ€” ${f.detail}` : ''}`,
+ );
+ // Embeds ride the text leg (Discord posts them even with empty content), so
+ // a delivered embed counts as something reaching the user.
+ const nothingDelivered =
+ (state.attachmentsDelivered ?? 0) === 0 && !params.content?.trim() && !params.embeds?.length;
+ const content = [
+ // Never open with "Message sent" when nothing was: the lead line is what a
+ // skimming model reads first.
+ nothingDelivered ? 'Nothing was delivered.' : sentLine,
+ `WARNING: ${failures.length} of ${requested} attachment(s) were NOT delivered:`,
+ ...lines,
+ nothingDelivered
+ ? 'No text or embed was given and every attachment failed, so the user received nothing. Do not tell them a file was sent.'
+ : 'Only the text (and any attachments not listed above) reached the user. Do NOT claim these files were attached โ€” tell the user which files could not be delivered and share a download link for each instead.',
+ ].join('\n');
+ return { content, success: !nothingDelivered };
+};
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/botManagement.test.ts b/packages/builtin-tool-message/src/ExecutionRuntime/botManagement.test.ts
new file mode 100644
index 00000000000..4423e43e2b9
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/botManagement.test.ts
@@ -0,0 +1,281 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { MessageExecutionRuntime } from './index';
+import type { BotProviderQuery } from './types';
+
+const runtimeWith = (botProvider?: Partial<BotProviderQuery>) =>
+ new MessageExecutionRuntime({
+ botProvider: botProvider as BotProviderQuery | undefined,
+ service: {} as any,
+ });
+
+type Call = [method: keyof MessageExecutionRuntime, params: any, provider: keyof BotProviderQuery];
+
+const calls: Call[] = [
+ ['listPlatforms', {}, 'listPlatforms'],
+ ['listBots', {}, 'listBots'],
+ ['getBotDetail', { botId: 'b1' }, 'getBotDetail'],
+ [
+ 'createBot',
+ { agentId: 'a', applicationId: 'x', credentials: {}, platform: 'discord' },
+ 'createBot',
+ ],
+ ['updateBot', { botId: 'b1', settings: {} }, 'updateBot'],
+ ['deleteBot', { botId: 'b1' }, 'deleteBot'],
+ ['toggleBot', { botId: 'b1', enabled: true }, 'toggleBot'],
+ ['connectBot', { botId: 'b1' }, 'connectBot'],
+ ['listMessengers', {}, 'listMessengers'],
+ ['getMessengerDetail', { installationId: 'i1' }, 'getMessengerDetail'],
+ ['uninstallMessenger', { installationId: 'i1' }, 'uninstallMessenger'],
+ ['listMessengerPlatforms', {}, 'listMessengerPlatforms'],
+ ['listMessengerLinks', {}, 'listMessengerLinks'],
+ ['setMessengerActiveAgent', { agentId: 'a1', platform: 'slack' }, 'setMessengerActiveAgent'],
+ ['unlinkMessenger', { platform: 'slack' }, 'unlinkMessenger'],
+ ['sendMessengerPush', { content: 'hi', platform: 'telegram' }, 'sendMessengerPush'],
+];
+
+const invoke = (runtime: MessageExecutionRuntime, method: Call[0], params: unknown) =>
+ (runtime[method] as (p: unknown) => Promise<any>).call(runtime, params);
+
+describe('MessageExecutionRuntime bot management', () => {
+ it.each(calls)('%s fails cleanly without a bot provider', async (method, params) => {
+ const output = await invoke(runtimeWith(), method, params);
+
+ expect(output.success).toBe(false);
+ expect(output.content).toMatch(/not available/);
+ });
+
+ it.each(calls)('%s reports a provider error instead of throwing', async (method, params, fn) => {
+ const output = await invoke(
+ runtimeWith({ [fn]: vi.fn().mockRejectedValue(new Error('boom')) }),
+ method,
+ params,
+ );
+
+ expect(output).toEqual({ content: `${method} error: boom`, success: false });
+ });
+
+ it('lists platforms with their required credentials', async () => {
+ const output = await runtimeWith({
+ listPlatforms: vi.fn().mockResolvedValue([
+ {
+ credentialFields: [
+ { key: 'botToken', required: true },
+ { key: 'note', required: false },
+ ],
+ id: 'discord',
+ name: 'Discord',
+ },
+ { credentialFields: [], id: 'wechat', name: 'WeChat' },
+ ]),
+ }).listPlatforms({});
+
+ expect(output.content).toBe(
+ '2 supported platform(s):\n- **Discord** (discord) โ€” requires: botToken\n- **WeChat** (wechat)',
+ );
+ });
+
+ it('lists bots, and says so when there are none', async () => {
+ const listBots = vi
+ .fn()
+ .mockResolvedValueOnce([
+ { enabled: true, id: 'b1', platform: 'discord', serverId: 's1', userId: 'u1' },
+ ]);
+ listBots.mockResolvedValueOnce([]);
+ const runtime = runtimeWith({ listBots });
+
+ expect((await runtime.listBots({})).content).toBe(
+ '1 configured bot(s):\n- discord (platform: discord, botId: b1, enabled: true, status: unknown, serverId: s1, userId: u1)',
+ );
+ expect((await runtime.listBots({})).content).toMatch(/^No bots configured/);
+ });
+
+ it('describes one bot, or reports it missing', async () => {
+ const getBotDetail = vi
+ .fn()
+ .mockResolvedValueOnce({
+ applicationId: 'app1',
+ enabled: false,
+ id: 'b1',
+ platform: 'discord',
+ runtimeStatus: 'connected',
+ settings: { a: 1 },
+ })
+ .mockResolvedValueOnce(null);
+ const runtime = runtimeWith({ getBotDetail });
+
+ expect((await runtime.getBotDetail({ botId: 'b1' })).content).toBe(
+ 'Bot b1:\n- Platform: discord\n- App ID: app1\n- Enabled: false\n- Status: connected\n- Settings: {"a":1}',
+ );
+ expect(await runtime.getBotDetail({ botId: 'b2' })).toEqual({
+ content: 'Bot not found: b2',
+ success: false,
+ });
+ });
+
+ it('confirms bot writes', async () => {
+ const runtime = runtimeWith({
+ connectBot: vi.fn().mockResolvedValue({ status: 'connecting' }),
+ createBot: vi.fn().mockResolvedValue({ id: 'b9', platform: 'slack' }),
+ deleteBot: vi.fn().mockResolvedValue(undefined),
+ toggleBot: vi.fn().mockResolvedValue(undefined),
+ updateBot: vi.fn().mockResolvedValue(undefined),
+ });
+
+ expect((await runtime.createBot(calls[3][1])).content).toBe('Created slack bot (id: b9)');
+ expect((await runtime.updateBot({ botId: 'b1' })).content).toBe('Updated bot b1');
+ expect((await runtime.deleteBot({ botId: 'b1' })).content).toBe('Deleted bot b1');
+ expect((await runtime.toggleBot({ botId: 'b1', enabled: false })).content).toBe(
+ 'Bot b1 disabled',
+ );
+ expect((await runtime.connectBot({ botId: 'b1' })).content).toBe(
+ 'Bot connection initiated (status: connecting)',
+ );
+ });
+});
+
+describe('MessageExecutionRuntime messenger management', () => {
+ it('lists messenger installs, and points to settings when there are none', async () => {
+ const listMessengers = vi
+ .fn()
+ .mockResolvedValueOnce([
+ {
+ id: 'i1',
+ installedAt: new Date('2026-10-01T00:00:00Z'),
+ platform: 'slack',
+ tenantName: 'Acme',
+ },
+ { id: 'i2', platform: 'feishu', tenantId: 't2' },
+ ])
+ .mockResolvedValueOnce([]);
+ const runtime = runtimeWith({ listMessengers });
+
+ expect((await runtime.listMessengers({})).content).toBe(
+ '2 System Bot connection(s):\n- installationId: i1, platform: slack, tenant: Acme, installedAt: 2026-10-01T00:00:00.000Z\n- installationId: i2, platform: feishu, tenantId: t2',
+ );
+ expect((await runtime.listMessengers({})).content).toMatch(/^No System Bot connections/);
+ });
+
+ it('describes one install, or reports it missing', async () => {
+ const getMessengerDetail = vi
+ .fn()
+ .mockResolvedValueOnce({
+ applicationId: 'app',
+ id: 'i1',
+ installedAt: '2026-10-01',
+ platform: 'slack',
+ revokedAt: null,
+ scope: 'bot',
+ tenantId: '',
+ tenantName: 'Acme',
+ })
+ .mockResolvedValueOnce(null);
+ const runtime = runtimeWith({ getMessengerDetail });
+
+ expect((await runtime.getMessengerDetail({ installationId: 'i1' })).content).toBe(
+ 'installationId: i1\nplatform: slack\ntenantId: (global)\ntenant: Acme\napplicationId: app\nscope: bot\ninstalledAt: 2026-10-01\nrevoked: no',
+ );
+ expect((await runtime.getMessengerDetail({ installationId: 'i9' })).success).toBe(false);
+ });
+
+ it('lists install platforms and account links', async () => {
+ const runtime = runtimeWith({
+ listMessengerLinks: vi
+ .fn()
+ .mockResolvedValueOnce([
+ { activeAgentId: null, platform: 'slack', platformUsername: 'arvin', tenantId: 't1' },
+ ])
+ .mockResolvedValueOnce([]),
+ listMessengerPlatforms: vi
+ .fn()
+ .mockResolvedValueOnce([{ appId: 'A1', botUsername: 'lobe', id: 'slack', name: 'Slack' }])
+ .mockResolvedValueOnce([]),
+ });
+
+ expect((await runtime.listMessengerPlatforms({})).content).toContain(
+ '- slack (Slack) appId: A1 botUsername: lobe',
+ );
+ expect((await runtime.listMessengerPlatforms({})).content).toMatch(/^No System Bot platforms/);
+ expect((await runtime.listMessengerLinks({})).content).toBe(
+ '1 System Bot link(s):\n- platform: slack, tenantId: t1, activeAgentId: (none), platformUser: arvin',
+ );
+ expect((await runtime.listMessengerLinks({})).content).toMatch(/^No System Bot account links/);
+ });
+
+ it('confirms messenger writes', async () => {
+ const runtime = runtimeWith({
+ setMessengerActiveAgent: vi.fn().mockResolvedValue(undefined),
+ uninstallMessenger: vi.fn().mockResolvedValue(undefined),
+ unlinkMessenger: vi.fn().mockResolvedValue(undefined),
+ });
+
+ expect((await runtime.uninstallMessenger({ installationId: 'i1' })).content).toBe(
+ 'System Bot connection i1 disconnected.',
+ );
+ expect(
+ (await runtime.setMessengerActiveAgent({ agentId: null, platform: 'slack', tenantId: 't1' }))
+ .content,
+ ).toBe('Active agent for slack (tenant t1) cleared.');
+ expect((await runtime.unlinkMessenger({ platform: 'telegram' })).content).toBe(
+ 'Unlinked your account from telegram. The workspace install is unaffected.',
+ );
+ });
+});
+
+describe('MessageExecutionRuntime.sendMessengerPush', () => {
+ it.each([
+ ['sent', true, /pushed to the user's telegram DM/],
+ ['queued', true, /queued/],
+ ['unlinked', false, /no linked telegram account/],
+ ['unavailable', false, /currently unavailable/],
+ ])('maps status %s', async (status, success, content) => {
+ const output = await runtimeWith({
+ sendMessengerPush: vi.fn().mockResolvedValue({ status }),
+ }).sendMessengerPush({ content: 'hi', platform: 'telegram' });
+
+ expect(output.success).toBe(success);
+ expect(output.content).toMatch(content);
+ });
+
+ it('reports the remaining WeChat quota', async () => {
+ const output = await runtimeWith({
+ sendMessengerPush: vi.fn().mockResolvedValue({ remaining: 3, status: 'sent' }),
+ }).sendMessengerPush({ content: 'hi', platform: 'wechat' });
+
+ expect(output.content).toBe(
+ "Message pushed to the user's wechat DM (3 sends left in the current WeChat window).",
+ );
+ });
+
+ it('asks which Slack workspace when the user linked several', async () => {
+ const sendMessengerPush = vi.fn();
+ const output = await runtimeWith({
+ listMessengerLinks: vi.fn().mockResolvedValue([
+ { platform: 'slack', tenantId: 't1' },
+ { platform: 'slack', tenantId: 't2' },
+ ]),
+ listMessengers: vi
+ .fn()
+ .mockResolvedValue([{ platform: 'slack', tenantId: 't1', tenantName: 'Acme' }]),
+ sendMessengerPush,
+ }).sendMessengerPush({ content: 'hi', platform: 'slack' });
+
+ expect(sendMessengerPush).not.toHaveBeenCalled();
+ expect(output.state.status).toBe('needs_workspace_selection');
+ expect(output.content).toContain('- Acme (tenantId: t1)\n- t2 (tenantId: t2)');
+ });
+
+ it('pushes to the only linked Slack workspace', async () => {
+ const sendMessengerPush = vi.fn().mockResolvedValue({ status: 'sent' });
+ await runtimeWith({
+ listMessengerLinks: vi.fn().mockResolvedValue([{ platform: 'slack', tenantId: 't1' }]),
+ sendMessengerPush,
+ }).sendMessengerPush({ content: 'hi', platform: 'slack' });
+
+ expect(sendMessengerPush).toHaveBeenCalledWith({
+ content: 'hi',
+ platform: 'slack',
+ tenantId: 't1',
+ });
+ });
+});
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/botManagement.ts b/packages/builtin-tool-message/src/ExecutionRuntime/botManagement.ts
new file mode 100644
index 00000000000..9c1468fdd14
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/botManagement.ts
@@ -0,0 +1,544 @@
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import type {
+ ConnectBotParams,
+ ConnectBotState,
+ CreateBotParams,
+ CreateBotState,
+ DeleteBotParams,
+ DeleteBotState,
+ GetBotDetailParams,
+ GetBotDetailState,
+ GetMessengerDetailParams,
+ GetMessengerDetailState,
+ ListBotsParams,
+ ListBotsState,
+ ListMessengerLinksParams,
+ ListMessengerLinksState,
+ ListMessengerPlatformsParams,
+ ListMessengerPlatformsState,
+ ListMessengersParams,
+ ListMessengersState,
+ ListPlatformsParams,
+ ListPlatformsState,
+ MessengerPushPlatformType,
+ MessengerPushWorkspaceOption,
+ SendMessengerPushParams,
+ SendMessengerPushState,
+ SetMessengerActiveAgentParams,
+ SetMessengerActiveAgentState,
+ ToggleBotParams,
+ ToggleBotState,
+ UninstallMessengerParams,
+ UninstallMessengerState,
+ UnlinkMessengerParams,
+ UnlinkMessengerState,
+ UpdateBotParams,
+ UpdateBotState,
+} from '../types';
+import { ChannelMessageRuntime } from './channelMessages';
+import type { BotProviderQuery, MessageExecutionRuntimeOptions } from './types';
+
+/**
+ * The message tool's runtime: channel operations from `ChannelMessageRuntime`, plus managing the
+ * user's bots and System Bot messenger installs through `BotProviderQuery`.
+ */
+export class MessageExecutionRuntime extends ChannelMessageRuntime {
+ private botProvider?: BotProviderQuery;
+
+ constructor(options: MessageExecutionRuntimeOptions) {
+ super(options);
+ this.botProvider = options.botProvider;
+ }
+
+ // ==================== Bot Management ====================
+
+ async listPlatforms(_params: ListPlatformsParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return { content: 'Bot provider is not available.', success: false };
+ }
+ try {
+ const platforms = await this.botProvider.listPlatforms();
+ const formatted = platforms
+ .map((p) => {
+ const reqFields = p.credentialFields
+ .filter((f) => f.required)
+ .map((f) => f.key)
+ .join(', ');
+ return `- **${p.name}** (${p.id})${reqFields ? ` โ€” requires: ${reqFields}` : ''}`;
+ })
+ .join('\n');
+
+ return {
+ content: `${platforms.length} supported platform(s):\n${formatted}`,
+ state: { platforms } satisfies ListPlatformsState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `listPlatforms error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async listBots(_params: ListBotsParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return {
+ content: 'Bot provider query is not available in this context.',
+ success: false,
+ };
+ }
+
+ try {
+ const bots = await this.botProvider.listBots();
+ const formatted = bots
+ .map((b) => {
+ const parts = [
+ `platform: ${b.platform}`,
+ `botId: ${b.id}`,
+ `enabled: ${b.enabled}`,
+ `status: ${b.runtimeStatus ?? 'unknown'}`,
+ ];
+ if (b.serverId) {
+ parts.push(`serverId: ${b.serverId}`);
+ }
+ if (b.userId) {
+ parts.push(`userId: ${b.userId}`);
+ }
+ return `- ${b.platform} (${parts.join(', ')})`;
+ })
+ .join('\n');
+
+ return {
+ content:
+ bots.length > 0
+ ? `${bots.length} configured bot(s):\n${formatted}`
+ : 'No bots configured for this agent. Set up a bot integration first.',
+ state: { bots } satisfies ListBotsState,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `listBots error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async getBotDetail(params: GetBotDetailParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return { content: 'Bot provider is not available.', success: false };
+ }
+ try {
+ const bot = await this.botProvider.getBotDetail(params.botId);
+ if (!bot) {
+ return { content: `Bot not found: ${params.botId}`, success: false };
+ }
+ return {
+ content: `Bot ${bot.id}:\n- Platform: ${bot.platform}\n- App ID: ${bot.applicationId}\n- Enabled: ${bot.enabled}\n- Status: ${bot.runtimeStatus ?? 'unknown'}${bot.settings ? `\n- Settings: ${JSON.stringify(bot.settings)}` : ''}`,
+ state: bot satisfies GetBotDetailState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `getBotDetail error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async createBot(params: CreateBotParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return { content: 'Bot provider is not available.', success: false };
+ }
+ try {
+ const result = await this.botProvider.createBot(params);
+ return {
+ content: `Created ${result.platform} bot (id: ${result.id})`,
+ state: result satisfies CreateBotState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `createBot error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async updateBot(params: UpdateBotParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return { content: 'Bot provider is not available.', success: false };
+ }
+ try {
+ await this.botProvider.updateBot(params.botId, {
+ credentials: params.credentials,
+ settings: params.settings,
+ });
+ return {
+ content: `Updated bot ${params.botId}`,
+ state: { success: true } satisfies UpdateBotState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `updateBot error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async deleteBot(params: DeleteBotParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return { content: 'Bot provider is not available.', success: false };
+ }
+ try {
+ await this.botProvider.deleteBot(params.botId);
+ return {
+ content: `Deleted bot ${params.botId}`,
+ state: { success: true } satisfies DeleteBotState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `deleteBot error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async toggleBot(params: ToggleBotParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return { content: 'Bot provider is not available.', success: false };
+ }
+ try {
+ await this.botProvider.toggleBot(params.botId, params.enabled);
+ return {
+ content: `Bot ${params.botId} ${params.enabled ? 'enabled' : 'disabled'}`,
+ state: { enabled: params.enabled, success: true } satisfies ToggleBotState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `toggleBot error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async connectBot(params: ConnectBotParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider) {
+ return { content: 'Bot provider is not available.', success: false };
+ }
+ try {
+ const result = await this.botProvider.connectBot(params.botId);
+ return {
+ content: `Bot connection initiated (status: ${result.status})`,
+ state: result satisfies ConnectBotState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `connectBot error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ // ==================== System Bot Messenger Management ====================
+
+ async listMessengers(_params: ListMessengersParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.listMessengers) {
+ return {
+ content: 'System Bot messenger discovery is not available in this context.',
+ success: false,
+ };
+ }
+ try {
+ const installations = await this.botProvider.listMessengers();
+ if (installations.length === 0) {
+ return {
+ content:
+ 'No System Bot connections found. Tell the user to connect one via Settings โ†’ Messenger; `listMessengerPlatforms` shows what platforms are available.',
+ state: { installations } satisfies ListMessengersState,
+ success: true,
+ };
+ }
+ const lines = installations.map((i) => {
+ const parts = [`installationId: ${i.id}`, `platform: ${i.platform}`];
+ if (i.tenantName) parts.push(`tenant: ${i.tenantName}`);
+ else if (i.tenantId) parts.push(`tenantId: ${i.tenantId}`);
+ if (i.installedAt) {
+ const at = i.installedAt instanceof Date ? i.installedAt.toISOString() : i.installedAt;
+ parts.push(`installedAt: ${at}`);
+ }
+ return `- ${parts.join(', ')}`;
+ });
+ return {
+ content: `${installations.length} System Bot connection(s):\n${lines.join('\n')}`,
+ state: { installations } satisfies ListMessengersState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `listMessengers error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async getMessengerDetail(params: GetMessengerDetailParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.getMessengerDetail) {
+ return { content: 'getMessengerDetail is not available.', success: false };
+ }
+ try {
+ const install = await this.botProvider.getMessengerDetail(params.installationId);
+ if (!install) {
+ return {
+ content: `Messenger installation not found: ${params.installationId}`,
+ success: false,
+ };
+ }
+ const lines = [
+ `installationId: ${install.id}`,
+ `platform: ${install.platform}`,
+ `tenantId: ${install.tenantId || '(global)'}`,
+ ];
+ if (install.tenantName) lines.push(`tenant: ${install.tenantName}`);
+ if (install.applicationId) lines.push(`applicationId: ${install.applicationId}`);
+ if (install.scope) lines.push(`scope: ${install.scope}`);
+ if (install.installedAt) {
+ const at =
+ install.installedAt instanceof Date
+ ? install.installedAt.toISOString()
+ : install.installedAt;
+ lines.push(`installedAt: ${at}`);
+ }
+ lines.push(`revoked: ${install.revokedAt ? 'yes' : 'no'}`);
+ return {
+ content: lines.join('\n'),
+ state: install satisfies GetMessengerDetailState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `getMessengerDetail error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async uninstallMessenger(params: UninstallMessengerParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.uninstallMessenger) {
+ return { content: 'uninstallMessenger is not available.', success: false };
+ }
+ try {
+ await this.botProvider.uninstallMessenger(params.installationId);
+ return {
+ content: `System Bot connection ${params.installationId} disconnected.`,
+ state: { success: true } satisfies UninstallMessengerState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `uninstallMessenger error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async listMessengerPlatforms(
+ _params: ListMessengerPlatformsParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.listMessengerPlatforms) {
+ return { content: 'listMessengerPlatforms is not available.', success: false };
+ }
+ try {
+ const platforms = await this.botProvider.listMessengerPlatforms();
+ if (platforms.length === 0) {
+ return {
+ content:
+ 'No System Bot platforms are configured on this deployment. Ask the operator to enable at least one platform under Messenger configuration.',
+ state: { platforms } satisfies ListMessengerPlatformsState,
+ success: true,
+ };
+ }
+ const lines = platforms.map((p) => {
+ const parts = [p.id];
+ if (p.name && p.name !== p.id) parts.push(`(${p.name})`);
+ if (p.appId) parts.push(`appId: ${p.appId}`);
+ if (p.botUsername) parts.push(`botUsername: ${p.botUsername}`);
+ return `- ${parts.join(' ')}`;
+ });
+ return {
+ content: `${platforms.length} platform(s) available for System Bot install:\n${lines.join('\n')}\n\nInstalls are initiated via Settings โ†’ Messenger (OAuth requires a browser).`,
+ state: { platforms } satisfies ListMessengerPlatformsState,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `listMessengerPlatforms error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async listMessengerLinks(_params: ListMessengerLinksParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.listMessengerLinks) {
+ return { content: 'listMessengerLinks is not available.', success: false };
+ }
+ try {
+ const links = await this.botProvider.listMessengerLinks();
+ if (links.length === 0) {
+ return {
+ content:
+ 'No System Bot account links. The user has not completed verify-im on any platform yet.',
+ state: { links } satisfies ListMessengerLinksState,
+ success: true,
+ };
+ }
+ const lines = links.map((l) => {
+ const parts = [`platform: ${l.platform}`];
+ if (l.tenantId) parts.push(`tenantId: ${l.tenantId}`);
+ parts.push(`activeAgentId: ${l.activeAgentId ?? '(none)'}`);
+ if (l.platformUsername) parts.push(`platformUser: ${l.platformUsername}`);
+ return `- ${parts.join(', ')}`;
+ });
+ return {
+ content: `${links.length} System Bot link(s):\n${lines.join('\n')}`,
+ state: { links } satisfies ListMessengerLinksState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `listMessengerLinks error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ async setMessengerActiveAgent(
+ params: SetMessengerActiveAgentParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.setMessengerActiveAgent) {
+ return { content: 'setMessengerActiveAgent is not available.', success: false };
+ }
+ try {
+ await this.botProvider.setMessengerActiveAgent(params);
+ const target = params.agentId === null ? 'cleared' : `set to agent ${params.agentId}`;
+ const scope = params.tenantId ? ` (tenant ${params.tenantId})` : '';
+ return {
+ content: `Active agent for ${params.platform}${scope} ${target}.`,
+ state: { success: true } satisfies SetMessengerActiveAgentState,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `setMessengerActiveAgent error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async unlinkMessenger(params: UnlinkMessengerParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.unlinkMessenger) {
+ return { content: 'unlinkMessenger is not available.', success: false };
+ }
+ try {
+ await this.botProvider.unlinkMessenger(params);
+ const scope = params.tenantId ? ` (tenant ${params.tenantId})` : '';
+ return {
+ content: `Unlinked your account from ${params.platform}${scope}. The workspace install is unaffected.`,
+ state: { success: true } satisfies UnlinkMessengerState,
+ success: true,
+ };
+ } catch (e) {
+ return { content: `unlinkMessenger error: ${(e as Error).message}`, success: false };
+ }
+ }
+
+ // ==================== Proactive Messenger Push ====================
+
+ /**
+ * Resolve the Slack workspace a push should target when the caller didn't
+ * pass `tenantId`. Returns the single linked tenantId, or the candidate
+ * list when the choice is ambiguous (the user linked several workspaces).
+ */
+ private async resolveSlackPushTenant(): Promise<
+ { tenantId?: string } | { workspaces: MessengerPushWorkspaceOption[] }
+ > {
+ const links = (await this.botProvider!.listMessengerLinks?.()) ?? [];
+ const slackTenantIds = links
+ .filter((link) => link.platform === 'slack' && link.tenantId)
+ .map((link) => link.tenantId!);
+ if (slackTenantIds.length <= 1) return { tenantId: slackTenantIds[0] };
+
+ // Enrich with workspace names so the agent can present readable choices;
+ // installs may be missing (installed by a teammate) โ€” fall back to the id.
+ const installs = await this.botProvider!.listMessengers?.().catch(() => []);
+ const nameByTenant = new Map(
+ (installs ?? [])
+ .filter((install) => install.platform === 'slack')
+ .map((install) => [install.tenantId, install.tenantName]),
+ );
+ return {
+ workspaces: slackTenantIds.map((tenantId) => ({
+ tenantId,
+ tenantName: nameByTenant.get(tenantId) || undefined,
+ })),
+ };
+ }
+
+ async sendMessengerPush(params: SendMessengerPushParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.botProvider?.sendMessengerPush) {
+ return { content: 'sendMessengerPush is not available.', success: false };
+ }
+ const platform = params.platform as MessengerPushPlatformType;
+ try {
+ let tenantId = params.tenantId;
+
+ // Slack links can span several workspaces โ€” never pick one silently.
+ if (platform === 'slack' && tenantId === undefined) {
+ const resolved = await this.resolveSlackPushTenant();
+ if ('workspaces' in resolved) {
+ const lines = resolved.workspaces.map(
+ (w) => `- ${w.tenantName ?? w.tenantId} (tenantId: ${w.tenantId})`,
+ );
+ return {
+ content:
+ `The user's Slack account is linked to ${resolved.workspaces.length} workspaces:\n${lines.join('\n')}\n\n` +
+ 'Ask the user which workspace to push to, then call sendMessengerPush again with that tenantId.',
+ state: {
+ platform,
+ status: 'needs_workspace_selection',
+ workspaces: resolved.workspaces,
+ } satisfies SendMessengerPushState,
+ success: true,
+ };
+ }
+ tenantId = resolved.tenantId;
+ }
+
+ const result = await this.botProvider.sendMessengerPush({
+ content: params.content,
+ platform,
+ tenantId,
+ });
+ const state: SendMessengerPushState = {
+ platform,
+ remaining: result.remaining,
+ status: result.status,
+ tenantId,
+ };
+
+ switch (result.status) {
+ case 'sent': {
+ const quota =
+ platform === 'wechat' && result.remaining !== undefined
+ ? ` (${result.remaining} sends left in the current WeChat window)`
+ : '';
+ return {
+ content: `Message pushed to the user's ${platform} DM${quota}.`,
+ state,
+ success: true,
+ };
+ }
+ case 'queued': {
+ return {
+ // Queued is a success: delivery is deferred, not dropped. The
+ // agent must relay the "message the bot first" step to the user.
+ content:
+ 'The WeChat send window is closed or its quota is exhausted, so the message was queued. ' +
+ 'Tell the user to send any message to the LobeHub WeChat bot first โ€” the queued push will be delivered right after their message opens a new window.',
+ state,
+ success: true,
+ };
+ }
+ case 'unlinked': {
+ return {
+ content: `The user has no linked ${platform} account for the LobeHub System Bot. Ask them to open Settings โ†’ Messenger and connect ${platform} first.`,
+ state,
+ success: false,
+ };
+ }
+ default: {
+ return {
+ content: `Proactive push to ${platform} is currently unavailable โ€” the platform is not configured on this deployment or delivery failed. Do not retry immediately; surface this to the user.`,
+ state,
+ success: false,
+ };
+ }
+ }
+ } catch (e) {
+ return { content: `sendMessengerPush error: ${(e as Error).message}`, success: false };
+ }
+ }
+}
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/channelMessages.test.ts b/packages/builtin-tool-message/src/ExecutionRuntime/channelMessages.test.ts
new file mode 100644
index 00000000000..804c5145954
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/channelMessages.test.ts
@@ -0,0 +1,116 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { MessageExecutionRuntime } from './index';
+import type { MessageRuntimeService } from './types';
+
+const runtimeWith = (service: Partial<MessageRuntimeService>) =>
+ new MessageExecutionRuntime({ service: service as MessageRuntimeService });
+
+const base = { channelId: 'c1', platform: 'discord' };
+
+// [method, params, what the adapter returns, the line the model reads]
+const cases: [keyof MessageRuntimeService, any, any, string][] = [
+ ['editMessage', { ...base, content: 'x', messageId: 'm1' }, {}, 'Message m1 edited successfully'],
+ ['deleteMessage', { ...base, messageId: 'm1' }, {}, 'Message m1 deleted successfully'],
+ [
+ 'reactToMessage',
+ { ...base, emoji: '๐Ÿ‘', messageId: 'm1' },
+ {},
+ 'Reacted with ๐Ÿ‘ to message m1',
+ ],
+ [
+ 'getReactions',
+ { ...base, messageId: 'm1' },
+ { reactions: [{ count: 2, emoji: '๐Ÿ‘' }] },
+ 'Reactions on message m1: ๐Ÿ‘: 2',
+ ],
+ ['pinMessage', { ...base, messageId: 'm1' }, {}, 'Message m1 pinned in discord:c1'],
+ ['unpinMessage', { ...base, messageId: 'm1' }, {}, 'Message m1 unpinned'],
+ ['listPins', base, { messages: [{}, {}] }, '2 pinned messages in discord:c1'],
+ [
+ 'getChannelInfo',
+ base,
+ { memberCount: 5, name: 'general', type: 'text' },
+ 'Channel: general (type: text, members: 5)',
+ ],
+ [
+ 'getMemberInfo',
+ { ...base, memberId: 'u1' },
+ { displayName: 'Arvin', status: 'online' },
+ 'Member: Arvin (status: online)',
+ ],
+ [
+ 'createThread',
+ { ...base, content: 'x', name: 'Bug' },
+ { threadId: 't1' },
+ 'Thread "Bug" created (threadId: t1)',
+ ],
+ [
+ 'createPoll',
+ { ...base, options: ['a', 'b'], question: 'Ship?' },
+ { pollId: 'p1' },
+ 'Poll "Ship?" created in discord:c1 (pollId: p1)',
+ ],
+];
+
+describe('ChannelMessageRuntime', () => {
+ it.each(cases)(
+ '%s turns the adapter result into one line',
+ async (method, params, result, line) => {
+ const fn = vi.fn().mockResolvedValue(result);
+ const output = await (runtimeWith({ [method]: fn }) as any)[method](params);
+
+ expect(fn).toHaveBeenCalledWith(params);
+ expect(output.success).toBe(true);
+ expect(output.content).toContain(line);
+ },
+ );
+
+ it.each(cases)('%s reports an adapter error instead of throwing', async (method, params) => {
+ const output = await (
+ runtimeWith({
+ [method]: vi.fn().mockRejectedValue(new Error('rate limited')),
+ }) as any
+ )[method](params);
+
+ expect(output).toEqual({ content: `${method} error: rate limited`, success: false });
+ });
+
+ it('lists channels and threads', async () => {
+ const runtime = runtimeWith({
+ listChannels: vi.fn().mockResolvedValue({ channels: [{ id: 'c1', name: 'general' }] }),
+ listThreads: vi.fn().mockResolvedValue({ threads: [{ id: 't1', name: 'Bug' }] }),
+ });
+
+ expect((await runtime.listChannels({ platform: 'discord' })).content).toMatch(
+ /^1 channels found on discord/,
+ );
+ expect((await runtime.listThreads(base)).content).toMatch(/^1 threads in discord:c1/);
+ });
+
+ it('says when a platform has no document or DM API', async () => {
+ const runtime = runtimeWith({});
+
+ expect(await runtime.readDocument({ platform: 'discord', url: 'https://x' } as any)).toEqual({
+ content: 'readDocument is not supported on discord',
+ success: false,
+ });
+ expect(
+ (await runtime.sendDirectMessage({ content: 'hi', platform: 'discord', userId: 'u1' }))
+ .success,
+ ).toBe(false);
+ });
+
+ it('rejects conflicting or malformed Discord cursors before calling the adapter', async () => {
+ const readMessages = vi.fn();
+ const runtime = runtimeWith({ readMessages });
+
+ expect((await runtime.readMessages({ ...base, after: '2', before: '1' })).content).toMatch(
+ /mutually exclusive/,
+ );
+ expect((await runtime.readMessages({ ...base, before: 'abc' })).content).toMatch(
+ /decimal message ID/,
+ );
+ expect(readMessages).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/channelMessages.ts b/packages/builtin-tool-message/src/ExecutionRuntime/channelMessages.ts
new file mode 100644
index 00000000000..c0155a41797
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/channelMessages.ts
@@ -0,0 +1,458 @@
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import type {
+ CreatePollParams,
+ CreateThreadParams,
+ DeleteMessageParams,
+ EditMessageParams,
+ GetChannelInfoParams,
+ GetMemberInfoParams,
+ GetReactionsParams,
+ ListChannelsParams,
+ ListPinsParams,
+ ListThreadsParams,
+ MessageItem,
+ PinMessageParams,
+ ReactToMessageParams,
+ ReadDocumentParams,
+ ReadMessagesParams,
+ ReplyToThreadParams,
+ SearchMessagesParams,
+ SendDirectMessageParams,
+ SendMessageParams,
+ UnpinMessageParams,
+} from '../types';
+import { describeAttachmentOutcome } from './attachmentOutcome';
+import type { MessageImageResolver } from './messageImages';
+import {
+ collectImageCandidates,
+ describeAttachedImages,
+ formatMessageLines,
+} from './messageImages';
+import { describeDiscordPagination } from './pagination';
+import type { MessageExecutionRuntimeOptions, MessageRuntimeService } from './types';
+
+/**
+ * Operations on a chat platform's channels, messages and threads, all served by the platform
+ * adapter (`MessageRuntimeService`). Bot and messenger management builds on this in
+ * `MessageExecutionRuntime`.
+ */
+export class ChannelMessageRuntime {
+ private resolveImages?: MessageImageResolver;
+ private service: MessageRuntimeService;
+
+ constructor(options: Pick<MessageExecutionRuntimeOptions, 'resolveImages' | 'service'>) {
+ this.service = options.service;
+ this.resolveImages = options.resolveImages;
+ }
+
+ /**
+ * The newest image attachments of a message page, stored for the model. Never throws: a
+ * failed store leaves the images named in the text, and the read still succeeds.
+ */
+ private async attachImages(messages: MessageItem[] | undefined) {
+ const { candidates, total } = collectImageCandidates(messages);
+ if (candidates.length === 0 || !this.resolveImages) return { images: [], total };
+
+ try {
+ return { images: await this.resolveImages(candidates), total };
+ } catch {
+ return { images: [], total };
+ }
+ }
+
+ // ==================== Core Message Operations ====================
+
+ async sendMessage(params: SendMessageParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.sendMessage(params);
+ const outcome = describeAttachmentOutcome(
+ params,
+ result,
+ `Message sent to ${params.platform}:${params.channelId} (messageId: ${result.messageId})`,
+ );
+ return { content: outcome.content, state: result, success: outcome.success };
+ } catch (e) {
+ return {
+ content: `sendMessage error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async readMessages(params: ReadMessagesParams): Promise<BuiltinServerRuntimeOutput> {
+ if (params.platform === 'discord') {
+ if (params.before !== undefined && params.after !== undefined) {
+ return {
+ content: 'readMessages error: Discord before and after are mutually exclusive.',
+ success: false,
+ };
+ }
+ for (const direction of ['before', 'after'] as const) {
+ const cursor = params[direction];
+ if (cursor !== undefined && (typeof cursor !== 'string' || !/^\d+$/.test(cursor))) {
+ return {
+ content: `readMessages error: Discord ${direction} must be a non-empty decimal message ID string. Omit it when not needed.`,
+ success: false,
+ };
+ }
+ }
+ }
+ try {
+ const result = await this.service.readMessages(params);
+ const count = result.messages?.length ?? 0;
+ const { images, total } = await this.attachImages(result.messages);
+ const formatted = formatMessageLines(result.messages, images);
+
+ const paginationHint =
+ params.platform === 'discord'
+ ? describeDiscordPagination(params, result)
+ : result.hasMore && result.nextCursor
+ ? `\n\n[More messages available โ€” pass cursor: "${result.nextCursor}" to fetch next page]`
+ : '';
+
+ return {
+ content: `Fetched ${count} messages from ${params.platform}:${params.channelId}${params.platform === 'discord' ? paginationHint : ''}\n\n${formatted ?? '(no messages)'}${params.platform === 'discord' ? '' : paginationHint}${describeAttachedImages(images, total)}`,
+ state: images.length > 0 ? { ...result, images } : result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `readMessages error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async readDocument(params: ReadDocumentParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.service.readDocument) {
+ return {
+ content: `readDocument is not supported on ${params.platform}`,
+ success: false,
+ };
+ }
+ if (!params.url && !params.documentId) {
+ return {
+ content: 'readDocument error: pass the document `url` (preferred) or its `documentId`',
+ success: false,
+ };
+ }
+ try {
+ const result = await this.service.readDocument(params);
+ const header = [
+ `Document${result.title ? `: ${result.title}` : ''}`,
+ result.url ? `URL: ${result.url}` : undefined,
+ result.documentId
+ ? `ID: ${result.documentId}${result.kind ? ` (${result.kind})` : ''}`
+ : undefined,
+ ]
+ .filter(Boolean)
+ .join('\n');
+ const truncatedHint = result.truncated
+ ? '\n\n[Content truncated โ€” the document is longer than what fits here]'
+ : '';
+ return {
+ content: `${header}\n\n${result.content?.trim() || '(empty document)'}${truncatedHint}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `readDocument error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async editMessage(params: EditMessageParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.editMessage(params);
+ return {
+ content: `Message ${params.messageId} edited successfully`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `editMessage error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async deleteMessage(params: DeleteMessageParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.deleteMessage(params);
+ return {
+ content: `Message ${params.messageId} deleted successfully`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `deleteMessage error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async searchMessages(params: SearchMessagesParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.searchMessages(params);
+ const count = result.totalFound ?? result.messages?.length ?? 0;
+ const { images, total } = await this.attachImages(result.messages);
+ const formatted = formatMessageLines(result.messages, images);
+
+ return {
+ content: `Found ${count} messages matching "${params.query}" in ${params.platform}:${params.channelId}\n\n${formatted ?? '(no results)'}${describeAttachedImages(images, total)}`,
+ state: images.length > 0 ? { ...result, images } : result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `searchMessages error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Reactions ====================
+
+ async reactToMessage(params: ReactToMessageParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.reactToMessage(params);
+ return {
+ content: `Reacted with ${params.emoji} to message ${params.messageId}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `reactToMessage error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async getReactions(params: GetReactionsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.getReactions(params);
+ const formatted = result.reactions?.map((r) => `${r.emoji}: ${r.count}`).join(', ');
+
+ return {
+ content: `Reactions on message ${params.messageId}: ${formatted ?? '(none)'}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `getReactions error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Pin Management ====================
+
+ async pinMessage(params: PinMessageParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.pinMessage(params);
+ return {
+ content: `Message ${params.messageId} pinned in ${params.platform}:${params.channelId}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `pinMessage error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async unpinMessage(params: UnpinMessageParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.unpinMessage(params);
+ return {
+ content: `Message ${params.messageId} unpinned`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `unpinMessage error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async listPins(params: ListPinsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.listPins(params);
+ const count = result.messages?.length ?? 0;
+
+ return {
+ content: `${count} pinned messages in ${params.platform}:${params.channelId}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `listPins error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Channel Management ====================
+
+ async getChannelInfo(params: GetChannelInfoParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.getChannelInfo(params);
+ return {
+ content: `Channel: ${result.name ?? params.channelId} (type: ${result.type ?? 'unknown'}, members: ${result.memberCount ?? 'N/A'})`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `getChannelInfo error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async listChannels(params: ListChannelsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.listChannels(params);
+ const count = result.channels?.length ?? 0;
+ const formatted = result.channels?.map((c) => `#${c.name} (${c.id})`).join('\n');
+
+ return {
+ content: `${count} channels found on ${params.platform}\n\n${formatted ?? '(none)'}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `listChannels error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Member Information ====================
+
+ async getMemberInfo(params: GetMemberInfoParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.getMemberInfo(params);
+ return {
+ content: `Member: ${result.displayName ?? result.username ?? params.memberId} (status: ${result.status ?? 'unknown'})`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `getMemberInfo error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Thread Operations ====================
+
+ async createThread(params: CreateThreadParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.createThread(params);
+ return {
+ content: `Thread "${params.name}" created (threadId: ${result.threadId})`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `createThread error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async listThreads(params: ListThreadsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.listThreads(params);
+ const count = result.threads?.length ?? 0;
+ const formatted = result.threads?.map((t) => `${t.name} (${t.id})`).join('\n');
+
+ return {
+ content: `${count} threads in ${params.platform}:${params.channelId}\n\n${formatted ?? '(none)'}`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `listThreads error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ async replyToThread(params: ReplyToThreadParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.replyToThread(params);
+ const outcome = describeAttachmentOutcome(
+ params,
+ result,
+ `Reply sent to thread ${params.threadId} (messageId: ${result.messageId})`,
+ );
+ return { content: outcome.content, state: result, success: outcome.success };
+ } catch (e) {
+ return {
+ content: `replyToThread error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Platform-Specific: Polls ====================
+
+ async createPoll(params: CreatePollParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const result = await this.service.createPoll(params);
+ return {
+ content: `Poll "${params.question}" created in ${params.platform}:${params.channelId} (pollId: ${result.pollId})`,
+ state: result,
+ success: true,
+ };
+ } catch (e) {
+ return {
+ content: `createPoll error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+
+ // ==================== Direct Messaging ====================
+
+ async sendDirectMessage(params: SendDirectMessageParams): Promise<BuiltinServerRuntimeOutput> {
+ if (!this.service.sendDirectMessage) {
+ return {
+ content: `sendDirectMessage is not supported on ${params.platform}`,
+ success: false,
+ };
+ }
+ try {
+ const result = await this.service.sendDirectMessage(params);
+ const outcome = describeAttachmentOutcome(
+ params,
+ result,
+ `Direct message sent to user ${params.userId} on ${params.platform} (messageId: ${result.messageId})`,
+ );
+ return { content: outcome.content, state: result, success: outcome.success };
+ } catch (e) {
+ return {
+ content: `sendDirectMessage error: ${(e as Error).message}`,
+ success: false,
+ };
+ }
+ }
+}
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts b/packages/builtin-tool-message/src/ExecutionRuntime/index.ts
index 7348e235bf6..c36987bd537 100644
--- a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/index.ts
@@ -1,88 +1,3 @@
-import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
-
-import type {
- ConfiguredBotInfo,
- ConnectBotParams,
- ConnectBotState,
- CreateBotParams,
- CreateBotState,
- CreatePollParams,
- CreatePollState,
- CreateThreadParams,
- CreateThreadState,
- DeleteBotParams,
- DeleteBotState,
- DeleteMessageParams,
- DeleteMessageState,
- EditMessageParams,
- EditMessageState,
- GetBotDetailParams,
- GetBotDetailState,
- GetChannelInfoParams,
- GetChannelInfoState,
- GetMemberInfoParams,
- GetMemberInfoState,
- GetMessengerDetailParams,
- GetMessengerDetailState,
- GetReactionsParams,
- GetReactionsState,
- ListBotsParams,
- ListBotsState,
- ListChannelsParams,
- ListChannelsState,
- ListMessengerLinksParams,
- ListMessengerLinksState,
- ListMessengerPlatformsParams,
- ListMessengerPlatformsState,
- ListMessengersParams,
- ListMessengersState,
- ListPinsParams,
- ListPinsState,
- ListPlatformsParams,
- ListPlatformsState,
- ListThreadsParams,
- ListThreadsState,
- MessengerInfo,
- MessengerLinkInfo,
- MessengerPlatformInfo,
- MessengerPushPlatformType,
- MessengerPushStatus,
- MessengerPushWorkspaceOption,
- PinMessageParams,
- PinMessageState,
- PlatformInfo,
- ReactToMessageParams,
- ReactToMessageState,
- ReadDocumentParams,
- ReadDocumentState,
- ReadMessagesParams,
- ReadMessagesState,
- ReplyToThreadParams,
- ReplyToThreadState,
- SearchMessagesParams,
- SearchMessagesState,
- SendAttachmentsOutcome,
- SendDirectMessageParams,
- SendDirectMessageState,
- SendMessageAttachment,
- SendMessageParams,
- SendMessageState,
- SendMessengerPushParams,
- SendMessengerPushState,
- SetMessengerActiveAgentParams,
- SetMessengerActiveAgentState,
- ToggleBotParams,
- ToggleBotState,
- UninstallMessengerParams,
- UninstallMessengerState,
- UnlinkMessengerParams,
- UnlinkMessengerState,
- UnpinMessageParams,
- UnpinMessageState,
- UpdateBotParams,
- UpdateBotState,
-} from '../types';
-
// Re-export all param/state types so adapters can import from executionRuntime entry
export type {
ConfiguredBotInfo,
@@ -167,1080 +82,15 @@ export type {
UpdateBotState,
} from '../types';
export type { MessageItem } from '../types';
-
-/**
- * Service interface for message operations.
- * Each platform adapter must implement this interface for its supported operations.
- * Unsupported operations should throw an error indicating the platform limitation.
- */
-export interface MessageRuntimeService {
- createPoll: (params: CreatePollParams) => Promise<CreatePollState>;
- createThread: (params: CreateThreadParams) => Promise<CreateThreadState>;
- deleteMessage: (params: DeleteMessageParams) => Promise<DeleteMessageState>;
- editMessage: (params: EditMessageParams) => Promise<EditMessageState>;
- getChannelInfo: (params: GetChannelInfoParams) => Promise<GetChannelInfoState>;
- getMemberInfo: (params: GetMemberInfoParams) => Promise<GetMemberInfoState>;
- getReactions: (params: GetReactionsParams) => Promise<GetReactionsState>;
- listChannels: (params: ListChannelsParams) => Promise<ListChannelsState>;
- listPins: (params: ListPinsParams) => Promise<ListPinsState>;
- listThreads: (params: ListThreadsParams) => Promise<ListThreadsState>;
- pinMessage: (params: PinMessageParams) => Promise<PinMessageState>;
- reactToMessage: (params: ReactToMessageParams) => Promise<ReactToMessageState>;
- /**
- * Read a cloud document linked from the chat. Optional: only platforms
- * with a document API (Feishu/Lark docx) implement it; the runtime reports
- * "not supported" elsewhere and `messageCapabilities` trims the tool.
- */
- readDocument?: (params: ReadDocumentParams) => Promise<ReadDocumentState>;
- readMessages: (params: ReadMessagesParams) => Promise<ReadMessagesState>;
- replyToThread: (params: ReplyToThreadParams) => Promise<ReplyToThreadState>;
- searchMessages: (params: SearchMessagesParams) => Promise<SearchMessagesState>;
- sendDirectMessage?: (params: SendDirectMessageParams) => Promise<SendDirectMessageState>;
- sendMessage: (params: SendMessageParams) => Promise<SendMessageState>;
- unpinMessage: (params: UnpinMessageParams) => Promise<UnpinMessageState>;
-}
-
-/**
- * Interface for bot provider management operations.
- * Implemented by the server-side factory using AgentBotProviderModel + TRPC router logic.
- */
-export interface BotProviderQuery {
- connectBot: (botId: string) => Promise<{ status: string }>;
- createBot: (params: {
- agentId: string;
- applicationId: string;
- credentials: Record<string, string>;
- platform: string;
- settings?: Record<string, unknown>;
- }) => Promise<{ id: string; platform: string }>;
- deleteBot: (botId: string) => Promise<void>;
- getBotDetail: (botId: string) => Promise<GetBotDetailState | null>;
- // โ”€โ”€โ”€ System Bot messenger management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
- // All optional so callers can compose a minimal BotProviderQuery. When
- // absent, the executor returns a "feature not wired up" message.
- /** Single install detail, or null when not found. */
- getMessengerDetail?: (installationId: string) => Promise<GetMessengerDetailState | null>;
- listBots: () => Promise<ConfiguredBotInfo[]>;
- /** User's account links across platforms. */
- listMessengerLinks?: () => Promise<MessengerLinkInfo[]>;
- /** Platforms available for OAuth install. */
- listMessengerPlatforms?: () => Promise<MessengerPlatformInfo[]>;
- /** User's workspace-scoped System Bot installs. */
- listMessengers?: () => Promise<MessengerInfo[]>;
- listPlatforms: () => Promise<PlatformInfo[]>;
- /**
- * Proactively push a message to the caller's own linked messenger DM.
- * Mirrors `messenger.sendMessengerPush` โ€” the runtime resolves Slack
- * workspace ambiguity BEFORE calling this, so the handler only sees
- * deliverable requests.
- */
- sendMessengerPush?: (params: SendMessengerPushParams) => Promise<{
- remaining?: number;
- status: Exclude<MessengerPushStatus, 'needs_workspace_selection'>;
- }>;
- /** Change which agent receives inbound IM on a link. */
- setMessengerActiveAgent?: (params: SetMessengerActiveAgentParams) => Promise<void>;
- toggleBot: (botId: string, enabled: boolean) => Promise<void>;
- /** Revoke a workspace install (affects every user in that workspace). */
- uninstallMessenger?: (installationId: string) => Promise<void>;
- /** Remove the current user's account link only. */
- unlinkMessenger?: (params: UnlinkMessengerParams) => Promise<void>;
- updateBot: (
- botId: string,
- params: { credentials?: Record<string, string>; settings?: Record<string, unknown> },
- ) => Promise<void>;
-}
-
-export interface MessageExecutionRuntimeOptions {
- botProvider?: BotProviderQuery;
- service: MessageRuntimeService;
-}
-
-/**
- * Turn a send state's attachment outcome into what the model must read.
- *
- * Attachment failures are swallowed per item on purpose so the text leg still
- * ships โ€” but a `success: true` that says nothing about them is how the model
- * ends up telling the user "see attached" about a file that never arrived.
- * The failed attachments are named, with the reason, and the model is told
- * to fall back to a download link instead of claiming delivery.
- *
- * `success` stays true while SOMETHING reached the user (text, an embed, or
- * at least one attachment). When there was no text and every attachment failed, nothing was
- * delivered and the call is reported as failed.
- */
-const describeAttachmentOutcome = (
- params: { attachments?: SendMessageAttachment[]; content?: string; embeds?: unknown[] },
- state: SendAttachmentsOutcome,
- /** The success line, used verbatim while something reached the user. */
- sentLine: string,
-): { content: string; success: boolean } => {
- const failures = state.attachmentFailures ?? [];
- if (failures.length === 0) return { content: sentLine, success: true };
-
- const requested = params.attachments?.length ?? failures.length;
- const lines = failures.map(
- (f) =>
- `- "${f.name ?? '(unnamed)'}" (${f.type}): ${f.reason}${f.detail ? ` โ€” ${f.detail}` : ''}`,
- );
- // Embeds ride the text leg (Discord posts them even with empty content), so
- // a delivered embed counts as something reaching the user.
- const nothingDelivered =
- (state.attachmentsDelivered ?? 0) === 0 && !params.content?.trim() && !params.embeds?.length;
- const content = [
- // Never open with "Message sent" when nothing was: the lead line is what a
- // skimming model reads first.
- nothingDelivered ? 'Nothing was delivered.' : sentLine,
- `WARNING: ${failures.length} of ${requested} attachment(s) were NOT delivered:`,
- ...lines,
- nothingDelivered
- ? 'No text or embed was given and every attachment failed, so the user received nothing. Do not tell them a file was sent.'
- : 'Only the text (and any attachments not listed above) reached the user. Do NOT claim these files were attached โ€” tell the user which files could not be delivered and share a download link for each instead.',
- ].join('\n');
- return { content, success: !nothingDelivered };
-};
-
-/** Discord has no has_more flag: expose real IDs, not an inferred availability claim. */
-const describeDiscordPagination = (
- params: ReadMessagesParams,
- result: ReadMessagesState,
-): string => {
- const messages = result.messages;
- if (!Array.isArray(messages)) {
- return '\n\n[Pagination blocked: the response did not contain a message page. Do not claim history is complete.]';
- }
- if (messages.length === 0) {
- return '\n\n[No messages returned for this request. Stop this traversal of visible history; this does not prove the channel has no inaccessible history.]';
- }
-
- // Snowflakes exceed Number.MAX_SAFE_INTEGER. Do not depend on response ordering.
- if (messages.some((message) => typeof message.id !== 'string' || !/^\d+$/.test(message.id))) {
- return '\n\n[Pagination blocked: a message ID is not a decimal string. Do not invent a cursor.]';
- }
- const ids = messages.map((message) => message.id);
- const oldest = ids.reduce((a, b) => (BigInt(a) < BigInt(b) ? a : b));
- const newest = ids.reduce((a, b) => (BigInt(a) > BigInt(b) ? a : b));
- const direction = params.after !== undefined ? 'after' : 'before';
- const cursor = direction === 'after' ? newest : oldest;
- const previous = params[direction];
- if (
- previous !== undefined &&
- /^\d+$/.test(previous) &&
- (direction === 'after'
- ? BigInt(cursor) <= BigInt(previous)
- : BigInt(cursor) >= BigInt(previous))
- ) {
- return '\n\n[Pagination blocked: the cursor did not advance. Stop and investigate; do not claim history is complete.]';
- }
- const next = JSON.stringify({
- platform: params.platform,
- channelId: params.channelId,
- [direction]: cursor,
- ...(params.limit !== undefined ? { limit: params.limit } : {}),
- });
- return `\n\n[Discord pagination: oldest message ID: "${oldest}"; newest message ID: "${newest}". Within the 3โ€“5-call readMessages budget, to continue toward ${direction === 'before' ? 'older' : 'newer'} messages, call readMessages with ${next}. Use only one of before/after. More messages are unknown, regardless of page size; stop on a successful empty page, or stop and investigate errors/non-advancing cursors. For large-volume requests or tasks needing more calls, use the lobehub skill to batch read via the CLI (lh bot message read) outside the conversation context instead of repeatedly calling readMessages.]`;
-};
-
-export class MessageExecutionRuntime {
- private botProvider?: BotProviderQuery;
- private service: MessageRuntimeService;
-
- constructor(options: MessageExecutionRuntimeOptions) {
- this.service = options.service;
- this.botProvider = options.botProvider;
- }
-
- // ==================== Core Message Operations ====================
-
- async sendMessage(params: SendMessageParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.sendMessage(params);
- const outcome = describeAttachmentOutcome(
- params,
- result,
- `Message sent to ${params.platform}:${params.channelId} (messageId: ${result.messageId})`,
- );
- return { content: outcome.content, state: result, success: outcome.success };
- } catch (e) {
- return {
- content: `sendMessage error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async readMessages(params: ReadMessagesParams): Promise<BuiltinServerRuntimeOutput> {
- if (params.platform === 'discord') {
- if (params.before !== undefined && params.after !== undefined) {
- return {
- content: 'readMessages error: Discord before and after are mutually exclusive.',
- success: false,
- };
- }
- for (const direction of ['before', 'after'] as const) {
- const cursor = params[direction];
- if (cursor !== undefined && (typeof cursor !== 'string' || !/^\d+$/.test(cursor))) {
- return {
- content: `readMessages error: Discord ${direction} must be a non-empty decimal message ID string. Omit it when not needed.`,
- success: false,
- };
- }
- }
- }
- try {
- const result = await this.service.readMessages(params);
- const count = result.messages?.length ?? 0;
- const formatted = result.messages
- ?.map(
- (m) =>
- `[${m.timestamp}] [messageId: ${JSON.stringify(m.id)}] ${m.author.name}: ${m.content}`,
- )
- .join('\n');
-
- const paginationHint =
- params.platform === 'discord'
- ? describeDiscordPagination(params, result)
- : result.hasMore && result.nextCursor
- ? `\n\n[More messages available โ€” pass cursor: "${result.nextCursor}" to fetch next page]`
- : '';
-
- return {
- content: `Fetched ${count} messages from ${params.platform}:${params.channelId}${params.platform === 'discord' ? paginationHint : ''}\n\n${formatted ?? '(no messages)'}${params.platform === 'discord' ? '' : paginationHint}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `readMessages error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async readDocument(params: ReadDocumentParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.service.readDocument) {
- return {
- content: `readDocument is not supported on ${params.platform}`,
- success: false,
- };
- }
- if (!params.url && !params.documentId) {
- return {
- content: 'readDocument error: pass the document `url` (preferred) or its `documentId`',
- success: false,
- };
- }
- try {
- const result = await this.service.readDocument(params);
- const header = [
- `Document${result.title ? `: ${result.title}` : ''}`,
- result.url ? `URL: ${result.url}` : undefined,
- result.documentId
- ? `ID: ${result.documentId}${result.kind ? ` (${result.kind})` : ''}`
- : undefined,
- ]
- .filter(Boolean)
- .join('\n');
- const truncatedHint = result.truncated
- ? '\n\n[Content truncated โ€” the document is longer than what fits here]'
- : '';
- return {
- content: `${header}\n\n${result.content?.trim() || '(empty document)'}${truncatedHint}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `readDocument error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async editMessage(params: EditMessageParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.editMessage(params);
- return {
- content: `Message ${params.messageId} edited successfully`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `editMessage error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async deleteMessage(params: DeleteMessageParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.deleteMessage(params);
- return {
- content: `Message ${params.messageId} deleted successfully`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `deleteMessage error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async searchMessages(params: SearchMessagesParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.searchMessages(params);
- const count = result.totalFound ?? result.messages?.length ?? 0;
- const formatted = result.messages
- ?.map(
- (m) =>
- `[${m.timestamp}] [messageId: ${JSON.stringify(m.id)}] ${m.author.name}: ${m.content}`,
- )
- .join('\n');
-
- return {
- content: `Found ${count} messages matching "${params.query}" in ${params.platform}:${params.channelId}\n\n${formatted ?? '(no results)'}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `searchMessages error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Reactions ====================
-
- async reactToMessage(params: ReactToMessageParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.reactToMessage(params);
- return {
- content: `Reacted with ${params.emoji} to message ${params.messageId}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `reactToMessage error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async getReactions(params: GetReactionsParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.getReactions(params);
- const formatted = result.reactions?.map((r) => `${r.emoji}: ${r.count}`).join(', ');
-
- return {
- content: `Reactions on message ${params.messageId}: ${formatted ?? '(none)'}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `getReactions error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Pin Management ====================
-
- async pinMessage(params: PinMessageParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.pinMessage(params);
- return {
- content: `Message ${params.messageId} pinned in ${params.platform}:${params.channelId}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `pinMessage error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async unpinMessage(params: UnpinMessageParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.unpinMessage(params);
- return {
- content: `Message ${params.messageId} unpinned`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `unpinMessage error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async listPins(params: ListPinsParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.listPins(params);
- const count = result.messages?.length ?? 0;
-
- return {
- content: `${count} pinned messages in ${params.platform}:${params.channelId}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `listPins error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Channel Management ====================
-
- async getChannelInfo(params: GetChannelInfoParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.getChannelInfo(params);
- return {
- content: `Channel: ${result.name ?? params.channelId} (type: ${result.type ?? 'unknown'}, members: ${result.memberCount ?? 'N/A'})`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `getChannelInfo error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async listChannels(params: ListChannelsParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.listChannels(params);
- const count = result.channels?.length ?? 0;
- const formatted = result.channels?.map((c) => `#${c.name} (${c.id})`).join('\n');
-
- return {
- content: `${count} channels found on ${params.platform}\n\n${formatted ?? '(none)'}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `listChannels error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Member Information ====================
-
- async getMemberInfo(params: GetMemberInfoParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.getMemberInfo(params);
- return {
- content: `Member: ${result.displayName ?? result.username ?? params.memberId} (status: ${result.status ?? 'unknown'})`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `getMemberInfo error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Thread Operations ====================
-
- async createThread(params: CreateThreadParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.createThread(params);
- return {
- content: `Thread "${params.name}" created (threadId: ${result.threadId})`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `createThread error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async listThreads(params: ListThreadsParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.listThreads(params);
- const count = result.threads?.length ?? 0;
- const formatted = result.threads?.map((t) => `${t.name} (${t.id})`).join('\n');
-
- return {
- content: `${count} threads in ${params.platform}:${params.channelId}\n\n${formatted ?? '(none)'}`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `listThreads error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async replyToThread(params: ReplyToThreadParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.replyToThread(params);
- const outcome = describeAttachmentOutcome(
- params,
- result,
- `Reply sent to thread ${params.threadId} (messageId: ${result.messageId})`,
- );
- return { content: outcome.content, state: result, success: outcome.success };
- } catch (e) {
- return {
- content: `replyToThread error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Platform-Specific: Polls ====================
-
- async createPoll(params: CreatePollParams): Promise<BuiltinServerRuntimeOutput> {
- try {
- const result = await this.service.createPoll(params);
- return {
- content: `Poll "${params.question}" created in ${params.platform}:${params.channelId} (pollId: ${result.pollId})`,
- state: result,
- success: true,
- };
- } catch (e) {
- return {
- content: `createPoll error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Direct Messaging ====================
-
- async sendDirectMessage(params: SendDirectMessageParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.service.sendDirectMessage) {
- return {
- content: `sendDirectMessage is not supported on ${params.platform}`,
- success: false,
- };
- }
- try {
- const result = await this.service.sendDirectMessage(params);
- const outcome = describeAttachmentOutcome(
- params,
- result,
- `Direct message sent to user ${params.userId} on ${params.platform} (messageId: ${result.messageId})`,
- );
- return { content: outcome.content, state: result, success: outcome.success };
- } catch (e) {
- return {
- content: `sendDirectMessage error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- // ==================== Bot Management ====================
-
- async listPlatforms(_params: ListPlatformsParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return { content: 'Bot provider is not available.', success: false };
- }
- try {
- const platforms = await this.botProvider.listPlatforms();
- const formatted = platforms
- .map((p) => {
- const reqFields = p.credentialFields
- .filter((f) => f.required)
- .map((f) => f.key)
- .join(', ');
- return `- **${p.name}** (${p.id})${reqFields ? ` โ€” requires: ${reqFields}` : ''}`;
- })
- .join('\n');
-
- return {
- content: `${platforms.length} supported platform(s):\n${formatted}`,
- state: { platforms } satisfies ListPlatformsState,
- success: true,
- };
- } catch (e) {
- return { content: `listPlatforms error: ${(e as Error).message}`, success: false };
- }
- }
-
- async listBots(_params: ListBotsParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return {
- content: 'Bot provider query is not available in this context.',
- success: false,
- };
- }
-
- try {
- const bots = await this.botProvider.listBots();
- const formatted = bots
- .map((b) => {
- const parts = [
- `platform: ${b.platform}`,
- `botId: ${b.id}`,
- `enabled: ${b.enabled}`,
- `status: ${b.runtimeStatus ?? 'unknown'}`,
- ];
- if (b.serverId) {
- parts.push(`serverId: ${b.serverId}`);
- }
- if (b.userId) {
- parts.push(`userId: ${b.userId}`);
- }
- return `- ${b.platform} (${parts.join(', ')})`;
- })
- .join('\n');
-
- return {
- content:
- bots.length > 0
- ? `${bots.length} configured bot(s):\n${formatted}`
- : 'No bots configured for this agent. Set up a bot integration first.',
- state: { bots } satisfies ListBotsState,
- success: true,
- };
- } catch (e) {
- return {
- content: `listBots error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async getBotDetail(params: GetBotDetailParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return { content: 'Bot provider is not available.', success: false };
- }
- try {
- const bot = await this.botProvider.getBotDetail(params.botId);
- if (!bot) {
- return { content: `Bot not found: ${params.botId}`, success: false };
- }
- return {
- content: `Bot ${bot.id}:\n- Platform: ${bot.platform}\n- App ID: ${bot.applicationId}\n- Enabled: ${bot.enabled}\n- Status: ${bot.runtimeStatus ?? 'unknown'}${bot.settings ? `\n- Settings: ${JSON.stringify(bot.settings)}` : ''}`,
- state: bot satisfies GetBotDetailState,
- success: true,
- };
- } catch (e) {
- return { content: `getBotDetail error: ${(e as Error).message}`, success: false };
- }
- }
-
- async createBot(params: CreateBotParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return { content: 'Bot provider is not available.', success: false };
- }
- try {
- const result = await this.botProvider.createBot(params);
- return {
- content: `Created ${result.platform} bot (id: ${result.id})`,
- state: result satisfies CreateBotState,
- success: true,
- };
- } catch (e) {
- return { content: `createBot error: ${(e as Error).message}`, success: false };
- }
- }
-
- async updateBot(params: UpdateBotParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return { content: 'Bot provider is not available.', success: false };
- }
- try {
- await this.botProvider.updateBot(params.botId, {
- credentials: params.credentials,
- settings: params.settings,
- });
- return {
- content: `Updated bot ${params.botId}`,
- state: { success: true } satisfies UpdateBotState,
- success: true,
- };
- } catch (e) {
- return { content: `updateBot error: ${(e as Error).message}`, success: false };
- }
- }
-
- async deleteBot(params: DeleteBotParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return { content: 'Bot provider is not available.', success: false };
- }
- try {
- await this.botProvider.deleteBot(params.botId);
- return {
- content: `Deleted bot ${params.botId}`,
- state: { success: true } satisfies DeleteBotState,
- success: true,
- };
- } catch (e) {
- return { content: `deleteBot error: ${(e as Error).message}`, success: false };
- }
- }
-
- async toggleBot(params: ToggleBotParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return { content: 'Bot provider is not available.', success: false };
- }
- try {
- await this.botProvider.toggleBot(params.botId, params.enabled);
- return {
- content: `Bot ${params.botId} ${params.enabled ? 'enabled' : 'disabled'}`,
- state: { enabled: params.enabled, success: true } satisfies ToggleBotState,
- success: true,
- };
- } catch (e) {
- return { content: `toggleBot error: ${(e as Error).message}`, success: false };
- }
- }
-
- async connectBot(params: ConnectBotParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider) {
- return { content: 'Bot provider is not available.', success: false };
- }
- try {
- const result = await this.botProvider.connectBot(params.botId);
- return {
- content: `Bot connection initiated (status: ${result.status})`,
- state: result satisfies ConnectBotState,
- success: true,
- };
- } catch (e) {
- return { content: `connectBot error: ${(e as Error).message}`, success: false };
- }
- }
-
- // ==================== System Bot Messenger Management ====================
-
- async listMessengers(_params: ListMessengersParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.listMessengers) {
- return {
- content: 'System Bot messenger discovery is not available in this context.',
- success: false,
- };
- }
- try {
- const installations = await this.botProvider.listMessengers();
- if (installations.length === 0) {
- return {
- content:
- 'No System Bot connections found. Tell the user to connect one via Settings โ†’ Messenger; `listMessengerPlatforms` shows what platforms are available.',
- state: { installations } satisfies ListMessengersState,
- success: true,
- };
- }
- const lines = installations.map((i) => {
- const parts = [`installationId: ${i.id}`, `platform: ${i.platform}`];
- if (i.tenantName) parts.push(`tenant: ${i.tenantName}`);
- else if (i.tenantId) parts.push(`tenantId: ${i.tenantId}`);
- if (i.installedAt) {
- const at = i.installedAt instanceof Date ? i.installedAt.toISOString() : i.installedAt;
- parts.push(`installedAt: ${at}`);
- }
- return `- ${parts.join(', ')}`;
- });
- return {
- content: `${installations.length} System Bot connection(s):\n${lines.join('\n')}`,
- state: { installations } satisfies ListMessengersState,
- success: true,
- };
- } catch (e) {
- return { content: `listMessengers error: ${(e as Error).message}`, success: false };
- }
- }
-
- async getMessengerDetail(params: GetMessengerDetailParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.getMessengerDetail) {
- return { content: 'getMessengerDetail is not available.', success: false };
- }
- try {
- const install = await this.botProvider.getMessengerDetail(params.installationId);
- if (!install) {
- return {
- content: `Messenger installation not found: ${params.installationId}`,
- success: false,
- };
- }
- const lines = [
- `installationId: ${install.id}`,
- `platform: ${install.platform}`,
- `tenantId: ${install.tenantId || '(global)'}`,
- ];
- if (install.tenantName) lines.push(`tenant: ${install.tenantName}`);
- if (install.applicationId) lines.push(`applicationId: ${install.applicationId}`);
- if (install.scope) lines.push(`scope: ${install.scope}`);
- if (install.installedAt) {
- const at =
- install.installedAt instanceof Date
- ? install.installedAt.toISOString()
- : install.installedAt;
- lines.push(`installedAt: ${at}`);
- }
- lines.push(`revoked: ${install.revokedAt ? 'yes' : 'no'}`);
- return {
- content: lines.join('\n'),
- state: install satisfies GetMessengerDetailState,
- success: true,
- };
- } catch (e) {
- return { content: `getMessengerDetail error: ${(e as Error).message}`, success: false };
- }
- }
-
- async uninstallMessenger(params: UninstallMessengerParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.uninstallMessenger) {
- return { content: 'uninstallMessenger is not available.', success: false };
- }
- try {
- await this.botProvider.uninstallMessenger(params.installationId);
- return {
- content: `System Bot connection ${params.installationId} disconnected.`,
- state: { success: true } satisfies UninstallMessengerState,
- success: true,
- };
- } catch (e) {
- return { content: `uninstallMessenger error: ${(e as Error).message}`, success: false };
- }
- }
-
- async listMessengerPlatforms(
- _params: ListMessengerPlatformsParams,
- ): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.listMessengerPlatforms) {
- return { content: 'listMessengerPlatforms is not available.', success: false };
- }
- try {
- const platforms = await this.botProvider.listMessengerPlatforms();
- if (platforms.length === 0) {
- return {
- content:
- 'No System Bot platforms are configured on this deployment. Ask the operator to enable at least one platform under Messenger configuration.',
- state: { platforms } satisfies ListMessengerPlatformsState,
- success: true,
- };
- }
- const lines = platforms.map((p) => {
- const parts = [p.id];
- if (p.name && p.name !== p.id) parts.push(`(${p.name})`);
- if (p.appId) parts.push(`appId: ${p.appId}`);
- if (p.botUsername) parts.push(`botUsername: ${p.botUsername}`);
- return `- ${parts.join(' ')}`;
- });
- return {
- content: `${platforms.length} platform(s) available for System Bot install:\n${lines.join('\n')}\n\nInstalls are initiated via Settings โ†’ Messenger (OAuth requires a browser).`,
- state: { platforms } satisfies ListMessengerPlatformsState,
- success: true,
- };
- } catch (e) {
- return {
- content: `listMessengerPlatforms error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async listMessengerLinks(_params: ListMessengerLinksParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.listMessengerLinks) {
- return { content: 'listMessengerLinks is not available.', success: false };
- }
- try {
- const links = await this.botProvider.listMessengerLinks();
- if (links.length === 0) {
- return {
- content:
- 'No System Bot account links. The user has not completed verify-im on any platform yet.',
- state: { links } satisfies ListMessengerLinksState,
- success: true,
- };
- }
- const lines = links.map((l) => {
- const parts = [`platform: ${l.platform}`];
- if (l.tenantId) parts.push(`tenantId: ${l.tenantId}`);
- parts.push(`activeAgentId: ${l.activeAgentId ?? '(none)'}`);
- if (l.platformUsername) parts.push(`platformUser: ${l.platformUsername}`);
- return `- ${parts.join(', ')}`;
- });
- return {
- content: `${links.length} System Bot link(s):\n${lines.join('\n')}`,
- state: { links } satisfies ListMessengerLinksState,
- success: true,
- };
- } catch (e) {
- return { content: `listMessengerLinks error: ${(e as Error).message}`, success: false };
- }
- }
-
- async setMessengerActiveAgent(
- params: SetMessengerActiveAgentParams,
- ): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.setMessengerActiveAgent) {
- return { content: 'setMessengerActiveAgent is not available.', success: false };
- }
- try {
- await this.botProvider.setMessengerActiveAgent(params);
- const target = params.agentId === null ? 'cleared' : `set to agent ${params.agentId}`;
- const scope = params.tenantId ? ` (tenant ${params.tenantId})` : '';
- return {
- content: `Active agent for ${params.platform}${scope} ${target}.`,
- state: { success: true } satisfies SetMessengerActiveAgentState,
- success: true,
- };
- } catch (e) {
- return {
- content: `setMessengerActiveAgent error: ${(e as Error).message}`,
- success: false,
- };
- }
- }
-
- async unlinkMessenger(params: UnlinkMessengerParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.unlinkMessenger) {
- return { content: 'unlinkMessenger is not available.', success: false };
- }
- try {
- await this.botProvider.unlinkMessenger(params);
- const scope = params.tenantId ? ` (tenant ${params.tenantId})` : '';
- return {
- content: `Unlinked your account from ${params.platform}${scope}. The workspace install is unaffected.`,
- state: { success: true } satisfies UnlinkMessengerState,
- success: true,
- };
- } catch (e) {
- return { content: `unlinkMessenger error: ${(e as Error).message}`, success: false };
- }
- }
-
- // ==================== Proactive Messenger Push ====================
-
- /**
- * Resolve the Slack workspace a push should target when the caller didn't
- * pass `tenantId`. Returns the single linked tenantId, or the candidate
- * list when the choice is ambiguous (the user linked several workspaces).
- */
- private async resolveSlackPushTenant(): Promise<
- { tenantId?: string } | { workspaces: MessengerPushWorkspaceOption[] }
- > {
- const links = (await this.botProvider!.listMessengerLinks?.()) ?? [];
- const slackTenantIds = links
- .filter((link) => link.platform === 'slack' && link.tenantId)
- .map((link) => link.tenantId!);
- if (slackTenantIds.length <= 1) return { tenantId: slackTenantIds[0] };
-
- // Enrich with workspace names so the agent can present readable choices;
- // installs may be missing (installed by a teammate) โ€” fall back to the id.
- const installs = await this.botProvider!.listMessengers?.().catch(() => []);
- const nameByTenant = new Map(
- (installs ?? [])
- .filter((install) => install.platform === 'slack')
- .map((install) => [install.tenantId, install.tenantName]),
- );
- return {
- workspaces: slackTenantIds.map((tenantId) => ({
- tenantId,
- tenantName: nameByTenant.get(tenantId) || undefined,
- })),
- };
- }
-
- async sendMessengerPush(params: SendMessengerPushParams): Promise<BuiltinServerRuntimeOutput> {
- if (!this.botProvider?.sendMessengerPush) {
- return { content: 'sendMessengerPush is not available.', success: false };
- }
- const platform = params.platform as MessengerPushPlatformType;
- try {
- let tenantId = params.tenantId;
-
- // Slack links can span several workspaces โ€” never pick one silently.
- if (platform === 'slack' && tenantId === undefined) {
- const resolved = await this.resolveSlackPushTenant();
- if ('workspaces' in resolved) {
- const lines = resolved.workspaces.map(
- (w) => `- ${w.tenantName ?? w.tenantId} (tenantId: ${w.tenantId})`,
- );
- return {
- content:
- `The user's Slack account is linked to ${resolved.workspaces.length} workspaces:\n${lines.join('\n')}\n\n` +
- 'Ask the user which workspace to push to, then call sendMessengerPush again with that tenantId.',
- state: {
- platform,
- status: 'needs_workspace_selection',
- workspaces: resolved.workspaces,
- } satisfies SendMessengerPushState,
- success: true,
- };
- }
- tenantId = resolved.tenantId;
- }
-
- const result = await this.botProvider.sendMessengerPush({
- content: params.content,
- platform,
- tenantId,
- });
- const state: SendMessengerPushState = {
- platform,
- remaining: result.remaining,
- status: result.status,
- tenantId,
- };
-
- switch (result.status) {
- case 'sent': {
- const quota =
- platform === 'wechat' && result.remaining !== undefined
- ? ` (${result.remaining} sends left in the current WeChat window)`
- : '';
- return {
- content: `Message pushed to the user's ${platform} DM${quota}.`,
- state,
- success: true,
- };
- }
- case 'queued': {
- return {
- // Queued is a success: delivery is deferred, not dropped. The
- // agent must relay the "message the bot first" step to the user.
- content:
- 'The WeChat send window is closed or its quota is exhausted, so the message was queued. ' +
- 'Tell the user to send any message to the LobeHub WeChat bot first โ€” the queued push will be delivered right after their message opens a new window.',
- state,
- success: true,
- };
- }
- case 'unlinked': {
- return {
- content: `The user has no linked ${platform} account for the LobeHub System Bot. Ask them to open Settings โ†’ Messenger and connect ${platform} first.`,
- state,
- success: false,
- };
- }
- default: {
- return {
- content: `Proactive push to ${platform} is currently unavailable โ€” the platform is not configured on this deployment or delivery failed. Do not retry immediately; surface this to the user.`,
- state,
- success: false,
- };
- }
- }
- } catch (e) {
- return { content: `sendMessengerPush error: ${(e as Error).message}`, success: false };
- }
- }
-}
+export { MessageExecutionRuntime } from './botManagement';
+export { ChannelMessageRuntime } from './channelMessages';
+export type {
+ MessageImageCandidate,
+ MessageImageResolver,
+ MessageToolImage,
+} from './messageImages';
+export type {
+ BotProviderQuery,
+ MessageExecutionRuntimeOptions,
+ MessageRuntimeService,
+} from './types';
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/messageImages.test.ts b/packages/builtin-tool-message/src/ExecutionRuntime/messageImages.test.ts
new file mode 100644
index 00000000000..97ce0bfa410
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/messageImages.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import type { MessageItem } from '../types';
+import { MessageExecutionRuntime } from './index';
+import { collectImageCandidates, imageMediaType, MAX_MESSAGE_IMAGES } from './messageImages';
+
+const message = (id: string, timestamp: string, extra: Partial<MessageItem> = {}): MessageItem => ({
+ author: { id: 'u1', name: 'none01161' },
+ content: '',
+ id,
+ timestamp,
+ ...extra,
+});
+
+const screenshot = {
+ contentType: 'image/png',
+ name: 'image.png',
+ size: 1000,
+ url: 'https://cdn.discordapp.com/attachments/1/2/image.png?ex=1',
+};
+
+// Regression: a screenshot posted on its own read as `none01161: ` with nothing after it, so
+// the woken bot answered that it could not see any screenshot.
+const page = [
+ message('1564834667952087122', '2026-10-28T02:54:18.062Z', { content: '่ฟ™ไธช่ƒฝไฟฎไธ€ไธ‹ๅ—๏ผŒๆกŒ้ข็ซฏ' }),
+ message('1564834596426747917', '2026-10-28T02:54:01.009Z', {
+ content: '่ฟ™ไธชๆŒ‚็€็š„้กต้ขๅฅฝๅƒ่ฟ‡ไธ€ไผšๅฐฑๅ˜lobeaiไบ†',
+ }),
+ message('1564834535558881420', '2026-10-28T02:53:46.497Z', { attachments: [screenshot] }),
+];
+
+const runtimeWith = (resolveImages?: ReturnType<typeof vi.fn>) =>
+ new MessageExecutionRuntime({
+ resolveImages: resolveImages as any,
+ service: { readMessages: vi.fn().mockResolvedValue({ messages: page }) } as any,
+ });
+
+const read = (runtime: MessageExecutionRuntime) =>
+ runtime.readMessages({ channelId: '1149011097802788864', platform: 'discord' });
+
+describe('readMessages image attachments', () => {
+ it('attaches stored images to the result so a vision model can see them', async () => {
+ const resolveImages = vi.fn(async (candidates: any[]) =>
+ candidates.map((c) => ({ ...c, fileId: 'file_1', url: 'https://app/f/file_1' })),
+ );
+
+ const output = await read(runtimeWith(resolveImages));
+
+ expect(resolveImages).toHaveBeenCalledWith([
+ {
+ mediaType: 'image/png',
+ messageId: '1564834535558881420',
+ name: 'image.png',
+ size: 1000,
+ url: screenshot.url,
+ },
+ ]);
+ expect(output.state.images).toEqual([
+ {
+ fileId: 'file_1',
+ mediaType: 'image/png',
+ messageId: '1564834535558881420',
+ name: 'image.png',
+ size: 1000,
+ url: 'https://app/f/file_1',
+ },
+ ]);
+ expect(output.content).toContain('none01161: [image #1 attached to this result: image.png]');
+ expect(output.content).toContain('attached to this result as image #1.');
+ });
+
+ it('still names the image when it cannot be stored, and tells the model it cannot see it', async () => {
+ const output = await read(runtimeWith(vi.fn().mockRejectedValue(new Error('S3 down'))));
+
+ expect(output.success).toBe(true);
+ expect(output.state.images).toBeUndefined();
+ expect(output.content).toContain('none01161: [attachment: image.png, image/png]');
+ expect(output.content).toContain('could not be loaded, so you cannot see them');
+ });
+
+ it('names the image in text when no store is wired', async () => {
+ const output = await read(runtimeWith());
+
+ expect(output.state.images).toBeUndefined();
+ expect(output.content).toContain('[attachment: image.png, image/png]');
+ });
+
+ it('applies to searchMessages too', async () => {
+ const runtime = new MessageExecutionRuntime({
+ resolveImages: vi.fn(async (candidates: any[]) =>
+ candidates.map((c) => ({ ...c, url: 'https://app/f/file_2' })),
+ ) as any,
+ service: { searchMessages: vi.fn().mockResolvedValue({ messages: page }) } as any,
+ });
+
+ const output = await runtime.searchMessages({
+ channelId: 'c1',
+ platform: 'discord',
+ query: 'lobeai',
+ });
+
+ expect(output.state.images).toHaveLength(1);
+ });
+});
+
+describe('collectImageCandidates', () => {
+ it('keeps the newest images up to the cap and reports the total', () => {
+ const many = Array.from({ length: MAX_MESSAGE_IMAGES + 2 }, (_, i) =>
+ message(`m${i}`, new Date(Date.UTC(2026, 0, 1, 0, i)).toISOString(), {
+ attachments: [{ ...screenshot, name: `${i}.png` }],
+ }),
+ );
+
+ const { candidates, total } = collectImageCandidates(many);
+
+ expect(total).toBe(MAX_MESSAGE_IMAGES + 2);
+ expect(candidates.map((c) => c.name)).toEqual(['5.png', '4.png', '3.png', '2.png']);
+ });
+
+ it('skips files a vision model cannot read', () => {
+ expect(imageMediaType({ contentType: 'image/svg+xml', name: 'a.svg', url: 'x' })).toBe(
+ undefined,
+ );
+ expect(imageMediaType({ contentType: 'application/pdf', name: 'a.pdf', url: 'x' })).toBe(
+ undefined,
+ );
+ expect(imageMediaType({ name: 'shot.JPG', url: 'x' })).toBe('image/jpeg');
+ });
+});
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/messageImages.ts b/packages/builtin-tool-message/src/ExecutionRuntime/messageImages.ts
new file mode 100644
index 00000000000..d717a98eb70
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/messageImages.ts
@@ -0,0 +1,126 @@
+import type { MessageItem, MessageItemAttachment } from '../types';
+
+/**
+ * At most this many images ride on one readMessages / searchMessages result. Each one costs
+ * vision tokens on every later turn until the result goes stale, so only the newest are kept.
+ */
+export const MAX_MESSAGE_IMAGES = 4;
+
+/** Formats a vision model reads natively; anything else stays a text marker. */
+const IMAGE_MEDIA_TYPES = new Set(['image/gif', 'image/jpeg', 'image/png', 'image/webp']);
+
+const MEDIA_TYPE_BY_EXT: Record<string, string> = {
+ gif: 'image/gif',
+ jpeg: 'image/jpeg',
+ jpg: 'image/jpeg',
+ png: 'image/png',
+ webp: 'image/webp',
+};
+
+/** An image attachment the model may be shown, newest message first. */
+export interface MessageImageCandidate {
+ mediaType: string;
+ messageId: string;
+ name: string;
+ size?: number;
+ url: string;
+}
+
+/** A candidate stored where the model provider can fetch it (`pluginState.images` entry). */
+export interface MessageToolImage {
+ fileId?: string;
+ mediaType: string;
+ messageId: string;
+ name: string;
+ url: string;
+}
+
+/**
+ * Turns platform image URLs into URLs a model provider can fetch for as long as the topic lives.
+ * Platform CDN links expire (Discord signs them for about a day), so the server copies the bytes
+ * into file storage. Candidates it cannot or will not store are left out of the result.
+ */
+export type MessageImageResolver = (
+ candidates: MessageImageCandidate[],
+) => Promise<MessageToolImage[]>;
+
+/** The image media type of an attachment, or undefined when it is not a readable image. */
+export const imageMediaType = (attachment: MessageItemAttachment): string | undefined => {
+ const declared = attachment.contentType?.split(';')[0].trim().toLowerCase();
+ if (declared) return IMAGE_MEDIA_TYPES.has(declared) ? declared : undefined;
+
+ const ext = attachment.name.split('.').pop()?.toLowerCase();
+ return ext ? MEDIA_TYPE_BY_EXT[ext] : undefined;
+};
+
+const timeOf = (message: MessageItem) => {
+ const time = Date.parse(message.timestamp);
+ return Number.isFinite(time) ? time : 0;
+};
+
+/**
+ * Image attachments across a page of messages, newest message first and capped. Returns the
+ * total too, so the result can say how many were left out.
+ */
+export const collectImageCandidates = (
+ messages: MessageItem[] | undefined,
+ limit = MAX_MESSAGE_IMAGES,
+): { candidates: MessageImageCandidate[]; total: number } => {
+ const all = [...(messages ?? [])]
+ .sort((a, b) => timeOf(b) - timeOf(a))
+ .flatMap((message) =>
+ (message.attachments ?? []).flatMap((attachment) => {
+ const mediaType = imageMediaType(attachment);
+ if (!mediaType || !attachment.url) return [];
+ return [
+ {
+ mediaType,
+ messageId: message.id,
+ name: attachment.name,
+ size: attachment.size,
+ url: attachment.url,
+ },
+ ];
+ }),
+ );
+
+ return { candidates: all.slice(0, limit), total: all.length };
+};
+
+/**
+ * One message per line. Attachments are named after the text, so an image-only message no
+ * longer reads as an empty line; an image that rides on this result says which one it is.
+ */
+export const formatMessageLines = (
+ messages: MessageItem[] | undefined,
+ images: MessageToolImage[] = [],
+): string | undefined => {
+ if (!messages) return undefined;
+
+ return messages
+ .map((m) => {
+ const attachments = (m.attachments ?? []).map((attachment) => {
+ const index = images.findIndex(
+ (image) => image.messageId === m.id && image.name === attachment.name,
+ );
+ if (index >= 0) return `[image #${index + 1} attached to this result: ${attachment.name}]`;
+ const type = attachment.contentType ? `, ${attachment.contentType}` : '';
+ return `[attachment: ${attachment.name}${type}]`;
+ });
+ const body = [m.content, ...attachments].filter(Boolean).join(' ');
+
+ return `[${m.timestamp}] [messageId: ${JSON.stringify(m.id)}] ${m.author.name}: ${body}`;
+ })
+ .join('\n');
+};
+
+/** Footer telling the model what it can see and what was left out. */
+export const describeAttachedImages = (images: MessageToolImage[], total: number): string => {
+ if (total === 0) return '';
+ if (images.length === 0) {
+ return `\n\n[${total} image attachment(s) in these messages could not be loaded, so you cannot see them. Do not describe them; ask the user what they show if it matters.]`;
+ }
+ const skipped = total - images.length;
+ const range = images.length === 1 ? 'image #1' : `images #1โ€“#${images.length}, newest first`;
+ return `\n\n[${images.length} image(s) from these messages are attached to this result as ${range}.${skipped > 0 ? ` ${skipped} older image(s) are not attached.` : ''}]`;
+};
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/pagination.ts b/packages/builtin-tool-message/src/ExecutionRuntime/pagination.ts
new file mode 100644
index 00000000000..622a8292429
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/pagination.ts
@@ -0,0 +1,42 @@
+import type { ReadMessagesParams, ReadMessagesState } from '../types';
+
+/** Discord has no has_more flag: expose real IDs, not an inferred availability claim. */
+export const describeDiscordPagination = (
+ params: ReadMessagesParams,
+ result: ReadMessagesState,
+): string => {
+ const messages = result.messages;
+ if (!Array.isArray(messages)) {
+ return '\n\n[Pagination blocked: the response did not contain a message page. Do not claim history is complete.]';
+ }
+ if (messages.length === 0) {
+ return '\n\n[No messages returned for this request. Stop this traversal of visible history; this does not prove the channel has no inaccessible history.]';
+ }
+
+ // Snowflakes exceed Number.MAX_SAFE_INTEGER. Do not depend on response ordering.
+ if (messages.some((message) => typeof message.id !== 'string' || !/^\d+$/.test(message.id))) {
+ return '\n\n[Pagination blocked: a message ID is not a decimal string. Do not invent a cursor.]';
+ }
+ const ids = messages.map((message) => message.id);
+ const oldest = ids.reduce((a, b) => (BigInt(a) < BigInt(b) ? a : b));
+ const newest = ids.reduce((a, b) => (BigInt(a) > BigInt(b) ? a : b));
+ const direction = params.after !== undefined ? 'after' : 'before';
+ const cursor = direction === 'after' ? newest : oldest;
+ const previous = params[direction];
+ if (
+ previous !== undefined &&
+ /^\d+$/.test(previous) &&
+ (direction === 'after'
+ ? BigInt(cursor) <= BigInt(previous)
+ : BigInt(cursor) >= BigInt(previous))
+ ) {
+ return '\n\n[Pagination blocked: the cursor did not advance. Stop and investigate; do not claim history is complete.]';
+ }
+ const next = JSON.stringify({
+ platform: params.platform,
+ channelId: params.channelId,
+ [direction]: cursor,
+ ...(params.limit !== undefined ? { limit: params.limit } : {}),
+ });
+ return `\n\n[Discord pagination: oldest message ID: "${oldest}"; newest message ID: "${newest}". Within the 3โ€“5-call readMessages budget, to continue toward ${direction === 'before' ? 'older' : 'newer'} messages, call readMessages with ${next}. Use only one of before/after. More messages are unknown, regardless of page size; stop on a successful empty page, or stop and investigate errors/non-advancing cursors. For large-volume requests or tasks needing more calls, use the lobehub skill to batch read via the CLI (lh bot message read) outside the conversation context instead of repeatedly calling readMessages.]`;
+};
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/types.ts b/packages/builtin-tool-message/src/ExecutionRuntime/types.ts
new file mode 100644
index 00000000000..2b3a39443ff
--- /dev/null
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/types.ts
@@ -0,0 +1,145 @@
+import type {
+ ConfiguredBotInfo,
+ CreatePollParams,
+ CreatePollState,
+ CreateThreadParams,
+ CreateThreadState,
+ DeleteMessageParams,
+ DeleteMessageState,
+ EditMessageParams,
+ EditMessageState,
+ GetBotDetailState,
+ GetChannelInfoParams,
+ GetChannelInfoState,
+ GetMemberInfoParams,
+ GetMemberInfoState,
+ GetMessengerDetailState,
+ GetReactionsParams,
+ GetReactionsState,
+ ListChannelsParams,
+ ListChannelsState,
+ ListPinsParams,
+ ListPinsState,
+ ListThreadsParams,
+ ListThreadsState,
+ MessengerInfo,
+ MessengerLinkInfo,
+ MessengerPlatformInfo,
+ MessengerPushStatus,
+ PinMessageParams,
+ PinMessageState,
+ PlatformInfo,
+ ReactToMessageParams,
+ ReactToMessageState,
+ ReadDocumentParams,
+ ReadDocumentState,
+ ReadMessagesParams,
+ ReadMessagesState,
+ ReplyToThreadParams,
+ ReplyToThreadState,
+ SearchMessagesParams,
+ SearchMessagesState,
+ SendDirectMessageParams,
+ SendDirectMessageState,
+ SendMessageParams,
+ SendMessageState,
+ SendMessengerPushParams,
+ SetMessengerActiveAgentParams,
+ UnlinkMessengerParams,
+ UnpinMessageParams,
+ UnpinMessageState,
+} from '../types';
+import type { MessageImageResolver } from './messageImages';
+
+/**
+ * Service interface for message operations.
+ * Each platform adapter must implement this interface for its supported operations.
+ * Unsupported operations should throw an error indicating the platform limitation.
+ */
+export interface MessageRuntimeService {
+ createPoll: (params: CreatePollParams) => Promise<CreatePollState>;
+ createThread: (params: CreateThreadParams) => Promise<CreateThreadState>;
+ deleteMessage: (params: DeleteMessageParams) => Promise<DeleteMessageState>;
+ editMessage: (params: EditMessageParams) => Promise<EditMessageState>;
+ getChannelInfo: (params: GetChannelInfoParams) => Promise<GetChannelInfoState>;
+ getMemberInfo: (params: GetMemberInfoParams) => Promise<GetMemberInfoState>;
+ getReactions: (params: GetReactionsParams) => Promise<GetReactionsState>;
+ listChannels: (params: ListChannelsParams) => Promise<ListChannelsState>;
+ listPins: (params: ListPinsParams) => Promise<ListPinsState>;
+ listThreads: (params: ListThreadsParams) => Promise<ListThreadsState>;
+ pinMessage: (params: PinMessageParams) => Promise<PinMessageState>;
+ reactToMessage: (params: ReactToMessageParams) => Promise<ReactToMessageState>;
+ /**
+ * Read a cloud document linked from the chat. Optional: only platforms
+ * with a document API (Feishu/Lark docx) implement it; the runtime reports
+ * "not supported" elsewhere and `messageCapabilities` trims the tool.
+ */
+ readDocument?: (params: ReadDocumentParams) => Promise<ReadDocumentState>;
+ readMessages: (params: ReadMessagesParams) => Promise<ReadMessagesState>;
+ replyToThread: (params: ReplyToThreadParams) => Promise<ReplyToThreadState>;
+ searchMessages: (params: SearchMessagesParams) => Promise<SearchMessagesState>;
+ sendDirectMessage?: (params: SendDirectMessageParams) => Promise<SendDirectMessageState>;
+ sendMessage: (params: SendMessageParams) => Promise<SendMessageState>;
+ unpinMessage: (params: UnpinMessageParams) => Promise<UnpinMessageState>;
+}
+
+/**
+ * Interface for bot provider management operations.
+ * Implemented by the server-side factory using AgentBotProviderModel + TRPC router logic.
+ */
+export interface BotProviderQuery {
+ connectBot: (botId: string) => Promise<{ status: string }>;
+ createBot: (params: {
+ agentId: string;
+ applicationId: string;
+ credentials: Record<string, string>;
+ platform: string;
+ settings?: Record<string, unknown>;
+ }) => Promise<{ id: string; platform: string }>;
+ deleteBot: (botId: string) => Promise<void>;
+ getBotDetail: (botId: string) => Promise<GetBotDetailState | null>;
+ // โ”€โ”€โ”€ System Bot messenger management โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
+ // All optional so callers can compose a minimal BotProviderQuery. When
+ // absent, the executor returns a "feature not wired up" message.
+ /** Single install detail, or null when not found. */
+ getMessengerDetail?: (installationId: string) => Promise<GetMessengerDetailState | null>;
+ listBots: () => Promise<ConfiguredBotInfo[]>;
+ /** User's account links across platforms. */
+ listMessengerLinks?: () => Promise<MessengerLinkInfo[]>;
+ /** Platforms available for OAuth install. */
+ listMessengerPlatforms?: () => Promise<MessengerPlatformInfo[]>;
+ /** User's workspace-scoped System Bot installs. */
+ listMessengers?: () => Promise<MessengerInfo[]>;
+ listPlatforms: () => Promise<PlatformInfo[]>;
+ /**
+ * Proactively push a message to the caller's own linked messenger DM.
+ * Mirrors `messenger.sendMessengerPush` โ€” the runtime resolves Slack
+ * workspace ambiguity BEFORE calling this, so the handler only sees
+ * deliverable requests.
+ */
+ sendMessengerPush?: (params: SendMessengerPushParams) => Promise<{
+ remaining?: number;
+ status: Exclude<MessengerPushStatus, 'needs_workspace_selection'>;
+ }>;
+ /** Change which agent receives inbound IM on a link. */
+ setMessengerActiveAgent?: (params: SetMessengerActiveAgentParams) => Promise<void>;
+ toggleBot: (botId: string, enabled: boolean) => Promise<void>;
+ /** Revoke a workspace install (affects every user in that workspace). */
+ uninstallMessenger?: (installationId: string) => Promise<void>;
+ /** Remove the current user's account link only. */
+ unlinkMessenger?: (params: UnlinkMessengerParams) => Promise<void>;
+ updateBot: (
+ botId: string,
+ params: { credentials?: Record<string, string>; settings?: Record<string, unknown> },
+ ) => Promise<void>;
+}
+
+export interface MessageExecutionRuntimeOptions {
+ botProvider?: BotProviderQuery;
+ /**
+ * Stores image attachments of read / searched messages so they can ride on the tool result
+ * (`state.images`) for vision models. Absent = images are named in the text only.
+ */
+ resolveImages?: MessageImageResolver;
+ service: MessageRuntimeService;
+}
diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.ts
index 79196bed457..41ca94e5d4e 100644
--- a/packages/builtin-tool-message/src/types.ts
+++ b/packages/builtin-tool-message/src/types.ts
@@ -283,8 +283,17 @@ export interface ReadMessagesState {
totalFetched?: number;
}
+export interface MessageItemAttachment {
+ /** MIME type when the platform reports it (Discord `content_type`). */
+ contentType?: string;
+ name: string;
+ /** Bytes, when the platform reports it. */
+ size?: number;
+ url: string;
+}
+
export interface MessageItem {
- attachments?: { name: string; url: string }[];
+ attachments?: MessageItemAttachment[];
author: { id: string; name: string };
content: string;
id: string;
diff --git a/packages/context-engine/src/processors/StaleToolResultTrim.ts b/packages/context-engine/src/processors/StaleToolResultTrim.ts
index f2387992fb0..d539663eb25 100644
--- a/packages/context-engine/src/processors/StaleToolResultTrim.ts
+++ b/packages/context-engine/src/processors/StaleToolResultTrim.ts
@@ -66,6 +66,14 @@ export interface StaleToolResultTrimConfig {
* @default true
*/
enabled?: boolean;
+ /**
+ * Chars an image attached to a tool result (`pluginState.images`) counts as in the size gate
+ * and the savings estimate. Images are billed per pixel, not per char, so without a weight a
+ * history of image reads never clears the gate and dropping them looks like no saving at all.
+ * Anthropic bills a ~1000ร—1000 image at ~1.3k tokens, about 5k chars.
+ * @default 5000
+ */
+ imageCharEquivalent?: number;
/**
* Trailing message count that is never trimmed. The model is actively
* working with the tail of the conversation; trimming there saves little and
@@ -106,8 +114,12 @@ export interface StaleToolResultTrimConfig {
}
const LOCAL_SYSTEM = 'lobe-local-system';
+
+const imageCountOf = (message: Message) =>
+ (message.pluginState as { images?: unknown[] } | undefined)?.images?.length ?? 0;
const BROWSER = 'lobe-browser';
const WEB_BROWSING = 'lobe-web-browsing';
+const MESSAGE = 'lobe-message';
export interface CacheEconomics {
/** Cached-read price relative to the plain input price. */
@@ -160,6 +172,7 @@ const READ_APIS = new Set(['readFile']);
const WRITE_APIS = new Set(['writeFile', 'editFile']);
const COMMAND_APIS = new Set(['runCommand', 'getCommandOutput']);
const CRAWL_APIS = new Set(['search', 'crawlSinglePage', 'crawlMultiPages']);
+const MESSAGE_READ_APIS = new Set(['readMessages', 'searchMessages']);
interface PluginInfo {
apiName?: string;
@@ -283,6 +296,7 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
crawlKeepChars: config.crawlKeepChars ?? 1000,
economics,
enabled: config.enabled ?? true,
+ imageCharEquivalent: config.imageCharEquivalent ?? 5000,
keepRecentMessages: config.keepRecentMessages ?? 20,
minTotalToolChars: config.minTotalToolChars ?? 100_000,
pageTextKeepChars: config.pageTextKeepChars ?? 1000,
@@ -328,7 +342,9 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
let closedToolChars = 0;
for (let i = 0; i < boundary; i++) {
const m = messages[i];
- if (m.role === 'tool' && typeof m.content === 'string') closedToolChars += m.content.length;
+ if (m.role !== 'tool') continue;
+ if (typeof m.content === 'string') closedToolChars += m.content.length;
+ closedToolChars += imageCountOf(m) * this.config.imageCharEquivalent;
}
if (closedToolChars < this.config.minTotalToolChars) {
return this.markAsExecuted(context);
@@ -404,8 +420,14 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
// the candidates, and the priced payload are all frozen at the turn
// boundary, so the decision cannot flip mid-operation and flip the
// prefix with it.
+ // A trimmed result also loses its images (pass 3), which is most of the saving for an
+ // image read.
const potentialSavedChars = candidates.reduce(
- (s, c) => s + (messages[c.index].content as string).length - c.content.length,
+ (s, c) =>
+ s +
+ (messages[c.index].content as string).length -
+ c.content.length +
+ imageCountOf(messages[c.index]) * this.config.imageCharEquivalent,
0,
);
const triggeredAt = toEpochMs(messages[lastUserIndex]?.createdAt);
@@ -428,6 +450,7 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
for (let i = 0; i < payloadEnd; i++) {
const m = messages[i];
if (typeof m.content === 'string') totalChars += m.content.length;
+ totalChars += imageCountOf(m) * this.config.imageCharEquivalent;
}
const gainEstimate =
this.config.warmRemainingStepsEstimate * potentialSavedChars * this.config.cacheReadPrice;
@@ -469,7 +492,10 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
const candidate = candidateByIndex.get(index);
if (!candidate) return message;
- savedChars += (message.content as string).length - candidate.content.length;
+ savedChars +=
+ (message.content as string).length -
+ candidate.content.length +
+ imageCountOf(message) * this.config.imageCharEquivalent;
byRule[candidate.rule] = (byRule[candidate.rule] ?? 0) + 1;
// A trimmed image read must not keep its attachments: MessageContentProcessor
// (later in the pipeline) would still turn pluginState.images into
@@ -564,6 +590,17 @@ export class StaleToolResultTrimProcessor extends BaseProcessor {
};
}
+ if (identifier === MESSAGE && MESSAGE_READ_APIS.has(apiName)) {
+ // Chat images read from the channel cost vision tokens on every later turn. The text
+ // (who said what) stays; the images are dropped once the result leaves the recent window.
+ const images = (message.pluginState as { images?: unknown[] } | undefined)?.images;
+ if (!images?.length) return undefined;
+ return {
+ content: `${content}\n[${images.length} image(s) from this ${apiName} result are no longer attached. Call ${apiName} again if you need to see them.]`,
+ rule: 'staleMessageImages',
+ };
+ }
+
if (
identifier === LOCAL_SYSTEM &&
COMMAND_APIS.has(apiName) &&
diff --git a/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts
index 6bea2bc00ce..31d2be6994a 100644
--- a/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts
+++ b/packages/context-engine/src/processors/__tests__/StaleToolResultTrim.test.ts
@@ -108,6 +108,70 @@ describe('StaleToolResultTrimProcessor', () => {
expect(result.metadata.staleToolResultTrim?.trimmedMessages ?? 0).toBe(0);
});
+ describe('chat images from readMessages', () => {
+ const T0 = Date.parse('2026-09-20T08:00:00Z');
+ const images = (n: number) =>
+ Array.from({ length: n }, (_, i) => ({ mediaType: 'image/png', url: `https://app/f/${i}` }));
+ const readWithImages = (n: number) =>
+ toolMessage('lobe-message', 'readMessages', 'Fetched 3 messages', {
+ pluginState: { images: images(n), messages: [] },
+ });
+ // Old read, filler pushing it out of the recency tail, then the turn boundary.
+ const history = (imageCount: number, gapMs: number) => [
+ readWithImages(imageCount),
+ { content: 'filler 1', id: 'f1', role: 'assistant' },
+ { content: 'filler 2', id: 'f2', role: 'assistant' },
+ { content: 'filler 3', id: 'f3', role: 'assistant' },
+ { content: 'done', createdAt: T0, id: 'prev', role: 'assistant' },
+ { content: 'next', createdAt: T0 + gapMs, id: 'trigger', role: 'user' },
+ ];
+
+ it('drops the images of an old result but keeps its text', async () => {
+ const result = await createProcessor().process(createContext(history(1, 600_000)));
+
+ expect(result.messages[0].content).toBe(
+ 'Fetched 3 messages\n[1 image(s) from this readMessages result are no longer attached. Call readMessages again if you need to see them.]',
+ );
+ expect((result.messages[0] as any).pluginState.images).toBeUndefined();
+ expect((result.messages[0] as any).pluginState.messages).toEqual([]);
+ expect(result.metadata.staleToolResultTrim?.byRule).toEqual({ staleMessageImages: 1 });
+ });
+
+ // Regression (Codex P2): images were worth 0 chars, so a history of image reads never
+ // cleared the size gate however many images it held.
+ it('counts images toward the minimum-size gate', async () => {
+ const processor = new StaleToolResultTrimProcessor({
+ imageCharEquivalent: 5000,
+ keepRecentMessages: 3,
+ minTotalToolChars: 20_000,
+ });
+
+ const below = await processor.process(createContext(history(3, 600_000)));
+ expect((below.messages[0] as any).pluginState.images).toHaveLength(3);
+
+ const above = await processor.process(createContext(history(4, 600_000)));
+ expect((above.messages[0] as any).pluginState.images).toBeUndefined();
+ });
+
+ // Regression (Codex P2): the replacement only appends text, so without counting the dropped
+ // images the saving was negative and the warm-cache break-even always skipped.
+ it('counts dropped images as savings in the warm-cache break-even', async () => {
+ const result = await createProcessor().process(createContext(history(4, 60_000)));
+
+ expect(result.metadata.staleToolResultTrim).toMatchObject({
+ cacheWarm: true,
+ byRule: { staleMessageImages: 1 },
+ });
+ expect((result.messages[0] as any).pluginState.images).toBeUndefined();
+ });
+
+ it('keeps the images inside the recency window', async () => {
+ const result = await createProcessor().process(createContext([readWithImages(1)]));
+
+ expect((result.messages[0] as any).pluginState.images).toHaveLength(1);
+ });
+ });
+
it('trims stale browser snapshots outside the recency window', async () => {
const messages = [
toolMessage('lobe-browser', 'snapshot', '- button "ๅ†™ไฝœ" [ref=e1]\n'.repeat(100)),