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.

✨ feat: support bot attachments across all platforms (#15029)

Rdmclin21698b7e77d87
diff --git a/apps/cli/src/commands/bot.ts b/apps/cli/src/commands/bot.ts
index 481528b13c3..c73589cff25 100644
--- a/apps/cli/src/commands/bot.ts
+++ b/apps/cli/src/commands/bot.ts
@@ -6,6 +6,7 @@ import { getTrpcClient } from '../api/client';
import { confirm, outputJson, printBoxTable, printTable, timeAgo } from '../utils/format';
import { log } from '../utils/logger';
import { registerBotMessageCommands } from './botMessage';
+import { registerBotMessengersCommands } from './botMessengers';
// ── Access policy helpers ──────────────────────────────
@@ -475,6 +476,9 @@ export function registerBotCommand(program: Command) {
// Register message subcommand group
registerBotMessageCommands(bot);
+ // Register messengers subcommand group (System Bot installations + account links)
+ registerBotMessengersCommands(bot);
+
// ── platforms ───────────────────────────────────────────
bot
diff --git a/apps/cli/src/commands/botMessage.test.ts b/apps/cli/src/commands/botMessage.test.ts
index 0d2b84d8144..85cc4fe9ae1 100644
--- a/apps/cli/src/commands/botMessage.test.ts
+++ b/apps/cli/src/commands/botMessage.test.ts
@@ -1,6 +1,6 @@
import { mkdtemp, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
-import { join } from 'node:path';
+import path from 'node:path';
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -10,6 +10,8 @@ import { registerBotMessageCommands } from './botMessage';
const { mockTrpcClient } = vi.hoisted(() => ({
mockTrpcClient: {
botMessage: {
+ replyToThread: { mutate: vi.fn() },
+ sendDirectMessage: { mutate: vi.fn() },
sendMessage: { mutate: vi.fn() },
},
},
@@ -35,6 +37,13 @@ describe('bot message send --attachment', () => {
mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
mockTrpcClient.botMessage.sendMessage.mutate.mockReset();
mockTrpcClient.botMessage.sendMessage.mutate.mockResolvedValue({ messageId: 'm-1' });
+ mockTrpcClient.botMessage.sendDirectMessage.mutate.mockReset();
+ mockTrpcClient.botMessage.sendDirectMessage.mutate.mockResolvedValue({
+ channelId: 'dm-1',
+ messageId: 'm-dm-1',
+ });
+ mockTrpcClient.botMessage.replyToThread.mutate.mockReset();
+ mockTrpcClient.botMessage.replyToThread.mutate.mockResolvedValue({ messageId: 'm-tr-1' });
});
afterEach(() => {
@@ -85,9 +94,9 @@ describe('bot message send --attachment', () => {
});
it('base64-encodes a local file path', async () => {
- const dir = await mkdtemp(join(tmpdir(), 'lh-cli-attach-'));
- const path = join(dir, 'tiny.txt');
- await writeFile(path, 'hello');
+ const dir = await mkdtemp(path.join(tmpdir(), 'lh-cli-attach-'));
+ const filePath = path.join(dir, 'tiny.txt');
+ await writeFile(filePath, 'hello');
const program = createProgram();
await program.parseAsync([
@@ -102,7 +111,7 @@ describe('bot message send --attachment', () => {
'--message',
'm',
'--attachment',
- path,
+ filePath,
]);
const call = mockTrpcClient.botMessage.sendMessage.mutate.mock.calls[0][0];
@@ -160,3 +169,249 @@ describe('bot message send --attachment', () => {
expect(call.attachments).toBeUndefined();
});
});
+
+describe('bot message dm --attachment', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockTrpcClient.botMessage.sendDirectMessage.mutate.mockReset();
+ mockTrpcClient.botMessage.sendDirectMessage.mutate.mockResolvedValue({
+ channelId: 'dm-1',
+ messageId: 'm-dm-1',
+ });
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ });
+
+ function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ const bot = program.command('bot');
+ registerBotMessageCommands(bot);
+ return program;
+ }
+
+ it('sends a DM with a remote-URL attachment', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'message',
+ 'dm',
+ 'bot-1',
+ '--user-id',
+ 'u-1',
+ '--message',
+ 'hi',
+ '--attachment',
+ 'https://cdn.example.com/foo.png',
+ ]);
+
+ expect(mockTrpcClient.botMessage.sendDirectMessage.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ attachments: [
+ expect.objectContaining({
+ fetchUrl: 'https://cdn.example.com/foo.png',
+ type: 'image',
+ }),
+ ],
+ botId: 'bot-1',
+ content: 'hi',
+ userId: 'u-1',
+ }),
+ );
+ });
+
+ it('omits attachments when no flag is given', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'message',
+ 'dm',
+ 'bot-1',
+ '--user-id',
+ 'u-1',
+ '--message',
+ 'plain',
+ ]);
+ const call = mockTrpcClient.botMessage.sendDirectMessage.mutate.mock.calls[0][0];
+ expect(call.attachments).toBeUndefined();
+ });
+});
+
+describe('bot message thread reply --attachment', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockTrpcClient.botMessage.replyToThread.mutate.mockReset();
+ mockTrpcClient.botMessage.replyToThread.mutate.mockResolvedValue({ messageId: 'm-tr-1' });
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ });
+
+ function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ const bot = program.command('bot');
+ registerBotMessageCommands(bot);
+ return program;
+ }
+
+ it('replies to a thread with attachments', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'message',
+ 'thread',
+ 'reply',
+ 'bot-1',
+ '--thread-id',
+ 'th-1',
+ '--message',
+ 'reply',
+ '--attachment',
+ 'https://cdn.example.com/a.png',
+ ]);
+
+ expect(mockTrpcClient.botMessage.replyToThread.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({
+ attachments: [
+ expect.objectContaining({
+ fetchUrl: 'https://cdn.example.com/a.png',
+ type: 'image',
+ }),
+ ],
+ botId: 'bot-1',
+ content: 'reply',
+ threadId: 'th-1',
+ }),
+ );
+ });
+});
+
+describe('bot message send via System Bot messenger install (@id)', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ mockTrpcClient.botMessage.sendMessage.mutate.mockReset();
+ mockTrpcClient.botMessage.sendMessage.mutate.mockResolvedValue({ messageId: 'm-mi-1' });
+ mockTrpcClient.botMessage.sendDirectMessage.mutate.mockReset();
+ mockTrpcClient.botMessage.sendDirectMessage.mutate.mockResolvedValue({ messageId: 'm-mi-2' });
+ mockTrpcClient.botMessage.replyToThread.mutate.mockReset();
+ mockTrpcClient.botMessage.replyToThread.mutate.mockResolvedValue({ messageId: 'm-mi-3' });
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ });
+
+ function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ const bot = program.command('bot');
+ registerBotMessageCommands(bot);
+ return program;
+ }
+
+ it('@-prefixed positional arg routes to messengerInstallationId on send', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'message',
+ 'send',
+ '@inst_abc',
+ '--target',
+ 'C1',
+ '--message',
+ 'hi',
+ ]);
+
+ const call = mockTrpcClient.botMessage.sendMessage.mutate.mock.calls[0][0];
+ expect(call.messengerInstallationId).toBe('inst_abc');
+ expect(call.botId).toBeUndefined();
+ expect(call.channelId).toBe('C1');
+ });
+
+ it('@-prefixed routes on dm', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'message',
+ 'dm',
+ '@inst_xyz',
+ '--user-id',
+ 'U1',
+ '--message',
+ 'hi',
+ ]);
+ const call = mockTrpcClient.botMessage.sendDirectMessage.mutate.mock.calls[0][0];
+ expect(call.messengerInstallationId).toBe('inst_xyz');
+ expect(call.botId).toBeUndefined();
+ });
+
+ it('@-prefixed routes on thread reply', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'message',
+ 'thread',
+ 'reply',
+ '@inst_thr',
+ '--thread-id',
+ 'T1',
+ '--message',
+ 'r',
+ ]);
+ const call = mockTrpcClient.botMessage.replyToThread.mutate.mock.calls[0][0];
+ expect(call.messengerInstallationId).toBe('inst_thr');
+ });
+
+ it('plain (non-@) positional stays as botId', async () => {
+ const program = createProgram();
+ await program.parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'message',
+ 'send',
+ 'uuid-bot-id',
+ '--target',
+ 'C1',
+ '--message',
+ 'hi',
+ ]);
+ const call = mockTrpcClient.botMessage.sendMessage.mutate.mock.calls[0][0];
+ expect(call.botId).toBe('uuid-bot-id');
+ expect(call.messengerInstallationId).toBeUndefined();
+ });
+});
diff --git a/apps/cli/src/commands/botMessage.ts b/apps/cli/src/commands/botMessage.ts
index cee9cda82ea..62aa084b11f 100644
--- a/apps/cli/src/commands/botMessage.ts
+++ b/apps/cli/src/commands/botMessage.ts
@@ -45,6 +45,28 @@ const inferAttachmentType = (mimeType?: string): AttachmentInput['type'] => {
return 'file';
};
+/**
+ * Resolve a list of `--attachment` flag values into `AttachmentInput[]`. Each
+ * entry is either a URL or a local file path. Returns `undefined` when no
+ * flags were passed so callers can omit the field on the wire entirely (the
+ * TRPC schema treats absent vs empty differently). Bails the process on
+ * load failures — a silently-dropped attachment would be worse than a
+ * loud error here.
+ */
+const resolveAttachmentFlags = async (flags: string[]): Promise<AttachmentInput[] | undefined> => {
+ if (flags.length === 0) return undefined;
+ const out: AttachmentInput[] = [];
+ for (const raw of flags) {
+ try {
+ out.push(await parseAttachmentArg(raw));
+ } catch (error) {
+ log.error(`Failed to load attachment "${raw}": ${(error as Error).message}`);
+ process.exit(1);
+ }
+ }
+ return out;
+};
+
/**
* Parse a single `--attachment <value>` argument. Accepted forms:
* - `https://…` / `http://…` → fetchUrl, type inferred from extension
@@ -72,6 +94,26 @@ const parseAttachmentArg = async (raw: string): Promise<AttachmentInput> => {
};
};
+/**
+ * Resolve the `<botIdOrAtKey>` positional argument into a `{ botId? |
+ * messengerInstallationId? }` shape that matches the TRPC send procedures'
+ * `exactly-one-of` constraint.
+ *
+ * Convention: a value prefixed with `@` is treated as a System Bot
+ * messenger installation id (e.g. `@inst_abc123`); anything else is a
+ * per-agent bot id. The `@` was chosen because `agent_bot_providers`.id is
+ * always a UUID — no UUID starts with `@`, so the prefix unambiguously
+ * disambiguates without breaking the existing UUID-only call sites.
+ */
+const resolveSendTargetArg = (
+ value: string,
+): { botId?: string; messengerInstallationId?: string } => {
+ if (value.startsWith('@')) {
+ return { messengerInstallationId: value.slice(1) };
+ }
+ return { botId: value };
+};
+
export function registerBotMessageCommands(bot: Command) {
const message = bot
.command('message')
@@ -80,8 +122,11 @@ export function registerBotMessageCommands(bot: Command) {
// ── send ────────────────────────────────────────────────
message
- .command('send <botId>')
- .description('Send a message to a channel')
+ .command('send <botIdOrAtKey>')
+ .description(
+ 'Send a message to a channel. Pass a per-agent bot id, or "@<messenger-install-id>" ' +
+ 'to send through a System Bot messenger installation (see `lh bot messengers list`).',
+ )
.requiredOption('--target <channelId>', 'Target channel / conversation ID')
.requiredOption('--message <text>', 'Message content')
.option(
@@ -95,7 +140,7 @@ export function registerBotMessageCommands(bot: Command) {
.option('--json', 'Output JSON')
.action(
async (
- botId: string,
+ botIdOrAtKey: string,
options: {
attachment: string[];
json?: boolean;
@@ -104,23 +149,13 @@ export function registerBotMessageCommands(bot: Command) {
target: string;
},
) => {
- let attachments: AttachmentInput[] | undefined;
- if (options.attachment.length > 0) {
- attachments = [];
- for (const raw of options.attachment) {
- try {
- attachments.push(await parseAttachmentArg(raw));
- } catch (error) {
- log.error(`Failed to load attachment "${raw}": ${(error as Error).message}`);
- process.exit(1);
- }
- }
- }
+ const attachments = await resolveAttachmentFlags(options.attachment);
+ const target = resolveSendTargetArg(botIdOrAtKey);
const client = await getTrpcClient();
const result = await client.botMessage.sendMessage.mutate({
+ ...target,
attachments,
- botId,
channelId: options.target,
content: options.message,
replyTo: options.replyTo,
@@ -139,6 +174,53 @@ export function registerBotMessageCommands(bot: Command) {
},
);
+ // ── dm (direct message) ─────────────────────────────────
+
+ message
+ .command('dm <botIdOrAtKey>')
+ .description(
+ 'Send a direct message to a platform user. Pass a per-agent bot id, or ' +
+ '"@<messenger-install-id>" for a System Bot install.',
+ )
+ .requiredOption('--user-id <id>', 'Target user ID on the platform')
+ .requiredOption('--message <text>', 'Message content')
+ .option(
+ '--attachment <pathOrUrl>',
+ 'Attach a file by local path or remote URL (repeatable). ' +
+ 'Local paths are base64-encoded; http(s) URLs are passed as fetchUrl.',
+ collectOptions,
+ [],
+ )
+ .option('--json', 'Output JSON')
+ .action(
+ async (
+ botIdOrAtKey: string,
+ options: { attachment: string[]; json?: boolean; message: string; userId: string },
+ ) => {
+ const attachments = await resolveAttachmentFlags(options.attachment);
+ const target = resolveSendTargetArg(botIdOrAtKey);
+
+ const client = await getTrpcClient();
+ const result = await client.botMessage.sendDirectMessage.mutate({
+ ...target,
+ attachments,
+ content: options.message,
+ userId: options.userId,
+ });
+
+ if (options.json) {
+ outputJson(result);
+ return;
+ }
+
+ const r = result as any;
+ const suffix = attachments?.length ? ` with ${attachments.length} attachment(s)` : '';
+ console.log(
+ `${pc.green('✓')} DM sent${r.messageId ? ` (${pc.dim(r.messageId)})` : ''}${suffix}`,
+ );
+ },
+ );
+
// ── read ────────────────────────────────────────────────
message
@@ -544,21 +626,43 @@ export function registerBotMessageCommands(bot: Command) {
});
thread
- .command('reply <botId>')
- .description('Reply to a thread')
+ .command('reply <botIdOrAtKey>')
+ .description(
+ 'Reply to a thread. Pass a per-agent bot id, or "@<messenger-install-id>" ' +
+ 'for a System Bot install.',
+ )
.requiredOption('--thread-id <id>', 'Thread ID')
.requiredOption('--message <text>', 'Reply content')
- .action(async (botId: string, options: { message: string; threadId: string }) => {
- const client = await getTrpcClient();
- const result = await client.botMessage.replyToThread.mutate({
- botId,
- content: options.message,
- threadId: options.threadId,
- });
+ .option(
+ '--attachment <pathOrUrl>',
+ 'Attach a file by local path or remote URL (repeatable). ' +
+ 'Local paths are base64-encoded; http(s) URLs are passed as fetchUrl.',
+ collectOptions,
+ [],
+ )
+ .action(
+ async (
+ botIdOrAtKey: string,
+ options: { attachment: string[]; message: string; threadId: string },
+ ) => {
+ const attachments = await resolveAttachmentFlags(options.attachment);
+ const target = resolveSendTargetArg(botIdOrAtKey);
- const r = result as any;
- console.log(`${pc.green('✓')} Reply sent${r.messageId ? ` (${pc.dim(r.messageId)})` : ''}`);
- });
+ const client = await getTrpcClient();
+ const result = await client.botMessage.replyToThread.mutate({
+ ...target,
+ attachments,
+ content: options.message,
+ threadId: options.threadId,
+ });
+
+ const r = result as any;
+ const suffix = attachments?.length ? ` with ${attachments.length} attachment(s)` : '';
+ console.log(
+ `${pc.green('✓')} Reply sent${r.messageId ? ` (${pc.dim(r.messageId)})` : ''}${suffix}`,
+ );
+ },
+ );
// ── channel (subcommand group) ──────────────────────────
diff --git a/apps/cli/src/commands/botMessengers.test.ts b/apps/cli/src/commands/botMessengers.test.ts
new file mode 100644
index 00000000000..b12b619dbbc
--- /dev/null
+++ b/apps/cli/src/commands/botMessengers.test.ts
@@ -0,0 +1,365 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as FormatModule from '../utils/format';
+import { registerBotMessengersCommands } from './botMessengers';
+
+const { mockTrpcClient } = vi.hoisted(() => ({
+ mockTrpcClient: {
+ messenger: {
+ availablePlatforms: { query: vi.fn() },
+ getMyLink: { query: vi.fn() },
+ listMyInstallations: { query: vi.fn() },
+ listMyLinks: { query: vi.fn() },
+ setActiveAgent: { mutate: vi.fn() },
+ unlink: { mutate: vi.fn() },
+ uninstallInstallation: { mutate: vi.fn() },
+ },
+ },
+}));
+
+const { getTrpcClient: mockGetTrpcClient } = vi.hoisted(() => ({
+ getTrpcClient: vi.fn(),
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: mockGetTrpcClient }));
+vi.mock('../utils/logger', () => ({
+ log: { debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() },
+ setVerbose: vi.fn(),
+}));
+
+// `confirm` always answers yes — we test uninstall/unlink under the explicit
+// `--yes` flag too, but for the prompt path we want a deterministic answer.
+vi.mock('../utils/format', async () => {
+ const actual = await vi.importActual<typeof FormatModule>('../utils/format');
+ return { ...actual, confirm: vi.fn(async () => true) };
+});
+
+describe('bot messengers', () => {
+ let exitSpy: ReturnType<typeof vi.spyOn>;
+ let consoleSpy: ReturnType<typeof vi.spyOn>;
+ let errorSpy: ReturnType<typeof vi.spyOn>;
+
+ beforeEach(() => {
+ exitSpy = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ mockGetTrpcClient.mockResolvedValue(mockTrpcClient);
+ for (const fn of [
+ mockTrpcClient.messenger.availablePlatforms.query,
+ mockTrpcClient.messenger.getMyLink.query,
+ mockTrpcClient.messenger.listMyInstallations.query,
+ mockTrpcClient.messenger.listMyLinks.query,
+ mockTrpcClient.messenger.setActiveAgent.mutate,
+ mockTrpcClient.messenger.unlink.mutate,
+ mockTrpcClient.messenger.uninstallInstallation.mutate,
+ ]) {
+ fn.mockReset();
+ }
+ });
+
+ afterEach(() => {
+ exitSpy.mockRestore();
+ consoleSpy.mockRestore();
+ errorSpy.mockRestore();
+ });
+
+ function createProgram() {
+ const program = new Command();
+ program.exitOverride();
+ const bot = program.command('bot');
+ registerBotMessengersCommands(bot);
+ return program;
+ }
+
+ function renderedOutput(): string {
+ return consoleSpy.mock.calls.map((c) => String(c[0])).join('\n');
+ }
+
+ // ── installations ──────────────────────────────────────
+
+ describe('list', () => {
+ it('renders the installation table with SEND ARG hint', async () => {
+ mockTrpcClient.messenger.listMyInstallations.query.mockResolvedValueOnce([
+ {
+ applicationId: 'A1',
+ id: 'inst_abc',
+ installedAt: '2026-01-15T00:00:00Z',
+ platform: 'slack',
+ tenantId: 'T1',
+ tenantName: 'Acme Corp',
+ },
+ ]);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'list']);
+ const out = renderedOutput();
+ expect(mockTrpcClient.messenger.listMyInstallations.query).toHaveBeenCalled();
+ expect(out).toContain('inst_abc');
+ expect(out).toContain('Acme Corp');
+ // The hint should explain how to use the id with the send commands
+ expect(out).toContain('@<INSTALLATION ID>');
+ });
+
+ it('reports empty state with install guidance', async () => {
+ mockTrpcClient.messenger.listMyInstallations.query.mockResolvedValueOnce([]);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'list']);
+ const out = renderedOutput();
+ expect(out).toContain('No System Bot installations connected.');
+ expect(out).toContain('Settings → Messenger');
+ });
+
+ it('--json passes through the payload', async () => {
+ const payload = [{ id: 'inst_only', platform: 'discord', tenantId: 'g1' }];
+ mockTrpcClient.messenger.listMyInstallations.query.mockResolvedValueOnce(payload);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'list', '--json']);
+ expect(renderedOutput()).toContain('"id": "inst_only"');
+ });
+ });
+
+ describe('view', () => {
+ it('prints details for a matching install', async () => {
+ mockTrpcClient.messenger.listMyInstallations.query.mockResolvedValueOnce([
+ {
+ applicationId: 'A1',
+ id: 'inst_match',
+ installedAt: '2026-01-15T00:00:00Z',
+ platform: 'slack',
+ scope: 'chat:write,users:read',
+ tenantId: 'T1',
+ tenantName: 'Acme Corp',
+ },
+ ]);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'view', 'inst_match']);
+ const out = renderedOutput();
+ expect(out).toContain('inst_match');
+ expect(out).toContain('slack');
+ expect(out).toContain('Acme Corp');
+ expect(out).toContain('chat:write,users:read');
+ });
+
+ it('exits non-zero when install missing', async () => {
+ mockTrpcClient.messenger.listMyInstallations.query.mockResolvedValueOnce([]);
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'view',
+ 'inst_missing',
+ ]);
+ expect(errorSpy).toHaveBeenCalled();
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+
+ it('--json missing install emits JSON null + exit 1 (scriptable)', async () => {
+ mockTrpcClient.messenger.listMyInstallations.query.mockResolvedValueOnce([]);
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'view',
+ 'inst_missing',
+ '--json',
+ ]);
+ // No human-readable error log; the JSON-pipe consumer gets `null`.
+ expect(errorSpy).not.toHaveBeenCalled();
+ expect(consoleSpy.mock.calls.map((c) => String(c[0])).join('\n')).toContain('null');
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+ });
+
+ describe('uninstall', () => {
+ it('--yes skips confirm and calls the mutation', async () => {
+ mockTrpcClient.messenger.uninstallInstallation.mutate.mockResolvedValueOnce({
+ success: true,
+ });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'uninstall',
+ 'inst_abc',
+ '--yes',
+ ]);
+ expect(mockTrpcClient.messenger.uninstallInstallation.mutate).toHaveBeenCalledWith({
+ installationId: 'inst_abc',
+ });
+ expect(renderedOutput()).toContain('revoked');
+ });
+
+ it('confirms before calling when --yes is omitted', async () => {
+ mockTrpcClient.messenger.listMyInstallations.query.mockResolvedValueOnce([
+ { id: 'inst_abc', platform: 'slack', tenantId: 'T1', tenantName: 'Acme' },
+ ]);
+ mockTrpcClient.messenger.uninstallInstallation.mutate.mockResolvedValueOnce({
+ success: true,
+ });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'uninstall',
+ 'inst_abc',
+ ]);
+ // Mocked confirm returns true → mutation still fires
+ expect(mockTrpcClient.messenger.uninstallInstallation.mutate).toHaveBeenCalled();
+ });
+ });
+
+ describe('platforms', () => {
+ it('renders the platforms table', async () => {
+ mockTrpcClient.messenger.availablePlatforms.query.mockResolvedValueOnce([
+ { appId: 'A123', id: 'slack', name: 'Slack' },
+ { botUsername: 'lobehub_bot', id: 'telegram', name: 'Telegram' },
+ ]);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'platforms']);
+ const out = renderedOutput();
+ expect(out).toContain('slack');
+ expect(out).toContain('A123');
+ expect(out).toContain('lobehub_bot');
+ });
+
+ it('handles empty platform list gracefully', async () => {
+ mockTrpcClient.messenger.availablePlatforms.query.mockResolvedValueOnce([]);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'platforms']);
+ expect(renderedOutput()).toContain('No System Bot platforms');
+ });
+ });
+
+ // ── links ──────────────────────────────────────────────
+
+ describe('links list', () => {
+ it('renders the links table', async () => {
+ mockTrpcClient.messenger.listMyLinks.query.mockResolvedValueOnce([
+ {
+ activeAgentId: 'agent_1',
+ platform: 'slack',
+ platformUserId: 'U1',
+ platformUsername: 'alice',
+ tenantId: 'T1',
+ },
+ ]);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'links', 'list']);
+ const out = renderedOutput();
+ expect(out).toContain('agent_1');
+ expect(out).toContain('alice');
+ });
+
+ it('reports empty state', async () => {
+ mockTrpcClient.messenger.listMyLinks.query.mockResolvedValueOnce([]);
+ await createProgram().parseAsync(['node', 'test', 'bot', 'messengers', 'links', 'list']);
+ expect(renderedOutput()).toContain('No account links yet');
+ });
+ });
+
+ describe('links view', () => {
+ it('shows the link detail', async () => {
+ mockTrpcClient.messenger.getMyLink.query.mockResolvedValueOnce({
+ activeAgentId: 'agent_2',
+ platform: 'slack',
+ platformUserId: 'U2',
+ platformUsername: 'bob',
+ tenantId: 'T2',
+ });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'links',
+ 'view',
+ 'slack',
+ '--tenant',
+ 'T2',
+ ]);
+ expect(mockTrpcClient.messenger.getMyLink.query).toHaveBeenCalledWith({
+ platform: 'slack',
+ tenantId: 'T2',
+ });
+ expect(renderedOutput()).toContain('agent_2');
+ });
+
+ it('exits non-zero on missing link', async () => {
+ mockTrpcClient.messenger.getMyLink.query.mockResolvedValueOnce(null);
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'links',
+ 'view',
+ 'discord',
+ ]);
+ expect(errorSpy).toHaveBeenCalled();
+ expect(exitSpy).toHaveBeenCalledWith(1);
+ });
+ });
+
+ describe('links set-agent', () => {
+ it('passes agentId through to setActiveAgent', async () => {
+ mockTrpcClient.messenger.setActiveAgent.mutate.mockResolvedValueOnce({ success: true });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'links',
+ 'set-agent',
+ 'slack',
+ '--agent',
+ 'agent_xyz',
+ '--tenant',
+ 'T1',
+ ]);
+ expect(mockTrpcClient.messenger.setActiveAgent.mutate).toHaveBeenCalledWith({
+ agentId: 'agent_xyz',
+ platform: 'slack',
+ tenantId: 'T1',
+ });
+ });
+
+ it('clears the agent when --agent none is passed', async () => {
+ mockTrpcClient.messenger.setActiveAgent.mutate.mockResolvedValueOnce({ success: true });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'links',
+ 'set-agent',
+ 'telegram',
+ '--agent',
+ 'none',
+ ]);
+ expect(mockTrpcClient.messenger.setActiveAgent.mutate).toHaveBeenCalledWith({
+ agentId: null,
+ platform: 'telegram',
+ tenantId: undefined,
+ });
+ });
+ });
+
+ describe('links unlink', () => {
+ it('passes platform + tenant to the unlink mutation with --yes', async () => {
+ mockTrpcClient.messenger.unlink.mutate.mockResolvedValueOnce({ success: true });
+ await createProgram().parseAsync([
+ 'node',
+ 'test',
+ 'bot',
+ 'messengers',
+ 'links',
+ 'unlink',
+ 'slack',
+ '--tenant',
+ 'T1',
+ '--yes',
+ ]);
+ expect(mockTrpcClient.messenger.unlink.mutate).toHaveBeenCalledWith({
+ platform: 'slack',
+ tenantId: 'T1',
+ });
+ });
+ });
+});
diff --git a/apps/cli/src/commands/botMessengers.ts b/apps/cli/src/commands/botMessengers.ts
new file mode 100644
index 00000000000..25e240c2373
--- /dev/null
+++ b/apps/cli/src/commands/botMessengers.ts
@@ -0,0 +1,305 @@
+/**
+ * `lh bot messengers ...` — manages the user's System Bot installations
+ * (Slack workspaces, Discord guilds, Telegram), distinct from per-agent bots.
+ *
+ * Mirrors `bot ...` (per-agent CRUD) and `bot message ...` (send/read), but
+ * operates on `messenger_installations` (workspace-scoped) and
+ * `messenger_account_links` (per-user routing). Subcommands talk directly to
+ * `lambdaClient.messenger.*` — there's no shared CLI-side service layer for
+ * this domain yet.
+ *
+ * **uninstall vs unlink** (recurring confusion — surface in command help):
+ * - `uninstall <installationId>` revokes the install for the **whole
+ * workspace**. Other users in that workspace can no longer use the bot.
+ * - `links unlink <platform>` only removes the **current user's** account
+ * binding. Workspace stays installed; colleagues are unaffected.
+ */
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { confirm, outputJson, printTable } from '../utils/format';
+
+const PLATFORMS = ['telegram', 'slack', 'discord'] as const;
+type MessengerPlatform = (typeof PLATFORMS)[number];
+
+const validatePlatform = (value: string): MessengerPlatform => {
+ if (!(PLATFORMS as readonly string[]).includes(value)) {
+ throw new Error(`Unknown messenger platform: ${value}. Valid values: ${PLATFORMS.join(', ')}.`);
+ }
+ return value as MessengerPlatform;
+};
+
+export function registerBotMessengersCommands(bot: Command) {
+ const messengers = bot
+ .command('messengers')
+ .description(
+ 'Manage System Bot messenger installations (Slack workspaces, Discord guilds, Telegram) ' +
+ 'and per-user account links',
+ );
+
+ // ── installations ──────────────────────────────────────
+
+ messengers
+ .command('list')
+ .description('List all System Bot installations the current user has connected.')
+ .option('--json', 'Output JSON')
+ .action(async (options: { json?: boolean }) => {
+ const client = await getTrpcClient();
+ const installations = await client.messenger.listMyInstallations.query();
+
+ if (options.json) {
+ outputJson(installations);
+ return;
+ }
+
+ if (installations.length === 0) {
+ console.log('No System Bot installations connected.');
+ console.log(
+ `\nRun ${pc.dim('lh bot messengers platforms')} to see what's available, then install via ` +
+ `${pc.dim('Settings → Messenger')} (OAuth requires a browser).`,
+ );
+ return;
+ }
+
+ const rows = installations.map((i: any) => [
+ i.id || '',
+ i.platform || '',
+ i.tenantName || i.tenantId || '(global)',
+ i.applicationId || '',
+ i.installedAt ? new Date(i.installedAt).toISOString().slice(0, 10) : '',
+ ]);
+ printTable(rows, ['INSTALLATION ID', 'PLATFORM', 'TENANT', 'APP ID', 'INSTALLED']);
+ console.log(
+ `\nUse ${pc.dim('@<INSTALLATION ID>')} as the positional argument on ` +
+ `${pc.dim('lh bot message send/dm/thread reply')} to route through a System Bot install.`,
+ );
+ });
+
+ messengers
+ .command('view <installationId>')
+ .description('Show detail for one installation.')
+ .option('--json', 'Output JSON')
+ .action(async (installationId: string, options: { json?: boolean }) => {
+ const client = await getTrpcClient();
+ const installations = (await client.messenger.listMyInstallations.query()) as any[];
+ const install = installations.find((i) => i.id === installationId);
+
+ if (!install) {
+ // Under `--json`, scripts need a parseable output even on miss —
+ // emit `null` to stdout (rather than a human-readable error), then
+ // exit non-zero so error handling still works in pipelines.
+ if (options.json) {
+ outputJson(null);
+ } else {
+ console.error(pc.red(`Installation not found: ${installationId}`));
+ }
+ process.exit(1);
+ return;
+ }
+
+ if (options.json) {
+ outputJson(install);
+ return;
+ }
+
+ console.log(`${pc.bold('Installation')} ${pc.dim(install.id)}`);
+ console.log(` Platform: ${install.platform}`);
+ console.log(` Tenant: ${install.tenantName || install.tenantId || '(global)'}`);
+ if (install.tenantId && install.tenantName) {
+ console.log(` Tenant ID: ${install.tenantId}`);
+ }
+ console.log(` Application ID: ${install.applicationId}`);
+ if (install.scope) console.log(` OAuth Scope: ${install.scope}`);
+ if (install.installedAt) {
+ console.log(` Installed: ${new Date(install.installedAt).toISOString()}`);
+ }
+ if (install.enterpriseId) {
+ console.log(` Enterprise ID: ${install.enterpriseId}`);
+ }
+ if (install.isEnterpriseInstall) {
+ console.log(` Enterprise: yes`);
+ }
+ });
+
+ messengers
+ .command('uninstall <installationId>')
+ .description(
+ 'Revoke a workspace install. AFFECTS EVERY USER IN THAT WORKSPACE — for Slack this freezes ' +
+ 'the bot; for Discord it removes the audit entry (a guild admin must remove the bot ' +
+ 'separately). To disconnect only your own account, use `bot messengers links unlink`.',
+ )
+ .option('--yes', 'Skip confirmation prompt')
+ .action(async (installationId: string, options: { yes?: boolean }) => {
+ const client = await getTrpcClient();
+
+ if (!options.yes) {
+ const installations = (await client.messenger.listMyInstallations.query()) as any[];
+ const install = installations.find((i) => i.id === installationId);
+ const label = install
+ ? `${install.platform} (${install.tenantName || install.tenantId || 'global'})`
+ : installationId;
+ const ok = await confirm(
+ `${pc.yellow('⚠')} Uninstall ${pc.bold(label)} — this revokes the install for the whole workspace. Continue?`,
+ );
+ if (!ok) {
+ console.log('Aborted.');
+ return;
+ }
+ }
+
+ await client.messenger.uninstallInstallation.mutate({ installationId });
+ console.log(`${pc.green('✓')} Installation ${pc.dim(installationId)} revoked.`);
+ });
+
+ messengers
+ .command('platforms')
+ .description('List the platforms available for System Bot OAuth install.')
+ .option('--json', 'Output JSON')
+ .action(async (options: { json?: boolean }) => {
+ const client = await getTrpcClient();
+ const platforms = await client.messenger.availablePlatforms.query();
+
+ if (options.json) {
+ outputJson(platforms);
+ return;
+ }
+
+ if (platforms.length === 0) {
+ console.log('No System Bot platforms are configured on this deployment.');
+ return;
+ }
+
+ const rows = platforms.map((p: any) => [
+ p.id || '',
+ p.name || '',
+ p.appId || '',
+ p.botUsername || '',
+ ]);
+ printTable(rows, ['ID', 'NAME', 'APP ID', 'BOT USERNAME']);
+ console.log(
+ `\nInstalls are initiated via ${pc.dim('Settings → Messenger')} in the web UI ` +
+ '(OAuth needs a browser).',
+ );
+ });
+
+ // ── account links ──────────────────────────────────────
+
+ const links = messengers
+ .command('links')
+ .description('Manage per-user account links — routing of inbound IM to your agents');
+
+ links
+ .command('list')
+ .description('List all your account links across platforms and tenants.')
+ .option('--json', 'Output JSON')
+ .action(async (options: { json?: boolean }) => {
+ const client = await getTrpcClient();
+ const linkRows = await client.messenger.listMyLinks.query();
+
+ if (options.json) {
+ outputJson(linkRows);
+ return;
+ }
+
+ if (linkRows.length === 0) {
+ console.log('No account links yet. Complete verify-im on a platform first.');
+ return;
+ }
+
+ const rows = linkRows.map((l: any) => [
+ l.platform || '',
+ l.tenantId || '(global)',
+ l.activeAgentId || pc.dim('(unset)'),
+ l.platformUsername || l.platformUserId || '',
+ ]);
+ printTable(rows, ['PLATFORM', 'TENANT', 'ACTIVE AGENT', 'PLATFORM USER']);
+ });
+
+ links
+ .command('view <platform>')
+ .description('Show one account link.')
+ .option('--tenant <id>', 'Tenant scope (Slack workspace id). Omit for global-bot platforms.')
+ .option('--json', 'Output JSON')
+ .action(async (platform: string, options: { json?: boolean; tenant?: string }) => {
+ const client = await getTrpcClient();
+ const platformValidated = validatePlatform(platform);
+ const link = await client.messenger.getMyLink.query({
+ platform: platformValidated,
+ tenantId: options.tenant,
+ });
+
+ if (!link) {
+ console.error(
+ pc.red(
+ `No link found for ${platform}${options.tenant ? ` (tenant ${options.tenant})` : ''}`,
+ ),
+ );
+ process.exit(1);
+ return;
+ }
+
+ if (options.json) {
+ outputJson(link);
+ return;
+ }
+
+ console.log(`${pc.bold('Link')} ${pc.dim(link.platform)}`);
+ if (link.tenantId) console.log(` Tenant ID: ${link.tenantId}`);
+ console.log(` Platform User ID: ${link.platformUserId}`);
+ if (link.platformUsername) {
+ console.log(` Platform User: ${link.platformUsername}`);
+ }
+ console.log(` Active Agent: ${link.activeAgentId ?? pc.dim('(unset)')}`);
+ });
+
+ links
+ .command('set-agent <platform>')
+ .description('Change which agent receives inbound IM on a platform link.')
+ .requiredOption('--agent <id>', 'Agent id to route to, or "none" to clear the active agent.')
+ .option('--tenant <id>', 'Tenant scope (Slack workspace id). Omit for global-bot platforms.')
+ .action(async (platform: string, options: { agent: string; tenant?: string }) => {
+ const client = await getTrpcClient();
+ const platformValidated = validatePlatform(platform);
+ const agentId = options.agent === 'none' ? null : options.agent;
+
+ await client.messenger.setActiveAgent.mutate({
+ agentId,
+ platform: platformValidated,
+ tenantId: options.tenant,
+ });
+
+ const scope = options.tenant ? ` (tenant ${options.tenant})` : '';
+ const target = agentId === null ? 'cleared' : `set to agent ${pc.dim(agentId)}`;
+ console.log(`${pc.green('✓')} Active agent for ${platform}${scope} ${target}.`);
+ });
+
+ links
+ .command('unlink <platform>')
+ .description(
+ 'Remove your account link for a platform. Workspace install is unaffected — colleagues ' +
+ 'can still use the bot.',
+ )
+ .option('--tenant <id>', 'Tenant scope (Slack workspace id). Omit for global-bot platforms.')
+ .option('--yes', 'Skip confirmation prompt')
+ .action(async (platform: string, options: { tenant?: string; yes?: boolean }) => {
+ const client = await getTrpcClient();
+ const platformValidated = validatePlatform(platform);
+
+ if (!options.yes) {
+ const ok = await confirm(
+ `Unlink your account from ${pc.bold(platform)}${options.tenant ? ` (tenant ${options.tenant})` : ''}?`,
+ );
+ if (!ok) {
+ console.log('Aborted.');
+ return;
+ }
+ }
+
+ await client.messenger.unlink.mutate({
+ platform: platformValidated,
+ tenantId: options.tenant,
+ });
+ console.log(`${pc.green('✓')} Unlinked.`);
+ });
+}
diff --git a/docs/usage/channels/discord.mdx b/docs/usage/channels/discord.mdx
index a8f8f8fd947..c0ab7cc2217 100644
--- a/docs/usage/channels/discord.mdx
+++ b/docs/usage/channels/discord.mdx
@@ -117,6 +117,8 @@ By connecting a Discord channel to your LobeHub agent, users can interact with t
![](https://hub-apac-1.lobeobjects.space/docs/d83686461d14690e87512491c1349b6b.webp)
Copy the generated URL, open it in your browser, select the server you want to add the bot to, and click **Authorize**.
+
+ > **Private channels need explicit access.** Server-level authorization only grants the bot category/server defaults. If a channel is marked **Private Channel**, Discord ignores the bot's server-wide role and the bot won't receive any events there — including @mentions — until you open the channel's **Settings → Permissions** and add the bot (or a role it has) under **Members and roles**. You can also click **Sync Now** to make the channel inherit its category's permissions.
</Steps>
## Step 4: Test the Connection
@@ -191,5 +193,6 @@ See the [Channels overview](/docs/usage/channels/overview#direct-message-policy)
## Troubleshooting
- **Bot not responding in server:** Confirm the bot has been invited to the server with the correct permissions, and Message Content Intent is enabled. If **Group Policy** is `Disabled` or `Allowlist`, double-check the channel is in **Allowed Channel IDs**. If **Allowed User IDs** is set, the sender's user ID must be in it.
+- **@mention doesn't reach the bot in one specific channel:** The channel is likely a **Private Channel**. Discord drops every event for users/bots not explicitly listed in that channel's permissions, no matter what server-wide role they have. Open the channel's **Settings → Permissions**, click **Add members or roles**, and add the bot (or a role it has). Alternatively click **Sync Now** to inherit the parent category's permissions. A quick visual check: if the bot's name renders without an underline/link styling when you type `@<botname>`, Discord thinks it has no access to that channel.
- **Bot not responding to DMs:** Open **Advanced Settings** and confirm **DM Policy** is not set to `Disabled`. If **Allowed User IDs** is set, make sure the sender's Discord user ID is in it.
- **Test Connection failed:** Double-check the Application ID, Bot Token, and Public Key are correct.
diff --git a/docs/usage/channels/discord.zh-CN.mdx b/docs/usage/channels/discord.zh-CN.mdx
index 3962b953338..d6ebf3da847 100644
--- a/docs/usage/channels/discord.zh-CN.mdx
+++ b/docs/usage/channels/discord.zh-CN.mdx
@@ -116,6 +116,8 @@ tags:
![](https://hub-apac-1.lobeobjects.space/docs/2f6350e6bfe770e0e64b18762af3b63e.webp)
复制生成的链接,在浏览器中打开,选择您希望添加机器人的服务器,然后点击 **授权**。
+
+ > **私有频道需要单独授权。** 服务器层级的授权只会给机器人分类 / 服务器的默认权限。如果某个频道开启了 **Private Channel(私有频道)**,Discord 会忽略机器人在服务器层级的角色,机器人在该频道收不到任何事件(包括 @提及),直到你在频道的 **设置 → Permissions(权限)** 中点击 **Add members or roles**,把机器人本身或它持有的角色加进来。也可以直接点 **Sync Now** 让频道继承分类的权限。
</Steps>
## 第四步:测试连接
@@ -190,5 +192,6 @@ LobeHub 通过三层叠加配置控制入站消息,全部位于 **高级设置
## 故障排除
- **机器人未在服务器中响应:** 确认机器人已被邀请到服务器并拥有正确的权限,同时启用了消息内容意图。如果 **群组策略** 是 `Disabled` 或 `Allowlist`,确认目标频道在 **允许的频道 ID** 列表里。如果 **允许的用户 ID** 已填,发送者的用户 ID 必须在列表里。
+- **某个频道里 @不到机器人:** 通常是因为该频道是 **Private Channel(私有频道)**。Discord 会丢弃所有未被显式加入频道权限列表的用户 / 机器人的事件,无论他们在服务器层级是什么角色。打开该频道的 **设置 → Permissions(权限)**,点击 **Add members or roles**,把机器人或它持有的角色加进来;或者点 **Sync Now** 让频道继承父分类的权限。一个快速肉眼判断:输入 `@<机器人名>` 时如果出现的机器人名字没有下划线 / 链接样式,说明 Discord 认为它无权访问该频道。
- **机器人不回私信:** 打开 **高级设置**,确认 **私信策略** 不是 `Disabled`。如果 **允许的用户 ID** 已填,确认发起方的 Discord 用户 ID 在列表里。
- **测试连接失败:** 仔细检查应用程序 ID、机器人令牌和公钥是否正确。
diff --git a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts b/packages/builtin-tool-message/src/ExecutionRuntime/index.ts
index 660d1bb5d0e..0ef0677b55d 100644
--- a/packages/builtin-tool-message/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-message/src/ExecutionRuntime/index.ts
@@ -22,18 +22,29 @@ import type {
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,
PinMessageParams,
PinMessageState,
PlatformInfo,
@@ -49,8 +60,14 @@ import type {
SendDirectMessageState,
SendMessageParams,
SendMessageState,
+ SetMessengerActiveAgentParams,
+ SetMessengerActiveAgentState,
ToggleBotParams,
ToggleBotState,
+ UninstallMessengerParams,
+ UninstallMessengerState,
+ UnlinkMessengerParams,
+ UnlinkMessengerState,
UnpinMessageParams,
UnpinMessageState,
UpdateBotParams,
@@ -80,18 +97,29 @@ export type {
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,
PinMessageParams,
PinMessageState,
PlatformInfo,
@@ -108,8 +136,14 @@ export type {
SendMessageAttachment,
SendMessageParams,
SendMessageState,
+ SetMessengerActiveAgentParams,
+ SetMessengerActiveAgentState,
ToggleBotParams,
ToggleBotState,
+ UninstallMessengerParams,
+ UninstallMessengerState,
+ UnlinkMessengerParams,
+ UnlinkMessengerState,
UnpinMessageParams,
UnpinMessageState,
UpdateBotParams,
@@ -158,9 +192,26 @@ export interface BotProviderQuery {
}) => 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[]>;
+ /** 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> },
@@ -689,4 +740,204 @@ export class MessageExecutionRuntime {
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 installations connected. Tell the user to install 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 installation(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: `Workspace install ${params.installationId} revoked. The bot is now disconnected for everyone in that workspace.`,
+ 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 };
+ }
+ }
}
diff --git a/packages/builtin-tool-message/src/executor/index.ts b/packages/builtin-tool-message/src/executor/index.ts
index 56815a16625..e16f7635b09 100644
--- a/packages/builtin-tool-message/src/executor/index.ts
+++ b/packages/builtin-tool-message/src/executor/index.ts
@@ -13,9 +13,13 @@ import type {
GetBotDetailParams,
GetChannelInfoParams,
GetMemberInfoParams,
+ GetMessengerDetailParams,
GetReactionsParams,
ListBotsParams,
ListChannelsParams,
+ ListMessengerLinksParams,
+ ListMessengerPlatformsParams,
+ ListMessengersParams,
ListPinsParams,
ListPlatformsParams,
ListThreadsParams,
@@ -26,7 +30,10 @@ import type {
SearchMessagesParams,
SendDirectMessageParams,
SendMessageParams,
+ SetMessengerActiveAgentParams,
ToggleBotParams,
+ UninstallMessengerParams,
+ UnlinkMessengerParams,
UnpinMessageParams,
UpdateBotParams,
} from '../types';
@@ -242,6 +249,57 @@ class MessageExecutor extends BaseExecutor<typeof MessageApiName> {
): Promise<BuiltinToolResult> => {
return this.runtime.connectBot(params);
};
+
+ // ==================== System Bot Messenger Management ====================
+
+ listMessengers = async (
+ params: ListMessengersParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ return this.runtime.listMessengers(params);
+ };
+
+ getMessengerDetail = async (
+ params: GetMessengerDetailParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ return this.runtime.getMessengerDetail(params);
+ };
+
+ uninstallMessenger = async (
+ params: UninstallMessengerParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ return this.runtime.uninstallMessenger(params);
+ };
+
+ listMessengerPlatforms = async (
+ params: ListMessengerPlatformsParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ return this.runtime.listMessengerPlatforms(params);
+ };
+
+ listMessengerLinks = async (
+ params: ListMessengerLinksParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ return this.runtime.listMessengerLinks(params);
+ };
+
+ setMessengerActiveAgent = async (
+ params: SetMessengerActiveAgentParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ return this.runtime.setMessengerActiveAgent(params);
+ };
+
+ unlinkMessenger = async (
+ params: UnlinkMessengerParams,
+ _ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ return this.runtime.unlinkMessenger(params);
+ };
}
export { MessageExecutor };
diff --git a/packages/builtin-tool-message/src/manifest.ts b/packages/builtin-tool-message/src/manifest.ts
index 774dfddaded..ac1dbb81e5d 100644
--- a/packages/builtin-tool-message/src/manifest.ts
+++ b/packages/builtin-tool-message/src/manifest.ts
@@ -5,6 +5,60 @@ import { MessageApiName, MessageToolIdentifier } from './types';
const platformEnum = ['discord', 'telegram', 'slack', 'feishu', 'lark', 'qq', 'wechat'];
+/**
+ * Shared schema fragment for the outbound `attachments` array on message-
+ * sending tools (`sendMessage`, `sendDirectMessage`, `replyToThread`). Mirrors
+ * the `SendMessageAttachment` TypeScript type and the TRPC zod schema.
+ *
+ * Either `data` (base64-encoded bytes) or `fetchUrl` (public URL the
+ * platform server can GET) must be provided. `fetchUrl` is preferred when
+ * the bytes already live somewhere reachable — base64 inflates the request
+ * payload ~33% and many platforms (LINE, QQ guild) can ONLY consume URLs.
+ *
+ * Platform support varies — see each platform's `sendAttachments` helper
+ * for the actual delivery shape:
+ * - WeChat / Discord / Telegram / Slack / Feishu / Lark: full support
+ * - LINE: image + HTTPS URL only; other types degrade to a text-link line
+ * - QQ: group / c2c only; guild / dms / data-only degrade to text-link
+ */
+const attachmentsSchema = {
+ description:
+ 'Optional outbound media attachments (images / files / video / audio). Each item must provide either `fetchUrl` (preferred — a public URL the platform server fetches) or `data` (base64-encoded bytes). When you have a stable public URL for the file, ALWAYS use `fetchUrl` — base64 bloats the payload and a few platforms (LINE, QQ guild) only accept URLs.',
+ items: {
+ additionalProperties: false,
+ properties: {
+ data: {
+ description:
+ 'Base64-encoded bytes. Use only when no public URL exists; prefer `fetchUrl`. Some platforms (LINE, QQ guild) cannot consume this and will fall back to a text-link mention of the attachment.',
+ type: 'string',
+ },
+ fetchUrl: {
+ description:
+ 'Public HTTPS URL the platform server can GET to retrieve the bytes. Preferred over `data`.',
+ type: 'string',
+ },
+ mimeType: {
+ description: 'MIME type (e.g. "image/png", "application/pdf"). Optional but helpful.',
+ type: 'string',
+ },
+ name: {
+ description:
+ 'Filename shown to the recipient (e.g. "report.pdf"). Optional; some platforms infer from URL.',
+ type: 'string',
+ },
+ type: {
+ description:
+ 'Media category. Drives which platform-specific endpoint is used (e.g. image → Telegram sendPhoto, file → Telegram sendDocument).',
+ enum: ['image', 'file', 'video', 'audio'],
+ type: 'string',
+ },
+ },
+ required: ['type'],
+ type: 'object',
+ },
+ type: 'array',
+};
+
/**
* Schema for the bot's `settings` JSON column. Both `createBot` and
* `updateBot` accept a partial object — only the keys you pass are written
@@ -106,15 +160,26 @@ export const MessageManifest: BuiltinToolManifest = {
// ==================== Direct Messaging ====================
{
description:
- 'Send a direct/private message to a user by their platform user ID. Creates a DM channel automatically. Use this when the user asks to "DM me" or "send me a private message".',
+ 'Send a direct/private message to a user by their platform user ID. Creates a DM channel automatically. Use this when the user asks to "DM me" or "send me a private message". Supports optional outbound media `attachments` (images / files / video / audio). To pick the target: call `listBots` for the platform first — if there\'s an entry, use its `botId`; otherwise call `listMessengers` and use that entry\'s `id` as `messengerInstallationId`.',
name: MessageApiName.sendDirectMessage,
parameters: {
additionalProperties: false,
properties: {
+ attachments: attachmentsSchema,
+ botId: {
+ description:
+ 'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',
+ type: 'string',
+ },
content: {
description: 'Message content',
type: 'string',
},
+ messengerInstallationId: {
+ description:
+ 'System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.',
+ type: 'string',
+ },
platform: {
description: 'Target messaging platform',
enum: platformEnum,
@@ -132,11 +197,18 @@ export const MessageManifest: BuiltinToolManifest = {
// ==================== Core Message Operations ====================
{
- description: 'Send a message to a specific channel or conversation on the target platform.',
+ description:
+ "Send a message to a specific channel or conversation on the target platform. Supports optional outbound media `attachments` (images / files / video / audio) — use this when you need to deliver a generated image, document, or other binary alongside your reply. To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",
name: MessageApiName.sendMessage,
parameters: {
additionalProperties: false,
properties: {
+ attachments: attachmentsSchema,
+ botId: {
+ description:
+ 'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',
+ type: 'string',
+ },
channelId: {
description: 'Channel / conversation / room ID to send the message to',
type: 'string',
@@ -147,10 +219,16 @@ export const MessageManifest: BuiltinToolManifest = {
type: 'string',
},
embeds: {
- description: 'Optional array of embed/attachment objects (platform-specific structure)',
+ description:
+ 'Optional array of platform-specific embed objects (Discord embeds, Slack blocks, etc.). For generic file/image delivery use `attachments` instead.',
items: { type: 'object' },
type: 'array',
},
+ messengerInstallationId: {
+ description:
+ 'System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.',
+ type: 'string',
+ },
platform: {
description: 'Target messaging platform',
enum: platformEnum,
@@ -550,15 +628,27 @@ export const MessageManifest: BuiltinToolManifest = {
},
},
{
- description: 'Send a reply to a thread.',
+ description:
+ "Send a reply to a thread. Supports optional outbound media `attachments` (images / files / video / audio). To pick the target: call `listBots` first — if there's an entry for the platform, use its `botId`; otherwise call `listMessengers` and use that entry's `id` as `messengerInstallationId`.",
name: MessageApiName.replyToThread,
parameters: {
additionalProperties: false,
properties: {
+ attachments: attachmentsSchema,
+ botId: {
+ description:
+ 'Per-agent bot id from `listBots`. Provide exactly one of `botId` or `messengerInstallationId`.',
+ type: 'string',
+ },
content: {
description: 'Reply message content',
type: 'string',
},
+ messengerInstallationId: {
+ description:
+ 'System Bot installation id from `listMessengers`. Provide exactly one of `botId` or `messengerInstallationId`.',
+ type: 'string',
+ },
platform: {
description: 'Target messaging platform',
enum: platformEnum,
@@ -629,7 +719,7 @@ export const MessageManifest: BuiltinToolManifest = {
},
{
description:
- 'List all configured bot integrations for the current agent. Use this first to discover which platforms are connected and get bot IDs.',
+ "List all per-agent bot integrations configured for the current agent (with runtime status). Returns this agent's per-agent bots only — use `listMessengers` to see the user's System Bot installations (a separate outbound channel source). For sending decisions, try `listBots` first; if it has no entry for the target platform, fall back to `listMessengers`.",
name: MessageApiName.listBots,
parameters: {
additionalProperties: false,
@@ -761,6 +851,117 @@ export const MessageManifest: BuiltinToolManifest = {
type: 'object',
},
},
+
+ // ==================== System Bot Messenger Management ====================
+ {
+ description:
+ "List the current user's LobeHub System Bot installations across workspaces (Slack workspaces, Discord guilds, Telegram). Each entry returns an `id` to pass back as `installationId` on `getMessengerDetail` / `uninstallMessenger`, or as `messengerInstallationId` on send APIs. Use this when the user asks about their connected workspaces, or as the fallback when `listBots` has no entry for the target platform.",
+ name: MessageApiName.listMessengers,
+ parameters: {
+ additionalProperties: false,
+ properties: {},
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Get detailed metadata about a single System Bot installation. Returns the same fields as `listMessengers` plus `revokedAt` (null when active). Use before `uninstallMessenger` to surface tenant info in the confirmation prompt.',
+ name: MessageApiName.getMessengerDetail,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ installationId: {
+ description: 'Stable installation id from `listMessengers`.',
+ type: 'string',
+ },
+ },
+ required: ['installationId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Revoke a System Bot workspace install. **This affects every user in that workspace** — for Slack it freezes the workspace's bot since dispatch is gated on the install token; for Discord it removes the audit entry (the bot itself stays in the guild until an admin removes it). Always confirm with the user before calling. To disconnect only the current user's account (not the whole workspace), use `unlinkMessenger` instead.",
+ name: MessageApiName.uninstallMessenger,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ installationId: {
+ description: 'Installation id to revoke.',
+ type: 'string',
+ },
+ },
+ required: ['installationId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'List the platforms where the user can install the LobeHub System Bot. Returns `appId` / `botUsername` for deep-link install URLs. Use when guiding the user through `Settings → Messenger` install for a new platform — note the actual install flow requires browser OAuth and cannot be initiated from this tool.',
+ name: MessageApiName.listMessengerPlatforms,
+ parameters: {
+ additionalProperties: false,
+ properties: {},
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "List the user's per-platform account links — one entry per (platform, tenant). Each link determines which agent receives inbound IM messages from that platform/tenant. Use before `setMessengerActiveAgent` to find the current routing.",
+ name: MessageApiName.listMessengerLinks,
+ parameters: {
+ additionalProperties: false,
+ properties: {},
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Change which agent receives inbound IM messages on a specific platform link. Pass `agentId: null` to clear the active agent (next message gets the "/agents to pick" prompt). Pass `tenantId` to scope to one Slack workspace; omit for Telegram (global bot).',
+ name: MessageApiName.setMessengerActiveAgent,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ agentId: {
+ description:
+ 'Agent id to route to, or null to clear. The agent must belong to the current user.',
+ type: ['string', 'null'],
+ },
+ platform: {
+ description: 'Target platform',
+ enum: platformEnum,
+ type: 'string',
+ },
+ tenantId: {
+ description: 'Optional tenant scope (Slack workspace id).',
+ type: 'string',
+ },
+ },
+ required: ['platform', 'agentId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Remove the current user's account link for a platform. The workspace install stays — other users can still use the System Bot in that workspace; only the current user's inbound routing is removed. To revoke the install for everyone, use `uninstallMessenger`.",
+ name: MessageApiName.unlinkMessenger,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ platform: {
+ description: 'Target platform',
+ enum: platformEnum,
+ type: 'string',
+ },
+ tenantId: {
+ description: 'Optional tenant scope (Slack workspace id).',
+ type: 'string',
+ },
+ },
+ required: ['platform'],
+ type: 'object',
+ },
+ },
],
identifier: MessageToolIdentifier,
meta: {
diff --git a/packages/builtin-tool-message/src/systemRole.ts b/packages/builtin-tool-message/src/systemRole.ts
index 9bc2a45f6a1..7db0005126c 100644
--- a/packages/builtin-tool-message/src/systemRole.ts
+++ b/packages/builtin-tool-message/src/systemRole.ts
@@ -12,15 +12,57 @@ export const systemPrompt = `You have access to a Message tool that provides uni
<bot_management>
1. **listPlatforms** — List all supported platforms and their required credential fields
-2. **listBots** — List configured bots for the current agent (with runtime status)
+2. **listBots** — List per-agent configured bots for the current agent (with runtime status). Also the primary discovery for sending — see \`<outbound_routing>\`.
3. **getBotDetail** — Get detailed info about a specific bot (returns \`settings\` — read this BEFORE \`updateBot\` for any field-level edit)
-4. **createBot** — Create a new bot integration (requires agentId, platform, applicationId, credentials; optional initial settings)
+4. **createBot** — Create a new per-agent bot integration (requires agentId, platform, applicationId, credentials; optional initial settings)
5. **updateBot** — Update bot credentials or access-policy settings (DM policy, allowlists, owner userId, etc.)
-6. **deleteBot** — Remove a bot integration
-7. **toggleBot** — Enable or disable a bot
-8. **connectBot** — Start a bot (establish connection to the platform)
+6. **deleteBot** — Remove a per-agent bot integration
+7. **toggleBot** — Enable or disable a per-agent bot
+8. **connectBot** — Start a per-agent bot (establish connection to the platform)
</bot_management>
+<outbound_routing>
+The send APIs (\`sendMessage\`, \`sendDirectMessage\`, \`replyToThread\`) can deliver through **two sources** — both use the same underlying platform clients (so attachments / formatting / rate behavior are identical), but they come from different lists:
+
+- **Per-agent bot** (pass \`botId\`) — the agent's own credentials, configured via \`createBot\`. Listed by \`listBots\`. Messages appear with the per-agent bot's identity.
+- **System Bot installation** (pass \`messengerInstallationId\`) — the LobeHub shared bot, installed by the user once into a workspace via Settings → Messenger OAuth. Listed by \`listMessengers\`. Messages appear with the LobeHub System Bot identity.
+
+**Two-step routing rule — apply in order:**
+
+1. **Call \`listBots\`.** If any entry has \`platform: "<target>"\` → use its \`botId\` on the send API. Done.
+2. **Otherwise call \`listMessengers\`.** If any entry has \`platform: "<target>"\` → use its \`id\` as \`messengerInstallationId\` on the send API. Done.
+3. **Neither has the platform → do NOT pick a different platform.** Tell the user: "I can't reach <platform> for you yet. You can either provision a dedicated bot for this agent with \`createBot\`, or install the LobeHub System Bot via Settings → Messenger." Stop.
+
+Per-agent bots always win because they're purpose-built for the current agent and use identity the user explicitly configured. Only fall back to System Bot when the agent has nothing for the platform. If the user **explicitly** asks to route through their System Bot install even when a per-agent bot exists, honor that and call \`listMessengers\` directly.
+
+The send APIs accept **exactly one** of \`botId\` / \`messengerInstallationId\` — the server will reject both-or-neither.
+</outbound_routing>
+
+<system_bot_management>
+The **System Bot** is the LobeHub-owned shared bot the user installs via \`Settings → Messenger\` OAuth. It's separate from per-agent bots (\`createBot\` / \`listBots\`). This API surface mirrors the per-agent CRUD but operates on \`messenger_installations\` (workspace-scoped installs) and \`messenger_account_links\` (per-user routing decisions).
+
+**Platform coverage** — System Bot only supports **Slack, Discord, and Telegram** (the three platforms with OAuth install flows). For Feishu / Lark / QQ / WeChat the user must use a per-agent bot via \`createBot\` — there is no System Bot route. \`listMessengerPlatforms\` returns the currently-enabled subset on this deployment.
+
+**Read**
+1. **listMessengers** — List the user's installs across workspaces. Returns \`installationId\`, \`platform\`, \`tenantId\`, \`tenantName\`, \`installedAt\`. Use this when the user asks about their connected workspaces.
+2. **getMessengerDetail** — Single install detail by \`installationId\`. Adds \`revokedAt\` (null when active). Use before \`uninstallMessenger\` so the confirmation prompt names the tenant.
+3. **listMessengerPlatforms** — Platforms available for OAuth install + their deep-link \`appId\` / \`botUsername\`. Use when guiding the user to install a new platform.
+4. **listMessengerLinks** — User's per-platform account links — one entry per (platform, tenantId) showing which agent receives inbound IM.
+
+**Mutate**
+5. **uninstallMessenger** — **Revokes the workspace install** for everyone in that workspace. For Slack this freezes the bot (dispatch is token-gated); for Discord it only removes the audit entry (an admin must remove the bot from the guild separately). **Always confirm with the user before calling** — surface the tenant name.
+6. **unlinkMessenger** — Removes only the **current user's account link** for one (platform, tenantId). Other users in the same workspace are unaffected. Use this when the user says "stop routing my Slack DMs here" — NOT \`uninstallMessenger\`, which is destructive for the whole workspace.
+7. **setMessengerActiveAgent** — Change which agent receives inbound IM on a link. Pass \`agentId: null\` to clear the active agent. Scope to one workspace via \`tenantId\`; omit for global-bot platforms (Telegram). The agent must belong to the current user — server rejects cross-user ids.
+
+**Critical disambiguation — \`uninstallMessenger\` vs \`unlinkMessenger\`:**
+- "remove my account from Slack" / "stop receiving DMs from this workspace on my LobeHub" → \`unlinkMessenger\`
+- "uninstall the LobeHub bot from my workspace" / "remove the integration for everyone" → \`uninstallMessenger\` (workspace-admin level decision)
+
+When in doubt, ask. Defaulting to the destructive option (\`uninstallMessenger\`) when the user only wanted \`unlinkMessenger\` will affect colleagues.
+
+**Why there's no \`createMessenger\`**: OAuth install requires browser redirect — the tool cannot start the flow. When \`listMessengers\` returns nothing for a platform the user wants, tell them: "Open \`Settings → Messenger\` and install for <platform>". You can list the available platforms via \`listMessengerPlatforms\` and surface the \`appId\` so the user knows what they're installing.
+</system_bot_management>
+
<access_policies>
The bot's \`settings\` JSON column controls **who can talk to the bot** on every platform. Use \`updateBot({ botId, settings: {...} })\` to change any of the keys below. Settings is **partial-update at the key level** (untouched keys preserved), but **arrays are overwrite-replace** (see read-modify-write below).
@@ -62,27 +104,49 @@ Skipping step 1 will silently wipe other entries.
</access_policies>
<messaging_capabilities>
-1. **sendDirectMessage** — Send a private/direct message to a user by their platform user ID (auto-creates DM channel)
-2. **sendMessage** — Send a message to a channel or conversation
-2. **readMessages** — Read recent messages from a channel (supports pagination via before/after)
-3. **editMessage** — Edit an existing message (author only)
-4. **deleteMessage** — Delete a message (requires permissions)
-5. **searchMessages** — Search messages by query, optionally filter by author
-6. **reactToMessage** — Add an emoji reaction to a message
-7. **getReactions** — List reactions on a message
-8. **pinMessage** / **unpinMessage** / **listPins** — Pin management
-9. **getChannelInfo** — Get channel details (name, description, member count)
-10. **listChannels** — List channels in a server/workspace
-11. **getMemberInfo** — Get member profile information
-12. **createThread** / **listThreads** / **replyToThread** — Thread operations
-13. **createPoll** — Create a poll (Discord, Telegram)
+1. **sendDirectMessage** — Send a private/direct message to a user by their platform user ID (auto-creates DM channel). Supports **\`attachments\`** for outbound media (see \`<attachments>\`).
+2. **sendMessage** — Send a message to a channel or conversation. Supports **\`attachments\`** for outbound media.
+3. **readMessages** — Read recent messages from a channel (supports pagination via before/after)
+4. **editMessage** — Edit an existing message (author only)
+5. **deleteMessage** — Delete a message (requires permissions)
+6. **searchMessages** — Search messages by query, optionally filter by author
+7. **reactToMessage** — Add an emoji reaction to a message
+8. **getReactions** — List reactions on a message
+9. **pinMessage** / **unpinMessage** / **listPins** — Pin management
+10. **getChannelInfo** — Get channel details (name, description, member count)
+11. **listChannels** — List channels in a server/workspace
+12. **getMemberInfo** — Get member profile information
+13. **createThread** / **listThreads** / **replyToThread** — Thread operations. \`replyToThread\` supports **\`attachments\`**.
+14. **createPoll** — Create a poll (Discord, Telegram)
</messaging_capabilities>
+<attachments>
+\`sendMessage\`, \`sendDirectMessage\`, and \`replyToThread\` accept an optional **\`attachments\`** array for outbound media — use it when you've generated an image / file / video / audio that the user should receive alongside (or instead of) text.
+
+Each item is \`{ type: 'image' | 'file' | 'video' | 'audio', name?, mimeType?, fetchUrl?, data? }\`. **Exactly one of \`fetchUrl\` or \`data\` is required per item.**
+
+**Source preference — always prefer \`fetchUrl\`:**
+- \`fetchUrl\` (a public HTTPS URL the platform server fetches): ~zero overhead, works on every supported platform, and a few platforms (LINE images, QQ guild) can ONLY consume URLs.
+- \`data\` (base64-encoded bytes inline): inflates the request payload by ~33%, eats tool-call budget, and silently degrades on LINE / QQ-guild to a text-link fallback. Only use when you have no fetchable URL.
+
+**Per-platform reality (silent degradation rules):**
+- **WeChat** — full support; one item per iLink sendmessage call (protocol §6.7).
+- **Discord** — full support; up to 10 attachments per message (extra auto-batched).
+- **Telegram** — \`image\`→sendPhoto, \`file\`→sendDocument, \`video\`→sendVideo, \`audio\`→sendAudio. First item carries \`content\` as caption (1024-char cap, auto-truncated).
+- **Slack** — v2 \`files.completeUploadExternal\`; \`content\` rides as \`initial_comment\` on the same message.
+- **Feishu / Lark** — image / file / video / audio all upload-then-send; text is delivered as its own message first (Lark has no composite text+media).
+- **LINE** — only \`image\` + HTTPS URL works as typed media; \`video\` / \`audio\` / \`file\` / data-only items degrade to a text-link line. LINE has no native push-API \`file\` message.
+- **QQ** — group + c2c support full rich-media (URL only — base64 degrades). Guild + DMS degrade everything to text-links.
+
+For platforms with degradation rules, prefer URL-sourced \`image\` attachments when you want maximum compatibility. The runtime never throws on a degraded attachment — it logs and falls back so the reply still reaches the user.
+</attachments>
+
<usage_guidelines>
-- When the user asks about bots or messaging from the web UI, call \`listBots\` first to discover configured bots (one call returns all). When you are already inside a platform conversation (e.g. replying in a Discord channel), you already have the context — skip \`listBots\` and use the current channel directly.
+- **Before any send (\`sendMessage\` / \`sendDirectMessage\` / \`replyToThread\`)** from the web UI, follow the two-step rule in \`<outbound_routing>\`: \`listBots\` first; if it has no entry for the target platform, fall back to \`listMessengers\`.
+- When you are already inside a platform conversation (e.g. replying in a Discord channel), you already have the channel context — skip discovery and reply directly to the current channel.
- **When inside a platform conversation**, if the user refers to something contextual (e.g. "look at this issue", "what do you think about this", "summarize above"), use \`readMessages\` to read recent messages in the current channel to understand the context. Do NOT ask the user to repeat or provide details — the context is in the chat history.
-- If no bots are configured, use \`listPlatforms\` to show available platforms and guide the user to set one up via \`createBot\`
-- When the user asks to "DM me" or "send me a private message", use \`sendDirectMessage\`. If \`userId\` is available from \`listBots\`, use it directly. If not, ask the user for their platform user ID.
+- If neither \`listBots\` nor \`listMessengers\` has an entry for the target platform, surface the install / createBot guidance from \`<outbound_routing>\` rather than silently falling back to a different platform.
+- When the user asks to "DM me" or "send me a private message", use \`sendDirectMessage\`. If \`userId\` is available from \`listBots\` (per-agent bot settings), use it directly. If not, ask the user for their platform user ID.
- **Never ask the user for channel IDs.** Use \`listChannels\` to discover channels yourself. If \`serverId\` is available from \`listBots\`, use it directly. If not, ask the user for the server/guild ID.
- When the user references a channel by name (e.g. "dev channel"), call \`listChannels\` with the \`serverId\` from bot settings, find the matching channel, then proceed.
- \`readMessages\`: \`channelId\` and \`platform\` are **required**. All other parameters are **optional** — omit them when not needed. \`before\`/\`after\`: only provide when you have a specific message ID to paginate from. Do NOT pass empty strings — omit entirely. For quick context (e.g. "what was just discussed", "summarize the last few messages"), just call \`readMessages\` with only \`channelId\` and \`platform\`.
@@ -120,12 +184,13 @@ Skipping step 1 will silently wipe other entries.
- Supports sending messages to groups, guild channels, and direct messages
- Very limited operations: only sendMessage is available
- channelId format includes thread type prefix (e.g., "group:id" or "guild:id")
+- Outbound attachments: group + c2c support image/video/voice/file via rich-media upload (URL only — \`data\` base64 isn't accepted by QQ's upload API and degrades to a text-link). Guild + DMS degrade all attachments to text-links.
**WeChat:**
- Uses iLink Bot API with long-polling for message delivery
- Sending messages requires a context token from an active conversation
- Only sendMessage is available, and only within active conversation context
-- Outbound text, images, files, and videos are supported (each media item is sent as a separate message per protocol)
+- Outbound attachments: full support — text, images, files, videos, audio. Each media item is sent as a separate iLink sendmessage call per protocol §6.7.
- Message operations may fail if no active conversation context exists
</platform_notes>
`;
diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.ts
index 44a989167ea..89bbd6662e1 100644
--- a/packages/builtin-tool-message/src/types.ts
+++ b/packages/builtin-tool-message/src/types.ts
@@ -58,6 +58,26 @@ export const MessageApiName = {
listPlatforms: 'listPlatforms',
toggleBot: 'toggleBot',
updateBot: 'updateBot',
+
+ // ==================== System Bot Messenger Management ====================
+ // Operates on `messenger_installations` (workspace-scoped OAuth installs)
+ // and `messenger_account_links` (per-user routing decisions). Mirrors the
+ // per-agent bot CRUD surface but for the LobeHub System Bot, which can't
+ // be created via tool calls (OAuth requires browser flow).
+ /** List the current user's System Bot installations across workspaces. */
+ listMessengers: 'listMessengers',
+ /** Get one install's detail by installationId. */
+ getMessengerDetail: 'getMessengerDetail',
+ /** Revoke a workspace install (cascades to all users in that workspace). */
+ uninstallMessenger: 'uninstallMessenger',
+ /** List the platforms where the user can install the LobeHub System Bot. */
+ listMessengerPlatforms: 'listMessengerPlatforms',
+ /** List the user's account links — one row per (platform, tenant). */
+ listMessengerLinks: 'listMessengerLinks',
+ /** Change which agent receives inbound IM on a specific link. */
+ setMessengerActiveAgent: 'setMessengerActiveAgent',
+ /** Remove the user's account link for a platform (does not uninstall). */
+ unlinkMessenger: 'unlinkMessenger',
} as const;
export type MessageApiNameType = (typeof MessageApiName)[keyof typeof MessageApiName];
@@ -76,6 +96,11 @@ export interface MessageTarget {
// --- Direct Messaging ---
export interface SendDirectMessageParams {
+ /**
+ * Optional: outbound media attachments (images / files / video / audio).
+ * Same shape as `SendMessageParams.attachments` — see `SendMessageAttachment`.
+ */
+ attachments?: SendMessageAttachment[];
/** Message content */
content: string;
/** Platform */
@@ -373,6 +398,11 @@ export interface ListThreadsState {
}
export interface ReplyToThreadParams {
+ /**
+ * Optional: outbound media attachments (images / files / video / audio).
+ * Same shape as `SendMessageParams.attachments` — see `SendMessageAttachment`.
+ */
+ attachments?: SendMessageAttachment[];
/** Reply content */
content: string;
/** Platform */
@@ -513,3 +543,132 @@ export interface ConnectBotParams {
export interface ConnectBotState {
status: string;
}
+
+// --- System Bot Messenger Management ---
+
+/**
+ * Summary of a System Bot installation surfaced to the LLM / caller. Mirrors
+ * the safe metadata shape returned by `messenger.listMyInstallations` — never
+ * the credentials.
+ */
+export interface MessengerInfo {
+ /** Platform application/bot id (Slack appId, Discord applicationId, …). */
+ applicationId: string;
+ /** Slack-only: enterprise grid id when this is an enterprise install. */
+ enterpriseId?: string | null;
+ /** Stable installation id — pass back on `uninstallMessenger` / `getMessengerDetail`. */
+ id: string;
+ /** ISO timestamp of when the install was created (or Date instance). */
+ installedAt?: string | Date;
+ /** Slack-only: whether this install is at the enterprise (org-wide) level. */
+ isEnterpriseInstall?: boolean;
+ /** Messaging platform (slack / discord / telegram / …). */
+ platform: string;
+ /** OAuth scope string granted at install time (Slack-only typically). */
+ scope?: string;
+ /** Tenant identifier — Slack workspace, Discord guild, … (empty for Telegram). */
+ tenantId: string;
+ /** Optional human-friendly tenant label (workspace / guild name). */
+ tenantName?: string;
+}
+
+/**
+ * Summary of a user-platform account link. One row per (userId, platform,
+ * tenantId) — controls which agent the user's inbound IM messages route to.
+ */
+export interface MessengerLinkInfo {
+ /** The agent currently set as active for inbound messages (null = unset). */
+ activeAgentId: string | null;
+ /** When the link was created. */
+ createdAt?: string | Date;
+ platform: string;
+ /** Platform-side user id (Slack user id, Discord user id, Telegram chat id). */
+ platformUserId?: string;
+ /** Display name surfaced when verify-im completed. */
+ platformUsername?: string;
+ /** Tenant scope for the link — empty for global-bot platforms (Telegram). */
+ tenantId?: string;
+}
+
+/**
+ * Subset of `messenger.availablePlatforms` payload surfaced to the LLM.
+ * Includes the deep-link fields the verify-im flow uses to direct the user
+ * to the right install URL.
+ */
+export interface MessengerPlatformInfo {
+ /** Slack appId or Discord applicationId — feeds deep-link URLs. */
+ appId?: string;
+ /** Telegram-only deep-link target (`https://t.me/<botUsername>`). */
+ botUsername?: string;
+ /** Platform id (slack / discord / telegram / …). */
+ id: string;
+ /** Display name. */
+ name: string;
+}
+
+export interface ListMessengersParams {
+ /** No parameters needed — returns all installs for the current user. */
+}
+
+export interface ListMessengersState {
+ installations: MessengerInfo[];
+}
+
+export interface GetMessengerDetailParams {
+ /** Stable installation id from `listMessengers`. */
+ installationId: string;
+}
+
+export interface GetMessengerDetailState extends MessengerInfo {
+ /** ISO timestamp of when the install was revoked (null when active). */
+ revokedAt?: string | Date | null;
+}
+
+export interface UninstallMessengerParams {
+ installationId: string;
+}
+
+export interface UninstallMessengerState {
+ success: boolean;
+}
+
+export interface ListMessengerPlatformsParams {
+ /** No parameters needed. */
+}
+
+export interface ListMessengerPlatformsState {
+ platforms: MessengerPlatformInfo[];
+}
+
+export interface ListMessengerLinksParams {
+ /** No parameters needed — returns all links for the current user. */
+}
+
+export interface ListMessengerLinksState {
+ links: MessengerLinkInfo[];
+}
+
+export interface SetMessengerActiveAgentParams {
+ /**
+ * Agent id to route inbound messages to. Pass `null` to clear the active
+ * agent (next message hits the "/agents to pick" prompt).
+ */
+ agentId: string | null;
+ platform: string;
+ /** Optional: scope to a specific workspace (Slack). Omit for global-bot platforms. */
+ tenantId?: string;
+}
+
+export interface SetMessengerActiveAgentState {
+ success: boolean;
+}
+
+export interface UnlinkMessengerParams {
+ platform: string;
+ /** Optional: scope to a specific workspace (Slack). Omit for global-bot platforms. */
+ tenantId?: string;
+}
+
+export interface UnlinkMessengerState {
+ success: boolean;
+}
diff --git a/packages/chat-adapter-feishu/src/api.ts b/packages/chat-adapter-feishu/src/api.ts
index 1c649746580..f163656092f 100644
--- a/packages/chat-adapter-feishu/src/api.ts
+++ b/packages/chat-adapter-feishu/src/api.ts
@@ -123,6 +123,75 @@ export class LarkApiClient {
return name ? { name } : null;
}
+ // ------------------------------------------------------------------
+ // Outbound media + non-text messages
+ // ------------------------------------------------------------------
+
+ /**
+ * Upload an image to Lark/Feishu's message-scoped image store. Returns the
+ * `image_key` you'd pass through `sendMessageWithMsgType(chatId, 'image',
+ * JSON.stringify({ image_key }))` to actually deliver it.
+ *
+ * See: https://open.feishu.cn/document/server-docs/im-v1/image/create
+ */
+ async uploadImage(buffer: Buffer, name?: string): Promise<{ image_key: string }> {
+ const form = new FormData();
+ form.append('image_type', 'message');
+ form.append(
+ 'image',
+ new Blob([new Uint8Array(buffer)], { type: 'application/octet-stream' }),
+ name ?? 'image',
+ );
+ const data = await this.callMultipart('/im/v1/images', form);
+ return { image_key: data.data.image_key };
+ }
+
+ /**
+ * Upload a file (or audio / video / generic stream) to Lark/Feishu's
+ * message-scoped file store. `fileType` controls how the receiver
+ * previews the file. Returns the `file_key` you'd pass through
+ * `sendMessageWithMsgType(chatId, 'file', JSON.stringify({ file_key }))`
+ * (or `'audio' | 'media'` depending on the source).
+ *
+ * See: https://open.feishu.cn/document/server-docs/im-v1/file/create
+ */
+ async uploadFile(
+ buffer: Buffer,
+ name: string,
+ fileType: 'opus' | 'mp4' | 'pdf' | 'doc' | 'xls' | 'ppt' | 'stream',
+ ): Promise<{ file_key: string }> {
+ const form = new FormData();
+ form.append('file_type', fileType);
+ form.append('file_name', name);
+ form.append(
+ 'file',
+ new Blob([new Uint8Array(buffer)], { type: 'application/octet-stream' }),
+ name,
+ );
+ const data = await this.callMultipart('/im/v1/files', form);
+ return { file_key: data.data.file_key };
+ }
+
+ /**
+ * Send a non-text Lark/Feishu message. `content` must already be the
+ * platform-specific JSON-stringified payload (e.g. `{"image_key":"..."}`
+ * for `msg_type='image'`).
+ *
+ * See: https://open.feishu.cn/document/server-docs/im-v1/message/create
+ */
+ async sendMessageWithMsgType(
+ chatId: string,
+ msgType: 'image' | 'file' | 'audio' | 'media',
+ content: string,
+ ): Promise<{ messageId: string; raw: any }> {
+ const data = await this.call('POST', '/im/v1/messages?receive_id_type=chat_id', {
+ content,
+ msg_type: msgType,
+ receive_id: chatId,
+ });
+ return { messageId: data.data.message_id, raw: data.data };
+ }
+
// ------------------------------------------------------------------
// Media / Resource download
// ------------------------------------------------------------------
@@ -228,4 +297,31 @@ export class LarkApiClient {
return data;
}
+
+ /**
+ * `multipart/form-data` POST variant for endpoints that accept file
+ * uploads (`/im/v1/images`, `/im/v1/files`). Auth header is still required;
+ * the multipart boundary header is set automatically by undici when `body`
+ * is a `FormData` instance.
+ */
+ private async callMultipart(path: string, form: FormData): Promise<any> {
+ const token = await this.getTenantAccessToken();
+ const url = `${this.baseUrl}${path}`;
+ const response = await fetch(url, {
+ body: form,
+ headers: { Authorization: `Bearer ${token}` },
+ method: 'POST',
+ });
+
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(`Lark API multipart POST ${path} failed: ${response.status} ${text}`);
+ }
+
+ const data: any = await response.json();
+ if (data.code !== 0) {
+ throw new Error(`Lark API multipart POST ${path} failed: ${data.code} ${data.msg}`);
+ }
+ return data;
+ }
}
diff --git a/packages/chat-adapter-line/src/api.ts b/packages/chat-adapter-line/src/api.ts
index fa18e777cfc..a51bebdd94d 100644
--- a/packages/chat-adapter-line/src/api.ts
+++ b/packages/chat-adapter-line/src/api.ts
@@ -51,6 +51,19 @@ export class LineApiClient {
await this.post('/v2/bot/message/push', payload);
}
+ /**
+ * Generic push for one or more outbound `LineOutboundMessage` objects. The
+ * Messaging API caps a single push at 5 messages — callers must batch.
+ * Used by the agent-reply outbound media path; plain text replies stay on
+ * the simpler `pushText`.
+ * @see https://developers.line.biz/en/reference/messaging-api/#send-push-message
+ */
+ async push(to: string, messages: LinePushMessageRequest['messages']): Promise<void> {
+ if (messages.length === 0) return;
+ const payload: LinePushMessageRequest = { messages, to };
+ await this.post('/v2/bot/message/push', payload);
+ }
+
/**
* Surface the typing-style "loading" animation in a 1:1 user chat. LINE
* does not expose this for groups or multi-person rooms — callers must
diff --git a/packages/chat-adapter-line/src/index.ts b/packages/chat-adapter-line/src/index.ts
index 8774d3627cd..cea016f16de 100644
--- a/packages/chat-adapter-line/src/index.ts
+++ b/packages/chat-adapter-line/src/index.ts
@@ -24,6 +24,7 @@ export type {
LineMessage,
LineMessageContentType,
LineMessageEvent,
+ LineOutboundMessage,
LinePushMessageRequest,
LineSource,
LineSourceType,
diff --git a/packages/chat-adapter-line/src/types.ts b/packages/chat-adapter-line/src/types.ts
index aa7c9e44fba..a944a7c2c8b 100644
--- a/packages/chat-adapter-line/src/types.ts
+++ b/packages/chat-adapter-line/src/types.ts
@@ -145,8 +145,20 @@ export interface LineWebhookPayload {
// ---------- Outbound API ----------
+/**
+ * Outbound message shapes supported by the Messaging API push endpoint.
+ * Media messages require **public HTTPS URLs** — LINE fetches the bytes
+ * server-side, so inline binary upload is not an option.
+ */
+export type LineOutboundMessage =
+ | { text: string; type: 'text' }
+ | { originalContentUrl: string; previewImageUrl: string; type: 'image' }
+ | { originalContentUrl: string; previewImageUrl: string; type: 'video' }
+ | { duration: number; originalContentUrl: string; type: 'audio' };
+
export interface LinePushMessageRequest {
- messages: Array<{ text: string; type: 'text' }>;
+ /** Per the docs, up to 5 message objects can be batched per push call. */
+ messages: LineOutboundMessage[];
/** Optional notification disabling. */
notificationDisabled?: boolean;
/** Recipient: userId / groupId / roomId. */
diff --git a/packages/chat-adapter-qq/src/api.ts b/packages/chat-adapter-qq/src/api.ts
index 6a0767cdbe3..62669763ad9 100644
--- a/packages/chat-adapter-qq/src/api.ts
+++ b/packages/chat-adapter-qq/src/api.ts
@@ -179,6 +179,85 @@ export class QQApiClient {
return this.call<QQSendMessageResponse>('POST', `/dms/${guildId}/messages`, params);
}
+ // ==================== Rich media (openplatform) ====================
+
+ /**
+ * Upload outbound rich media for a group chat. QQ's openplatform path
+ * accepts either a public URL (the server fetches it) or inline bytes;
+ * we use URL-only because hosting base64 inline requires a staging
+ * bucket that this codebase doesn't have yet. Returns a `file_info`
+ * token that must be passed to `sendGroupMedia` to actually deliver
+ * the file in chat.
+ *
+ * @see https://bot.q.qq.com/wiki/develop/api-v2/server-inter/message/send-receive/rich-media.html
+ */
+ async uploadGroupRichMedia(
+ groupOpenId: string,
+ fileType: 1 | 2 | 3 | 4,
+ url: string,
+ ): Promise<{ file_info: string; ttl?: number }> {
+ return this.call<{ file_info: string; ttl?: number }>(
+ 'POST',
+ `/v2/groups/${groupOpenId}/files`,
+ { file_type: fileType, srv_send_msg: false, url },
+ );
+ }
+
+ /**
+ * C2C (direct message to a user) counterpart of `uploadGroupRichMedia`.
+ * Same body shape, different route.
+ */
+ async uploadC2CRichMedia(
+ openId: string,
+ fileType: 1 | 2 | 3 | 4,
+ url: string,
+ ): Promise<{ file_info: string; ttl?: number }> {
+ return this.call<{ file_info: string; ttl?: number }>('POST', `/v2/users/${openId}/files`, {
+ file_type: fileType,
+ srv_send_msg: false,
+ url,
+ });
+ }
+
+ /**
+ * Send a rich-media message to a group. QQ requires the file to have been
+ * uploaded first (see `uploadGroupRichMedia`); media + text content are
+ * mutually exclusive on the same message (`msg_type` is either 7 (MEDIA)
+ * or 0 (TEXT), not both), so callers send the text leg separately.
+ */
+ async sendGroupMedia(
+ groupOpenId: string,
+ fileInfo: string,
+ options?: { eventId?: string; msgId?: string; msgSeq?: number },
+ ): Promise<QQSendMessageResponse> {
+ const params: QQSendMessageParams = {
+ content: ' ',
+ media: { file_info: fileInfo },
+ msg_type: QQ_MSG_TYPE.MEDIA,
+ };
+ if (options?.msgId) params.msg_id = options.msgId;
+ if (options?.eventId) params.event_id = options.eventId;
+ if (options?.msgSeq !== undefined) params.msg_seq = options.msgSeq;
+ return this.call<QQSendMessageResponse>('POST', `/v2/groups/${groupOpenId}/messages`, params);
+ }
+
+ /** C2C counterpart of `sendGroupMedia`. */
+ async sendC2CMedia(
+ openId: string,
+ fileInfo: string,
+ options?: { eventId?: string; msgId?: string; msgSeq?: number },
+ ): Promise<QQSendMessageResponse> {
+ const params: QQSendMessageParams = {
+ content: ' ',
+ media: { file_info: fileInfo },
+ msg_type: QQ_MSG_TYPE.MEDIA,
+ };
+ if (options?.msgId) params.msg_id = options.msgId;
+ if (options?.eventId) params.event_id = options.eventId;
+ if (options?.msgSeq !== undefined) params.msg_seq = options.msgSeq;
+ return this.call<QQSendMessageResponse>('POST', `/v2/users/${openId}/messages`, params);
+ }
+
/**
* Get the WebSocket gateway URL for establishing a persistent connection.
*/
diff --git a/packages/chat-adapter-qq/src/types.ts b/packages/chat-adapter-qq/src/types.ts
index f1dd999a754..24a3d5be6aa 100644
--- a/packages/chat-adapter-qq/src/types.ts
+++ b/packages/chat-adapter-qq/src/types.ts
@@ -90,6 +90,14 @@ export interface QQSendMessageParams {
markdown?: {
content: string;
};
+ /**
+ * Rich-media payload used together with `msg_type: 7 (MEDIA)`. The
+ * `file_info` token comes from the upload step (see
+ * `QQApiClient.uploadGroupRichMedia` / `uploadC2CRichMedia`).
+ */
+ media?: {
+ file_info: string;
+ };
msg_id?: string;
msg_seq?: number;
msg_type: number;
diff --git a/src/server/routers/lambda/botMessage.ts b/src/server/routers/lambda/botMessage.ts
index 18521197360..268ae81466d 100644
--- a/src/server/routers/lambda/botMessage.ts
+++ b/src/server/routers/lambda/botMessage.ts
@@ -13,6 +13,7 @@ import { z } from 'zod';
import type { DecryptedBotProvider } from '@/database/models/agentBotProvider';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import { MessengerInstallationModel } from '@/database/models/messengerInstallation';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
@@ -40,11 +41,43 @@ const botMessageProcedure = authedProcedure.use(serverDatabase).use(async (opts)
});
});
-// ── Service Factory ──────────────────────────────────────
+// ── Shared input schemas ─────────────────────────────────
+
+/**
+ * Mirror of `SendMessageAttachment` (builtin-tool-message types). Shared
+ * across `sendMessage`, `sendDirectMessage`, and `replyToThread` so the
+ * three procedures stay in lockstep — the platform-specific helpers
+ * downstream only see one shape.
+ */
+const attachmentsInputSchema = z.array(
+ z.object({
+ data: z.string().optional(),
+ fetchUrl: z.string().url().optional(),
+ mimeType: z.string().optional(),
+ name: z.string().optional(),
+ type: z.enum(['image', 'file', 'video', 'audio']),
+ }),
+);
-const createServiceForBot = (provider: DecryptedBotProvider): MessageRuntimeService => {
- const { platform, applicationId, credentials } = provider;
+// ── Service Factory ──────────────────────────────────────
+/**
+ * Build a `MessageRuntimeService` from raw platform + applicationId +
+ * credentials. Shared between two resolution sources:
+ *
+ * 1. Per-agent bot channels (`agent_bot_providers` row) — `resolveBot`
+ * 2. System Bot messenger installs (`messenger_installations` row) —
+ * `resolveMessengerInstall`
+ *
+ * Both paths produce the same underlying outbound API client, so the
+ * downstream `MessageRuntimeService` behavior (attachments included) is
+ * identical regardless of where the credentials came from.
+ */
+const createServiceForCredentials = (
+ platform: string,
+ applicationId: string,
+ credentials: Record<string, any>,
+): MessageRuntimeService => {
switch (platform) {
case 'discord': {
return new DiscordMessageService(new DiscordApi(credentials.botToken));
@@ -85,6 +118,13 @@ const createServiceForBot = (provider: DecryptedBotProvider): MessageRuntimeServ
}
};
+const createServiceForBot = (provider: DecryptedBotProvider): MessageRuntimeService =>
+ createServiceForCredentials(
+ provider.platform,
+ provider.applicationId,
+ provider.credentials as Record<string, any>,
+ );
+
const resolveBot = async (
model: AgentBotProviderModel,
botId: string,
@@ -111,6 +151,77 @@ const resolveBot = async (
};
};
+/**
+ * Resolve a system-bot messenger installation row into a runnable
+ * `MessageRuntimeService`. Authorization: only the user who installed the
+ * row can target it — workspace admins who installed under a different
+ * LobeHub account need their own session.
+ */
+const resolveMessengerInstall = async (
+ ctx: { serverDB: any; userId: string },
+ installationId: string,
+): Promise<{
+ platform: MessagePlatformType;
+ service: MessageRuntimeService;
+ settings: Record<string, unknown>;
+}> => {
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
+ const row = await MessengerInstallationModel.findById(ctx.serverDB, installationId, gateKeeper);
+ if (!row) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Messenger installation not found: ${installationId}`,
+ });
+ }
+ if (row.revokedAt) {
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: `Messenger installation has been revoked: ${installationId}`,
+ });
+ }
+ if (row.installedByUserId !== ctx.userId) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'You can only send through messenger installs you initiated',
+ });
+ }
+ return {
+ platform: row.platform as MessagePlatformType,
+ service: createServiceForCredentials(
+ row.platform,
+ row.applicationId,
+ row.credentials as Record<string, any>,
+ ),
+ settings: {},
+ };
+};
+
+/**
+ * Common dispatcher: either a per-agent `botId` or a system-bot
+ * `messengerInstallationId`. Each procedure's zod input enforces the
+ * "exactly one of" constraint at the boundary; this helper assumes that
+ * invariant has already been checked.
+ */
+const resolveSendTarget = async (
+ ctx: { agentBotProviderModel: AgentBotProviderModel; serverDB: any; userId: string },
+ input: { botId?: string; messengerInstallationId?: string },
+): Promise<{
+ platform: MessagePlatformType;
+ service: MessageRuntimeService;
+ settings: Record<string, unknown>;
+}> => {
+ if (input.botId) return resolveBot(ctx.agentBotProviderModel, input.botId);
+ if (input.messengerInstallationId)
+ return resolveMessengerInstall(
+ { serverDB: ctx.serverDB, userId: ctx.userId },
+ input.messengerInstallationId,
+ );
+ throw new TRPCError({
+ code: 'BAD_REQUEST',
+ message: 'Provide exactly one of botId or messengerInstallationId',
+ });
+};
+
// ── Router ───────────────────────────────────────────────
export const botMessageRouter = router({
@@ -118,14 +229,20 @@ export const botMessageRouter = router({
sendDirectMessage: botMessageProcedure
.input(
- z.object({
- botId: z.string(),
- content: z.string(),
- userId: z.string(),
- }),
+ z
+ .object({
+ attachments: attachmentsInputSchema.optional(),
+ botId: z.string().optional(),
+ content: z.string(),
+ messengerInstallationId: z.string().optional(),
+ userId: z.string(),
+ })
+ .refine((v) => !!v.botId !== !!v.messengerInstallationId, {
+ message: 'Provide exactly one of botId or messengerInstallationId',
+ }),
)
.mutation(async ({ input, ctx }) => {
- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);
+ const { service, platform } = await resolveSendTarget(ctx, input);
if (!service.sendDirectMessage) {
throw new TRPCError({
code: 'BAD_REQUEST',
@@ -133,6 +250,7 @@ export const botMessageRouter = router({
});
}
return service.sendDirectMessage({
+ attachments: input.attachments,
content: input.content,
platform,
userId: input.userId,
@@ -143,27 +261,22 @@ export const botMessageRouter = router({
sendMessage: botMessageProcedure
.input(
- z.object({
- attachments: z
- .array(
- z.object({
- data: z.string().optional(),
- fetchUrl: z.string().url().optional(),
- mimeType: z.string().optional(),
- name: z.string().optional(),
- type: z.enum(['image', 'file', 'video', 'audio']),
- }),
- )
- .optional(),
- botId: z.string(),
- channelId: z.string(),
- content: z.string(),
- embeds: z.array(z.record(z.unknown())).optional(),
- replyTo: z.string().optional(),
- }),
+ z
+ .object({
+ attachments: attachmentsInputSchema.optional(),
+ botId: z.string().optional(),
+ channelId: z.string(),
+ content: z.string(),
+ embeds: z.array(z.record(z.unknown())).optional(),
+ messengerInstallationId: z.string().optional(),
+ replyTo: z.string().optional(),
+ })
+ .refine((v) => !!v.botId !== !!v.messengerInstallationId, {
+ message: 'Provide exactly one of botId or messengerInstallationId',
+ }),
)
.mutation(async ({ input, ctx }) => {
- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);
+ const { service, platform } = await resolveSendTarget(ctx, input);
return service.sendMessage({
attachments: input.attachments,
channelId: input.channelId,
@@ -450,15 +563,22 @@ export const botMessageRouter = router({
replyToThread: botMessageProcedure
.input(
- z.object({
- botId: z.string(),
- content: z.string(),
- threadId: z.string(),
- }),
+ z
+ .object({
+ attachments: attachmentsInputSchema.optional(),
+ botId: z.string().optional(),
+ content: z.string(),
+ messengerInstallationId: z.string().optional(),
+ threadId: z.string(),
+ })
+ .refine((v) => !!v.botId !== !!v.messengerInstallationId, {
+ message: 'Provide exactly one of botId or messengerInstallationId',
+ }),
)
.mutation(async ({ input, ctx }) => {
- const { service, platform } = await resolveBot(ctx.agentBotProviderModel, input.botId);
+ const { service, platform } = await resolveSendTarget(ctx, input);
return service.replyToThread({
+ attachments: input.attachments,
content: input.content,
platform,
threadId: input.threadId,
diff --git a/src/server/services/bot/platforms/discord/api.ts b/src/server/services/bot/platforms/discord/api.ts
index da9c6015984..79556ac34eb 100644
--- a/src/server/services/bot/platforms/discord/api.ts
+++ b/src/server/services/bot/platforms/discord/api.ts
@@ -1,4 +1,4 @@
-import { REST } from '@discordjs/rest';
+import { type RawFile, REST } from '@discordjs/rest';
import debug from 'debug';
import {
ApplicationCommandOptionType,
@@ -118,10 +118,19 @@ export class DiscordApi {
await this.rest.patch(Routes.channel(channelId), { body: { name: truncatedName } });
}
- async createMessage(channelId: string, content: string): Promise<{ id: string }> {
- log('createMessage: channel=%s', channelId);
+ async createMessage(
+ channelId: string,
+ content: string,
+ files?: RawFile[],
+ ): Promise<{ id: string }> {
+ log('createMessage: channel=%s, files=%d', channelId, files?.length ?? 0);
+ // When `files` is set, @discordjs/rest packs `body` into `payload_json`
+ // and emits multipart/form-data automatically. Without files we keep the
+ // application/json path because that's what the API rate-limit bucket
+ // expects for plain messages.
const data = (await this.rest.post(Routes.channelMessages(channelId), {
body: { content },
+ ...(files && files.length > 0 ? { files } : {}),
})) as RESTPostAPIChannelMessageResult;
return { id: data.id };
diff --git a/src/server/services/bot/platforms/discord/client.ts b/src/server/services/bot/platforms/discord/client.ts
index d733a554d67..be49cd1b1e1 100644
--- a/src/server/services/bot/platforms/discord/client.ts
+++ b/src/server/services/bot/platforms/discord/client.ts
@@ -23,6 +23,7 @@ import {
import { formatUsageStats } from '../utils';
import { DiscordApi } from './api';
import { patchDiscordForwardedInteractions, patchDiscordThreadRecovery } from './patch';
+import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';
const log = debug('bot-platform:discord:bot');
@@ -229,10 +230,27 @@ class DiscordGatewayClient implements PlatformClient {
const discord = this.discord;
return {
addReaction: (messageId, emoji) => discord.createReaction(channelId, messageId, emoji),
- // Attachments are silently dropped for now — Discord outbound media
- // is its own follow-up; reply text still ships.
- createMessage: (content) =>
- discord.createMessage(channelId, messengerContentText(content)).then(() => {}),
+ createMessage: async (content) => {
+ const text = messengerContentText(content);
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+ if (!attachments?.length) {
+ await discord.createMessage(channelId, text);
+ return;
+ }
+ const files = await materializeAttachmentsForDiscord(attachments);
+ if (files.length === 0) {
+ await discord.createMessage(channelId, text);
+ return;
+ }
+ const batches = batchDiscordFiles(files);
+ for (const [i, batch] of batches.entries()) {
+ await discord.createMessage(channelId, i === 0 ? text : '', batch);
+ }
+ },
+ // editMessage: keep the text-only contract. Editing a message to add
+ // attachments is an advanced flow (PATCH with `attachments[]` keep-set
+ // + `files[]` adds) that isn't worth the complexity for the bot reply
+ // path — new chunks with attachments flow through `createMessage`.
editMessage: (messageId, content) =>
discord.editMessage(channelId, messageId, messengerContentText(content)),
removeReaction: (messageId, emoji) => discord.removeOwnReaction(channelId, messageId, emoji),
diff --git a/src/server/services/bot/platforms/discord/sendAttachments.test.ts b/src/server/services/bot/platforms/discord/sendAttachments.test.ts
new file mode 100644
index 00000000000..488928974d5
--- /dev/null
+++ b/src/server/services/bot/platforms/discord/sendAttachments.test.ts
@@ -0,0 +1,99 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ batchDiscordFiles,
+ DISCORD_MAX_ATTACHMENTS_PER_MESSAGE,
+ materializeAttachmentsForDiscord,
+} from './sendAttachments';
+
+describe('materializeAttachmentsForDiscord', () => {
+ beforeEach(() => {
+ vi.stubGlobal('fetch', vi.fn());
+ });
+
+ it('decodes base64 data into a Buffer with the explicit filename', async () => {
+ const files = await materializeAttachmentsForDiscord([
+ {
+ data: Buffer.from('hello').toString('base64'),
+ mimeType: 'image/png',
+ name: 'foo.png',
+ type: 'image',
+ },
+ ]);
+
+ expect(files).toHaveLength(1);
+ expect(files[0].name).toBe('foo.png');
+ expect(files[0].contentType).toBe('image/png');
+ expect(Buffer.isBuffer(files[0].data)).toBe(true);
+ expect((files[0].data as Buffer).toString()).toBe('hello');
+ });
+
+ it('fetches fetchUrl attachments and materializes their bytes', async () => {
+ const fetchMock = vi.mocked(fetch);
+ fetchMock.mockResolvedValueOnce(
+ new Response(new Uint8Array([1, 2, 3, 4]), {
+ headers: { 'Content-Type': 'image/png' },
+ status: 200,
+ }) as any,
+ );
+
+ const files = await materializeAttachmentsForDiscord([
+ { fetchUrl: 'https://cdn.example.com/pic.png', type: 'image' },
+ ]);
+
+ expect(fetchMock).toHaveBeenCalledWith('https://cdn.example.com/pic.png', expect.any(Object));
+ expect(files).toHaveLength(1);
+ expect(files[0].name).toBe('pic.png');
+ });
+
+ it('skips attachments that fail to materialize but keeps the rest', async () => {
+ const fetchMock = vi.mocked(fetch);
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }) as any);
+
+ const files = await materializeAttachmentsForDiscord([
+ { fetchUrl: 'https://cdn.example.com/broken.png', type: 'image' },
+ { data: Buffer.from('ok').toString('base64'), name: 'ok.txt', type: 'file' },
+ ]);
+
+ expect(files).toHaveLength(1);
+ expect(files[0].name).toBe('ok.txt');
+ });
+
+ it('falls back to a generic filename when name is missing', async () => {
+ const files = await materializeAttachmentsForDiscord([
+ { data: Buffer.from('a').toString('base64'), mimeType: 'image/png', type: 'image' },
+ { data: Buffer.from('b').toString('base64'), mimeType: 'application/pdf', type: 'file' },
+ ]);
+
+ expect(files[0].name).toBe('attachment-1.png');
+ expect(files[1].name).toBe('attachment-2.pdf');
+ });
+});
+
+describe('batchDiscordFiles', () => {
+ const file = (name: string) => ({ data: Buffer.from('x'), name });
+
+ it('returns empty array for empty input', () => {
+ expect(batchDiscordFiles([])).toEqual([]);
+ });
+
+ it('keeps a single batch when files <= cap', () => {
+ const files = Array.from({ length: DISCORD_MAX_ATTACHMENTS_PER_MESSAGE }, (_, i) =>
+ file(`f${i}.png`),
+ );
+ const batches = batchDiscordFiles(files);
+ expect(batches).toHaveLength(1);
+ expect(batches[0]).toHaveLength(DISCORD_MAX_ATTACHMENTS_PER_MESSAGE);
+ });
+
+ it('splits when files exceed the cap', () => {
+ const files = Array.from({ length: DISCORD_MAX_ATTACHMENTS_PER_MESSAGE + 3 }, (_, i) =>
+ file(`f${i}.png`),
+ );
+ const batches = batchDiscordFiles(files);
+ expect(batches).toHaveLength(2);
+ expect(batches[0]).toHaveLength(DISCORD_MAX_ATTACHMENTS_PER_MESSAGE);
+ expect(batches[1]).toHaveLength(3);
+ });
+});
diff --git a/src/server/services/bot/platforms/discord/sendAttachments.ts b/src/server/services/bot/platforms/discord/sendAttachments.ts
new file mode 100644
index 00000000000..c46dbef507e
--- /dev/null
+++ b/src/server/services/bot/platforms/discord/sendAttachments.ts
@@ -0,0 +1,145 @@
+import type { RawFile } from '@discordjs/rest';
+import debug from 'debug';
+
+import type { BotMessageAttachment } from '../types';
+
+const log = debug('bot-platform:discord:send-attachments');
+
+/**
+ * Discord caps each message at 10 attachments. Batches beyond that go into
+ * follow-up messages.
+ *
+ * See: https://discord.com/developers/docs/resources/channel#create-message
+ */
+export const DISCORD_MAX_ATTACHMENTS_PER_MESSAGE = 10;
+
+/**
+ * Materialize an attachment's bytes from `data` (base64) or `fetchUrl` (HTTP
+ * GET, 15s timeout). Returns undefined if neither source resolves so the
+ * caller can skip the failing item without aborting the whole batch.
+ */
+const loadAttachmentBuffer = async (
+ attachment: BotMessageAttachment,
+): Promise<Buffer | undefined> => {
+ if (attachment.data) {
+ try {
+ return Buffer.from(attachment.data, 'base64');
+ } catch (error) {
+ log('loadAttachmentBuffer: failed to decode base64: %O', error);
+ }
+ }
+ if (attachment.fetchUrl) {
+ try {
+ const response = await fetch(attachment.fetchUrl, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (response.ok) {
+ return Buffer.from(await response.arrayBuffer());
+ }
+ log('loadAttachmentBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);
+ } catch (error) {
+ log('loadAttachmentBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);
+ }
+ }
+ return undefined;
+};
+
+/**
+ * Pick a filename for the Discord upload. Falls back to a generic name with
+ * the appropriate extension inferred from `mimeType` so Discord's preview
+ * works (Discord uses the filename extension, not mimeType, to pick its
+ * viewer).
+ */
+const resolveFilename = (attachment: BotMessageAttachment, index: number): string => {
+ if (attachment.name) return attachment.name;
+ if (attachment.fetchUrl) {
+ try {
+ const base = new URL(attachment.fetchUrl).pathname.split('/').pop();
+ if (base) return base;
+ } catch {
+ // ignore — fall through to the generic name
+ }
+ }
+ const ext = mimeToExt(attachment.mimeType) ?? defaultExtForType(attachment.type);
+ return `attachment-${index + 1}${ext}`;
+};
+
+const mimeToExt = (mimeType?: string): string | undefined => {
+ if (!mimeType) return undefined;
+ // Common cases; Discord's previewer covers far more, but we only need the
+ // ones the agent runtime is realistically going to emit.
+ const map: Record<string, string> = {
+ 'application/json': '.json',
+ 'application/pdf': '.pdf',
+ 'audio/mp4': '.m4a',
+ 'audio/mpeg': '.mp3',
+ 'audio/ogg': '.ogg',
+ 'audio/wav': '.wav',
+ 'image/bmp': '.bmp',
+ 'image/gif': '.gif',
+ 'image/jpeg': '.jpg',
+ 'image/png': '.png',
+ 'image/svg+xml': '.svg',
+ 'image/webp': '.webp',
+ 'text/plain': '.txt',
+ 'video/mp4': '.mp4',
+ 'video/webm': '.webm',
+ };
+ return map[mimeType];
+};
+
+const defaultExtForType = (type: BotMessageAttachment['type']): string => {
+ switch (type) {
+ case 'image': {
+ return '.png';
+ }
+ case 'video': {
+ return '.mp4';
+ }
+ case 'audio': {
+ return '.mp3';
+ }
+ case 'file':
+ default: {
+ return '';
+ }
+ }
+};
+
+/**
+ * Convert JSON-safe `BotMessageAttachment[]` into `@discordjs/rest`-shaped
+ * `RawFile[]` ready to ride along a `rest.post(channelMessages)` call. Each
+ * item that fails to materialize is logged and skipped; the rest still ship.
+ */
+export const materializeAttachmentsForDiscord = async (
+ attachments: BotMessageAttachment[],
+): Promise<RawFile[]> => {
+ const out: RawFile[] = [];
+ for (const [index, att] of attachments.entries()) {
+ const buffer = await loadAttachmentBuffer(att);
+ if (!buffer) {
+ log('materializeAttachmentsForDiscord: skipping attachment "%s"', att.name ?? '(unnamed)');
+ continue;
+ }
+ out.push({
+ contentType: att.mimeType,
+ data: buffer,
+ name: resolveFilename(att, index),
+ });
+ }
+ return out;
+};
+
+/**
+ * Split a list of materialized files into batches of `DISCORD_MAX_ATTACHMENTS_PER_MESSAGE`.
+ * Callers send the first batch with `content`, and subsequent batches with no
+ * text so the agent's reply doesn't repeat once per batch.
+ */
+export const batchDiscordFiles = (files: RawFile[]): RawFile[][] => {
+ if (files.length === 0) return [];
+ const batches: RawFile[][] = [];
+ for (let i = 0; i < files.length; i += DISCORD_MAX_ATTACHMENTS_PER_MESSAGE) {
+ batches.push(files.slice(i, i + DISCORD_MAX_ATTACHMENTS_PER_MESSAGE));
+ }
+ return batches;
+};
diff --git a/src/server/services/bot/platforms/discord/service.test.ts b/src/server/services/bot/platforms/discord/service.test.ts
new file mode 100644
index 00000000000..5555470a21d
--- /dev/null
+++ b/src/server/services/bot/platforms/discord/service.test.ts
@@ -0,0 +1,167 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DiscordMessageService } from './service';
+
+const makeApi = () => ({
+ createMessage: vi.fn().mockResolvedValue({ id: 'msg-1' }),
+});
+
+describe('DiscordMessageService.sendMessage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', vi.fn());
+ });
+
+ it('sends text-only when no attachments', async () => {
+ const api = makeApi();
+ const service = new DiscordMessageService(api as any);
+
+ const result = await service.sendMessage({
+ channelId: 'ch-1',
+ content: 'hello',
+ platform: 'discord',
+ });
+
+ expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'hello');
+ expect(result).toMatchObject({ channelId: 'ch-1', messageId: 'msg-1', platform: 'discord' });
+ });
+
+ it('forwards base64 attachments as multipart files', async () => {
+ const api = makeApi();
+ const service = new DiscordMessageService(api as any);
+
+ await service.sendMessage({
+ attachments: [
+ {
+ data: Buffer.from('img').toString('base64'),
+ mimeType: 'image/png',
+ name: 'foo.png',
+ type: 'image',
+ },
+ ],
+ channelId: 'ch-1',
+ content: 'here',
+ platform: 'discord',
+ });
+
+ expect(api.createMessage).toHaveBeenCalledTimes(1);
+ expect(api.createMessage).toHaveBeenCalledWith(
+ 'ch-1',
+ 'here',
+ expect.arrayContaining([
+ expect.objectContaining({
+ contentType: 'image/png',
+ name: 'foo.png',
+ }),
+ ]),
+ );
+ });
+
+ it('splits >10 attachments across multiple createMessage calls', async () => {
+ const api = makeApi();
+ const service = new DiscordMessageService(api as any);
+
+ const attachments = Array.from({ length: 12 }, (_, i) => ({
+ data: Buffer.from(`bytes-${i}`).toString('base64'),
+ mimeType: 'image/png',
+ name: `a${i}.png`,
+ type: 'image' as const,
+ }));
+
+ await service.sendMessage({
+ attachments,
+ channelId: 'ch-1',
+ content: 'batch',
+ platform: 'discord',
+ });
+
+ expect(api.createMessage).toHaveBeenCalledTimes(2);
+ // First batch carries the content
+ expect(api.createMessage.mock.calls[0][0]).toBe('ch-1');
+ expect(api.createMessage.mock.calls[0][1]).toBe('batch');
+ expect(api.createMessage.mock.calls[0][2]).toHaveLength(10);
+ // Second batch is content-empty, 2 files
+ expect(api.createMessage.mock.calls[1][1]).toBe('');
+ expect(api.createMessage.mock.calls[1][2]).toHaveLength(2);
+ });
+
+ it('falls back to text-only when all attachments fail to materialize', async () => {
+ const api = makeApi();
+ const service = new DiscordMessageService(api as any);
+ const fetchMock = vi.mocked(fetch);
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 500 }) as any);
+
+ await service.sendMessage({
+ attachments: [{ fetchUrl: 'https://cdn.example.com/broken.png', type: 'image' }],
+ channelId: 'ch-1',
+ content: 'still send the text',
+ platform: 'discord',
+ });
+
+ // Only a single text-only call should be made — no files arg.
+ expect(api.createMessage).toHaveBeenCalledTimes(1);
+ expect(api.createMessage).toHaveBeenCalledWith('ch-1', 'still send the text');
+ });
+});
+
+describe('DiscordMessageService.sendDirectMessage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('creates DM channel and posts text + attachments via the shared path', async () => {
+ const api = {
+ createDMChannel: vi.fn().mockResolvedValue({ id: 'dm-ch' }),
+ createMessage: vi.fn().mockResolvedValue({ id: 'msg-dm' }),
+ };
+ const service = new DiscordMessageService(api as any);
+
+ await service.sendDirectMessage!({
+ attachments: [
+ {
+ data: Buffer.from('img').toString('base64'),
+ mimeType: 'image/png',
+ name: 'foo.png',
+ type: 'image',
+ },
+ ],
+ content: 'hello DM',
+ platform: 'discord',
+ userId: 'user-1',
+ });
+
+ expect(api.createDMChannel).toHaveBeenCalledWith('user-1');
+ expect(api.createMessage).toHaveBeenCalledWith(
+ 'dm-ch',
+ 'hello DM',
+ expect.arrayContaining([
+ expect.objectContaining({ contentType: 'image/png', name: 'foo.png' }),
+ ]),
+ );
+ });
+});
+
+describe('DiscordMessageService.replyToThread', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('posts to the thread id with attachments', async () => {
+ const api = { createMessage: vi.fn().mockResolvedValue({ id: 'tr-1' }) };
+ const service = new DiscordMessageService(api as any);
+
+ await service.replyToThread({
+ attachments: [{ data: Buffer.from('x').toString('base64'), name: 'x.png', type: 'image' }],
+ content: 'thread reply',
+ platform: 'discord',
+ threadId: 'thread-id-1',
+ });
+
+ expect(api.createMessage).toHaveBeenCalledWith(
+ 'thread-id-1',
+ 'thread reply',
+ expect.arrayContaining([expect.objectContaining({ name: 'x.png' })]),
+ );
+ });
+});
diff --git a/src/server/services/bot/platforms/discord/service.ts b/src/server/services/bot/platforms/discord/service.ts
index 4dd1e877c35..5d5bf50dca7 100644
--- a/src/server/services/bot/platforms/discord/service.ts
+++ b/src/server/services/bot/platforms/discord/service.ts
@@ -30,6 +30,8 @@ import type {
ReplyToThreadState,
SearchMessagesParams,
SearchMessagesState,
+ SendDirectMessageParams,
+ SendDirectMessageState,
SendMessageParams,
SendMessageState,
UnpinMessageParams,
@@ -41,6 +43,7 @@ import type { MessageRuntimeService } from '@/server/services/toolExecution/serv
import type { DiscordApi } from './api';
import { MAX_DISCORD_HISTORY_LIMIT } from './const';
+import { batchDiscordFiles, materializeAttachmentsForDiscord } from './sendAttachments';
/**
* Normalize a Discord API message object to MessageItem.
@@ -57,22 +60,54 @@ const toMessageItem = (msg: any): MessageItem => ({
export class DiscordMessageService implements MessageRuntimeService {
constructor(private api: DiscordApi) {}
+ /**
+ * Shared outbound path used by `sendMessage`, `sendDirectMessage`, and
+ * `replyToThread`. Materializes attachments, batches them under Discord's
+ * 10-files-per-message cap, and falls back to a text-only `createMessage`
+ * if all attachments fail to resolve. Returns the message id of the FIRST
+ * post (the one that carried the text content).
+ */
+ private async postToChannel(
+ channelId: string,
+ content: string,
+ attachments: SendMessageParams['attachments'],
+ ): Promise<{ id: string } | undefined> {
+ if (!attachments?.length) {
+ return this.api.createMessage(channelId, content);
+ }
+
+ const files = await materializeAttachmentsForDiscord(attachments);
+ if (files.length === 0) {
+ // All attachments failed to materialize — fall back to text-only so the
+ // reply still reaches the user.
+ return this.api.createMessage(channelId, content);
+ }
+
+ // Discord caps attachments per message at 10. The first batch carries the
+ // text content; subsequent batches send empty-content follow-ups so the
+ // reply body isn't repeated.
+ const batches = batchDiscordFiles(files);
+ let firstResult: { id: string } | undefined;
+ for (const [i, batch] of batches.entries()) {
+ const result = await this.api.createMessage(channelId, i === 0 ? content : '', batch);
+ if (i === 0) firstResult = result;
+ }
+ return firstResult;
+ }
+
// ==================== Direct Messaging ====================
- sendDirectMessage = async (params: {
- content: string;
- userId: string;
- }): Promise<{ channelId?: string; messageId?: string; platform?: string }> => {
+ sendDirectMessage = async (params: SendDirectMessageParams): Promise<SendDirectMessageState> => {
const dmChannel = await this.api.createDMChannel(params.userId);
- const result = await this.api.createMessage(dmChannel.id, params.content);
- return { channelId: dmChannel.id, messageId: result.id, platform: 'discord' };
+ const result = await this.postToChannel(dmChannel.id, params.content, params.attachments);
+ return { channelId: dmChannel.id, messageId: result?.id, platform: 'discord' };
};
// ==================== Core Message Operations ====================
sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {
- const result = await this.api.createMessage(params.channelId, params.content);
- return { channelId: params.channelId, messageId: result.id, platform: 'discord' };
+ const result = await this.postToChannel(params.channelId, params.content, params.attachments);
+ return { channelId: params.channelId, messageId: result?.id, platform: 'discord' };
};
readMessages = async (params: ReadMessagesParams): Promise<ReadMessagesState> => {
@@ -257,8 +292,10 @@ export class DiscordMessageService implements MessageRuntimeService {
};
replyToThread = async (params: ReplyToThreadParams): Promise<ReplyToThreadState> => {
- const result = await this.api.createMessage(params.threadId, params.content);
- return { messageId: result.id, threadId: params.threadId };
+ // Discord threads ARE channels — posting to a thread id goes through the
+ // same `channelMessages` route, so we reuse the shared attachments path.
+ const result = await this.postToChannel(params.threadId, params.content, params.attachments);
+ return { messageId: result?.id, threadId: params.threadId };
};
// ==================== Platform-Specific: Polls ====================
diff --git a/src/server/services/bot/platforms/feishu/client.ts b/src/server/services/bot/platforms/feishu/client.ts
index a68b52724f8..69b4227ecb7 100644
--- a/src/server/services/bot/platforms/feishu/client.ts
+++ b/src/server/services/bot/platforms/feishu/client.ts
@@ -28,6 +28,7 @@ import {
} from '../types';
import { formatUsageStats } from '../utils';
import { FeishuWSConnection } from './gateway';
+import { sendFeishuAttachments } from './sendAttachments';
const log = debug('bot-platform:feishu:client');
@@ -63,10 +64,16 @@ function createMessenger(
const chatId = extractChatId(platformThreadId);
return {
addReaction: (messageId, emoji) => api.addReaction(messageId, emoji).then(() => {}),
- // Attachments are silently dropped for now — Lark/Feishu outbound media
- // is its own follow-up; reply text still ships.
- createMessage: (content) =>
- api.sendMessage(chatId, messengerContentText(content)).then(() => {}),
+ createMessage: async (content) => {
+ const text = messengerContentText(content);
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+ if (text.trim()) {
+ await api.sendMessage(chatId, text);
+ }
+ if (attachments?.length) {
+ await sendFeishuAttachments(api, chatId, attachments);
+ }
+ },
editMessage: (messageId, content) =>
api.editMessage(messageId, messengerContentText(content)).then(() => {}),
// Feishu / Lark currently expose no authenticated removeReaction endpoint.
diff --git a/src/server/services/bot/platforms/feishu/sendAttachments.test.ts b/src/server/services/bot/platforms/feishu/sendAttachments.test.ts
new file mode 100644
index 00000000000..50d09078122
--- /dev/null
+++ b/src/server/services/bot/platforms/feishu/sendAttachments.test.ts
@@ -0,0 +1,109 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { sendFeishuAttachments } from './sendAttachments';
+
+const makeApi = () => ({
+ sendMessageWithMsgType: vi.fn().mockResolvedValue({ messageId: 'm-1', raw: {} }),
+ uploadFile: vi.fn().mockResolvedValue({ file_key: 'file_xyz' }),
+ uploadImage: vi.fn().mockResolvedValue({ image_key: 'img_abc' }),
+});
+
+describe('sendFeishuAttachments', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', vi.fn());
+ });
+
+ it('uploads image and sends with msg_type=image', async () => {
+ const api = makeApi();
+
+ const n = await sendFeishuAttachments(api as any, 'oc_chat', [
+ {
+ data: Buffer.from('img-bytes').toString('base64'),
+ mimeType: 'image/png',
+ name: 'foo.png',
+ type: 'image',
+ },
+ ]);
+
+ expect(n).toBe(1);
+ expect(api.uploadImage).toHaveBeenCalledWith(expect.any(Buffer), 'foo.png');
+ expect(api.sendMessageWithMsgType).toHaveBeenCalledWith(
+ 'oc_chat',
+ 'image',
+ JSON.stringify({ image_key: 'img_abc' }),
+ );
+ });
+
+ it('infers file_type from extension/mime', async () => {
+ const api = makeApi();
+
+ await sendFeishuAttachments(api as any, 'oc_chat', [
+ {
+ data: Buffer.from('pdf').toString('base64'),
+ mimeType: 'application/pdf',
+ name: 'doc.pdf',
+ type: 'file',
+ },
+ ]);
+
+ expect(api.uploadFile).toHaveBeenCalledWith(expect.any(Buffer), 'doc.pdf', 'pdf');
+ expect(api.sendMessageWithMsgType).toHaveBeenCalledWith(
+ 'oc_chat',
+ 'file',
+ JSON.stringify({ file_key: 'file_xyz' }),
+ );
+ });
+
+ it('routes video to msg_type=media and audio to msg_type=audio', async () => {
+ const api = makeApi();
+
+ await sendFeishuAttachments(api as any, 'oc_chat', [
+ { data: Buffer.from('v').toString('base64'), name: 'v.mp4', type: 'video' },
+ { data: Buffer.from('a').toString('base64'), name: 'a.mp3', type: 'audio' },
+ ]);
+
+ expect(api.uploadFile).toHaveBeenNthCalledWith(1, expect.any(Buffer), 'v.mp4', 'mp4');
+ expect(api.sendMessageWithMsgType).toHaveBeenNthCalledWith(
+ 1,
+ 'oc_chat',
+ 'media',
+ JSON.stringify({ file_key: 'file_xyz' }),
+ );
+ expect(api.uploadFile).toHaveBeenNthCalledWith(2, expect.any(Buffer), 'a.mp3', 'opus');
+ expect(api.sendMessageWithMsgType).toHaveBeenNthCalledWith(
+ 2,
+ 'oc_chat',
+ 'audio',
+ JSON.stringify({ file_key: 'file_xyz' }),
+ );
+ });
+
+ it('continues remaining attachments when one upload fails', async () => {
+ const api = makeApi();
+ api.uploadImage
+ .mockRejectedValueOnce(new Error('429'))
+ .mockResolvedValueOnce({ image_key: 'img_2' });
+
+ const n = await sendFeishuAttachments(api as any, 'oc_chat', [
+ { data: Buffer.from('a').toString('base64'), name: 'a.png', type: 'image' },
+ { data: Buffer.from('b').toString('base64'), name: 'b.png', type: 'image' },
+ ]);
+
+ expect(n).toBe(1);
+ expect(api.sendMessageWithMsgType).toHaveBeenCalledTimes(1);
+ });
+
+ it('returns 0 when no attachments resolve', async () => {
+ const api = makeApi();
+
+ const n = await sendFeishuAttachments(api as any, 'oc_chat', [
+ { type: 'image' } as any, // no data, no fetchUrl
+ ]);
+
+ expect(n).toBe(0);
+ expect(api.uploadImage).not.toHaveBeenCalled();
+ expect(api.sendMessageWithMsgType).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/bot/platforms/feishu/sendAttachments.ts b/src/server/services/bot/platforms/feishu/sendAttachments.ts
new file mode 100644
index 00000000000..5c83824be34
--- /dev/null
+++ b/src/server/services/bot/platforms/feishu/sendAttachments.ts
@@ -0,0 +1,118 @@
+import type { LarkApiClient } from '@lobechat/chat-adapter-feishu';
+import debug from 'debug';
+
+import type { BotMessageAttachment } from '../types';
+
+const log = debug('bot-platform:feishu:send-attachments');
+
+type LarkFileType = 'opus' | 'mp4' | 'pdf' | 'doc' | 'xls' | 'ppt' | 'stream';
+
+/**
+ * Map a `BotMessageAttachment` to the Lark/Feishu `file_type` enum used by
+ * `POST /im/v1/files`. The upload API rejects unknown values, so when we
+ * can't infer a known extension we fall back to `stream` (generic binary).
+ */
+const inferFeishuFileType = (att: BotMessageAttachment): LarkFileType => {
+ // Honor explicit attachment.type first.
+ if (att.type === 'audio') return 'opus';
+ if (att.type === 'video') return 'mp4';
+
+ const name = (att.name ?? '').toLowerCase();
+ const mime = (att.mimeType ?? '').toLowerCase();
+
+ if (name.endsWith('.pdf') || mime === 'application/pdf') return 'pdf';
+ if (name.endsWith('.doc') || name.endsWith('.docx') || mime.includes('msword')) return 'doc';
+ if (name.endsWith('.xls') || name.endsWith('.xlsx') || mime.includes('excel')) return 'xls';
+ if (name.endsWith('.ppt') || name.endsWith('.pptx') || mime.includes('powerpoint')) return 'ppt';
+ if (mime.startsWith('audio/')) return 'opus';
+ if (mime.startsWith('video/')) return 'mp4';
+ return 'stream';
+};
+
+const fallbackFilename = (att: BotMessageAttachment, index: number): string => {
+ if (att.name) return att.name;
+ if (att.fetchUrl) {
+ try {
+ const base = new URL(att.fetchUrl).pathname.split('/').pop();
+ if (base) return base;
+ } catch {
+ // fall through
+ }
+ }
+ return `attachment-${index + 1}`;
+};
+
+const loadAttachmentBuffer = async (
+ attachment: BotMessageAttachment,
+): Promise<Buffer | undefined> => {
+ if (attachment.data) {
+ try {
+ return Buffer.from(attachment.data, 'base64');
+ } catch (error) {
+ log('loadAttachmentBuffer: failed to decode base64: %O', error);
+ }
+ }
+ if (attachment.fetchUrl) {
+ try {
+ const response = await fetch(attachment.fetchUrl, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (response.ok) {
+ return Buffer.from(await response.arrayBuffer());
+ }
+ log('loadAttachmentBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);
+ } catch (error) {
+ log('loadAttachmentBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);
+ }
+ }
+ return undefined;
+};
+
+/**
+ * Upload + send each attachment as its own Lark/Feishu message:
+ *
+ * - `image` → `POST /im/v1/images` → `sendMessageWithMsgType(chatId, 'image', {image_key})`
+ * - `file` / `video` / `audio` → `POST /im/v1/files` → `sendMessageWithMsgType`
+ * with msg_type `'file'` / `'media'` / `'audio'` respectively.
+ *
+ * Lark/Feishu has no single "text + media" composite message, so the caller
+ * sends the text leg through a separate `sendMessage` (or `replyMessage`)
+ * first. Single-attachment failures are logged and skipped so the rest
+ * still ship.
+ */
+export const sendFeishuAttachments = async (
+ api: LarkApiClient,
+ chatId: string,
+ attachments: BotMessageAttachment[],
+): Promise<number> => {
+ let delivered = 0;
+ for (const [index, att] of attachments.entries()) {
+ try {
+ const buffer = await loadAttachmentBuffer(att);
+ if (!buffer) {
+ log('sendFeishuAttachments: skipping attachment with no resolvable bytes');
+ continue;
+ }
+ const filename = fallbackFilename(att, index);
+ if (att.type === 'image') {
+ const { image_key } = await api.uploadImage(buffer, filename);
+ await api.sendMessageWithMsgType(chatId, 'image', JSON.stringify({ image_key }));
+ } else {
+ const fileType = inferFeishuFileType(att);
+ const { file_key } = await api.uploadFile(buffer, filename, fileType);
+ const msgType: 'file' | 'media' | 'audio' =
+ att.type === 'video' ? 'media' : att.type === 'audio' ? 'audio' : 'file';
+ await api.sendMessageWithMsgType(chatId, msgType, JSON.stringify({ file_key }));
+ }
+ delivered += 1;
+ } catch (error) {
+ log(
+ 'sendFeishuAttachments: failed to send %s "%s": %O',
+ att.type,
+ att.name ?? '(unnamed)',
+ error,
+ );
+ }
+ }
+ return delivered;
+};
diff --git a/src/server/services/bot/platforms/feishu/service.ts b/src/server/services/bot/platforms/feishu/service.ts
index 1467feef6ad..f038ab7ee5b 100644
--- a/src/server/services/bot/platforms/feishu/service.ts
+++ b/src/server/services/bot/platforms/feishu/service.ts
@@ -42,6 +42,7 @@ import type { MessageRuntimeService } from '@/server/services/toolExecution/serv
import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';
import { MAX_FEISHU_HISTORY_LIMIT } from './const';
+import { sendFeishuAttachments } from './sendAttachments';
/**
* Normalize a Feishu/Lark message object to MessageItem.
@@ -82,10 +83,20 @@ export class FeishuMessageService implements MessageRuntimeService {
// ==================== Core Message Operations ====================
sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {
- const result = await this.api.sendMessage(params.channelId, params.content);
+ // Lark/Feishu has no composite "text + media" message, so the text leg
+ // ships first (so the user reads context before media) and each
+ // attachment becomes its own follow-up message.
+ let messageId: string | undefined;
+ if (params.content?.trim()) {
+ const result = await this.api.sendMessage(params.channelId, params.content);
+ messageId = result.messageId;
+ }
+ if (params.attachments?.length) {
+ await sendFeishuAttachments(this.api, params.channelId, params.attachments);
+ }
return {
channelId: params.channelId,
- messageId: result.messageId,
+ messageId,
platform: this.platformName,
};
};
diff --git a/src/server/services/bot/platforms/line/client.ts b/src/server/services/bot/platforms/line/client.ts
index 2de21d4fe86..394d6bc6eb8 100644
--- a/src/server/services/bot/platforms/line/client.ts
+++ b/src/server/services/bot/platforms/line/client.ts
@@ -27,6 +27,7 @@ import {
type ValidationResult,
} from '../types';
import { formatUsageStats } from '../utils';
+import { sendLineAttachments } from './sendAttachments';
const log = debug('bot-platform:line:bot');
@@ -167,10 +168,20 @@ class LineWebhookClient implements PlatformClient {
getMessenger(platformThreadId: string): PlatformMessenger {
const { id: recipient, type } = decodeThread(platformThreadId);
return {
- // Attachments are silently dropped for now — LINE outbound media is
- // its own follow-up; reply text still ships.
createMessage: async (content) => {
- await this.api.pushText(recipient, messengerContentText(content));
+ const text = messengerContentText(content);
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+ if (attachments?.length) {
+ // LINE has no composite text+media message — the leading-text path
+ // packs both into a single `push` so the user reads context before
+ // the media. `sendLineAttachments` handles fallback text-links
+ // for unsupported types (video/audio/file/data-only).
+ await sendLineAttachments(this.api, recipient, attachments, text);
+ return;
+ }
+ if (text.trim()) {
+ await this.api.pushText(recipient, text);
+ }
},
// LINE does not support editing — `supportsMessageEdit: false` makes the
// bridge skip the per-step progress edit, but we still implement this
diff --git a/src/server/services/bot/platforms/line/sendAttachments.test.ts b/src/server/services/bot/platforms/line/sendAttachments.test.ts
new file mode 100644
index 00000000000..d54d13c2fe1
--- /dev/null
+++ b/src/server/services/bot/platforms/line/sendAttachments.test.ts
@@ -0,0 +1,120 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { buildLineMessages, sendLineAttachments } from './sendAttachments';
+
+describe('buildLineMessages', () => {
+ it('puts the leading text first', () => {
+ const messages = buildLineMessages(
+ [{ fetchUrl: 'https://cdn.example.com/a.png', type: 'image' }],
+ 'hello',
+ );
+ expect(messages[0]).toEqual({ text: 'hello', type: 'text' });
+ expect(messages[1]).toEqual({
+ originalContentUrl: 'https://cdn.example.com/a.png',
+ previewImageUrl: 'https://cdn.example.com/a.png',
+ type: 'image',
+ });
+ });
+
+ it('emits typed image messages for https image attachments', () => {
+ const messages = buildLineMessages([
+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },
+ ]);
+ expect(messages).toEqual([
+ {
+ originalContentUrl: 'https://cdn.example.com/a.png',
+ previewImageUrl: 'https://cdn.example.com/a.png',
+ type: 'image',
+ },
+ ]);
+ });
+
+ it('degrades non-image / non-https / data-only attachments to text-links', () => {
+ const messages = buildLineMessages([
+ { fetchUrl: 'https://cdn.example.com/doc.pdf', name: 'doc.pdf', type: 'file' },
+ { fetchUrl: 'https://cdn.example.com/v.mp4', type: 'video' },
+ { data: 'aGVsbG8=', name: 'inline.png', type: 'image' },
+ ]);
+
+ expect(messages).toHaveLength(1);
+ expect(messages[0].type).toBe('text');
+ expect((messages[0] as any).text).toContain('doc.pdf');
+ expect((messages[0] as any).text).toContain('https://cdn.example.com/doc.pdf');
+ expect((messages[0] as any).text).toContain('attachment dropped: no public URL');
+ });
+
+ it('mixes typed image + text-fallback in the same push', () => {
+ const messages = buildLineMessages([
+ { fetchUrl: 'https://cdn.example.com/ok.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/bad.pdf', type: 'file' },
+ ]);
+ expect(messages).toHaveLength(2);
+ expect(messages[0].type).toBe('image');
+ expect(messages[1].type).toBe('text');
+ });
+
+ it('rejects http:// URLs (LINE requires HTTPS)', () => {
+ const messages = buildLineMessages([
+ { fetchUrl: 'http://insecure.example.com/a.png', type: 'image' },
+ ]);
+ expect(messages).toHaveLength(1);
+ expect(messages[0].type).toBe('text');
+ });
+});
+
+describe('sendLineAttachments', () => {
+ const makeApi = () => ({ push: vi.fn().mockResolvedValue(undefined) });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('returns the count of typed media messages (not text)', async () => {
+ const api = makeApi();
+ const n = await sendLineAttachments(
+ api as any,
+ 'U1',
+ [
+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/c.pdf', type: 'file' },
+ ],
+ 'hi',
+ );
+ // 2 image messages count; leading text + file text-fallback don't.
+ expect(n).toBe(2);
+ expect(api.push).toHaveBeenCalledTimes(1);
+ });
+
+ it('batches >5 messages across multiple push calls', async () => {
+ const api = makeApi();
+ const atts = Array.from({ length: 8 }, (_, i) => ({
+ fetchUrl: `https://cdn.example.com/${i}.png`,
+ type: 'image' as const,
+ }));
+ await sendLineAttachments(api as any, 'U1', atts);
+ // 8 image messages → 2 push batches (5 + 3)
+ expect(api.push).toHaveBeenCalledTimes(2);
+ expect((api.push.mock.calls[0][1] as any[]).length).toBe(5);
+ expect((api.push.mock.calls[1][1] as any[]).length).toBe(3);
+ });
+
+ it('continues to next batch when one push fails', async () => {
+ const api = makeApi();
+ api.push.mockRejectedValueOnce(new Error('rate limit'));
+ const atts = Array.from({ length: 6 }, (_, i) => ({
+ fetchUrl: `https://cdn.example.com/${i}.png`,
+ type: 'image' as const,
+ }));
+ await sendLineAttachments(api as any, 'U1', atts);
+ expect(api.push).toHaveBeenCalledTimes(2);
+ });
+
+ it('returns 0 and skips push when there are no resolvable messages', async () => {
+ const api = makeApi();
+ const n = await sendLineAttachments(api as any, 'U1', []);
+ expect(n).toBe(0);
+ expect(api.push).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/bot/platforms/line/sendAttachments.ts b/src/server/services/bot/platforms/line/sendAttachments.ts
new file mode 100644
index 00000000000..6322c496ca7
--- /dev/null
+++ b/src/server/services/bot/platforms/line/sendAttachments.ts
@@ -0,0 +1,106 @@
+import type { LineApiClient, LineOutboundMessage } from '@lobechat/chat-adapter-line';
+import debug from 'debug';
+
+import type { BotMessageAttachment } from '../types';
+
+const log = debug('bot-platform:line:send-attachments');
+
+/** LINE caps a single push at 5 message objects — callers must batch. */
+const LINE_MAX_MESSAGES_PER_PUSH = 5;
+
+/**
+ * LINE's Messaging API has no inline binary upload — every media message
+ * must reference a public HTTPS URL. Attachments delivered as `data` (base64)
+ * are degraded into a text fallback so the user at least sees *something*
+ * about the missing media. Hosting base64 content via a staging bucket is
+ * tracked separately.
+ */
+const REMOTE_URL_RE = /^https:\/\//;
+
+const renderTextLink = (att: BotMessageAttachment): string => {
+ const name = att.name ?? `${att.type}`;
+ if (att.fetchUrl) return `📎 ${name}: ${att.fetchUrl}`;
+ return `📎 ${name} (attachment dropped: no public URL)`;
+};
+
+const isHttpsUrl = (url: string | undefined): url is string => !!url && REMOTE_URL_RE.test(url);
+
+/**
+ * Convert outbound `BotMessageAttachment[]` into LINE-shaped push messages.
+ *
+ * Rules per LINE Messaging API:
+ * - `image` (HTTPS URL) → typed `image` message (reuse URL for preview)
+ * - `video` / `audio` / `file` / `data`-only → degrade to text-link
+ * (video needs a separate preview URL, audio needs `duration` in ms,
+ * file isn't supported via push at all; we don't have these inputs)
+ *
+ * `leadingText` is prepended as the first text message so the conversation
+ * keeps the "context first, media second" order users expect.
+ */
+export const buildLineMessages = (
+ attachments: BotMessageAttachment[],
+ leadingText?: string,
+): LineOutboundMessage[] => {
+ const out: LineOutboundMessage[] = [];
+
+ if (leadingText?.trim()) {
+ out.push({ text: leadingText, type: 'text' });
+ }
+
+ const fallbackLines: string[] = [];
+
+ for (const att of attachments) {
+ if (att.type === 'image' && isHttpsUrl(att.fetchUrl)) {
+ out.push({
+ originalContentUrl: att.fetchUrl,
+ previewImageUrl: att.fetchUrl,
+ type: 'image',
+ });
+ continue;
+ }
+
+ // Video / audio / file: see header comment. Degrade to text-link.
+ log(
+ 'buildLineMessages: degrading %s "%s" to text link (LINE push API limitation)',
+ att.type,
+ att.name ?? '(unnamed)',
+ );
+ fallbackLines.push(renderTextLink(att));
+ }
+
+ if (fallbackLines.length > 0) {
+ out.push({ text: fallbackLines.join('\n'), type: 'text' });
+ }
+
+ return out;
+};
+
+/**
+ * Build LINE messages and push them in batches of `LINE_MAX_MESSAGES_PER_PUSH`.
+ * Returns the number of attachments that landed as a typed media message
+ * (text-link fallbacks don't count). Single push-batch failures are logged
+ * and the next batch still attempts — partial delivery is better than none.
+ */
+export const sendLineAttachments = async (
+ api: LineApiClient,
+ recipient: string,
+ attachments: BotMessageAttachment[],
+ leadingText?: string,
+): Promise<number> => {
+ const messages = buildLineMessages(attachments, leadingText);
+ if (messages.length === 0) return 0;
+
+ for (let i = 0; i < messages.length; i += LINE_MAX_MESSAGES_PER_PUSH) {
+ const batch = messages.slice(i, i + LINE_MAX_MESSAGES_PER_PUSH);
+ try {
+ await api.push(recipient, batch);
+ } catch (error) {
+ log('sendLineAttachments: push batch failed: %O', error);
+ }
+ }
+
+ // Count typed media messages (non-text) — they correspond to attachments
+ // that successfully became real media. Text and text-link fallbacks
+ // aren't "media".
+ return messages.filter((m) => m.type !== 'text').length;
+};
diff --git a/src/server/services/bot/platforms/qq/client.ts b/src/server/services/bot/platforms/qq/client.ts
index 2b7cdc871b3..d4d31666356 100644
--- a/src/server/services/bot/platforms/qq/client.ts
+++ b/src/server/services/bot/platforms/qq/client.ts
@@ -22,6 +22,7 @@ import {
type ValidationResult,
} from '../types';
import { formatUsageStats } from '../utils';
+import { sendQQAttachments } from './sendAttachments';
const log = debug('bot-platform:qq:bot');
@@ -266,10 +267,15 @@ class QQGatewayClient implements PlatformClient {
const targetId = extractChatId(platformThreadId);
const threadType = extractThreadType(platformThreadId);
return {
- // Attachments are silently dropped for now — QQ outbound media is its
- // own follow-up; reply text still ships.
- createMessage: (content) =>
- sendQQMessage(api, threadType, targetId, messengerContentText(content)),
+ createMessage: async (content) => {
+ const text = messengerContentText(content);
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+ if (attachments?.length) {
+ await sendQQAttachments(api, threadType, targetId, attachments, text);
+ return;
+ }
+ await sendQQMessage(api, threadType, targetId, text);
+ },
editMessage: (_messageId, content) =>
// QQ does not support editing — send a new message as fallback
sendQQMessage(api, threadType, targetId, messengerContentText(content)),
@@ -369,10 +375,15 @@ class QQWebhookClient implements PlatformClient {
const targetId = extractChatId(platformThreadId);
const threadType = extractThreadType(platformThreadId);
return {
- // Attachments are silently dropped for now — QQ outbound media is its
- // own follow-up; reply text still ships.
- createMessage: (content) =>
- sendQQMessage(api, threadType, targetId, messengerContentText(content)),
+ createMessage: async (content) => {
+ const text = messengerContentText(content);
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+ if (attachments?.length) {
+ await sendQQAttachments(api, threadType, targetId, attachments, text);
+ return;
+ }
+ await sendQQMessage(api, threadType, targetId, text);
+ },
editMessage: (_messageId, content) =>
sendQQMessage(api, threadType, targetId, messengerContentText(content)),
removeReaction: () => Promise.resolve(),
diff --git a/src/server/services/bot/platforms/qq/sendAttachments.test.ts b/src/server/services/bot/platforms/qq/sendAttachments.test.ts
new file mode 100644
index 00000000000..a66f7eebb43
--- /dev/null
+++ b/src/server/services/bot/platforms/qq/sendAttachments.test.ts
@@ -0,0 +1,122 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { sendQQAttachments } from './sendAttachments';
+
+const makeApi = () => ({
+ sendC2CMedia: vi.fn().mockResolvedValue({ id: 'm', timestamp: '' }),
+ sendC2CMessage: vi.fn().mockResolvedValue({ id: 'm', timestamp: '' }),
+ sendDmsMessage: vi.fn().mockResolvedValue({ id: 'm', timestamp: '' }),
+ sendGroupMedia: vi.fn().mockResolvedValue({ id: 'm', timestamp: '' }),
+ sendGroupMessage: vi.fn().mockResolvedValue({ id: 'm', timestamp: '' }),
+ sendGuildMessage: vi.fn().mockResolvedValue({ id: 'm', timestamp: '' }),
+ uploadC2CRichMedia: vi.fn().mockResolvedValue({ file_info: 'fi-c2c' }),
+ uploadGroupRichMedia: vi.fn().mockResolvedValue({ file_info: 'fi-group' }),
+});
+
+describe('sendQQAttachments', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('group: uploads via uploadGroupRichMedia and sends via sendGroupMedia', async () => {
+ const api = makeApi();
+ const n = await sendQQAttachments(
+ api as any,
+ 'group',
+ 'gid-1',
+ [{ fetchUrl: 'https://cdn.example.com/a.png', name: 'a.png', type: 'image' }],
+ 'hi',
+ );
+ expect(n).toBe(1);
+ expect(api.uploadGroupRichMedia).toHaveBeenCalledWith(
+ 'gid-1',
+ 1,
+ 'https://cdn.example.com/a.png',
+ );
+ expect(api.sendGroupMedia).toHaveBeenCalledWith('gid-1', 'fi-group');
+ // Text leg goes through sendGroupMessage as a separate call
+ expect(api.sendGroupMessage).toHaveBeenCalledWith('gid-1', 'hi');
+ });
+
+ it('c2c: uses C2C upload + send', async () => {
+ const api = makeApi();
+ const n = await sendQQAttachments(api as any, 'c2c', 'openid-1', [
+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },
+ ]);
+ expect(n).toBe(1);
+ expect(api.uploadC2CRichMedia).toHaveBeenCalled();
+ expect(api.sendC2CMedia).toHaveBeenCalled();
+ });
+
+ it('infers QQ file_type from attachment.type (image=1, video=2, audio=3, file=4)', async () => {
+ const api = makeApi();
+ await sendQQAttachments(api as any, 'group', 'gid', [
+ { fetchUrl: 'https://x/a.png', type: 'image' },
+ { fetchUrl: 'https://x/b.mp4', type: 'video' },
+ { fetchUrl: 'https://x/c.mp3', type: 'audio' },
+ { fetchUrl: 'https://x/d.pdf', type: 'file' },
+ ]);
+ expect(api.uploadGroupRichMedia.mock.calls.map((c) => c[1])).toEqual([1, 2, 3, 4]);
+ });
+
+ it('guild: all attachments degrade to a text-link line', async () => {
+ const api = makeApi();
+ const n = await sendQQAttachments(
+ api as any,
+ 'guild',
+ 'cid',
+ [
+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/b.pdf', name: 'b.pdf', type: 'file' },
+ ],
+ 'check this',
+ );
+ expect(n).toBe(0);
+ expect(api.uploadGroupRichMedia).not.toHaveBeenCalled();
+ // Combined into a single sendGuildMessage call
+ expect(api.sendGuildMessage).toHaveBeenCalledTimes(1);
+ const text = api.sendGuildMessage.mock.calls[0][1];
+ expect(text).toContain('check this');
+ expect(text).toContain('https://cdn.example.com/a.png');
+ expect(text).toContain('b.pdf');
+ });
+
+ it('data-only attachments fall back to text-link (no public URL)', async () => {
+ const api = makeApi();
+ const n = await sendQQAttachments(api as any, 'group', 'gid', [
+ { data: 'aGVsbG8=', name: 'inline.png', type: 'image' },
+ ]);
+ expect(n).toBe(0);
+ expect(api.uploadGroupRichMedia).not.toHaveBeenCalled();
+ const text = api.sendGroupMessage.mock.calls[0][1];
+ expect(text).toContain('inline.png');
+ expect(text).toContain('attachment dropped: no public URL');
+ });
+
+ it('keeps remaining media + falls back on failed upload', async () => {
+ const api = makeApi();
+ api.uploadGroupRichMedia
+ .mockRejectedValueOnce(new Error('429'))
+ .mockResolvedValueOnce({ file_info: 'fi-2' });
+ const n = await sendQQAttachments(api as any, 'group', 'gid', [
+ { fetchUrl: 'https://x/a.png', name: 'a.png', type: 'image' },
+ { fetchUrl: 'https://x/b.png', name: 'b.png', type: 'image' },
+ ]);
+ expect(n).toBe(1);
+ expect(api.sendGroupMedia).toHaveBeenCalledTimes(1);
+ // The failing attachment becomes a text-link in the fallback
+ expect(api.sendGroupMessage).toHaveBeenCalledTimes(1);
+ expect(api.sendGroupMessage.mock.calls[0][1]).toContain('a.png');
+ });
+
+ it('skips text leg when there is nothing to say', async () => {
+ const api = makeApi();
+ await sendQQAttachments(api as any, 'group', 'gid', [
+ { fetchUrl: 'https://x/a.png', type: 'image' },
+ ]);
+ // No leadingText, no fallback lines → no text call
+ expect(api.sendGroupMessage).not.toHaveBeenCalled();
+ expect(api.sendGroupMedia).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/server/services/bot/platforms/qq/sendAttachments.ts b/src/server/services/bot/platforms/qq/sendAttachments.ts
new file mode 100644
index 00000000000..1413857d764
--- /dev/null
+++ b/src/server/services/bot/platforms/qq/sendAttachments.ts
@@ -0,0 +1,153 @@
+import type { QQApiClient } from '@lobechat/chat-adapter-qq';
+import debug from 'debug';
+
+import type { BotMessageAttachment } from '../types';
+
+const log = debug('bot-platform:qq:send-attachments');
+
+/**
+ * QQ openplatform rich-media file_type enum.
+ * 1 = image, 2 = video, 3 = voice, 4 = file
+ */
+type QQFileType = 1 | 2 | 3 | 4;
+
+const inferQQFileType = (att: BotMessageAttachment): QQFileType => {
+ switch (att.type) {
+ case 'image': {
+ return 1;
+ }
+ case 'video': {
+ return 2;
+ }
+ case 'audio': {
+ return 3;
+ }
+ case 'file':
+ default: {
+ return 4;
+ }
+ }
+};
+
+const renderTextLink = (att: BotMessageAttachment): string => {
+ const name = att.name ?? att.type;
+ if (att.fetchUrl) return `📎 ${name}: ${att.fetchUrl}`;
+ return `📎 ${name} (attachment dropped: no public URL)`;
+};
+
+type ThreadType = 'group' | 'guild' | 'c2c' | 'dms' | string;
+
+const supportsRichMedia = (threadType: ThreadType): threadType is 'group' | 'c2c' =>
+ threadType === 'group' || threadType === 'c2c';
+
+/**
+ * Dispatch a text-only message to the right QQ endpoint. Mirrors the
+ * `sendQQMessage` helper in `qq/client.ts` but kept private here so the
+ * attachments path doesn't pull a circular dep.
+ */
+const sendText = async (
+ api: QQApiClient,
+ threadType: ThreadType,
+ targetId: string,
+ text: string,
+): Promise<void> => {
+ if (!text.trim()) return;
+ switch (threadType) {
+ case 'group': {
+ await api.sendGroupMessage(targetId, text);
+ return;
+ }
+ case 'guild': {
+ await api.sendGuildMessage(targetId, text);
+ return;
+ }
+ case 'c2c': {
+ await api.sendC2CMessage(targetId, text);
+ return;
+ }
+ case 'dms': {
+ await api.sendDmsMessage(targetId, text);
+ return;
+ }
+ default: {
+ await api.sendGroupMessage(targetId, text);
+ }
+ }
+};
+
+/**
+ * Deliver attachments alongside an outbound QQ reply.
+ *
+ * Two flavours, chosen by `threadType`:
+ *
+ * - **`group` / `c2c`** — full rich-media path. For each attachment with a
+ * public HTTPS `fetchUrl`, upload it to get a `file_info` token, then
+ * post a separate `msg_type: 7 (MEDIA)` message. QQ doesn't allow media
+ * + content on the same message, so the text leg ships as its own call.
+ * - **`guild` / `dms`** — the channel API requires multipart upload which
+ * isn't implemented here yet; attachments degrade to a text-link line.
+ *
+ * `data` (base64) attachments also degrade to text-link because QQ's
+ * upload API only accepts URLs and this codebase has no staging bucket.
+ *
+ * Returns the number of attachments successfully delivered as media (not
+ * text-link fallbacks).
+ */
+export const sendQQAttachments = async (
+ api: QQApiClient,
+ threadType: ThreadType,
+ targetId: string,
+ attachments: BotMessageAttachment[],
+ leadingText?: string,
+): Promise<number> => {
+ // Text leg first so the conversation reads context → media.
+ const fallbackLines: string[] = [];
+ let mediaDelivered = 0;
+
+ if (supportsRichMedia(threadType)) {
+ for (const att of attachments) {
+ if (!att.fetchUrl) {
+ fallbackLines.push(renderTextLink(att));
+ continue;
+ }
+ try {
+ const fileType = inferQQFileType(att);
+ const upload =
+ threadType === 'group'
+ ? await api.uploadGroupRichMedia(targetId, fileType, att.fetchUrl)
+ : await api.uploadC2CRichMedia(targetId, fileType, att.fetchUrl);
+ if (threadType === 'group') {
+ await api.sendGroupMedia(targetId, upload.file_info);
+ } else {
+ await api.sendC2CMedia(targetId, upload.file_info);
+ }
+ mediaDelivered += 1;
+ } catch (error) {
+ log(
+ 'sendQQAttachments: failed on %s "%s" — degrading to text link: %O',
+ att.type,
+ att.name ?? '(unnamed)',
+ error,
+ );
+ fallbackLines.push(renderTextLink(att));
+ }
+ }
+ } else {
+ // guild / dms / unknown — all attachments degrade.
+ for (const att of attachments) {
+ fallbackLines.push(renderTextLink(att));
+ }
+ }
+
+ const combinedText = [leadingText, fallbackLines.join('\n')]
+ .filter((s) => s && s.trim())
+ .join('\n\n');
+ if (combinedText) {
+ try {
+ await sendText(api, threadType, targetId, combinedText);
+ } catch (error) {
+ log('sendQQAttachments: text leg failed: %O', error);
+ }
+ }
+ return mediaDelivered;
+};
diff --git a/src/server/services/bot/platforms/slack/api.ts b/src/server/services/bot/platforms/slack/api.ts
index 1b627c1e173..cf8e54c6cad 100644
--- a/src/server/services/bot/platforms/slack/api.ts
+++ b/src/server/services/bot/platforms/slack/api.ts
@@ -506,6 +506,73 @@ export class SlackApi {
];
}
+ // ==================== Outbound File Upload (v2) ====================
+
+ /**
+ * Step 1 of the Slack v2 upload flow: request a one-shot upload URL plus a
+ * `file_id` we'll later associate with a channel via
+ * `completeFileUpload`.
+ *
+ * See: https://api.slack.com/methods/files.getUploadURLExternal
+ */
+ async getFileUploadUrl(params: {
+ filename: string;
+ length: number;
+ }): Promise<{ file_id: string; upload_url: string }> {
+ log('getFileUploadUrl: filename=%s, length=%d', params.filename, params.length);
+ const data = await this.call('files.getUploadURLExternal', {
+ filename: params.filename,
+ length: params.length,
+ });
+ return { file_id: data.file_id, upload_url: data.upload_url };
+ }
+
+ /**
+ * Step 2: PUT the binary bytes to the signed upload URL Slack returned in
+ * step 1. The URL is signed, so no `Authorization` header is needed (and
+ * including one is actively rejected).
+ */
+ async putFileBytes(uploadUrl: string, buffer: Buffer): Promise<void> {
+ log('putFileBytes: bytes=%d', buffer.length);
+ const response = await fetch(uploadUrl, {
+ body: new Uint8Array(buffer),
+ method: 'POST',
+ });
+ if (!response.ok) {
+ const text = await response.text();
+ throw new Error(`Slack v2 upload failed: ${response.status} ${text}`);
+ }
+ }
+
+ /**
+ * Step 3: associate uploaded file_id(s) with a channel and post the file
+ * message. `initial_comment` doubles as the text leg of the reply so
+ * callers don't have to send a separate `chat.postMessage`.
+ *
+ * See: https://api.slack.com/methods/files.completeUploadExternal
+ */
+ async completeFileUpload(params: {
+ channelId: string;
+ files: Array<{ id: string; title?: string }>;
+ initialComment?: string;
+ threadTs?: string;
+ }): Promise<void> {
+ log(
+ 'completeFileUpload: channel=%s, files=%d, thread=%s',
+ params.channelId,
+ params.files.length,
+ params.threadTs ?? '(none)',
+ );
+ await this.call('files.completeUploadExternal', {
+ channel_id: params.channelId,
+ files: params.files,
+ initial_comment: params.initialComment,
+ thread_ts: params.threadTs,
+ });
+ }
+
+ // ==================== Private ====================
+
private async call(method: string, body: Record<string, unknown>): Promise<any> {
const url = `${SLACK_API_BASE}/${method}`;
diff --git a/src/server/services/bot/platforms/slack/client.ts b/src/server/services/bot/platforms/slack/client.ts
index b8b9cb84870..d47490fd532 100644
--- a/src/server/services/bot/platforms/slack/client.ts
+++ b/src/server/services/bot/platforms/slack/client.ts
@@ -23,6 +23,7 @@ import { formatUsageStats } from '../utils';
import { SLACK_API_BASE, SlackApi } from './api';
import { SlackSocketModeConnection } from './gateway';
import { markdownToSlackMrkdwn } from './markdownToMrkdwn';
+import { sendSlackAttachments } from './sendAttachments';
const log = debug('bot-platform:slack:bot');
@@ -51,14 +52,30 @@ function createMessenger(config: BotProviderConfig, platformThreadId: string): P
return {
addReaction: (messageId, emoji) => slack.addReaction(channelId, messageId, emoji),
- // Attachments are silently dropped for now — Slack outbound media is
- // its own follow-up; reply text still ships.
- createMessage: (content) => {
+ createMessage: async (content) => {
const text = messengerContentText(content);
- return threadTs
- ? slack.postMessageInThread(channelId, threadTs, text).then(() => {})
- : slack.postMessage(channelId, text).then(() => {});
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+ if (attachments?.length) {
+ const delivered = await sendSlackAttachments(slack, {
+ attachments,
+ channelId,
+ initialComment: text,
+ threadTs,
+ });
+ if (delivered > 0) return;
+ // All attachments failed → fall through to text-only so the reply
+ // still reaches the user.
+ }
+ if (!text.trim()) return;
+ if (threadTs) {
+ await slack.postMessageInThread(channelId, threadTs, text);
+ } else {
+ await slack.postMessage(channelId, text);
+ }
},
+ // editMessage keeps the text-only contract. Slack v2 file attachments
+ // can't be added to an existing message in-place — new chunks with
+ // attachments flow through createMessage instead.
editMessage: (messageId, content) =>
slack.updateMessage(channelId, messageId, messengerContentText(content)),
removeReaction: (messageId, emoji) => slack.removeReaction(channelId, messageId, emoji),
diff --git a/src/server/services/bot/platforms/slack/sendAttachments.test.ts b/src/server/services/bot/platforms/slack/sendAttachments.test.ts
new file mode 100644
index 00000000000..61090eeef5a
--- /dev/null
+++ b/src/server/services/bot/platforms/slack/sendAttachments.test.ts
@@ -0,0 +1,119 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { sendSlackAttachments } from './sendAttachments';
+
+const makeApi = () => ({
+ completeFileUpload: vi.fn().mockResolvedValue(undefined),
+ getFileUploadUrl: vi.fn().mockResolvedValue({
+ file_id: 'F123',
+ upload_url: 'https://files.slack.com/upload/x',
+ }),
+ putFileBytes: vi.fn().mockResolvedValue(undefined),
+});
+
+describe('sendSlackAttachments', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', vi.fn());
+ });
+
+ it('runs the 3-step v2 flow for base64 attachments', async () => {
+ const api = makeApi();
+
+ const n = await sendSlackAttachments(api as any, {
+ attachments: [
+ {
+ data: Buffer.from('hello').toString('base64'),
+ mimeType: 'image/png',
+ name: 'foo.png',
+ type: 'image',
+ },
+ ],
+ channelId: 'C1',
+ initialComment: 'caption',
+ threadTs: '123.456',
+ });
+
+ expect(n).toBe(1);
+ expect(api.getFileUploadUrl).toHaveBeenCalledWith({
+ filename: 'foo.png',
+ length: Buffer.from('hello').length,
+ });
+ expect(api.putFileBytes).toHaveBeenCalledWith(
+ 'https://files.slack.com/upload/x',
+ expect.any(Buffer),
+ );
+ expect(api.completeFileUpload).toHaveBeenCalledWith({
+ channelId: 'C1',
+ files: [{ id: 'F123', title: 'foo.png' }],
+ initialComment: 'caption',
+ threadTs: '123.456',
+ });
+ });
+
+ it('fetches fetchUrl attachments and uploads the bytes', async () => {
+ const api = makeApi();
+ const fetchMock = vi.mocked(fetch);
+ fetchMock.mockResolvedValueOnce(
+ new Response(new Uint8Array([1, 2, 3, 4]), { status: 200 }) as any,
+ );
+
+ const n = await sendSlackAttachments(api as any, {
+ attachments: [{ fetchUrl: 'https://cdn.example.com/pic.png', type: 'image' }],
+ channelId: 'C1',
+ });
+
+ expect(n).toBe(1);
+ expect(fetchMock).toHaveBeenCalledWith('https://cdn.example.com/pic.png', expect.any(Object));
+ expect(api.getFileUploadUrl).toHaveBeenCalled();
+ expect(api.putFileBytes).toHaveBeenCalled();
+ expect(api.completeFileUpload).toHaveBeenCalled();
+ });
+
+ it('keeps remaining attachments when one fails to upload', async () => {
+ const api = makeApi();
+ api.getFileUploadUrl.mockRejectedValueOnce(new Error('slack 429')).mockResolvedValueOnce({
+ file_id: 'F999',
+ upload_url: 'https://files.slack.com/upload/y',
+ });
+
+ const n = await sendSlackAttachments(api as any, {
+ attachments: [
+ { data: Buffer.from('a').toString('base64'), name: 'a.png', type: 'image' },
+ { data: Buffer.from('b').toString('base64'), name: 'b.png', type: 'image' },
+ ],
+ channelId: 'C1',
+ });
+
+ expect(n).toBe(1);
+ expect(api.completeFileUpload).toHaveBeenCalledWith(
+ expect.objectContaining({ files: [{ id: 'F999', title: 'b.png' }] }),
+ );
+ });
+
+ it('returns 0 when all attachments fail (no completeFileUpload call)', async () => {
+ const api = makeApi();
+ api.getFileUploadUrl.mockRejectedValue(new Error('slack 500'));
+
+ const n = await sendSlackAttachments(api as any, {
+ attachments: [{ data: Buffer.from('x').toString('base64'), name: 'x.png', type: 'image' }],
+ channelId: 'C1',
+ });
+
+ expect(n).toBe(0);
+ expect(api.completeFileUpload).not.toHaveBeenCalled();
+ });
+
+ it('returns 0 when completeFileUpload itself fails', async () => {
+ const api = makeApi();
+ api.completeFileUpload.mockRejectedValueOnce(new Error('slack down'));
+
+ const n = await sendSlackAttachments(api as any, {
+ attachments: [{ data: Buffer.from('x').toString('base64'), name: 'x.png', type: 'image' }],
+ channelId: 'C1',
+ });
+
+ expect(n).toBe(0);
+ });
+});
diff --git a/src/server/services/bot/platforms/slack/sendAttachments.ts b/src/server/services/bot/platforms/slack/sendAttachments.ts
new file mode 100644
index 00000000000..bfaeee88b14
--- /dev/null
+++ b/src/server/services/bot/platforms/slack/sendAttachments.ts
@@ -0,0 +1,104 @@
+import debug from 'debug';
+
+import type { BotMessageAttachment } from '../types';
+import type { SlackApi } from './api';
+
+const log = debug('bot-platform:slack:send-attachments');
+
+const loadAttachmentBuffer = async (
+ attachment: BotMessageAttachment,
+): Promise<Buffer | undefined> => {
+ if (attachment.data) {
+ try {
+ return Buffer.from(attachment.data, 'base64');
+ } catch (error) {
+ log('loadAttachmentBuffer: failed to decode base64: %O', error);
+ }
+ }
+ if (attachment.fetchUrl) {
+ try {
+ const response = await fetch(attachment.fetchUrl, {
+ signal: AbortSignal.timeout(15_000),
+ });
+ if (response.ok) {
+ return Buffer.from(await response.arrayBuffer());
+ }
+ log('loadAttachmentBuffer: HTTP %d for %s', response.status, attachment.fetchUrl);
+ } catch (error) {
+ log('loadAttachmentBuffer: fetch failed for %s: %O', attachment.fetchUrl, error);
+ }
+ }
+ return undefined;
+};
+
+const fallbackFilename = (att: BotMessageAttachment, index: number): string => {
+ if (att.name) return att.name;
+ if (att.fetchUrl) {
+ try {
+ const base = new URL(att.fetchUrl).pathname.split('/').pop();
+ if (base) return base;
+ } catch {
+ // fall through
+ }
+ }
+ return `attachment-${index + 1}`;
+};
+
+/**
+ * Upload + post attachments to Slack via the v2 three-step flow:
+ *
+ * 1. `files.getUploadURLExternal` → signed upload URL + file id
+ * 2. PUT bytes to the signed URL (no auth header)
+ * 3. `files.completeUploadExternal` — associate file ids with a channel
+ * (and optional thread), posting the file message. `initialComment`
+ * doubles as the text leg of the reply.
+ *
+ * Single-attachment failures are logged and skipped so the rest still ship.
+ * Returns the number of files successfully uploaded — callers use 0 to
+ * decide whether to fall back to `postMessage` for the text leg.
+ */
+export const sendSlackAttachments = async (
+ api: SlackApi,
+ params: {
+ attachments: BotMessageAttachment[];
+ channelId: string;
+ initialComment?: string;
+ threadTs?: string;
+ },
+): Promise<number> => {
+ const uploaded: Array<{ id: string; title?: string }> = [];
+
+ for (const [index, att] of params.attachments.entries()) {
+ try {
+ const buffer = await loadAttachmentBuffer(att);
+ if (!buffer) {
+ log('sendSlackAttachments: skipping attachment with no resolvable bytes');
+ continue;
+ }
+ const filename = fallbackFilename(att, index);
+ const { file_id, upload_url } = await api.getFileUploadUrl({
+ filename,
+ length: buffer.length,
+ });
+ await api.putFileBytes(upload_url, buffer);
+ uploaded.push({ id: file_id, title: att.name });
+ } catch (error) {
+ log('sendSlackAttachments: failed on attachment "%s": %O', att.name ?? '(unnamed)', error);
+ }
+ }
+
+ if (uploaded.length === 0) return 0;
+
+ try {
+ await api.completeFileUpload({
+ channelId: params.channelId,
+ files: uploaded,
+ initialComment: params.initialComment,
+ threadTs: params.threadTs,
+ });
+ } catch (error) {
+ log('sendSlackAttachments: completeFileUpload failed: %O', error);
+ return 0;
+ }
+ return uploaded.length;
+};
diff --git a/src/server/services/bot/platforms/slack/service.ts b/src/server/services/bot/platforms/slack/service.ts
index 4509543f736..fa1f68dc8d3 100644
--- a/src/server/services/bot/platforms/slack/service.ts
+++ b/src/server/services/bot/platforms/slack/service.ts
@@ -42,6 +42,7 @@ import { PlatformUnsupportedError } from '@/server/services/toolExecution/server
import type { SlackApi } from './api';
import { MAX_SLACK_HISTORY_LIMIT } from './const';
+import { sendSlackAttachments } from './sendAttachments';
/**
* Normalize a Slack message object to MessageItem.
@@ -61,6 +62,19 @@ export class SlackMessageService implements MessageRuntimeService {
// ==================== Core Message Operations ====================
sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {
+ if (params.attachments?.length) {
+ const delivered = await sendSlackAttachments(this.api, {
+ attachments: params.attachments,
+ channelId: params.channelId,
+ initialComment: params.content,
+ // The TRPC / builtin-tool path doesn't carry a thread anchor today.
+ // The agent-reply path goes through `SlackGatewayClient.getMessenger`
+ // which DOES carry thread_ts and uses `sendSlackAttachments` directly.
+ });
+ if (delivered > 0) {
+ return { channelId: params.channelId, platform: 'slack' };
+ }
+ }
const result = await this.api.postMessage(params.channelId, params.content);
return { channelId: params.channelId, messageId: result.ts, platform: 'slack' };
};
diff --git a/src/server/services/bot/platforms/telegram/api.test.ts b/src/server/services/bot/platforms/telegram/api.test.ts
index e67bc7c9d09..7ee1fb71897 100644
--- a/src/server/services/bot/platforms/telegram/api.test.ts
+++ b/src/server/services/bot/platforms/telegram/api.test.ts
@@ -89,6 +89,55 @@ describe('TelegramApi HTML parse fallback', () => {
);
});
+ it('sendPhoto retries caption without parse_mode on HTML parse error', async () => {
+ fetchSpy
+ .mockResolvedValueOnce(
+ telegramErrorResponse(
+ 400,
+ 'Bad Request: can\'t parse entities: Unsupported start tag "foo" at byte offset 5',
+ ),
+ )
+ .mockResolvedValueOnce(okResponse({ message_id: 7 }));
+
+ const api = new TelegramApi(BOT_TOKEN);
+ const result = await api.sendPhoto({
+ caption: 'look at <foo> & the answer is 42',
+ chatId: 'chat-1',
+ source: { url: 'https://example.com/img.png' },
+ });
+
+ expect(result).toEqual({ message_id: 7 });
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+
+ const retryBody = JSON.parse((fetchSpy.mock.calls[1][1] as RequestInit).body as string);
+ expect(retryBody.parse_mode).toBeUndefined();
+ expect(retryBody.caption).not.toContain('<foo>');
+ expect(retryBody.caption).toContain('the answer is 42');
+ });
+
+ it('sendDocument with Buffer source retries caption without HTML on parse error', async () => {
+ fetchSpy
+ .mockResolvedValueOnce(
+ telegramErrorResponse(400, "Bad Request: can't parse entities: Unsupported start tag"),
+ )
+ .mockResolvedValueOnce(okResponse({ message_id: 11 }));
+
+ const api = new TelegramApi(BOT_TOKEN);
+ const result = await api.sendDocument({
+ caption: '<b>bad',
+ chatId: 'chat-1',
+ source: { buffer: Buffer.from('hello'), filename: 'note.txt', mimeType: 'text/plain' },
+ });
+
+ expect(result).toEqual({ message_id: 11 });
+ expect(fetchSpy).toHaveBeenCalledTimes(2);
+
+ const retryInit = fetchSpy.mock.calls[1][1] as RequestInit;
+ const retryForm = retryInit.body as FormData;
+ expect(retryForm.get('parse_mode')).toBeNull();
+ expect(retryForm.get('caption')).toBe('bad');
+ });
+
it('TELEGRAM_API_BASE is exported', () => {
expect(TELEGRAM_API_BASE).toBe('https://api.telegram.org');
});
diff --git a/src/server/services/bot/platforms/telegram/api.ts b/src/server/services/bot/platforms/telegram/api.ts
index c61af0aff53..4380481efa0 100644
--- a/src/server/services/bot/platforms/telegram/api.ts
+++ b/src/server/services/bot/platforms/telegram/api.ts
@@ -456,4 +456,187 @@ export class TelegramApi {
return await attempt();
}
}
+
+ /**
+ * `multipart/form-data` variant for endpoints that take a binary upload
+ * (sendPhoto/sendDocument/...). `binaryField` names the form field that
+ * carries the file (Telegram inspects field names — `photo` for sendPhoto,
+ * `document` for sendDocument, etc.). Non-string scalars in `fields` are
+ * JSON-stringified so Telegram interprets numbers / booleans correctly.
+ */
+ private async callMultipart(
+ method: string,
+ fields: Record<string, string | number | boolean | undefined>,
+ file?: { binaryField: string; buffer: Buffer; filename: string; mimeType?: string },
+ ): Promise<any> {
+ const url = `${TELEGRAM_API_BASE}/bot${this.botToken}/${method}`;
+
+ const buildForm = (): FormData => {
+ const form = new FormData();
+ for (const [key, value] of Object.entries(fields)) {
+ if (value === undefined) continue;
+ form.append(key, typeof value === 'string' ? value : String(value));
+ }
+ if (file) {
+ const blob = new Blob([new Uint8Array(file.buffer)], {
+ type: file.mimeType ?? 'application/octet-stream',
+ });
+ form.append(file.binaryField, blob, file.filename);
+ }
+ return form;
+ };
+
+ const attempt = async (): Promise<any> => {
+ const response = await fetch(url, {
+ body: buildForm(),
+ method: 'POST',
+ // Let undici set the multipart boundary header automatically.
+ signal: AbortSignal.timeout(TELEGRAM_FETCH_TIMEOUT_MS),
+ });
+
+ if (!response.ok) {
+ const text = await response.text();
+ log(
+ 'Telegram API multipart error: method=%s, status=%d, body=%s',
+ method,
+ response.status,
+ text,
+ );
+ throw new Error(`Telegram API ${method} failed: ${response.status} ${text}`);
+ }
+
+ const data = await response.json();
+ if (data.ok === false) {
+ const desc = data.description || 'Unknown error';
+ log(
+ 'Telegram API logical error: method=%s, error_code=%d, description=%s',
+ method,
+ data.error_code,
+ desc,
+ );
+ throw new Error(`Telegram API ${method} failed: ${data.error_code} ${desc}`);
+ }
+ return data;
+ };
+
+ try {
+ return await attempt();
+ } catch (error) {
+ if (!isTransientNetworkError(error)) throw error;
+ log('Telegram API %s: transient network error, retrying once: %O', method, error);
+ return await attempt();
+ }
+ }
+
+ // ==================== Outbound Media ====================
+
+ /**
+ * Send media (image/file/video/audio) on Telegram. Each media type has its
+ * own API endpoint and dedicated binary field name, so callers go through
+ * one of the typed helpers below. URL-source goes via JSON; Buffer-source
+ * goes via multipart/form-data.
+ */
+ private async sendMedia(
+ method: 'sendPhoto' | 'sendDocument' | 'sendVideo' | 'sendAudio',
+ binaryField: 'photo' | 'document' | 'video' | 'audio',
+ params: {
+ caption?: string;
+ chatId: string | number;
+ source: { url: string } | { buffer: Buffer; filename: string; mimeType?: string };
+ },
+ ): Promise<{ message_id: number }> {
+ const caption = params.caption ? this.truncateCaption(params.caption) : undefined;
+
+ // Captions render as HTML so links/formatting survive — but the LLM/user
+ // content can contain unbalanced or stray `<`,`>`,`&`. Without this
+ // fallback the whole attachment send fails and the message degrades to
+ // text-only delivery; mirror the sendMessage retry-as-plain-text path.
+ const send = (useHtml: boolean): Promise<any> => {
+ const captionForSend =
+ caption && !useHtml ? this.truncateCaption(stripHTML(caption)) : caption;
+
+ if ('url' in params.source) {
+ return this.call(method, {
+ caption: captionForSend,
+ chat_id: params.chatId,
+ parse_mode: captionForSend && useHtml ? 'HTML' : undefined,
+ [binaryField]: params.source.url,
+ });
+ }
+
+ return this.callMultipart(
+ method,
+ {
+ caption: captionForSend,
+ chat_id: params.chatId,
+ parse_mode: captionForSend && useHtml ? 'HTML' : undefined,
+ },
+ {
+ binaryField,
+ buffer: params.source.buffer,
+ filename: params.source.filename,
+ mimeType: params.source.mimeType,
+ },
+ );
+ };
+
+ try {
+ const data = await send(true);
+ return { message_id: data.result.message_id };
+ } catch (error) {
+ if (!caption || !isParseEntitiesError(error)) throw error;
+ log(
+ '%s: caption HTML parse failed, retrying as plain text. chatId=%s',
+ method,
+ params.chatId,
+ );
+ const data = await send(false);
+ return { message_id: data.result.message_id };
+ }
+ }
+
+ async sendPhoto(params: {
+ caption?: string;
+ chatId: string | number;
+ source: { url: string } | { buffer: Buffer; filename: string; mimeType?: string };
+ }): Promise<{ message_id: number }> {
+ log('sendPhoto: chatId=%s', params.chatId);
+ return this.sendMedia('sendPhoto', 'photo', params);
+ }
+
+ async sendDocument(params: {
+ caption?: string;
+ chatId: string | number;
+ source: { url: string } | { buffer: Buffer; filename: string; mimeType?: string };
+ }): Promise<{ message_id: number }> {
+ log('sendDocument: chatId=%s', params.chatId);
+ return this.sendMedia('sendDocument', 'document', params);
+ }
+
+ async sendVideo(params: {
+ caption?: string;
+ chatId: string | number;
+ source: { url: string } | { buffer: Buffer; filename: string; mimeType?: string };
+ }): Promise<{ message_id: number }> {
+ log('sendVideo: chatId=%s', params.chatId);
+ return this.sendMedia('sendVideo', 'video', params);
+ }
+
+ async sendAudio(params: {
+ caption?: string;
+ chatId: string | number;
+ source: { url: string } | { buffer: Buffer; filename: string; mimeType?: string };
+ }): Promise<{ message_id: number }> {
+ log('sendAudio: chatId=%s', params.chatId);
+ return this.sendMedia('sendAudio', 'audio', params);
+ }
+
+ /**
+ * Telegram caption limit is 1024 characters (vs. 4096 for sendMessage).
+ * Truncate with an ellipsis instead of letting the API reject the call.
+ */
+ private truncateCaption(text: string): string {
+ if (text.length > 1024) return text.slice(0, 1021) + '...';
+ return text;
+ }
}
diff --git a/src/server/services/bot/platforms/telegram/client.ts b/src/server/services/bot/platforms/telegram/client.ts
index 3909cbfa6f6..b65cc1d5aed 100644
--- a/src/server/services/bot/platforms/telegram/client.ts
+++ b/src/server/services/bot/platforms/telegram/client.ts
@@ -24,6 +24,7 @@ import { formatUsageStats } from '../utils';
import { TELEGRAM_API_BASE, TelegramApi } from './api';
import { extractBotId, setTelegramWebhook } from './helpers';
import { markdownToTelegramHTML } from './markdownToHTML';
+import { sendTelegramAttachments } from './sendAttachments';
const log = debug('bot-platform:telegram:bot');
@@ -176,10 +177,22 @@ class TelegramWebhookClient implements PlatformClient {
return {
addReaction: (messageId, emoji) =>
telegram.setMessageReaction(chatId, parseTelegramMessageId(messageId), emoji),
- // Attachments are silently dropped — Telegram outbound media support
- // is tracked in its own follow-up; reply text still ships.
- createMessage: (content) =>
- telegram.sendMessage(chatId, messengerContentText(content)).then(() => {}),
+ createMessage: async (content) => {
+ const text = messengerContentText(content);
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+ if (attachments?.length) {
+ const delivered = await sendTelegramAttachments(telegram, chatId, attachments, text);
+ if (delivered > 0) return;
+ // All attachments failed → fall through to text-only so the reply
+ // still reaches the user.
+ }
+ if (text.trim()) {
+ await telegram.sendMessage(chatId, text);
+ }
+ },
+ // editMessage keeps the text-only contract. Telegram doesn't support
+ // converting a text message into a media message — new chunks with
+ // attachments flow through createMessage instead.
editMessage: (messageId, content) =>
telegram.editMessageText(
chatId,
diff --git a/src/server/services/bot/platforms/telegram/sendAttachments.test.ts b/src/server/services/bot/platforms/telegram/sendAttachments.test.ts
new file mode 100644
index 00000000000..2fb64ed6d35
--- /dev/null
+++ b/src/server/services/bot/platforms/telegram/sendAttachments.test.ts
@@ -0,0 +1,107 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { sendTelegramAttachments } from './sendAttachments';
+
+const makeApi = () => ({
+ sendAudio: vi.fn().mockResolvedValue({ message_id: 1 }),
+ sendDocument: vi.fn().mockResolvedValue({ message_id: 1 }),
+ sendPhoto: vi.fn().mockResolvedValue({ message_id: 1 }),
+ sendVideo: vi.fn().mockResolvedValue({ message_id: 1 }),
+});
+
+describe('sendTelegramAttachments', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('dispatches to sendPhoto for image with URL source', async () => {
+ const api = makeApi();
+
+ const n = await sendTelegramAttachments(
+ api as any,
+ 'chat-1',
+ [{ fetchUrl: 'https://cdn.example.com/foo.png', name: 'foo.png', type: 'image' }],
+ 'caption text',
+ );
+
+ expect(n).toBe(1);
+ expect(api.sendPhoto).toHaveBeenCalledWith({
+ caption: 'caption text',
+ chatId: 'chat-1',
+ source: { url: 'https://cdn.example.com/foo.png' },
+ });
+ });
+
+ it('dispatches to sendDocument for file with base64 data → Buffer', async () => {
+ const api = makeApi();
+
+ const n = await sendTelegramAttachments(api as any, 'chat-1', [
+ {
+ data: Buffer.from('pdf-bytes').toString('base64'),
+ mimeType: 'application/pdf',
+ name: 'doc.pdf',
+ type: 'file',
+ },
+ ]);
+
+ expect(n).toBe(1);
+ expect(api.sendDocument).toHaveBeenCalledWith({
+ caption: undefined,
+ chatId: 'chat-1',
+ source: expect.objectContaining({
+ buffer: expect.any(Buffer),
+ filename: 'doc.pdf',
+ mimeType: 'application/pdf',
+ }),
+ });
+ });
+
+ it('only carries the caption on the first attachment', async () => {
+ const api = makeApi();
+
+ await sendTelegramAttachments(
+ api as any,
+ 'chat-1',
+ [
+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/c.pdf', type: 'file' },
+ ],
+ 'hello',
+ );
+
+ expect(api.sendPhoto).toHaveBeenCalledTimes(2);
+ expect(api.sendDocument).toHaveBeenCalledTimes(1);
+ expect(api.sendPhoto.mock.calls[0][0].caption).toBe('hello');
+ expect(api.sendPhoto.mock.calls[1][0].caption).toBeUndefined();
+ expect(api.sendDocument.mock.calls[0][0].caption).toBeUndefined();
+ });
+
+ it('continues with remaining attachments when one fails', async () => {
+ const api = makeApi();
+ api.sendPhoto
+ .mockRejectedValueOnce(new Error('Telegram 429'))
+ .mockResolvedValueOnce({ message_id: 2 });
+
+ const n = await sendTelegramAttachments(api as any, 'chat-1', [
+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },
+ ]);
+
+ expect(n).toBe(1);
+ expect(api.sendPhoto).toHaveBeenCalledTimes(2);
+ });
+
+ it('skips attachments with no resolvable source', async () => {
+ const api = makeApi();
+
+ const n = await sendTelegramAttachments(api as any, 'chat-1', [
+ { type: 'image' } as any, // no data, no fetchUrl
+ { fetchUrl: 'https://cdn.example.com/b.png', type: 'image' },
+ ]);
+
+ expect(n).toBe(1);
+ expect(api.sendPhoto).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/server/services/bot/platforms/telegram/sendAttachments.ts b/src/server/services/bot/platforms/telegram/sendAttachments.ts
new file mode 100644
index 00000000000..ed9563a87f7
--- /dev/null
+++ b/src/server/services/bot/platforms/telegram/sendAttachments.ts
@@ -0,0 +1,120 @@
+import debug from 'debug';
+
+import type { BotMessageAttachment } from '../types';
+import type { TelegramApi } from './api';
+
+const log = debug('bot-platform:telegram:send-attachments');
+
+/**
+ * Normalized form fed into the typed `TelegramApi.send{Photo,Document,...}`
+ * helpers. URL-source is preferred when available — Telegram fetches the
+ * bytes server-side, saving us a round-trip + base64 inflation.
+ */
+type TelegramMediaSource =
+ | { url: string }
+ | { buffer: Buffer; filename: string; mimeType?: string };
+
+const fallbackFilename = (att: BotMessageAttachment, index: number): string => {
+ if (att.name) return att.name;
+ if (att.fetchUrl) {
+ try {
+ const base = new URL(att.fetchUrl).pathname.split('/').pop();
+ if (base) return base;
+ } catch {
+ // fall through
+ }
+ }
+ return `attachment-${index + 1}`;
+};
+
+/**
+ * Resolve a `BotMessageAttachment` into a Telegram-ready source. Prefers
+ * `fetchUrl` so Telegram fetches the bytes server-side. Falls back to
+ * materializing `data` (base64) as a Buffer for multipart upload. Returns
+ * `undefined` when neither source is usable so the caller can skip the item.
+ */
+const resolveTelegramSource = (
+ att: BotMessageAttachment,
+ index: number,
+): TelegramMediaSource | undefined => {
+ if (att.fetchUrl) {
+ return { url: att.fetchUrl };
+ }
+ if (att.data) {
+ try {
+ return {
+ buffer: Buffer.from(att.data, 'base64'),
+ filename: fallbackFilename(att, index),
+ mimeType: att.mimeType,
+ };
+ } catch (error) {
+ log('resolveTelegramSource: failed to decode base64 for "%s": %O', att.name, error);
+ }
+ }
+ return undefined;
+};
+
+const dispatch = async (
+ api: TelegramApi,
+ chatId: string | number,
+ att: BotMessageAttachment,
+ source: TelegramMediaSource,
+ caption: string | undefined,
+): Promise<void> => {
+ switch (att.type) {
+ case 'image': {
+ await api.sendPhoto({ caption, chatId, source });
+ return;
+ }
+ case 'video': {
+ await api.sendVideo({ caption, chatId, source });
+ return;
+ }
+ case 'audio': {
+ await api.sendAudio({ caption, chatId, source });
+ return;
+ }
+ case 'file':
+ default: {
+ await api.sendDocument({ caption, chatId, source });
+ }
+ }
+};
+
+/**
+ * Deliver each attachment as its own typed Telegram media call. The first
+ * attachment carries `caption` (acting as the text leg of the reply); the
+ * rest are caption-less so the body isn't repeated. Single-item failures
+ * are logged and skipped so the rest still ship.
+ *
+ * Returns the number of successfully delivered attachments — callers can
+ * use 0 to decide whether to fall back to a plain `sendMessage` for the
+ * text leg.
+ */
+export const sendTelegramAttachments = async (
+ api: TelegramApi,
+ chatId: string | number,
+ attachments: BotMessageAttachment[],
+ caption?: string,
+): Promise<number> => {
+ let delivered = 0;
+ for (const [index, att] of attachments.entries()) {
+ const source = resolveTelegramSource(att, index);
+ if (!source) {
+ log('sendTelegramAttachments: skipping attachment without resolvable source');
+ continue;
+ }
+ try {
+ await dispatch(api, chatId, att, source, delivered === 0 ? caption : undefined);
+ delivered += 1;
+ } catch (error) {
+ log(
+ 'sendTelegramAttachments: failed to send %s "%s": %O',
+ att.type,
+ att.name ?? '(unnamed)',
+ error,
+ );
+ }
+ }
+ return delivered;
+};
diff --git a/src/server/services/bot/platforms/telegram/service.test.ts b/src/server/services/bot/platforms/telegram/service.test.ts
new file mode 100644
index 00000000000..0a584ecb055
--- /dev/null
+++ b/src/server/services/bot/platforms/telegram/service.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { TelegramMessageService } from './service';
+
+const makeApi = () => ({
+ sendAudio: vi.fn().mockResolvedValue({ message_id: 1 }),
+ sendDocument: vi.fn().mockResolvedValue({ message_id: 1 }),
+ sendMessage: vi.fn().mockResolvedValue({ message_id: 10 }),
+ sendPhoto: vi.fn().mockResolvedValue({ message_id: 1 }),
+ sendVideo: vi.fn().mockResolvedValue({ message_id: 1 }),
+});
+
+describe('TelegramMessageService.sendMessage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('uses sendMessage when no attachments', async () => {
+ const api = makeApi();
+ const service = new TelegramMessageService(api as any);
+
+ const result = await service.sendMessage({
+ channelId: 'chat-1',
+ content: 'hello',
+ platform: 'telegram',
+ });
+
+ expect(api.sendMessage).toHaveBeenCalledWith('chat-1', 'hello');
+ expect(api.sendPhoto).not.toHaveBeenCalled();
+ expect(result.messageId).toBe('10');
+ });
+
+ it('dispatches attachments to typed media methods with content as caption', async () => {
+ const api = makeApi();
+ const service = new TelegramMessageService(api as any);
+
+ await service.sendMessage({
+ attachments: [
+ { fetchUrl: 'https://cdn.example.com/a.png', type: 'image' },
+ { fetchUrl: 'https://cdn.example.com/b.pdf', type: 'file' },
+ ],
+ channelId: 'chat-1',
+ content: 'caption',
+ platform: 'telegram',
+ });
+
+ expect(api.sendMessage).not.toHaveBeenCalled();
+ expect(api.sendPhoto).toHaveBeenCalledWith(
+ expect.objectContaining({ caption: 'caption', chatId: 'chat-1' }),
+ );
+ expect(api.sendDocument).toHaveBeenCalledWith(expect.objectContaining({ caption: undefined }));
+ });
+
+ it('falls back to text sendMessage when all attachments fail', async () => {
+ const api = makeApi();
+ api.sendPhoto.mockRejectedValueOnce(new Error('429'));
+ const service = new TelegramMessageService(api as any);
+
+ await service.sendMessage({
+ attachments: [{ fetchUrl: 'https://cdn.example.com/a.png', type: 'image' }],
+ channelId: 'chat-1',
+ content: 'still send',
+ platform: 'telegram',
+ });
+
+ expect(api.sendPhoto).toHaveBeenCalled();
+ expect(api.sendMessage).toHaveBeenCalledWith('chat-1', 'still send');
+ });
+});
diff --git a/src/server/services/bot/platforms/telegram/service.ts b/src/server/services/bot/platforms/telegram/service.ts
index 2cbe81cdfd0..d0bc3d183ab 100644
--- a/src/server/services/bot/platforms/telegram/service.ts
+++ b/src/server/services/bot/platforms/telegram/service.ts
@@ -39,6 +39,7 @@ import type { MessageRuntimeService } from '@/server/services/toolExecution/serv
import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';
import type { TelegramApi } from './api';
+import { sendTelegramAttachments } from './sendAttachments';
export class TelegramMessageService implements MessageRuntimeService {
constructor(private api: TelegramApi) {}
@@ -46,6 +47,29 @@ export class TelegramMessageService implements MessageRuntimeService {
// ==================== Core Message Operations ====================
sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {
+ // Attachments path: the first attachment carries `content` as its caption
+ // (Telegram pairs caption with media), so we don't double up on a
+ // separate text-only sendMessage. If every attachment fails to
+ // materialize, fall back to the original text-only path so the reply
+ // still reaches the user.
+ if (params.attachments?.length) {
+ const delivered = await sendTelegramAttachments(
+ this.api,
+ params.channelId,
+ params.attachments,
+ params.content,
+ );
+ if (delivered > 0) {
+ return { channelId: params.channelId, platform: 'telegram' };
+ }
+ }
+
+ if (!params.content?.trim()) {
+ // No text and no successful attachments — nothing to send. Return a
+ // soft state instead of throwing so the caller doesn't see a crash
+ // for a no-op.
+ return { channelId: params.channelId, platform: 'telegram' };
+ }
const result = await this.api.sendMessage(params.channelId, params.content);
return {
channelId: params.channelId,
diff --git a/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.ts b/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.ts
index d0ca8e537cb..c212439fa72 100644
--- a/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.ts
+++ b/src/server/services/toolExecution/serverRuntimes/__tests__/message.test.ts
@@ -1,5 +1,5 @@
import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';
-import { describe, expect, it, vi } from 'vitest';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { ToolExecutionContext } from '../../types';
@@ -13,6 +13,63 @@ vi.mock('@/database/models/agentBotProvider', () => ({
})),
}));
+// ── System Bot model mocks ──────────────────────────────
+// The `botProvider.*` System Bot methods (added in LOBE-9288) talk directly
+// to these models instead of going through the messenger TRPC router, so
+// the test must stub them at module boundary. Each mock returns a `vi.fn()`
+// the individual test can `mockResolvedValueOnce` against.
+const mockListByInstallerUserId = vi.fn();
+const mockFindInstallationById = vi.fn();
+const mockMarkRevoked = vi.fn();
+
+vi.mock('@/database/models/messengerInstallation', () => ({
+ MessengerInstallationModel: {
+ findById: mockFindInstallationById,
+ listByInstallerUserId: mockListByInstallerUserId,
+ markRevoked: mockMarkRevoked,
+ },
+}));
+
+const mockLinkList = vi.fn();
+const mockLinkSetActiveAgent = vi.fn();
+const mockLinkDeleteByPlatform = vi.fn();
+
+vi.mock('@/database/models/messengerAccountLink', () => ({
+ MessengerAccountLinkModel: vi.fn().mockImplementation(() => ({
+ deleteByPlatform: mockLinkDeleteByPlatform,
+ list: mockLinkList,
+ setActiveAgent: mockLinkSetActiveAgent,
+ })),
+}));
+
+// Stub the agents schema as an opaque token — the runtime only uses it for
+// `select.from(agents)` reference equality, so any object works.
+vi.mock('@/database/schemas', () => ({
+ agents: { id: 'agents.id', userId: 'agents.userId' },
+}));
+
+// `@/config/messenger` reads env-side messenger config — stub the four
+// getters used by `listMessengerPlatforms`.
+const mockGetEnabledMessengerPlatforms = vi.fn();
+const mockGetMessengerSlackConfig = vi.fn();
+const mockGetMessengerDiscordConfig = vi.fn();
+const mockGetMessengerTelegramConfig = vi.fn();
+
+vi.mock('@/config/messenger', () => ({
+ getEnabledMessengerPlatforms: mockGetEnabledMessengerPlatforms,
+ getMessengerDiscordConfig: mockGetMessengerDiscordConfig,
+ getMessengerSlackConfig: mockGetMessengerSlackConfig,
+ getMessengerTelegramConfig: mockGetMessengerTelegramConfig,
+}));
+
+const mockListSerializedPlatforms = vi.fn();
+
+vi.mock('@/server/services/messenger', () => ({
+ messengerPlatformRegistry: {
+ listSerializedPlatforms: mockListSerializedPlatforms,
+ },
+}));
+
vi.mock('@/server/modules/KeyVaultsEncrypt', () => ({
KeyVaultsGateKeeper: {
initWithEnvKey: vi.fn().mockResolvedValue({}),
@@ -366,4 +423,325 @@ describe('messageRuntime', () => {
expect(result.content).toContain('No message service configured for platform');
});
});
+
+ // ==================== System Bot management (LOBE-9288) ====================
+ // Each test exercises both layers in one shot:
+ // 1. `botProvider.<method>` in `src/server/services/toolExecution/serverRuntimes/message/index.ts`
+ // 2. `MessageExecutionRuntime.<method>` formatting in
+ // `packages/builtin-tool-message/src/ExecutionRuntime/index.ts`
+ // …because the factory returns a runtime where the botProvider impl is
+ // already wired. Calling `runtime.listMessengers({})` hits both.
+ //
+ // System Bot mocks are module-level `vi.fn()`s — their call history
+ // accumulates across tests, which trips `.not.toHaveBeenCalled()` checks
+ // in negative paths. Reset before every System Bot case below.
+ beforeEach(() => {
+ for (const fn of [
+ mockListByInstallerUserId,
+ mockFindInstallationById,
+ mockMarkRevoked,
+ mockLinkList,
+ mockLinkSetActiveAgent,
+ mockLinkDeleteByPlatform,
+ mockGetEnabledMessengerPlatforms,
+ mockGetMessengerSlackConfig,
+ mockGetMessengerDiscordConfig,
+ mockGetMessengerTelegramConfig,
+ mockListSerializedPlatforms,
+ ]) {
+ fn.mockReset();
+ }
+ });
+
+ describe('System Bot — listMessengers', () => {
+ it('returns user-scoped non-revoked installs', async () => {
+ mockListByInstallerUserId.mockResolvedValueOnce([
+ {
+ applicationId: 'app-slack',
+ createdAt: new Date('2026-01-15T00:00:00Z'),
+ id: 'inst_active',
+ metadata: { tenantName: 'Acme' },
+ platform: 'slack',
+ revokedAt: null,
+ tenantId: 'T1',
+ },
+ // Revoked rows are intentionally surfaced from the model — the
+ // runtime filters them. Including one here proves the filter works.
+ {
+ applicationId: 'app-discord',
+ createdAt: new Date('2026-01-10T00:00:00Z'),
+ id: 'inst_revoked',
+ metadata: {},
+ platform: 'discord',
+ revokedAt: new Date('2026-02-01T00:00:00Z'),
+ tenantId: 'G1',
+ },
+ ]);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.listMessengers({});
+
+ expect(result.success).toBe(true);
+ expect(result.state.installations).toHaveLength(1);
+ expect(result.state.installations[0].id).toBe('inst_active');
+ expect(result.content).toContain('inst_active');
+ expect(result.content).not.toContain('inst_revoked');
+ });
+
+ it('reports empty state with install guidance', async () => {
+ mockListByInstallerUserId.mockResolvedValueOnce([]);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.listMessengers({});
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('No System Bot installations connected');
+ expect(result.content).toContain('Settings → Messenger');
+ });
+ });
+
+ describe('System Bot — getMessengerDetail', () => {
+ it('returns details for an install owned by the current user', async () => {
+ mockFindInstallationById.mockResolvedValueOnce({
+ applicationId: 'app-slack',
+ createdAt: new Date('2026-01-15T00:00:00Z'),
+ id: 'inst_match',
+ installedByUserId: 'user-1',
+ metadata: { scope: 'chat:write', tenantName: 'Acme' },
+ platform: 'slack',
+ revokedAt: null,
+ tenantId: 'T1',
+ });
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.getMessengerDetail({ installationId: 'inst_match' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('inst_match');
+ expect(result.content).toContain('Acme');
+ });
+
+ it('rejects detail lookup when the caller is not the installer', async () => {
+ mockFindInstallationById.mockResolvedValueOnce({
+ applicationId: 'app-slack',
+ createdAt: new Date(),
+ id: 'inst_other',
+ installedByUserId: 'someone-else',
+ metadata: {},
+ platform: 'slack',
+ revokedAt: null,
+ tenantId: 'T1',
+ });
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.getMessengerDetail({ installationId: 'inst_other' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('only view installations you initiated');
+ });
+
+ it('returns not-found when the install does not exist', async () => {
+ mockFindInstallationById.mockResolvedValueOnce(null);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.getMessengerDetail({ installationId: 'inst_missing' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not found');
+ });
+ });
+
+ describe('System Bot — uninstallMessenger', () => {
+ it('marks the row revoked when caller is the installer', async () => {
+ mockFindInstallationById.mockResolvedValueOnce({
+ applicationId: 'app',
+ createdAt: new Date(),
+ id: 'inst_ok',
+ installedByUserId: 'user-1',
+ metadata: {},
+ platform: 'slack',
+ revokedAt: null,
+ tenantId: 'T1',
+ });
+ mockMarkRevoked.mockResolvedValueOnce(undefined);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.uninstallMessenger({ installationId: 'inst_ok' });
+
+ expect(result.success).toBe(true);
+ expect(mockMarkRevoked).toHaveBeenCalledWith(expect.anything(), 'inst_ok');
+ });
+
+ it('rejects when caller is not the installer (FORBIDDEN)', async () => {
+ mockFindInstallationById.mockResolvedValueOnce({
+ applicationId: 'app',
+ createdAt: new Date(),
+ id: 'inst_blocked',
+ installedByUserId: 'someone-else',
+ metadata: {},
+ platform: 'slack',
+ revokedAt: null,
+ tenantId: 'T1',
+ });
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.uninstallMessenger({ installationId: 'inst_blocked' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('only uninstall installations you initiated');
+ expect(mockMarkRevoked).not.toHaveBeenCalled();
+ });
+
+ it('returns not-found when the install does not exist', async () => {
+ mockFindInstallationById.mockResolvedValueOnce(null);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.uninstallMessenger({ installationId: 'inst_gone' });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('not found');
+ });
+ });
+
+ describe('System Bot — listMessengerPlatforms', () => {
+ it('returns enabled platforms with deep-link metadata', async () => {
+ mockGetEnabledMessengerPlatforms.mockResolvedValueOnce(['slack', 'telegram']);
+ mockListSerializedPlatforms.mockReturnValueOnce([
+ { id: 'slack', name: 'Slack' },
+ { id: 'telegram', name: 'Telegram' },
+ { id: 'discord', name: 'Discord' },
+ ]);
+ mockGetMessengerSlackConfig.mockResolvedValueOnce({ appId: 'A123' });
+ mockGetMessengerTelegramConfig.mockResolvedValueOnce({ botUsername: 'lobehub_bot' });
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.listMessengerPlatforms({});
+
+ expect(result.success).toBe(true);
+ // Discord is filtered out (not in enabled list)
+ expect(result.state.platforms).toHaveLength(2);
+ expect(result.content).toContain('slack');
+ expect(result.content).toContain('A123');
+ expect(result.content).toContain('lobehub_bot');
+ });
+ });
+
+ describe('System Bot — listMessengerLinks', () => {
+ it('returns the user’s account links', async () => {
+ mockLinkList.mockResolvedValueOnce([
+ {
+ activeAgentId: 'agent_1',
+ createdAt: new Date('2026-01-15T00:00:00Z'),
+ platform: 'slack',
+ platformUserId: 'U1',
+ platformUsername: 'alice',
+ tenantId: 'T1',
+ },
+ ]);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.listMessengerLinks({});
+
+ expect(result.success).toBe(true);
+ expect(result.state.links).toHaveLength(1);
+ expect(result.content).toContain('agent_1');
+ expect(result.content).toContain('slack');
+ });
+
+ it('reports empty state when the user has no links', async () => {
+ mockLinkList.mockResolvedValueOnce([]);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.listMessengerLinks({});
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('No System Bot account links');
+ });
+ });
+
+ describe('System Bot — setMessengerActiveAgent', () => {
+ /**
+ * Build a serverDB stub whose `select().from().where().limit()` chain
+ * returns the agent rows the runtime expects when validating ownership.
+ * Returning `[]` here simulates "agent doesn't belong to this user".
+ */
+ const ctxWithAgents = (agentLookupResult: Array<{ id: string }>): ToolExecutionContext => ({
+ serverDB: {
+ select: () => ({
+ from: () => ({
+ where: () => ({
+ limit: () => Promise.resolve(agentLookupResult),
+ }),
+ }),
+ }),
+ } as any,
+ toolManifestMap: {},
+ userId: 'user-1',
+ });
+
+ it('updates the link when the agent belongs to the user', async () => {
+ mockLinkSetActiveAgent.mockResolvedValueOnce({ id: 'link-1', activeAgentId: 'agent_x' });
+
+ const runtime = await messageRuntime.factory(ctxWithAgents([{ id: 'agent_x' }]));
+ const result = await runtime.setMessengerActiveAgent({
+ agentId: 'agent_x',
+ platform: 'slack',
+ tenantId: 'T1',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockLinkSetActiveAgent).toHaveBeenCalledWith('slack', 'agent_x', 'T1');
+ });
+
+ it('rejects when the agent does not belong to the caller', async () => {
+ const runtime = await messageRuntime.factory(ctxWithAgents([]));
+ const result = await runtime.setMessengerActiveAgent({
+ agentId: 'agent_foreign',
+ platform: 'slack',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('Agent not found');
+ expect(mockLinkSetActiveAgent).not.toHaveBeenCalled();
+ });
+
+ it('clears the active agent when agentId is null', async () => {
+ mockLinkSetActiveAgent.mockResolvedValueOnce({ id: 'link-1', activeAgentId: null });
+
+ // Null agentId path skips ownership check entirely.
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.setMessengerActiveAgent({
+ agentId: null,
+ platform: 'telegram',
+ });
+
+ expect(result.success).toBe(true);
+ expect(mockLinkSetActiveAgent).toHaveBeenCalledWith('telegram', null, undefined);
+ });
+
+ it('returns NOT_FOUND when the link does not exist', async () => {
+ mockLinkSetActiveAgent.mockResolvedValueOnce(undefined);
+
+ const runtime = await messageRuntime.factory(ctxWithAgents([{ id: 'agent_x' }]));
+ const result = await runtime.setMessengerActiveAgent({
+ agentId: 'agent_x',
+ platform: 'discord',
+ });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('No account link found');
+ });
+ });
+
+ describe('System Bot — unlinkMessenger', () => {
+ it('delegates to the link model', async () => {
+ mockLinkDeleteByPlatform.mockResolvedValueOnce(undefined);
+
+ const runtime = await messageRuntime.factory(validContext);
+ const result = await runtime.unlinkMessenger({ platform: 'slack', tenantId: 'T1' });
+
+ expect(result.success).toBe(true);
+ expect(mockLinkDeleteByPlatform).toHaveBeenCalledWith('slack', 'T1');
+ });
+ });
});
diff --git a/src/server/services/toolExecution/serverRuntimes/message/index.ts b/src/server/services/toolExecution/serverRuntimes/message/index.ts
index 0f613a3d911..aa36d001e6f 100644
--- a/src/server/services/toolExecution/serverRuntimes/message/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/message/index.ts
@@ -4,8 +4,19 @@ import { MessageExecutionRuntime } from '@lobechat/builtin-tool-message/executio
import { LarkApiClient } from '@lobechat/chat-adapter-feishu';
import { QQApiClient } from '@lobechat/chat-adapter-qq';
import { WechatApiClient } from '@lobechat/chat-adapter-wechat';
+import { TRPCError } from '@trpc/server';
+import { and, eq } from 'drizzle-orm';
+import {
+ getEnabledMessengerPlatforms,
+ getMessengerDiscordConfig,
+ getMessengerSlackConfig,
+ getMessengerTelegramConfig,
+} from '@/config/messenger';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
+import { MessengerAccountLinkModel } from '@/database/models/messengerAccountLink';
+import { MessengerInstallationModel } from '@/database/models/messengerInstallation';
+import { agents } from '@/database/schemas';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import {
assertBotAccessSettings,
@@ -24,6 +35,7 @@ import { TelegramMessageService } from '@/server/services/bot/platforms/telegram
import { WechatMessageService } from '@/server/services/bot/platforms/wechat/service';
import { GatewayService } from '@/server/services/gateway';
import { getBotRuntimeStatus } from '@/server/services/gateway/runtimeStatus';
+import { messengerPlatformRegistry } from '@/server/services/messenger';
import type { ServerRuntimeRegistration } from '../types';
import { MessageDispatcherService } from './MessageDispatcherService';
@@ -212,6 +224,197 @@ export const messageRuntime: ServerRuntimeRegistration = {
{},
);
},
+
+ // ─── System Bot messenger management ─────────────────────────────────
+ // Mirrors `messenger.*` TRPC procedures but exposed via the tool runtime
+ // so LLM-driven flows can manage installs + links the same way the
+ // Settings → Messenger UI does. Each handler enforces user ownership;
+ // the underlying models are already user-scoped where applicable.
+ listMessengers: async () => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required to list System Bot installations');
+ }
+ const linkGateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
+ const rows = await MessengerInstallationModel.listByInstallerUserId(
+ context.serverDB,
+ context.userId,
+ linkGateKeeper,
+ );
+ // We intentionally skip the Slack auth.test reconciliation that the
+ // `messenger.listMyInstallations` TRPC procedure runs. A stale Slack
+ // install will still appear here; the actual send/uninstall call will
+ // surface the underlying token error if and when it matters.
+ return rows
+ .filter((row) => !row.revokedAt)
+ .map((row) => ({
+ applicationId: row.applicationId,
+ enterpriseId:
+ ((row.metadata as Record<string, unknown> | null)?.enterpriseId as
+ | string
+ | null
+ | undefined) ?? null,
+ id: row.id,
+ installedAt:
+ row.createdAt instanceof Date ? row.createdAt.toISOString() : String(row.createdAt),
+ isEnterpriseInstall:
+ (row.metadata as Record<string, unknown> | null)?.isEnterpriseInstall === true,
+ platform: row.platform,
+ scope: ((row.metadata as Record<string, unknown> | null)?.scope as string) ?? '',
+ tenantId: row.tenantId,
+ tenantName:
+ ((row.metadata as Record<string, unknown> | null)?.tenantName as string) ?? '',
+ }));
+ },
+
+ getMessengerDetail: async (installationId) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required to load installation');
+ }
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
+ const row = await MessengerInstallationModel.findById(
+ context.serverDB,
+ installationId,
+ gateKeeper,
+ );
+ if (!row) return null;
+ // Same ownership guard as `messenger.uninstallInstallation` — the
+ // installer is the only user who can see install metadata via the tool.
+ if (row.installedByUserId !== context.userId) {
+ throw new Error('You can only view installations you initiated');
+ }
+ return {
+ applicationId: row.applicationId,
+ enterpriseId:
+ ((row.metadata as Record<string, unknown> | null)?.enterpriseId as
+ | string
+ | null
+ | undefined) ?? null,
+ id: row.id,
+ installedAt:
+ row.createdAt instanceof Date ? row.createdAt.toISOString() : String(row.createdAt),
+ isEnterpriseInstall:
+ (row.metadata as Record<string, unknown> | null)?.isEnterpriseInstall === true,
+ platform: row.platform,
+ revokedAt:
+ row.revokedAt instanceof Date ? row.revokedAt.toISOString() : (row.revokedAt ?? null),
+ scope: ((row.metadata as Record<string, unknown> | null)?.scope as string) ?? '',
+ tenantId: row.tenantId,
+ tenantName:
+ ((row.metadata as Record<string, unknown> | null)?.tenantName as string) ?? '',
+ };
+ },
+
+ uninstallMessenger: async (installationId) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required to uninstall');
+ }
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey().catch(() => undefined);
+ const row = await MessengerInstallationModel.findById(
+ context.serverDB,
+ installationId,
+ gateKeeper,
+ );
+ if (!row) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Installation not found: ${installationId}`,
+ });
+ }
+ if (row.installedByUserId !== context.userId) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'You can only uninstall installations you initiated',
+ });
+ }
+ await MessengerInstallationModel.markRevoked(context.serverDB, row.id);
+ },
+
+ listMessengerPlatforms: async () => {
+ // Mirror of `messenger.availablePlatforms` — surfaces per-deployment
+ // OAuth deep-link fields (appId / botUsername) so the LLM can tell the
+ // user *which* LobeHub bot identity they'd be installing.
+ const enabled = await getEnabledMessengerPlatforms();
+ const enabledSet = new Set<string>(enabled);
+ const definitions = messengerPlatformRegistry
+ .listSerializedPlatforms()
+ .filter((def) => enabledSet.has(def.id));
+
+ const [discordConfig, slackConfig, telegramConfig] = await Promise.all([
+ enabledSet.has('discord') ? getMessengerDiscordConfig() : Promise.resolve(null),
+ enabledSet.has('slack') ? getMessengerSlackConfig() : Promise.resolve(null),
+ enabledSet.has('telegram') ? getMessengerTelegramConfig() : Promise.resolve(null),
+ ]);
+
+ return definitions.map((def) => ({
+ appId:
+ def.id === 'slack'
+ ? slackConfig?.appId
+ : def.id === 'discord'
+ ? discordConfig?.applicationId
+ : undefined,
+ botUsername: def.id === 'telegram' ? telegramConfig?.botUsername : undefined,
+ id: def.id,
+ name: def.name,
+ }));
+ },
+
+ listMessengerLinks: async () => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required to list account links');
+ }
+ const linkModel = new MessengerAccountLinkModel(context.serverDB, context.userId);
+ const rows = await linkModel.list();
+ return rows.map((row) => ({
+ activeAgentId: row.activeAgentId ?? null,
+ createdAt:
+ row.createdAt instanceof Date ? row.createdAt.toISOString() : String(row.createdAt),
+ platform: row.platform,
+ platformUserId: row.platformUserId,
+ platformUsername: row.platformUsername ?? undefined,
+ tenantId: row.tenantId || undefined,
+ }));
+ },
+
+ setMessengerActiveAgent: async (params) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required');
+ }
+ // Validate agent ownership before mutating the link — matches the
+ // `messenger.setActiveAgent` behavior (rejects cross-user agent ids).
+ if (params.agentId !== null) {
+ const [agentRow] = await context.serverDB
+ .select({ id: agents.id })
+ .from(agents)
+ .where(and(eq(agents.id, params.agentId), eq(agents.userId, context.userId)))
+ .limit(1);
+ if (!agentRow) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `Agent not found or not owned by you: ${params.agentId}`,
+ });
+ }
+ }
+ const linkModel = new MessengerAccountLinkModel(context.serverDB, context.userId);
+ const updated = await linkModel.setActiveAgent(
+ params.platform,
+ params.agentId,
+ params.tenantId,
+ );
+ if (!updated) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message: `No account link found for ${params.platform}${params.tenantId ? ` (tenant ${params.tenantId})` : ''}. The user must complete verify-im first.`,
+ });
+ }
+ },
+
+ unlinkMessenger: async (params) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required');
+ }
+ const linkModel = new MessengerAccountLinkModel(context.serverDB, context.userId);
+ await linkModel.deleteByPlatform(params.platform, params.tenantId);
+ },
};
return new MessageExecutionRuntime({ botProvider, service });
diff --git a/src/store/tool/slices/builtin/executors/lobe-message.ts b/src/store/tool/slices/builtin/executors/lobe-message.ts
deleted file mode 100644
index f48093b3418..00000000000
--- a/src/store/tool/slices/builtin/executors/lobe-message.ts
+++ /dev/null
@@ -1,328 +0,0 @@
-/**
- * Lobe Message Executor
- *
- * Frontend executor for the Message builtin tool.
- * Delegates all operations to the server via TRPC since they require
- * database access (bot credentials, platform adapters).
- */
-import { MessageApiName, MessageToolIdentifier } from '@lobechat/builtin-tool-message';
-import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
-import { BaseExecutor } from '@lobechat/types';
-
-import { lambdaClient } from '@/libs/trpc/client';
-import { agentBotProviderService } from '@/services/agentBotProvider';
-
-class MessageExecutor extends BaseExecutor<typeof MessageApiName> {
- readonly identifier = MessageToolIdentifier;
- protected readonly apiEnum = MessageApiName;
-
- // ==================== Bot Management ====================
-
- listPlatforms = async (_params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- try {
- const platforms = await agentBotProviderService.listPlatforms();
- const items = (platforms as any[]).map((p: any) => {
- const credSchema = (p.schema ?? []).find(
- (f: any) => f.key === 'credentials' && f.properties,
- );
- const fields = (credSchema?.properties ?? []) as any[];
- const reqFields = fields
- .filter((f: any) => f.required)
- .map((f: any) => f.key)
- .join(', ');
- return `- **${p.name}** (${p.id})${reqFields ? ` — requires: ${reqFields}` : ''}`;
- });
-
- return {
- content: `${(platforms as any[]).length} supported platform(s):\n${items.join('\n')}`,
- state: { platforms },
- success: true,
- };
- } catch (e) {
- return { content: `listPlatforms error: ${(e as Error).message}`, success: false };
- }
- };
-
- listBots = async (_params: any, ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- try {
- const agentId = ctx.agentId;
- if (!agentId) {
- return { content: 'agentId is required to list bots', success: false };
- }
-
- const bots = await agentBotProviderService.getByAgentId(agentId);
- const items = (bots as any[]).map((b: any) => {
- const parts = [
- `platform: ${b.platform}`,
- `botId: ${b.id}`,
- `enabled: ${b.enabled}`,
- `status: ${b.runtimeStatus ?? 'unknown'}`,
- ];
- if (b.settings?.serverId) {
- parts.push(`serverId: ${b.settings.serverId}`);
- }
- if (b.settings?.userId) {
- parts.push(`userId: ${b.settings.userId}`);
- }
- return `- ${b.platform} (${parts.join(', ')})`;
- });
-
- return {
- content:
- (bots as any[]).length > 0
- ? `${(bots as any[]).length} configured bot(s):\n${items.join('\n')}`
- : 'No bots configured for this agent. Set up a bot integration first.',
- state: { bots },
- success: true,
- };
- } catch (e) {
- return { content: `listBots error: ${(e as Error).message}`, success: false };
- }
- };
-
- getBotDetail = async (
- params: { botId: string },
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- const bots = await lambdaClient.agentBotProvider.list.query();
- const bot = (bots as any[]).find((b: any) => b.id === 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'}`,
- state: bot,
- success: true,
- };
- } catch (e) {
- return { content: `getBotDetail error: ${(e as Error).message}`, success: false };
- }
- };
-
- createBot = async (
- params: {
- agentId: string;
- applicationId: string;
- credentials: Record<string, string>;
- platform: string;
- },
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- const result = await agentBotProviderService.create(params);
- return {
- content: `Created ${params.platform} bot (id: ${(result as any).id})`,
- state: result,
- success: true,
- };
- } catch (e) {
- return { content: `createBot error: ${(e as Error).message}`, success: false };
- }
- };
-
- updateBot = async (
- params: {
- botId: string;
- credentials?: Record<string, string>;
- settings?: Record<string, unknown>;
- },
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- await agentBotProviderService.update(params.botId, {
- credentials: params.credentials,
- settings: params.settings,
- });
- return { content: `Updated bot ${params.botId}`, state: { success: true }, success: true };
- } catch (e) {
- return { content: `updateBot error: ${(e as Error).message}`, success: false };
- }
- };
-
- deleteBot = async (
- params: { botId: string },
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- await agentBotProviderService.delete(params.botId);
- return { content: `Deleted bot ${params.botId}`, state: { success: true }, success: true };
- } catch (e) {
- return { content: `deleteBot error: ${(e as Error).message}`, success: false };
- }
- };
-
- toggleBot = async (
- params: { botId: string; enabled: boolean },
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- await agentBotProviderService.update(params.botId, { enabled: params.enabled });
- return {
- content: `Bot ${params.botId} ${params.enabled ? 'enabled' : 'disabled'}`,
- state: { enabled: params.enabled, success: true },
- success: true,
- };
- } catch (e) {
- return { content: `toggleBot error: ${(e as Error).message}`, success: false };
- }
- };
-
- connectBot = async (
- params: { botId: string },
- _ctx: BuiltinToolContext,
- ): Promise<BuiltinToolResult> => {
- try {
- // Look up bot to get platform + applicationId
- const bots = await lambdaClient.agentBotProvider.list.query();
- const bot = (bots as any[]).find((b: any) => b.id === params.botId);
- if (!bot) {
- return { content: `Bot not found: ${params.botId}`, success: false };
- }
-
- const result = await agentBotProviderService.connectBot({
- applicationId: bot.applicationId,
- platform: bot.platform,
- });
- return {
- content: `Bot connection initiated (status: ${result.status})`,
- state: result,
- success: true,
- };
- } catch (e) {
- return { content: `connectBot error: ${(e as Error).message}`, success: false };
- }
- };
-
- // ==================== Direct Messaging ====================
-
- sendDirectMessage = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('sendDirectMessage', params);
- };
-
- // ==================== Message Operations ====================
- // All message operations go through the botMessage TRPC router
-
- sendMessage = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('sendMessage', params);
- };
-
- readMessages = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('readMessages', params, 'query');
- };
-
- editMessage = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('editMessage', params);
- };
-
- deleteMessage = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('deleteMessage', params);
- };
-
- searchMessages = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('searchMessages', params, 'query');
- };
-
- reactToMessage = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('reactToMessage', params);
- };
-
- getReactions = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('getReactions', params, 'query');
- };
-
- pinMessage = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('pinMessage', params);
- };
-
- unpinMessage = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('unpinMessage', params);
- };
-
- listPins = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('listPins', params, 'query');
- };
-
- getChannelInfo = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('getChannelInfo', params, 'query');
- };
-
- listChannels = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('listChannels', params, 'query');
- };
-
- getMemberInfo = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('getMemberInfo', params, 'query');
- };
-
- createThread = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('createThread', params);
- };
-
- listThreads = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('listThreads', params, 'query');
- };
-
- replyToThread = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('replyToThread', params);
- };
-
- createPoll = async (params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {
- return this._callBotMessage('createPoll', params);
- };
-
- // ==================== Internal Helper ====================
-
- /**
- * Route a message operation to the botMessage TRPC router.
- * The AI provides `platform` + `channelId`, but the TRPC router needs `botId`.
- * We resolve the botId by looking up the bot for the given platform.
- */
- private _callBotMessage = async (
- apiName: string,
- params: any,
- method: 'mutate' | 'query' = 'mutate',
- ): Promise<BuiltinToolResult> => {
- try {
- let botId = params.botId as string | undefined;
-
- // Resolve botId from platform if not provided
- if (!botId && params.platform) {
- const bots = await lambdaClient.agentBotProvider.list.query();
- const bot = (bots as any[]).find((b: any) => b.platform === params.platform && b.enabled);
- if (!bot) {
- return {
- content: `No enabled bot found for platform "${params.platform}". Configure one first.`,
- success: false,
- };
- }
- botId = bot.id;
- }
-
- if (!botId) {
- return { content: 'botId or platform is required', success: false };
- }
-
- const router = lambdaClient.botMessage as any;
- const procedure = router[apiName];
- if (!procedure) {
- return { content: `Unknown message API: ${apiName}`, success: false };
- }
-
- const { botId: _, platform: __, ...rest } = params;
- const input = { botId, ...rest };
- const result =
- method === 'query' ? await procedure.query(input) : await procedure.mutate(input);
-
- return {
- content: JSON.stringify(result),
- state: result,
- success: true,
- };
- } catch (e) {
- return { content: `${apiName} error: ${(e as Error).message}`, success: false };
- }
- };
-}
-
-export const messageExecutor = new MessageExecutor();
diff --git a/src/store/tool/slices/builtin/executors/lobe-message/index.ts b/src/store/tool/slices/builtin/executors/lobe-message/index.ts
new file mode 100644
index 00000000000..f815bdab562
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/lobe-message/index.ts
@@ -0,0 +1,21 @@
+/**
+ * Lobe Message Executor — frontend entry.
+ *
+ * Composes the shared `MessageExecutor` + `MessageExecutionRuntime` from
+ * `@lobechat/builtin-tool-message` with TRPC-backed adapters so the
+ * frontend and server run the same orchestration / formatting code paths.
+ *
+ * Adding a new API only requires updating `MessageApiName` + the runtime;
+ * the frontend executor inherits the new method automatically.
+ */
+import { MessageExecutionRuntime } from '@lobechat/builtin-tool-message/executionRuntime';
+import { MessageExecutor } from '@lobechat/builtin-tool-message/executor';
+
+import { trpcBotProvider, trpcMessageService } from './trpcAdapters';
+
+const runtime = new MessageExecutionRuntime({
+ botProvider: trpcBotProvider,
+ service: trpcMessageService,
+});
+
+export const messageExecutor = new MessageExecutor(runtime);
diff --git a/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts
new file mode 100644
index 00000000000..f2483c7e56d
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/lobe-message/trpcAdapters.ts
@@ -0,0 +1,315 @@
+/**
+ * TRPC adapters for the Message tool executor.
+ *
+ * Implements the `BotProviderQuery` and `MessageRuntimeService` interfaces
+ * from `@lobechat/builtin-tool-message/executionRuntime` by routing every
+ * call through `lambdaClient.*`. This lets the frontend reuse the runtime's
+ * orchestration + formatting logic instead of duplicating it.
+ */
+import type {
+ BotProviderQuery,
+ MessageRuntimeService,
+} from '@lobechat/builtin-tool-message/executionRuntime';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+// ────────────────────────────────────────────────────────────────────────
+// Bot provider — discovery + lifecycle (per-agent bots & messenger installs)
+// ────────────────────────────────────────────────────────────────────────
+
+export const trpcBotProvider: BotProviderQuery = {
+ listPlatforms: async () => {
+ const platforms = (await lambdaClient.agentBotProvider.listPlatforms.query()) as any[];
+ // The server returns raw serialized platforms whose credential fields
+ // are nested under `schema[].properties`. Flatten to the runtime's
+ // `PlatformInfo.credentialFields` shape (same transform the server-side
+ // BotProviderQuery does — see `serverRuntimes/message/index.ts`).
+ return platforms.map((p) => {
+ const credSchema = (p.schema ?? []).find((f: any) => f.key === 'credentials' && f.properties);
+ const credFields = (credSchema?.properties ?? []) as any[];
+ return {
+ credentialFields: credFields.map((f: any) => ({
+ key: f.key,
+ label: f.label ?? f.key,
+ required: !!f.required,
+ type: f.type ?? 'string',
+ })),
+ id: p.id,
+ name: p.name,
+ };
+ });
+ },
+
+ listBots: async () => {
+ // The runtime's `listBots` is agent-scoped; on the frontend the scope
+ // comes from the active context. We use the unscoped `list` query
+ // (it returns the caller's bots) — the runtime caller is expected to
+ // narrow by agentId itself (mirror of server behavior where the
+ // factory pulls `context.agentId`). For now we surface every bot the
+ // caller owns; agent filtering happens upstream in the LLM prompt.
+ const providers = (await lambdaClient.agentBotProvider.list.query()) as any[];
+ return providers.map((p) => ({
+ applicationId: p.applicationId,
+ enabled: p.enabled,
+ id: p.id,
+ platform: p.platform,
+ runtimeStatus: p.runtimeStatus,
+ // Settings nests serverId/userId — the runtime interface expects
+ // them flat. Map both back up so the formatter can render them.
+ serverId: (p.settings as Record<string, unknown> | null)?.serverId as string | undefined,
+ userId: (p.settings as Record<string, unknown> | null)?.userId as string | undefined,
+ }));
+ },
+
+ getBotDetail: async (botId) => {
+ const providers = (await lambdaClient.agentBotProvider.list.query()) as any[];
+ const bot = providers.find((b) => b.id === botId);
+ if (!bot) return null;
+ return {
+ applicationId: bot.applicationId,
+ enabled: bot.enabled,
+ id: bot.id,
+ platform: bot.platform,
+ runtimeStatus: bot.runtimeStatus,
+ settings: (bot.settings as Record<string, unknown>) ?? undefined,
+ };
+ },
+
+ createBot: async (params) => {
+ const result = (await lambdaClient.agentBotProvider.create.mutate({
+ agentId: params.agentId,
+ applicationId: params.applicationId,
+ credentials: params.credentials,
+ platform: params.platform,
+ settings: params.settings,
+ })) as { id: string };
+ return { id: result.id, platform: params.platform };
+ },
+
+ updateBot: async (botId, params) => {
+ await lambdaClient.agentBotProvider.update.mutate({
+ id: botId,
+ credentials: params.credentials,
+ settings: params.settings,
+ });
+ },
+
+ deleteBot: async (botId) => {
+ await lambdaClient.agentBotProvider.delete.mutate({ id: botId });
+ },
+
+ toggleBot: async (botId, enabled) => {
+ await lambdaClient.agentBotProvider.update.mutate({ id: botId, enabled });
+ },
+
+ connectBot: async (botId) => {
+ // The TRPC connectBot endpoint keys on `{ applicationId, platform }`
+ // rather than `botId`, so we resolve those from the bot list first.
+ // Two round-trips, but the alternative is changing the server contract
+ // — out of scope for the unification refactor.
+ const providers = (await lambdaClient.agentBotProvider.list.query()) as any[];
+ const bot = providers.find((b) => b.id === botId);
+ if (!bot) throw new Error(`Bot not found: ${botId}`);
+ return lambdaClient.agentBotProvider.connectBot.mutate({
+ applicationId: bot.applicationId,
+ platform: bot.platform,
+ });
+ },
+
+ // ─── System Bot messenger management ─────────────────────────────────
+ // Adapters around the existing `messenger.*` TRPC procedures, surfaced
+ // through the same runtime so the frontend reuses the runtime's
+ // formatting + empty-state copy. No new TRPC endpoints — `getMessengerDetail`
+ // filters the list client-side because installs are small (<10 per user)
+ // and the alternative is a one-off backend procedure.
+ listMessengers: async () => {
+ const installations = (await lambdaClient.messenger.listMyInstallations.query()) as any[];
+ return installations.map((i) => ({
+ applicationId: i.applicationId,
+ enterpriseId: i.enterpriseId ?? null,
+ id: i.id,
+ installedAt:
+ i.installedAt instanceof Date ? i.installedAt.toISOString() : String(i.installedAt),
+ isEnterpriseInstall: i.isEnterpriseInstall === true,
+ platform: i.platform,
+ scope: i.scope ?? '',
+ tenantId: i.tenantId,
+ tenantName: i.tenantName ?? '',
+ }));
+ },
+
+ getMessengerDetail: async (installationId) => {
+ const installations = (await lambdaClient.messenger.listMyInstallations.query()) as any[];
+ const install = installations.find((i) => i.id === installationId);
+ if (!install) return null;
+ return {
+ applicationId: install.applicationId,
+ enterpriseId: install.enterpriseId ?? null,
+ id: install.id,
+ installedAt:
+ install.installedAt instanceof Date
+ ? install.installedAt.toISOString()
+ : String(install.installedAt),
+ isEnterpriseInstall: install.isEnterpriseInstall === true,
+ platform: install.platform,
+ // `listMyInstallations` already filters revoked rows out, so any hit is active.
+ revokedAt: null,
+ scope: install.scope ?? '',
+ tenantId: install.tenantId,
+ tenantName: install.tenantName ?? '',
+ };
+ },
+
+ uninstallMessenger: async (installationId) => {
+ await lambdaClient.messenger.uninstallInstallation.mutate({ installationId });
+ },
+
+ listMessengerPlatforms: async () => {
+ const platforms = (await lambdaClient.messenger.availablePlatforms.query()) as any[];
+ return platforms.map((p) => ({
+ appId: p.appId,
+ botUsername: p.botUsername,
+ id: p.id,
+ name: p.name,
+ }));
+ },
+
+ listMessengerLinks: async () => {
+ const links = (await lambdaClient.messenger.listMyLinks.query()) as any[];
+ return links.map((l) => ({
+ activeAgentId: l.activeAgentId ?? null,
+ createdAt: l.createdAt instanceof Date ? l.createdAt.toISOString() : String(l.createdAt),
+ platform: l.platform,
+ platformUserId: l.platformUserId,
+ platformUsername: l.platformUsername ?? undefined,
+ tenantId: l.tenantId || undefined,
+ }));
+ },
+
+ setMessengerActiveAgent: async (params) => {
+ await lambdaClient.messenger.setActiveAgent.mutate({
+ agentId: params.agentId,
+ platform: params.platform as any,
+ tenantId: params.tenantId,
+ });
+ },
+
+ unlinkMessenger: async (params) => {
+ await lambdaClient.messenger.unlink.mutate({
+ platform: params.platform as any,
+ tenantId: params.tenantId,
+ });
+ },
+};
+
+// ────────────────────────────────────────────────────────────────────────
+// Message service — send / read / edit / react / pin / channel / thread …
+// ────────────────────────────────────────────────────────────────────────
+
+/**
+ * The `botMessage.*` TRPC procedures accept `{ botId, ...rest }` (no
+ * `platform`); they resolve platform server-side from the bot row.
+ *
+ * Runtime callers pass `{ platform, ...rest }` and may omit `botId`. We
+ * resolve `botId` from `platform` here (frontend convenience — find the
+ * first enabled bot on that platform) and strip `platform` before
+ * forwarding, mirroring the original `_callBotMessage` behavior.
+ */
+const resolveBotId = async (params: { botId?: string; platform?: string }): Promise<string> => {
+ if (params.botId) return params.botId;
+ if (!params.platform) {
+ throw new Error('botId or platform is required');
+ }
+ const providers = (await lambdaClient.agentBotProvider.list.query()) as any[];
+ const bot = providers.find((b) => b.platform === params.platform && b.enabled);
+ if (!bot) {
+ throw new Error(`No enabled bot found for platform "${params.platform}". Configure one first.`);
+ }
+ return bot.id;
+};
+
+/**
+ * Build the TRPC input by resolving `botId` and stripping the
+ * dispatch-only keys (`platform`, `botId` if injected) before merging
+ * back in. Cast through `any` because the runtime's per-API param shapes
+ * vary; the TRPC procedures will type-check the final shape.
+ */
+const buildTrpcInput = async (params: any): Promise<any> => {
+ const botId = await resolveBotId(params);
+ const { botId: _b, platform: _p, ...rest } = params ?? {};
+ return { ...rest, botId };
+};
+
+export const trpcMessageService: MessageRuntimeService = {
+ sendMessage: async (params) => {
+ return lambdaClient.botMessage.sendMessage.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ sendDirectMessage: async (params) => {
+ return lambdaClient.botMessage.sendDirectMessage.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ readMessages: async (params) => {
+ return lambdaClient.botMessage.readMessages.query(await buildTrpcInput(params)) as any;
+ },
+
+ editMessage: async (params) => {
+ return lambdaClient.botMessage.editMessage.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ deleteMessage: async (params) => {
+ return lambdaClient.botMessage.deleteMessage.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ searchMessages: async (params) => {
+ return lambdaClient.botMessage.searchMessages.query(await buildTrpcInput(params)) as any;
+ },
+
+ reactToMessage: async (params) => {
+ return lambdaClient.botMessage.reactToMessage.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ getReactions: async (params) => {
+ return lambdaClient.botMessage.getReactions.query(await buildTrpcInput(params)) as any;
+ },
+
+ pinMessage: async (params) => {
+ return lambdaClient.botMessage.pinMessage.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ unpinMessage: async (params) => {
+ return lambdaClient.botMessage.unpinMessage.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ listPins: async (params) => {
+ return lambdaClient.botMessage.listPins.query(await buildTrpcInput(params)) as any;
+ },
+
+ getChannelInfo: async (params) => {
+ return lambdaClient.botMessage.getChannelInfo.query(await buildTrpcInput(params)) as any;
+ },
+
+ listChannels: async (params) => {
+ return lambdaClient.botMessage.listChannels.query(await buildTrpcInput(params)) as any;
+ },
+
+ getMemberInfo: async (params) => {
+ return lambdaClient.botMessage.getMemberInfo.query(await buildTrpcInput(params)) as any;
+ },
+
+ createThread: async (params) => {
+ return lambdaClient.botMessage.createThread.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ listThreads: async (params) => {
+ return lambdaClient.botMessage.listThreads.query(await buildTrpcInput(params)) as any;
+ },
+
+ replyToThread: async (params) => {
+ return lambdaClient.botMessage.replyToThread.mutate(await buildTrpcInput(params)) as any;
+ },
+
+ createPoll: async (params) => {
+ return lambdaClient.botMessage.createPoll.mutate(await buildTrpcInput(params)) as any;
+ },
+};