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(bot): add hidden iMessage backend foundation (#15227)

Arvin Xubcc31ca331bc
diff --git a/package.json b/package.json
index 342e3160640..1478b5fa753 100644
--- a/package.json
+++ b/package.json
@@ -245,6 +245,7 @@
"@lobechat/business-model-bank": "workspace:*",
"@lobechat/business-model-runtime": "workspace:*",
"@lobechat/chat-adapter-feishu": "workspace:*",
+ "@lobechat/chat-adapter-imessage": "workspace:*",
"@lobechat/chat-adapter-line": "workspace:*",
"@lobechat/chat-adapter-qq": "workspace:*",
"@lobechat/chat-adapter-wechat": "workspace:*",
diff --git a/packages/builtin-tool-message/src/types.ts b/packages/builtin-tool-message/src/types.ts
index 89bbd6662e1..c95067b62a8 100644
--- a/packages/builtin-tool-message/src/types.ts
+++ b/packages/builtin-tool-message/src/types.ts
@@ -7,6 +7,7 @@ export const MessageToolIdentifier = 'lobe-message';
export const MessagePlatform = {
discord: 'discord',
feishu: 'feishu',
+ imessage: 'imessage',
lark: 'lark',
qq: 'qq',
slack: 'slack',
diff --git a/packages/chat-adapter-imessage/package.json b/packages/chat-adapter-imessage/package.json
new file mode 100644
index 00000000000..37ac42153c6
--- /dev/null
+++ b/packages/chat-adapter-imessage/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "@lobechat/chat-adapter-imessage",
+ "version": "0.1.0",
+ "description": "iMessage adapter for chat SDK via BlueBubbles",
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "files": [
+ "dist"
+ ],
+ "scripts": {
+ "build": "tsup",
+ "clean": "rm -rf dist",
+ "dev": "tsup --watch",
+ "typecheck": "tsc --noEmit"
+ },
+ "dependencies": {
+ "chat": "^4.23.0"
+ },
+ "devDependencies": {
+ "@types/node": "^22.0.0",
+ "tsup": "^8.3.5",
+ "typescript": "^5.7.2"
+ }
+}
diff --git a/packages/chat-adapter-imessage/src/adapter.test.ts b/packages/chat-adapter-imessage/src/adapter.test.ts
new file mode 100644
index 00000000000..d00defd7f66
--- /dev/null
+++ b/packages/chat-adapter-imessage/src/adapter.test.ts
@@ -0,0 +1,227 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createImessageAdapter, extractAttachmentMetadata, ImessageAdapter } from './adapter';
+import { BlueBubblesApiClient } from './api';
+import type { BlueBubblesMessage, BlueBubblesWebhookEvent } from './types';
+
+const baseConfig = {
+ password: 'server-password',
+ serverUrl: 'https://bluebubbles.example.com',
+ webhookSecret: 'shared-secret',
+};
+
+function makeAdapter(overrides: Partial<typeof baseConfig> = {}) {
+ const adapter = createImessageAdapter({ ...baseConfig, ...overrides });
+ const processMessage = vi.fn(
+ async (_adapter: unknown, _threadId: string, factory: () => Promise<unknown> | unknown) =>
+ factory(),
+ );
+ const chat = {
+ getLogger: () => ({
+ child: () => ({}),
+ debug: vi.fn(),
+ error: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ }),
+ getUserName: () => 'imessage-bot',
+ processMessage,
+ } as any;
+ return { adapter, chat, processMessage };
+}
+
+function makeRequest(body: BlueBubblesWebhookEvent, secret = baseConfig.webhookSecret): Request {
+ return new Request(
+ `https://lobehub.example.com/api/agent/webhooks/imessage/mac?secret=${secret}`,
+ {
+ body: JSON.stringify(body),
+ method: 'POST',
+ },
+ );
+}
+
+function textMessage(overrides: Partial<BlueBubblesMessage> = {}): BlueBubblesMessage {
+ return {
+ chats: [{ guid: 'iMessage;-;chat-1', style: 45 }],
+ dateCreated: 1_700_000_000_000,
+ guid: 'msg-1',
+ handle: { address: '+15551234567' },
+ isFromMe: false,
+ text: 'hello',
+ ...overrides,
+ };
+}
+
+describe('ImessageAdapter webhook handling', () => {
+ let fetchSpy: any;
+
+ beforeEach(() => {
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ fetchSpy.mockRestore();
+ });
+
+ it('rejects POST with a missing or mismatched secret', async () => {
+ const { adapter, chat } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const res = await adapter.handleWebhook(
+ makeRequest({ data: textMessage(), type: 'new-message' }, 'wrong'),
+ );
+ expect(res.status).toBe(401);
+ });
+
+ it('dispatches a BlueBubbles new-message webhook to the chat guid thread', async () => {
+ const { adapter, chat, processMessage } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const res = await adapter.handleWebhook(
+ makeRequest({ data: textMessage(), type: 'new-message' }),
+ );
+
+ expect(res.status).toBe(200);
+ expect(processMessage).toHaveBeenCalledTimes(1);
+ expect(processMessage.mock.calls[0][1]).toBe('imessage:iMessage;-;chat-1');
+
+ const factory = processMessage.mock.calls[0][2] as () => Promise<any>;
+ const message = await factory();
+ expect(message.text).toBe('hello');
+ expect(message.author.userId).toBe('+15551234567');
+ expect(message.metadata.dateSent.getTime()).toBe(1_700_000_000_000);
+ });
+
+ it('enriches webhook messages that do not carry chats', async () => {
+ fetchSpy.mockResolvedValueOnce(
+ new Response(
+ JSON.stringify({
+ data: textMessage({ guid: 'msg-needs-enrichment', text: 'enriched' }),
+ }),
+ { status: 200 },
+ ),
+ );
+
+ const { adapter, chat, processMessage } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const res = await adapter.handleWebhook(
+ makeRequest({ data: { guid: 'msg-needs-enrichment', isFromMe: false }, type: 'new-message' }),
+ );
+
+ expect(res.status).toBe(200);
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(fetchSpy.mock.calls[0][0]).toBe(
+ 'https://bluebubbles.example.com/api/v1/message/msg-needs-enrichment?password=server-password&with=chats%2Cattachments',
+ );
+ expect(processMessage.mock.calls[0][1]).toBe('imessage:iMessage;-;chat-1');
+ });
+
+ it('ignores messages sent by the hosted Mac account', async () => {
+ const { adapter, chat, processMessage } = makeAdapter();
+ await adapter.initialize(chat);
+
+ const res = await adapter.handleWebhook(
+ makeRequest({ data: textMessage({ isFromMe: true }), type: 'new-message' }),
+ );
+
+ expect(res.status).toBe(200);
+ expect(processMessage).not.toHaveBeenCalled();
+ });
+});
+
+describe('ImessageAdapter parsing and outbound', () => {
+ let fetchSpy: any;
+
+ beforeEach(() => {
+ fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(
+ new Response(JSON.stringify({ data: { guid: 'sent-1', text: 'hi back' } }), {
+ status: 200,
+ }),
+ );
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ fetchSpy.mockRestore();
+ });
+
+ it('extracts metadata-only attachments from BlueBubbles messages', () => {
+ const attachments = extractAttachmentMetadata(
+ textMessage({
+ attachments: [
+ {
+ guid: 'att-1',
+ mimeType: 'image/png',
+ totalBytes: 123,
+ transferName: 'photo.png',
+ },
+ ],
+ }),
+ );
+
+ expect(attachments).toHaveLength(1);
+ expect(attachments[0].type).toBe('image');
+ expect(attachments[0].mimeType).toBe('image/png');
+ expect((attachments[0] as any).raw.guid).toBe('att-1');
+ });
+
+ it('postMessage sends text through BlueBubbles /message/text', async () => {
+ const adapter = new ImessageAdapter(baseConfig);
+ const result = await adapter.postMessage('imessage:iMessage;-;chat-1', 'hi back' as any);
+
+ expect(result.id).toBe('sent-1');
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit];
+ expect(url).toBe(
+ 'https://bluebubbles.example.com/api/v1/message/text?password=server-password',
+ );
+ expect(init.method).toBe('POST');
+ const body = JSON.parse(init.body as string);
+ expect(body.chatGuid).toBe('iMessage;-;chat-1');
+ expect(body.message).toBe('hi back');
+ expect(body.method).toBe('apple-script');
+ expect(body.tempGuid).toBeTruthy();
+ });
+
+ it('BlueBubblesApiClient pings the authenticated API endpoint', async () => {
+ const api = new BlueBubblesApiClient(baseConfig);
+ await api.ping();
+
+ expect(fetchSpy.mock.calls[0][0]).toBe(
+ 'https://bluebubbles.example.com/api/v1/ping?password=server-password',
+ );
+ });
+
+ it('applies the request timeout when fetching outbound attachment URLs', async () => {
+ vi.useFakeTimers();
+
+ fetchSpy.mockImplementationOnce(
+ async (_url: string | URL | Request, init?: RequestInit) =>
+ new Promise<Response>((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => {
+ reject(new DOMException('Attachment fetch timed out', 'AbortError'));
+ });
+ }),
+ );
+
+ const api = new BlueBubblesApiClient({ ...baseConfig, requestTimeoutMs: 1000 });
+ const sendPromise = api.sendAttachment('iMessage;-;chat-1', {
+ fetchUrl: 'https://assets.example.com/photo.png',
+ mimeType: 'image/png',
+ name: 'photo.png',
+ });
+ const assertion = expect(sendPromise).rejects.toMatchObject({ name: 'AbortError' });
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ await assertion;
+ expect(fetchSpy).toHaveBeenCalledTimes(1);
+ expect(fetchSpy.mock.calls[0][0]).toBe('https://assets.example.com/photo.png');
+ expect(fetchSpy.mock.calls[0][1]).toMatchObject({
+ method: 'GET',
+ signal: expect.any(AbortSignal),
+ });
+ });
+});
diff --git a/packages/chat-adapter-imessage/src/adapter.ts b/packages/chat-adapter-imessage/src/adapter.ts
new file mode 100644
index 00000000000..dd643abc525
--- /dev/null
+++ b/packages/chat-adapter-imessage/src/adapter.ts
@@ -0,0 +1,388 @@
+import type {
+ Adapter,
+ AdapterPostableMessage,
+ Attachment,
+ Author,
+ ChatInstance,
+ EmojiValue,
+ FetchOptions,
+ FetchResult,
+ FormattedContent,
+ Logger,
+ RawMessage,
+ ThreadInfo,
+ WebhookOptions,
+} from 'chat';
+import { Message, parseMarkdown } from 'chat';
+
+import { BlueBubblesApiClient, resolveAttachmentName } from './api';
+import { ImessageFormatConverter } from './format-converter';
+import type {
+ BlueBubblesAttachment,
+ BlueBubblesChat,
+ BlueBubblesMessage,
+ BlueBubblesWebhookEvent,
+ ImessageAdapterConfig,
+ ImessageBridgeTransport,
+ ImessageThreadId,
+} from './types';
+
+const NEW_MESSAGE_EVENT = 'new-message';
+
+function senderIdFromMessage(message: BlueBubblesMessage): string {
+ const handle = message.handle;
+ return (
+ handle?.address ||
+ handle?.uncanonicalizedId ||
+ String(message.handleId ?? message.otherHandle ?? 'unknown')
+ );
+}
+
+function extractText(message: BlueBubblesMessage): string {
+ const text = message.text?.trim();
+ if (text) return text;
+
+ const subject = message.subject?.trim();
+ if (subject) return subject;
+
+ const attachments = message.attachments ?? [];
+ if (attachments.length === 0) return '';
+ return attachments
+ .map((attachment) => {
+ const name = resolveAttachmentName(attachment);
+ return `[attachment: ${name}]`;
+ })
+ .join('\n');
+}
+
+function attachmentType(mimeType: string | undefined): 'audio' | 'file' | 'image' | 'video' {
+ if (mimeType?.startsWith('image/')) return 'image';
+ if (mimeType?.startsWith('video/')) return 'video';
+ if (mimeType?.startsWith('audio/')) return 'audio';
+ return 'file';
+}
+
+export function extractAttachmentMetadata(message: BlueBubblesMessage): Attachment[] {
+ return (message.attachments ?? []).map((attachment) => ({
+ mimeType: attachment.mimeType ?? 'application/octet-stream',
+ name: resolveAttachmentName(attachment),
+ raw: attachment,
+ size: attachment.totalBytes,
+ type: attachmentType(attachment.mimeType),
+ url: '',
+ })) as Attachment[];
+}
+
+function dateFromBlueBubbles(timestamp: number | null | undefined): Date {
+ if (!timestamp) return new Date();
+ return new Date(timestamp);
+}
+
+function isDirectChat(chat: BlueBubblesChat | undefined): boolean {
+ if (!chat) return false;
+ if (typeof chat.style === 'number') return chat.style !== 43;
+ if (Array.isArray(chat.participants)) return chat.participants.length <= 1;
+ return false;
+}
+
+export function encodeImessageThreadId(data: ImessageThreadId): string {
+ return `imessage:${data.chatGuid}`;
+}
+
+export function decodeImessageThreadId(threadId: string): ImessageThreadId {
+ if (threadId.startsWith('imessage:')) {
+ return { chatGuid: threadId.slice('imessage:'.length) };
+ }
+ return { chatGuid: threadId };
+}
+
+export class ImessageAdapter implements Adapter<ImessageThreadId, BlueBubblesMessage> {
+ readonly name = 'imessage';
+
+ private readonly api?: BlueBubblesApiClient;
+ private readonly botId: string;
+ private readonly formatConverter: ImessageFormatConverter;
+ private readonly knownDmThreads = new Map<string, boolean>();
+ private readonly transport?: ImessageBridgeTransport;
+ private readonly webhookSecret: string;
+
+ private _userName: string;
+ private chat!: ChatInstance;
+ private logger!: Logger;
+
+ constructor(config: ImessageAdapterConfig) {
+ if (!config.webhookSecret?.trim()) throw new Error('iMessage adapter requires webhookSecret');
+
+ if (config.transport) {
+ this.transport = config.transport;
+ } else {
+ if (!config.serverUrl?.trim()) throw new Error('iMessage adapter requires serverUrl');
+ if (!config.password?.trim()) throw new Error('iMessage adapter requires password');
+ this.api = new BlueBubblesApiClient({
+ password: config.password,
+ requestTimeoutMs: config.requestTimeoutMs,
+ serverUrl: config.serverUrl,
+ });
+ }
+ this.webhookSecret = config.webhookSecret;
+ this.botId = config.botUserId || 'imessage:self';
+ this._userName = config.userName || 'imessage-bot';
+ this.formatConverter = new ImessageFormatConverter();
+ }
+
+ get botUserId(): string {
+ return this.botId;
+ }
+
+ get userName(): string {
+ return this._userName;
+ }
+
+ async initialize(chat: ChatInstance): Promise<void> {
+ this.chat = chat;
+ this.logger = chat.getLogger(this.name);
+ this._userName = chat.getUserName();
+ this.logger.info(
+ this.transport
+ ? 'Initialized iMessage adapter via Desktop BlueBubbles bridge'
+ : 'Initialized iMessage adapter via BlueBubbles',
+ );
+ }
+
+ async handleWebhook(request: Request, options?: WebhookOptions): Promise<Response> {
+ if (request.method !== 'POST') {
+ return new Response('Method not allowed', { status: 405 });
+ }
+
+ const url = new URL(request.url);
+ if (url.searchParams.get('secret') !== this.webhookSecret) {
+ this.logger.warn('Rejected iMessage webhook with invalid secret');
+ return new Response('Invalid secret', { status: 401 });
+ }
+
+ let event: BlueBubblesWebhookEvent;
+ try {
+ event = (await request.json()) as BlueBubblesWebhookEvent;
+ } catch {
+ return new Response('Invalid JSON', { status: 400 });
+ }
+
+ if (event.type !== NEW_MESSAGE_EVENT) {
+ return Response.json({ ok: true });
+ }
+
+ const message = await this.resolveWebhookMessage(event.data);
+ if (!message?.guid) {
+ this.logger.warn('Ignored iMessage webhook without message guid');
+ return Response.json({ ok: true });
+ }
+
+ if (message.isFromMe) {
+ return Response.json({ ok: true });
+ }
+
+ const chat = message.chats?.[0];
+ const chatGuid = chat?.guid;
+ if (!chatGuid) {
+ this.logger.warn('Ignored iMessage webhook without chat guid for message=%s', message.guid);
+ return Response.json({ ok: true });
+ }
+
+ const threadId = this.encodeThreadId({ chatGuid });
+ this.knownDmThreads.set(threadId, isDirectChat(chat));
+ const messageFactory = async () => this.parseInbound(message, threadId);
+ this.chat.processMessage(this, threadId, messageFactory, options);
+
+ return Response.json({ ok: true });
+ }
+
+ async postMessage(
+ threadId: string,
+ message: AdapterPostableMessage,
+ ): Promise<RawMessage<BlueBubblesMessage>> {
+ const { chatGuid } = this.decodeThreadId(threadId);
+ const text = this.formatConverter.renderPostable(message);
+ const raw = this.transport?.sendText
+ ? await this.transport.sendText(chatGuid, text)
+ : await this.getApi().sendText(chatGuid, text);
+ return {
+ id: raw.guid || raw.tempGuid || `local_${Date.now()}`,
+ raw,
+ threadId,
+ };
+ }
+
+ async editMessage(
+ threadId: string,
+ _messageId: string,
+ message: AdapterPostableMessage,
+ ): Promise<RawMessage<BlueBubblesMessage>> {
+ return this.postMessage(threadId, message);
+ }
+
+ async deleteMessage(_threadId: string, _messageId: string): Promise<void> {
+ this.logger.warn('Message deletion not supported for iMessage via BlueBubbles');
+ }
+
+ async fetchMessages(
+ threadId: string,
+ options?: FetchOptions,
+ ): Promise<FetchResult<BlueBubblesMessage>> {
+ const { chatGuid } = this.decodeThreadId(threadId);
+ const result = this.transport?.getChatMessages
+ ? await this.transport.getChatMessages(chatGuid, {
+ limit: options?.limit,
+ sort: 'DESC',
+ withParts: ['attachments'],
+ })
+ : await this.getApi().getChatMessages(chatGuid, {
+ limit: options?.limit,
+ sort: 'DESC',
+ withParts: ['attachments'],
+ });
+ return {
+ messages: result.data.map((raw) => this.parseInbound(raw, threadId)).reverse(),
+ nextCursor: undefined,
+ };
+ }
+
+ async fetchThread(threadId: string): Promise<ThreadInfo> {
+ const { chatGuid } = this.decodeThreadId(threadId);
+ try {
+ const chat = this.transport?.getChat
+ ? await this.transport.getChat(chatGuid, ['participants'])
+ : await this.getApi().getChat(chatGuid, ['participants']);
+ const isDM = isDirectChat(chat);
+ this.knownDmThreads.set(threadId, isDM);
+ return {
+ channelId: threadId,
+ channelName: chat.displayName || chat.chatIdentifier,
+ id: threadId,
+ isDM,
+ metadata: chat as unknown as Record<string, unknown>,
+ };
+ } catch (error) {
+ this.logger.warn('fetchThread failed for %s: %s', threadId, error);
+ return {
+ channelId: threadId,
+ id: threadId,
+ isDM: this.knownDmThreads.get(threadId) ?? false,
+ metadata: { chatGuid },
+ };
+ }
+ }
+
+ async addReaction(
+ _threadId: string,
+ _messageId: string,
+ _emoji: EmojiValue | string,
+ ): Promise<void> {}
+
+ async removeReaction(
+ _threadId: string,
+ _messageId: string,
+ _emoji: EmojiValue | string,
+ ): Promise<void> {}
+
+ async startTyping(threadId: string): Promise<void> {
+ const { chatGuid } = this.decodeThreadId(threadId);
+ try {
+ if (this.transport?.startTyping) {
+ await this.transport.startTyping(chatGuid);
+ } else {
+ await this.getApi().startTyping(chatGuid);
+ }
+ } catch (error) {
+ this.logger.warn('startTyping failed for %s: %s', threadId, error);
+ }
+ }
+
+ parseMessage(raw: BlueBubblesMessage, threadId?: string): Message<BlueBubblesMessage> {
+ return this.parseInbound(
+ raw,
+ threadId ?? this.encodeThreadId({ chatGuid: raw.chats?.[0]?.guid ?? this.botId }),
+ );
+ }
+
+ encodeThreadId(data: ImessageThreadId): string {
+ return encodeImessageThreadId(data);
+ }
+
+ decodeThreadId(threadId: string): ImessageThreadId {
+ return decodeImessageThreadId(threadId);
+ }
+
+ channelIdFromThreadId(threadId: string): string {
+ return threadId;
+ }
+
+ isDM(threadId: string): boolean {
+ return this.knownDmThreads.get(threadId) ?? false;
+ }
+
+ renderFormatted(content: FormattedContent): string {
+ return this.formatConverter.fromAst(content);
+ }
+
+ private async resolveWebhookMessage(
+ message: BlueBubblesMessage | undefined,
+ ): Promise<BlueBubblesMessage | undefined> {
+ if (!message?.guid) return message;
+ if (message.chats?.[0]?.guid) return message;
+
+ if (!this.api) {
+ this.logger.warn(
+ 'iMessage bridge webhook message=%s did not include chat data; configure Desktop bridge enrichment',
+ message.guid,
+ );
+ return message;
+ }
+
+ try {
+ return await this.api.getMessage(message.guid, ['chats', 'attachments']);
+ } catch (error) {
+ this.logger.warn('Failed to enrich iMessage webhook message=%s: %s', message.guid, error);
+ return message;
+ }
+ }
+
+ private getApi(): BlueBubblesApiClient {
+ if (!this.api) throw new Error('BlueBubbles API is not available in Desktop bridge mode');
+ return this.api;
+ }
+
+ private parseInbound(message: BlueBubblesMessage, threadId: string): Message<BlueBubblesMessage> {
+ const text = extractText(message);
+ const formatted = parseMarkdown(text);
+ const userId = message.isFromMe ? this.botId : senderIdFromMessage(message);
+ const author: Author = {
+ fullName: userId,
+ isBot: Boolean(message.isFromMe),
+ isMe: Boolean(message.isFromMe),
+ userId,
+ userName: userId,
+ };
+
+ return new Message({
+ attachments: extractAttachmentMetadata(message),
+ author,
+ formatted,
+ id: message.guid,
+ metadata: {
+ dateSent: dateFromBlueBubbles(message.dateCreated),
+ edited: false,
+ },
+ raw: message,
+ text,
+ threadId,
+ });
+ }
+}
+
+export function createImessageAdapter(config: ImessageAdapterConfig): ImessageAdapter {
+ return new ImessageAdapter(config);
+}
+
+export function resolveAttachmentGuid(raw: BlueBubblesAttachment | undefined): string | undefined {
+ return raw?.guid;
+}
diff --git a/packages/chat-adapter-imessage/src/api.ts b/packages/chat-adapter-imessage/src/api.ts
new file mode 100644
index 00000000000..d0785ea9d54
--- /dev/null
+++ b/packages/chat-adapter-imessage/src/api.ts
@@ -0,0 +1,325 @@
+import { randomUUID } from 'node:crypto';
+
+import type {
+ BlueBubblesApiConfig,
+ BlueBubblesAttachment,
+ BlueBubblesChat,
+ BlueBubblesDownloadedAttachment,
+ BlueBubblesMessage,
+ BlueBubblesOutboundAttachment,
+ BlueBubblesQueryResult,
+ BlueBubblesResponse,
+ BlueBubblesSendOptions,
+ BlueBubblesWebhook,
+} from './types';
+
+const DEFAULT_REQUEST_TIMEOUT_MS = 60_000;
+
+interface RequestOptions {
+ body?: FormData | Record<string, unknown>;
+ method?: 'DELETE' | 'GET' | 'POST';
+ query?: Record<string, boolean | number | string | undefined>;
+ signal?: AbortSignal;
+}
+
+export class BlueBubblesApiClient {
+ readonly password: string;
+ readonly requestTimeoutMs: number;
+ readonly serverUrl: string;
+
+ constructor(options: BlueBubblesApiConfig) {
+ if (!options.serverUrl?.trim()) throw new Error('BlueBubbles serverUrl is required');
+ if (!options.password?.trim()) throw new Error('BlueBubbles password is required');
+
+ this.serverUrl = stripTrailingSlashes(options.serverUrl.trim());
+ this.password = options.password;
+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
+ }
+
+ async ping(): Promise<void> {
+ await this.requestData<Record<string, unknown>>('ping');
+ }
+
+ async getMessage(
+ guid: string,
+ withParts: string[] = ['chats', 'attachments'],
+ ): Promise<BlueBubblesMessage> {
+ return this.requestData<BlueBubblesMessage>(`message/${encodeURIComponent(guid)}`, {
+ query: { with: withParts.join(',') },
+ });
+ }
+
+ async getChat(guid: string, withParts: string[] = ['participants']): Promise<BlueBubblesChat> {
+ return this.requestData<BlueBubblesChat>(`chat/${encodeURIComponent(guid)}`, {
+ query: { with: withParts.join(',') },
+ });
+ }
+
+ async getChatMessages(
+ chatGuid: string,
+ options: {
+ after?: number | string;
+ before?: number | string;
+ limit?: number;
+ offset?: number;
+ sort?: 'ASC' | 'DESC';
+ withParts?: string[];
+ } = {},
+ ): Promise<BlueBubblesQueryResult<BlueBubblesMessage>> {
+ const response = await this.request<BlueBubblesMessage[]>(
+ `chat/${encodeURIComponent(chatGuid)}/message`,
+ {
+ query: {
+ after: options.after,
+ before: options.before,
+ limit: options.limit,
+ offset: options.offset,
+ sort: options.sort,
+ with: (options.withParts ?? ['attachments']).join(','),
+ },
+ },
+ );
+ return { data: response.data ?? [], metadata: response.metadata };
+ }
+
+ async queryMessages(
+ body: Record<string, unknown>,
+ ): Promise<BlueBubblesQueryResult<BlueBubblesMessage>> {
+ const response = await this.request<BlueBubblesMessage[]>('message/query', {
+ body,
+ method: 'POST',
+ });
+ return { data: response.data ?? [], metadata: response.metadata };
+ }
+
+ async queryChats(
+ body: Record<string, unknown>,
+ ): Promise<BlueBubblesQueryResult<BlueBubblesChat>> {
+ const response = await this.request<BlueBubblesChat[]>('chat/query', {
+ body,
+ method: 'POST',
+ });
+ return { data: response.data ?? [], metadata: response.metadata };
+ }
+
+ async registerWebhook(
+ url: string,
+ events: string[] = ['new-message'],
+ ): Promise<BlueBubblesWebhook> {
+ return this.requestData<BlueBubblesWebhook>('webhook', {
+ body: { events, url },
+ method: 'POST',
+ });
+ }
+
+ async listWebhooks(url?: string): Promise<BlueBubblesWebhook[]> {
+ const response = await this.request<BlueBubblesWebhook[]>('webhook', {
+ query: { url },
+ });
+ return response.data ?? [];
+ }
+
+ async sendText(
+ chatGuid: string,
+ message: string,
+ options: BlueBubblesSendOptions = {},
+ ): Promise<BlueBubblesMessage> {
+ return this.requestData<BlueBubblesMessage>('message/text', {
+ body: {
+ chatGuid,
+ message,
+ method: options.method ?? 'apple-script',
+ tempGuid: options.tempGuid ?? randomUUID(),
+ },
+ method: 'POST',
+ });
+ }
+
+ async sendAttachment(
+ chatGuid: string,
+ attachment: BlueBubblesOutboundAttachment,
+ options: BlueBubblesSendOptions = {},
+ ): Promise<BlueBubblesMessage> {
+ const { buffer, mimeType } = await resolveAttachmentBytes(attachment, this.requestTimeoutMs);
+ const name = attachment.name || inferFileName(mimeType || attachment.mimeType);
+ const form = new FormData();
+ const attachmentBytes = buffer.buffer.slice(
+ buffer.byteOffset,
+ buffer.byteOffset + buffer.byteLength,
+ ) as ArrayBuffer;
+ form.set('chatGuid', chatGuid);
+ form.set('tempGuid', options.tempGuid ?? randomUUID());
+ form.set('method', options.method ?? 'apple-script');
+ form.set('name', name);
+ form.set(
+ 'attachment',
+ new Blob([attachmentBytes], { type: mimeType ?? attachment.mimeType }),
+ name,
+ );
+
+ return this.requestData<BlueBubblesMessage>('message/attachment', {
+ body: form,
+ method: 'POST',
+ });
+ }
+
+ async startTyping(chatGuid: string): Promise<void> {
+ await this.requestData<Record<string, unknown>>(`chat/${encodeURIComponent(chatGuid)}/typing`, {
+ method: 'POST',
+ });
+ }
+
+ async stopTyping(chatGuid: string): Promise<void> {
+ await this.requestData<Record<string, unknown>>(`chat/${encodeURIComponent(chatGuid)}/typing`, {
+ method: 'DELETE',
+ });
+ }
+
+ async downloadAttachment(guid: string): Promise<BlueBubblesDownloadedAttachment> {
+ const url = this.buildUrl(`attachment/${encodeURIComponent(guid)}/download`, {
+ original: true,
+ });
+ const response = await fetchWithTimeout(url, { method: 'GET' }, this.requestTimeoutMs);
+ if (!response.ok) {
+ const detail = await safeReadError(response);
+ throw new Error(detail || `downloadAttachment ${guid} failed with HTTP ${response.status}`);
+ }
+
+ return {
+ buffer: Buffer.from(await response.arrayBuffer()),
+ mimeType: response.headers.get('content-type') ?? undefined,
+ };
+ }
+
+ private async requestData<T>(path: string, options: RequestOptions = {}): Promise<T> {
+ const response = await this.request<T>(path, options);
+ return (response.data ?? ({} as T)) as T;
+ }
+
+ private async request<T>(
+ path: string,
+ { method = 'GET', body, query, signal }: RequestOptions = {},
+ ): Promise<BlueBubblesResponse<T>> {
+ const url = this.buildUrl(path, query);
+ const init: RequestInit = { method, signal };
+
+ if (body instanceof FormData) {
+ init.body = body;
+ } else if (body) {
+ init.body = JSON.stringify(body);
+ init.headers = { 'Content-Type': 'application/json' };
+ }
+
+ const response = await fetchWithTimeout(url, init, this.requestTimeoutMs);
+ return parseResponse<T>(response, path);
+ }
+
+ private buildUrl(
+ path: string,
+ query?: Record<string, boolean | number | string | undefined>,
+ ): string {
+ const url = new URL(path.replace(/^\/+/, ''), `${this.serverUrl}/api/v1/`);
+ url.searchParams.set('password', this.password);
+ for (const [key, value] of Object.entries(query ?? {})) {
+ if (value === undefined) continue;
+ url.searchParams.set(key, String(value));
+ }
+ return url.toString();
+ }
+}
+
+async function parseResponse<T>(
+ response: Response,
+ label: string,
+): Promise<BlueBubblesResponse<T>> {
+ const text = await response.text();
+ const payload = parseJson<BlueBubblesResponse<T>>(text);
+
+ if (!response.ok) {
+ const detail = readBlueBubblesError(payload) ?? text;
+ throw new Error(detail || `${label} failed with HTTP ${response.status}`);
+ }
+
+ return payload ?? {};
+}
+
+async function safeReadError(response: Response): Promise<string | undefined> {
+ const text = await response.text();
+ const payload = parseJson<BlueBubblesResponse>(text);
+ return readBlueBubblesError(payload) ?? (text || undefined);
+}
+
+function readBlueBubblesError(payload: BlueBubblesResponse | undefined): string | undefined {
+ if (!payload) return undefined;
+ const data = payload.data as { error?: unknown; message?: unknown } | undefined;
+ if (typeof data?.error === 'string') return data.error;
+ if (typeof data?.message === 'string') return data.message;
+ return payload.message;
+}
+
+function parseJson<T>(text: string): T | undefined {
+ if (!text) return undefined;
+ try {
+ return JSON.parse(text) as T;
+ } catch {
+ return undefined;
+ }
+}
+
+async function fetchWithTimeout(
+ url: string,
+ init: RequestInit,
+ timeoutMs: number,
+): Promise<Response> {
+ const abort = new AbortController();
+ const timer = setTimeout(() => abort.abort(), timeoutMs);
+ const signal = init.signal ? AbortSignal.any([init.signal, abort.signal]) : abort.signal;
+
+ try {
+ return await fetch(url, { ...init, signal });
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function stripTrailingSlashes(url: string): string {
+ let end = url.length;
+ while (end > 0 && url[end - 1] === '/') end--;
+ return url.slice(0, end);
+}
+
+async function resolveAttachmentBytes(
+ attachment: BlueBubblesOutboundAttachment,
+ requestTimeoutMs: number,
+): Promise<{ buffer: Buffer; mimeType?: string }> {
+ if (attachment.data) {
+ return { buffer: Buffer.from(attachment.data, 'base64'), mimeType: attachment.mimeType };
+ }
+
+ if (!attachment.fetchUrl) {
+ throw new Error('BlueBubbles attachment requires either data or fetchUrl');
+ }
+
+ const response = await fetchWithTimeout(attachment.fetchUrl, { method: 'GET' }, requestTimeoutMs);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch attachment ${attachment.fetchUrl}: HTTP ${response.status}`);
+ }
+ return {
+ buffer: Buffer.from(await response.arrayBuffer()),
+ mimeType: response.headers.get('content-type') ?? attachment.mimeType,
+ };
+}
+
+function inferFileName(mimeType: string | undefined): string {
+ if (!mimeType) return 'attachment.bin';
+ const [topLevel, subtype] = mimeType.split('/');
+ if (!subtype) return 'attachment.bin';
+ if (topLevel === 'image') return `image.${subtype}`;
+ if (topLevel === 'video') return `video.${subtype}`;
+ if (topLevel === 'audio') return `audio.${subtype}`;
+ return `attachment.${subtype}`;
+}
+
+export function resolveAttachmentName(attachment: BlueBubblesAttachment): string {
+ return attachment.transferName || attachment.filename || `${attachment.guid}.bin`;
+}
diff --git a/packages/chat-adapter-imessage/src/format-converter.ts b/packages/chat-adapter-imessage/src/format-converter.ts
new file mode 100644
index 00000000000..a492bcd41e2
--- /dev/null
+++ b/packages/chat-adapter-imessage/src/format-converter.ts
@@ -0,0 +1,17 @@
+import type { Root } from 'chat';
+import { BaseFormatConverter, parseMarkdown, stringifyMarkdown } from 'chat';
+
+/**
+ * iMessage ultimately receives plain text through BlueBubbles. Keeping the
+ * markdown markers here preserves Chat SDK compatibility; the LobeHub platform
+ * client strips markdown before final bot replies are sent.
+ */
+export class ImessageFormatConverter extends BaseFormatConverter {
+ fromAst(ast: Root): string {
+ return stringifyMarkdown(ast);
+ }
+
+ toAst(text: string): Root {
+ return parseMarkdown(text.trim());
+ }
+}
diff --git a/packages/chat-adapter-imessage/src/index.ts b/packages/chat-adapter-imessage/src/index.ts
new file mode 100644
index 00000000000..580d1d75e94
--- /dev/null
+++ b/packages/chat-adapter-imessage/src/index.ts
@@ -0,0 +1,27 @@
+export {
+ createImessageAdapter,
+ decodeImessageThreadId,
+ encodeImessageThreadId,
+ extractAttachmentMetadata,
+ ImessageAdapter,
+ resolveAttachmentGuid,
+} from './adapter';
+export { BlueBubblesApiClient, resolveAttachmentName } from './api';
+export { ImessageFormatConverter } from './format-converter';
+export type {
+ BlueBubblesApiConfig,
+ BlueBubblesAttachment,
+ BlueBubblesChat,
+ BlueBubblesDownloadedAttachment,
+ BlueBubblesHandle,
+ BlueBubblesMessage,
+ BlueBubblesOutboundAttachment,
+ BlueBubblesQueryResult,
+ BlueBubblesResponse,
+ BlueBubblesSendOptions,
+ BlueBubblesWebhook,
+ BlueBubblesWebhookEvent,
+ ImessageAdapterConfig,
+ ImessageBridgeTransport,
+ ImessageThreadId,
+} from './types';
diff --git a/packages/chat-adapter-imessage/src/types.ts b/packages/chat-adapter-imessage/src/types.ts
new file mode 100644
index 00000000000..5e5da518e23
--- /dev/null
+++ b/packages/chat-adapter-imessage/src/types.ts
@@ -0,0 +1,137 @@
+export interface BlueBubblesApiConfig {
+ /**
+ * BlueBubbles API password. The server accepts it as the `password` query
+ * parameter for REST calls.
+ */
+ password: string;
+ requestTimeoutMs?: number;
+ /**
+ * Public base URL of the BlueBubbles server, e.g. `https://mac.example.com`.
+ */
+ serverUrl: string;
+}
+
+export interface ImessageBridgeTransport {
+ getChat?: (guid: string, withParts?: string[]) => Promise<BlueBubblesChat>;
+ getChatMessages?: (
+ chatGuid: string,
+ options?: {
+ after?: number | string;
+ before?: number | string;
+ limit?: number;
+ offset?: number;
+ sort?: 'ASC' | 'DESC';
+ withParts?: string[];
+ },
+ ) => Promise<BlueBubblesQueryResult<BlueBubblesMessage>>;
+ sendText?: (
+ chatGuid: string,
+ message: string,
+ options?: BlueBubblesSendOptions,
+ ) => Promise<BlueBubblesMessage>;
+ startTyping?: (chatGuid: string) => Promise<void>;
+}
+
+export interface ImessageAdapterConfig {
+ botUserId?: string;
+ password?: string;
+ requestTimeoutMs?: number;
+ serverUrl?: string;
+ transport?: ImessageBridgeTransport;
+ userName?: string;
+ /**
+ * Shared secret appended to the LobeHub webhook URL. BlueBubbles webhooks are
+ * not signed, so the route-level secret is the lightweight authenticity gate.
+ */
+ webhookSecret: string;
+}
+
+export interface BlueBubblesResponse<T = unknown> {
+ data?: T;
+ message?: string;
+ metadata?: {
+ count?: number;
+ limit?: number;
+ offset?: number;
+ total?: number;
+ [key: string]: unknown;
+ };
+ status?: number;
+}
+
+export interface BlueBubblesHandle {
+ address?: string;
+ country?: string;
+ guid?: string;
+ service?: string;
+ uncanonicalizedId?: string;
+}
+
+export interface BlueBubblesChat {
+ chatIdentifier?: string;
+ displayName?: string;
+ guid: string;
+ lastMessage?: BlueBubblesMessage;
+ participants?: BlueBubblesHandle[];
+ serviceName?: string;
+ style?: number;
+}
+
+export interface BlueBubblesAttachment {
+ filename?: string;
+ guid: string;
+ mimeType?: string;
+ totalBytes?: number;
+ transferName?: string;
+}
+
+export interface BlueBubblesMessage {
+ attachments?: BlueBubblesAttachment[];
+ chats?: BlueBubblesChat[];
+ dateCreated?: number | null;
+ guid: string;
+ handle?: BlueBubblesHandle | null;
+ handleId?: number | string | null;
+ isFromMe?: boolean;
+ otherHandle?: number | string | null;
+ subject?: string | null;
+ tempGuid?: string;
+ text?: string | null;
+}
+
+export interface BlueBubblesWebhookEvent {
+ data?: BlueBubblesMessage;
+ type: string;
+}
+
+export interface BlueBubblesWebhook {
+ events: string[];
+ id: number;
+ url: string;
+}
+
+export interface BlueBubblesQueryResult<T> {
+ data: T[];
+ metadata?: BlueBubblesResponse<T[]>['metadata'];
+}
+
+export interface BlueBubblesSendOptions {
+ method?: 'apple-script' | 'private-api';
+ tempGuid?: string;
+}
+
+export interface BlueBubblesOutboundAttachment {
+ data?: string;
+ fetchUrl?: string;
+ mimeType?: string;
+ name?: string;
+}
+
+export interface BlueBubblesDownloadedAttachment {
+ buffer: Buffer;
+ mimeType?: string;
+}
+
+export interface ImessageThreadId {
+ chatGuid: string;
+}
diff --git a/packages/chat-adapter-imessage/tsconfig.json b/packages/chat-adapter-imessage/tsconfig.json
new file mode 100644
index 00000000000..5c90650b8ae
--- /dev/null
+++ b/packages/chat-adapter-imessage/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "declaration": true,
+ "declarationMap": true,
+ "sourceMap": true,
+ "outDir": "./dist",
+ "rootDir": "./src",
+ "strict": true,
+ "esModuleInterop": true,
+ "skipLibCheck": true,
+ "forceConsistentCasingInFileNames": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "lib": ["ES2022"]
+ },
+ "exclude": ["node_modules", "dist"],
+ "include": ["src/**/*"]
+}
diff --git a/packages/chat-adapter-imessage/tsup.config.ts b/packages/chat-adapter-imessage/tsup.config.ts
new file mode 100644
index 00000000000..d4c69d1df67
--- /dev/null
+++ b/packages/chat-adapter-imessage/tsup.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from 'tsup';
+
+export default defineConfig({
+ dts: true,
+ entry: ['src/index.ts'],
+ format: ['esm'],
+ sourcemap: true,
+});
diff --git a/packages/chat-adapter-imessage/vitest.config.mts b/packages/chat-adapter-imessage/vitest.config.mts
new file mode 100644
index 00000000000..5b40bc079f3
--- /dev/null
+++ b/packages/chat-adapter-imessage/vitest.config.mts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ coverage: {
+ all: false,
+ },
+ environment: 'node',
+ },
+});
diff --git a/packages/device-gateway-client/src/client.test.ts b/packages/device-gateway-client/src/client.test.ts
index c2b75211e84..a1a13b45982 100644
--- a/packages/device-gateway-client/src/client.test.ts
+++ b/packages/device-gateway-client/src/client.test.ts
@@ -206,6 +206,24 @@ describe('GatewayClient', () => {
expect(toolCallCb).toHaveBeenCalledWith(msg);
});
+ it('should handle message_api_request', () => {
+ const messageApiCb = vi.fn();
+ client.on('message_api_request', messageApiCb);
+
+ const msg = {
+ api: {
+ apiName: 'sendText',
+ payload: { chatGuid: 'chat-1', message: 'hello' },
+ platform: 'imessage',
+ },
+ requestId: 'req-message-1',
+ type: 'message_api_request',
+ };
+ handler(JSON.stringify(msg));
+
+ expect(messageApiCb).toHaveBeenCalledWith(msg);
+ });
+
it('should handle system_info_request', () => {
const sysInfoCb = vi.fn();
client.on('system_info_request', sysInfoCb);
@@ -268,6 +286,27 @@ describe('GatewayClient', () => {
});
});
+ describe('sendMessageApiResponse', () => {
+ it('should send message API response message', async () => {
+ client.connect();
+ await vi.advanceTimersByTimeAsync(1);
+
+ const ws = (client as any).ws;
+ client.sendMessageApiResponse({
+ requestId: 'req-message-1',
+ result: { content: '{"ok":true}', success: true },
+ });
+
+ expect(ws.send).toHaveBeenCalledWith(
+ JSON.stringify({
+ requestId: 'req-message-1',
+ result: { content: '{"ok":true}', success: true },
+ type: 'message_api_response',
+ }),
+ );
+ });
+ });
+
describe('sendSystemInfoResponse', () => {
it('should send system info response message', async () => {
client.connect();
diff --git a/packages/device-gateway-client/src/client.ts b/packages/device-gateway-client/src/client.ts
index 76abfad379b..3a36aaec272 100644
--- a/packages/device-gateway-client/src/client.ts
+++ b/packages/device-gateway-client/src/client.ts
@@ -10,6 +10,8 @@ import type {
ClientMessage,
ConnectionStatus,
GatewayClientEvents,
+ MessageApiRequestMessage,
+ MessageApiResponseMessage,
ServerMessage,
SystemInfoRequestMessage,
SystemInfoResponseMessage,
@@ -146,6 +148,13 @@ export class GatewayClient extends EventEmitter {
});
}
+ sendMessageApiResponse(response: Omit<MessageApiResponseMessage, 'type'>): void {
+ this.sendMessage({
+ ...response,
+ type: 'message_api_response',
+ });
+ }
+
sendSystemInfoResponse(response: Omit<SystemInfoResponseMessage, 'type'>): void {
this.sendMessage({
...response,
@@ -256,6 +265,11 @@ export class GatewayClient extends EventEmitter {
break;
}
+ case 'message_api_request': {
+ this.emit('message_api_request', message as MessageApiRequestMessage);
+ break;
+ }
+
case 'system_info_request': {
this.emit('system_info_request', message as SystemInfoRequestMessage);
break;
diff --git a/packages/device-gateway-client/src/http.test.ts b/packages/device-gateway-client/src/http.test.ts
index 6e8c2d64df6..7a1e26be13c 100644
--- a/packages/device-gateway-client/src/http.test.ts
+++ b/packages/device-gateway-client/src/http.test.ts
@@ -260,6 +260,83 @@ describe('GatewayHttpClient', () => {
});
});
+ describe('executeMessageApi', () => {
+ it('should return message API result on success', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: '{"guid":"sent-1"}', success: true }),
+ ok: true,
+ });
+
+ const result = await client.executeMessageApi(
+ { userId: 'user-1' },
+ { apiName: 'sendText', payload: { chatGuid: 'chat-1' }, platform: 'imessage' },
+ );
+
+ expect(result).toEqual({ content: '{"guid":"sent-1"}', error: undefined, success: true });
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://gateway.test.com/api/device/message-api',
+ expect.objectContaining({
+ body: JSON.stringify({
+ api: { apiName: 'sendText', payload: { chatGuid: 'chat-1' }, platform: 'imessage' },
+ userId: 'user-1',
+ }),
+ }),
+ );
+ });
+
+ it('should handle non-string content', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: { ok: true }, success: true }),
+ ok: true,
+ });
+
+ const result = await client.executeMessageApi(
+ { userId: 'user-1' },
+ { apiName: 'ping', payload: {}, platform: 'imessage' },
+ );
+
+ expect(result.content).toBe(JSON.stringify({ ok: true }));
+ });
+
+ it('should handle non-ok response', async () => {
+ mockFetch({
+ ok: false,
+ status: 503,
+ text: vi.fn().mockResolvedValue('Desktop offline'),
+ });
+
+ const result = await client.executeMessageApi(
+ { userId: 'user-1' },
+ { apiName: 'ping', payload: {}, platform: 'imessage' },
+ );
+
+ expect(result).toEqual({
+ content: 'Device message API call failed (HTTP 503)',
+ error: 'Desktop offline',
+ success: false,
+ });
+ });
+
+ it('should pass optional deviceId and timeout', async () => {
+ mockFetch({
+ json: vi.fn().mockResolvedValue({ content: 'ok', success: true }),
+ ok: true,
+ });
+
+ await client.executeMessageApi(
+ { deviceId: 'device-1', timeout: 5000, userId: 'user-1' },
+ { apiName: 'ping', payload: {}, platform: 'imessage' },
+ );
+
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://gateway.test.com/api/device/message-api',
+ expect.objectContaining({
+ body: expect.stringContaining('"deviceId":"device-1"'),
+ }),
+ );
+ });
+ });
+
describe('getDeviceSystemInfo', () => {
it('should return system info on success', async () => {
const systemInfo = {
diff --git a/packages/device-gateway-client/src/http.ts b/packages/device-gateway-client/src/http.ts
index c15175d920b..f2b37203921 100644
--- a/packages/device-gateway-client/src/http.ts
+++ b/packages/device-gateway-client/src/http.ts
@@ -14,6 +14,12 @@ export interface DeviceToolCallResult {
success: boolean;
}
+export interface DeviceMessageApiResult {
+ content: string;
+ error?: string;
+ success: boolean;
+}
+
export interface GatewayHttpClientOptions {
gatewayUrl: string;
serviceToken: string;
@@ -84,6 +90,35 @@ export class GatewayHttpClient {
};
}
+ async executeMessageApi(
+ params: { deviceId?: string; timeout?: number; userId: string },
+ api: { apiName: string; payload: Record<string, unknown>; platform: string },
+ ): Promise<DeviceMessageApiResult> {
+ const res = await this.post('/api/device/message-api', {
+ api,
+ deviceId: params.deviceId,
+ timeout: params.timeout,
+ userId: params.userId,
+ });
+
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ return {
+ content: `Device message API call failed (HTTP ${res.status})`,
+ error: text || `HTTP ${res.status}`,
+ success: false,
+ };
+ }
+
+ const data = await res.json();
+ return {
+ content:
+ typeof data.content === 'string' ? data.content : JSON.stringify(data.content ?? data),
+ error: data.error,
+ success: data.success ?? true,
+ };
+ }
+
async dispatchAgentRun(params: {
agentType: string;
cwd?: string;
diff --git a/packages/device-gateway-client/src/index.ts b/packages/device-gateway-client/src/index.ts
index ab43cddf075..418f4d5d17d 100644
--- a/packages/device-gateway-client/src/index.ts
+++ b/packages/device-gateway-client/src/index.ts
@@ -1,5 +1,10 @@
export type { GatewayClientLogger, GatewayClientOptions } from './client';
export { GatewayClient } from './client';
-export type { DeviceStatusResult, DeviceToolCallResult, GatewayHttpClientOptions } from './http';
+export type {
+ DeviceMessageApiResult,
+ DeviceStatusResult,
+ DeviceToolCallResult,
+ GatewayHttpClientOptions,
+} from './http';
export { GatewayHttpClient } from './http';
export * from './types';
diff --git a/packages/device-gateway-client/src/types.ts b/packages/device-gateway-client/src/types.ts
index 48df13f251e..ea56b69a988 100644
--- a/packages/device-gateway-client/src/types.ts
+++ b/packages/device-gateway-client/src/types.ts
@@ -44,6 +44,16 @@ export interface ToolCallResponseMessage {
type: 'tool_call_response';
}
+export interface MessageApiResponseMessage {
+ requestId: string;
+ result: {
+ content: string;
+ error?: string;
+ success: boolean;
+ };
+ type: 'message_api_response';
+}
+
// Server → Client
export interface HeartbeatAckMessage {
type: 'heartbeat_ack';
@@ -72,6 +82,16 @@ export interface ToolCallRequestMessage {
type: 'tool_call_request';
}
+export interface MessageApiRequestMessage {
+ api: {
+ apiName: string;
+ payload: Record<string, unknown>;
+ platform: string;
+ };
+ requestId: string;
+ type: 'message_api_request';
+}
+
// Server → Client
export interface SystemInfoRequestMessage {
requestId: string;
@@ -112,6 +132,7 @@ export type ClientMessage =
| AgentRunAckMessage
| AuthMessage
| HeartbeatMessage
+ | MessageApiResponseMessage
| SystemInfoResponseMessage
| ToolCallResponseMessage;
export type ServerMessage =
@@ -120,6 +141,7 @@ export type ServerMessage =
| AuthFailedMessage
| AuthSuccessMessage
| HeartbeatAckMessage
+ | MessageApiRequestMessage
| SystemInfoRequestMessage
| ToolCallRequestMessage;
@@ -140,6 +162,7 @@ export interface GatewayClientEvents {
disconnected: () => void;
error: (error: Error) => void;
heartbeat_ack: () => void;
+ message_api_request: (request: MessageApiRequestMessage) => void;
reconnecting: (delay: number) => void;
status_changed: (status: ConnectionStatus) => void;
system_info_request: (request: SystemInfoRequestMessage) => void;
diff --git a/src/server/services/bot/BotCallbackService.ts b/src/server/services/bot/BotCallbackService.ts
index 0d48ea42f70..8d974e5e014 100644
--- a/src/server/services/bot/BotCallbackService.ts
+++ b/src/server/services/bot/BotCallbackService.ts
@@ -227,6 +227,7 @@ export class BotCallbackService {
const client = entry.clientFactory.createClient(config, {
redisClient: getAgentRuntimeRedisClient() as any,
+ userId: row.userId ?? userId,
});
const messenger = client.getMessenger(platformThreadId);
diff --git a/src/server/services/bot/BotMessageRouter.ts b/src/server/services/bot/BotMessageRouter.ts
index a6caf659b0a..48c4053117a 100644
--- a/src/server/services/bot/BotMessageRouter.ts
+++ b/src/server/services/bot/BotMessageRouter.ts
@@ -322,6 +322,7 @@ export class BotMessageRouter {
const runtimeContext: BotPlatformRuntimeContext = {
appUrl: appEnv.APP_URL,
redisClient: getAgentRuntimeRedisClient() as any,
+ userId,
};
const client = entry.clientFactory.createClient(providerConfig, runtimeContext);
diff --git a/src/server/services/bot/platforms/const.ts b/src/server/services/bot/platforms/const.ts
index fdb70f27e87..2acba26231d 100644
--- a/src/server/services/bot/platforms/const.ts
+++ b/src/server/services/bot/platforms/const.ts
@@ -26,6 +26,7 @@ const USER_ID_TOOLTIP_BY_PLATFORM: Record<string, string> = {
// Feishu and Lark share `sharedSchema`, which always passes 'feishu' — the
// tooltip copy mentions both products so it reads naturally for either.
feishu: 'channel.userIdHint.feishu',
+ imessage: 'channel.userIdHint.imessage',
line: 'channel.userIdHint.line',
qq: 'channel.userIdHint.qq',
slack: 'channel.userIdHint.slack',
@@ -86,6 +87,7 @@ export type BotReplyLocale = Locales;
const PLATFORM_REPLY_LOCALES: Record<string, BotReplyLocale> = {
discord: 'en-US',
feishu: 'zh-CN',
+ imessage: 'en-US',
lark: 'en-US',
qq: 'zh-CN',
slack: 'en-US',
diff --git a/src/server/services/bot/platforms/imessage/client.test.ts b/src/server/services/bot/platforms/imessage/client.test.ts
new file mode 100644
index 00000000000..80eb25ab6fb
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/client.test.ts
@@ -0,0 +1,183 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ImessageClientFactory } from './client';
+
+const mockExecuteMessageApi = vi.hoisted(() => vi.fn());
+
+vi.mock('@/server/services/toolExecution/deviceProxy', () => ({
+ deviceProxy: {
+ executeMessageApi: mockExecuteMessageApi,
+ },
+}));
+
+vi.mock('@/server/services/gateway/runtimeStatus', () => ({
+ BOT_RUNTIME_STATUSES: {
+ connected: 'connected',
+ disconnected: 'disconnected',
+ failed: 'failed',
+ starting: 'starting',
+ },
+ getRuntimeStatusErrorMessage: (e: unknown) => (e instanceof Error ? e.message : 'unknown'),
+ updateBotRuntimeStatus: vi.fn().mockResolvedValue(undefined),
+}));
+
+const APPLICATION_ID = 'home-mac-mini';
+const credentials = {
+ desktopDeviceId: 'desktop-device-1',
+ webhookSecret: 'shared-secret',
+};
+
+const createClient = (settings: Record<string, unknown> = {}) =>
+ new ImessageClientFactory().createClient(
+ {
+ applicationId: APPLICATION_ID,
+ credentials,
+ platform: 'imessage',
+ settings,
+ },
+ { appUrl: 'https://lobehub.example.com', userId: 'user-1' },
+ );
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ mockExecuteMessageApi.mockReset();
+});
+
+describe('ImessageWebhookClient', () => {
+ it('extractChatId strips the iMessage thread prefix without changing the chat guid', () => {
+ const client = createClient();
+ expect(client.extractChatId('imessage:iMessage;-;abc:def')).toBe('iMessage;-;abc:def');
+ });
+
+ it('createAdapter wires the Desktop bridge transport into the SDK adapter', () => {
+ const client = createClient({ userId: '[email protected]' });
+ const adapter = client.createAdapter();
+ expect(adapter.imessage).toBeDefined();
+ expect((adapter.imessage as any).botUserId).toBe('[email protected]');
+ });
+
+ it('messenger.createMessage sends text through the Desktop bridge', async () => {
+ mockExecuteMessageApi.mockResolvedValueOnce({
+ content: JSON.stringify({ guid: 'sent-1', text: 'hello' }),
+ success: true,
+ });
+
+ const client = createClient();
+ const messenger = client.getMessenger('imessage:iMessage;-;chat-1');
+ await messenger.createMessage('hello');
+
+ expect(mockExecuteMessageApi).toHaveBeenCalledWith(
+ { deviceId: 'desktop-device-1', userId: 'user-1' },
+ {
+ apiName: 'sendText',
+ payload: {
+ applicationId: APPLICATION_ID,
+ chatGuid: 'iMessage;-;chat-1',
+ message: 'hello',
+ options: {},
+ },
+ platform: 'imessage',
+ },
+ 60_000,
+ );
+ });
+
+ it('extractFiles downloads BlueBubbles attachments through the Desktop bridge', async () => {
+ mockExecuteMessageApi.mockResolvedValueOnce({
+ content: JSON.stringify({
+ data: Buffer.from('image-bytes').toString('base64'),
+ mimeType: 'image/png',
+ }),
+ success: true,
+ });
+
+ const client = createClient();
+ const sources = await (client as any).extractFiles({
+ attachments: [
+ {
+ mimeType: 'image/png',
+ name: 'photo.png',
+ raw: {
+ guid: 'att-1',
+ mimeType: 'image/png',
+ transferName: 'photo.png',
+ },
+ type: 'image',
+ url: '',
+ },
+ ],
+ id: 'merged',
+ });
+
+ expect(sources).toHaveLength(1);
+ expect(sources[0].name).toBe('photo.png');
+ expect(sources[0].mimeType).toBe('image/png');
+ expect(sources[0].buffer.toString()).toBe('image-bytes');
+ expect(mockExecuteMessageApi).toHaveBeenCalledWith(
+ { deviceId: 'desktop-device-1', userId: 'user-1' },
+ {
+ apiName: 'downloadAttachment',
+ payload: {
+ applicationId: APPLICATION_ID,
+ guid: 'att-1',
+ },
+ platform: 'imessage',
+ },
+ 60_000,
+ );
+ });
+
+ it('formatMarkdown strips Markdown and formatReply appends usage only when enabled', () => {
+ const off = createClient();
+ const on = createClient({ showUsageStats: true });
+
+ expect(off.formatMarkdown!('**hi**')).toBe('hi');
+ expect(off.formatReply!('body', { totalCost: 0.01, totalTokens: 42 })).toBe('body');
+ expect(
+ on.formatReply!('body', { elapsedMs: 1234, totalCost: 0.01, totalTokens: 42 }).startsWith(
+ 'body\n\n',
+ ),
+ ).toBe(true);
+ });
+
+ it('start verifies the Desktop bridge can reach BlueBubbles', async () => {
+ mockExecuteMessageApi.mockResolvedValueOnce({
+ content: JSON.stringify({ ok: true }),
+ success: true,
+ });
+
+ const client = createClient();
+ await client.start();
+
+ expect(mockExecuteMessageApi).toHaveBeenCalledWith(
+ { deviceId: 'desktop-device-1', userId: 'user-1' },
+ {
+ apiName: 'ping',
+ payload: { applicationId: APPLICATION_ID },
+ platform: 'imessage',
+ },
+ 60_000,
+ );
+ });
+});
+
+describe('ImessageClientFactory.validateCredentials', () => {
+ it('reports missing fields without hitting the Desktop bridge', async () => {
+ const factory = new ImessageClientFactory();
+ const result = await factory.validateCredentials({});
+ expect(result.valid).toBe(false);
+ const fields = (result.errors ?? []).map((e) => e.field).sort();
+ expect(fields).toEqual(['applicationId', 'desktopDeviceId', 'webhookSecret']);
+ expect(mockExecuteMessageApi).not.toHaveBeenCalled();
+ });
+
+ it('returns valid=true when required Desktop bridge fields are present', async () => {
+ const factory = new ImessageClientFactory();
+ const result = await factory.validateCredentials(credentials, undefined, APPLICATION_ID);
+ expect(result.valid).toBe(true);
+ expect(mockExecuteMessageApi).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/services/bot/platforms/imessage/client.ts b/src/server/services/bot/platforms/imessage/client.ts
new file mode 100644
index 00000000000..b7e3f5e3d07
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/client.ts
@@ -0,0 +1,255 @@
+import {
+ type BlueBubblesAttachment,
+ type BlueBubblesOutboundAttachment,
+ createImessageAdapter,
+ resolveAttachmentGuid,
+ resolveAttachmentName,
+} from '@lobechat/chat-adapter-imessage';
+import type { Message } from 'chat';
+import debug from 'debug';
+
+import type { AttachmentSource } from '@/server/services/aiAgent/ingestAttachment';
+import {
+ BOT_RUNTIME_STATUSES,
+ getRuntimeStatusErrorMessage,
+ updateBotRuntimeStatus,
+} from '@/server/services/gateway/runtimeStatus';
+
+import { stripMarkdown } from '../stripMarkdown';
+import {
+ type BotMessageAttachment,
+ type BotPlatformRuntimeContext,
+ type BotProviderConfig,
+ ClientFactory,
+ messengerContentText,
+ type PlatformClient,
+ type PlatformMessenger,
+ type UsageStats,
+ type ValidationResult,
+} from '../types';
+import { formatUsageStats } from '../utils';
+import { ImessageDesktopBridgeApi } from './desktopBridge';
+
+const log = debug('bot-platform:imessage:bot');
+
+interface ImessageCredentials {
+ desktopDeviceId: string;
+ webhookSecret: string;
+}
+
+function resolveCredentials(credentials: Record<string, string>): ImessageCredentials {
+ const desktopDeviceId = credentials.desktopDeviceId?.trim();
+ const webhookSecret = credentials.webhookSecret?.trim();
+
+ if (!desktopDeviceId) throw new Error('Desktop Device ID is required');
+ if (!webhookSecret) throw new Error('Webhook Secret is required');
+
+ return { desktopDeviceId, webhookSecret };
+}
+
+function decodeThread(platformThreadId: string): string {
+ return platformThreadId.startsWith('imessage:')
+ ? platformThreadId.slice('imessage:'.length)
+ : platformThreadId;
+}
+
+function toBlueBubblesAttachment(attachment: BotMessageAttachment): BlueBubblesOutboundAttachment {
+ return {
+ data: attachment.data,
+ fetchUrl: attachment.fetchUrl,
+ mimeType: attachment.mimeType,
+ name: attachment.name,
+ };
+}
+
+class ImessageWebhookClient implements PlatformClient {
+ readonly id = 'imessage';
+ readonly applicationId: string;
+
+ private bridge: ImessageDesktopBridgeApi;
+ private config: BotProviderConfig;
+ private credentials: ImessageCredentials;
+
+ constructor(config: BotProviderConfig, context: BotPlatformRuntimeContext) {
+ this.config = config;
+ this.applicationId = config.applicationId;
+ this.credentials = resolveCredentials(config.credentials);
+ if (!context.userId?.trim()) {
+ throw new Error('User ID is required for iMessage Desktop bridge');
+ }
+ this.bridge = new ImessageDesktopBridgeApi({
+ applicationId: this.applicationId,
+ deviceId: this.credentials.desktopDeviceId,
+ userId: context.userId,
+ });
+ }
+
+ async start(): Promise<void> {
+ log(
+ 'Starting iMessage Desktop bridge appId=%s deviceId=%s',
+ this.applicationId,
+ this.credentials.desktopDeviceId,
+ );
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.starting,
+ });
+
+ try {
+ await this.bridge.ping();
+
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.connected,
+ });
+
+ log('iMessage Desktop bridge appId=%s ready', this.applicationId);
+ } catch (error) {
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ errorMessage: getRuntimeStatusErrorMessage(error),
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.failed,
+ });
+ throw error;
+ }
+ }
+
+ async stop(): Promise<void> {
+ log('Stopping iMessage appId=%s', this.applicationId);
+ await updateBotRuntimeStatus({
+ applicationId: this.applicationId,
+ platform: this.id,
+ status: BOT_RUNTIME_STATUSES.disconnected,
+ });
+ }
+
+ createAdapter(): Record<string, any> {
+ return {
+ imessage: createImessageAdapter({
+ botUserId: this.config.settings?.userId as string | undefined,
+ transport: {
+ getChat: this.bridge.getChat,
+ getChatMessages: this.bridge.getChatMessages,
+ sendText: this.bridge.sendText,
+ startTyping: this.bridge.startTyping,
+ },
+ webhookSecret: this.credentials.webhookSecret,
+ }),
+ };
+ }
+
+ getMessenger(platformThreadId: string): PlatformMessenger {
+ const chatGuid = decodeThread(platformThreadId);
+ return {
+ createMessage: async (content) => {
+ const text = messengerContentText(content);
+ const attachments = typeof content === 'string' ? undefined : content.attachments;
+
+ if (text.trim()) {
+ await this.bridge.sendText(chatGuid, text);
+ }
+
+ for (const attachment of attachments ?? []) {
+ await this.bridge.sendAttachment(chatGuid, toBlueBubblesAttachment(attachment));
+ }
+ },
+ editMessage: async (_messageId, content) => {
+ await this.getMessenger(platformThreadId).createMessage(content);
+ },
+ removeReaction: () => Promise.resolve(),
+ triggerTyping: async () => {
+ try {
+ await this.bridge.startTyping(chatGuid);
+ } catch (error) {
+ log('triggerTyping failed: %O', error);
+ }
+ },
+ };
+ }
+
+ async extractFiles(message: Message): Promise<AttachmentSource[] | undefined> {
+ const attachments = ((message as any).attachments ?? []) as Array<{
+ raw?: BlueBubblesAttachment;
+ }>;
+ const candidates = attachments
+ .map((attachment) => ({
+ guid: resolveAttachmentGuid(attachment.raw),
+ raw: attachment.raw,
+ }))
+ .filter((entry): entry is { guid: string; raw: BlueBubblesAttachment } =>
+ Boolean(entry.guid && entry.raw),
+ );
+
+ if (candidates.length === 0) return undefined;
+
+ const results = await Promise.all(
+ candidates.map(async ({ guid, raw }): Promise<AttachmentSource | undefined> => {
+ try {
+ const downloaded = await this.bridge.downloadAttachment(guid);
+ return {
+ buffer: downloaded.buffer,
+ mimeType: downloaded.mimeType ?? raw.mimeType ?? 'application/octet-stream',
+ name: resolveAttachmentName(raw),
+ size: downloaded.buffer.length,
+ };
+ } catch (error) {
+ log('extractFiles: downloadAttachment failed for guid=%s: %O', guid, error);
+ return undefined;
+ }
+ }),
+ );
+
+ const sources = results.filter((source): source is AttachmentSource => Boolean(source));
+ return sources.length > 0 ? sources : undefined;
+ }
+
+ extractChatId(platformThreadId: string): string {
+ return decodeThread(platformThreadId);
+ }
+
+ formatMarkdown(markdown: string): string {
+ return stripMarkdown(markdown);
+ }
+
+ formatReply(body: string, stats?: UsageStats): string {
+ if (!stats || !this.config.settings?.showUsageStats) return body;
+ return `${body}\n\n${formatUsageStats(stats)}`;
+ }
+
+ parseMessageId(compositeId: string): string {
+ return compositeId;
+ }
+}
+
+export class ImessageClientFactory extends ClientFactory {
+ createClient(config: BotProviderConfig, context: BotPlatformRuntimeContext): PlatformClient {
+ return new ImessageWebhookClient(config, context);
+ }
+
+ async validateCredentials(
+ credentials: Record<string, string>,
+ _settings?: Record<string, unknown>,
+ applicationId?: string,
+ ): Promise<ValidationResult> {
+ const errors: Array<{ field: string; message: string }> = [];
+ if (!credentials.desktopDeviceId?.trim()) {
+ errors.push({ field: 'desktopDeviceId', message: 'Desktop Device ID is required' });
+ }
+ if (!credentials.webhookSecret?.trim()) {
+ errors.push({ field: 'webhookSecret', message: 'Webhook Secret is required' });
+ }
+ if (!applicationId?.trim()) {
+ errors.push({ field: 'applicationId', message: 'Application ID is required' });
+ }
+ if (errors.length > 0) return { errors, valid: false };
+
+ return { valid: true };
+ }
+}
+
+export const imessageTestInternals = {
+ decodeThread,
+};
diff --git a/src/server/services/bot/platforms/imessage/definition.ts b/src/server/services/bot/platforms/imessage/definition.ts
new file mode 100644
index 00000000000..ccbc278a901
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/definition.ts
@@ -0,0 +1,19 @@
+import type { PlatformDefinition } from '../types';
+import { ImessageClientFactory } from './client';
+import { schema } from './schema';
+
+export const imessage: PlatformDefinition = {
+ id: 'imessage',
+ name: 'iMessage',
+ connectionMode: 'webhook',
+ description: 'Connect iMessage through the local LobeHub Desktop BlueBubbles bridge.',
+ documentation: {
+ portalUrl: 'https://bluebubbles.app/',
+ setupGuideUrl: 'https://lobehub.com/docs/usage/channels/imessage',
+ },
+ schema,
+ showWebhookUrl: false,
+ supportsMarkdown: false,
+ supportsMessageEdit: false,
+ clientFactory: new ImessageClientFactory(),
+};
diff --git a/src/server/services/bot/platforms/imessage/desktopBridge.ts b/src/server/services/bot/platforms/imessage/desktopBridge.ts
new file mode 100644
index 00000000000..7d3c692ca3a
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/desktopBridge.ts
@@ -0,0 +1,118 @@
+import type {
+ BlueBubblesChat,
+ BlueBubblesDownloadedAttachment,
+ BlueBubblesMessage,
+ BlueBubblesOutboundAttachment,
+ BlueBubblesQueryResult,
+ BlueBubblesSendOptions,
+} from '@lobechat/chat-adapter-imessage';
+
+import { deviceProxy } from '@/server/services/toolExecution/deviceProxy';
+
+const IMESSAGE_MESSAGE_API_TIMEOUT_MS = 60_000;
+
+interface ImessageDesktopBridgeOptions {
+ applicationId: string;
+ deviceId: string;
+ userId: string;
+}
+
+interface DownloadAttachmentResult {
+ data: string;
+ mimeType?: string;
+}
+
+export class ImessageDesktopBridgeApi {
+ private readonly applicationId: string;
+ private readonly deviceId: string;
+ private readonly userId: string;
+
+ constructor(options: ImessageDesktopBridgeOptions) {
+ this.applicationId = options.applicationId;
+ this.deviceId = options.deviceId;
+ this.userId = options.userId;
+ }
+
+ ping = async (): Promise<void> => {
+ await this.call<Record<string, unknown>>('ping', {});
+ };
+
+ getChat = async (
+ guid: string,
+ withParts: string[] = ['participants'],
+ ): Promise<BlueBubblesChat> => this.call<BlueBubblesChat>('getChat', { guid, withParts });
+
+ getChatMessages = async (
+ chatGuid: string,
+ options: {
+ after?: number | string;
+ before?: number | string;
+ limit?: number;
+ offset?: number;
+ sort?: 'ASC' | 'DESC';
+ withParts?: string[];
+ } = {},
+ ): Promise<BlueBubblesQueryResult<BlueBubblesMessage>> =>
+ this.call<BlueBubblesQueryResult<BlueBubblesMessage>>('getChatMessages', {
+ chatGuid,
+ options,
+ });
+
+ queryMessages = async (
+ body: Record<string, unknown>,
+ ): Promise<BlueBubblesQueryResult<BlueBubblesMessage>> =>
+ this.call<BlueBubblesQueryResult<BlueBubblesMessage>>('queryMessages', { body });
+
+ queryChats = async (
+ body: Record<string, unknown>,
+ ): Promise<BlueBubblesQueryResult<BlueBubblesChat>> =>
+ this.call<BlueBubblesQueryResult<BlueBubblesChat>>('queryChats', { body });
+
+ sendText = async (
+ chatGuid: string,
+ message: string,
+ options: BlueBubblesSendOptions = {},
+ ): Promise<BlueBubblesMessage> =>
+ this.call<BlueBubblesMessage>('sendText', { chatGuid, message, options });
+
+ sendAttachment = async (
+ chatGuid: string,
+ attachment: BlueBubblesOutboundAttachment,
+ options: BlueBubblesSendOptions = {},
+ ): Promise<BlueBubblesMessage> =>
+ this.call<BlueBubblesMessage>('sendAttachment', { attachment, chatGuid, options });
+
+ startTyping = async (chatGuid: string): Promise<void> => {
+ await this.call<Record<string, unknown>>('startTyping', { chatGuid });
+ };
+
+ downloadAttachment = async (guid: string): Promise<BlueBubblesDownloadedAttachment> => {
+ const result = await this.call<DownloadAttachmentResult>('downloadAttachment', { guid });
+ return {
+ buffer: Buffer.from(result.data, 'base64'),
+ mimeType: result.mimeType,
+ };
+ };
+
+ private async call<T>(apiName: string, payload: Record<string, unknown>): Promise<T> {
+ const result = await deviceProxy.executeMessageApi(
+ { deviceId: this.deviceId, userId: this.userId },
+ {
+ apiName,
+ payload: {
+ applicationId: this.applicationId,
+ ...payload,
+ },
+ platform: 'imessage',
+ },
+ IMESSAGE_MESSAGE_API_TIMEOUT_MS,
+ );
+
+ if (!result.success) {
+ throw new Error(result.error || result.content || 'iMessage Desktop bridge call failed');
+ }
+
+ if (!result.content) return {} as T;
+ return JSON.parse(result.content) as T;
+ }
+}
diff --git a/src/server/services/bot/platforms/imessage/protocol-spec.md b/src/server/services/bot/platforms/imessage/protocol-spec.md
new file mode 100644
index 00000000000..6d0c95ade9c
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/protocol-spec.md
@@ -0,0 +1,90 @@
+# iMessage via BlueBubbles Desktop Bridge – Bot Integration Notes
+
+Authoritative references:
+
+- BlueBubbles REST API and webhooks: <https://docs.bluebubbles.app/server/developer-guides/rest-api-and-webhooks>
+- BlueBubbles Server source: <https://github.com/BlueBubblesApp/bluebubbles-server>
+
+## Architecture
+
+LobeHub does not speak to Apple's iMessage service directly. Operators host
+BlueBubbles Server on a Mac signed into Messages. The LobeHub Desktop app runs
+a loopback webhook bridge on that Mac and keeps the BlueBubbles REST URL and
+password local.
+
+```text
+iMessage -> macOS Messages -> BlueBubbles -> 127.0.0.1 LobeHub Desktop bridge
+Desktop bridge -> /api/agent/webhooks/imessage/:applicationId -> LobeHub bot router
+LobeHub bot reply -> Device Gateway tool call -> Desktop bridge -> BlueBubbles REST API
+```
+
+## Credentials
+
+Cloud bot provider:
+
+| Field | Source | Notes |
+| ----------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------- |
+| `applicationId` | Operator-chosen LobeHub identifier | Shared by the cloud provider and Desktop bridge. |
+| `desktopDeviceId` | LobeHub Desktop Gateway settings | Identifies the Desktop device that can reach BlueBubbles locally. |
+| `webhookSecret` | Operator-generated | Desktop forwards BlueBubbles events to LobeHub with `?secret=<value>` because BlueBubbles does not sign. |
+
+Desktop-only bridge config:
+
+| Field | Source | Notes |
+| ---------------------- | --------------------------- | -------------------------------------------------------------- |
+| `applicationId` | Same as cloud provider | Selects which cloud bot receives forwarded events. |
+| `blueBubblesServerUrl` | Local BlueBubbles base URL | Usually `http://127.0.0.1:<port>`. No public URL is required. |
+| `blueBubblesPassword` | BlueBubbles Server password | Stored only in Desktop local settings. |
+| `webhookSecret` | Same as cloud provider | Used by the Desktop loopback URL and the cloud forwarding URL. |
+
+## Webhook lifecycle
+
+1. Desktop starts a loopback HTTP server bound to `127.0.0.1`.
+2. Desktop registers a BlueBubbles `new-message` webhook pointing to
+ `http://127.0.0.1:<port>/webhooks/bluebubbles/:applicationId?secret=...`.
+3. BlueBubbles posts `{ "type": "new-message", "data": <message> }` locally.
+4. Desktop enriches the payload with
+ `GET /api/v1/message/:guid?with=chats,attachments` when possible.
+5. Desktop forwards the event to
+ `/api/agent/webhooks/imessage/:applicationId?secret=...`.
+6. The Chat SDK adapter ignores `isFromMe` messages to avoid loops and
+ dispatches inbound messages as `imessage:<chatGuid>`.
+
+## Outbound lifecycle
+
+The server never calls BlueBubbles directly. It uses the existing Device Gateway
+tool-call channel to ask the configured Desktop device to execute iMessage
+bridge actions:
+
+- `imessage.ping`
+- `imessage.sendText`
+- `imessage.sendAttachment`
+- `imessage.startTyping`
+- `imessage.downloadAttachment`
+- `imessage.getChat`
+- `imessage.getChatMessages`
+- `imessage.queryMessages`
+- `imessage.queryChats`
+
+## Capabilities
+
+- Text reply: Desktop calls `POST /api/v1/message/text`
+- Attachment reply: Desktop calls `POST /api/v1/message/attachment`
+- Attachment download: Desktop calls `GET /api/v1/attachment/:guid/download`
+- Read recent messages: Desktop calls `GET /api/v1/chat/:guid/message`
+- Search messages: Desktop calls `POST /api/v1/message/query`
+- Channel metadata: Desktop calls `GET /api/v1/chat/:guid`
+
+Typing indicators call `POST /api/v1/chat/:guid/typing`, which requires
+BlueBubbles Private API. Failures are logged and ignored.
+
+## Limitations
+
+- LobeHub Desktop must stay online for inbound forwarding and outbound replies.
+- iMessage has no general bot mention primitive. Group wake behavior relies on
+ watch keywords and group policy, not native `@bot` mentions.
+- Message editing, deleting, reactions, pins, polls, and threads are not
+ exposed as LobeHub bot capabilities for iMessage.
+- BlueBubbles advanced send features may require the Private API / SIP changes
+ on the Mac. LobeHub's basic text and attachment path uses AppleScript by
+ default.
diff --git a/src/server/services/bot/platforms/imessage/schema.ts b/src/server/services/bot/platforms/imessage/schema.ts
new file mode 100644
index 00000000000..b9365401e82
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/schema.ts
@@ -0,0 +1,83 @@
+import { DEFAULT_BOT_DEBOUNCE_MS, MAX_BOT_DEBOUNCE_MS } from '@lobechat/const';
+
+import { displayToolCallsField, makeUserIdField, watchKeywordsField } from '../const';
+import type { FieldSchema } from '../types';
+
+export const schema: FieldSchema[] = [
+ {
+ key: 'credentials',
+ label: 'channel.credentials',
+ properties: [
+ {
+ key: 'desktopDeviceId',
+ description: 'channel.imessage.desktopDeviceIdHint',
+ label: 'channel.imessage.desktopDeviceId',
+ placeholder: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
+ required: true,
+ type: 'string',
+ },
+ {
+ key: 'webhookSecret',
+ description: 'channel.imessage.webhookSecretHint',
+ label: 'channel.imessage.webhookSecret',
+ required: true,
+ type: 'password',
+ },
+ ],
+ type: 'object',
+ },
+ {
+ key: 'applicationId',
+ description: 'channel.imessage.applicationIdHint',
+ label: 'channel.applicationId',
+ placeholder: 'channel.imessage.applicationIdPlaceholder',
+ required: true,
+ type: 'string',
+ },
+ {
+ key: 'settings',
+ label: 'channel.settings',
+ properties: [
+ makeUserIdField('imessage'),
+ {
+ key: 'charLimit',
+ default: 5000,
+ description: 'channel.charLimitHint',
+ label: 'channel.charLimit',
+ maximum: 10_000,
+ minimum: 100,
+ type: 'number',
+ },
+ {
+ key: 'concurrency',
+ default: 'queue',
+ description: 'channel.concurrencyHint',
+ enum: ['queue', 'debounce'],
+ enumDescriptions: ['channel.concurrencyQueueHint', 'channel.concurrencyDebounceHint'],
+ enumLabels: ['channel.concurrencyQueue', 'channel.concurrencyDebounce'],
+ label: 'channel.concurrency',
+ type: 'string',
+ },
+ {
+ key: 'debounceMs',
+ default: DEFAULT_BOT_DEBOUNCE_MS,
+ description: 'channel.debounceMsHint',
+ label: 'channel.debounceMs',
+ maximum: MAX_BOT_DEBOUNCE_MS,
+ minimum: 100,
+ type: 'number',
+ visibleWhen: { field: 'concurrency', value: 'debounce' },
+ },
+ {
+ key: 'showUsageStats',
+ default: false,
+ description: 'channel.showUsageStatsHint',
+ label: 'channel.showUsageStats',
+ type: 'boolean',
+ },
+ displayToolCallsField,
+ watchKeywordsField,
+ ],
+ type: 'object',
+ },
+];
diff --git a/src/server/services/bot/platforms/imessage/service.test.ts b/src/server/services/bot/platforms/imessage/service.test.ts
new file mode 100644
index 00000000000..23e6f4436fa
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/service.test.ts
@@ -0,0 +1,143 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ImessageMessageService } from './service';
+
+const makeApi = () => ({
+ getChatMessages: vi.fn().mockResolvedValue({
+ data: [
+ {
+ attachments: [{ guid: 'att-1', mimeType: 'image/png', transferName: 'photo.png' }],
+ dateCreated: 1_700_000_000_000,
+ guid: 'msg-1',
+ handle: { address: '+15551234567' },
+ text: 'hello',
+ },
+ ],
+ }),
+ queryMessages: vi.fn().mockResolvedValue({
+ data: [
+ {
+ dateCreated: 1_700_000_000_000,
+ guid: 'msg-2',
+ handle: { address: '+15551234567' },
+ text: 'search hit',
+ },
+ {
+ dateCreated: 1_700_000_001_000,
+ guid: 'msg-3',
+ handle: { address: '+15557654321' },
+ text: 'other hit',
+ },
+ ],
+ metadata: { total: 2 },
+ }),
+ sendAttachment: vi.fn().mockResolvedValue({ guid: 'att-sent' }),
+ sendText: vi.fn().mockResolvedValue({ guid: 'text-sent' }),
+});
+
+describe('ImessageMessageService', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('sends text and attachments to the BlueBubbles chat guid', async () => {
+ const api = makeApi();
+ const service = new ImessageMessageService(api as any);
+
+ const result = await service.sendMessage({
+ attachments: [
+ {
+ data: Buffer.from('image-bytes').toString('base64'),
+ mimeType: 'image/png',
+ name: 'photo.png',
+ type: 'image',
+ },
+ ],
+ channelId: 'iMessage;-;chat-1',
+ content: 'hello',
+ platform: 'imessage',
+ });
+
+ expect(api.sendText).toHaveBeenCalledWith('iMessage;-;chat-1', 'hello');
+ expect(api.sendAttachment).toHaveBeenCalledWith('iMessage;-;chat-1', {
+ data: Buffer.from('image-bytes').toString('base64'),
+ fetchUrl: undefined,
+ mimeType: 'image/png',
+ name: 'photo.png',
+ });
+ expect(result).toEqual({
+ channelId: 'iMessage;-;chat-1',
+ messageId: 'att-sent',
+ platform: 'imessage',
+ });
+ });
+
+ it('reads recent messages and maps BlueBubbles attachments', async () => {
+ const api = makeApi();
+ const service = new ImessageMessageService(api as any);
+
+ const result = await service.readMessages({
+ channelId: 'iMessage;-;chat-1',
+ limit: 10,
+ platform: 'imessage',
+ });
+
+ expect(api.getChatMessages).toHaveBeenCalledWith('iMessage;-;chat-1', {
+ after: undefined,
+ before: undefined,
+ limit: 10,
+ sort: 'DESC',
+ withParts: ['attachments'],
+ });
+ expect(result.messages?.[0]).toMatchObject({
+ attachments: [{ name: 'photo.png', url: 'bluebubbles:attachment:att-1' }],
+ author: { id: '+15551234567', name: '+15551234567' },
+ content: 'hello',
+ id: 'msg-1',
+ });
+ });
+
+ it('searches messages and applies optional author filtering', async () => {
+ const api = makeApi();
+ const service = new ImessageMessageService(api as any);
+
+ const result = await service.searchMessages({
+ authorId: '+15551234567',
+ channelId: 'iMessage;-;chat-1',
+ limit: 5,
+ platform: 'imessage',
+ query: 'hit',
+ });
+
+ expect(api.queryMessages).toHaveBeenCalledWith({
+ chatGuid: 'iMessage;-;chat-1',
+ limit: 5,
+ sort: 'DESC',
+ where: [
+ {
+ args: { query: '%hit%' },
+ statement: 'message.text LIKE :query COLLATE NOCASE',
+ },
+ ],
+ with: ['attachments'],
+ });
+ expect(result.messages).toHaveLength(1);
+ expect(result.messages?.[0].id).toBe('msg-2');
+ expect(result.totalFound).toBe(1);
+ });
+
+ it('keeps the query metadata total when no author filter is applied', async () => {
+ const api = makeApi();
+ const service = new ImessageMessageService(api as any);
+
+ const result = await service.searchMessages({
+ channelId: 'iMessage;-;chat-1',
+ limit: 5,
+ platform: 'imessage',
+ query: 'hit',
+ });
+
+ expect(result.messages).toHaveLength(2);
+ expect(result.totalFound).toBe(2);
+ });
+});
diff --git a/src/server/services/bot/platforms/imessage/service.ts b/src/server/services/bot/platforms/imessage/service.ts
new file mode 100644
index 00000000000..2b69a4d9eab
--- /dev/null
+++ b/src/server/services/bot/platforms/imessage/service.ts
@@ -0,0 +1,255 @@
+import type {
+ CreatePollParams,
+ CreatePollState,
+ CreateThreadParams,
+ CreateThreadState,
+ DeleteMessageParams,
+ DeleteMessageState,
+ EditMessageParams,
+ EditMessageState,
+ GetChannelInfoParams,
+ GetChannelInfoState,
+ GetMemberInfoParams,
+ GetMemberInfoState,
+ GetReactionsParams,
+ GetReactionsState,
+ ListChannelsParams,
+ ListChannelsState,
+ ListPinsParams,
+ ListPinsState,
+ ListThreadsParams,
+ ListThreadsState,
+ MessageItem,
+ PinMessageParams,
+ PinMessageState,
+ ReactToMessageParams,
+ ReactToMessageState,
+ ReadMessagesParams,
+ ReadMessagesState,
+ ReplyToThreadParams,
+ ReplyToThreadState,
+ SearchMessagesParams,
+ SearchMessagesState,
+ SendMessageParams,
+ SendMessageState,
+ UnpinMessageParams,
+ UnpinMessageState,
+} from '@lobechat/builtin-tool-message/executionRuntime';
+import type {
+ BlueBubblesChat,
+ BlueBubblesMessage,
+ BlueBubblesOutboundAttachment,
+ BlueBubblesQueryResult,
+} from '@lobechat/chat-adapter-imessage';
+import { resolveAttachmentName } from '@lobechat/chat-adapter-imessage';
+
+import type { MessageRuntimeService } from '@/server/services/toolExecution/serverRuntimes/message/adapters/types';
+import { PlatformUnsupportedError } from '@/server/services/toolExecution/serverRuntimes/message/PlatformUnsupportedError';
+
+function authorFromMessage(message: BlueBubblesMessage): MessageItem['author'] {
+ if (message.isFromMe) return { id: 'me', name: 'me' };
+
+ const handle = message.handle;
+ const id =
+ handle?.address ||
+ handle?.uncanonicalizedId ||
+ String(message.handleId ?? message.otherHandle ?? 'unknown');
+ return { id, name: id };
+}
+
+function messageToItem(message: BlueBubblesMessage): MessageItem {
+ return {
+ attachments: (message.attachments ?? []).map((attachment) => ({
+ name: resolveAttachmentName(attachment),
+ url: `bluebubbles:attachment:${attachment.guid}`,
+ })),
+ author: authorFromMessage(message),
+ content: message.text ?? message.subject ?? '',
+ id: message.guid,
+ timestamp: new Date(message.dateCreated ?? Date.now()).toISOString(),
+ };
+}
+
+function chatName(chat: BlueBubblesChat): string {
+ return chat.displayName || chat.chatIdentifier || chat.guid;
+}
+
+interface ImessageMessageApi {
+ getChat: (guid: string, withParts?: string[]) => Promise<BlueBubblesChat>;
+ getChatMessages: (
+ chatGuid: string,
+ options?: {
+ after?: number | string;
+ before?: number | string;
+ limit?: number;
+ offset?: number;
+ sort?: 'ASC' | 'DESC';
+ withParts?: string[];
+ },
+ ) => Promise<BlueBubblesQueryResult<BlueBubblesMessage>>;
+ queryChats: (body: Record<string, unknown>) => Promise<BlueBubblesQueryResult<BlueBubblesChat>>;
+ queryMessages: (
+ body: Record<string, unknown>,
+ ) => Promise<BlueBubblesQueryResult<BlueBubblesMessage>>;
+ sendAttachment: (
+ chatGuid: string,
+ attachment: BlueBubblesOutboundAttachment,
+ ) => Promise<BlueBubblesMessage>;
+ sendText: (chatGuid: string, message: string) => Promise<BlueBubblesMessage>;
+}
+
+/**
+ * iMessage message-tool adapter backed by BlueBubbles.
+ *
+ * The `channelId` accepted by Message tools is the BlueBubbles `chatGuid`
+ * (also exposed as `imessage:<chatGuid>` in inbound bot thread IDs).
+ */
+export class ImessageMessageService implements MessageRuntimeService {
+ constructor(private api: ImessageMessageApi) {}
+
+ sendMessage = async (params: SendMessageParams): Promise<SendMessageState> => {
+ let lastMessage: BlueBubblesMessage | undefined;
+
+ if (params.content?.trim()) {
+ lastMessage = await this.api.sendText(params.channelId, params.content);
+ }
+
+ for (const attachment of params.attachments ?? []) {
+ lastMessage = await this.api.sendAttachment(params.channelId, {
+ data: attachment.data,
+ fetchUrl: attachment.fetchUrl,
+ mimeType: attachment.mimeType,
+ name: attachment.name,
+ });
+ }
+
+ return {
+ channelId: params.channelId,
+ messageId: lastMessage?.guid ?? lastMessage?.tempGuid,
+ platform: 'imessage',
+ };
+ };
+
+ readMessages = async (params: ReadMessagesParams): Promise<ReadMessagesState> => {
+ const result = await this.api.getChatMessages(params.channelId, {
+ after: params.after,
+ before: params.before,
+ limit: params.limit ?? 25,
+ sort: 'DESC',
+ withParts: ['attachments'],
+ });
+
+ return {
+ channelId: params.channelId,
+ messages: result.data.map(messageToItem).reverse(),
+ platform: 'imessage',
+ totalFetched: result.data.length,
+ };
+ };
+
+ editMessage = async (_params: EditMessageParams): Promise<EditMessageState> => {
+ throw new PlatformUnsupportedError('iMessage', 'editMessage');
+ };
+
+ deleteMessage = async (_params: DeleteMessageParams): Promise<DeleteMessageState> => {
+ throw new PlatformUnsupportedError('iMessage', 'deleteMessage');
+ };
+
+ searchMessages = async (params: SearchMessagesParams): Promise<SearchMessagesState> => {
+ const result = await this.api.queryMessages({
+ chatGuid: params.channelId,
+ limit: params.limit ?? 25,
+ sort: 'DESC',
+ where: [
+ {
+ args: { query: `%${params.query}%` },
+ statement: 'message.text LIKE :query COLLATE NOCASE',
+ },
+ ],
+ with: ['attachments'],
+ });
+
+ const authorId = params.authorId?.trim();
+ const filtered = authorId
+ ? result.data.filter((message) => authorFromMessage(message).id === authorId)
+ : result.data;
+
+ return {
+ messages: filtered.map(messageToItem),
+ query: params.query,
+ totalFound: authorId ? filtered.length : (result.metadata?.total ?? filtered.length),
+ };
+ };
+
+ reactToMessage = async (_params: ReactToMessageParams): Promise<ReactToMessageState> => {
+ throw new PlatformUnsupportedError('iMessage', 'reactToMessage');
+ };
+
+ getReactions = async (_params: GetReactionsParams): Promise<GetReactionsState> => {
+ throw new PlatformUnsupportedError('iMessage', 'getReactions');
+ };
+
+ pinMessage = async (_params: PinMessageParams): Promise<PinMessageState> => {
+ throw new PlatformUnsupportedError('iMessage', 'pinMessage');
+ };
+
+ unpinMessage = async (_params: UnpinMessageParams): Promise<UnpinMessageState> => {
+ throw new PlatformUnsupportedError('iMessage', 'unpinMessage');
+ };
+
+ listPins = async (_params: ListPinsParams): Promise<ListPinsState> => {
+ throw new PlatformUnsupportedError('iMessage', 'listPins');
+ };
+
+ getChannelInfo = async (params: GetChannelInfoParams): Promise<GetChannelInfoState> => {
+ const chat = await this.api.getChat(params.channelId, ['participants']);
+ return {
+ id: chat.guid,
+ memberCount: chat.participants?.length,
+ name: chatName(chat),
+ type: chat.style === 43 ? 'group' : 'direct',
+ };
+ };
+
+ listChannels = async (_params: ListChannelsParams): Promise<ListChannelsState> => {
+ const result = await this.api.queryChats({
+ limit: 100,
+ sort: 'lastmessage',
+ with: ['lastmessage'],
+ });
+
+ return {
+ channels: result.data.map((chat) => ({
+ id: chat.guid,
+ name: chatName(chat),
+ type: chat.style === 43 ? 'group' : 'direct',
+ })),
+ };
+ };
+
+ getMemberInfo = async (_params: GetMemberInfoParams): Promise<GetMemberInfoState> => {
+ throw new PlatformUnsupportedError('iMessage', 'getMemberInfo');
+ };
+
+ createThread = async (_params: CreateThreadParams): Promise<CreateThreadState> => {
+ throw new PlatformUnsupportedError('iMessage', 'createThread');
+ };
+
+ listThreads = async (_params: ListThreadsParams): Promise<ListThreadsState> => {
+ throw new PlatformUnsupportedError('iMessage', 'listThreads');
+ };
+
+ replyToThread = async (params: ReplyToThreadParams): Promise<ReplyToThreadState> => {
+ const result = await this.sendMessage({
+ attachments: params.attachments,
+ channelId: params.threadId,
+ content: params.content,
+ platform: 'imessage',
+ });
+ return { messageId: result.messageId, threadId: params.threadId };
+ };
+
+ createPoll = async (_params: CreatePollParams): Promise<CreatePollState> => {
+ throw new PlatformUnsupportedError('iMessage', 'createPoll');
+ };
+}
diff --git a/src/server/services/bot/platforms/types.ts b/src/server/services/bot/platforms/types.ts
index 2e232ee0083..fe205a06b23 100644
--- a/src/server/services/bot/platforms/types.ts
+++ b/src/server/services/bot/platforms/types.ts
@@ -355,6 +355,7 @@ export interface BotPlatformRuntimeContext {
appUrl?: string;
redisClient?: BotPlatformRedisClient;
registerByToken?: (token: string) => void;
+ userId?: string;
}
// --------------- Validation ---------------
diff --git a/src/server/services/gateway/GatewayManager.test.ts b/src/server/services/gateway/GatewayManager.test.ts
index 1ab0afc87dd..51ac45d9d2e 100644
--- a/src/server/services/gateway/GatewayManager.test.ts
+++ b/src/server/services/gateway/GatewayManager.test.ts
@@ -227,6 +227,29 @@ describe('GatewayManager', () => {
expect(mockBot.start).toHaveBeenCalled();
});
+ it('should scope lookup by the requested user but build runtime context from the provider row', async () => {
+ const mockBot = createMockBot();
+ const factory = vi.fn().mockReturnValue(mockBot);
+ mockAgentBotProviderModel.findEnabledByApplicationId.mockResolvedValue({
+ applicationId: 'app-123',
+ credentials: { token: 'tok123' },
+ settings: {},
+ userId: 'provider-user',
+ });
+
+ const manager = new GatewayManager({ definitions: [createFakeDefinition('slack', factory)] });
+
+ await manager.startClient('slack', 'app-123', 'requested-user');
+
+ expect(vi.mocked(AgentBotProviderModel)).toHaveBeenCalledWith(
+ mockDb,
+ 'requested-user',
+ mockGateKeeper,
+ );
+ expect(factory.mock.calls[0][1]).toMatchObject({ userId: 'provider-user' });
+ expect(mockBot.start).toHaveBeenCalled();
+ });
+
it('should stop existing bot before starting a new one for the same key', async () => {
const mockBot1 = createMockBot();
const mockBot2 = createMockBot();
diff --git a/src/server/services/gateway/GatewayManager.ts b/src/server/services/gateway/GatewayManager.ts
index 4bb7c19c5a8..202d34a69f7 100644
--- a/src/server/services/gateway/GatewayManager.ts
+++ b/src/server/services/gateway/GatewayManager.ts
@@ -1,6 +1,7 @@
import debug from 'debug';
import { getServerDB } from '@/database/core/db-adaptor';
+import type { DecryptedBotProvider } from '@/database/models/agentBotProvider';
import { AgentBotProviderModel } from '@/database/models/agentBotProvider';
import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
@@ -186,14 +187,7 @@ export class GatewayManager {
// Factory
// ------------------------------------------------------------------
- private createClient(
- platform: string,
- provider: {
- applicationId: string;
- credentials: Record<string, string>;
- settings?: Record<string, unknown> | null;
- },
- ): PlatformClient | null {
+ private createClient(platform: string, provider: DecryptedBotProvider): PlatformClient | null {
const def = this.definitionByPlatform.get(platform);
if (!def) {
log('No definition registered for platform: %s', platform);
@@ -205,6 +199,7 @@ export class GatewayManager {
const context: BotPlatformRuntimeContext = {
appUrl: process.env.APP_URL,
redisClient: getAgentRuntimeRedisClient() as any,
+ userId: provider.userId,
};
return def.clientFactory.createClient(config, context);
diff --git a/src/server/services/toolExecution/__tests__/deviceProxy.test.ts b/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
index 6bea6927c9d..8a33493c4df 100644
--- a/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
+++ b/src/server/services/toolExecution/__tests__/deviceProxy.test.ts
@@ -9,6 +9,7 @@ const mockEnv = vi.hoisted(() => ({
}));
const mockClient = vi.hoisted(() => ({
+ executeMessageApi: vi.fn(),
executeToolCall: vi.fn(),
getDeviceSystemInfo: vi.fn(),
queryDeviceList: vi.fn(),
@@ -256,6 +257,67 @@ describe('DeviceProxy', () => {
});
});
+ describe('executeMessageApi', () => {
+ const params = { deviceId: 'dev-1', userId: 'user-1' };
+ const api = { apiName: 'sendText', payload: { chatGuid: 'chat-1' }, platform: 'imessage' };
+
+ it('should return error when not configured', async () => {
+ const proxy = new DeviceProxy();
+ const result = await proxy.executeMessageApi(params, api);
+
+ expect(result).toEqual({
+ content: 'Device Gateway is not configured',
+ error: 'GATEWAY_NOT_CONFIGURED',
+ success: false,
+ });
+ });
+
+ it('should execute message API with default timeout', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ const expected = { content: '{"ok":true}', success: true };
+ mockClient.executeMessageApi.mockResolvedValue(expected);
+
+ const proxy = new DeviceProxy();
+ const result = await proxy.executeMessageApi(params, api);
+
+ expect(result).toEqual(expected);
+ expect(mockClient.executeMessageApi).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', timeout: 30_000, userId: 'user-1' },
+ api,
+ );
+ });
+
+ it('should use custom timeout', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ mockClient.executeMessageApi.mockResolvedValue({ content: 'ok', success: true });
+
+ const proxy = new DeviceProxy();
+ await proxy.executeMessageApi(params, api, 60_000);
+
+ expect(mockClient.executeMessageApi).toHaveBeenCalledWith(
+ { deviceId: 'dev-1', timeout: 60_000, userId: 'user-1' },
+ api,
+ );
+ });
+
+ it('should return error result on exception', async () => {
+ mockEnv.DEVICE_GATEWAY_URL = 'https://gateway.example.com';
+ mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
+ mockClient.executeMessageApi.mockRejectedValue(new Error('connection refused'));
+
+ const proxy = new DeviceProxy();
+ const result = await proxy.executeMessageApi(params, api);
+
+ expect(result).toEqual({
+ content: 'Device message API error: connection refused',
+ error: 'connection refused',
+ success: false,
+ });
+ });
+ });
+
describe('getClient (lazy initialization)', () => {
it('should return null when URL is missing', async () => {
mockEnv.DEVICE_GATEWAY_SERVICE_TOKEN = 'token';
diff --git a/src/server/services/toolExecution/deviceProxy.ts b/src/server/services/toolExecution/deviceProxy.ts
index cd0b1f81778..8181bb88e2a 100644
--- a/src/server/services/toolExecution/deviceProxy.ts
+++ b/src/server/services/toolExecution/deviceProxy.ts
@@ -1,7 +1,9 @@
import { type DeviceAttachment } from '@lobechat/builtin-tool-remote-device';
import {
+ type DeviceMessageApiResult,
type DeviceStatusResult,
type DeviceSystemInfo,
+ type DeviceToolCallResult,
GatewayHttpClient,
} from '@lobechat/device-gateway-client';
import type { HeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
@@ -94,7 +96,7 @@ export class DeviceProxy {
params: { deviceId: string; userId: string },
toolCall: { apiName: string; arguments: string; identifier: string },
timeout = 30_000,
- ): Promise<{ content: string; error?: string; success: boolean }> {
+ ): Promise<DeviceToolCallResult> {
const client = this.getClient();
if (!client) {
return {
@@ -124,6 +126,40 @@ export class DeviceProxy {
}
}
+ async executeMessageApi(
+ params: { deviceId: string; userId: string },
+ api: { apiName: string; payload: Record<string, unknown>; platform: string },
+ timeout = 30_000,
+ ): Promise<DeviceMessageApiResult> {
+ const client = this.getClient();
+ if (!client) {
+ return {
+ content: 'Device Gateway is not configured',
+ error: 'GATEWAY_NOT_CONFIGURED',
+ success: false,
+ };
+ }
+
+ log(
+ 'executeMessageApi: userId=%s, deviceId=%s, api=%s/%s',
+ params.userId,
+ params.deviceId,
+ api.platform,
+ api.apiName,
+ );
+
+ try {
+ return await client.executeMessageApi(
+ { deviceId: params.deviceId, timeout, userId: params.userId },
+ api,
+ );
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ log('executeMessageApi: error — %s', message);
+ return { content: `Device message API error: ${message}`, error: message, success: false };
+ }
+ }
+
private getClient(): GatewayHttpClient | null {
const url = gatewayEnv.DEVICE_GATEWAY_URL;
const token = gatewayEnv.DEVICE_GATEWAY_SERVICE_TOKEN;
diff --git a/src/server/services/toolExecution/serverRuntimes/message/index.ts b/src/server/services/toolExecution/serverRuntimes/message/index.ts
index aa36d001e6f..b75c516bfac 100644
--- a/src/server/services/toolExecution/serverRuntimes/message/index.ts
+++ b/src/server/services/toolExecution/serverRuntimes/message/index.ts
@@ -27,6 +27,8 @@ import { platformRegistry } from '@/server/services/bot/platforms';
import { DiscordApi } from '@/server/services/bot/platforms/discord/api';
import { DiscordMessageService } from '@/server/services/bot/platforms/discord/service';
import { FeishuMessageService } from '@/server/services/bot/platforms/feishu/service';
+import { ImessageDesktopBridgeApi } from '@/server/services/bot/platforms/imessage/desktopBridge';
+import { ImessageMessageService } from '@/server/services/bot/platforms/imessage/service';
import { QQMessageService } from '@/server/services/bot/platforms/qq/service';
import { SlackApi } from '@/server/services/bot/platforms/slack/api';
import { SlackMessageService } from '@/server/services/bot/platforms/slack/service';
@@ -82,6 +84,16 @@ export const messageRuntime: ServerRuntimeRegistration = {
'feishu',
);
},
+ imessage: async () => {
+ const { applicationId, credentials } = await resolveCredentials(providerModel, 'imessage');
+ return new ImessageMessageService(
+ new ImessageDesktopBridgeApi({
+ applicationId,
+ deviceId: credentials.desktopDeviceId,
+ userId: context.userId!,
+ }),
+ );
+ },
lark: async () => {
const { applicationId, credentials } = await resolveCredentials(providerModel, 'lark');
return new FeishuMessageService(