🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(agent-address): land the mail and linq transports as agent-address packages (#20269)
Arvin Xu7be45e3960bc
diff --git a/packages/agent-address-linq/package.json b/packages/agent-address-linq/package.jsonnew file mode 100644index 00000000000..b9bbd9c488d--- /dev/null+++ b/packages/agent-address-linq/package.json@@ -0,0 +1,24 @@+{+ "name": "@lobechat/agent-address-linq",+ "version": "0.1.0",+ "description": "Linq (iMessage / SMS) transport behind an agent's own phone address",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "files": [+ "dist"+ ],+ "scripts": {+ "build": "tsup",+ "clean": "rm -rf dist",+ "dev": "tsup --watch",+ "typecheck": "tsc --noEmit"+ },+ "devDependencies": {+ "@types/node": "^24.13.2",+ "standardwebhooks": "^1.0.0",+ "tsup": "^8.5.1",+ "typescript": "^6.0.3"+ }+}diff --git a/packages/agent-address-linq/src/api.test.ts b/packages/agent-address-linq/src/api.test.tsnew file mode 100644index 00000000000..31791767be2--- /dev/null+++ b/packages/agent-address-linq/src/api.test.ts@@ -0,0 +1,218 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { LinqApiClient } from './api';++const jsonResponse = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ headers: { 'content-type': 'application/json' },+ status,+ });++describe('LinqApiClient', () => {+ const fetchMock = vi.fn();++ beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ const createClient = (overrides: Partial<ConstructorParameters<typeof LinqApiClient>[0]> = {}) =>+ new LinqApiClient({+ apiKey: 'test-key',+ baseUrl: 'https://linq.test/v3',+ fromNumber: '+15550000001',+ ...overrides,+ });++ it('defaults to the Linq production base URL and rejects a missing key', () => {+ expect(new LinqApiClient({ apiKey: 'k' }).baseUrl).toBe('https://api.linqapp.com/v3');+ expect(() => new LinqApiClient({ apiKey: ' ' })).toThrow('Linq apiKey is required');+ });++ it('sends a bearer-authenticated text message to POST /chats/{chatId}/messages', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ chat_id: 'c1', message: { id: 'm1' } }));++ const client = createClient();+ const result = await client.sendText('chat 1', 'hello **world**');++ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://linq.test/v3/chats/chat%201/messages');+ expect(init.method).toBe('POST');+ expect(init.headers.Authorization).toBe('Bearer test-key');+ expect(JSON.parse(init.body)).toEqual({+ message: { parts: [{ type: 'text', value: 'hello **world**' }] },+ });+ expect(result.message.id).toBe('m1');+ });++ it('passes an idempotency key through to the message body', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ chat_id: 'c1', message: { id: 'm1' } }));++ await createClient().sendText('c1', 'hi', { idempotencyKey: 'push-1' });++ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({+ message: { idempotency_key: 'push-1', parts: [{ type: 'text', value: 'hi' }] },+ });+ });++ it('opens a chat with POST /chats when the handle has no chat yet', async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ chats: [] }))+ .mockResolvedValueOnce(jsonResponse({ chat: { id: 'new-chat' } }));++ const result = await createClient().sendToHandle({ handle: '+15550000002', text: 'first' });++ const [listUrl] = fetchMock.mock.calls[0];+ expect(listUrl).toBe('https://linq.test/v3/chats?limit=1&to=%2B15550000002');++ const [createUrl, createInit] = fetchMock.mock.calls[1];+ expect(createUrl).toBe('https://linq.test/v3/chats');+ expect(createInit.method).toBe('POST');+ expect(JSON.parse(createInit.body)).toEqual({+ from: '+15550000001',+ message: { parts: [{ type: 'text', value: 'first' }] },+ to: ['+15550000002'],+ });+ expect(result.chatId).toBe('new-chat');+ });++ it('reuses an existing chat instead of opening a second one', async () => {+ fetchMock+ .mockResolvedValueOnce(jsonResponse({ chats: [{ id: 'existing' }] }))+ .mockResolvedValueOnce(jsonResponse({ chat_id: 'existing', message: { id: 'm9' } }));++ const result = await createClient().sendToHandle({ handle: '+15550000002', text: 'again' });++ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(fetchMock.mock.calls[1][0]).toBe('https://linq.test/v3/chats/existing/messages');+ expect(result).toEqual({ chatId: 'existing', message: { id: 'm9' } });+ });++ it('refuses to open a chat without a from number', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ chats: [] }));+ const client = createClient({ fromNumber: undefined });++ await expect(client.sendToHandle({ handle: '+1', text: 'x' })).rejects.toThrow(+ 'Linq createChat requires a from number (LINQ_FROM_NUMBER)',+ );+ });++ it('drives typing with POST and DELETE on /chats/{chatId}/typing', async () => {+ fetchMock.mockResolvedValue(new Response(null, { status: 204 }));+ const client = createClient();++ await client.startTyping('c1');+ await client.stopTyping('c1');++ expect(fetchMock.mock.calls[0][0]).toBe('https://linq.test/v3/chats/c1/typing');+ expect(fetchMock.mock.calls[0][1].method).toBe('POST');+ expect(fetchMock.mock.calls[1][0]).toBe('https://linq.test/v3/chats/c1/typing');+ expect(fetchMock.mock.calls[1][1].method).toBe('DELETE');+ });++ it('marks a chat read with POST /chats/{chatId}/read', async () => {+ fetchMock.mockResolvedValue(new Response(null, { status: 204 }));++ await createClient().markRead('c1');++ expect(fetchMock.mock.calls[0][0]).toBe('https://linq.test/v3/chats/c1/read');+ expect(fetchMock.mock.calls[0][1].method).toBe('POST');+ });++ it('pre-uploads an attachment via POST /attachments then a presigned PUT', async () => {+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({+ attachment_id: 'att-1',+ http_method: 'PUT',+ required_headers: { 'content-type': 'image/png' },+ upload_url: 'https://upload.test/put/att-1',+ }),+ )+ .mockResolvedValueOnce(new Response('', { status: 200 }));++ const attachmentId = await createClient().uploadAttachment({+ data: Buffer.from('png-bytes').toString('base64'),+ mimeType: 'image/png',+ name: 'chart.png',+ });++ expect(attachmentId).toBe('att-1');++ const [createUrl, createInit] = fetchMock.mock.calls[0];+ expect(createUrl).toBe('https://linq.test/v3/attachments');+ expect(createInit.headers.Authorization).toBe('Bearer test-key');+ expect(JSON.parse(createInit.body)).toEqual({+ content_type: 'image/png',+ filename: 'chart.png',+ size_bytes: 9,+ });++ const [putUrl, putInit] = fetchMock.mock.calls[1];+ expect(putUrl).toBe('https://upload.test/put/att-1');+ expect(putInit.method).toBe('PUT');+ // The presigned URL carries its own credentials — never leak the API key.+ expect(putInit.headers.Authorization).toBeUndefined();+ expect(putInit.headers['content-type']).toBe('image/png');+ expect(Buffer.from(putInit.body).toString()).toBe('png-bytes');+ });++ it('sends a pre-uploaded attachment as a media part after the text leg', async () => {+ fetchMock+ .mockResolvedValueOnce(+ jsonResponse({+ attachment_id: 'att-2',+ required_headers: {},+ upload_url: 'https://u.test',+ }),+ )+ .mockResolvedValueOnce(new Response('', { status: 200 }))+ .mockResolvedValueOnce(jsonResponse({ chats: [{ id: 'c1' }] }))+ .mockResolvedValueOnce(jsonResponse({ chat_id: 'c1', message: { id: 'm2' } }));++ await createClient().sendToHandle({+ attachment: { data: Buffer.from('x').toString('base64'), mimeType: 'application/pdf' },+ handle: '+15550000002',+ text: 'report',+ });++ expect(JSON.parse(fetchMock.mock.calls[3][1].body)).toEqual({+ message: {+ parts: [+ { type: 'text', value: 'report' },+ { type: 'media', attachment_id: 'att-2' },+ ],+ },+ });+ });++ it('surfaces the upstream error code and message', async () => {+ fetchMock.mockResolvedValueOnce(+ jsonResponse({ error: { code: 2024, message: 'Recipient opted out' } }, 403),+ );++ await expect(createClient().sendText('c1', 'hi')).rejects.toThrow('Recipient opted out (2024)');+ });++ it('rejects consecutive text parts before hitting the API', async () => {+ await expect(+ createClient().sendMessage('c1', [+ { type: 'text', value: 'a' },+ { type: 'text', value: 'b' },+ ]),+ ).rejects.toThrow('Linq rejects consecutive text parts');+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('pings through GET /phone_numbers for credential validation', async () => {+ fetchMock.mockResolvedValueOnce(jsonResponse({ phone_numbers: [] }));++ await createClient().ping();++ expect(fetchMock.mock.calls[0][0]).toBe('https://linq.test/v3/phone_numbers?limit=1');+ });+});diff --git a/packages/agent-address-linq/src/api.ts b/packages/agent-address-linq/src/api.tsnew file mode 100644index 00000000000..bd604444506--- /dev/null+++ b/packages/agent-address-linq/src/api.ts@@ -0,0 +1,427 @@+import type {+ LinqApiConfig,+ LinqAttachmentCreateResponse,+ LinqChat,+ LinqChatCreateResponse,+ LinqChatListResponse,+ LinqMessageContent,+ LinqMessagePart,+ LinqMessageSendResponse,+ LinqOutboundAttachment,+ LinqSendOptions,+} from './types';+import { LINQ_DEFAULT_BASE_URL } from './types';++const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;++/** Linq caps a single message at 100 parts; consecutive text parts are invalid. */+export const LINQ_MAX_PARTS = 100;++/** URL-sourced media (downloaded by Linq on send) is capped at 10MB. */+export const LINQ_URL_MEDIA_MAX_BYTES = 10 * 1024 * 1024;++interface RequestOptions {+ body?: FormData | Record<string, unknown> | Uint8Array;+ headers?: Record<string, string>;+ method?: 'DELETE' | 'GET' | 'POST' | 'PUT';+ query?: Record<string, boolean | number | string | undefined>;+ signal?: AbortSignal;+}++/**+ * Thin, dependency-free client for Linq's REST v3 API.+ *+ * Used by the paths that must stay off the chat-SDK router (proactive push,+ * link notifications, typing) and by the adapter wrapper's `stopTyping`, which+ * the chat SDK has no hook for. Inbound dispatch reuses the official+ * `@linqapp/chat-sdk-adapter` instead of this client.+ */+export class LinqApiClient {+ readonly apiKey: string;+ readonly baseUrl: string;+ readonly fromNumber?: string;+ readonly requestTimeoutMs: number;++ constructor(options: LinqApiConfig) {+ if (!options.apiKey?.trim()) throw new Error('Linq apiKey is required');+ this.apiKey = options.apiKey.trim();+ this.baseUrl = stripTrailingSlashes(options.baseUrl?.trim() || LINQ_DEFAULT_BASE_URL);+ this.fromNumber = options.fromNumber?.trim() || undefined;+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;+ }++ // -------------------------------------------------------------------------+ // Health+ // -------------------------------------------------------------------------++ /** Cheap authenticated round-trip used to validate a key. */+ async ping(): Promise<void> {+ await this.request('phone_numbers', { query: { limit: 1 } });+ }++ // -------------------------------------------------------------------------+ // Chats & messages+ // -------------------------------------------------------------------------++ /** `GET /chats` — optionally filtered to one participant handle. */+ async listChats(+ options: { cursor?: string; limit?: number; to?: string } = {},+ ): Promise<LinqChatListResponse> {+ const payload = await this.request<LinqChatListResponse & { data?: LinqChat[] }>('chats', {+ query: { cursor: options.cursor, limit: options.limit, to: options.to },+ });+ return { chats: payload?.chats ?? payload?.data ?? [], next_cursor: payload?.next_cursor };+ }++ /** Most recent chat with `handle`, or undefined when LobeHub has never talked to it. */+ async findChat(handle: string): Promise<LinqChat | undefined> {+ const payload = await this.listChats({ limit: 1, to: handle });+ return payload.chats?.[0];+ }++ /**+ * `POST /chats` — opens a chat AND sends the first message. To message a+ * handle LobeHub has not talked to yet, the parts belong here: Linq has no+ * "create an empty chat" shape.+ */+ async createChat(params: {+ from?: string;+ parts: LinqMessagePart[];+ to: string;+ idempotencyKey?: string;+ }): Promise<LinqChatCreateResponse> {+ const from = params.from?.trim() || this.fromNumber;+ if (!from) throw new Error('Linq createChat requires a from number (LINQ_FROM_NUMBER)');++ return this.request<LinqChatCreateResponse>('chats', {+ body: {+ from,+ message: withIdempotency({ parts: params.parts }, params.idempotencyKey),+ to: [params.to],+ },+ method: 'POST',+ });+ }++ /** `POST /chats/{chatId}/messages`. */+ async sendMessage(+ chatId: string,+ parts: LinqMessagePart[],+ options: LinqSendOptions = {},+ ): Promise<LinqMessageSendResponse> {+ assertSendableParts(parts);+ return this.request<LinqMessageSendResponse>(`chats/${encodeURIComponent(chatId)}/messages`, {+ body: { message: withIdempotency({ parts }, options.idempotencyKey) },+ method: 'POST',+ });+ }++ /** Convenience wrapper for the single-text-part case. */+ async sendText(+ chatId: string,+ text: string,+ options: LinqSendOptions = {},+ ): Promise<LinqMessageSendResponse> {+ return this.sendMessage(chatId, [{ type: 'text', value: text }], options);+ }++ /**+ * `POST /chats/{chatId}/messages` for a chat that may not exist yet.+ *+ * Linq needs a chat id to send into, and opening a chat requires the first+ * message. So: reuse the existing chat when there is one, otherwise open the+ * chat with these very parts.+ */+ async sendToHandle(params: {+ attachment?: LinqOutboundAttachment;+ handle: string;+ options?: LinqSendOptions;+ parts?: LinqMessagePart[];+ text?: string;+ }): Promise<{ chatId: string; message?: LinqMessageSendResponse['message'] }> {+ const parts: LinqMessagePart[] = [...(params.parts ?? [])];+ if (params.text) parts.unshift({ type: 'text', value: params.text });+ if (params.attachment) {+ parts.push({+ type: 'media',+ attachment_id: await this.uploadAttachment(params.attachment),+ });+ }+ if (parts.length === 0) throw new Error('sendToHandle requires text, parts or an attachment');+ assertSendableParts(parts);++ const existing = await this.findChat(params.handle);+ if (existing) {+ const sent = await this.sendMessage(existing.id, parts, params.options ?? {});+ return { chatId: existing.id, message: sent.message };+ }++ const created = await this.createChat({+ idempotencyKey: params.options?.idempotencyKey,+ parts,+ to: params.handle,+ });+ return { chatId: created.chat.id };+ }++ // -------------------------------------------------------------------------+ // Typing & read receipts+ // -------------------------------------------------------------------------++ /** `POST /chats/{chatId}/typing` — shows the indicator for ~85s. */+ async startTyping(chatId: string): Promise<void> {+ await this.request(`chats/${encodeURIComponent(chatId)}/typing`, { method: 'POST' });+ }++ /**+ * `DELETE /chats/{chatId}/typing` — clears the indicator immediately.+ *+ * The official chat-SDK adapter exposes `startTyping` only (the chat SDK+ * adapter contract has no stop hook); this is the补齐 half.+ */+ async stopTyping(chatId: string): Promise<void> {+ await this.request(`chats/${encodeURIComponent(chatId)}/typing`, { method: 'DELETE' });+ }++ /** `POST /chats/{chatId}/read` — marks every message in the chat as read. */+ async markRead(chatId: string): Promise<void> {+ await this.request(`chats/${encodeURIComponent(chatId)}/read`, { method: 'POST' });+ }++ // -------------------------------------------------------------------------+ // Attachments+ // -------------------------------------------------------------------------++ /** Step 1 of the pre-upload flow: ask Linq for a presigned PUT. */+ async createAttachment(input: {+ contentType: string;+ filename: string;+ sizeBytes: number;+ }): Promise<LinqAttachmentCreateResponse> {+ return this.request<LinqAttachmentCreateResponse>('attachments', {+ body: {+ content_type: input.contentType,+ filename: input.filename,+ size_bytes: input.sizeBytes,+ },+ method: 'POST',+ });+ }++ /**+ * Steps 1+2 of the pre-upload flow. Returns the reusable `attachment_id`.+ *+ * `attachment_id` (not a public URL) is what a media part references, which+ * is also how files over 10MB get in — URL-based media is capped there.+ */+ async uploadAttachment(attachment: LinqOutboundAttachment): Promise<string> {+ const bytes = await resolveAttachmentBytes(attachment, this.requestTimeoutMs);+ const mimeType = bytes.mimeType ?? attachment.mimeType ?? 'application/octet-stream';+ const filename = attachment.name?.trim() || inferFileName(mimeType);++ const created = await this.createAttachment({+ contentType: mimeType,+ filename,+ sizeBytes: bytes.buffer.byteLength,+ });++ const uploadUrl = created.upload_url;+ if (!uploadUrl) throw new Error('Linq attachment create returned no upload_url');++ await this.putBytes(uploadUrl, created.required_headers ?? {}, bytes.buffer);+ return created.attachment_id;+ }++ private async putBytes(+ uploadUrl: string,+ headers: Record<string, string>,+ buffer: Uint8Array,+ ): Promise<void> {+ const response = await fetchWithTimeout(+ uploadUrl,+ {+ body: toArrayBuffer(buffer),+ headers,+ method: 'PUT',+ },+ this.requestTimeoutMs,+ );++ if (!response.ok) {+ const detail = await safeReadError(response);+ throw new Error(detail || `Linq attachment upload failed with HTTP ${response.status}`);+ }+ }++ // -------------------------------------------------------------------------+ // Transport+ // -------------------------------------------------------------------------++ private async request<T>(path: string, options: RequestOptions = {}): Promise<T> {+ const { body, headers, method = 'GET', query, signal } = options;+ const url = this.buildUrl(path, query);+ const init: RequestInit = {+ headers: { Authorization: `Bearer ${this.apiKey}`, ...headers },+ method,+ signal,+ };++ if (body instanceof FormData) {+ init.body = body;+ } else if (body instanceof Uint8Array) {+ // `fetch` accepts ArrayBuffer, not a typed-array view; slice out just the+ // bytes this view covers so a pooled Buffer never leaks its neighbours.+ init.body = toArrayBuffer(body);+ } else if (body) {+ init.body = JSON.stringify(body);+ init.headers = {+ ...(init.headers as Record<string, string>),+ 'Content-Type': 'application/json',+ };+ }++ const response = await fetchWithTimeout(url, init, this.requestTimeoutMs);+ return parseResponse<T>(response, `${method} ${path}`);+ }++ private buildUrl(+ path: string,+ query?: Record<string, boolean | number | string | undefined>,+ ): string {+ const url = new URL(path.replace(/^\/+/, ''), `${this.baseUrl}/`);+ for (const [key, value] of Object.entries(query ?? {})) {+ if (value === undefined) continue;+ url.searchParams.set(key, String(value));+ }+ return url.toString();+ }+}++/**+ * Linq rejects consecutive text parts, so a caller that concatenates two text+ * legs must merge them instead of emitting `[text, text]`.+ */+export const assertSendableParts = (parts: LinqMessagePart[]): void => {+ if (parts.length === 0) throw new Error('Linq message requires at least one part');+ if (parts.length > LINQ_MAX_PARTS) {+ throw new Error(`Linq message exceeds ${LINQ_MAX_PARTS} parts (${parts.length})`);+ }+ for (let index = 1; index < parts.length; index++) {+ if (parts[index].type === 'text' && parts[index - 1].type === 'text') {+ throw new Error('Linq rejects consecutive text parts — merge them into one part');+ }+ }+};++const withIdempotency = (+ message: LinqMessageContent,+ idempotencyKey: string | undefined,+): Record<string, unknown> => {+ const payload = { ...message } as Record<string, unknown>;+ if (idempotencyKey) payload.idempotency_key = idempotencyKey;+ return payload;+};++/** `fetch` wants an ArrayBuffer, and a view may be a window onto a pooled Buffer. */+const toArrayBuffer = (view: Uint8Array): ArrayBuffer =>+ view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength) as ArrayBuffer;++async function parseResponse<T>(response: Response, label: string): Promise<T> {+ const text = await response.text();+ if (response.status === 204 || !text) {+ if (!response.ok) throw new Error(`${label} failed with HTTP ${response.status}`);+ return {} as T;+ }++ const payload = parseJson<T>(text);+ if (!response.ok) {+ const detail = readLinqError(payload) ?? text;+ throw new Error(detail || `${label} failed with HTTP ${response.status}`);+ }+ return (payload ?? ({} as T)) as T;+}++async function safeReadError(response: Response): Promise<string | undefined> {+ const text = await response.text();+ if (!text) return undefined;+ return readLinqError(parseJson(text)) ?? text;+}++function readLinqError(payload: unknown): string | undefined {+ if (!payload || typeof payload !== 'object') return undefined;+ const record = payload as Record<string, any>;+ const error = record.error;+ if (typeof error === 'string') return error;+ if (error && typeof error === 'object') {+ const code = error.code ?? record.code;+ const message = error.message ?? record.message;+ if (message) return code ? `${message} (${code})` : String(message);+ }+ if (typeof record.message === 'string') return record.message;+ return undefined;+}++function parseJson<T>(text: string): T | 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: LinqOutboundAttachment,+ requestTimeoutMs: number,+): Promise<{ buffer: Uint8Array; mimeType?: string }> {+ if (attachment.data) {+ const buffer = Buffer.from(attachment.data, 'base64');+ return {+ buffer: new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength),+ mimeType: attachment.mimeType,+ };+ }++ if (!attachment.fetchUrl) {+ throw new Error('Linq 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: new Uint8Array(await response.arrayBuffer()),+ mimeType: response.headers.get('content-type') ?? attachment.mimeType,+ };+}++function inferFileName(mimeType: string): string {+ 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}`;+}diff --git a/packages/agent-address-linq/src/format-converter.test.ts b/packages/agent-address-linq/src/format-converter.test.tsnew file mode 100644index 00000000000..a96996528f6--- /dev/null+++ b/packages/agent-address-linq/src/format-converter.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { markdownToPlainText } from './format-converter';++describe('markdownToPlainText', () => {+ it('strips markdown markers because Linq delivers text parts verbatim', () => {+ const plain = markdownToPlainText('**bold** and *italic* and `code`');++ expect(plain).toContain('bold');+ expect(plain).toContain('italic');+ expect(plain).toContain('code');+ expect(plain).not.toContain('**');+ expect(plain).not.toContain('`');+ });++ it('keeps link targets reachable as text', () => {+ const plain = markdownToPlainText('See [the docs](https://lobehub.com/docs).');++ expect(plain).toContain('https://lobehub.com/docs');+ expect(plain).not.toContain('](');+ });++ it('drops heading markers but keeps the heading text', () => {+ const plain = markdownToPlainText('## Daily brief\n\n- item one\n- item two');++ expect(plain).toContain('Daily brief');+ expect(plain).not.toContain('##');+ expect(plain).toContain('item one');+ });++ it('leaves already-plain text untouched', () => {+ expect(markdownToPlainText(' plain text ')).toBe('plain text');+ });+});diff --git a/packages/agent-address-linq/src/format-converter.ts b/packages/agent-address-linq/src/format-converter.tsnew file mode 100644index 00000000000..25bc588d03c--- /dev/null+++ b/packages/agent-address-linq/src/format-converter.ts@@ -0,0 +1,75 @@+/**+ * Linq delivers a `text` part **verbatim** — the API docs are explicit that+ * "Markdown syntax will be delivered as plain text". An agent reply containing+ * `**bold**` would therefore reach the user as literal asterisks, so every+ * outbound leg (direct REST sends, proactive push, link notifications) degrades+ * markdown to plain text first.+ *+ * Deliberate difference from `chat`'s `toPlainText(ast)`, which the official+ * adapter uses for its `fromAst` path: link targets are kept as+ * `label (https://…)` rather than dropped. A chat bubble that silently loses the+ * URL an agent just sent is a functional loss, and the server's established+ * plain-text renderer (`apps/server/.../stripMarkdown.ts`) keeps them too.+ */++const CODE_BLOCK_PLACEHOLDER = '\u0000LINQ_CODE_BLOCK_';+const INLINE_CODE_PLACEHOLDER = '\u0000LINQ_INLINE_CODE_';++const restore = (text: string, placeholder: string, values: string[]): string =>+ text.replaceAll(new RegExp(`${placeholder}(\\d+)\\u0000`, 'g'), (match, index: string) => {+ const value = values[Number(index)];+ return value === undefined ? match : value;+ });++/**+ * Degrade markdown to the plain text a Linq text part can carry.+ *+ * Fenced and inline code are lifted out first so their contents survive the+ * inline rules untouched (a code sample full of `*` is not emphasis).+ */+export const markdownToPlainText = (markdown: string): string => {+ const trimmed = markdown.trim();+ if (!trimmed) return '';++ const codeBlocks: string[] = [];+ let text = trimmed.replaceAll(+ /^ {0,3}```[\w-]*\r?\n([\s\S]*?)^ {0,3}```/gm,+ (_match, content: string) => {+ const index = codeBlocks.push(content.replace(/\n$/, '')) - 1;+ return `${CODE_BLOCK_PLACEHOLDER}${index}\u0000`;+ },+ );++ const inlineCode: string[] = [];+ text = text.replaceAll(/`([^`\n]+)`/g, (_match, code: string) => {+ const index = inlineCode.push(code) - 1;+ return `${INLINE_CODE_PLACEHOLDER}${index}\u0000`;+ });++ // Links and images first, so `[**bold**](url)` keeps its target and an image+ // degrades to its alt text (or the URL when there is no alt).+ text = text.replaceAll(+ /!?\[([^\]]*)\]\(\s*([^)\s]+)(?:\s+"[^"]*")?\s*\)/g,+ (_match, label: string, url: string) => {+ const labelText = (label ?? '').trim();+ return labelText ? `${labelText} (${url})` : url;+ },+ );++ // Block-level syntax.+ text = text.replaceAll(/^ {0,3}#{1,6}[ \t]+/gm, '');+ text = text.replaceAll(/^[ \t]*>[ \t]?/gm, '');+ text = text.replaceAll(/^ {0,3}[-*_]{3,}[ \t]*$/gm, '---');++ // Inline emphasis. `_` rules are boundary-anchored so `snake_case_names`+ // survive; `*` cannot appear inside ordinary prose.+ text = text.replaceAll(/\*{1,3}([^*\n]+)\*{1,3}/g, '$1');+ text = text.replaceAll(/(^|[\s(])__([^_\n]+)__(?=[\s).,:;!?]|$)/gm, '$1$2');+ text = text.replaceAll(/(^|[\s(])_([^_\n]+)_(?=[\s).,:;!?]|$)/gm, '$1$2');+ text = text.replaceAll(/~~([^~\n]+)~~/g, '$1');++ text = restore(text, INLINE_CODE_PLACEHOLDER, inlineCode);+ text = restore(text, CODE_BLOCK_PLACEHOLDER, codeBlocks);++ return text.trim();+};diff --git a/packages/agent-address-linq/src/index.ts b/packages/agent-address-linq/src/index.tsnew file mode 100644index 00000000000..3283982e29a--- /dev/null+++ b/packages/agent-address-linq/src/index.ts@@ -0,0 +1,53 @@+/**+ * Linq transport — the provider behind an agent's own `phone` address.+ *+ * Linq is a carrier (iMessage / SMS), not a social platform: this package owns+ * the REST client, Standard Webhooks verification + replay dedupe, and the+ * markdown → plain-text degradation Linq requires. There is no chat-SDK+ * adapter here, and no per-agent bot registration — the number is shared+ * infrastructure, the agent merely owns an address on it.+ */+export {+ assertSendableParts,+ LINQ_MAX_PARTS,+ LINQ_URL_MEDIA_MAX_BYTES,+ LinqApiClient,+} from './api';+export { markdownToPlainText } from './format-converter';+export type {+ LinqApiConfig,+ LinqAttachmentCreateResponse,+ LinqChat,+ LinqChatCreateResponse,+ LinqChatListResponse,+ LinqInboundMessage,+ LinqLinkPart,+ LinqMediaPart,+ LinqMessageContent,+ LinqMessagePart,+ LinqMessageSendResponse,+ LinqOutboundAttachment,+ LinqSendOptions,+ LinqSentMessage,+ LinqTextPart,+ LinqWebhookEvent,+ LinqWebhookSignatureHeaders,+} from './types';+export { LINQ_DEFAULT_BASE_URL } from './types';+export type {+ InMemoryLinqWebhookDedupeStoreOptions,+ LinqWebhookDedupeStore,+ LinqWebhookGateOptions,+ LinqWebhookGateResult,+ LinqWebhookSignatureFailure,+ LinqWebhookSignatureOptions,+} from './webhook';+export {+ createInMemoryLinqWebhookDedupeStore,+ LINQ_WEBHOOK_ID_TTL_SECONDS,+ LINQ_WEBHOOK_TOLERANCE_SECONDS,+ LinqWebhookDeduplicator,+ signLinqWebhookPayload,+ verifyLinqWebhookRequest,+ verifyLinqWebhookSignature,+} from './webhook';diff --git a/packages/agent-address-linq/src/linq-wire.test.ts b/packages/agent-address-linq/src/linq-wire.test.tsnew file mode 100644index 00000000000..83dfeceba1f--- /dev/null+++ b/packages/agent-address-linq/src/linq-wire.test.ts@@ -0,0 +1,209 @@+import { createServer, type IncomingMessage, type Server } from 'node:http';+import type { AddressInfo } from 'node:net';++import { afterAll, beforeAll, describe, expect, it } from 'vitest';++import {+ LinqApiClient,+ LinqWebhookDeduplicator,+ signLinqWebhookPayload,+ verifyLinqWebhookRequest,+} from './index';++/**+ * Wire-level end-to-end check against a **real HTTP mock of Linq's v3 API**.+ *+ * Unlike the per-module tests (which stub `fetch`), this exercises the actual+ * request bytes LobeHub sends and the actual signature Linq would send back:+ * real `http.createServer`, real `fetch`, real HMAC. That is what makes it a+ * substitute for the live Linq account we cannot provision here.+ */++const SECRET = `whsec_${Buffer.from('linq-wire-smoke-secret').toString('base64')}`;+const FROM = '+15550000001';+const TO = '+15550000002';++interface RecordedRequest {+ auth?: string;+ body: string;+ method: string;+ path: string;+}++const recorded: RecordedRequest[] = [];++const readBody = async (req: IncomingMessage): Promise<string> => {+ const chunks: Buffer[] = [];+ for await (const chunk of req) chunks.push(chunk as Buffer);+ return Buffer.concat(chunks).toString();+};++let server: Server;+let base = '';++beforeAll(async () => {+ server = createServer(async (req, res) => {+ const url = new URL(req.url ?? '/', 'http://localhost');+ const body = await readBody(req);+ recorded.push({+ auth: req.headers.authorization,+ body,+ method: req.method ?? '',+ path: url.pathname,+ });++ const json = (payload: unknown, status = 200) => {+ res.writeHead(status, { 'content-type': 'application/json' });+ res.end(JSON.stringify(payload));+ };++ // Linq v3 surface used by the adapter.+ if (req.method === 'GET' && url.pathname === '/v3/chats') {+ return json({ chats: [{ id: 'chat-1', is_group: false }] });+ }+ if (req.method === 'POST' && url.pathname === '/v3/chats') {+ return json({ chat: { id: 'chat-1', is_group: false } });+ }+ if (req.method === 'POST' && url.pathname === '/v3/chats/chat-1/messages') {+ return json({ chat_id: 'chat-1', message: { id: 'msg-1' } });+ }+ if (req.method === 'POST' && url.pathname === '/v3/chats/chat-1/typing') {+ res.writeHead(204);+ return res.end();+ }+ if (req.method === 'DELETE' && url.pathname === '/v3/chats/chat-1/typing') {+ res.writeHead(204);+ return res.end();+ }+ if (req.method === 'POST' && url.pathname === '/v3/chats/chat-1/read') {+ res.writeHead(204);+ return res.end();+ }+ if (req.method === 'POST' && url.pathname === '/v3/attachments') {+ return json({+ attachment_id: 'att-1',+ http_method: 'PUT',+ required_headers: { 'content-type': 'image/png' },+ upload_url: `${base}/upload/att-1`,+ });+ }+ if (req.method === 'PUT' && url.pathname === '/upload/att-1') {+ res.writeHead(200);+ return res.end();+ }++ return json({ error: { code: 404, message: `unrouted ${req.method} ${url.pathname}` } }, 404);+ });++ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+});++afterAll(async () => {+ await new Promise<void>((resolve) => server.close(() => resolve()));+});++const buildClient = () =>+ new LinqApiClient({ apiKey: 'linq-wire-key', baseUrl: `${base}/v3`, fromNumber: FROM });++/**+ * `body` is what the request carries; `signBody` is what the signature covers.+ * They differ only in the tampering case — signing the tampered body would make+ * it a legitimate delivery of different content, not an attack.+ */+const buildSignedWebhook = (params: { body: string; id: string; signBody?: string }) => {+ const timestamp = Math.floor(Date.now() / 1000);+ return new Request('https://app.lobehub.com/api/agent/messenger/webhooks/linq', {+ body: params.body,+ headers: {+ 'webhook-id': params.id,+ 'webhook-signature': signLinqWebhookPayload({+ body: params.signBody ?? params.body,+ id: params.id,+ secret: SECRET,+ timestamp,+ }),+ 'webhook-timestamp': String(timestamp),+ },+ method: 'POST',+ });+};++describe('Linq wire smoke (real HTTP mock of api.linqapp.com/v3)', () => {+ it('drives the whole messenger surface over HTTP and rejects replayed deliveries', async () => {+ const client = buildClient();+ recorded.length = 0;++ // --- Outbound: find-or-open the chat, then send -------------------------+ await client.sendToHandle({ handle: TO, text: 'Daily brief' });++ // --- Typing / read receipts -------------------------------------------+ await client.startTyping('chat-1');+ await client.stopTyping('chat-1');+ await client.markRead('chat-1');++ // --- Attachment pre-upload + media send -------------------------------+ const attachmentId = await client.uploadAttachment({+ data: Buffer.from('png-bytes').toString('base64'),+ mimeType: 'image/png',+ name: 'chart.png',+ });+ await client.sendMessage('chat-1', [{ attachment_id: attachmentId, type: 'media' }]);++ // --- Inbound: verify a signed delivery, then reject its replay --------+ const deduplicator = new LinqWebhookDeduplicator();+ const body = JSON.stringify({+ data: { chat: { id: 'chat-1' }, direction: 'inbound', id: 'msg-in-1' },+ event_type: 'message.received',+ });++ const inbound = await verifyLinqWebhookRequest(buildSignedWebhook({ body, id: 'wh-1' }), {+ deduplicator,+ signingSecret: SECRET,+ });+ const replay = await verifyLinqWebhookRequest(buildSignedWebhook({ body, id: 'wh-1' }), {+ deduplicator,+ signingSecret: SECRET,+ });+ const tampered = await verifyLinqWebhookRequest(+ // Signature is valid for `body`, but the request carries a modified one.+ buildSignedWebhook({ body: `${body} `, id: 'wh-2', signBody: body }),+ { deduplicator, signingSecret: SECRET },+ );++ console.log(+ [+ '--- Linq wire transcript (method path auth body) ---',+ ...recorded.map(+ (r) => `${r.method} ${r.path.replace(base, '')} ${r.auth ?? '-'} ${r.body || '-'}`,+ ),+ '--- webhook gate ---',+ `signed inbound -> ok=${inbound.ok}`,+ `replayed webhook-id -> ok=${replay.ok} status=${replay.ok ? '-' : replay.response.status}`,+ `tampered body -> ok=${tampered.ok} status=${tampered.ok ? '-' : tampered.response.status}`,+ ].join('\n'),+ );++ expect(recorded.map((r) => `${r.method} ${r.path.replace(base, '')}`)).toEqual([+ 'GET /v3/chats',+ 'POST /v3/chats/chat-1/messages',+ 'POST /v3/chats/chat-1/typing',+ 'DELETE /v3/chats/chat-1/typing',+ 'POST /v3/chats/chat-1/read',+ 'POST /v3/attachments',+ 'PUT /upload/att-1',+ 'POST /v3/chats/chat-1/messages',+ ]);++ // Every authenticated call carries the Bearer key; the presigned upload+ // must NOT (it is a public URL that already embeds its own signature).+ expect(recorded[0].auth).toBe('Bearer linq-wire-key');+ expect(recorded[6].auth).toBeUndefined();++ expect(inbound.ok).toBe(true);+ expect(replay.ok).toBe(false);+ if (!replay.ok) expect(replay.response.status).toBe(409);+ expect(tampered.ok).toBe(false);+ if (!tampered.ok) expect(tampered.response.status).toBe(401);+ });+});diff --git a/packages/agent-address-linq/src/types.ts b/packages/agent-address-linq/src/types.tsnew file mode 100644index 00000000000..fd2ab0a368e--- /dev/null+++ b/packages/agent-address-linq/src/types.ts@@ -0,0 +1,175 @@+/**+ * Linq REST v3 + webhook types.+ *+ * Deliberately hand-written and dependency-light: the LobeHub server's+ * outbound / proactive-push path must not pull the chat SDK (and therefore the+ * whole agent runtime) into a serverless function just to send one DM, the same+ * reason `chat-adapter-imessage`'s `BlueBubblesApiClient` is standalone.+ *+ * Shapes mirror `@linqapp/sdk` (v0.75) — see `resources/chats/chats.d.ts`,+ * `resources/chats/messages.d.ts`, `resources/attachments.d.ts` and+ * `resources/webhook-events.d.ts` upstream.+ */++/** Linq's production REST base. `LINQ_BASE_URL` may override it (staging, mock). */+export const LINQ_DEFAULT_BASE_URL = 'https://api.linqapp.com/v3';++export interface LinqApiConfig {+ /** Bearer token issued by Linq for the partner account. */+ apiKey: string;+ /**+ * REST base URL. Defaults to `LINQ_DEFAULT_BASE_URL`. Point this at a local+ * mock in tests / local acceptance.+ */+ baseUrl?: string;+ /**+ * The LobeHub-owned Linq (iMessage) number in E.164 — the `from` for chats+ * LobeHub opens itself (proactive push). Inbound chats already carry it.+ */+ fromNumber?: string;+ requestTimeoutMs?: number;+}++// ---------------------------------------------------------------------------+// Message parts+// ---------------------------------------------------------------------------++export interface LinqTextPart {+ type: 'text';+ /**+ * Sent verbatim. Markdown is NOT parsed by Linq — degrade it before building+ * a part (see `toPlainText` in `./format-converter`).+ */+ value: string;+}++/**+ * Media part. Exactly one of `url` (public HTTPS, ≤10MB) or `attachment_id`+ * (pre-uploaded via `POST /v3/attachments`, ≤100MB) must be set.+ */+export interface LinqMediaPart {+ attachment_id?: string;+ sticker?: boolean;+ type: 'media';+ url?: string;+}++/** A rich preview card. Must be the ONLY part in its message. */+export interface LinqLinkPart {+ type: 'link';+ value: string;+}++export type LinqMessagePart = LinqLinkPart | LinqMediaPart | LinqTextPart;++export interface LinqMessageContent {+ parts: LinqMessagePart[];+ preferred_service?: string;+ reply_to?: { message_id: string };+}++// ---------------------------------------------------------------------------+// Chats / messages+// ---------------------------------------------------------------------------++export interface LinqChat {+ created_at?: string;+ display_name?: string | null;+ handles?: unknown[];+ id: string;+ is_archived?: boolean;+ is_group?: boolean;+ service?: string;+}++export interface LinqSentMessage {+ created_at?: string;+ delivery_status?: 'pending' | 'queued' | 'sent' | 'delivered' | 'received' | 'read' | 'failed';+ id: string;+ parts?: unknown[];+ sent_at?: string | null;+}++/** `POST /v3/chats` — opens the chat AND sends the first message. */+export interface LinqChatCreateResponse {+ chat: LinqChat;+}++/** `POST /v3/chats/{chatId}/messages`. */+export interface LinqMessageSendResponse {+ chat_id: string;+ message: LinqSentMessage;+}++/** `GET /v3/chats`. */+export interface LinqChatListResponse {+ chats?: LinqChat[];+ next_cursor?: string | null;+}++export interface LinqSendOptions {+ /**+ * Dedupes retries of the same logical send. Must be stable across retries to+ * have any effect. Max 255 chars.+ */+ idempotencyKey?: string;+}++// ---------------------------------------------------------------------------+// Attachments+// ---------------------------------------------------------------------------++/** `POST /v3/attachments` — presigned upload + reusable id. */+export interface LinqAttachmentCreateResponse {+ attachment_id: string;+ /** `PUT` the raw bytes here with `required_headers`, within 15 minutes. */+ http_method?: 'PUT';+ required_headers?: Record<string, string> | null;+ upload_url: string;+}++export interface LinqOutboundAttachment {+ /** Raw bytes, base64. Mutually exclusive with `fetchUrl`. */+ data?: string;+ /** Public HTTPS URL to pull the bytes from. Mutually exclusive with `data`. */+ fetchUrl?: string;+ mimeType?: string;+ name?: string;+ /** Known byte size, used to skip a HEAD probe when uploading `fetchUrl`. */+ size?: number;+}++// ---------------------------------------------------------------------------+// Webhooks+// ---------------------------------------------------------------------------++/** Headers Linq sets on every delivery (Standard Webhooks). */+export interface LinqWebhookSignatureHeaders {+ /** `webhook-id` — unique per delivery, the dedupe key. */+ id: string;+ /** `webhook-signature` — space-separated `v1,<base64>` entries. */+ signature: string;+ /** `webhook-timestamp` — unix seconds. */+ timestamp: string;+}++export interface LinqWebhookEvent<TData = LinqInboundMessage> {+ [key: string]: unknown;+ data: TData;+ /** e.g. `message.received`. */+ event_type: string;+}++/** The `message.received` payload — the inbound half we route to agents. */+export interface LinqInboundMessage {+ [key: string]: unknown;+ chat: { id: string; is_group?: boolean };+ /** `inbound` for messages sent TO the LobeHub number. */+ direction?: 'inbound' | 'outbound';+ id: string;+ parts?: LinqMessagePart[];+ /** Phone number of the human, when Linq resolved one. */+ sender?: { handle?: string } | string | null;+ sender_handle?: { handle?: string; id?: string; service?: string } | null;+ sent_at?: string | null;+}diff --git a/packages/agent-address-linq/src/webhook.test.ts b/packages/agent-address-linq/src/webhook.test.tsnew file mode 100644index 00000000000..d0622e31288--- /dev/null+++ b/packages/agent-address-linq/src/webhook.test.ts@@ -0,0 +1,364 @@+import { Webhook } from 'standardwebhooks';+import { describe, expect, it, vi } from 'vitest';++import {+ createInMemoryLinqWebhookDedupeStore,+ LinqWebhookDeduplicator,+ signLinqWebhookPayload,+ verifyLinqWebhookRequest,+ verifyLinqWebhookSignature,+} from './webhook';++/**+ * Standard Webhooks secrets are `whsec_<base64>`; the reference implementation+ * (and therefore Linq) base64-decodes everything after the prefix.+ */+const encodeSecret = (raw: string) => `whsec_${Buffer.from(raw).toString('base64')}`;++const SECRET = encodeSecret('lobe-linq-webhook-test-secret');++const BODY = JSON.stringify({+ data: {+ chat: { id: 'chat-1', is_group: false },+ direction: 'inbound',+ id: 'msg-1',+ parts: [{ type: 'text', value: 'hello' }],+ sender_handle: { handle: '+15550000002' },+ },+ event_type: 'message.received',+});++const nowSeconds = () => Math.floor(Date.now() / 1000);++const sign = (params: { body: string; id: string; secret?: string; timestamp: number | string }) =>+ signLinqWebhookPayload({ secret: SECRET, ...params });++const buildRequest = (params: {+ body: string;+ headers?: Record<string, string>;+ method?: string;+}): Request =>+ new Request('https://app.lobehub.com/api/webhooks/messenger/linq', {+ body: params.method === 'GET' ? undefined : params.body,+ headers: params.headers,+ method: params.method ?? 'POST',+ });++describe('verifyLinqWebhookSignature', () => {+ it('accepts a correctly signed delivery', () => {+ const id = 'wh_1';+ const timestamp = nowSeconds();++ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: {+ id,+ signature: sign({ body: BODY, id, timestamp }),+ timestamp: String(timestamp),+ },+ secret: SECRET,+ }),+ ).toEqual({ ok: true });+ });++ it('rejects a tampered body', () => {+ const id = 'wh_tamper';+ const timestamp = nowSeconds();+ const signature = sign({ body: BODY, id, timestamp });++ expect(+ verifyLinqWebhookSignature({+ body: `${BODY} `,+ headers: { id, signature, timestamp: String(timestamp) },+ secret: SECRET,+ }),+ ).toEqual({ ok: false, reason: 'invalid-signature' });+ });++ it('rejects a signature made with another secret', () => {+ const id = 'wh_other_secret';+ const timestamp = nowSeconds();+ const signature = sign({+ body: BODY,+ id,+ secret: encodeSecret('some-other-secret'),+ timestamp,+ });++ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: { id, signature, timestamp: String(timestamp) },+ secret: SECRET,+ }),+ ).toEqual({ ok: false, reason: 'invalid-signature' });+ });++ it('enforces the 5 minute tolerance window', () => {+ const id = 'wh_window';+ const base = 1_700_000_000;+ const now = base * 1000;++ const okAt300 = sign({ body: BODY, id, timestamp: base - 300 });+ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: { id, signature: okAt300, timestamp: String(base - 300) },+ now,+ secret: SECRET,+ }),+ ).toEqual({ ok: true });++ const staleAt301 = sign({ body: BODY, id, timestamp: base - 301 });+ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: { id, signature: staleAt301, timestamp: String(base - 301) },+ now,+ secret: SECRET,+ }),+ ).toEqual({ ok: false, reason: 'timestamp-out-of-tolerance' });++ // A delivery from the future is just as untrustworthy as a stale one.+ const future = sign({ body: BODY, id, timestamp: base + 4000 });+ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: { id, signature: future, timestamp: String(base + 4000) },+ now,+ secret: SECRET,+ }),+ ).toEqual({ ok: false, reason: 'timestamp-out-of-tolerance' });+ });++ it('requires all three Standard Webhooks headers', () => {+ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: { id: '', signature: 'v1,x', timestamp: '1' },+ secret: SECRET,+ }),+ ).toEqual({ ok: false, reason: 'missing-headers' });+ });++ it('accepts one valid entry among several (key rotation) and ignores other versions', () => {+ const id = 'wh_rotate';+ const timestamp = nowSeconds();+ const valid = sign({ body: BODY, id, timestamp });++ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: {+ id,+ signature: `v0,not-a-real-signature v1,${Buffer.from('nope').toString('base64')} ${valid}`,+ timestamp: String(timestamp),+ },+ secret: SECRET,+ }),+ ).toEqual({ ok: true });+ });++ it('accepts a bare base64 secret without the whsec_ prefix', () => {+ const id = 'wh_bare';+ const timestamp = nowSeconds();+ const bare = Buffer.from('lobe-linq-webhook-test-secret').toString('base64');+ const signature = signLinqWebhookPayload({ body: BODY, id, secret: bare, timestamp });++ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: { id, signature, timestamp: String(timestamp) },+ secret: bare,+ }),+ ).toEqual({ ok: true });+ });++ // The whole point of reusing the official adapter is that our gate and Linq+ // agree on the wire format. `standardwebhooks` is the reference+ // implementation the official adapter (and @linqapp/sdk) delegate to.+ it('agrees with the standardwebhooks reference implementation in both directions', () => {+ const reference = new Webhook(SECRET);+ const id = 'wh_cross';+ const timestamp = nowSeconds();+ const headers = { 'webhook-id': id, 'webhook-timestamp': String(timestamp) };++ const ours = sign({ body: BODY, id, timestamp });++ // Ours is accepted by the reference implementation...+ expect(reference.verify(BODY, { ...headers, 'webhook-signature': ours })).toEqual(+ JSON.parse(BODY),+ );++ // ...and theirs is accepted by ours.+ const theirs = reference.sign(id, new Date(timestamp * 1000), BODY);+ expect(+ verifyLinqWebhookSignature({+ body: BODY,+ headers: { id, signature: theirs, timestamp: String(timestamp) },+ secret: SECRET,+ }),+ ).toEqual({ ok: true });+ });+});++describe('LinqWebhookDeduplicator', () => {+ it('claims a webhook-id exactly once', async () => {+ const deduplicator = new LinqWebhookDeduplicator();++ expect(await deduplicator.isDuplicate('wh_a')).toBe(false);+ expect(await deduplicator.isDuplicate('wh_a')).toBe(true);+ expect(await deduplicator.isDuplicate('wh_b')).toBe(false);+ });++ it('releases a claim once its TTL expires', async () => {+ let now = 1_000_000;+ const store = createInMemoryLinqWebhookDedupeStore({ now: () => now });+ const deduplicator = new LinqWebhookDeduplicator(store, 60);++ expect(await deduplicator.isDuplicate('wh_ttl')).toBe(false);+ now += 61_000;+ expect(await deduplicator.isDuplicate('wh_ttl')).toBe(false);+ });++ it('bounds the number of tracked ids', async () => {+ const store = createInMemoryLinqWebhookDedupeStore({ maxEntries: 2 });++ expect(await store.claim('a', 60)).toBe(true);+ expect(await store.claim('b', 60)).toBe(true);+ expect(await store.claim('c', 60)).toBe(true);++ // `a` was evicted when the cap was reached, so it can be claimed again.+ expect(await store.claim('a', 60)).toBe(true);+ expect(await store.claim('c', 60)).toBe(false);+ });+});++describe('verifyLinqWebhookRequest', () => {+ const buildValid = (params: { id?: string; body?: string } = {}) => {+ const id = params.id ?? 'wh_gate';+ const body = params.body ?? BODY;+ const timestamp = nowSeconds();+ return {+ body,+ id,+ request: buildRequest({+ body,+ headers: {+ 'webhook-id': id,+ 'webhook-signature': sign({ body, id, timestamp }),+ 'webhook-timestamp': String(timestamp),+ },+ }),+ };+ };++ it('returns the parsed event for a valid delivery', async () => {+ const { id, request } = buildValid();++ const result = await verifyLinqWebhookRequest(request, { signingSecret: SECRET });++ expect(result.ok).toBe(true);+ if (result.ok) {+ expect(result.id).toBe(id);+ expect(result.event.event_type).toBe('message.received');+ }+ });++ it('answers 503 when the signing secret is not configured', async () => {+ const { request } = buildValid();++ const result = await verifyLinqWebhookRequest(request, { signingSecret: undefined });++ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.response.status).toBe(503);+ });++ it('answers 401 for an unsigned delivery', async () => {+ const result = await verifyLinqWebhookRequest(buildRequest({ body: BODY }), {+ signingSecret: SECRET,+ });++ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.response.status).toBe(401);+ });++ it('answers 409 for a replayed webhook-id', async () => {+ const deduplicator = new LinqWebhookDeduplicator();++ // Linq retries deliver a fresh Request with the same webhook-id and body.+ const first = await verifyLinqWebhookRequest(buildValid({ id: 'wh_replay' }).request, {+ deduplicator,+ signingSecret: SECRET,+ });+ const second = await verifyLinqWebhookRequest(buildValid({ id: 'wh_replay' }).request, {+ deduplicator,+ signingSecret: SECRET,+ });++ expect(first.ok).toBe(true);+ expect(second.ok).toBe(false);+ if (!second.ok) expect(second.response.status).toBe(409);+ });++ // Security property: an attacker who can post to the endpoint must not be+ // able to burn a webhook-id and suppress Linq's genuine delivery of it.+ it('verifies the signature before touching the dedupe store', async () => {+ const deduplicator = new LinqWebhookDeduplicator();+ const id = 'wh_ordering';+ const forged = buildRequest({+ body: BODY,+ headers: {+ 'webhook-id': id,+ 'webhook-signature': 'v1,Zm9yZ2Vk',+ 'webhook-timestamp': String(nowSeconds()),+ },+ });++ const forgedResult = await verifyLinqWebhookRequest(forged, {+ deduplicator,+ signingSecret: SECRET,+ });+ expect(forgedResult.ok).toBe(false);++ const { request } = buildValid({ id });+ const genuine = await verifyLinqWebhookRequest(request, {+ deduplicator,+ signingSecret: SECRET,+ });+ expect(genuine.ok).toBe(true);+ });++ it('answers 400 for a signed but malformed body', async () => {+ const id = 'wh_bad_json';+ const body = '{not json';+ const timestamp = nowSeconds();+ const request = buildRequest({+ body,+ headers: {+ 'webhook-id': id,+ 'webhook-signature': sign({ body, id, timestamp }),+ 'webhook-timestamp': String(timestamp),+ },+ });++ const result = await verifyLinqWebhookRequest(request, { signingSecret: SECRET });++ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.response.status).toBe(400);+ });++ it('accepts a caller-buffered raw body without re-reading the request', async () => {+ const { request } = buildValid({ id: 'wh_buffered' });+ const text = vi.spyOn(request, 'text');++ const result = await verifyLinqWebhookRequest(request, {+ rawBody: BODY,+ signingSecret: SECRET,+ });++ expect(result.ok).toBe(true);+ expect(text).not.toHaveBeenCalled();+ });+});diff --git a/packages/agent-address-linq/src/webhook.ts b/packages/agent-address-linq/src/webhook.tsnew file mode 100644index 00000000000..e5e5bbc5a83--- /dev/null+++ b/packages/agent-address-linq/src/webhook.ts@@ -0,0 +1,269 @@+import { createHmac, timingSafeEqual } from 'node:crypto';++import type { LinqWebhookEvent, LinqWebhookSignatureHeaders } from './types';++/**+ * Linq signs every webhook delivery with **Standard Webhooks**:+ *+ * ```+ * signed content = `${webhook-id}.${webhook-timestamp}.${rawBody}`+ * signature = `v1,` + base64(HMAC-SHA256(secretKey, signed content))+ * ```+ *+ * `webhook-signature` may carry several space-separated entries (key+ * rotation); any `v1,<sig>` that matches verifies the delivery. Deliveries+ * older than five minutes are rejected, and comparison is constant-time.+ *+ * This module owns the messenger **webhook gate**: the same algorithm the+ * official `@linqapp/chat-sdk-adapter` runs through `standardwebhooks` for the+ * chat-SDK dispatch path, plus the two things that adapter does not do —+ * `webhook-id` de-duplication and gate-shaped status codes.+ * `webhook.test.ts` cross-checks this implementation against the official+ * verifier so the two cannot drift.+ */++/** Standard Webhooks tolerance — deliveries older than this are rejected. */+export const LINQ_WEBHOOK_TOLERANCE_SECONDS = 5 * 60;++/** How long a `webhook-id` stays claimed. Covers Linq's retry window. */+export const LINQ_WEBHOOK_ID_TTL_SECONDS = 10 * 60;++/** Standard Webhooks secrets are `whsec_<base64>`; the prefix is not key material. */+const SECRET_PREFIX = 'whsec_';++const decodeSecret = (secret: string): Buffer => {+ if (secret.startsWith(SECRET_PREFIX)) {+ return Buffer.from(secret.slice(SECRET_PREFIX.length), 'base64');+ }+ // Not every deployment configures the `whsec_` form; the reference+ // implementation treats a bare string the same way (base64), so keep parity.+ return Buffer.from(secret, 'base64');+};++/**+ * Produce the `webhook-signature` value for a payload.+ *+ * Exported because it is the only way to build a realistic fixture: the mock+ * Linq server in the acceptance harness and the unit tests both sign with it,+ * so the verifier is exercised against the real algorithm rather than a+ * hard-coded digest.+ */+export const signLinqWebhookPayload = (params: {+ body: string;+ id: string;+ secret: string;+ timestamp: number | string;+}): string => {+ const signedContent = `${params.id}.${params.timestamp}.${params.body}`;+ const digest = createHmac('sha256', decodeSecret(params.secret))+ .update(signedContent)+ .digest('base64');+ return `v1,${digest}`;+};++export type LinqWebhookSignatureFailure =+ 'invalid-signature' | 'missing-headers' | 'timestamp-out-of-tolerance';++export interface LinqWebhookSignatureOptions {+ /** Raw request body — the exact bytes the signature was computed over. */+ body: string;+ headers: LinqWebhookSignatureHeaders;+ /** Injectable clock, in milliseconds. Defaults to `Date.now()`. */+ now?: number;+ secret: string;+ toleranceSeconds?: number;+}++/**+ * Pure Standard Webhooks verification — no I/O, so it is directly testable and+ * reusable outside a `Request` (the smoke harness signs with+ * `signLinqWebhookPayload` and verifies with this).+ */+export const verifyLinqWebhookSignature = (+ options: LinqWebhookSignatureOptions,+): { ok: true } | { ok: false; reason: LinqWebhookSignatureFailure } => {+ const { body, headers, secret } = options;+ const { id, signature, timestamp } = headers;++ if (!id || !signature || !timestamp) return { ok: false, reason: 'missing-headers' };++ const tolerance = options.toleranceSeconds ?? LINQ_WEBHOOK_TOLERANCE_SECONDS;+ const sentAtSeconds = Number(timestamp);+ if (!Number.isFinite(sentAtSeconds)) return { ok: false, reason: 'invalid-signature' };++ const nowSeconds = Math.floor((options.now ?? Date.now()) / 1000);+ if (Math.abs(nowSeconds - sentAtSeconds) > tolerance) {+ return { ok: false, reason: 'timestamp-out-of-tolerance' };+ }++ const expected = signLinqWebhookPayload({ body, id, secret, timestamp }).split(',')[1];+ const expectedBytes = Buffer.from(expected);++ for (const entry of signature.split(' ')) {+ const [version, candidate] = entry.split(',');+ if (version !== 'v1' || !candidate) continue;++ const candidateBytes = Buffer.from(candidate);+ // Length check first: `timingSafeEqual` throws on a length mismatch, and a+ // mismatched length already proves the signature wrong.+ if (+ candidateBytes.length === expectedBytes.length &&+ timingSafeEqual(candidateBytes, expectedBytes)+ ) {+ return { ok: true };+ }+ }++ return { ok: false, reason: 'invalid-signature' };+};++// ---------------------------------------------------------------------------+// webhook-id de-duplication+// ---------------------------------------------------------------------------++/**+ * Claim store behind the deduplicator.+ *+ * `claim` must be atomic: return `true` exactly once per id, `false` for every+ * replay. In-process deployments get+ * `createInMemoryLinqWebhookDedupeStore`; a multi-instance deployment injects a+ * Redis-backed store (see the messenger platform's gate) so two webhook+ * workers cannot both accept the same delivery.+ */+export interface LinqWebhookDedupeStore {+ claim: (id: string, ttlSeconds: number) => Promise<boolean>;+}++export interface InMemoryLinqWebhookDedupeStoreOptions {+ /** Hard cap on tracked ids; oldest claims are evicted first. */+ maxEntries?: number;+ /** Injectable clock, in milliseconds. */+ now?: () => number;+}++/**+ * Bounded in-memory claim store.+ *+ * Webhook deliveries are bursty and short-lived, so a Map with lazy expiry and+ * an entry cap is enough for a single process and cannot grow without bound.+ */+export const createInMemoryLinqWebhookDedupeStore = (+ options: InMemoryLinqWebhookDedupeStoreOptions = {},+): LinqWebhookDedupeStore => {+ const maxEntries = options.maxEntries ?? 10_000;+ const now = options.now ?? Date.now;+ const claims = new Map<string, number>();++ return {+ async claim(id: string, ttlSeconds: number): Promise<boolean> {+ const current = now();+ const expiresAt = claims.get(id);+ if (expiresAt !== undefined && expiresAt > current) return false;++ // Opportunistic sweep: delivery rates are low enough that evicting on+ // claim keeps the map clean without a timer to leak.+ for (const [key, expiry] of claims) {+ if (expiry <= current) claims.delete(key);+ }++ while (claims.size >= maxEntries) {+ const oldest = claims.keys().next();+ if (oldest.done) break;+ claims.delete(oldest.value);+ }++ claims.set(id, current + ttlSeconds * 1000);+ return true;+ },+ };+};++/** Thin wrapper so callers read `isDuplicate(id)` instead of `!claim(id)`. */+export class LinqWebhookDeduplicator {+ constructor(+ private readonly store: LinqWebhookDedupeStore = createInMemoryLinqWebhookDedupeStore(),+ private readonly ttlSeconds: number = LINQ_WEBHOOK_ID_TTL_SECONDS,+ ) {}++ /** True when this `webhook-id` was already accepted (a Linq retry). */+ async isDuplicate(id: string): Promise<boolean> {+ return !(await this.store.claim(id, this.ttlSeconds));+ }+}++// ---------------------------------------------------------------------------+// Request-level gate+// ---------------------------------------------------------------------------++export type LinqWebhookGateResult =+ { event: LinqWebhookEvent; id: string; ok: true } | { ok: false; response: Response };++export interface LinqWebhookGateOptions {+ deduplicator?: LinqWebhookDeduplicator;+ now?: number;+ /** Raw body, when the caller already buffered it (otherwise it is read here). */+ rawBody?: string;+ signingSecret: string | undefined;+ toleranceSeconds?: number;+}++/**+ * Verify + de-duplicate one Linq webhook delivery.+ *+ * Order matters: signature first (never let an unauthenticated body touch the+ * dedupe store, or an attacker can burn ids and suppress real deliveries),+ * then the replay check.+ */+export const verifyLinqWebhookRequest = async (+ request: Request,+ options: LinqWebhookGateOptions,+): Promise<LinqWebhookGateResult> => {+ const { deduplicator, signingSecret } = options;++ if (!signingSecret) {+ return {+ ok: false,+ response: new Response('Linq webhook signing secret is not configured', { status: 503 }),+ };+ }++ const body = options.rawBody ?? (await request.text());+ const headers: LinqWebhookSignatureHeaders = {+ id: request.headers.get('webhook-id') ?? '',+ signature: request.headers.get('webhook-signature') ?? '',+ timestamp: request.headers.get('webhook-timestamp') ?? '',+ };++ const verified = verifyLinqWebhookSignature({+ body,+ headers,+ now: options.now,+ secret: signingSecret,+ toleranceSeconds: options.toleranceSeconds,+ });+ if (!verified.ok) {+ return {+ ok: false,+ response: new Response(`Invalid Linq webhook (${verified.reason})`, { status: 401 }),+ };+ }++ if (deduplicator && (await deduplicator.isDuplicate(headers.id))) {+ // 409, not 200: Linq stops retrying once it sees a definitive answer, and a+ // replay is a duplicate delivery — never a second inbound message.+ return { ok: false, response: new Response('Duplicate Linq webhook', { status: 409 }) };+ }++ let event: LinqWebhookEvent;+ try {+ event = JSON.parse(body) as LinqWebhookEvent;+ } catch {+ return { ok: false, response: new Response('Invalid JSON', { status: 400 }) };+ }++ if (!event || typeof event !== 'object' || typeof event.event_type !== 'string') {+ return { ok: false, response: new Response('Invalid Linq event', { status: 400 }) };+ }++ return { event, id: headers.id, ok: true };+};diff --git a/packages/agent-address-linq/tsconfig.json b/packages/agent-address-linq/tsconfig.jsonnew file mode 100644index 00000000000..5c90650b8ae--- /dev/null+++ b/packages/agent-address-linq/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/agent-address-linq/tsup.config.ts b/packages/agent-address-linq/tsup.config.tsnew file mode 100644index 00000000000..d4c69d1df67--- /dev/null+++ b/packages/agent-address-linq/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/agent-address-linq/vitest.config.mts b/packages/agent-address-linq/vitest.config.mtsnew file mode 100644index 00000000000..d28fa984095--- /dev/null+++ b/packages/agent-address-linq/vitest.config.mts@@ -0,0 +1,8 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ coverage: {},+ environment: 'node',+ },+});diff --git a/packages/agent-address-mail/package.json b/packages/agent-address-mail/package.jsonnew file mode 100644index 00000000000..d0e8e85435c--- /dev/null+++ b/packages/agent-address-mail/package.json@@ -0,0 +1,23 @@+{+ "name": "@lobechat/agent-address-mail",+ "version": "0.1.0",+ "description": "Agent Mail (lobe.id) transport behind an agent's own mail address",+ "type": "module",+ "exports": {+ ".": "./src/index.ts"+ },+ "files": [+ "dist"+ ],+ "scripts": {+ "build": "tsup",+ "clean": "rm -rf dist",+ "dev": "tsup --watch",+ "typecheck": "tsc --noEmit"+ },+ "devDependencies": {+ "@types/node": "^24.13.2",+ "tsup": "^8.5.1",+ "typescript": "^6.0.3"+ }+}diff --git a/packages/agent-address-mail/src/api.ts b/packages/agent-address-mail/src/api.tsnew file mode 100644index 00000000000..ff676a994b8--- /dev/null+++ b/packages/agent-address-mail/src/api.ts@@ -0,0 +1,274 @@+import { createHmac, timingSafeEqual } from 'node:crypto';++import type {+ EmailApiError,+ EmailInbox,+ EmailMessageDetail,+ EmailWebhook,+ EmailWebhookEvent,+} from './types';++export const DEFAULT_API_BASE_URL = 'https://api.lobe.id';++/** Default tolerance for the webhook signature timestamp — 5 minutes. */+export const DEFAULT_SIGNATURE_TOLERANCE_SECONDS = 300;++const hmacHex = (secret: string, payload: string) =>+ createHmac('sha256', secret).update(payload).digest('hex');++/**+ * Signature header format, per the Agent Mail docs:+ * `X-AgentMail-Signature: t=<unix seconds>,v1=<hex hmac-sha256 of "<t>.<body>">`.+ */+export const computeAgentMailSignature = (+ secret: string,+ body: string,+ timestamp: number,+): string => `t=${timestamp},v1=${hmacHex(secret, `${timestamp}.${body}`)}`;++export const parseAgentMailSignature = (+ header: string | null | undefined,+): { t: number; v1: string } | null => {+ if (!header) return null;+ const parts = new Map(+ header+ .split(',')+ .map((segment) => segment.split('='))+ .filter((pair): pair is [string, string] => pair.length === 2)+ .map(([key, value]) => [key.trim(), value.trim()]),+ );+ const rawTimestamp = parts.get('t');+ const v1 = parts.get('v1');+ if (!rawTimestamp || !v1) return null;+ const t = Number.parseInt(rawTimestamp, 10);+ if (!Number.isFinite(t)) return null;+ return { t, v1 };+};++/**+ * Verify a webhook delivery. Returns `false` (never throws) when the header is+ * malformed, the timestamp falls outside the tolerance window, or the HMAC+ * does not match — so the caller can answer 401 without leaking which check+ * failed.+ *+ * `now` is injectable for tests.+ */+export const verifyAgentMailSignature = (params: {+ body: string;+ header: string | null | undefined;+ now?: number;+ secret: string;+ toleranceSeconds?: number;+}): boolean => {+ const { body, header, secret } = params;+ if (!secret) return false;++ const parsed = parseAgentMailSignature(header);+ if (!parsed) return false;++ const now = Math.floor((params.now ?? Date.now()) / 1000);+ const tolerance = params.toleranceSeconds ?? DEFAULT_SIGNATURE_TOLERANCE_SECONDS;+ // Reject both stale and future-dated signatures — an attacker replaying or+ // pre-computing a timestamp must fall inside the same window as a retry.+ if (Math.abs(now - parsed.t) > tolerance) return false;++ const expected = Buffer.from(hmacHex(secret, `${parsed.t}.${body}`), 'utf8');+ const provided = Buffer.from(parsed.v1, 'utf8');+ if (expected.length !== provided.length) return false;+ return timingSafeEqual(expected, provided);+};++// Scanned rather than matched with `/\/+$/`: a regex anchored at the end+// backtracks polynomially on a slash-heavy string, and this runs on a+// caller-supplied base URL.+const stripTrailingSlashes = (url: string) => {+ let end = url.length;+ while (end > 0 && url[end - 1] === '/') end -= 1;+ return url.slice(0, end);+};++/**+ * Agent Mail REST client. Stateless and cheap to construct — every method+ * throws on a non-2xx response with the service's `{ error: { code, message } }`+ * envelope flattened into the message.+ */+export class LobeMailApiClient {+ readonly apiKey: string;+ readonly baseUrl: string;++ private readonly fetchImpl: typeof fetch;++ constructor(options: { apiKey: string; baseUrl?: string; fetchImpl?: typeof fetch }) {+ this.apiKey = options.apiKey;+ this.baseUrl = stripTrailingSlashes(options.baseUrl || DEFAULT_API_BASE_URL);+ this.fetchImpl = options.fetchImpl ?? fetch;+ }++ private async request<T>(path: string, init: RequestInit = {}): Promise<T> {+ const response = await this.fetchImpl(`${this.baseUrl}${path}`, {+ ...init,+ headers: {+ 'Authorization': `Bearer ${this.apiKey}`,+ 'Content-Type': 'application/json',+ ...init.headers,+ },+ });++ if (!response.ok) {+ const body = await response.text().catch(() => '');+ let detail = body;+ try {+ const parsed = JSON.parse(body) as EmailApiError;+ detail = parsed.error?.message || parsed.error?.code || body;+ } catch {+ // keep the raw body+ }+ throw new Error(+ `Agent Mail ${init.method ?? 'GET'} ${path} failed: ${response.status}${+ detail ? ` — ${detail}` : ''+ }`,+ );+ }++ if (response.status === 204) return undefined as T;+ return (await response.json()) as T;+ }++ // ---------------- Inboxes ----------------++ createInbox = (input: {+ clientId?: string;+ displayName?: string;+ endUserId?: string;+ metadata?: Record<string, unknown>;+ username?: string;+ }): Promise<EmailInbox> =>+ this.request<EmailInbox>('/v1/inboxes', { body: JSON.stringify(input), method: 'POST' });++ getInbox = (idOrAddress: string): Promise<EmailInbox> =>+ this.request<EmailInbox>(`/v1/inboxes/${encodeURIComponent(idOrAddress)}`);++ listInboxes = (params?: {+ clientId?: string;+ endUserId?: string;+ limit?: number;+ }): Promise<{ data: EmailInbox[] }> => {+ const query = new URLSearchParams();+ if (params?.clientId) query.set('clientId', params.clientId);+ if (params?.endUserId) query.set('endUserId', params.endUserId);+ if (params?.limit) query.set('limit', String(params.limit));+ const suffix = query.size > 0 ? `?${query.toString()}` : '';+ return this.request<{ data: EmailInbox[] }>(`/v1/inboxes${suffix}`);+ };++ deleteInbox = (idOrAddress: string): Promise<void> =>+ this.request<void>(`/v1/inboxes/${encodeURIComponent(idOrAddress)}`, { method: 'DELETE' });++ // ---------------- Webhooks ----------------++ createWebhook = (input: {+ events?: string[];+ inboxId?: string;+ url: string;+ }): Promise<EmailWebhook> =>+ this.request<EmailWebhook>('/v1/webhooks', { body: JSON.stringify(input), method: 'POST' });++ listWebhooks = (): Promise<{ data: EmailWebhook[] }> =>+ this.request<{ data: EmailWebhook[] }>('/v1/webhooks');++ deleteWebhook = (id: string): Promise<void> =>+ this.request<void>(`/v1/webhooks/${encodeURIComponent(id)}`, { method: 'DELETE' });++ // ---------------- Messages ----------------++ getMessage = (id: string): Promise<EmailMessageDetail> =>+ this.request<EmailMessageDetail>(`/v1/messages/${encodeURIComponent(id)}`);++ /**+ * Fetch the original `message/rfc822`. Used for loop protection: the JSON+ * message shape exposes no arbitrary headers, so `Auto-Submitted` /+ * `Precedence` / `List-Id` are only readable from the raw source.+ * Returns `null` instead of throwing — a missing raw body must not block+ * a legitimate inbound message.+ */+ getRawMessage = async (id: string): Promise<null | string> => {+ try {+ const response = await this.fetchImpl(+ `${this.baseUrl}/v1/messages/${encodeURIComponent(id)}/raw`,+ {+ headers: { Authorization: `Bearer ${this.apiKey}` },+ },+ );+ if (!response.ok) return null;+ return await response.text();+ } catch {+ return null;+ }+ };++ replyToMessage = (+ id: string,+ input: { html?: string; replyAll?: boolean; text?: string },+ ): Promise<EmailMessageDetail> =>+ this.request<EmailMessageDetail>(`/v1/messages/${encodeURIComponent(id)}/reply`, {+ body: JSON.stringify(input),+ method: 'POST',+ });++ /**+ * Download an attachment's bytes. Never throws — attachments are optional+ * context and a failure must not fail the whole inbound turn.+ */+ downloadAttachment = async (+ messageId: string,+ index: number,+ ): Promise<null | { buffer: Buffer; contentType?: string }> => {+ try {+ const response = await this.fetchImpl(+ `${this.baseUrl}/v1/messages/${encodeURIComponent(messageId)}/attachments/${index}`,+ { headers: { Authorization: `Bearer ${this.apiKey}` } },+ );+ if (!response.ok) return null;+ const bytes = Buffer.from(await response.arrayBuffer());+ return {+ buffer: bytes,+ contentType: response.headers.get('content-type') ?? undefined,+ };+ } catch {+ return null;+ }+ };++ sendMessage = (+ inboxId: string,+ input: { html?: string; subject: string; text?: string; to: string },+ ): Promise<EmailMessageDetail> =>+ this.request<EmailMessageDetail>(`/v1/inboxes/${encodeURIComponent(inboxId)}/messages`, {+ body: JSON.stringify(input),+ method: 'POST',+ });++ waitForMessage = (+ inboxId: string,+ params?: {+ from?: string;+ markRead?: boolean;+ since?: string;+ subject?: string;+ timeout?: number;+ },+ ): Promise<{ message: EmailMessageDetail | null; timedOut: boolean }> => {+ const query = new URLSearchParams();+ if (params?.from) query.set('from', params.from);+ if (params?.subject) query.set('subject', params.subject);+ if (params?.since) query.set('since', params.since);+ if (params?.timeout !== undefined) query.set('timeout', String(params.timeout));+ if (params?.markRead !== undefined) query.set('markRead', String(params.markRead));+ const suffix = query.size > 0 ? `?${query.toString()}` : '';+ return this.request<{ message: EmailMessageDetail | null; timedOut: boolean }>(+ `/v1/inboxes/${encodeURIComponent(inboxId)}/messages/wait${suffix}`,+ );+ };+}++export type { EmailMessageDetail as EmailMessage, EmailWebhookEvent };diff --git a/packages/agent-address-mail/src/index.ts b/packages/agent-address-mail/src/index.tsnew file mode 100644index 00000000000..653cb3ca2c8--- /dev/null+++ b/packages/agent-address-mail/src/index.ts@@ -0,0 +1,36 @@+/**+ * Agent Mail (lobe.id) transport — the provider behind an agent's own `mail`+ * address.+ *+ * This package knows only how to talk to Agent Mail and how to turn an email+ * into a normalized message: REST client, webhook signature verification, raw+ * header loop protection, quoted-history stripping, and markdown → HTML/text+ * rendering. It deliberately implements **no** chat-SDK adapter and carries no+ * platform identity/thread/typing semantics — an agent's address is its own,+ * not a bot inside someone else's platform.+ */+export {+ computeAgentMailSignature,+ DEFAULT_API_BASE_URL,+ DEFAULT_SIGNATURE_TOLERANCE_SECONDS,+ LobeMailApiClient,+ parseAgentMailSignature,+ verifyAgentMailSignature,+} from './api';+export {+ checkInboundEmail,+ type IgnoreDecision,+ type IgnoreReason,+ parseRawHeaders,+} from './loop-guard';+export { markdownToHtml, markdownToPlainText } from './markdown';+export { stripQuotedReply } from './quotes';+export type {+ EmailAddress,+ EmailInbox,+ EmailMessageDetail,+ EmailMessageSummary,+ EmailRawMessage,+ EmailWebhook,+ EmailWebhookEvent,+} from './types';diff --git a/packages/agent-address-mail/src/loop-guard.ts b/packages/agent-address-mail/src/loop-guard.tsnew file mode 100644index 00000000000..b215d7720a5--- /dev/null+++ b/packages/agent-address-mail/src/loop-guard.ts@@ -0,0 +1,111 @@+/**+ * Loop protection for inbound email.+ *+ * An agent that answers every arriving message will happily answer a vacation+ * autoresponder, a mailing-list blast, or the bounce notification its own+ * failed reply produced — and each of those answers produces another message.+ * The service exposes no arbitrary headers on the JSON message shape, so the+ * authoritative check runs against the raw `message/rfc822` source+ * (`GET /v1/messages/:id/raw`); address and subject heuristics cover the case+ * where the raw body is unavailable.+ */++const BOUNCE_SENDER = /^(?:mailer-daemon|mail-daemon|postmaster|mailer|bounce|no-?reply-bounces)@/i;++const BOUNCE_SUBJECT =+ /undelivered mail|delivery status notification|mail delivery (?:failed|failure)|returned mail|return to sender|failure notice|undeliverable|无法投递|投递失败|退信|傳送失敗/i;++const AUTO_REPLY_SUBJECT =+ /out of office|automatic repl|auto[- ]?repl|automatic response|auto[- ]?response|vacation|away from my (?:inbox|desk)|自动回复|自动答复|自动回覆|自动回信|休假|不在办公室/i;++/** Parse the header block of a raw RFC822 message into lower-cased keys. */+export const parseRawHeaders = (raw: string): Record<string, string> => {+ const headerBlock = raw.split(/\r?\n\r?\n/, 1)[0] ?? '';+ const headers: Record<string, string> = {};++ for (const line of headerBlock.split(/\r?\n/)) {+ if (/^[ \t]/.test(line)) {+ // Folded continuation of the previous header.+ const keys = Object.keys(headers);+ const last = keys.at(-1);+ if (last) headers[last] = `${headers[last]} ${line.trim()}`;+ continue;+ }+ const separator = line.indexOf(':');+ if (separator <= 0) continue;+ const key = line.slice(0, separator).trim().toLowerCase();+ const value = line.slice(separator + 1).trim();+ headers[key] = headers[key] ? `${headers[key]}, ${value}` : value;+ }++ return headers;+};++export type IgnoreReason =+ | 'auto_reply'+ | 'auto_response_suppress'+ | 'auto_submitted'+ | 'bounce'+ | 'mailing_list'+ | 'precedence_bulk'+ | 'self_addressed';++export interface IgnoreDecision {+ ignored: boolean;+ reason?: IgnoreReason;+}++/**+ * Decide whether an inbound message must not be handed to the agent.+ * `headers` may be `null` when the raw body could not be fetched — the+ * address/subject heuristics still apply.+ */+export const checkInboundEmail = (params: {+ from: string;+ headers?: Record<string, string> | null;+ inboxAddress?: string;+ subject?: null | string;+}): IgnoreDecision => {+ const { from, headers } = params;+ const subject = params.subject ?? '';++ if (params.inboxAddress && from && from.toLowerCase() === params.inboxAddress.toLowerCase()) {+ return { ignored: true, reason: 'self_addressed' };+ }++ if (BOUNCE_SENDER.test(from)) return { ignored: true, reason: 'bounce' };+ if (BOUNCE_SUBJECT.test(subject)) return { ignored: true, reason: 'bounce' };++ if (headers) {+ // RFC 3834: a legitimate automatic reply announces itself here. Anything+ // other than an explicit `no` means the message must not be answered.+ const autoSubmitted = headers['auto-submitted'];+ if (autoSubmitted && autoSubmitted.trim().toLowerCase() !== 'no') {+ return { ignored: true, reason: 'auto_submitted' };+ }++ const precedence = headers['precedence']?.trim().toLowerCase();+ if (precedence && ['bulk', 'junk', 'list'].includes(precedence)) {+ return { ignored: true, reason: 'precedence_bulk' };+ }++ if (headers['x-auto-response-suppress']) {+ return { ignored: true, reason: 'auto_response_suppress' };+ }++ // Mailing lists: replies would be broadcast to every subscriber.+ if (headers['list-id'] || headers['list-post']) {+ return { ignored: true, reason: 'mailing_list' };+ }++ // `Return-Path: <>` marks a bounce (the envelope sender is null).+ const returnPath = headers['return-path'];+ if (returnPath !== undefined && /^<\s*>$/.test(returnPath.trim())) {+ return { ignored: true, reason: 'bounce' };+ }+ }++ if (AUTO_REPLY_SUBJECT.test(subject)) return { ignored: true, reason: 'auto_reply' };++ return { ignored: false };+};diff --git a/packages/agent-address-mail/src/markdown.ts b/packages/agent-address-mail/src/markdown.tsnew file mode 100644index 00000000000..0c5014572ae--- /dev/null+++ b/packages/agent-address-mail/src/markdown.ts@@ -0,0 +1,216 @@+/**+ * Minimal Markdown → HTML / plain-text rendering for outbound email.+ *+ * The adapter deliberately avoids pulling a Markdown pipeline into a package+ * that also runs in the browser-safe layer: outbound replies only need the+ * small subset the agent actually emits (headings, lists, code, links,+ * emphasis, quotes, rules). Unknown syntax degrades to escaped text.+ *+ * Both outputs are derived from the same token walk so the HTML and the text+ * alternative never disagree about the content.+ */++const escapeHtml = (input: string) =>+ input+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"')+ .replaceAll("'", ''');++/** Inline spans. `href`-carrying rules run before emphasis so `*` inside a URL survives. */+const renderInline = (input: string): string => {+ let out = escapeHtml(input);++ out = out.replaceAll(/`([^`]+)`/g, (_, code: string) => `<code>${code}</code>`);+ out = out.replaceAll(+ /\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g,+ (_, label: string, href: string) => `<a href="${href}" rel="noreferrer noopener">${label}</a>`,+ );+ out = out.replaceAll(+ /(?<!["'>=])(https?:\/\/[^\s<]+)/g,+ (href: string) => `<a href="${href}" rel="noreferrer noopener">${href}</a>`,+ );+ out = out.replaceAll(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');+ out = out.replaceAll(/__([^_]+)__/g, '<strong>$1</strong>');+ out = out.replaceAll(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');+ out = out.replaceAll(/(^|[\s(])_([^_\n]+)_(?=[\s).,!?:;]|$)/g, '$1<em>$2</em>');++ return out;+};++/** Same walk as `renderInline`, minus tags — the `text/plain` alternative. */+const renderInlineText = (input: string): string =>+ input+ .replaceAll(/`([^`]+)`/g, '$1')+ .replaceAll(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '$1 ($2)')+ .replaceAll(/\*\*([^*]+)\*\*/g, '$1')+ .replaceAll(/__([^_]+)__/g, '$1')+ .replaceAll(/(^|[\s(])\*([^*\n]+)\*(?=[\s).,!?:;]|$)/g, '$1$2')+ .replaceAll(/(^|[\s(])_([^_\n]+)_(?=[\s).,!?:;]|$)/g, '$1$2');++interface Block {+ kind: 'code' | 'heading' | 'hr' | 'list' | 'paragraph' | 'quote';+ level?: number;+ lines: string[];+ ordered?: boolean;+}++const BLOCK_START = /^(?:#{1,6}\s|```|---|\*\*\*|>\s?|\s*(?:[-*+]|\d+[.)])\s)/;++/** Split into block tokens; consecutive non-block lines merge into one paragraph. */+const tokenize = (markdown: string): Block[] => {+ const lines = markdown.replaceAll('\r\n', '\n').split('\n');+ const blocks: Block[] = [];+ let index = 0;++ while (index < lines.length) {+ const line = lines[index]!;++ if (line.trimStart().startsWith('```')) {+ const code: string[] = [];+ index += 1;+ while (index < lines.length && !lines[index]!.trimStart().startsWith('```')) {+ code.push(lines[index]!);+ index += 1;+ }+ index += 1; // closing fence+ blocks.push({ kind: 'code', lines: code });+ continue;+ }++ if (/(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line.trim())) {+ blocks.push({ kind: 'hr', lines: [] });+ index += 1;+ continue;+ }++ const heading = /^(#{1,6})(.*)$/.exec(line);+ const headingRest = heading?.[2] ?? '';+ if (+ heading &&+ (headingRest === '' || headingRest.startsWith(' ') || headingRest.startsWith('\t'))+ ) {+ blocks.push({+ kind: 'heading',+ level: heading[1]!.length,+ lines: [headingRest.trim()],+ });+ index += 1;+ continue;+ }++ if (/^\s*>\s?/.test(line)) {+ const quote: string[] = [];+ while (index < lines.length && /^\s*>\s?/.test(lines[index]!)) {+ quote.push(lines[index]!.replace(/^\s*>\s?/, ''));+ index += 1;+ }+ blocks.push({ kind: 'quote', lines: quote });+ continue;+ }++ if (/^\s*(?:[-*+]|\d+[.)])\s+/.test(line)) {+ const ordered = /^\s*\d+[.)]\s+/.test(line);+ const items: string[] = [];+ while (index < lines.length && /^\s*(?:[-*+]|\d+[.)])\s+/.test(lines[index]!)) {+ items.push(lines[index]!.replace(/^\s*(?:[-*+]|\d+[.)])\s+/, ''));+ index += 1;+ }+ blocks.push({ kind: 'list', lines: items, ordered });+ continue;+ }++ if (line.trim() === '') {+ index += 1;+ continue;+ }++ const paragraph: string[] = [];+ while (+ index < lines.length &&+ lines[index]!.trim() !== '' &&+ !BLOCK_START.test(lines[index]!)+ ) {+ paragraph.push(lines[index]!);+ index += 1;+ }+ blocks.push({ kind: 'paragraph', lines: paragraph });+ }++ return blocks;+};++/** Ordered vs unordered comes from the `ordered` flag recorded while tokenizing. */+export const markdownToHtml = (markdown: string): string => {+ const blocks = tokenize(markdown);+ const parts: string[] = [];++ for (const block of blocks) {+ switch (block.kind) {+ case 'code': {+ parts.push(`<pre><code>${escapeHtml(block.lines.join('\n'))}</code></pre>`);+ break;+ }+ case 'heading': {+ const level = block.level ?? 1;+ parts.push(`<h${level}>${renderInline(block.lines[0] ?? '')}</h${level}>`);+ break;+ }+ case 'hr': {+ parts.push('<hr />');+ break;+ }+ case 'list': {+ const tag = block.ordered ? 'ol' : 'ul';+ const items = block.lines.map((item) => `<li>${renderInline(item)}</li>`).join('');+ parts.push(`<${tag}>${items}</${tag}>`);+ break;+ }+ case 'quote': {+ parts.push(`<blockquote>${renderInline(block.lines.join('\n'))}</blockquote>`);+ break;+ }+ default: {+ parts.push(`<p>${renderInline(block.lines.join('\n'))}</p>`);+ }+ }+ }++ return parts.join('\n');+};++export const markdownToPlainText = (markdown: string): string => {+ const blocks = tokenize(markdown);+ const parts: string[] = [];++ for (const block of blocks) {+ switch (block.kind) {+ case 'code': {+ parts.push(block.lines.join('\n'));+ break;+ }+ case 'heading': {+ parts.push(renderInlineText(block.lines[0] ?? ''));+ break;+ }+ case 'hr': {+ parts.push('---');+ break;+ }+ case 'list': {+ parts.push(block.lines.map((item) => `- ${renderInlineText(item)}`).join('\n'));+ break;+ }+ case 'quote': {+ parts.push(block.lines.map((line) => `> ${renderInlineText(line)}`).join('\n'));+ break;+ }+ default: {+ parts.push(renderInlineText(block.lines.join('\n')));+ }+ }+ }++ return parts.join('\n\n').trim();+};diff --git a/packages/agent-address-mail/src/quotes.ts b/packages/agent-address-mail/src/quotes.tsnew file mode 100644index 00000000000..667af4769ae--- /dev/null+++ b/packages/agent-address-mail/src/quotes.ts@@ -0,0 +1,130 @@+/**+ * Strip the quoted history and signature out of an inbound mail body.+ *+ * Inbound mail is a *thread*: the raw body repeats every previous reply.+ * Feeding that to the agent wastes context and — worse — re-reads the agent's+ * own earlier answer as if the user had just said it again. We cut the body at+ * the first reply-attribution marker the common clients emit, then drop+ * `>`-prefixed blocks and the `-- ` signature.+ *+ * When the whole body is quoting (a bare "thanks!" reply that only kept the+ * history, or a reply sent from a client that quotes first) the stripped text+ * would be empty — an empty user turn is useless, so we fall back to the+ * original body.+ */++/**+ * Attribution markers, one per client idiom.+ *+ * The wildcards between the fixed parts are bounded on purpose. An unbounded+ * `[^\n]*?` on either side of a literal makes the engine backtrack+ * polynomially on a hostile body (one long line repeating the literal), and+ * this runs on attacker-supplied mail. Real attribution lines are a date plus+ * a name plus a verb, comfortably inside the bound.+ */+const ATTRIBUTION_PATTERNS: RegExp[] = [+ // English clients: "On Mon, 1 Jan 2026 at 10:00, Jane <[email protected]> wrote:"+ /^\s*On\b[^\n]{1,300}wrote:\s*$/im,+ // Outlook / Thunderbird separators+ /^\s*-{2,}[ \t]*Original Message[ \t]*-{2,}\s*$/im,+ /^\s*_{10,}\s*$/m,+ /^\s*From:\s*(?:\S.*|[\t\v\f \xA0\u1680\u2000-\u200A\u202F\u205F\u3000\uFEFF])$/im,+ // Chinese clients+ /^\s*在[^\n]{0,300}?写道[::]\s*$/m,+ /^\s*在[^\n]{0,300}?wrote:\s*$/im,+ /^\s*(?:发件人|寄件者|发信人)[::]/m,+ /^\s*-{2,}[ \t]*(?:原始邮件|转发邮件|回复邮件)[ \t]*-{2,}\s*$/m,+ // Apple Mail+ /^\s*Begin forwarded message:\s*$/im,+ /^\s*Am [^\n]{0,300}?schrieb [^\n]{0,300}?:\s*$/im,+ /^\s*El [^\n]{0,300}?escribió:\s*$/im,+];++/**+ * A `From:` line alone is not enough — a plain text body may legitimately+ * start that way. Only treat it as an Outlook header block when the next few+ * lines look like the rest of the header set.+ */+const hasAddressHeaderBlock = (lines: string[]): boolean =>+ lines.some((line, index) => {+ if (!/^\s*From:\s*\S/.test(line)) return false;+ return lines+ .slice(index, index + 4)+ .some((next) => /^\s*(?:Sent|To|Subject|Date|发送时间|收件人|主题)[::]/.test(next));+ });++const cutAtAttribution = (text: string): string => {+ const lines = text.split('\n');+ if (hasAddressHeaderBlock(lines)) {+ const index = lines.findIndex((line) => /^\s*From:\s*\S/.test(line));+ if (index > 0) return lines.slice(0, index).join('\n');+ }++ for (const pattern of ATTRIBUTION_PATTERNS) {+ const match = pattern.exec(text);+ if (!match || match.index === 0) continue;+ return text.slice(0, match.index);+ }++ return text;+};++const dropQuotedAndSignature = (text: string): string => {+ const lines = text.split('\n');+ const kept: string[] = [];++ for (const line of lines) {+ // `-- ` on its own line starts the signature (RFC 3676).+ if (/^--\s*$/.test(line)) break;+ if (/^\s*>/.test(line)) continue;+ kept.push(line);+ }++ return kept.join('\n');+};++// A linear string pass rather than `/[ \t]+\n/` + `/\n{3,}/`: both regexes+// backtrack polynomially on a body full of tabs or newlines, and the body is+// attacker-supplied. The result is unchanged — trailing spaces/tabs are+// dropped per line and a run of blank lines collapses to a single one.+const collapseBlankLines = (text: string) => {+ const kept: string[] = [];+ let blankRun = 0;++ for (const rawLine of text.split('\n')) {+ let end = rawLine.length;+ while (end > 0 && (rawLine[end - 1] === ' ' || rawLine[end - 1] === '\t')) end -= 1;+ const line = rawLine.slice(0, end);++ if (line === '') {+ blankRun += 1;+ if (blankRun > 1) continue;+ } else {+ blankRun = 0;+ }++ kept.push(line);+ }++ return kept.join('\n').trim();+};++/** A line that only announces the quoted block, carrying no content itself. */+const isAttributionLine = (line: string) => {+ const trimmed = line.trim();+ if (!trimmed || /^--$/.test(trimmed)) return true;+ return ATTRIBUTION_PATTERNS.some((pattern) => new RegExp(pattern.source, 'i').test(trimmed));+};++export const stripQuotedReply = (body: string): string => {+ const trimmed = (body ?? '').trim();+ if (!trimmed) return '';++ const stripped = collapseBlankLines(dropQuotedAndSignature(cutAtAttribution(trimmed)));++ // Quote-only mail (a bare "thanks!" that kept the whole history, or a client+ // that quotes before writing) leaves nothing but the attribution line. Hand+ // the original body over rather than an empty or attribution-only turn.+ const hasContent = stripped.split('\n').some((line) => !isAttributionLine(line));+ return hasContent ? stripped : trimmed;+};diff --git a/packages/agent-address-mail/src/types.ts b/packages/agent-address-mail/src/types.tsnew file mode 100644index 00000000000..0373c795bb5--- /dev/null+++ b/packages/agent-address-mail/src/types.ts@@ -0,0 +1,137 @@+/**+ * Types for the Agent Mail (`lobe.id`) email adapter.+ *+ * The service is documented at https://api.lobe.id — an agent owns one inbox+ * (`[email protected]`) and receives mail through a signed webhook. The+ * webhook payload deliberately carries only a *summary*: the body must be+ * fetched back through `GET /v1/messages/:id`.+ */++/** Address object as the API serialises sender/recipients. */+export interface EmailAddress {+ address: string;+ name?: string;+}++/** Message summary — the shape embedded in a `message.received` webhook event. */+export interface EmailMessageSummary {+ attachments: Array<{+ contentType?: string;+ filename?: string | null;+ index: number;+ size?: number;+ }>;+ /** Verification codes extracted by the service, best first. */+ codes: string[];+ direction: 'inbound' | 'outbound';+ from: EmailAddress | null;+ id: string;+ inboxId: string;+ /** Verification / magic links extracted by the service. */+ links: string[];+ read: boolean;+ receivedAt: string;+ snippet: string | null;+ status: string;+ subject: string | null;+ to: EmailAddress[];+}++/** Full message — `GET /v1/messages/:id`. */+export interface EmailMessageDetail extends EmailMessageSummary {+ bcc: EmailAddress[];+ cc: EmailAddress[];+ envelope: { from: string | null; to: string | null };+ error: string | null;+ html: string | null;+ inReplyTo: string | null;+ messageId: string | null;+ references: string[];+ replyTo: EmailAddress[];+ size: number;+ text: string | null;+}++export interface EmailInbox {+ address: string;+ clientId: string | null;+ createdAt: string;+ displayName: string | null;+ endUserId: string | null;+ id: string;+ metadata: Record<string, unknown>;+}++export interface EmailWebhook {+ createdAt: string;+ enabled: boolean;+ events: string[];+ id: string;+ inboxId: string | null;+ /** Only present in the creation response. */+ secret?: string;+ url: string;+}++/** Webhook envelope. `id` is stable for a delivery attempt series (retries reuse it). */+export interface EmailWebhookEvent {+ createdAt: string;+ data: {+ inbox: { address: string; clientId: string | null; id: string };+ message: EmailMessageSummary;+ };+ id: string;+ type: 'message.received';+}++/** chat-sdk thread identity: `email:<threadKey>`. */+export interface EmailThreadId {+ /** Root conversation key — the first `References` entry, else the message id. */+ id: string;+}++/**+ * Raw inbound payload handed to `Message.raw`. Carries the summary plus the+ * resolved thread/body so the server-side client can download attachments+ * without a second round trip to the webhook payload.+ */+export interface EmailRawMessage {+ /** Webhook envelope this inbound message came from (absent on outbound). */+ event?: EmailWebhookEvent;+ message: EmailMessageSummary;+ /** Body with the quoted history stripped. */+ text: string;+ threadKey: string;+}++/** Per-thread outbound state, shared between the adapter and the platform client. */+export interface EmailThreadRecord {+ /** Sender we reply to (Reply-To unless the mail was a bulk send). */+ from: string;+ /** Message id the next reply should thread under. */+ lastMessageId: string;+ subject: string | null;+}++export interface EmailAdapterConfig {+ /** The inbox address, used to detect self-addressed mail. */+ address?: string;+ apiBaseUrl?: string;+ /** Agent Mail API key (`am_…`). */+ apiKey: string;+ /** Injectable fetch, for tests. */+ fetchImpl?: typeof fetch;+ /** Inbox id (`inb_…`) — reply target and `POST /v1/inboxes/:id/messages` owner. */+ inboxId?: string;+ /** Reject webhook timestamps older than this, in seconds. Default 300 (5 min). */+ signatureToleranceSeconds?: number;+ /** Shared thread state so outbound replies land in the right thread. */+ threadState?: Map<string, EmailThreadRecord>;+ userName?: string;+ /** Webhook signing secret, returned once by `POST /v1/webhooks`. */+ webhookSecret: string;+}++export interface EmailApiError {+ error?: { code?: string; message?: string };+}diff --git a/packages/agent-address-mail/src/units.test.ts b/packages/agent-address-mail/src/units.test.tsnew file mode 100644index 00000000000..abf3fbd3ca2--- /dev/null+++ b/packages/agent-address-mail/src/units.test.ts@@ -0,0 +1,253 @@+import { describe, expect, it, vi } from 'vitest';++import {+ computeAgentMailSignature,+ LobeMailApiClient,+ parseAgentMailSignature,+ verifyAgentMailSignature,+} from './api';+import { checkInboundEmail, parseRawHeaders } from './loop-guard';+import { markdownToHtml, markdownToPlainText } from './markdown';+import { stripQuotedReply } from './quotes';++describe('signature helpers', () => {+ const secret = 'whsec_abc';+ const body = '{"id":"evt_1"}';+ const now = 1_767_000_000_000;++ it('round-trips compute → verify inside the tolerance window', () => {+ const header = computeAgentMailSignature(secret, body, Math.floor(now / 1000));+ expect(verifyAgentMailSignature({ body, header, now, secret })).toBe(true);+ });++ it('rejects a body that was modified after signing', () => {+ const header = computeAgentMailSignature(secret, body, Math.floor(now / 1000));+ expect(verifyAgentMailSignature({ body: `${body} `, header, now, secret })).toBe(false);+ });++ it('rejects a signature from another secret', () => {+ const header = computeAgentMailSignature('other', body, Math.floor(now / 1000));+ expect(verifyAgentMailSignature({ body, header, now, secret })).toBe(false);+ });++ it('rejects a timestamp older than 5 minutes', () => {+ const header = computeAgentMailSignature(secret, body, Math.floor(now / 1000) - 301);+ expect(verifyAgentMailSignature({ body, header, now, secret })).toBe(false);+ const fresh = computeAgentMailSignature(secret, body, Math.floor(now / 1000) - 299);+ expect(verifyAgentMailSignature({ body, header: fresh, now, secret })).toBe(true);+ });++ it('returns null for malformed headers instead of throwing', () => {+ expect(parseAgentMailSignature(null)).toBeNull();+ expect(parseAgentMailSignature('garbage')).toBeNull();+ expect(parseAgentMailSignature('t=abc,v1=zz')).toBeNull();+ expect(verifyAgentMailSignature({ body, header: 'nope', now, secret })).toBe(false);+ });+});++describe('LobeMailApiClient', () => {+ it('surfaces the service error envelope on a non-2xx response', async () => {+ const fetchImpl = vi.fn(async () =>+ Response.json({ error: { code: 'not_found', message: 'Inbox not found' } }, { status: 404 }),+ ) as unknown as typeof fetch;++ const client = new LobeMailApiClient({ apiKey: 'am_x', fetchImpl });+ await expect(client.getInbox('inb_missing')).rejects.toThrow(/404 — Inbox not found/);+ });++ it('creates an inbox and registers a webhook with the bearer key', async () => {+ const calls: Array<{ body?: string; url: string }> = [];+ const fetchImpl = vi.fn(async (input: any, init: any) => {+ calls.push({ body: init?.body, url: String(input) });+ if (String(input).endsWith('/v1/inboxes')) {+ return Response.json({ address: '[email protected]', id: 'inb_1' }, { status: 201 });+ }+ return Response.json({ id: 'whk_1', secret: 'whsec_1' }, { status: 201 });+ }) as unknown as typeof fetch;++ const client = new LobeMailApiClient({+ apiKey: 'am_x',+ baseUrl: 'https://api.lobe.id',+ fetchImpl,+ });+ const inbox = await client.createInbox({ clientId: 'agt_1', endUserId: 'user:u1' });+ const hook = await client.createWebhook({+ inboxId: inbox.id,+ url: 'https://app.example.com/api/agent/webhooks/email/inb_1',+ });++ expect(inbox.id).toBe('inb_1');+ expect(hook.secret).toBe('whsec_1');+ expect(JSON.parse(calls[0]!.body!)).toEqual({ clientId: 'agt_1', endUserId: 'user:u1' });+ expect(calls[1]!.url).toBe('https://api.lobe.id/v1/webhooks');+ });++ it('long-polls the wait endpoint with the from / timeout filters', async () => {+ let seen = '';+ const fetchImpl = vi.fn(async (input: any) => {+ seen = String(input);+ return Response.json({ message: { codes: ['839201'] }, timedOut: false });+ }) as unknown as typeof fetch;++ const client = new LobeMailApiClient({+ apiKey: 'am_x',+ baseUrl: 'https://api.lobe.id',+ fetchImpl,+ });+ const result = await client.waitForMessage('inb_1', { from: 'github', timeout: 30 });++ expect(seen).toContain('/v1/inboxes/inb_1/messages/wait');+ expect(seen).toContain('from=github');+ expect(seen).toContain('timeout=30');+ expect(result.timedOut).toBe(false);+ });++ it('normalizes a slash-heavy base URL without a regex backtrack', async () => {+ let seen = '';+ const fetchImpl = vi.fn(async (input: any) => {+ seen = String(input);+ return Response.json({ address: '[email protected]', id: 'inb_1' });+ }) as unknown as typeof fetch;++ const client = new LobeMailApiClient({+ apiKey: 'am_x',+ baseUrl: `https://api.lobe.id${'/'.repeat(50_000)}`,+ fetchImpl,+ });++ // Every trailing slash is dropped, exactly once, and the request still runs.+ expect(client.baseUrl).toBe('https://api.lobe.id');+ await client.getInbox('inb_1');+ expect(seen).toBe('https://api.lobe.id/v1/inboxes/inb_1');+ });+});++describe('markdown rendering', () => {+ it('renders headings, lists, code and inline emphasis', () => {+ const html = markdownToHtml(+ '# Title\n\nSome **bold** and `code`.\n\n- one\n- two\n\n```\nraw <tag>\n```',+ );+ expect(html).toContain('<h1>Title</h1>');+ expect(html).toContain('<strong>bold</strong>');+ expect(html).toContain('<code>code</code>');+ expect(html).toContain('<ul><li>one</li><li>two</li></ul>');+ // Code fences are escaped, never injected as markup.+ expect(html).toContain('<pre><code>raw <tag></code></pre>');+ });++ it('escapes raw HTML in the body', () => {+ expect(markdownToHtml('<script>alert(1)</script>')).toContain('<script>');+ });++ it('produces a readable plain-text alternative', () => {+ const text = markdownToPlainText('# Title\n\nSee [docs](https://lobehub.com)\n\n1. first');+ expect(text).toContain('Title');+ expect(text).toContain('See docs (https://lobehub.com)');+ expect(text).toContain('- first');+ });++ it('renders ordered lists as <ol>', () => {+ expect(markdownToHtml('1. a\n2. b')).toContain('<ol><li>a</li><li>b</li></ol>');+ });+});++describe('quoted reply stripping', () => {+ it('cuts an English "On ... wrote:" block', () => {+ const body =+ 'Yes, that works.\n\nOn Mon, Sep 29, 2026 at 10:00 Jane <[email protected]> wrote:\n> quote';+ expect(stripQuotedReply(body)).toBe('Yes, that works.');+ });++ it('removes Outlook header blocks and signature separators', () => {+ const body = 'Confirmed.\n\n-- \nArvin\n\nFrom: Jane\nSent: Monday\nTo: Arvin\nSubject: hi';+ expect(stripQuotedReply(body)).toBe('Confirmed.');+ });++ it('keeps the original body for a quote-only reply', () => {+ const body = 'On Mon, Sep 29, 2026 at 10:00 Jane <[email protected]> wrote:\n> only history here';+ expect(stripQuotedReply(body)).toBe(body);+ });++ it('drops only `>`-quoted lines when there is no attribution line', () => {+ expect(stripQuotedReply('New answer\n> old\n>> older')).toBe('New answer');+ });++ it('collapses blank runs and trailing whitespace without a regex backtrack', () => {+ expect(stripQuotedReply('line one \n\n\n\n\nline two\t\n')).toBe('line one\n\nline two');+ });++ it('handles a hostile body without pathological backtracking', () => {+ const repeats = 100_000;+ // Shapes that made the previous forms backtrack polynomially:+ // - a line repeating an attribution keyword, with no closing `:` for the+ // unbounded `[^\n]*?` wildcards to settle on;+ // - a long run of tabs *not* followed by a newline, for `[ \t]+\n`;+ // - a long run of newlines, for `\n{3,}`.+ const hostile = [+ `Am ${'schrieb '.repeat(repeats)}`,+ '在 '.repeat(repeats),+ `${'\t'.repeat(repeats)}x`,+ '\n'.repeat(repeats),+ ].join('\n');++ const started = performance.now();+ const result = stripQuotedReply(hostile);+ const elapsed = performance.now() - started;++ expect(typeof result).toBe('string');+ // Linear work finishes in milliseconds; the quadratic forms took seconds+ // on input an order of magnitude smaller.+ expect(elapsed).toBeLessThan(2000);+ });+});++describe('loop protection', () => {+ it('parses folded headers and lower-cases keys', () => {+ const headers = parseRawHeaders('From: [email protected]\r\nSubject: one\r\n two\r\nX-Y: z\r\n\r\nbody');+ expect(headers.from).toBe('[email protected]');+ expect(headers.subject).toBe('one two');+ expect(headers['x-y']).toBe('z');+ });++ const base = { from: '[email protected]', subject: 'Hello' };++ it('ignores auto-submitted / bulk / list mail from headers', () => {+ expect(checkInboundEmail({ ...base, headers: { 'auto-submitted': 'auto-generated' } })).toEqual(+ {+ ignored: true,+ reason: 'auto_submitted',+ },+ );+ expect(checkInboundEmail({ ...base, headers: { precedence: 'Bulk' } }).reason).toBe(+ 'precedence_bulk',+ );+ expect(checkInboundEmail({ ...base, headers: { 'list-id': '<x.lists>' } }).reason).toBe(+ 'mailing_list',+ );+ expect(+ checkInboundEmail({ ...base, headers: { 'x-auto-response-suppress': 'All' } }).reason,+ ).toBe('auto_response_suppress');+ });++ it('accepts an explicit Auto-Submitted: no', () => {+ expect(checkInboundEmail({ ...base, headers: { 'auto-submitted': 'no' } }).ignored).toBe(false);+ });++ it('treats a null envelope sender as a bounce', () => {+ expect(checkInboundEmail({ ...base, headers: { 'return-path': '<>' } }).reason).toBe('bounce');+ });++ it('still works when the raw headers could not be fetched', () => {+ expect(checkInboundEmail({ ...base, headers: null }).ignored).toBe(false);+ expect(+ checkInboundEmail({ ...base, headers: null, subject: 'Out of office: automatic reply' })+ .reason,+ ).toBe('auto_reply');+ });++ it('ignores mail addressed from the inbox itself', () => {+ expect(+ checkInboundEmail({ from: '[email protected]', inboxAddress: '[email protected]', subject: 'x' }).reason,+ ).toBe('self_addressed');+ });+});diff --git a/packages/agent-address-mail/tsconfig.json b/packages/agent-address-mail/tsconfig.jsonnew file mode 100644index 00000000000..5c90650b8ae--- /dev/null+++ b/packages/agent-address-mail/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/agent-address-mail/tsup.config.ts b/packages/agent-address-mail/tsup.config.tsnew file mode 100644index 00000000000..d4c69d1df67--- /dev/null+++ b/packages/agent-address-mail/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/agent-address-mail/vitest.config.mts b/packages/agent-address-mail/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/agent-address-mail/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});