π€― 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-identity): land the AgentAccount service and provider registry skeleton (#20289)
Arvin Xu400d6f1ebc4f
diff --git a/.env.example b/.env.exampleindex ae6934c83c6..33e898ada5f 100644--- a/.env.example+++ b/.env.example@@ -536,3 +536,28 @@ OPENAI_API_KEY=sk-xxxxxxxxx# Leave unset to keep official lobehub.com links, even when MARKET_BASE_URL is configured.# This does not change the Market API endpoint or authentication.# MARKET_SKILL_INSTALL_BASE_URL=https://market.example.com++# ---------------------------------------------------------------------------+# Agent Identity providers (an agent's own mail address / phone number)+#+# Both providers are optional and independent: a deployment may run one, both,+# or neither. Accounts provisioned from them land in `agent_accounts`; a+# missing key only means that provider is not registered.+#+# Agent Mail (lobe.id) β gives an agent its own inbox (`[email protected]`).+# The tenant key (`am_β¦`) comes from the lobe.id console. When+# AGENT_MAIL_WEBHOOK_URL is set, provisioning registers the webhook and stores+# the returned per-inbox secret as that account's credential.+# AGENT_MAIL_API_KEY=am_xxxxxxxxxxxxx+# AGENT_MAIL_API_BASE_URL=https://api.lobe.id+# AGENT_MAIL_WEBHOOK_URL=https://yourdomain.com/api/agent/accounts/webhooks/agent-mail+# AGENT_MAIL_WEBHOOK_SECRET=xxxxxxxxxxxxxxxxxxxxxxxxxxxxx+#+# Linq (iMessage / SMS) β gives an agent a phone number on LobeHub's carrier+# account. Linq numbers are carrier inventory rather than something the REST API+# mints, so LINQ_FROM_NUMBER is the operator's number pool (comma-separated);+# each number backs one live phone account.+# LINQ_API_KEY=linq_xxxxxxxxxxxxx+# LINQ_API_BASE_URL=https://api.linqapp.com/v3+# LINQ_FROM_NUMBER=+15550000000,+15550000001+# LINQ_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxdiff --git a/apps/server/src/modules/Redis/keys.ts b/apps/server/src/modules/Redis/keys.tsindex 93d0ddb09fd..e4bd2243179 100644--- a/apps/server/src/modules/Redis/keys.ts+++ b/apps/server/src/modules/Redis/keys.ts@@ -25,6 +25,11 @@ export const RedisKeyNamespace = {* drains them into the next turn itself when the running one hands back.*/AGENT_STEER: 'agentSteer',+ /**+ * Agent identity keys β replay claims for agent-account provider webhooks,+ * shared by every instance that may receive a delivery.+ */+ AGENT_IDENTITY: 'agent-identity',/*** Bot-wake channel state: when the bot and its owner last spoke, the follow-up window, the* silent-wake budget and the per-channel wake scheduler.@@ -175,6 +180,17 @@ export const RedisKeys = {*/threadStartFence: (threadId: string): string => `thread_start:v1:${threadId}`,},+ /**+ * Agent identity scope β see {@link RedisKeyNamespace.AGENT_IDENTITY}.+ */+ agentIdentity: {+ /**+ * Replay claim on one provider webhook delivery.+ * Full key: agent-identity:webhook_event:v1:{provider}:{eventId}+ */+ webhookEvent: (provider: string, eventId: string): string =>+ `webhook_event:v1:${provider}:${eventId}`,+ },/*** AI generation scope - for AI-generated content like welcome messages*/@@ -243,6 +259,7 @@ export const RedisKeys = {* land under another scope's prefix. Every scope must be mapped.*/export const RedisKeyScopeNamespace = {+ agentIdentity: RedisKeyNamespace.AGENT_IDENTITY,agentSignal: RedisKeyNamespace.AGENT_SIGNAL,agentSteer: RedisKeyNamespace.AGENT_STEER,aiGeneration: RedisKeyNamespace.AI_GENERATION,diff --git a/apps/server/src/services/agentIdentity/__tests__/agentMailProvider.test.ts b/apps/server/src/services/agentIdentity/__tests__/agentMailProvider.test.tsnew file mode 100644index 00000000000..b724e2421aa--- /dev/null+++ b/apps/server/src/services/agentIdentity/__tests__/agentMailProvider.test.ts@@ -0,0 +1,602 @@+import { createInMemoryLinqWebhookDedupeStore } from '@lobechat/agent-address-linq';+import type { EmailMessageDetail } from '@lobechat/agent-address-mail';+import { computeAgentMailSignature } from '@lobechat/agent-address-mail';+import type { AgentAccountRef } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { createAgentMailProvider } from '../providers/agentMail';++/** A claim store of its own, so one test's accepted ids never leak into the next. */+const isolated = () => ({ dedupeStore: createInMemoryLinqWebhookDedupeStore() });++const SECRET = 'whsec_mail_secret';++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), {+ headers: { 'content-type': 'application/json' },+ status,+ });++const mailDetail = (overrides: Partial<EmailMessageDetail> = {}): EmailMessageDetail => ({+ attachments: [],+ bcc: [],+ cc: [],+ codes: [],+ direction: 'inbound',+ envelope: { from: '[email protected]', to: '[email protected]' },+ error: null,+ from: { address: '[email protected]', name: 'Human' },+ html: null,+ id: 'msg_in_1',+ inboxId: 'inb_1',+ inReplyTo: null,+ links: [],+ messageId: '<[email protected]>',+ read: false,+ receivedAt: '2026-10-02T00:00:00.000Z',+ references: ['<[email protected]>'],+ replyTo: [],+ size: 42,+ snippet: null,+ status: 'received',+ subject: 'Hello',+ text: 'the answer',+ to: [{ address: '[email protected]' }],+ ...overrides,+});++/** Minimal stand-in for the Agent Mail REST surface the provider touches. */+const createMailFetch = (+ options: { detail?: Partial<EmailMessageDetail>; raw?: null | string } = {},+) => {+ const calls: Array<{ body?: unknown; method: string; path: string }> = [];++ const fetchImpl: typeof fetch = async (input, init) => {+ const url = typeof input === 'string' ? input : input.toString();+ const method = init?.method ?? 'GET';+ const { pathname } = new URL(url);+ calls.push({+ body: init?.body ? JSON.parse(String(init.body)) : undefined,+ method,+ path: pathname,+ });++ if (method === 'POST' && pathname === '/v1/inboxes') {+ return json({ address: '[email protected]', clientId: 'cli_1', id: 'inb_1', metadata: {} });+ }+ if (method === 'POST' && pathname === '/v1/webhooks') {+ return json({ id: 'wh_1', secret: SECRET, url: 'https://app.lobehub.com/hook' });+ }+ if (method === 'DELETE' && pathname === '/v1/inboxes/inb_1') {+ return new Response(null, { status: 204 });+ }+ if (method === 'POST' && pathname === '/v1/inboxes/inb_1/messages') {+ return json(mailDetail({ direction: 'outbound', id: 'msg_out_1' }));+ }+ if (method === 'POST' && pathname === '/v1/messages/msg_in_1/reply') {+ return json(mailDetail({ direction: 'outbound', id: 'msg_out_reply_1' }));+ }+ if (method === 'GET' && pathname === '/v1/messages/msg_in_1') {+ return json(mailDetail(options.detail));+ }+ if (method === 'GET' && pathname === '/v1/messages/msg_in_1/raw') {+ if (options.raw === null) return new Response('', { status: 404 });+ return new Response(options.raw ?? 'From: [email protected]\r\nSubject: Hello\r\n\r\nbody');+ }++ throw new Error(`unexpected mail request ${method} ${pathname}`);+ };++ return { calls, fetchImpl };+};++const inboundBody = (address = '[email protected]', messageId = 'msg_in_1') =>+ JSON.stringify({+ createdAt: '2026-10-02T00:00:00.000Z',+ data: {+ inbox: { address, clientId: 'cli_1', id: 'inb_1' },+ message: { id: messageId },+ },+ id: 'evt_1',+ type: 'message.received',+ });++const ref = (overrides: Partial<AgentAccountRef> = {}): AgentAccountRef => ({+ credential: { webhookSecret: SECRET },+ id: 'acc_1',+ identifier: '[email protected]',+ kind: 'mail',+ metadata: { inboxId: 'inb_1' },+ provider: 'agent-mail',+ ...overrides,+});++describe('agent-mail provider β declaration', () => {+ it('declares the mail identity it issues and what it can do', () => {+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test' });++ expect(provider.provider).toBe('agent-mail');+ expect(provider.kind).toBe('mail');+ expect(provider.capabilities).toEqual({ receive: true, send: true });+ });+});++describe('agent-mail provider β provisioning', () => {+ it('deletes the inbox it just opened when webhook registration fails', async () => {+ const calls: Array<{ method: string; path: string }> = [];+ const fetchImpl: typeof fetch = async (input, init) => {+ const { pathname } = new URL(typeof input === 'string' ? input : input.toString());+ const method = init?.method ?? 'GET';+ calls.push({ method, path: pathname });+ if (method === 'POST' && pathname === '/v1/inboxes')+ return json({ address: '[email protected]', clientId: 'cli_1', id: 'inb_1', metadata: {} });+ if (method === 'POST' && pathname === '/v1/webhooks')+ return json({ error: { message: 'upstream unavailable' } }, 503);+ if (method === 'DELETE' && pathname === '/v1/inboxes/inb_1')+ return new Response(null, { status: 204 });+ throw new Error(`unexpected ${method} ${pathname}`);+ };+ const provider = createAgentMailProvider({+ ...isolated(),+ apiKey: 'am_test',+ fetchImpl,+ webhookUrl: 'https://app.lobehub.com/hook',+ });++ await expect(provider.provision({ agentId: 'agent_7', userId: 'user_1' })).rejects.toThrow(+ /503/,+ );+ expect(calls).toContainEqual({ method: 'DELETE', path: '/v1/inboxes/inb_1' });+ });++ it('keeps an inbox a concurrent provisioning request already bound', async () => {+ // Webhook registration failed here, but the same deterministic `clientId`+ // handed another in-flight request this very inbox, and that request+ // committed its account first. Cleaning up would delete a live mailbox.+ const calls: Array<{ method: string; path: string }> = [];+ const fetchImpl: typeof fetch = async (input, init) => {+ const { pathname } = new URL(typeof input === 'string' ? input : input.toString());+ const method = init?.method ?? 'GET';+ calls.push({ method, path: pathname });+ if (method === 'POST' && pathname === '/v1/inboxes')+ return json({ address: '[email protected]', clientId: 'cli_1', id: 'inb_1', metadata: {} });+ if (method === 'POST' && pathname === '/v1/webhooks')+ return json({ error: { message: 'upstream unavailable' } }, 503);+ throw new Error(`unexpected ${method} ${pathname}`);+ };+ const provider = createAgentMailProvider({+ ...isolated(),+ apiKey: 'am_test',+ fetchImpl,+ webhookUrl: 'https://app.lobehub.com/hook',+ });++ // Not held when the request starts; the other request commits in between,+ // which is exactly the window this guard covers.+ let checks = 0;+ await expect(+ provider.provision({+ agentId: 'agent_7',+ isIdentifierHeld: async () => {+ checks += 1;+ return checks > 1;+ },+ userId: 'user_1',+ }),+ ).rejects.toThrow(/503/);++ expect(calls).not.toContainEqual({ method: 'DELETE', path: '/v1/inboxes/inb_1' });+ });++ it('opens an inbox and stores the returned handle as the identifier', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ const result = await provider.provision({ agentId: 'agent_7', userId: 'user_1' });++ expect(result.identifier).toBe('[email protected]');+ expect(result.metadata).toEqual({ clientId: 'cli_1', inboxId: 'inb_1' });+ expect(calls.some((c) => c.method === 'POST' && c.path === '/v1/inboxes')).toBe(true);+ });++ it('registers the webhook and returns its one-time secret as the credential', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({+ apiKey: 'am_test',+ fetchImpl,+ webhookUrl: 'https://app.lobehub.com/hook',+ });++ const result = await provider.provision({ agentId: 'agent_7', userId: 'user_1' });++ expect(result.credential).toEqual({ webhookSecret: SECRET });+ expect(result.credentialHint?.masked).toBe('β’β’β’β’cret');+ expect(calls.some((c) => c.method === 'POST' && c.path === '/v1/webhooks')).toBe(true);+ });++ it('asks for the inbox by the agent id, so a retry is handed the one already opened', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ await provider.provision({ agentId: 'agent_7', userId: 'user_1' });++ expect(calls.find((c) => c.method === 'POST' && c.path === '/v1/inboxes')?.body).toMatchObject({+ clientId: 'agent_7',+ endUserId: 'agent_7',+ });+ });++ it('does not register a second webhook for an inbox a live account already holds', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({+ ...isolated(),+ apiKey: 'am_test',+ fetchImpl,+ webhookUrl: 'https://app.lobehub.com/hook',+ });++ // The first attempt committed its row and only the response was lost: the+ // row keeps the webhook secret, so a fresh webhook would sign deliveries+ // with a secret nothing stores.+ const result = await provider.provision({+ agentId: 'agent_7',+ isIdentifierHeld: async (identifier) => identifier === '[email protected]',+ userId: 'user_1',+ });++ expect(result).toEqual({+ identifier: '[email protected]',+ metadata: { clientId: 'cli_1', inboxId: 'inb_1' },+ });+ expect(calls.some((c) => c.path === '/v1/webhooks')).toBe(false);+ });++ it('releases the inbox on release', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ await provider.release(ref());++ expect(calls).toContainEqual(+ expect.objectContaining({ method: 'DELETE', path: '/v1/inboxes/inb_1' }),+ );+ });++ it('treats an inbox that is already gone as released', async () => {+ const fetchImpl: typeof fetch = async () =>+ json({ error: { code: 'not_found', message: 'Inbox not found' } }, 404);+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ await expect(provider.release(ref())).resolves.toBeUndefined();+ });++ it('still surfaces a release the provider actually refused', async () => {+ const fetchImpl: typeof fetch = async () => json({ error: { message: 'boom' } }, 500);+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ await expect(provider.release(ref())).rejects.toThrow(/500/);+ });+});++describe('agent-mail provider β inbound', () => {+ it('routes a delivery by the inbox address in its payload', () => {+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test' });++ expect(provider.resolveInboundIdentifier({ body: inboundBody(), headers: {} })).toBe(+ '[email protected]',+ );+ expect(provider.resolveInboundIdentifier({ body: 'not json', headers: {} })).toBeUndefined();+ });++ it('accepts a correctly signed delivery and rejects a forged one', async () => {+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test' });+ const body = inboundBody();+ const timestamp = Math.floor(Date.now() / 1000);++ const accepted = await provider.verifyInbound(+ {+ body,+ headers: { 'x-agentmail-signature': computeAgentMailSignature(SECRET, body, timestamp) },+ },+ ref(),+ );+ expect(accepted).toEqual({+ eventId: 'evt_1',+ occurredAt: new Date('2026-10-02T00:00:00.000Z'),+ payload: expect.objectContaining({ id: 'evt_1' }),+ type: 'message.received',+ });++ const forged = await provider.verifyInbound(+ {+ body,+ headers: {+ 'x-agentmail-signature': computeAgentMailSignature('wrong_secret', body, timestamp),+ },+ },+ ref(),+ );+ expect(forged).toBeNull();+ });++ it('flags a replay of an event it already accepted as a duplicate', async () => {+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test' });+ const body = inboundBody();+ const headers = {+ 'x-agentmail-signature': computeAgentMailSignature(+ SECRET,+ body,+ Math.floor(Date.now() / 1000),+ ),+ };++ await expect(provider.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ eventId: 'evt_1' }),+ );+ await expect(provider.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ duplicate: true }),+ );+ });++ it('remembers an accepted event across provider instances, as each webhook request builds one', async () => {+ const body = inboundBody('[email protected]', 'msg_in_1').replace('evt_1', 'evt_cross_instance');+ const headers = {+ 'x-agentmail-signature': computeAgentMailSignature(+ SECRET,+ body,+ Math.floor(Date.now() / 1000),+ ),+ };++ const firstRequest = createAgentMailProvider({ apiKey: 'am_test' });+ const secondRequest = createAgentMailProvider({ apiKey: 'am_test' });++ await expect(firstRequest.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ eventId: 'evt_cross_instance' }),+ );+ await expect(secondRequest.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ duplicate: true }),+ );+ });++ it('falls back to the shared secret when the account carries none', async () => {+ const provider = createAgentMailProvider({+ ...isolated(),+ apiKey: 'am_test',+ webhookSecret: SECRET,+ });+ const body = inboundBody();+ const timestamp = Math.floor(Date.now() / 1000);++ await expect(+ provider.verifyInbound(+ {+ body,+ headers: { 'x-agentmail-signature': computeAgentMailSignature(SECRET, body, timestamp) },+ },+ ref({ credential: null }),+ ),+ ).resolves.toEqual(expect.objectContaining({ eventId: 'evt_1' }));+ });++ it('processes a retry after the message fetch failed instead of dropping it', async () => {+ let detailAttempts = 0;+ const { fetchImpl: base } = createMailFetch();+ const fetchImpl: typeof fetch = async (input, init) => {+ const { pathname } = new URL(typeof input === 'string' ? input : input.toString());+ if (pathname === '/v1/messages/msg_in_1' && ++detailAttempts === 1)+ return json({ error: { message: 'temporarily unavailable' } }, 503);+ return base(input, init);+ };+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });+ const body = inboundBody();+ const request = {+ body,+ headers: {+ 'x-agentmail-signature': computeAgentMailSignature(+ SECRET,+ body,+ Math.floor(Date.now() / 1000),+ ),+ },+ };++ const first = await provider.verifyInbound(request, ref());+ await expect(provider.normalizeInbound(first!, ref())).rejects.toThrow(/503/);++ // The provider retries the same event: it must be processed, not acked as a duplicate.+ const retry = await provider.verifyInbound(request, ref());+ expect(retry).not.toHaveProperty('duplicate', true);+ await expect(provider.normalizeInbound(retry!, ref())).resolves.toMatchObject({+ providerMessageId: 'msg_in_1',+ });+ });++ it('normalizes a message, stripping the quoted history', async () => {+ const { fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ const message = await provider.normalizeInbound(+ { eventId: 'evt_1', payload: JSON.parse(inboundBody()) },+ ref(),+ );++ expect(message).toMatchObject({+ from: '[email protected]',+ providerMessageId: 'msg_in_1',+ subject: 'Hello',+ threadKey: '<[email protected]>',+ to: '[email protected]',+ });+ expect(message!.text).toContain('the answer');+ });++ it('drops a message the deployment key can read but this inbox does not own', async () => {+ // The fetch back is not scoped to the account: it runs with the deployment+ // key. A caller who installs their own webhook secret can sign a delivery+ // whose payload names their inbox but whose message id lives elsewhere.+ const { fetchImpl } = createMailFetch({ detail: { inboxId: 'inb_someone_else' } });+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ const message = await provider.normalizeInbound(+ { eventId: 'evt_1', payload: JSON.parse(inboundBody()) },+ ref(),+ );++ expect(message).toBeNull();+ });++ it('carries the attachments, so an attachment-only email still reaches the agent with its files', async () => {+ const { fetchImpl } = createMailFetch({+ detail: {+ attachments: [+ { contentType: 'application/pdf', filename: 'invoice.pdf', index: 0, size: 1024 },+ { index: 1 },+ ],+ text: null,+ },+ });+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ const message = await provider.normalizeInbound(+ { eventId: 'evt_1', payload: JSON.parse(inboundBody()) },+ ref(),+ );++ expect(message?.text).toBe('');+ expect(message?.attachments).toEqual([+ {+ mimeType: 'application/pdf',+ name: 'invoice.pdf',+ size: 1024,+ url: 'https://api.lobe.id/v1/messages/msg_in_1/attachments/0',+ },+ {+ mimeType: 'application/octet-stream',+ name: undefined,+ size: undefined,+ url: 'https://api.lobe.id/v1/messages/msg_in_1/attachments/1',+ },+ ]);+ });++ it('hands over the mail detail a mail record needs: addressing, RFC threading, attachments', async () => {+ const { fetchImpl } = createMailFetch({+ detail: {+ attachments: [+ { contentType: 'application/pdf', filename: 'invoice.pdf', index: 0, size: 1024 },+ ],+ cc: [{ address: '[email protected]' }],+ from: { address: '[email protected]', name: 'Human' },+ inReplyTo: '<[email protected]>',+ references: ['<[email protected]>', '<[email protected]>'],+ replyTo: [{ address: '[email protected]', name: 'Desk' }],+ },+ });+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ const message = await provider.normalizeInbound(+ { eventId: 'evt_1', payload: JSON.parse(inboundBody()) },+ ref(),+ );++ expect(message?.mail).toEqual({+ attachments: [+ { contentType: 'application/pdf', filename: 'invoice.pdf', index: 0, size: 1024 },+ ],+ cc: [{ address: '[email protected]' }],+ fromName: 'Human',+ inReplyTo: '<[email protected]>',+ messageId: '<[email protected]>',+ references: ['<[email protected]>', '<[email protected]>'],+ replyTo: [{ address: '[email protected]', name: 'Desk' }],+ to: [{ address: '[email protected]' }],+ });+ });++ it('drops robot mail instead of handing it to the agent', async () => {+ const { fetchImpl } = createMailFetch({+ raw: 'From: [email protected]\r\nSubject: Hello\r\nAuto-Submitted: auto-replied\r\n\r\nx',+ });+ const provider = createAgentMailProvider({ ...isolated(), apiKey: 'am_test', fetchImpl });++ const message = await provider.normalizeInbound(+ { eventId: 'evt_1', payload: JSON.parse(inboundBody()) },+ ref(),+ );++ expect(message).toBeNull();+ });+});++describe('agent-mail provider β outbound', () => {+ it('sends through the inbox and returns the provider message id', async () => {+ const { fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({ apiKey: 'am_test', fetchImpl });++ const result = await provider.send(ref(), {+ subject: 'Re: Hello',+ text: 'hi back',+ to: '[email protected]',+ });++ expect(result).toEqual({ providerMessageId: 'msg_out_1' });+ });++ it('answers within the thread when the caller names the message it replies to', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({ apiKey: 'am_test', fetchImpl });++ const result = await provider.send(ref(), {+ replyToProviderMessageId: 'msg_in_1',+ text: 'hi back',+ to: '[email protected]',+ });++ // The reply route inherits the recipients and threads the message; going+ // through `sendMessage` would start a second conversation with the same+ // subject instead of answering the human in theirs.+ expect(calls.filter((call) => call.method === 'POST')).toEqual([+ { body: { text: 'hi back' }, method: 'POST', path: '/v1/messages/msg_in_1/reply' },+ ]);+ expect(result).toEqual({ providerMessageId: 'msg_out_reply_1' });+ });+});++describe('agent-mail provider β reply ownership', () => {+ it('refuses to reply to a message that lives in another accountβs inbox', async () => {+ // One deployment API key spans every inbox, and the reply route sends as the+ // inbox that owns the message. Answering a foreign id would speak as another+ // agent, skipping every lifecycle and capability check done for this one.+ const { calls, fetchImpl } = createMailFetch({ detail: { inboxId: 'inb_other' } });+ const provider = createAgentMailProvider({ apiKey: 'am_test', fetchImpl });++ await expect(+ provider.send(ref(), {+ replyToProviderMessageId: 'msg_in_1',+ text: 'hi back',+ to: '[email protected]',+ }),+ ).rejects.toMatchObject({ code: 'reply_target_not_owned', name: 'AgentAccountError' });++ // The refusal happens before the send: nothing was written to the provider.+ expect(calls.filter((call) => call.method === 'POST')).toEqual([]);+ });++ it('replies when the target belongs to the accountβs own inbox', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const provider = createAgentMailProvider({ apiKey: 'am_test', fetchImpl });++ const result = await provider.send(ref(), {+ replyToProviderMessageId: 'msg_in_1',+ text: 'hi back',+ to: '[email protected]',+ });++ expect(calls).toEqual([+ { body: undefined, method: 'GET', path: '/v1/messages/msg_in_1' },+ { body: { text: 'hi back' }, method: 'POST', path: '/v1/messages/msg_in_1/reply' },+ ]);+ expect(result).toEqual({ providerMessageId: 'msg_out_reply_1' });+ });+});diff --git a/apps/server/src/services/agentIdentity/__tests__/identityChain.test.ts b/apps/server/src/services/agentIdentity/__tests__/identityChain.test.tsnew file mode 100644index 00000000000..56968432b22--- /dev/null+++ b/apps/server/src/services/agentIdentity/__tests__/identityChain.test.ts@@ -0,0 +1,267 @@+// @vitest-environment node+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';++import type { EmailMessageDetail } from '@lobechat/agent-address-mail';+import { computeAgentMailSignature } from '@lobechat/agent-address-mail';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentAccountModel } from '@/database/models/agentAccount';+import { agentAccounts, agents, users } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';++import { AgentAccountService } from '../index';+import { createAgentMailProvider } from '../providers/agentMail';+import { createLinqProvider } from '../providers/linq';+import { AgentAccountProviderRegistry } from '../registry';++/**+ * End-to-end evidence run for the identity service chain.+ *+ * Unlike the unit tests, nothing here is stubbed in-process: the service talks+ * to the real `@lobechat/agent-address-mail` client over a loopback HTTP server+ * (a stand-in for the lobe.id tenant that operations has not provisioned yet),+ * against the real Drizzle model on the PGlite test database, with the real+ * AES-GCM KeyVaults gatekeeper. Only the SaaS on the other side of the wire is+ * a fixture β and that is exactly the prerequisite the task says is missing.+ */++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'agent-identity-chain-user';+const agentId = 'agent-identity-chain-agent';+const WEBHOOK_SECRET = 'whsec_e2e_agent_mail';++const mailDetail = (overrides: Partial<EmailMessageDetail> = {}): EmailMessageDetail => ({+ attachments: [],+ bcc: [],+ cc: [],+ codes: [],+ direction: 'inbound',+ envelope: { from: '[email protected]', to: '[email protected]' },+ error: null,+ from: { address: '[email protected]', name: 'Human' },+ html: null,+ id: 'msg_in_e2e',+ inboxId: 'inb_e2e',+ inReplyTo: null,+ links: [],+ messageId: '<[email protected]>',+ read: false,+ receivedAt: '2026-10-02T00:00:00.000Z',+ references: ['<[email protected]>'],+ replyTo: [],+ size: 42,+ snippet: null,+ status: 'received',+ subject: 'Hello agent',+ text: 'the answer\n\nOn Mon, someone wrote:\n> older history',+ to: [{ address: '[email protected]' }],+ ...overrides,+});++/** A loopback stand-in for the lobe.id tenant the Agent Mail client talks to. */+const startMockAgentMail = async () => {+ const seen: string[] = [];+ const server = createServer((req, res) => {+ const chunks: Buffer[] = [];+ req.on('data', (chunk) => chunks.push(chunk as Buffer));+ req.on('end', () => {+ const method = req.method ?? 'GET';+ const { pathname } = new URL(req.url ?? '/', 'http://127.0.0.1');+ seen.push(`${method} ${pathname}`);++ const json = (status: number, body: unknown) => {+ res.writeHead(status, { 'content-type': 'application/json' });+ res.end(JSON.stringify(body));+ };++ if (method === 'POST' && pathname === '/v1/inboxes') {+ return json(200, {+ address: '[email protected]',+ clientId: 'cli_e2e',+ id: 'inb_e2e',+ metadata: {},+ });+ }+ if (method === 'POST' && pathname === '/v1/webhooks') {+ return json(200, { id: 'wh_e2e', secret: WEBHOOK_SECRET, url: 'http://127.0.0.1/hook' });+ }+ if (method === 'DELETE' && pathname === '/v1/inboxes/inb_e2e') {+ res.writeHead(204);+ return res.end();+ }+ if (method === 'POST' && pathname === '/v1/inboxes/inb_e2e/messages') {+ return json(200, mailDetail({ direction: 'outbound', id: 'msg_out_e2e' }));+ }+ if (method === 'GET' && pathname === '/v1/messages/msg_in_e2e') {+ return json(200, mailDetail());+ }+ if (method === 'GET' && pathname === '/v1/messages/msg_in_e2e/raw') {+ res.writeHead(200, { 'content-type': 'message/rfc822' });+ return res.end('From: [email protected]\r\nSubject: Hello agent\r\n\r\nbody');+ }++ return json(404, { error: { message: `unexpected ${method} ${pathname}` } });+ });+ });++ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));+ const { port } = server.address() as AddressInfo;++ return { baseUrl: `http://127.0.0.1:${port}`, seen, server };+};++let mock: Awaited<ReturnType<typeof startMockAgentMail>>;+let gateKeeper: KeyVaultsGateKeeper;+let service: AgentAccountService;++beforeAll(async () => {+ // A real 32-byte AES-GCM key, so the credential path is exercised for real.+ vi.stubEnv('KEY_VAULTS_SECRET', Buffer.alloc(32, 7).toString('base64'));+ gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();+ mock = await startMockAgentMail();+});++afterAll(async () => {+ await new Promise<void>((resolve, reject) =>+ mock.server.close((error) => (error ? reject(error) : resolve())),+ );+ vi.unstubAllEnvs();+});++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values({ id: agentId, userId });++ const registry = new AgentAccountProviderRegistry()+ .register(+ createAgentMailProvider({+ apiBaseUrl: mock.baseUrl,+ apiKey: 'am_e2e',+ webhookUrl: 'http://127.0.0.1/hook',+ }),+ )+ .register(createLinqProvider({ apiKey: 'linq_e2e', fromNumbers: ['+15550002222'] }));++ service = new AgentAccountService(serverDB, userId, { gateKeeper, registry });+});++afterEach(async () => {+ await serverDB.delete(agentAccounts);+ await serverDB.delete(users);+});++describe('Agent identity chain β end to end over loopback', () => {+ it('provisions, sends, receives and revokes across both providers', async () => {+ const transcript: string[] = [];++ // 1. Provision a mail account through the provider (real HTTP round trip).+ const mail = await service.provision({+ agentId,+ displayName: 'Toby mailbox',+ provider: 'agent-mail',+ });+ transcript.push(+ `1. provision(agent-mail) -> ${mail.identifier} kind=${mail.kind} capabilities=${JSON.stringify(mail.capabilities)} hasCredential=${mail.hasCredential}`,+ );+ expect(mail).toMatchObject({+ capabilities: { receive: true, send: true },+ hasCredential: true,+ identifier: '[email protected]',+ kind: 'mail',+ });++ // 2. Provision a phone account (Linq number comes from deployment config).+ const phone = await service.provision({ agentId, provider: 'linq' });+ transcript.push(+ `2. provision(linq) -> ${phone.identifier} kind=${phone.kind} capabilities=${JSON.stringify(phone.capabilities)}`,+ );+ expect(phone).toMatchObject({ identifier: '+15550002222', kind: 'phone', provider: 'linq' });++ // 3. Reads never carry the ciphertext; the credential is stated, not shown.+ const listed = await service.list({ agentId });+ expect(listed).toHaveLength(2);+ for (const account of listed) expect(account).not.toHaveProperty('credentials');+ transcript.push(`3. list(agentId) -> ${listed.length} accounts, none expose credentials`);++ // 4. The stored column is real ciphertext, not the plaintext secret.+ const [row] = await serverDB+ .select({ credentials: agentAccounts.credentials })+ .from(agentAccounts)+ .where(eq(agentAccounts.id, mail.id));+ transcript.push(+ `4. agent_accounts.credentials -> ${String(row.credentials).slice(0, 24)}β¦ (plaintext leaked=${String(row.credentials).includes(WEBHOOK_SECRET)})`,+ );+ expect(row.credentials).toBeTruthy();+ expect(row.credentials).not.toContain(WEBHOOK_SECRET);+ await expect(+ new AgentAccountModel(serverDB, userId, gateKeeper).getCredential(mail.id),+ ).resolves.toEqual({ webhookSecret: WEBHOOK_SECRET });++ // 5. Send outbound through the provider.+ const sent = await service.send(mail.id, {+ subject: 'Re: Hello agent',+ text: 'hi back',+ to: '[email protected]',+ });+ transcript.push(`5. send(mail) -> providerMessageId=${sent.providerMessageId}`);+ expect(sent).toEqual({ providerMessageId: 'msg_out_e2e' });++ // 6. Deliver a signed inbound webhook: resolve β verify β normalize.+ const body = JSON.stringify({+ createdAt: '2026-10-02T00:00:00.000Z',+ data: {+ inbox: { address: '[email protected]', clientId: 'cli_e2e', id: 'inb_e2e' },+ message: { id: 'msg_in_e2e' },+ },+ id: 'evt_e2e',+ type: 'message.received',+ });+ const outcome = await service.handleInbound('agent-mail', {+ body,+ headers: {+ 'x-agentmail-signature': computeAgentMailSignature(+ WEBHOOK_SECRET,+ body,+ Math.floor(Date.now() / 1000),+ ),+ },+ });+ if (outcome.outcome !== 'delivered')+ throw new Error(`expected delivered, got ${outcome.outcome}`);+ transcript.push(+ `6. handleInbound(agent-mail) -> ${outcome.outcome} from=${outcome.message.from} to=${outcome.message.to} text=${JSON.stringify(outcome.message.text)}`,+ );+ expect(outcome.message).toMatchObject({+ from: '[email protected]',+ providerMessageId: 'msg_in_e2e',+ text: 'the answer',+ to: '[email protected]',+ });++ // 7. A forged delivery produces no message.+ const forged = await service.handleInbound('agent-mail', {+ body,+ headers: { 'x-agentmail-signature': 't=1,v1=deadbeef' },+ });+ transcript.push(`7. handleInbound(forged signature) -> ${forged.outcome}`);+ expect(forged.outcome).toBe('rejected');++ // 8. Revoke: the provider releases its side and the secret is purged.+ await service.revoke(mail.id);+ const revoked = await service.get(mail.id);+ transcript.push(+ `8. revoke(mail) -> status=${revoked!.status} hasCredential=${revoked!.hasCredential} providerReleased=${mock.seen.includes('DELETE /v1/inboxes/inb_e2e')}`,+ );+ expect(revoked).toMatchObject({ hasCredential: false, status: 'revoked' });+ expect(mock.seen).toContain('DELETE /v1/inboxes/inb_e2e');++ transcript.push(`wire: ${mock.seen.join(' | ')}`);+ console.log(`\n[identity-chain]\n${transcript.join('\n')}\n[/identity-chain]\n`);+ });+});diff --git a/apps/server/src/services/agentIdentity/__tests__/index.test.ts b/apps/server/src/services/agentIdentity/__tests__/index.test.tsnew file mode 100644index 00000000000..b9aa4e2528e--- /dev/null+++ b/apps/server/src/services/agentIdentity/__tests__/index.test.ts@@ -0,0 +1,741 @@+// @vitest-environment node+import type { EmailMessageDetail } from '@lobechat/agent-address-mail';+import { computeAgentMailSignature } from '@lobechat/agent-address-mail';+import { getTestDB } from '@lobechat/database/test-utils';+import { TRPCError } from '@trpc/server';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { agentAccounts, agents, users, workspaces } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { AgentAccountService } from '../index';+import { createAgentMailProvider } from '../providers/agentMail';+import { createLinqProvider } from '../providers/linq';+import { AgentAccountProviderRegistry } from '../registry';++// The agent's edit ACL is its own suite's subject; here it is the seam whose+// verdict the service must honor, admitting exactly whom the ACL admits.+const { assertCanEditResource, assertCanPerformResourceAction } = vi.hoisted(() => ({+ assertCanEditResource: vi.fn(async (_params: { userId: string; workspaceId?: string }) => {}),+ assertCanPerformResourceAction: vi.fn(async (_params: { userId: string }) => {}),+}));+vi.mock('@/server/services/resourcePermission', () => ({+ assertCanEditResource,+ assertCanPerformResourceAction,+}));++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'agent-identity-service-user';+const agentId = 'agent-identity-service-agent';+const otherAgentId = 'agent-identity-service-agent-2';+const foreignUserId = 'agent-identity-service-user-2';+const foreignAgentId = 'agent-identity-service-agent-3';+const WEBHOOK_SECRET = 'whsec_svc_secret';++const gateKeeper = {+ decrypt: vi.fn(async (ciphertext: string) => ({ plaintext: ciphertext })),+ encrypt: vi.fn(async (plaintext: string) => plaintext),+};++const json = (body: unknown, status = 200) =>+ new Response(JSON.stringify(body), { headers: { 'content-type': 'application/json' }, status });++const mailDetail = (overrides: Partial<EmailMessageDetail> = {}): EmailMessageDetail => ({+ attachments: [],+ bcc: [],+ cc: [],+ codes: [],+ direction: 'inbound',+ envelope: { from: '[email protected]', to: '[email protected]' },+ error: null,+ from: { address: '[email protected]', name: 'Human' },+ html: null,+ id: 'msg_in_1',+ inboxId: 'inb_1',+ inReplyTo: null,+ links: [],+ messageId: '<[email protected]>',+ read: false,+ receivedAt: '2026-10-02T00:00:00.000Z',+ references: ['<[email protected]>'],+ replyTo: [],+ size: 42,+ snippet: null,+ status: 'received',+ subject: 'Hello',+ text: 'the answer',+ to: [{ address: '[email protected]' }],+ ...overrides,+});++const createMailFetch = () => {+ const calls: Array<{ method: string; path: string }> = [];+ const fetchImpl: typeof fetch = async (input, init) => {+ const url = typeof input === 'string' ? input : input.toString();+ const { pathname } = new URL(url);+ const method = init?.method ?? 'GET';+ calls.push({ method, path: pathname });++ if (method === 'POST' && pathname === '/v1/inboxes') {+ return json({ address: '[email protected]', clientId: 'cli_1', id: 'inb_1', metadata: {} });+ }+ if (method === 'POST' && pathname === '/v1/webhooks') {+ return json({ id: 'wh_1', secret: WEBHOOK_SECRET, url: 'https://app.lobehub.com/hook' });+ }+ if (method === 'DELETE' && pathname === '/v1/inboxes/inb_1') {+ return new Response(null, { status: 204 });+ }+ if (method === 'POST' && pathname === '/v1/inboxes/inb_1/messages') {+ return json(mailDetail({ direction: 'outbound', id: 'msg_out_1' }));+ }+ if (method === 'GET' && pathname === '/v1/messages/msg_in_1') return json(mailDetail());+ if (method === 'GET' && pathname === '/v1/messages/msg_in_1/raw') {+ return new Response('From: [email protected]\r\nSubject: Hello\r\n\r\nbody');+ }+ throw new Error(`unexpected mail request ${method} ${pathname}`);+ };++ return { calls, fetchImpl };+};++const buildService = (fetchImpl: typeof fetch) => {+ const registry = new AgentAccountProviderRegistry().register(+ createAgentMailProvider({+ apiKey: 'am_svc',+ fetchImpl,+ webhookUrl: 'https://app.lobehub.com/hook',+ }),+ );++ return new AgentAccountService(serverDB, userId, { gateKeeper, registry });+};++const inboundBody = (address = '[email protected]', eventId = 'evt_1') =>+ JSON.stringify({+ createdAt: '2026-10-02T00:00:00.000Z',+ data: { inbox: { address, clientId: 'cli_1', id: 'inb_1' }, message: { id: 'msg_in_1' } },+ id: eventId,+ type: 'message.received',+ });++beforeEach(async () => {+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(agents).values([+ { id: agentId, userId },+ { id: otherAgentId, userId },+ ]);+});++afterEach(async () => {+ await serverDB.delete(agentAccounts);+ await serverDB.delete(users);+ vi.clearAllMocks();+ assertCanEditResource.mockReset();+});++describe('AgentAccountService β provisioning', () => {+ it('persists the provider-declared kind and capabilities, and keeps the secret out of reads', async () => {+ const { fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);++ const created = await service.provision({ agentId, provider: 'agent-mail' });++ expect(created).toMatchObject({+ agentId,+ capabilities: { receive: true, send: true },+ hasCredential: true,+ identifier: '[email protected]',+ kind: 'mail',+ provider: 'agent-mail',+ status: 'active',+ });+ expect(created).not.toHaveProperty('credentials');+ expect(created.metadata).toEqual({ clientId: 'cli_1', inboxId: 'inb_1' });++ const listed = await service.list({ agentId });+ expect(listed).toHaveLength(1);+ expect(listed[0]).not.toHaveProperty('credentials');++ const found = await service.get(created.id);+ expect(found).not.toHaveProperty('credentials');+ });++ it('refuses an unregistered provider unless capabilities are stated', async () => {+ const service = buildService(createMailFetch().fetchImpl);++ await expect(+ service.create({+ agentId,+ identifier: 'agent@github',+ kind: 'service',+ provider: 'user',+ }),+ ).rejects.toMatchObject({ code: 'capabilities_required', reason: 'invalid' });++ const created = await service.create({+ agentId,+ capabilities: { login: true, receive: false, send: false },+ credential: { password: 'hunter2' },+ identifier: 'agent@github',+ kind: 'service',+ provider: 'user',+ });+ expect(created).toMatchObject({ kind: 'service', provider: 'user', status: 'active' });+ expect(created.capabilities).toEqual({ login: true, receive: false, send: false });+ });++ it('refuses to mount a handle on a provider the deployment runs, before writing anything', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);++ // Mounting would persist an inbox the caller merely names; revoke would then+ // delete it, and send would speak as it, with the deployment-wide key.+ await expect(+ service.create({+ agentId,+ capabilities: { receive: true, send: true },+ identifier: '[email protected]',+ kind: 'mail',+ metadata: { inboxId: 'inb_someone_else' },+ provider: 'agent-mail',+ }),+ ).rejects.toMatchObject({ code: 'provider_managed', reason: 'invalid' });++ expect(await service.list()).toHaveLength(0);+ expect(calls).toEqual([]);+ });++ it('keeps a reserved provider name unmountable while its key is absent', async () => {+ // A deployment without the Agent Mail key does not register the provider.+ // That omission must not make its handles mountable: the row would speak+ // and delete with the deployment-wide key once the key is restored.+ const service = new AgentAccountService(serverDB, userId, {+ gateKeeper,+ registry: new AgentAccountProviderRegistry(),+ });++ await expect(+ service.create({+ agentId,+ capabilities: { receive: true, send: true },+ identifier: '[email protected]',+ kind: 'mail',+ metadata: { inboxId: 'inb_someone_else' },+ provider: 'agent-mail',+ }),+ ).rejects.toMatchObject({ code: 'provider_managed', reason: 'invalid' });++ expect(await service.list()).toHaveLength(0);+ });++ it('refuses to open an account on an agent the caller does not own', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);++ await serverDB.insert(users).values({ id: foreignUserId });+ await serverDB.insert(agents).values({ id: foreignAgentId, userId: foreignUserId });++ // An agent the caller cannot see answers like a missing one, so the refusal+ // never confirms that a colleague's private agent exists.+ await expect(+ service.provision({ agentId: foreignAgentId, provider: 'agent-mail' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ // Refused before the provider ran, so no remote inbox was created at all.+ expect(calls).toEqual([]);+ expect(await service.list()).toHaveLength(0);++ await expect(+ service.create({+ agentId: foreignAgentId,+ capabilities: { receive: false, send: false },+ identifier: 'agent@github',+ kind: 'service',+ provider: 'user',+ }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });++ expect(await service.list()).toHaveLength(0);+ });++ it('releases the issued inbox and refuses readably when the row cannot be written', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ await service.provision({ agentId, provider: 'agent-mail' });++ // The mock hands out the same address again, so the second insert collides+ // on the routing key after the provider already opened an inbox.+ await expect(+ service.provision({ agentId: otherAgentId, provider: 'agent-mail' }),+ ).rejects.toMatchObject({+ code: 'identifier_taken',+ message: expect.stringMatching(/already bound to another agent/),+ });++ expect(calls.filter((c) => c.method === 'DELETE')).toEqual([+ { method: 'DELETE', path: '/v1/inboxes/inb_1' },+ ]);+ expect(await service.list()).toHaveLength(1);+ });++ it('keeps the inbox and returns the account when the insert committed but its ack was lost', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const model = (service as any).model;+ const create = model.create;+ model.create = async (...args: unknown[]) => {+ await create(...args);+ throw new Error('Connection terminated unexpectedly');+ };++ const account = await service.provision({ agentId, provider: 'agent-mail' });++ expect(account).toMatchObject({ agentId, identifier: '[email protected]' });+ expect(calls.some((c) => c.method === 'DELETE')).toBe(false);+ expect(await service.list()).toHaveLength(1);+ });++ it('still releases the inbox when a failed write left no row behind', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ (service as any).model.create = async () => {+ throw new Error('Connection refused');+ };++ await expect(service.provision({ agentId, provider: 'agent-mail' })).rejects.toThrow(+ /Connection refused/,+ );+ expect(calls).toContainEqual({ method: 'DELETE', path: '/v1/inboxes/inb_1' });+ });++ it('keeps the live inbox when a retry collides on its own routing key', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const first = await service.provision({ agentId, provider: 'agent-mail' });++ // `provision` is idempotent by contract, so a retry can be handed the inbox+ // that already backs the live row; the insert then collides on the routing+ // key. That collision is *this* account, not a rival: releasing here would+ // delete the inbox the live account is using.+ const retry = await service.provision({ agentId, provider: 'agent-mail' });++ expect(retry.id).toBe(first.id);+ expect(retry.identifier).toBe('[email protected]');+ expect(calls.some((c) => c.method === 'DELETE')).toBe(false);+ expect(await service.list()).toHaveLength(1);+ });++ it('reconciles a rebind against the live row, not the revoked one it replaced', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const first = await service.provision({ agentId, provider: 'agent-mail' });+ await service.revoke(first.id);++ // A released handle can be bound again, so the key now carries both the+ // revoked row and the account that replaced it. A retry that collides has to+ // read the live one; reading the replaced row would release its inbox.+ const live = await service.provision({ agentId, provider: 'agent-mail' });+ const deletesBeforeRetry = calls.filter((c) => c.method === 'DELETE').length;++ const retry = await service.provision({ agentId, provider: 'agent-mail' });++ expect(retry.id).toBe(live.id);+ expect(calls.filter((c) => c.method === 'DELETE')).toHaveLength(deletesBeforeRetry);+ expect(await service.list()).toHaveLength(2);+ });++ it('lets a released handle be bound again', async () => {+ const service = buildService(createMailFetch().fetchImpl);+ const first = await service.provision({ agentId, provider: 'agent-mail' });+ await service.revoke(first.id);++ const second = await service.provision({ agentId, provider: 'agent-mail' });++ expect(second.identifier).toBe('[email protected]');+ expect(second.status).not.toBe('revoked');+ expect(second.id).not.toBe(first.id);+ });++ it('hands out one pool number per live phone account', async () => {+ const registry = new AgentAccountProviderRegistry().register(+ createLinqProvider({ apiKey: 'linq_svc', fromNumbers: ['+15550002222'] }),+ );+ const service = new AgentAccountService(serverDB, userId, { gateKeeper, registry });++ const first = await service.provision({ agentId, provider: 'linq' });+ expect(first.identifier).toBe('+15550002222');++ await expect(+ service.provision({ agentId: otherAgentId, provider: 'linq' }),+ ).rejects.toMatchObject({ code: 'capacity_exhausted' });++ await service.revoke(first.id);+ await expect(+ service.provision({ agentId: otherAgentId, provider: 'linq' }),+ ).resolves.toMatchObject({ agentId: otherAgentId, identifier: '+15550002222' });+ });++ it('surfaces the registry error for a provider the deployment does not run', async () => {+ const service = buildService(createMailFetch().fetchImpl);++ await expect(service.provision({ agentId, provider: 'linq' })).rejects.toThrow(+ /Unknown agent account provider "linq"/,+ );+ });+});++describe('AgentAccountService β actions', () => {+ it('sends through the account provider', async () => {+ const { fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await expect(+ service.send(created.id, { subject: 'Re: Hello', text: 'hi back', to: '[email protected]' }),+ ).resolves.toEqual({ providerMessageId: 'msg_out_1' });+ });++ it('refuses to send from a revoked account', async () => {+ const { fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await service.revoke(created.id);++ await expect(service.send(created.id, { text: 'hi', to: '[email protected]' })).rejects.toThrow(+ /revoked/,+ );+ });++ it('refuses to send from a suspended account', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await serverDB+ .update(agentAccounts)+ .set({ status: 'suspended' })+ .where(eq(agentAccounts.id, created.id));++ await expect(service.send(created.id, { text: 'hi', to: '[email protected]' })).rejects.toThrow(+ /suspended/,+ );+ expect(calls.some((call) => call.method === 'POST' && call.path.includes('/messages'))).toBe(+ false,+ );+ });++ it('refuses to send from an account whose persisted capabilities exclude sending', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await serverDB+ .update(agentAccounts)+ .set({ capabilities: { receive: true, send: false } })+ .where(eq(agentAccounts.id, created.id));++ await expect(service.send(created.id, { text: 'hi', to: '[email protected]' })).rejects.toThrow(+ /not allowed to send/,+ );+ expect(calls.some((call) => call.method === 'POST' && call.path.includes('/messages'))).toBe(+ false,+ );+ });++ it('refuses to move an account through the generic patch', async () => {+ const service = buildService(createMailFetch().fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ // Lifecycle must go through `revoke`, which also releases the provider+ // resource, purges the credential and stamps `revokedAt` β writing the+ // status directly would free the handle while skipping all of that.+ const lifecyclePatch = { status: 'revoked' } as unknown as Parameters<typeof service.update>[1];++ await expect(service.update(created.id, lifecyclePatch)).rejects.toThrow(/not patchable/);++ expect(await service.get(created.id)).toMatchObject({ status: 'active' });+ });++ it('refuses to rewrite the provider-owned handles of an issued account', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ // Send and release act on `metadata.inboxId` with the deployment-wide key,+ // so a patched id would let the account send as, or delete, another inbox.+ await expect(+ service.update(created.id, { metadata: { inboxId: 'inb_someone_else' } }),+ ).rejects.toMatchObject({ code: 'provider_owned_field', reason: 'invalid' });+ expect(await service.get(created.id)).toMatchObject({+ metadata: { clientId: 'cli_1', inboxId: 'inb_1' },+ });++ await service.revoke(created.id);+ expect(calls).toContainEqual({ method: 'DELETE', path: '/v1/inboxes/inb_1' });++ // A caller-mounted account of an unregistered provider still owns its metadata.+ const mounted = await service.create({+ agentId,+ capabilities: { login: true, receive: false, send: false },+ identifier: 'agent@github',+ kind: 'service',+ provider: 'user',+ });+ await expect(service.update(mounted.id, { metadata: { org: 'lobehub' } })).resolves.toBe(+ mounted.id,+ );+ });++ it('admits exactly the members the agent edit ACL admits, for every write', async () => {+ const workspaceId = 'agent-identity-service-ws';+ const editorId = 'agent-identity-service-editor';+ await serverDB.insert(users).values([{ id: foreignUserId }, { id: editorId }]);+ const sharedAgentId = 'agent-identity-service-shared-agent';+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: workspaceId, primaryOwnerId: userId, slug: workspaceId });+ await serverDB+ .insert(agents)+ .values({ id: sharedAgentId, userId, visibility: 'public', workspaceId });+ // The member may use the shared agent but holds no edit level on it; the+ // editor is a collaborator with an edit grant, though not its creator.+ assertCanEditResource.mockImplementation(async (params) => {+ if (params.userId === foreignUserId) {+ throw new TRPCError({ code: 'FORBIDDEN', message: 'no edit' });+ }+ });++ const { calls, fetchImpl } = createMailFetch();+ const registry = new AgentAccountProviderRegistry().register(+ createAgentMailProvider({ apiKey: 'am_svc', fetchImpl, webhookUrl: 'https://x/hook' }),+ );+ const serviceFor = (id: string) =>+ new AgentAccountService(serverDB, id, { gateKeeper, registry, workspaceId });+ const member = serviceFor(foreignUserId);+ const editor = serviceFor(editorId);++ await expect(+ member.provision({ agentId: sharedAgentId, provider: 'agent-mail' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(calls).toEqual([]);++ // The transports admit an edit-level collaborator, so the service must not+ // refuse them a second time on a creator-only rule.+ const created = await editor.provision({ agentId: sharedAgentId, provider: 'agent-mail' });+ expect(assertCanEditResource).toHaveBeenCalledWith(+ expect.objectContaining({ resourceId: sharedAgentId, resourceType: 'agent', workspaceId }),+ );++ // The workspace scope lets the member see the account; that is not enough+ // to replace its secret, rewrite it or release its inbox.+ expect(await member.get(created.id)).toBeDefined();+ await expect(member.setCredential(created.id, { webhookSecret: 'x' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(member.update(created.id, { displayName: 'mine' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(member.revoke(created.id)).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(calls.some((c) => c.method === 'DELETE')).toBe(false);++ await expect(editor.update(created.id, { displayName: 'Ops inbox' })).resolves.toBe(created.id);+ expect(await editor.get(created.id)).toMatchObject({ displayName: 'Ops inbox' });++ await serverDB.delete(agentAccounts);+ await serverDB.delete(agents).where(eq(agents.id, sharedAgentId));+ await serverDB.delete(workspaces);+ });++ it('refuses to send through an agent the member may not use', async () => {+ const workspaceId = 'agent-identity-service-use-ws';+ const memberId = 'agent-identity-service-use-member';+ const useAgentId = 'agent-identity-service-use-agent';+ await serverDB.insert(users).values([{ id: memberId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: workspaceId, primaryOwnerId: userId, slug: workspaceId });+ await serverDB+ .insert(agents)+ .values({ id: useAgentId, userId, visibility: 'public', workspaceId });++ const { calls, fetchImpl } = createMailFetch();+ const registry = new AgentAccountProviderRegistry().register(+ createAgentMailProvider({ apiKey: 'am_svc', fetchImpl, webhookUrl: 'https://x/hook' }),+ );+ const serviceFor = (id: string) =>+ new AgentAccountService(serverDB, id, { gateKeeper, registry, workspaceId });++ const created = await serviceFor(userId).provision({+ agentId: useAgentId,+ provider: 'agent-mail',+ });+ const sent = () => calls.filter((c) => c.method === 'POST' && c.path.includes('/messages'));+ const member = serviceFor(memberId);++ // The account row is workspace-scoped, so the member can read it. Acting+ // through it is a *use* of the parent agent, which this member lacks.+ expect(await member.get(created.id)).toBeDefined();+ assertCanPerformResourceAction.mockImplementation(async (params: { userId: string }) => {+ if (params.userId === memberId) throw new TRPCError({ code: 'FORBIDDEN', message: 'no use' });+ });++ await expect(+ member.send(created.id, { text: 'hi', to: '[email protected]' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(sent()).toEqual([]);++ // Holding `use` β even without `edit` β is enough to answer from it.+ assertCanPerformResourceAction.mockImplementation(async () => {});+ await expect(+ member.send(created.id, { text: 'hi back', to: '[email protected]' }),+ ).resolves.toEqual({ providerMessageId: 'msg_out_1' });++ await serverDB.delete(agentAccounts);+ await serverDB.delete(agents).where(eq(agents.id, useAgentId));+ await serverDB.delete(workspaces);+ });++ it('does not release the provider resource again when revoking a revoked account', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await service.revoke(created.id);+ await service.revoke(created.id);++ // The second revoke targets a row that no longer holds the inbox: it must+ // stay side-effect free, or a replaced row would delete the live inbox.+ expect(calls.filter((call) => call.method === 'DELETE')).toHaveLength(1);+ });++ it('releases on the provider and purges the credential when revoking', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await service.revoke(created.id);++ expect(calls).toContainEqual({ method: 'DELETE', path: '/v1/inboxes/inb_1' });+ const revoked = await service.get(created.id);+ expect(revoked).toMatchObject({ hasCredential: false, status: 'revoked' });+ expect(revoked!.revokedAt).toBeTruthy();+ });+});++describe('AgentAccountService β inbound routing', () => {+ it('resolves the account, verifies the signature and normalizes the message', async () => {+ const { fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ const body = inboundBody();+ const outcome = await service.handleInbound('agent-mail', {+ body,+ headers: {+ 'x-agentmail-signature': computeAgentMailSignature(+ WEBHOOK_SECRET,+ body,+ Math.floor(Date.now() / 1000),+ ),+ },+ });++ expect(outcome.outcome).toBe('delivered');+ if (outcome.outcome !== 'delivered') throw new Error('unreachable');+ expect(outcome.accountId).toBe(created.id);+ expect(outcome.message).toMatchObject({+ from: '[email protected]',+ providerMessageId: 'msg_in_1',+ to: '[email protected]',+ });+ });++ it('rejects a delivery whose signature does not verify', async () => {+ const { fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ await service.provision({ agentId, provider: 'agent-mail' });++ const outcome = await service.handleInbound('agent-mail', {+ body: inboundBody(),+ headers: { 'x-agentmail-signature': 't=1,v1=deadbeef' },+ });++ expect(outcome.outcome).toBe('rejected');+ });++ it('does not route a delivery to a suspended account', async () => {+ const { fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await serverDB+ .update(agentAccounts)+ .set({ status: 'suspended' })+ .where(eq(agentAccounts.id, created.id));++ const body = inboundBody();+ const outcome = await service.handleInbound('agent-mail', {+ body,+ headers: {+ 'x-agentmail-signature': computeAgentMailSignature(+ WEBHOOK_SECRET,+ body,+ Math.floor(Date.now() / 1000),+ ),+ },+ });++ expect(outcome.outcome).toBe('unknown-account');+ });++ it('acknowledges but does not deliver to an account that cannot receive', async () => {+ const { calls, fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ const created = await service.provision({ agentId, provider: 'agent-mail' });++ await serverDB+ .update(agentAccounts)+ .set({ capabilities: { receive: false, send: true } })+ .where(eq(agentAccounts.id, created.id));++ // A fresh event id: the default replay store outlives a single test.+ const body = inboundBody(undefined, 'evt_receive_disabled');+ const outcome = await service.handleInbound('agent-mail', {+ body,+ headers: {+ 'x-agentmail-signature': computeAgentMailSignature(+ WEBHOOK_SECRET,+ body,+ Math.floor(Date.now() / 1000),+ ),+ },+ });++ expect(outcome).toMatchObject({+ accountId: created.id,+ event: { eventId: expect.any(String) },+ outcome: 'ignored',+ reason: 'receive-disabled',+ });+ expect(+ calls.some((call) => call.method === 'GET' && call.path.startsWith('/v1/messages')),+ ).toBe(false);+ });++ it('reports an unmapped address as an unknown account', async () => {+ const { fetchImpl } = createMailFetch();+ const service = buildService(fetchImpl);+ await service.provision({ agentId, provider: 'agent-mail' });++ const outcome = await service.handleInbound('agent-mail', {+ body: inboundBody('[email protected]'),+ headers: {},+ });++ expect(outcome.outcome).toBe('unknown-account');+ });+});diff --git a/apps/server/src/services/agentIdentity/__tests__/linqProvider.test.ts b/apps/server/src/services/agentIdentity/__tests__/linqProvider.test.tsnew file mode 100644index 00000000000..1081638e066--- /dev/null+++ b/apps/server/src/services/agentIdentity/__tests__/linqProvider.test.ts@@ -0,0 +1,303 @@+import {+ createInMemoryLinqWebhookDedupeStore,+ signLinqWebhookPayload,+} from '@lobechat/agent-address-linq';+import type { AgentAccountRef } from '@lobechat/types';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { createLinqProvider } from '../providers/linq';++/** A claim store of its own, so one test's accepted ids never leak into the next. */+const isolated = () => ({ dedupeStore: createInMemoryLinqWebhookDedupeStore() });++const SECRET = 'whsec_bGluZXNlY3JldA==';+const NOW = Date.parse('2026-10-02T00:00:00.000Z');+const TIMESTAMP = Math.floor(NOW / 1000);++const inboundBody = (overrides: Record<string, unknown> = {}) =>+ JSON.stringify({+ data: {+ chat: { id: 'chat_1' },+ id: 'msg_1',+ parts: [{ type: 'text', value: 'hello agent' }],+ sender_handle: { handle: '+15550001111' },+ sent_at: '2026-10-02T00:00:00.000Z',+ ...overrides,+ },+ event_type: 'message.received',+ });++const signed = (body: string, id = 'delivery_1') => ({+ headers: {+ 'webhook-id': id,+ 'webhook-signature': signLinqWebhookPayload({ body, id, secret: SECRET, timestamp: TIMESTAMP }),+ 'webhook-timestamp': String(TIMESTAMP),+ },+});++const ref = (overrides: Partial<AgentAccountRef> = {}): AgentAccountRef => ({+ credential: { webhookSecret: SECRET },+ id: 'acc_1',+ identifier: '+15550002222',+ kind: 'phone',+ metadata: { number: '+15550002222' },+ provider: 'linq',+ ...overrides,+});++describe('linq provider β declaration', () => {+ it('declares the phone identity it issues and what it can do', () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test' });++ expect(provider.provider).toBe('linq');+ expect(provider.kind).toBe('phone');+ expect(provider.capabilities).toEqual({ receive: true, send: true });+ });++ it('refuses to provision without an operator-provisioned number', async () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test' });++ await expect(provider.provision({ agentId: 'agent_7', userId: 'user_1' })).rejects.toThrow(+ /operator-provisioned number/,+ );+ });++ it('binds the configured number when one is available', async () => {+ const provider = createLinqProvider({+ ...isolated(),+ apiKey: 'linq_test',+ fromNumbers: ['+15550002222'],+ });++ await expect(provider.provision({ agentId: 'agent_7', userId: 'user_1' })).resolves.toEqual({+ identifier: '+15550002222',+ metadata: { number: '+15550002222' },+ });+ });++ it('binds the first number in the pool that no live account holds', async () => {+ const provider = createLinqProvider({+ apiKey: 'linq_test',+ fromNumbers: ['+15550002222', '+15550003333'],+ });+ const held = new Set(['+15550002222']);++ await expect(+ provider.provision({+ agentId: 'agent_8',+ isIdentifierHeld: async (number) => held.has(number),+ userId: 'user_1',+ }),+ ).resolves.toEqual({+ identifier: '+15550003333',+ metadata: { number: '+15550003333' },+ });+ });++ it('refuses with a readable capacity error once every number is held', async () => {+ const provider = createLinqProvider({+ ...isolated(),+ apiKey: 'linq_test',+ fromNumbers: ['+15550002222'],+ });++ await expect(+ provider.provision({+ agentId: 'agent_9',+ isIdentifierHeld: async () => true,+ userId: 'user_1',+ }),+ ).rejects.toMatchObject({+ code: 'capacity_exhausted',+ message: expect.stringMatching(/already in use by other agents/),+ });+ });+});++describe('linq provider β inbound', () => {+ it('routes by the addressed number, falling back to the configured one', () => {+ const withRecipient = createLinqProvider({ ...isolated(), apiKey: 'linq_test' });+ expect(+ withRecipient.resolveInboundIdentifier({+ body: inboundBody({ to: '+15550002222' }),+ headers: {},+ }),+ ).toBe('+15550002222');++ const fallback = createLinqProvider({+ ...isolated(),+ apiKey: 'linq_test',+ fromNumbers: ['+15550003333'],+ });+ expect(fallback.resolveInboundIdentifier({ body: inboundBody(), headers: {} })).toBe(+ '+15550003333',+ );+ });++ it('accepts a correctly signed delivery and rejects a forged one', async () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test', now: () => NOW });+ const body = inboundBody();++ await expect(+ provider.verifyInbound({ body, headers: signed(body).headers }, ref()),+ ).resolves.toEqual({+ eventId: 'delivery_1',+ payload: expect.objectContaining({ event_type: 'message.received' }),+ });++ await expect(+ provider.verifyInbound(+ { body, headers: { ...signed(body).headers, 'webhook-signature': 'v1,AAAA' } },+ ref(),+ ),+ ).resolves.toBeNull();+ });++ it('flags a replayed delivery as a duplicate', async () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test', now: () => NOW });+ const body = inboundBody();+ const headers = signed(body).headers;++ await expect(provider.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ eventId: 'delivery_1' }),+ );+ await expect(provider.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ duplicate: true }),+ );+ });++ it('remembers an accepted delivery across provider instances, as each webhook request builds one', async () => {+ const body = inboundBody();+ const headers = signed(body, 'delivery_cross_instance').headers;++ const firstRequest = createLinqProvider({ apiKey: 'linq_test', now: () => NOW });+ const secondRequest = createLinqProvider({ apiKey: 'linq_test', now: () => NOW });++ await expect(firstRequest.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ eventId: 'delivery_cross_instance' }),+ );+ await expect(secondRequest.verifyInbound({ body, headers }, ref())).resolves.toEqual(+ expect.objectContaining({ duplicate: true }),+ );+ });++ it('normalizes text and media parts into the transport-neutral message', async () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test', now: () => NOW });++ const message = await provider.normalizeInbound(+ {+ eventId: 'delivery_1',+ payload: JSON.parse(+ inboundBody({+ parts: [+ { type: 'text', value: 'look at this' },+ { type: 'media', url: 'https://cdn.linq.test/a.png' },+ ],+ }),+ ),+ },+ ref(),+ );++ expect(message).toMatchObject({+ from: '+15550001111',+ providerMessageId: 'msg_1',+ threadKey: 'chat_1',+ to: '+15550002222',+ });+ expect(message!.text).toBe('look at this');+ expect(message!.attachments).toEqual([+ { mimeType: 'application/octet-stream', url: 'https://cdn.linq.test/a.png' },+ ]);+ });++ it('drops a delivery with neither text nor media', async () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test', now: () => NOW });++ const message = await provider.normalizeInbound(+ { eventId: 'delivery_1', payload: JSON.parse(inboundBody({ parts: [] })) },+ ref(),+ );++ expect(message).toBeNull();+ });++ it('keeps an image-only message instead of dropping it', async () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test', now: () => NOW });++ const message = await provider.normalizeInbound(+ {+ eventId: 'delivery_1',+ payload: JSON.parse(+ inboundBody({ parts: [{ type: 'media', url: 'https://cdn.linq.test/b.jpg' }] }),+ ),+ },+ ref(),+ );++ expect(message).toMatchObject({ providerMessageId: 'msg_1', text: '' });+ expect(message!.attachments).toEqual([+ { mimeType: 'application/octet-stream', url: 'https://cdn.linq.test/b.jpg' },+ ]);+ });++ it('ignores events that are not a message a human sent to the number', async () => {+ const provider = createLinqProvider({ ...isolated(), apiKey: 'linq_test', now: () => NOW });++ const delivered = JSON.parse(inboundBody());+ const receipt = { ...delivered, event_type: 'message.delivered' };+ const echo = JSON.parse(inboundBody({ direction: 'outbound' }));++ await expect(+ provider.normalizeInbound({ eventId: 'delivery_1', payload: receipt }, ref()),+ ).resolves.toBeNull();+ await expect(+ provider.normalizeInbound({ eventId: 'delivery_2', payload: echo }, ref()),+ ).resolves.toBeNull();+ });++ it('does not guess a routing number when the deployment has a pool', () => {+ const provider = createLinqProvider({+ apiKey: 'linq_test',+ fromNumbers: ['+15550002222', '+15550003333'],+ });++ expect(provider.resolveInboundIdentifier({ body: inboundBody(), headers: {} })).toBeUndefined();+ });+});++describe('linq provider β outbound', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('sends into the existing chat and degrades markdown to plain text', async () => {+ const calls: Array<{ body?: unknown; method: string; url: string }> = [];+ vi.stubGlobal('fetch', (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = typeof input === 'string' ? input : input.toString();+ const method = init?.method ?? 'GET';+ calls.push({ body: init?.body ? JSON.parse(String(init.body)) : undefined, method, url });++ if (new URL(url).pathname === '/v3/chats') {+ return new Response(JSON.stringify({ chats: [{ id: 'chat_1' }] }), { status: 200 });+ }+ return new Response(JSON.stringify({ chat_id: 'chat_1', message: { id: 'msg_out_1' } }), {+ status: 200,+ });+ }) as typeof fetch);++ const provider = createLinqProvider({+ ...isolated(),+ apiKey: 'linq_test',+ fromNumbers: ['+15550002222'],+ });+ const result = await provider.send(ref(), {+ text: '**bold** and [link](https://x.test)',+ to: '+15550001111',+ });++ expect(result).toEqual({ providerMessageId: 'msg_out_1' });+ const send = calls.find((c) => c.method === 'POST');+ expect((send!.body as any).message.parts[0].value).toBe('bold and link (https://x.test)');+ });+});diff --git a/apps/server/src/services/agentIdentity/__tests__/providers.test.ts b/apps/server/src/services/agentIdentity/__tests__/providers.test.tsnew file mode 100644index 00000000000..53de9b960b8--- /dev/null+++ b/apps/server/src/services/agentIdentity/__tests__/providers.test.ts@@ -0,0 +1,116 @@+import { computeAgentMailSignature } from '@lobechat/agent-address-mail';+import { afterEach, describe, expect, it, vi } from 'vitest';++const { claimWebhookEvent, releaseWebhookEvent } = vi.hoisted(() => ({+ claimWebhookEvent: vi.fn(),+ releaseWebhookEvent: vi.fn(),+}));+vi.mock('@/server/services/redis', () => ({+ redisService: { agentIdentity: { claimWebhookEvent, releaseWebhookEvent } },+}));++/**+ * The deployment wiring: env key present β provider registered, absent β the+ * provider is omitted entirely (rather than registered broken). Reloaded per+ * test because the registry reads the env once at module load.+ */+const loadProviders = async () => {+ vi.resetModules();+ return import('../providers');+};++afterEach(() => {+ vi.unstubAllEnvs();+ vi.resetModules();+});++describe('createDefaultAgentAccountRegistry', () => {+ it('registers nothing when no provider key is configured', async () => {+ vi.stubEnv('AGENT_MAIL_API_KEY', '');+ vi.stubEnv('LINQ_API_KEY', '');++ const { createDefaultAgentAccountRegistry } = await loadProviders();++ expect(createDefaultAgentAccountRegistry().list()).toEqual([]);+ });++ it('registers only the provider whose key is present', async () => {+ vi.stubEnv('AGENT_MAIL_API_KEY', 'am_test');+ vi.stubEnv('LINQ_API_KEY', '');++ const { createDefaultAgentAccountRegistry } = await loadProviders();+ const registry = createDefaultAgentAccountRegistry();++ expect(registry.list().map((provider) => provider.provider)).toEqual(['agent-mail']);+ expect(registry.capabilities('agent-mail')).toEqual({ receive: true, send: true });+ });++ it('registers linq when its key is present and declares the phone capability', async () => {+ vi.stubEnv('AGENT_MAIL_API_KEY', '');+ vi.stubEnv('LINQ_API_KEY', 'linq_test');++ const { createDefaultAgentAccountRegistry } = await loadProviders();+ const registry = createDefaultAgentAccountRegistry();++ expect(registry.list().map((provider) => provider.provider)).toEqual(['linq']);+ expect(registry.get('linq').kind).toBe('phone');+ });++ it('builds an explicit registry from injected config, independent of env', async () => {+ vi.stubEnv('AGENT_MAIL_API_KEY', '');++ const { createAgentAccountRegistry } = await loadProviders();+ const registry = createAgentAccountRegistry({+ agentMail: { apiKey: 'am_injected' },+ linq: undefined,+ });++ expect(registry.list().map((provider) => provider.provider)).toEqual(['agent-mail']);+ expect(registry.get('agent-mail')).toMatchObject({+ capabilities: { receive: true, send: true },+ kind: 'mail',+ provider: 'agent-mail',+ });+ });++ it('backs Agent Mail replay claims with the shared Redis store, not per-process memory', async () => {+ vi.stubEnv('AGENT_MAIL_API_KEY', 'am_test');+ claimWebhookEvent.mockResolvedValueOnce(true).mockResolvedValueOnce(false);++ const { createDefaultAgentAccountRegistry } = await loadProviders();+ const provider = createDefaultAgentAccountRegistry().get('agent-mail');+ const body = JSON.stringify({+ createdAt: '2026-10-02T00:00:00.000Z',+ data: { inbox: { address: '[email protected]', clientId: null, id: 'inb_1' }, message: { id: 'm' } },+ id: 'evt_shared',+ type: 'message.received',+ });+ const request = {+ body,+ headers: {+ 'x-agentmail-signature': computeAgentMailSignature(+ 'whsec',+ body,+ Math.floor(Date.now() / 1000),+ ),+ },+ };+ const ref = {+ credential: { webhookSecret: 'whsec' },+ id: 'acc_1',+ identifier: '[email protected]',+ kind: 'mail' as const,+ metadata: { inboxId: 'inb_1' },+ provider: 'agent-mail',+ };++ // Another instance already accepted this event: Redis says so, and this+ // instance must treat it as a duplicate despite never having seen it.+ await expect(provider.verifyInbound(request, ref)).resolves.not.toHaveProperty('duplicate');+ await expect(provider.verifyInbound(request, ref)).resolves.toMatchObject({ duplicate: true });+ expect(claimWebhookEvent).toHaveBeenCalledWith(+ { eventId: 'evt_shared', provider: 'agent-mail' },+ expect.any(Number),+ );+ });+});diff --git a/apps/server/src/services/agentIdentity/__tests__/registry.test.ts b/apps/server/src/services/agentIdentity/__tests__/registry.test.tsnew file mode 100644index 00000000000..1939aa46d70--- /dev/null+++ b/apps/server/src/services/agentIdentity/__tests__/registry.test.ts@@ -0,0 +1,68 @@+import type { AgentAccountProvider } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { AgentAccountProviderRegistry } from '../registry';++/** A provider stub with sensible defaults; only the fields under test differ. */+const stubProvider = (overrides: Partial<AgentAccountProvider> = {}): AgentAccountProvider => ({+ capabilities: { receive: true, send: true },+ kind: 'mail',+ normalizeInbound: async () => null,+ provider: 'stub',+ provision: async () => ({ identifier: '[email protected]' }),+ release: async () => {},+ resolveInboundIdentifier: () => undefined,+ send: async () => ({ providerMessageId: 'm1' }),+ verifyInbound: async () => null,+ ...overrides,+});++describe('AgentAccountProviderRegistry', () => {+ it('resolves a registered provider by its provider id', () => {+ const registry = new AgentAccountProviderRegistry().register(stubProvider());++ expect(registry.has('stub')).toBe(true);+ expect(registry.get('stub').provider).toBe('stub');+ expect(registry.list()).toHaveLength(1);+ });++ it('refuses to register two providers under the same id', () => {+ const registry = new AgentAccountProviderRegistry().register(stubProvider());++ expect(() => registry.register(stubProvider())).toThrow(/already registered/);+ });++ it('fails an unknown provider with the list of registered ones', () => {+ const registry = new AgentAccountProviderRegistry().register(+ stubProvider({ provider: 'agent-mail' }),+ );++ expect(() => registry.get('linq')).toThrow(+ /Unknown agent account provider "linq".*agent-mail/s,+ );+ });++ it('says no provider is configured when the registry is empty', () => {+ expect(() => new AgentAccountProviderRegistry().get('linq')).toThrow(+ /no identity provider is configured/,+ );+ });++ it('reports the capability declaration of a provider', () => {+ const registry = new AgentAccountProviderRegistry().register(+ stubProvider({ capabilities: { receive: true, send: false } }),+ );++ expect(registry.capabilities('stub')).toEqual({ receive: true, send: false });+ });++ it('filters providers by the account kind they issue', () => {+ const registry = new AgentAccountProviderRegistry()+ .register(stubProvider({ provider: 'agent-mail', kind: 'mail' }))+ .register(stubProvider({ provider: 'linq', kind: 'phone' }));++ expect(registry.listByKind('phone').map((p) => p.provider)).toEqual(['linq']);+ expect(registry.listByKind('mail').map((p) => p.provider)).toEqual(['agent-mail']);+ expect(registry.listByKind('wallet')).toEqual([]);+ });+});diff --git a/apps/server/src/services/agentIdentity/errors.ts b/apps/server/src/services/agentIdentity/errors.tsnew file mode 100644index 00000000000..8976718d518--- /dev/null+++ b/apps/server/src/services/agentIdentity/errors.ts@@ -0,0 +1,49 @@+/**+ * Why an account write was refused, in terms a caller can show to a person.+ *+ * Conflicts β the request was valid, the deployment's state refuses it:+ * - `capacity_exhausted`: the provider hands out a finite operator inventory+ * (Linq numbers) and every unit is already bound to a live account.+ * - `identifier_taken`: another live account already routes on this handle, so+ * mounting it again would make inbound delivery ambiguous.+ *+ * Invalid requests β no state would make them succeed:+ * - `capabilities_required`: a mounted account's provider is not registered,+ * so only the caller can state what the account can do.+ * - `provider_managed`: the provider is registered, so its accounts are opened+ * through `provision`, never mounted from caller-supplied handles.+ * - `provider_owned_field`: the patch names a field the provider owns.+ * - `reply_target_not_owned`: the message named as a reply target lives in+ * another account's inbox, so answering it would send as that account.+ */+export type AgentAccountErrorCode =+ | 'capabilities_required'+ | 'capacity_exhausted'+ | 'identifier_taken'+ | 'provider_managed'+ | 'provider_owned_field'+ | 'reply_target_not_owned';++const INVALID_REQUEST_CODES = new Set<AgentAccountErrorCode>([+ 'capabilities_required',+ 'provider_managed',+ 'provider_owned_field',+ 'reply_target_not_owned',+]);++/** A refusal the transport layer maps to a 409 or a 400, never to a 500. */+export class AgentAccountError extends Error {+ readonly code: AgentAccountErrorCode;+ /** How a transport should answer: a state conflict (409) or a bad request (400). */+ readonly reason: 'conflict' | 'invalid';++ constructor(code: AgentAccountErrorCode, message: string) {+ super(message);+ this.code = code;+ this.name = 'AgentAccountError';+ this.reason = INVALID_REQUEST_CODES.has(code) ? 'invalid' : 'conflict';+ }+}++export const isAgentAccountError = (error: unknown): error is AgentAccountError =>+ error instanceof AgentAccountError;diff --git a/apps/server/src/services/agentIdentity/index.ts b/apps/server/src/services/agentIdentity/index.tsnew file mode 100644index 00000000000..56784ede8d5--- /dev/null+++ b/apps/server/src/services/agentIdentity/index.ts@@ -0,0 +1,518 @@+import type {+ AgentAccountCapabilities,+ AgentAccountCredentialHint,+ AgentAccountInboundEvent,+ AgentAccountInboundMessage,+ AgentAccountInboundRequest,+ AgentAccountKind,+ AgentAccountOutboundMessage,+ AgentAccountRef,+} from '@lobechat/types';++import type {+ AgentAccountGateKeeper,+ AgentAccountPatch,+ AgentAccountView,+} from '@/database/models/agentAccount';+import { AgentAccountModel, ROUTING_KEY_HELD_STATUSES } from '@/database/models/agentAccount';+import type { LobeChatDatabase } from '@/database/type';+import { assertAgentUsableBy } from '@/database/utils/agent-access';+import { unwrapPgError } from '@/server/modules/AgentRuntime/pgError';+import {+ assertCanEditResource,+ assertCanPerformResourceAction,+} from '@/server/services/resourcePermission';++import { AgentAccountError } from './errors';+import type { AgentAccountProviderRegistry } from './registry';+import { isReservedAgentAccountProvider } from './registry';++const PG_UNIQUE_VIOLATION = '23505';++export type { AgentAccountErrorCode } from './errors';+export { AgentAccountError, isAgentAccountError } from './errors';++/** Fields a caller may set when mounting an account it already has a handle for. */+export interface CreateAgentAccountParams {+ agentId: string;+ /**+ * What the account can do. Required: a mounted account's provider is never a+ * registered one (those go through `provision`), so nothing else can state it.+ */+ capabilities?: AgentAccountCapabilities;+ /** Write-only secret. Encrypted before it ever reaches the row. */+ credential?: Record<string, string>;+ credentialHint?: AgentAccountCredentialHint;+ displayName?: string;+ identifier: string;+ kind: AgentAccountKind;+ metadata?: Record<string, unknown>;+ provider: string;+}++/** Ask a provider to issue a brand-new account for the agent. */+export interface ProvisionAgentAccountParams {+ agentId: string;+ displayName?: string;+ provider: string;+}++export interface RevokeAgentAccountOptions {+ /** Also purge the stored credential. Default `true`. */+ purgeCredential?: boolean;+ /** Ask the provider to release its side first. Default `true`. */+ release?: boolean;+}++/** Why an authentic delivery produced no message. */+export type AgentAccountInboundIgnoredReason = 'duplicate' | 'filtered' | 'receive-disabled';++/**+ * What `handleInbound` decided, so the webhook route can pick a status code.+ *+ * Every authentic delivery carries its verified `event`, so the caller can+ * record it as a signal β including the ones that produce no message.+ */+export type AgentAccountInboundOutcome =+ | {+ accountId: string;+ event: AgentAccountInboundEvent;+ message: AgentAccountInboundMessage;+ outcome: 'delivered';+ }+ | {+ accountId: string;+ event: AgentAccountInboundEvent;+ outcome: 'ignored';+ reason: AgentAccountInboundIgnoredReason;+ }+ | { accountId?: string; outcome: 'rejected' | 'unknown-account' | 'unroutable' };++export interface AgentAccountServiceOptions {+ gateKeeper?: AgentAccountGateKeeper;+ registry: AgentAccountProviderRegistry;+ workspaceId?: string;+}++/**+ * Identity service: the one place that turns an `agent_accounts` row into+ * provider behaviour and back.+ *+ * It owns the orchestration only β resolve a provider, apply the credential+ * discipline the model enforces, and persist the provider's capability+ * declaration onto the row. All protocol detail lives in the provider; all+ * storage and scoping lives in {@link AgentAccountModel}.+ */+export class AgentAccountService {+ private readonly model: AgentAccountModel;+ private readonly db: LobeChatDatabase;+ private readonly userId: string;+ private readonly options: AgentAccountServiceOptions;++ constructor(db: LobeChatDatabase, userId: string, options: AgentAccountServiceOptions) {+ this.db = db;+ this.userId = userId;+ this.options = options;+ this.model = new AgentAccountModel(db, userId, options.gateKeeper, options.workspaceId);+ }++ // --------------- Reads (never return a credential) ---------------++ list = (query?: {+ agentId?: string;+ kind?: AgentAccountKind;+ provider?: string;+ }): Promise<AgentAccountView[]> => this.model.query(query);++ get = (id: string): Promise<AgentAccountView | undefined> => this.model.findById(id);++ // --------------- Writes ---------------++ /**+ * Mount an account whose handle already exists (a `user`-provided login, or+ * one issued out of band) under a provider this deployment does not run.+ *+ * A registered provider's accounts are opened through {@link provision} only.+ * Its send and release act on the stored handle with the deployment-wide key,+ * so a mounted handle β an inbox id the caller merely knows β would let the+ * caller send as, or delete, a resource that was never issued to them.+ */+ create = async (params: CreateAgentAccountParams): Promise<AgentAccountView> => {+ await this.assertCanEditAgent(params.agentId);++ // A reserved name is refused even when its provider is not registered: a+ // missing key only hides the provider, it does not make its handles+ // mountable. Otherwise an account mounted during that window would speak+ // and delete with the deployment-wide key once the key is restored.+ if (+ this.options.registry.has(params.provider) ||+ isReservedAgentAccountProvider(params.provider)+ ) {+ throw new AgentAccountError(+ 'provider_managed',+ `Accounts on the "${params.provider}" provider are opened through provisioning, not mounted.`,+ );+ }++ const { capabilities } = params;+ if (!capabilities) {+ throw new AgentAccountError(+ 'capabilities_required',+ `Agent account provider "${params.provider}" is not registered, so its capabilities cannot ` ++ 'be inferred. Pass capabilities explicitly when creating an account for an unregistered provider.',+ );+ }++ try {+ return await this.model.create({+ agentId: params.agentId,+ capabilities,+ credential: params.credential,+ credentialHint: params.credentialHint,+ displayName: params.displayName ?? null,+ identifier: params.identifier,+ kind: params.kind,+ metadata: params.metadata ?? {},+ provider: params.provider,+ // The handle already exists, so the account is usable as written; the+ // column default `provisioning` is for rows written ahead of the handle.+ status: 'active',+ });+ } catch (error) {+ throw this.toConflictError(error, params.provider, params.identifier) ?? error;+ }+ };++ /**+ * Open a new account through its provider and persist it. The account's kind+ * and capabilities come from the provider's declaration, never from the+ * caller β a provider is the only thing that knows what it issues.+ */+ provision = async (params: ProvisionAgentAccountParams): Promise<AgentAccountView> => {+ // Before the provider is asked to open anything: a refused caller must not+ // be able to make us create a remote inbox or bind a number at all.+ await this.assertCanEditAgent(params.agentId);++ const provider = this.options.registry.get(params.provider);+ const issued = await provider.provision({+ agentId: params.agentId,+ displayName: params.displayName,+ isIdentifierHeld: (identifier) =>+ AgentAccountModel.isRoutingKeyHeld(this.db, provider.provider, identifier),+ userId: this.userId,+ workspaceId: this.options.workspaceId,+ });++ try {+ return await this.model.create({+ agentId: params.agentId,+ capabilities: provider.capabilities,+ credential: issued.credential,+ credentialHint: issued.credentialHint,+ displayName: issued.displayName ?? params.displayName ?? null,+ identifier: issued.identifier,+ kind: provider.kind,+ metadata: issued.metadata ?? {},+ provider: provider.provider,+ // The provider has already issued the handle; record the terminal state.+ status: 'active',+ });+ } catch (error) {+ const conflict = this.toConflictError(error, provider.provider, issued.identifier);++ // Two very different failures land here, and the routing key settles both:+ //+ // - a unique violation means a live row already holds the handle. On an+ // idempotent provisioning retry that row is *this* account β the provider+ // contract makes `provision` idempotent, so it can hand back the very+ // inbox already backing the live row β and the first write simply+ // committed;+ // - any other error leaves the write's outcome unknown: the insert may have+ // committed and only its acknowledgement been lost.+ //+ // Only a live row counts. A released handle can be bound again, so the key+ // may carry both the revoked row and its replacement; reconciling against+ // the replaced one would release the resource the live account is using.+ // If even the lookup fails, keep the resource β an orphaned inbox can be+ // reaped, a broken account cannot be repaired by the user.+ let committed: AgentAccountView | undefined;+ try {+ committed = await AgentAccountModel.findByRoutingKey(+ this.db,+ provider.provider,+ issued.identifier,+ ROUTING_KEY_HELD_STATUSES,+ );+ } catch {+ throw conflict ?? error;+ }+ if (committed && committed.agentId === params.agentId) return committed;++ // The provider holds a resource (an inbox, a number binding) that no live+ // row of this agent points at. Hand it back so a failed write leaves+ // nothing billable behind; the release is best-effort because the original+ // error is the one worth surfacing.+ await provider+ .release({+ credential: issued.credential ?? null,+ // No row was written, so there is no account id to hand over.+ id: '',+ identifier: issued.identifier,+ kind: provider.kind,+ metadata: issued.metadata ?? {},+ provider: provider.provider,+ })+ .catch(() => undefined);++ throw conflict ?? error;+ }+ };++ /**+ * Patch the non-secret fields.+ *+ * `status` is deliberately not patchable: writing it here would free the+ * routing handle (the partial unique indexes stop counting revoked rows)+ * while skipping the provider release, the credential purge and `revokedAt`+ * β and could equally revive a row that had already been released. Lifecycle+ * moves through {@link revoke}.+ *+ * `metadata` of a registered provider's account is not patchable either: it+ * holds the provider-side handles (an inbox id) that send and release act on+ * with the deployment-wide key, so rewriting it would point the account at a+ * resource it was never issued.+ */+ update = async (id: string, patch: AgentAccountPatch): Promise<string | undefined> => {+ if ('status' in patch) {+ throw new Error(+ 'Agent account status is not patchable; release the account through `revoke` instead.',+ );+ }++ const account = await this.findEditable(id);+ if (!account) return undefined;++ if (+ 'metadata' in patch &&+ (this.options.registry.has(account.provider) ||+ isReservedAgentAccountProvider(account.provider))+ ) {+ throw new AgentAccountError(+ 'provider_owned_field',+ `Agent account metadata is owned by the "${account.provider}" provider and is not patchable.`,+ );+ }++ return this.model.update(id, patch);+ };++ /** Install or rotate a credential. Write-only: nothing reads it back out here. */+ setCredential = async (+ id: string,+ credential: Record<string, string>,+ hint?: Omit<AgentAccountCredentialHint, 'rotatedAt'>,+ ): Promise<string | undefined> => {+ if (!(await this.findEditable(id))) return undefined;++ return this.model.setCredential(id, credential, hint);+ };++ /**+ * Release the account on the provider side (when it is registered) and mark+ * the row revoked. Revocation always succeeds even if the provider is no+ * longer configured β a deployment that lost a key must still be able to+ * revoke the accounts it issued.+ */+ revoke = async (+ id: string,+ options: RevokeAgentAccountOptions = {},+ ): Promise<string | undefined> => {+ const release = options.release ?? true;+ const account = await this.findEditable(id);+ if (!account) return undefined;++ // Only the row that still holds the provider resource may release it.+ // Revoking an already-revoked row β or one revoked with `{ release: false }`+ // and then replaced by a re-provision on the deterministic client id β must+ // be side-effect free, or it deletes the inbox the live row now speaks+ // through.+ const holdsResource = ROUTING_KEY_HELD_STATUSES.includes(account.status);++ if (release && holdsResource && this.options.registry.has(account.provider)) {+ const credential = await this.model.getCredential(id);+ await this.options.registry.get(account.provider).release(this.toRef(account, credential));+ }++ return this.model.revoke(id, { purgeCredential: options.purgeCredential });+ };++ // --------------- Provider actions ---------------++ /** Send from one of the agent's accounts through its provider. */+ send = async (+ accountId: string,+ message: AgentAccountOutboundMessage,+ ): Promise<{ providerMessageId: string }> => {+ const account = await this.requireActiveAccount(accountId);+ // Sending is a *use* of the agent, not an edit of it. The account row is+ // scoped to the workspace and carries no visibility of its own, so the+ // model happily returns a colleague's private agent's account; without+ // this the caller would decrypt its credential and speak as that agent.+ await this.assertCanUseAgent(account.agentId);+ // The persisted capability is the account's contract (a phone line warming+ // up is receive-only), so it gates the irreversible provider call β not+ // the provider's declaration, which only seeds it at creation.+ if (!account.capabilities.send) {+ throw new Error(`Agent account ${accountId} is not allowed to send`);+ }+ const provider = this.options.registry.get(account.provider);+ const credential = await this.model.getCredential(accountId);++ return provider.send(this.toRef(account, credential), message);+ };++ /**+ * Route one inbound webhook delivery:+ *+ * 1. extract the routing identifier (untrusted) and resolve the account;+ * 2. verify the signature with that account's credential;+ * 3. normalize into the transport-neutral message.+ *+ * Only step 3's result is safe to hand onward β the earlier two answer the+ * webhook with 401/404 without producing a message.+ */+ handleInbound = async (+ providerName: string,+ request: AgentAccountInboundRequest,+ ): Promise<AgentAccountInboundOutcome> => {+ const provider = this.options.registry.get(providerName);++ const identifier = provider.resolveInboundIdentifier(request);+ if (!identifier) return { outcome: 'unroutable' };++ const resolved = await AgentAccountModel.findForInboundVerification(+ this.db,+ providerName,+ identifier,+ this.options.gateKeeper,+ );+ if (!resolved) return { outcome: 'unknown-account' };++ const ref = this.toRef(resolved.view, resolved.credential);++ const event = await provider.verifyInbound(request, ref);+ if (!event) return { accountId: resolved.view.id, outcome: 'rejected' };+ // Authentic but already handled: acknowledge so the provider stops+ // retrying, and produce nothing a second time.+ const accountId = resolved.view.id;+ if (event.duplicate) return { accountId, event, outcome: 'ignored', reason: 'duplicate' };+ // Same contract on the way in: a send-only account acknowledges the+ // delivery but must not turn it into agent work.+ if (!resolved.view.capabilities.receive) {+ return { accountId, event, outcome: 'ignored', reason: 'receive-disabled' };+ }++ const message = await provider.normalizeInbound(event, ref);+ if (!message) return { accountId, event, outcome: 'ignored', reason: 'filtered' };++ return { accountId, event, message, outcome: 'delivered' };+ };++ // --------------- Internals ---------------++ /**+ * An account binds an address *and a credential* to an agent, so writing one+ * needs the agent's effective **edit** level β the same rule the transports+ * apply, so a collaborator they admit is not refused here, and a member who+ * may merely view or use a shared agent is refused everywhere.+ *+ * Visibility first: an agent the caller cannot see answers NOT_FOUND, so the+ * ACL never becomes an oracle for a colleague's private agent. Outside a+ * workspace the visibility check alone is ownership.+ */+ private assertCanEditAgent = async (agentId: string): Promise<void> => {+ const ctx = { userId: this.userId, workspaceId: this.options.workspaceId };+ await assertAgentUsableBy(this.db, agentId, ctx);+ await assertCanEditResource({+ db: this.db,+ resourceId: agentId,+ resourceType: 'agent',+ ...ctx,+ });+ };++ /**+ * The rule for acting *through* an agent: visibility first, then the `use`+ * level. Sending from the agent's account is not an edit β a member may hold+ * `use` without holding `edit` β so this cannot reuse {@link assertCanEditAgent}.+ * Outside a workspace visibility alone is ownership, exactly as there.+ */+ private assertCanUseAgent = async (agentId: string): Promise<void> => {+ const workspaceId = this.options.workspaceId;+ const userId = this.userId;+ await assertAgentUsableBy(this.db, agentId, { userId, workspaceId });+ if (!workspaceId) return;++ await assertCanPerformResourceAction({+ action: 'use',+ db: this.db,+ resourceId: agentId,+ resourceType: 'agent',+ userId,+ workspaceId,+ });+ };++ /**+ * Load an account for a mutation, under the same edit rule as {@link create}+ * and {@link provision}. The model's scope alone is not enough: in a+ * workspace it matches every member's accounts, so without this any member+ * could rotate the creator's secret, rewrite the account or release it on+ * the provider.+ */+ private findEditable = async (id: string): Promise<AgentAccountView | undefined> => {+ const account = await this.model.findById(id);+ if (!account) return undefined;++ await this.assertCanEditAgent(account.agentId);+ return account;+ };++ /** Turn a routing-key unique violation into a refusal a person can act on. */+ private toConflictError = (+ error: unknown,+ provider: string,+ identifier: string,+ ): AgentAccountError | undefined => {+ if (unwrapPgError(error)?.code !== PG_UNIQUE_VIOLATION) return undefined;++ return new AgentAccountError(+ 'identifier_taken',+ `${identifier} is already bound to another agent on ${provider}. Release that account first.`,+ );+ };++ private requireActiveAccount = async (accountId: string): Promise<AgentAccountView> => {+ const account = await this.model.findById(accountId);+ if (!account) throw new Error(`Agent account ${accountId} was not found in this scope`);+ // Same liveness rule as inbound routing: `provisioning` is usable the+ // moment the row exists, while `suspended` and `revoked` must stop the+ // irreversible provider call, not just inbound delivery.+ if (account.status !== 'active' && account.status !== 'provisioning') {+ throw new Error(`Agent account ${accountId} is ${account.status} and cannot be used`);+ }+ return account;+ };++ private toRef = (+ view: AgentAccountView,+ credential?: Record<string, string> | null,+ ): AgentAccountRef => ({+ credential,+ id: view.id,+ identifier: view.identifier,+ kind: view.kind,+ metadata: view.metadata ?? {},+ provider: view.provider,+ });+}diff --git a/apps/server/src/services/agentIdentity/providers/agentMail.ts b/apps/server/src/services/agentIdentity/providers/agentMail.tsnew file mode 100644index 00000000000..ce348819ee7--- /dev/null+++ b/apps/server/src/services/agentIdentity/providers/agentMail.ts@@ -0,0 +1,339 @@+import type { LinqWebhookDedupeStore } from '@lobechat/agent-address-linq';+import { createInMemoryLinqWebhookDedupeStore } from '@lobechat/agent-address-linq';+import type { EmailMessageDetail, EmailWebhookEvent } from '@lobechat/agent-address-mail';+import {+ checkInboundEmail,+ LobeMailApiClient,+ LobeMailApiError,+ parseRawHeaders,+ stripQuotedReply,+ verifyAgentMailSignature,+} from '@lobechat/agent-address-mail';+import type {+ AgentAccountInboundEvent,+ AgentAccountInboundMessage,+ AgentAccountInboundRequest,+ AgentAccountOutboundMessage,+ AgentAccountProvider,+ AgentAccountProvisionInput,+ AgentAccountProvisionResult,+ AgentAccountRef,+} from '@lobechat/types';++import { AgentAccountError } from '../errors';++/** Server-side configuration for the Agent Mail (`lobe.id`) provider. */+export interface AgentMailProviderConfig {+ /** REST base override. Defaults to the package's `https://api.lobe.id`. */+ apiBaseUrl?: string;+ /** Agent Mail API key (`am_β¦`). */+ apiKey: string;+ /**+ * Replay store keyed by webhook event id. The claim-store shape is+ * transport-neutral, so the bounded in-memory store Linq ships is reused as+ * the single-process default; the deployment registry injects the shared+ * Redis-backed one.+ */+ dedupeStore?: LinqWebhookDedupeStore;+ /** Injected fetch, for tests and offline acceptance. */+ fetchImpl?: typeof fetch;+ /**+ * Shared webhook signing secret. Used only when the account itself carries no+ * per-inbox secret; a per-account secret always wins.+ */+ webhookSecret?: string;+ /**+ * Public HTTPS endpoint to register for this inbox. When present, provisioning+ * also creates the webhook and stores its one-time secret as the account+ * credential. Without a reachable public URL there is nothing to register, so+ * provisioning stays inbox-only.+ */+ webhookUrl?: string;+}++const parse = <T>(body: string): T | undefined => {+ try {+ return JSON.parse(body) as T;+ } catch {+ return undefined;+ }+};++/** Mask a secret for the non-secret hint β enough to tell two apart, never to use. */+const maskSecret = (secret: string): string =>+ secret.length <= 4 ? 'β’β’β’β’' : `β’β’β’β’${secret.slice(-4)}`;++/**+ * How long an accepted event id is remembered. Comfortably wider than the+ * signature tolerance, so a captured delivery cannot be replayed while its+ * signature still verifies.+ */+const EVENT_ID_TTL_SECONDS = 24 * 60 * 60;++/**+ * Process-wide default replay store. The deployment builds a fresh registry β+ * and so a fresh provider β for every webhook request, so a store created per+ * provider would forget each claim as soon as the request ended.+ */+const defaultDedupeStore = createInMemoryLinqWebhookDedupeStore();++const messageIdOf = (detail: { id?: string } | null | undefined): string => detail?.id ?? '';++/**+ * The Agent Mail (`lobe.id`) provider: an agent's own `mail` address.+ *+ * Thin by design β every byte of protocol work (REST, signature over the raw+ * body, quoted-history stripping, loop protection) already lives in+ * `@lobechat/agent-address-mail`. This layer only translates the provider+ * contract into those calls and declares what a mail account can do.+ */+export const createAgentMailProvider = (+ config: AgentMailProviderConfig,+): AgentAccountProvider<'mail'> => {+ const client = new LobeMailApiClient({+ apiKey: config.apiKey,+ baseUrl: config.apiBaseUrl,+ fetchImpl: config.fetchImpl,+ });++ const dedupeStore = config.dedupeStore ?? defaultDedupeStore;++ const inboxIdOf = (ref: AgentAccountRef): string => {+ const fromMetadata = ref.metadata?.inboxId;+ return typeof fromMetadata === 'string' && fromMetadata.length > 0+ ? fromMetadata+ : ref.identifier;+ };++ /**+ * Answer `providerMessageId` as the account behind `ref`.+ *+ * The reply route acts on the inbox that owns the message, not on the inbox+ * the caller asked us to send from β and one deployment API key spans every+ * inbox. Replying to an id from another account would therefore speak as that+ * account, skipping the lifecycle and capability checks this call already+ * passed for `ref`. The target is resolved first and refused unless it lives+ * in this account's inbox.+ */+ const replyInOwningInbox = async (+ ref: AgentAccountRef,+ providerMessageId: string,+ text: string,+ ): Promise<EmailMessageDetail> => {+ const inboxId = inboxIdOf(ref);+ const target = await client.getMessage(providerMessageId);+ if (target.inboxId !== inboxId) {+ throw new AgentAccountError(+ 'reply_target_not_owned',+ `Message ${providerMessageId} belongs to another agent's inbox, so it cannot be ` ++ `answered as ${inboxId}. Reply from the account that received it.`,+ );+ }++ return client.replyToMessage(providerMessageId, { text });+ };++ return {+ /** A mailbox can receive and send, and nothing else today. */+ capabilities: { receive: true, send: true },+ kind: 'mail',+ provider: 'agent-mail',++ provision: async (input: AgentAccountProvisionInput): Promise<AgentAccountProvisionResult> => {+ // `clientId` is the mail API's idempotency key: a retry for the same agent+ // gets the inbox it already opened instead of a second, billable one.+ const inbox = await client.createInbox({+ clientId: input.agentId,+ displayName: input.displayName,+ endUserId: input.agentId,+ });+ const identity: AgentAccountProvisionResult = {+ identifier: inbox.address,+ metadata: { clientId: inbox.clientId ?? null, inboxId: inbox.id },+ };++ // A live row already routes on this inbox: an earlier attempt committed+ // and only its response was lost. That row holds the webhook secret, so+ // registering again would only mint a second webhook whose secret nothing+ // stores. Hand back the inbox; the service reconciles to the live row.+ if (await input.isIdentifierHeld?.(inbox.address)) return identity;++ let credential: Record<string, string> | undefined;+ let credentialHint: AgentAccountProvisionResult['credentialHint'];++ if (config.webhookUrl) {+ let webhook: Awaited<ReturnType<typeof client.createWebhook>>;+ try {+ webhook = await client.createWebhook({ inboxId: inbox.id, url: config.webhookUrl });+ } catch (error) {+ // The inbox already exists but nothing will ever point at it: the+ // service only learns about an account once provision returns. Hand+ // it back here, or every retry during a webhook outage leaks one.+ //+ // Unless a concurrent request already bound it. `clientId` is+ // deterministic per agent, so two provisioning calls for the same+ // agent get this same inbox; if the other one committed an account+ // before this webhook call failed, deleting the inbox here would+ // dismantle a live mailbox the service is happily routing.+ if (!(await input.isIdentifierHeld?.(inbox.address))) {+ await client.deleteInbox(inbox.id).catch(() => undefined);+ }+ throw error;+ }+ if (webhook.secret) {+ credential = { webhookSecret: webhook.secret };+ credentialHint = { masked: maskSecret(webhook.secret) };+ }+ }++ return { ...identity, credential, credentialHint };+ },++ release: async (ref: AgentAccountRef): Promise<void> => {+ try {+ await client.deleteInbox(inboxIdOf(ref));+ } catch (error) {+ // Release is idempotent by contract: an inbox that is already gone is+ // exactly the state a release asks for, so a retried revoke succeeds.+ if (error instanceof LobeMailApiError && error.status === 404) return;+ throw error;+ }+ },++ send: async (+ ref: AgentAccountRef,+ message: AgentAccountOutboundMessage,+ ): Promise<{ providerMessageId: string }> => {+ // Answering a specific message goes through the reply route: the mail API+ // threads it (`In-Reply-To`/`References`, recipients inherited), while+ // `sendMessage` would open a second conversation carrying the same subject+ // and drop the human's thread. `threadKey` is the RFC root key, which is+ // not a message id, so it cannot address the reply.+ const detail = message.replyToProviderMessageId+ ? await replyInOwningInbox(ref, message.replyToProviderMessageId, message.text)+ : await client.sendMessage(inboxIdOf(ref), {+ subject: message.subject ?? '',+ text: message.text,+ to: message.to,+ });++ return { providerMessageId: messageIdOf(detail) };+ },++ resolveInboundIdentifier: (request: AgentAccountInboundRequest): string | undefined => {+ const event = parse<EmailWebhookEvent>(request.body);+ return event?.data?.inbox?.address || undefined;+ },++ verifyInbound: async (+ request: AgentAccountInboundRequest,+ ref: AgentAccountRef,+ ): Promise<AgentAccountInboundEvent | null> => {+ const secret = ref.credential?.webhookSecret ?? config.webhookSecret;+ if (!secret) return null;++ const verified = verifyAgentMailSignature({+ body: request.body,+ header: request.headers['x-agentmail-signature'],+ secret,+ });+ if (!verified) return null;++ const event = parse<EmailWebhookEvent>(request.body);+ if (!event?.id || !event.data?.message?.id) return null;++ // Signature first, then the claim: claiming before verifying would let an+ // unauthenticated caller burn ids and suppress real deliveries.+ const fresh = await dedupeStore.claim(event.id, EVENT_ID_TTL_SECONDS);++ const accepted = {+ eventId: event.id,+ occurredAt: event.createdAt ? new Date(event.createdAt) : undefined,+ payload: event,+ type: event.type,+ };+ return fresh ? accepted : { ...accepted, duplicate: true };+ },++ normalizeInbound: async (+ event: AgentAccountInboundEvent,+ ref: AgentAccountRef,+ ): Promise<AgentAccountInboundMessage | null> => {+ const payload = event.payload as EmailWebhookEvent;+ const inboxAddress = payload.data?.inbox?.address ?? ref.identifier;+ const summaryId = payload.data?.message?.id;+ if (!summaryId) return null;++ // The webhook carries only a summary; the body (and the raw source the+ // header-based loop guard needs) must be fetched back.+ let detail: Awaited<ReturnType<typeof client.getMessage>>;+ try {+ detail = await client.getMessage(summaryId);+ } catch (error) {+ // The event id was claimed in verifyInbound. Give it back so the+ // provider's retry is processed rather than acknowledged as a+ // duplicate β otherwise one transient fetch failure drops the email.+ await dedupeStore.release?.(event.eventId);+ throw error;+ }+ // The fetch back runs with the deployment key, so it is not scoped to+ // this account's inbox: the summary only names a message id. An editor+ // who installs their own webhook secret could otherwise pair their own+ // inbox address with a foreign message id and be handed its contents.+ if (detail.inboxId !== inboxIdOf(ref)) return null;++ const raw = await client.getRawMessage(summaryId);+ const headers = raw ? parseRawHeaders(raw) : null;++ const from = detail.from?.address ?? '';+ const decision = checkInboundEmail({+ from,+ headers,+ inboxAddress,+ subject: detail.subject,+ });+ // Autoresponders, bounces and mailing lists are dropped at the provider+ // boundary: answering them is how an agent talks to a robot forever.+ if (decision.ignored) return null;++ // The mail API serves attachment bytes only behind the deployment's API+ // key, so the URL is that endpoint: it names the message and index the+ // bytes are retrieved by, rather than a link anyone can open.+ const attachments = (detail.attachments ?? []).map((attachment) => ({+ mimeType: attachment.contentType || 'application/octet-stream',+ name: attachment.filename ?? undefined,+ size: attachment.size,+ url: `${client.baseUrl}/v1/messages/${encodeURIComponent(detail.id)}/attachments/${attachment.index}`,+ }));++ const addresses = (list: Array<{ address: string; name?: string }> | null | undefined) =>+ (list ?? []).map(({ address, name }) => (name ? { address, name } : { address }));++ return {+ attachments: attachments.length > 0 ? attachments : undefined,+ from,+ mail: {+ attachments: (detail.attachments ?? []).map((attachment) => ({+ contentType: attachment.contentType,+ filename: attachment.filename ?? undefined,+ index: attachment.index,+ size: attachment.size,+ })),+ cc: addresses(detail.cc),+ fromName: detail.from?.name || undefined,+ inReplyTo: detail.inReplyTo ?? undefined,+ messageId: detail.messageId ?? undefined,+ references: detail.references ?? [],+ replyTo: addresses(detail.replyTo),+ to: addresses(detail.to),+ },+ providerMessageId: detail.id,+ receivedAt: new Date(detail.receivedAt),+ subject: detail.subject ?? undefined,+ text: detail.text ? stripQuotedReply(detail.text) : '',+ threadKey: detail.references?.[0] ?? detail.messageId ?? undefined,+ to: inboxAddress,+ };+ },+ };+};diff --git a/apps/server/src/services/agentIdentity/providers/index.ts b/apps/server/src/services/agentIdentity/providers/index.tsnew file mode 100644index 00000000000..9c02d9e8524--- /dev/null+++ b/apps/server/src/services/agentIdentity/providers/index.ts@@ -0,0 +1,79 @@+import { agentIdentityEnv } from '@/envs/agentIdentity';+import { redisService } from '@/server/services/redis';++import { AgentAccountProviderRegistry } from '../registry';+import type { AgentMailProviderConfig } from './agentMail';+import { createAgentMailProvider } from './agentMail';+import type { LinqProviderConfig } from './linq';+import { createLinqProvider } from './linq';++export type { AgentMailProviderConfig } from './agentMail';+export { createAgentMailProvider } from './agentMail';+export type { LinqProviderConfig } from './linq';+export { createLinqProvider } from './linq';++/** `LINQ_FROM_NUMBER` is a comma-separated pool; one number is a pool of one. */+const parseNumberPool = (value: string | undefined): string[] =>+ (value ?? '')+ .split(',')+ .map((number) => number.trim())+ .filter(Boolean);++/** Which providers a deployment has wired up. Omitted = not registered. */+export interface AgentIdentityProviderConfig {+ agentMail?: AgentMailProviderConfig;+ linq?: LinqProviderConfig;+}++/**+ * Build a registry from an explicit config. Pure and injectable, so tests and+ * offline acceptance can register providers with fixture keys and a mock fetch+ * instead of reading deployment env.+ */+export const createAgentAccountRegistry = (+ config: AgentIdentityProviderConfig,+): AgentAccountProviderRegistry => {+ const registry = new AgentAccountProviderRegistry();++ if (config.agentMail) registry.register(createAgentMailProvider(config.agentMail));+ if (config.linq) registry.register(createLinqProvider(config.linq));++ return registry;+};++/**+ * The deployment registry: register each provider whose credentials are+ * present. A missing key omits the provider entirely rather than registering a+ * broken one, so `registry.get('linq')` fails with the real reason.+ */+export const createDefaultAgentAccountRegistry = (): AgentAccountProviderRegistry =>+ createAgentAccountRegistry({+ agentMail:+ agentIdentityEnv.ENABLED_AGENT_MAIL && agentIdentityEnv.AGENT_MAIL_API_KEY+ ? {+ apiBaseUrl: agentIdentityEnv.AGENT_MAIL_API_BASE_URL,+ apiKey: agentIdentityEnv.AGENT_MAIL_API_KEY,+ // Shared across instances: a retry or replay can land on any worker.+ dedupeStore: {+ claim: (eventId, ttlSeconds) =>+ redisService.agentIdentity.claimWebhookEvent(+ { eventId, provider: 'agent-mail' },+ ttlSeconds,+ ),+ release: (eventId) =>+ redisService.agentIdentity.releaseWebhookEvent({ eventId, provider: 'agent-mail' }),+ },+ webhookSecret: agentIdentityEnv.AGENT_MAIL_WEBHOOK_SECRET,+ webhookUrl: agentIdentityEnv.AGENT_MAIL_WEBHOOK_URL,+ }+ : undefined,+ linq:+ agentIdentityEnv.ENABLED_LINQ && agentIdentityEnv.LINQ_API_KEY+ ? {+ apiBaseUrl: agentIdentityEnv.LINQ_API_BASE_URL,+ apiKey: agentIdentityEnv.LINQ_API_KEY,+ fromNumbers: parseNumberPool(agentIdentityEnv.LINQ_FROM_NUMBER),+ webhookSecret: agentIdentityEnv.LINQ_WEBHOOK_SECRET,+ }+ : undefined,+ });diff --git a/apps/server/src/services/agentIdentity/providers/linq.ts b/apps/server/src/services/agentIdentity/providers/linq.tsnew file mode 100644index 00000000000..74760d51d3d--- /dev/null+++ b/apps/server/src/services/agentIdentity/providers/linq.ts@@ -0,0 +1,243 @@+import type {+ LinqInboundMessage,+ LinqMessagePart,+ LinqWebhookDedupeStore,+ LinqWebhookEvent,+ LinqWebhookSignatureHeaders,+} from '@lobechat/agent-address-linq';+import {+ createInMemoryLinqWebhookDedupeStore,+ LinqApiClient,+ LinqWebhookDeduplicator,+ markdownToPlainText,+ verifyLinqWebhookSignature,+} from '@lobechat/agent-address-linq';+import type {+ AgentAccountAttachment,+ AgentAccountInboundEvent,+ AgentAccountInboundMessage,+ AgentAccountInboundRequest,+ AgentAccountOutboundMessage,+ AgentAccountProvider,+ AgentAccountProvisionInput,+ AgentAccountProvisionResult,+ AgentAccountRef,+} from '@lobechat/types';++import { AgentAccountError } from '../errors';++/** Server-side configuration for the Linq (iMessage / SMS) provider. */+export interface LinqProviderConfig {+ /** REST base override. Defaults to the package's `https://api.linqapp.com/v3`. */+ apiBaseUrl?: string;+ /** Linq partner API key. */+ apiKey: string;+ /** Multi-instance replay store; defaults to the package's in-memory store. */+ dedupeStore?: LinqWebhookDedupeStore;+ /**+ * The operator's Linq number pool, in E.164. Linq numbers are carrier+ * inventory rather than something the REST API mints, so provisioning binds+ * the first free number to the agent. One number backs one live account β a+ * deployment opens as many phone accounts as it has numbers.+ */+ fromNumbers?: string[];+ /** Injectable clock, in milliseconds (signature tolerance, `receivedAt` fallback). */+ now?: () => number;+ /** Shared Linq webhook signing secret (`whsec_β¦`). */+ webhookSecret?: string;+}++/**+ * Process-wide default replay store. The deployment builds a fresh registry β+ * and so a fresh provider β for every webhook request, so a store created per+ * provider would forget each claim as soon as the request ended.+ */+const defaultDedupeStore = createInMemoryLinqWebhookDedupeStore();++/** The only event that carries a message a human sent to the number. */+const INBOUND_EVENT_TYPE = 'message.received';++const parse = <T>(body: string): T | undefined => {+ try {+ return JSON.parse(body) as T;+ } catch {+ return undefined;+ }+};++const asString = (value: unknown): string | undefined =>+ typeof value === 'string' && value.length > 0 ? value : undefined;++/** The human's handle, across the shapes Linq serializes a sender in. */+const senderHandle = (data: LinqInboundMessage): string | undefined => {+ const handle = data.sender_handle?.handle;+ if (handle) return handle;+ if (typeof data.sender === 'string') return asString(data.sender);+ return data.sender?.handle;+};++/** A Linq message is made of parts; only the text parts carry prose. */+const partsToText = (parts: LinqMessagePart[] | undefined): string =>+ (parts ?? [])+ .filter((part): part is Extract<LinqMessagePart, { type: 'text' }> => part.type === 'text')+ .map((part) => part.value)+ .join('\n')+ .trim();++/** Media parts are only usable downstream when Linq hosts the bytes at a URL. */+const partsToAttachments = (parts: LinqMessagePart[] | undefined): AgentAccountAttachment[] =>+ (parts ?? [])+ .filter(+ (part): part is Extract<LinqMessagePart, { type: 'media' }> =>+ part.type === 'media' && !!part.url,+ )+ .map((part) => ({ mimeType: 'application/octet-stream', url: part.url! }));++/**+ * The Linq provider: an agent's own `phone` address on LobeHub's carrier+ * account.+ *+ * Linq is a carrier, not a social platform, so there is no per-agent bot+ * registration and nothing here models threads/typing as platform features β+ * inbound is normalized to the same message shape every other provider+ * produces.+ */+export const createLinqProvider = (config: LinqProviderConfig): AgentAccountProvider<'phone'> => {+ const pool = config.fromNumbers ?? [];+ const deduplicator = new LinqWebhookDeduplicator(config.dedupeStore ?? defaultDedupeStore);++ return {+ /** A phone number can receive and send. */+ capabilities: { receive: true, send: true },+ kind: 'phone',+ provider: 'linq',++ provision: async (input: AgentAccountProvisionInput): Promise<AgentAccountProvisionResult> => {+ if (pool.length === 0) {+ throw new Error(+ 'Linq provisioning needs an operator-provisioned number: set LINQ_FROM_NUMBER ' ++ '(or pass fromNumbers to createLinqProvider) before opening a phone account.',+ );+ }++ for (const number of pool) {+ if (input.isIdentifierHeld && (await input.isIdentifierHeld(number))) continue;+ return { identifier: number, metadata: { number } };+ }++ throw new AgentAccountError(+ 'capacity_exhausted',+ `All ${pool.length} phone number(s) on this deployment are already in use by other ` ++ 'agents. Release a phone account or ask the operator to add a number.',+ );+ },++ release: async (_ref: AgentAccountRef): Promise<void> => {+ // Linq numbers are carrier inventory owned by the deployment and the REST+ // API exposes no release; revoking the account drops the binding locally.+ // Releasing the number itself is an operator action.+ },++ send: async (+ ref: AgentAccountRef,+ message: AgentAccountOutboundMessage,+ ): Promise<{ providerMessageId: string }> => {+ const fromNumber = asString(ref.metadata?.number) ?? ref.identifier;+ const client = new LinqApiClient({+ apiKey: config.apiKey,+ baseUrl: config.apiBaseUrl,+ fromNumber,+ });++ const sent = await client.sendToHandle({+ handle: message.to,+ // Linq delivers text verbatim, so markdown has to be degraded first.+ text: markdownToPlainText(message.text),+ });++ return { providerMessageId: sent.message?.id ?? '' };+ },++ resolveInboundIdentifier: (request: AgentAccountInboundRequest): string | undefined => {+ const event = parse<LinqWebhookEvent>(request.body);+ if (!event) return undefined;++ const data = (event.data ?? {}) as Record<string, unknown>;+ // The number the delivery was addressed to is the routing key. Field+ // naming has moved across Linq API versions, so accept the known+ // spellings and fall back to the deployment's number only when there is+ // exactly one β with a pool, guessing would deliver to the wrong agent.+ return (+ asString(data.to) ??+ asString(data.phone_number) ??+ asString(data.recipient) ??+ asString(event.to) ??+ asString(event.phone_number) ??+ (pool.length === 1 ? pool[0] : undefined)+ );+ },++ verifyInbound: async (+ request: AgentAccountInboundRequest,+ ref: AgentAccountRef,+ ): Promise<AgentAccountInboundEvent | null> => {+ const secret = ref.credential?.webhookSecret ?? config.webhookSecret;+ if (!secret) return null;++ const headers: LinqWebhookSignatureHeaders = {+ id: request.headers['webhook-id'] ?? '',+ signature: request.headers['webhook-signature'] ?? '',+ timestamp: request.headers['webhook-timestamp'] ?? '',+ };++ const verified = verifyLinqWebhookSignature({+ body: request.body,+ headers,+ now: config.now?.(),+ secret,+ });+ // Signature first, always: claiming an id before verifying lets an+ // unauthenticated caller burn ids and suppress real deliveries.+ if (!verified.ok) return null;++ if (!headers.id) return null;++ const event = parse<LinqWebhookEvent>(request.body);+ if (!event || typeof event.event_type !== 'string') return null;++ return (await deduplicator.isDuplicate(headers.id))+ ? { duplicate: true, eventId: headers.id, payload: event }+ : { eventId: headers.id, payload: event };+ },++ normalizeInbound: async (+ event: AgentAccountInboundEvent,+ ref: AgentAccountRef,+ ): Promise<AgentAccountInboundMessage | null> => {+ const payload = event.payload as LinqWebhookEvent<LinqInboundMessage>;+ // Linq signs every event type to the same endpoint β delivery receipts,+ // reactions and the echo of our own sends included. Only a message a+ // human sent to the number is inbound; anything else would wake the agent+ // on its own outbound.+ if (payload.event_type !== INBOUND_EVENT_TYPE) return null;++ const data = payload.data;+ if (!data?.id || data.direction === 'outbound') return null;++ const text = partsToText(data.parts);+ const attachments = partsToAttachments(data.parts);+ // A photo with no caption is still a message.+ if (!text && attachments.length === 0) return null;++ return {+ attachments: attachments.length > 0 ? attachments : undefined,+ from: senderHandle(data) ?? 'unknown',+ providerMessageId: data.id,+ receivedAt: new Date(data.sent_at ?? new Date(config.now?.() ?? Date.now()).toISOString()),+ text,+ threadKey: data.chat?.id,+ to: ref.identifier,+ };+ },+ };+};diff --git a/apps/server/src/services/agentIdentity/registry.ts b/apps/server/src/services/agentIdentity/registry.tsnew file mode 100644index 00000000000..5a1a5a85d7d--- /dev/null+++ b/apps/server/src/services/agentIdentity/registry.ts@@ -0,0 +1,85 @@+import type {+ AgentAccountCapabilities,+ AgentAccountKind,+ AgentAccountProvider,+} from '@lobechat/types';++/**+ * Provider names this codebase implements, reserved whether or not the+ * deployment currently has credentials for them.+ *+ * Registration is credential-gated β a missing key omits the provider β so the+ * registry alone cannot answer "is this name ours?". It must not: an account+ * mounted while the key is absent would become usable, and would act with the+ * deployment-wide key, the moment the key comes back. Keep this list in sync+ * with the providers under `./providers`.+ */+export const RESERVED_AGENT_ACCOUNT_PROVIDERS = ['agent-mail', 'linq'] as const;++/** Whether a provider name belongs to this codebase, credentials aside. */+export const isReservedAgentAccountProvider = (provider: string): boolean =>+ (RESERVED_AGENT_ACCOUNT_PROVIDERS as readonly string[]).includes(provider);++/**+ * The set of account providers this deployment can issue accounts from.+ *+ * Registration is explicit and provider-name keyed, so a caller can never+ * invent a provider at runtime: `get('linq')` either returns the provider the+ * deployment registered or fails with the list of ones it did. That is the+ * whole point of a registry here β the account row stores a `provider` string,+ * and this is what turns that string back into behaviour.+ */+export class AgentAccountProviderRegistry {+ private readonly providers = new Map<string, AgentAccountProvider>();++ /**+ * Register a provider. Re-registering the same name is a programming error,+ * not a silent override: two implementations for one `provider` value would+ * make the account row ambiguous about which one issued it.+ */+ register(provider: AgentAccountProvider): this {+ if (this.providers.has(provider.provider)) {+ throw new Error(`Agent account provider "${provider.provider}" is already registered`);+ }++ this.providers.set(provider.provider, provider);+ return this;+ }++ has(provider: string): boolean {+ return this.providers.has(provider);+ }++ /** Resolve a provider, with an actionable error when it is not configured. */+ get(provider: string): AgentAccountProvider {+ const resolved = this.providers.get(provider);+ if (!resolved) {+ const known = [...this.providers.keys()];+ throw new Error(+ `Unknown agent account provider "${provider}". ` ++ `Registered providers: ${known.length > 0 ? known.join(', ') : '(none β no identity provider is configured for this deployment)'}`,+ );+ }++ return resolved;+ }++ /** Every registered provider, in registration order. */+ list(): AgentAccountProvider[] {+ return [...this.providers.values()];+ }++ /** Providers that issue a given account kind. */+ listByKind(kind: AgentAccountKind): AgentAccountProvider[] {+ return this.list().filter((provider) => provider.kind === kind);+ }++ /**+ * The capability declaration of a provider. This is what a caller persists+ * onto the account row, so an account never claims capabilities that its+ * provider did not state.+ */+ capabilities(provider: string): AgentAccountCapabilities {+ return this.get(provider).capabilities;+ }+}diff --git a/apps/server/src/services/redis/README.md b/apps/server/src/services/redis/README.mdindex cf37973ba23..ac2e51dc5fa 100644--- a/apps/server/src/services/redis/README.md+++ b/apps/server/src/services/redis/README.md@@ -18,6 +18,9 @@ callers do not choose a provider, prefix, key, SET options or claim lifetime.distinct topics one nightly review may cover. Its keys live in the `agent-signal` namespacenext to the Agent Signal runtime stores. Each count returns `undefined` without Redis; theAgent Signal caller decides whether that fails open or closed.+- `agentIdentity`: replay claims on agent-account provider webhooks, one per provider event+ id, in the `agent-identity` namespace. `releaseWebhookEvent` gives a claim back when the+ delivery failed after it was claimed. Without Redis the claim falls back to a process-local one.`client.ts` is the connection seam. `getRedisServiceClient(scope)` takes the `RedisKeys` scope adomain reads its keys from; `RedisKeyScopeNamespace` maps every scope to the namespace that becomesdiff --git a/apps/server/src/services/redis/agentIdentity.ts b/apps/server/src/services/redis/agentIdentity.tsnew file mode 100644index 00000000000..c53afa5f617--- /dev/null+++ b/apps/server/src/services/redis/agentIdentity.ts@@ -0,0 +1,28 @@+import { RedisKeys } from '@/server/modules/Redis';++import { claimRedisOnce, releaseRedisClaim } from './cache';+import { getRedisServiceClient } from './client';++const getClient = () => getRedisServiceClient('agentIdentity');++// Webhook replay claims must hold across instances: a provider retry, or a captured+// delivery played back, can land on any worker, and a per-process store would accept it+// once per worker. Without Redis the claim degrades to a process-local one.+export const agentIdentity = {+ /** Claims one webhook delivery; `false` means another delivery already accepted it. */+ async claimWebhookEvent(scope: { eventId: string; provider: string }, ttlSeconds: number) {+ return claimRedisOnce(+ await getClient(),+ RedisKeys.agentIdentity.webhookEvent(scope.provider, scope.eventId),+ ttlSeconds * 1000,+ );+ },++ /** Gives a claim back after its processing failed, so the provider's retry is not dropped. */+ async releaseWebhookEvent(scope: { eventId: string; provider: string }) {+ return releaseRedisClaim(+ await getClient(),+ RedisKeys.agentIdentity.webhookEvent(scope.provider, scope.eventId),+ );+ },+};diff --git a/apps/server/src/services/redis/cache.test.ts b/apps/server/src/services/redis/cache.test.tsindex 956ee0bdb5f..bc81e370581 100644--- a/apps/server/src/services/redis/cache.test.ts+++ b/apps/server/src/services/redis/cache.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from 'vitest';import type { BaseRedisProvider } from '@/server/modules/Redis/types';-import { claimRedisOnce, readThroughRedis } from './cache';+import { claimRedisOnce, readThroughRedis, releaseRedisClaim } from './cache';const fakeRedis = (overrides: Partial<BaseRedisProvider> = {}) =>({@@ -102,3 +102,15 @@ describe('claimRedisOnce', () => {await expect(claimRedisOnce(redis, 'claim-fallback', 45_000)).resolves.toBe(false);});});++describe('releaseRedisClaim', () => {+ it('lets the next caller win a released claim, in Redis and in the local fallback', async () => {+ const redis = fakeRedis({ del: vi.fn().mockResolvedValue(1) });+ await releaseRedisClaim(redis, 'claim-release');+ expect(redis.del).toHaveBeenCalledWith('claim-release');++ await expect(claimRedisOnce(null, 'claim-release-local', 45_000)).resolves.toBe(true);+ await releaseRedisClaim(null, 'claim-release-local');+ await expect(claimRedisOnce(null, 'claim-release-local', 45_000)).resolves.toBe(true);+ });+});diff --git a/apps/server/src/services/redis/cache.ts b/apps/server/src/services/redis/cache.tsindex d4a51405bf5..a50abe5c0c0 100644--- a/apps/server/src/services/redis/cache.ts+++ b/apps/server/src/services/redis/cache.ts@@ -97,3 +97,19 @@ export const claimRedisOnce = async (return claimLocally(key, ttl);}};++/**+ * Give a {@link claimRedisOnce} claim back before it expires, so the next+ * caller wins it. For claims that guard work which can fail after the claim β+ * a dropped claim must not turn a retry into a skipped duplicate. Clears the+ * process-local claim too, since the claim may have fallen back to it.+ */+export const releaseRedisClaim = async (+ redis: BaseRedisProvider | null,+ key: RedisKey,+): Promise<void> => {+ localClaims.delete(normalizeRedisKey(key));+ if (!redis) return;++ await redis.del(key).catch(() => undefined);+};diff --git a/apps/server/src/services/redis/index.test.ts b/apps/server/src/services/redis/index.test.tsindex 6aea2019404..02277b7dc1a 100644--- a/apps/server/src/services/redis/index.test.ts+++ b/apps/server/src/services/redis/index.test.ts@@ -2,8 +2,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { redisService } from './index';-const { get, set } = vi.hoisted(() => ({ get: vi.fn(), set: vi.fn() }));-vi.mock('./client', () => ({ getRedisServiceClient: async () => ({ get, set }) }));+const { del, get, set } = vi.hoisted(() => ({ del: vi.fn(), get: vi.fn(), set: vi.fn() }));+vi.mock('./client', () => ({ getRedisServiceClient: async () => ({ del, get, set }) }));describe('Redis domain service', () => {beforeEach(() => {@@ -68,4 +68,20 @@ describe('Redis domain service', () => {px: 45_000,});});++ it('claims one webhook delivery per provider event id across instances, and releases it', async () => {+ set.mockResolvedValueOnce('OK').mockResolvedValueOnce(null);+ const scope = { eventId: 'evt_1', provider: 'agent-mail' };++ await expect(redisService.agentIdentity.claimWebhookEvent(scope, 86_400)).resolves.toBe(true);+ await expect(redisService.agentIdentity.claimWebhookEvent(scope, 86_400)).resolves.toBe(false);+ expect(set).toHaveBeenCalledWith('webhook_event:v1:agent-mail:evt_1', '1', {+ nx: true,+ px: 86_400_000,+ });++ del.mockResolvedValue(1);+ await redisService.agentIdentity.releaseWebhookEvent(scope);+ expect(del).toHaveBeenCalledWith('webhook_event:v1:agent-mail:evt_1');+ });});diff --git a/apps/server/src/services/redis/index.ts b/apps/server/src/services/redis/index.tsindex 7f68cc29544..2641b49d314 100644--- a/apps/server/src/services/redis/index.ts+++ b/apps/server/src/services/redis/index.ts@@ -1,3 +1,4 @@+import { agentIdentity } from './agentIdentity';import { agentSignal } from './agentSignal';import { botWake } from './botWake';import { deviceSystemInfo } from './deviceSystemInfo';@@ -10,6 +11,7 @@ import { workspaceRescan } from './workspaceRescan';/** Business Redis API. Providers, keys and expiry policy stay inside each domain. */export const redisService = {+ agentIdentity,agentSignal,botWake,deviceSystemInfo,diff --git a/package.json b/package.jsonindex a3989b23972..8746458b868 100644--- a/package.json+++ b/package.json@@ -229,6 +229,7 @@"@larksuiteoapi/node-sdk": "^1.73.0","@lexical/utils": "^0.42.0","@lobechat/agent-address-linq": "workspace:*",+ "@lobechat/agent-address-mail": "workspace:*","@lobechat/agent-gateway-client": "workspace:*","@lobechat/agent-mock": "workspace:*","@lobechat/agent-runtime": "workspace:*",diff --git a/packages/agent-address-linq/src/webhook.ts b/packages/agent-address-linq/src/webhook.tsindex e5e5bbc5a83..510409692a9 100644--- a/packages/agent-address-linq/src/webhook.ts+++ b/packages/agent-address-linq/src/webhook.ts@@ -132,6 +132,12 @@ export const verifyLinqWebhookSignature = (*/export interface LinqWebhookDedupeStore {claim: (id: string, ttlSeconds: number) => Promise<boolean>;+ /**+ * Give a claim back so the provider's retry is processed instead of being+ * acknowledged as a duplicate. Used when a claimed delivery failed after the+ * claim (a transient fetch error), so the event is not dropped for good.+ */+ release?: (id: string) => Promise<void>;}export interface InMemoryLinqWebhookDedupeStoreOptions {@@ -175,6 +181,9 @@ export const createInMemoryLinqWebhookDedupeStore = (claims.set(id, current + ttlSeconds * 1000);return true;},+ async release(id: string): Promise<void> {+ claims.delete(id);+ },};};diff --git a/packages/agent-address-mail/src/api.ts b/packages/agent-address-mail/src/api.tsindex ff676a994b8..b56f2c816a7 100644--- a/packages/agent-address-mail/src/api.ts+++ b/packages/agent-address-mail/src/api.ts@@ -92,6 +92,17 @@ const stripTrailingSlashes = (url: string) => {* throws on a non-2xx response with the service's `{ error: { code, message } }`* envelope flattened into the message.*/+/** A non-2xx answer from the Agent Mail REST API, with its HTTP status kept. */+export class LobeMailApiError extends Error {+ readonly status: number;++ constructor(status: number, message: string) {+ super(message);+ this.name = 'LobeMailApiError';+ this.status = status;+ }+}+export class LobeMailApiClient {readonly apiKey: string;readonly baseUrl: string;@@ -123,7 +134,8 @@ export class LobeMailApiClient {} catch {// keep the raw body}- throw new Error(+ throw new LobeMailApiError(+ response.status,`Agent Mail ${init.method ?? 'GET'} ${path} failed: ${response.status}${detail ? ` β ${detail}` : ''}`,diff --git a/packages/agent-address-mail/src/index.ts b/packages/agent-address-mail/src/index.tsindex 653cb3ca2c8..3c040a6c201 100644--- a/packages/agent-address-mail/src/index.ts+++ b/packages/agent-address-mail/src/index.ts@@ -14,6 +14,7 @@ export {DEFAULT_API_BASE_URL,DEFAULT_SIGNATURE_TOLERANCE_SECONDS,LobeMailApiClient,+ LobeMailApiError,parseAgentMailSignature,verifyAgentMailSignature,} from './api';diff --git a/packages/database/src/models/__tests__/agentAccount.test.ts b/packages/database/src/models/__tests__/agentAccount.test.tsindex 73fb6d52c38..0c6173e3600 100644--- a/packages/database/src/models/__tests__/agentAccount.test.ts+++ b/packages/database/src/models/__tests__/agentAccount.test.ts@@ -263,6 +263,48 @@ describe('AgentAccountModel scope and writes', () => {expect(withoutGatekeeper).toBeUndefined();});+ it('stops routing inbound once an account is released', async () => {+ const model = new AgentAccountModel(serverDB, userId, mockGateKeeper);+ const created = await model.create({+ ...mailAccount('[email protected]'),+ credential: { webhookSecret: 'whsec_released' },+ });++ // Live: the webhook resolves the account and can decrypt its credential.+ await expect(+ AgentAccountModel.findForInboundVerification(+ serverDB,+ 'agent-mail',+ '[email protected]',+ mockGateKeeper,+ ),+ ).resolves.toMatchObject({ credential: { webhookSecret: 'whsec_released' } });++ await model.revoke(created.id);++ // Released: a delivery addressed to the same handle must no longer resolve.+ // Revocation that stops sending but keeps receiving is not a release.+ await expect(+ AgentAccountModel.findForInboundVerification(+ serverDB,+ 'agent-mail',+ '[email protected]',+ mockGateKeeper,+ ),+ ).resolves.toBeUndefined();+ });++ it('stops routing inbound while an account is suspended', async () => {+ const model = new AgentAccountModel(serverDB, userId);+ const created = await model.create(mailAccount('[email protected]'));++ await model.update(created.id, { status: 'suspended' });++ await expect(+ AgentAccountModel.findForInboundVerification(serverDB, 'agent-mail', '[email protected]'),+ ).resolves.toBeUndefined();+ });+it('keeps one account per (agent, kind, provider, identifier)', async () => {const model = new AgentAccountModel(serverDB, userId);await model.create(mailAccount('[email protected]'));diff --git a/packages/database/src/models/agentAccount.ts b/packages/database/src/models/agentAccount.tsindex 1e5ea729206..df42a7c9b7d 100644--- a/packages/database/src/models/agentAccount.ts+++ b/packages/database/src/models/agentAccount.ts@@ -2,15 +2,22 @@ import type {AgentAccountCapabilities,AgentAccountCredentialHint,AgentAccountKind,+ AgentAccountStatus,} from '@lobechat/types';-import { and, desc, eq, ne, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, ne, sql } from 'drizzle-orm';import type { AgentAccountItem, NewAgentAccount } from '../schemas';import { agentAccounts } from '../schemas';import type { LobeChatDatabase } from '../type';import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';-interface GateKeeper {+/**+ * The encryption contract the account model needs.+ *+ * Structural on purpose: `KeyVaultsGateKeeper` satisfies it, and tests pass a+ * plain stub without depending on the class's private key material.+ */+export interface AgentAccountGateKeeper {decrypt: (ciphertext: string) => Promise<{ plaintext: string }>;encrypt: (plaintext: string) => Promise<string>;}@@ -26,12 +33,19 @@ export type AgentAccountView = Omit<AgentAccountItem, 'credentials'> & {hasCredential: boolean;};-/** The non-secret fields a caller may patch in place. */+/**+ * The non-secret fields a caller may patch in place.+ *+ * `status` is deliberately absent. Lifecycle moves through+ * {@link AgentAccountModel.revoke}, which releases the provider resource,+ * purges the credential and stamps `revokedAt`; a generic patch that could+ * write `status` would free the routing handle while skipping all of that, and+ * could equally revive a row that had already been released.+ */export interface AgentAccountPatch {capabilities?: AgentAccountCapabilities;displayName?: string | null;metadata?: Record<string, unknown>;- status?: AgentAccountItem['status'];}/** Strip the ciphertext from a freshly written row. */@@ -67,6 +81,31 @@ const viewColumns = {workspaceId: agentAccounts.workspaceId,};+/**+ * Statuses an inbound delivery may still reach.+ *+ * `provisioning` counts as live: both providers open an account synchronously,+ * so the handle is usable the moment the row exists. `revoked` and `suspended`+ * do not β releasing an identity has to stop its inbound, not merely its+ * outbound.+ */+const INBOUND_ROUTABLE_STATUSES: AgentAccountStatus[] = ['active', 'provisioning'];++/**+ * Statuses that actually hold the routing key.+ *+ * Mirrors the partial unique index on `(provider, identifier)`: a revoked row+ * keeps its audit trail but no longer holds the handle, so the same key can+ * carry both it and the account that replaced it. Anything reconciling a write+ * *by* routing key must read only these β reading the replaced row would act on+ * an account that is no longer there.+ */+export const ROUTING_KEY_HELD_STATUSES: AgentAccountStatus[] = [+ 'provisioning',+ 'active',+ 'suspended',+];+/*** Agent accounts (mail / phone / wallet / service) and their credentials.*@@ -76,11 +115,16 @@ const viewColumns = {*/export class AgentAccountModel {private db: LobeChatDatabase;- private gateKeeper?: GateKeeper;+ private gateKeeper?: AgentAccountGateKeeper;private userId: string;private workspaceId?: string;- constructor(db: LobeChatDatabase, userId: string, gateKeeper?: GateKeeper, workspaceId?: string) {+ constructor(+ db: LobeChatDatabase,+ userId: string,+ gateKeeper?: AgentAccountGateKeeper,+ workspaceId?: string,+ ) {this.db = db;this.userId = userId;this.workspaceId = workspaceId;@@ -255,39 +299,81 @@ export class AgentAccountModel {* the key may then carry both the revoked row and its live replacement; this* filter mirrors that index so inbound traffic (and the credential used to* verify it) always resolves to the live account.+ *+ * `statuses` narrows the lookup further when the caller has a liveness rule to+ * apply; inbound routing passes {@link INBOUND_ROUTABLE_STATUSES}.*/static findByRoutingKey = async (db: LobeChatDatabase,provider: string,identifier: string,+ statuses?: AgentAccountStatus[],): Promise<AgentAccountView | undefined> => {+ const conditions = [+ eq(agentAccounts.provider, provider),+ eq(agentAccounts.identifier, identifier),+ ne(agentAccounts.status, 'revoked'),+ ];+ if (statuses) conditions.push(inArray(agentAccounts.status, statuses));+const [row] = await db.select(viewColumns).from(agentAccounts)+ .where(and(...conditions))+ .limit(1);++ return row;+ };++ /**+ * Whether any non-revoked account already routes on this handle. Mirrors the+ * partial unique index on `(provider, identifier)`: a revoked row keeps its+ * audit trail but no longer holds the handle, so it can be bound again.+ */+ static isRoutingKeyHeld = async (+ db: LobeChatDatabase,+ provider: string,+ identifier: string,+ ): Promise<boolean> => {+ const [row] = await db+ .select({ id: agentAccounts.id })+ .from(agentAccounts).where(and(eq(agentAccounts.provider, provider),eq(agentAccounts.identifier, identifier),- ne(agentAccounts.status, 'revoked'),+ inArray(agentAccounts.status, ROUTING_KEY_HELD_STATUSES),),).limit(1);- return row;+ return !!row;};/*** Decrypt an account's credential while resolving an inbound webhook, so the* signature can be verified *before* the request is trusted. The trust model* is the same as the bot path: nothing else may call this.+ *+ * Only a live account is routable. A revoked number that keeps receiving is+ * the worst kind of release: the row says the identity is gone while the+ * carrier still delivers to it β and for Linq it is not even caught by the+ * credential check, because the signing secret comes from deployment config+ * rather than the account. Suspended accounts are excluded for the same+ * reason.*/static findForInboundVerification = async (db: LobeChatDatabase,provider: string,identifier: string,- gateKeeper?: GateKeeper,+ gateKeeper?: AgentAccountGateKeeper,): Promise<{ credential: Record<string, string> | null; view: AgentAccountView } | undefined> => {- const view = await AgentAccountModel.findByRoutingKey(db, provider, identifier);+ const view = await AgentAccountModel.findByRoutingKey(+ db,+ provider,+ identifier,+ INBOUND_ROUTABLE_STATUSES,+ );if (!view) return undefined;const [row] = await dbdiff --git a/packages/env/src/__tests__/agentIdentity.test.ts b/packages/env/src/__tests__/agentIdentity.test.tsnew file mode 100644index 00000000000..46c38c1e22d--- /dev/null+++ b/packages/env/src/__tests__/agentIdentity.test.ts@@ -0,0 +1,43 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { getAgentIdentityConfig } from '../agentIdentity';++describe('getAgentIdentityConfig', () => {+ afterEach(() => {+ vi.unstubAllEnvs();+ });++ it('reports each provider as its own capability', () => {+ vi.stubEnv('AGENT_MAIL_API_KEY', '');+ vi.stubEnv('LINQ_API_KEY', '');++ expect(getAgentIdentityConfig()).toMatchObject({+ ENABLED_AGENT_IDENTITY: false,+ ENABLED_AGENT_MAIL: false,+ ENABLED_LINQ: false,+ });++ vi.stubEnv('AGENT_MAIL_API_KEY', 'am_test');+ expect(getAgentIdentityConfig()).toMatchObject({+ ENABLED_AGENT_IDENTITY: true,+ ENABLED_AGENT_MAIL: true,+ ENABLED_LINQ: false,+ });++ vi.stubEnv('LINQ_API_KEY', 'linq_test');+ const both = getAgentIdentityConfig();+ expect(both).toMatchObject({ ENABLED_AGENT_MAIL: true, ENABLED_LINQ: true });+ expect(both.AGENT_MAIL_API_KEY).toBe('am_test');+ });++ it('carries the optional configuration through', () => {+ vi.stubEnv('AGENT_MAIL_API_KEY', 'am_test');+ vi.stubEnv('AGENT_MAIL_WEBHOOK_URL', 'https://app.lobehub.com/hook');+ vi.stubEnv('LINQ_API_KEY', 'linq_test');+ vi.stubEnv('LINQ_FROM_NUMBER', '+15550002222');++ const env = getAgentIdentityConfig();+ expect(env.AGENT_MAIL_WEBHOOK_URL).toBe('https://app.lobehub.com/hook');+ expect(env.LINQ_FROM_NUMBER).toBe('+15550002222');+ });+});diff --git a/packages/env/src/agentIdentity.ts b/packages/env/src/agentIdentity.tsnew file mode 100644index 00000000000..a07ec75675c--- /dev/null+++ b/packages/env/src/agentIdentity.ts@@ -0,0 +1,77 @@+import { createEnv } from '@t3-oss/env-core';+import { z } from 'zod';++declare global {+ // eslint-disable-next-line @typescript-eslint/no-namespace+ namespace NodeJS {+ interface ProcessEnv {+ /** Override for the Agent Mail REST base. Defaults to `https://api.lobe.id`. */+ AGENT_MAIL_API_BASE_URL?: string;+ /** Agent Mail (lobe.id) API key (`am_β¦`), the tenant that owns agent inboxes. */+ AGENT_MAIL_API_KEY?: string;+ /** Shared Agent Mail webhook secret, used when an account has no own one. */+ AGENT_MAIL_WEBHOOK_SECRET?: string;+ /**+ * Public HTTPS endpoint Agent Mail signs deliveries against. When set,+ * provisioning registers it and stores the returned per-inbox secret as+ * the account credential.+ */+ AGENT_MAIL_WEBHOOK_URL?: string;+ /** Override for the Linq REST base. Defaults to `https://api.linqapp.com/v3`. */+ LINQ_API_BASE_URL?: string;+ /** Linq partner API key. */+ LINQ_API_KEY?: string;+ /**+ * The operator's Linq number pool in E.164, comma-separated. Linq numbers+ * are carrier inventory, not something an API call mints, so a deployment+ * configures the numbers agent accounts bind to β one live account each.+ */+ LINQ_FROM_NUMBER?: string;+ /** Shared Linq webhook signing secret (`whsec_β¦`). */+ LINQ_WEBHOOK_SECRET?: string;+ }+ }+}++/**+ * Server config for the agent identity providers.+ *+ * Both providers are independent capabilities: a deployment that has wired up+ * Agent Mail but not Linq gets a registry with one provider, and vice versa.+ * `ENABLED_AGENT_IDENTITY` is the union, for callers that only need to know+ * whether *any* provider is usable.+ */+export const getAgentIdentityConfig = () =>+ createEnv({+ runtimeEnv: {+ AGENT_MAIL_API_BASE_URL: process.env.AGENT_MAIL_API_BASE_URL,+ AGENT_MAIL_API_KEY: process.env.AGENT_MAIL_API_KEY,+ AGENT_MAIL_WEBHOOK_SECRET: process.env.AGENT_MAIL_WEBHOOK_SECRET,+ AGENT_MAIL_WEBHOOK_URL: process.env.AGENT_MAIL_WEBHOOK_URL,+ ENABLED_AGENT_IDENTITY: !!process.env.AGENT_MAIL_API_KEY || !!process.env.LINQ_API_KEY,+ ENABLED_AGENT_MAIL: !!process.env.AGENT_MAIL_API_KEY,+ ENABLED_LINQ: !!process.env.LINQ_API_KEY,+ LINQ_API_BASE_URL: process.env.LINQ_API_BASE_URL,+ LINQ_API_KEY: process.env.LINQ_API_KEY,+ LINQ_FROM_NUMBER: process.env.LINQ_FROM_NUMBER,+ LINQ_WEBHOOK_SECRET: process.env.LINQ_WEBHOOK_SECRET,+ },+ server: {+ AGENT_MAIL_API_BASE_URL: z.string().optional(),+ AGENT_MAIL_API_KEY: z.string().optional(),+ AGENT_MAIL_WEBHOOK_SECRET: z.string().optional(),+ AGENT_MAIL_WEBHOOK_URL: z.string().optional(),+ /** True when at least one identity provider is configured. */+ ENABLED_AGENT_IDENTITY: z.boolean(),+ /** True when the Agent Mail (`am_β¦`) key is present. */+ ENABLED_AGENT_MAIL: z.boolean(),+ /** True when the Linq key is present. */+ ENABLED_LINQ: z.boolean(),+ LINQ_API_BASE_URL: z.string().optional(),+ LINQ_API_KEY: z.string().optional(),+ LINQ_FROM_NUMBER: z.string().optional(),+ LINQ_WEBHOOK_SECRET: z.string().optional(),+ },+ });++export const agentIdentityEnv = getAgentIdentityConfig();diff --git a/packages/types/src/agentAccount.ts b/packages/types/src/agentAccount.tsindex cefe5ead6b7..1c24925db99 100644--- a/packages/types/src/agentAccount.ts+++ b/packages/types/src/agentAccount.ts@@ -1,3 +1,5 @@+import type { AgentMailAddress, AgentMailAttachment } from './agentMail';+/*** Agent accounts β the identity assets an agent owns.*@@ -70,6 +72,12 @@ export interface AgentAccountInboundMessage {attachments?: AgentAccountAttachment[];/** Address the message came from. */from: string;+ /**+ * Mail-only detail a mail provider supplies on top of the transport-neutral+ * fields, so the full message (addressing, RFC threading headers, attachment+ * descriptors) can be recorded as an `agent_mails` row.+ */+ mail?: AgentAccountInboundMailDetail;/** Provider-side message id, used for dedupe and idempotent replies. */providerMessageId: string;receivedAt: Date;@@ -84,12 +92,166 @@ export interface AgentAccountInboundMessage {to: string;}+/** What a mail provider knows about an inbound mail beyond the neutral message. */+export interface AgentAccountInboundMailDetail {+ /** Attachment descriptors; the bytes stay with the provider. */+ attachments: AgentMailAttachment[];+ cc: AgentMailAddress[];+ fromName?: string;+ /** RFC 5322 `In-Reply-To`. */+ inReplyTo?: string;+ /** RFC 5322 `Message-ID`. */+ messageId?: string;+ /** RFC 5322 `References`, oldest first. */+ references: string[];+ replyTo: AgentMailAddress[];+ to: AgentMailAddress[];+}+/** A message the agent sends from one of its accounts. */export interface AgentAccountOutboundMessage {attachments?: AgentAccountAttachment[];+ /**+ * Provider-side message id this send answers β the `providerMessageId` of the+ * inbound message being replied to. A transport that threads by id (mail's+ * `replyToMessage`) answers inside that message's thread; one that threads by+ * key ignores it and uses {@link threadKey} instead.+ */+ replyToProviderMessageId?: string;subject?: string;text: string;/** Reply within this thread when the provider supports it. */threadKey?: string;to: string;}++/**+ * A persisted account, as a provider needs to act on it.+ *+ * `credential` is the one field that is not part of a normal read: the service+ * supplies the decrypted secret only on the paths allowed to use it (sending,+ * inbound signature verification) and never on list/detail.+ */+export interface AgentAccountRef {+ /** Decrypted credential, present only on trusted internal paths. */+ credential?: Record<string, string> | null;+ id: string;+ /** The handle that routes to this account: address, number, login. */+ identifier: string;+ kind: AgentAccountKind;+ /** Provider-side non-secret handles (inboxId, chatId, β¦). */+ metadata: Record<string, unknown>;+ provider: string;+}++/** Who the account is being opened for. */+export interface AgentAccountProvisionInput {+ agentId: string;+ /** Human label for the new account, when the provider can set one. */+ displayName?: string;+ /**+ * Whether a live account already routes on `identifier` for this provider.+ * Providers that bind from a finite operator inventory (Linq numbers) use it+ * to pick a free unit instead of colliding on the routing key.+ */+ isIdentifierHeld?: (identifier: string) => Promise<boolean>;+ userId: string;+ workspaceId?: string;+}++/**+ * What provisioning produced.+ *+ * `credential` is returned only when the provider mints a per-account secret+ * (an inbox webhook signing key, for example); the caller encrypts it with the+ * KeyVaults gatekeeper and never hands it back to a read.+ */+export interface AgentAccountProvisionResult {+ credential?: Record<string, string>;+ /** Non-secret display facts for the stored credential. */+ credentialHint?: AgentAccountCredentialHint;+ displayName?: string;+ identifier: string;+ metadata?: Record<string, unknown>;+}++/**+ * A raw inbound delivery, before any trust decision.+ *+ * `body` is the exact bytes the signature covers β parsing it for routing is+ * allowed, trusting it is not.+ */+export interface AgentAccountInboundRequest {+ body: string;+ headers: Record<string, string | undefined>;+}++/** A delivery whose signature has been verified, still in provider shape. */+export interface AgentAccountInboundEvent {+ /**+ * The signature is valid but this delivery id was already accepted β a+ * provider retry or a captured request played back. It is acknowledged+ * without producing a message, so a legitimate retry is not read as forged.+ */+ duplicate?: boolean;+ /** Provider delivery id; the replay-dedupe key. */+ eventId: string;+ /** When the provider says the event happened, when it says so. */+ occurredAt?: Date;+ payload: unknown;+ /** What happened, in the provider's vocabulary (e.g. `message.received`). */+ type?: string;+}++/**+ * The narrow contract a transport implements so an agent can own an address+ * with it.+ *+ * Deliberately small: there is no typing / read-receipt / reaction / capability+ * matrix / bot-credential surface here, because an account is the agent's own+ * identity rather than a bot inside someone else's platform. Anything a+ * provider needs beyond this lives in its own `metadata`.+ */+export interface AgentAccountProvider<K extends AgentAccountKind = AgentAccountKind> {+ /** What the account can do β declared here and persisted onto the account. */+ readonly capabilities: AgentAccountCapabilities;+ /** The account kind this provider issues. */+ readonly kind: K;+ /** Normalize a verified delivery into the transport-neutral message. */+ normalizeInbound: (+ event: AgentAccountInboundEvent,+ ref: AgentAccountRef,+ ) => Promise<AgentAccountInboundMessage | null>;++ /** Stable provider id (`agent-mail`, `linq`, β¦); the account's `provider` value. */+ readonly provider: string;++ /** Idempotent open. Runs before the account row exists. */+ provision: (input: AgentAccountProvisionInput) => Promise<AgentAccountProvisionResult>;++ /** Idempotent release. Called while revoking, before the row is marked revoked. */+ release: (ref: AgentAccountRef) => Promise<void>;++ /**+ * Extract the routing key (the account `identifier`) from an *untrusted*+ * delivery, so the account can be found and its credential used to verify.+ * Returning `undefined` means the delivery cannot be routed at all.+ */+ resolveInboundIdentifier: (request: AgentAccountInboundRequest) => string | undefined;++ send: (+ ref: AgentAccountRef,+ message: AgentAccountOutboundMessage,+ ) => Promise<{ providerMessageId: string }>;++ /**+ * Verify the signature over the raw body and recognise replays. Returns+ * `null` for anything forged, so the caller answers 401 without the provider+ * leaking which check failed; an authentic delivery id seen before comes back+ * flagged `duplicate` and is acknowledged without producing a message.+ */+ verifyInbound: (+ request: AgentAccountInboundRequest,+ ref: AgentAccountRef,+ ) => Promise<AgentAccountInboundEvent | null>;+}